repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
xps2/EDCBDon
https://github.com/xps2/EDCBDon
c14ac17d4decbb0c1a37c6bf8d2d6038a76eef27
c96e21e48ede0b4ecaae8c320aca3e5c1dab9b94
b698609129c89a660d12df458841d4cb021a6b9b
refs/heads/master
2021-09-06T19:19:08.962749
2018-02-10T10:18:07
2018-02-10T10:18:07
109,498,864
0
0
null
2017-11-04T13:54:30
2017-12-20T01:35:10
2017-12-20T01:38:46
null
[ { "alpha_fraction": 0.7947686314582825, "alphanum_fraction": 0.7947686314582825, "avg_line_length": 28.235294342041016, "blob_id": "9a03de125c71c89134a027dfeedb55584c8d67b5", "content_id": "b41fc5990be43714bccc182ebee7ac4d1b938750", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 805, "license_type": "permissive", "max_line_length": 94, "num_lines": 17, "path": "/README.md", "repo_name": "xps2/EDCBDon", "src_encoding": "UTF-8", "text": "# EDCBDon\nEDCBからMastodonでトートする\n\n## 準備\n### トークン\n* token.ini.sampleを、token.iniにリネームする。\n* token.iniを自分が使用しているインスタンスに合わせて変更する。\n* `python edcbdon.py --token`を実行する。\n* edcbdon_clientcred.secret, edcbdon_usercred.secretが作成されていることを確認する。\n* token.iniは不要なので削除する。\n### バッチ\n* edcbdon.ini.sampleをedcbdon.iniにリネームする\n* edcbdon.iniを自分が使用しているインスタンスに変更する。\n* edcbdon_clientcred.secret, edcbdon_usercred.secret, edcbdon.py, edcbdon.iniを任意のディレクトリにコピーする。\n\n## 実行方法\n* PostRecStart.batなどに`python edcbdon.py \"トートしたい内容\"`を記述する。\n" }, { "alpha_fraction": 0.5719112157821655, "alphanum_fraction": 0.5796331763267517, "avg_line_length": 21.56818199157715, "blob_id": "5fa8225703f5e6d43f84e35143171b5223a71f28", "content_id": "d50cf82f258d0194d1265e9f2618c90a4ef031f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2080, "license_type": "permissive", "max_line_length": 84, "num_lines": 88, "path": "/edcbdon.py", "repo_name": "xps2/EDCBDon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\nfrom argparse import ArgumentParser\r\nfrom ConfigParser import ConfigParser\r\nfrom mastodon import Mastodon\r\nimport sys\r\nfrom win32api import GetDiskFreeSpaceEx\r\n\r\nparser = ArgumentParser(\r\n prog=\"EDCBDon\"\r\n)\r\ngroup = parser.add_mutually_exclusive_group()\r\ngroup.add_argument('-t', '--token',\r\n action='store_true',\r\n help='get access token'\r\n)\r\ngroup.add_argument('toot',\r\n action='store',\r\n nargs='?',\r\n help='toot'\r\n)\r\nparser.add_argument('--hdd',\r\n action='store',\r\n)\r\n\r\n\r\ndef get_access_token():\r\n config = ConfigParser()\r\n config.readfp(open('token.ini'))\r\n\r\n section = 'Token'\r\n api_base_url = config.get(section, 'api_base_url')\r\n username = config.get(section, 'username')\r\n password = config.get(section, 'password')\r\n\r\n client_id = 'edcbdon_clientcred.secret'\r\n access_token = 'edcbdon_usercred.secret'\r\n scopes = ['read', 'write']\r\n\r\n Mastodon.create_app(\r\n 'EDCBDon',\r\n scopes=scopes,\r\n api_base_url=api_base_url,\r\n to_file=client_id\r\n )\r\n\r\n mastodon = Mastodon(\r\n client_id=client_id,\r\n api_base_url=api_base_url\r\n )\r\n\r\n mastodon.log_in(\r\n username=username,\r\n password=password,\r\n scopes=scopes,\r\n to_file=access_token\r\n )\r\n\r\n\r\ndef toot(toot_str, hdd_path):\r\n config = ConfigParser()\r\n config.readfp(open('edcbdon.ini'))\r\n section = 'EDCBDon'\r\n\r\n if hdd_path is not None:\r\n print hdd_path\r\n hdd = GetDiskFreeSpaceEx(hdd_path)\r\n toot_str = toot_str + u\" 空き容量: {:.2f}\".format(hdd[0] / (1024.0 ** 3)) + \"GB\"\r\n\r\n mastodon = Mastodon(\r\n client_id='edcbdon_clientcred.secret',\r\n access_token='edcbdon_usercred.secret',\r\n api_base_url=config.get(section, 'api_base_url')\r\n )\r\n\r\n mastodon.toot(toot_str)\r\n\r\ndef main():\r\n args = parser.parse_args(sys.argv[1:])\r\n \r\n if args.token:\r\n get_access_token()\r\n sys.exit(0)\r\n elif args.toot:\r\n toot(unicode(args.toot, 'cp932'), args.hdd)\r\n \r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 18, "blob_id": "e845eb3886861ad23514bce2e96a23dded62c0df", "content_id": "55e3724bc6df1395ba62e5a54bc11379df0528cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 20, "license_type": "permissive", "max_line_length": 18, "num_lines": 1, "path": "/requirements.txt", "repo_name": "xps2/EDCBDon", "src_encoding": "UTF-8", "text": "Mastodon.py>=1.2.1\r\n" } ]
3
xiedaolin2000/RM_BJC
https://github.com/xiedaolin2000/RM_BJC
02dd549d1a1aa49a5018e4c06ae0eeac5e76a8c1
92a6711e26869ac6e36a3a04e0542cee0feab88a
ec80f7e21cc93849d9d5ada7c70476e9a92f30b5
refs/heads/master
2020-03-17T23:57:00.836532
2018-11-19T06:38:01
2018-11-19T06:38:01
134,069,903
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48191171884536743, "alphanum_fraction": 0.5190839767456055, "avg_line_length": 40.27397155761719, "blob_id": "792a1c740c0069728dcba89e22c1f8867e2d4ea2", "content_id": "da115d6b8f00c77fcf57a9d1fcf916dcdfc8d182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3127, "license_type": "no_license", "max_line_length": 456, "num_lines": 73, "path": "/HR/migrations/0002_auto_20180521_2240.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.5 on 2018-05-21 14:40\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('HR', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='person',\n options={'ordering': ['-entryDate']},\n ),\n migrations.AlterField(\n model_name='person',\n name='address',\n field=models.CharField(max_length=200, null=True, verbose_name='住址'),\n ),\n migrations.AlterField(\n model_name='person',\n name='birthDay',\n field=models.DateField(default=datetime.date.today, null=True, verbose_name='出生日期'),\n ),\n migrations.AlterField(\n model_name='person',\n name='cityBirth',\n field=models.CharField(default='南京市', max_length=20, null=True, verbose_name='籍贯市'),\n ),\n migrations.AlterField(\n model_name='person',\n name='depart',\n field=models.CharField(default='0', max_length=10, null=True, verbose_name='部门'),\n ),\n migrations.AlterField(\n model_name='person',\n name='education',\n field=models.CharField(choices=[('0', '小学'), ('1', '初中'), ('2', '高中'), ('3', '大专'), ('4', '本科'), ('5', '研究生')], default='4', max_length=1, null=True, verbose_name='学历'),\n ),\n migrations.AlterField(\n model_name='person',\n name='graduatedDay',\n field=models.DateField(default=datetime.date.today, null=True, verbose_name='毕业日期'),\n ),\n migrations.AlterField(\n model_name='person',\n name='graduatedSchool',\n field=models.CharField(default='大学', max_length=20, null=True, verbose_name='毕业学校'),\n ),\n migrations.AlterField(\n model_name='person',\n name='level',\n field=models.CharField(choices=[('00', '00'), ('1B', '1B'), ('1A', '1A'), ('2B', '2B'), ('2A', '2A'), ('3B', '3B'), ('3A', '3A'), ('4B', '4B'), ('4A', '4A'), ('5B', '5B'), ('5A', '5A'), ('6B', '6B'), ('6A', '6A'), ('7B', '7B'), ('7A', '7A'), ('8B', '8B'), ('8A', '8A'), ('9B', '9B'), ('9A', '9A'), ('10B', '10B'), ('10A', '10A'), ('11B', '11B'), ('11A', '11A'), ('12B', '12B'), ('12A', '12A')], default='00', max_length=4, verbose_name='岗位级别'),\n ),\n migrations.AlterField(\n model_name='person',\n name='productUnit',\n field=models.CharField(default='0', max_length=10, null=True, verbose_name='产品线'),\n ),\n migrations.AlterField(\n model_name='person',\n name='projectName',\n field=models.CharField(default='0', max_length=20, null=True, verbose_name='项目组名'),\n ),\n migrations.AlterField(\n model_name='person',\n name='provinceBirth',\n field=models.CharField(default='江苏省', max_length=20, null=True, verbose_name='籍贯省份'),\n ),\n ]\n" }, { "alpha_fraction": 0.5471943020820618, "alphanum_fraction": 0.5763866305351257, "avg_line_length": 43.0428581237793, "blob_id": "58f17b3e280c8696cbf1331fbdad2140b45b4e46", "content_id": "b1eb97ea74164ca05d1f1d1e69454a8893ca5d87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3221, "license_type": "no_license", "max_line_length": 136, "num_lines": 70, "path": "/HR/migrations/0003_auto_20180606_2330.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.5 on 2018-06-06 15:30\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('HR', '0002_auto_20180521_2240'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Performace',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('dateRange', models.CharField(blank=True, default='2018Q1', max_length=10, null=True, verbose_name='考核周期')),\n ('total', models.IntegerField(blank=True, default=0, null=True, verbose_name='绩效得分')),\n ('result', models.CharField(blank=True, max_length=10, null=True, verbose_name='绩效结果')),\n ('appraisers', models.CharField(blank=True, max_length=10, null=True, verbose_name='考评人')),\n ('notes', models.CharField(blank=True, max_length=200, null=True, verbose_name='备注')),\n ],\n ),\n migrations.CreateModel(\n name='PerformaceDetail',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('dateRange', models.CharField(blank=True, default='2018Q1', max_length=10, null=True, verbose_name='考核周期')),\n ('kpi', models.CharField(default='考核指标项内容', max_length=50, verbose_name='考核项')),\n ('kpiValue', models.DecimalField(decimal_places=2, default=0.0, max_digits=5, verbose_name='考核项得分')),\n ],\n ),\n migrations.AddField(\n model_name='person',\n name='workStatus',\n field=models.CharField(choices=[('00', '在职'), ('11', '请假'), ('99', '离职')], default='00', max_length=5, verbose_name='工作状态'),\n ),\n migrations.AddField(\n model_name='salary',\n name='applyDate',\n field=models.DateField(default=datetime.date.today, verbose_name='生效月份'),\n ),\n migrations.AlterField(\n model_name='person',\n name='mobilePhone',\n field=models.CharField(default='18600000000', max_length=15, verbose_name='手机号码'),\n ),\n migrations.AlterField(\n model_name='person',\n name='userName',\n field=models.CharField(default='张三无名氏', max_length=15, verbose_name='姓名'),\n ),\n migrations.AlterField(\n model_name='person',\n name='workNo',\n field=models.CharField(default='B-12345', max_length=15, verbose_name='公司工号'),\n ),\n migrations.AddField(\n model_name='performacedetail',\n name='person',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='HR.Person', verbose_name='员工'),\n ),\n migrations.AddField(\n model_name='performace',\n name='person',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='HR.Person', verbose_name='员工'),\n ),\n ]\n" }, { "alpha_fraction": 0.5517241358757019, "alphanum_fraction": 0.7241379022598267, "avg_line_length": 18.66666603088379, "blob_id": "35d1962b2c252fc2d9d3d16ead49d41799acb81a", "content_id": "824d96b141a502b04e70942c32af3391f58b4f71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 58, "license_type": "no_license", "max_line_length": 28, "num_lines": 3, "path": "/requirements.txt", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "django==2.1.2\ndjango-debug-toolbar==1.10.1\nopenpyxl==2.5.9" }, { "alpha_fraction": 0.5728563666343689, "alphanum_fraction": 0.6103805303573608, "avg_line_length": 34.64374923706055, "blob_id": "726f24223b678a227a82f7f3e9c415861a8ef432", "content_id": "573fdd4c9657e1e050abb0c90dc3a033a8d4994a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7039, "license_type": "no_license", "max_line_length": 115, "num_lines": 160, "path": "/HR/models.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom datetime import date\n\n\n# Create your models here.\n\nclass Person(models.Model):\n \"\"\"\n 人员的基本信息,包含基本信息属性\n \"\"\"\n # verbose_name = \"员工详细信息\"\n #第一个参数表示字段的自述名称,或者使用verbose_name=\"XXXX\",但是OneToOneField第一个参数被占用了\n # staff = models.OneToOneField(auth.user, primary_key=True, verbose_name=\"员工姓名\")\n #staff = models.OneToOneField(User, primary_key=True, verbose_name=\"员工姓名\")\n #员工姓名\n userName = models.CharField(\"姓名\", max_length=15, default=\"张三无名氏\")\n #公司工号\n workNo = models.CharField(\"公司工号\", max_length=15,default=\"B-12345\")\n #华为工号\n workNoExt = models.CharField(\"华为工号\", max_length=15, null=True)\n #手机号码\n mobilePhone = models.CharField(\"手机号码\", max_length=15, default=\"18600000000\")\n #身份证号码\n IDNo = models.CharField(\"身份证\", max_length=18)\n #电子邮箱\n email = models.EmailField(\"电子邮箱\", max_length=50, null=True)\n #华为电子邮箱\n emailExt = models.EmailField(\"华为邮箱\", max_length=50, null=True)\n\n #性别字段只能是0或1的值,元组第一位表示保存的值,第二位表示显示的值\n sex = models.CharField(\"性别\", max_length=1, choices=((\"0\", \"女\"), (\"1\", \"男\")), default=\"1\")\n # 岗位级别\n levelList = (\n (\"00\", \"00\"),\n (\"1B\", \"1B\"), (\"1A\", \"1A\"), (\"2B\", \"2B\"), (\"2A\", \"2A\"),\n (\"3B\", \"3B\"), (\"3A\", \"3A\"), (\"4B\", \"4B\"), (\"4A\", \"4A\"),\n (\"5B\", \"5B\"), (\"5A\", \"5A\"), (\"6B\", \"6B\"), (\"6A\", \"6A\"),\n (\"7B\", \"7B\"), (\"7A\", \"7A\"), (\"8B\", \"8B\"), (\"8A\", \"8A\"),\n (\"9B\", \"9B\"), (\"9A\", \"9A\"), (\"10B\", \"10B\"), (\"10A\", \"10A\"),\n (\"11B\", \"11B\"), (\"11A\", \"11A\"), (\"12B\", \"12B\"), (\"12A\", \"12A\")\n )\n level = models.CharField(\"岗位级别\", max_length=4, choices=levelList, default=\"00\")\n # 到岗日期/入职日期\n entryDate = models.DateField(\"入职日期\", default=date.today)\n # 部门\n depart = models.CharField(\"部门\", max_length=10, default=\"0\", null=True)\n # 业务线\n productUnit = models.CharField(\"产品线\", max_length=10, default=\"0\",null=True)\n # 项目组\n projectName = models.CharField(\"项目组名\", max_length=20, default=\"0\",null=True)\n # 籍贯省\n provinceBirth = models.CharField(\"籍贯省份\", max_length=20,null=True, default=\"江苏省\")\n # 籍贯市\n cityBirth = models.CharField(\"籍贯市\", max_length=20,null=True, default=\"南京市\")\n # 出生日期\n birthDay = models.DateField(\"出生日期\", null=True,default=date.today)\n # 婚姻状况\n maritalStatus = models.CharField(\"婚姻状况\", max_length=1, \n choices=(('0','未婚'), ('1','已婚'), ('2','离异')), default=\"0\")\n \n #员工住址 ,第一个参数表示字段的自述名称,或者使用verbose_name=\"XXXX\"\n address = models.CharField(\"住址\", max_length=200, null=True)\n # 毕业院校\n graduatedSchool = models.CharField(\"毕业学校\", max_length=20, null=True,default=\"大学\")\n # 学历\n education = models.CharField(\"学历\", max_length=1,\n choices=(('0', '小学'), ('1', '初中'), ('2', '高中'), ('3', '大专'), ('4', '本科'), ('5', '研究生')),null=True, default=\"4\")\n # 大学专业名称\n profession = models.CharField(\"专业\", max_length=20, null=True, default=\"\")\n \n\t# 毕业时间\n graduatedDay = models.DateField(\"毕业日期\", null=True,default=date.today)\n \n #人员在职状态 用两位数字字符表现 XY: \n\t#(X=0 Y=0-9 归类为正常,基本计算正常成本,00 在职,01 出差,02 外出公干,03 调休;)\n\t#(X=1 Y=0-9 归类为福利请假:01 婚假,02 陪产假,03 病假,04 丧假,05 产假,06产检假,07 哺乳假)\n\t#(X=9 Y=0-9 归类为不在职:90 离职,91 辞退)\n workStatus = models.CharField(verbose_name = \"工作状态\", max_length=5, \n choices=(('00','在职'), ('11','请假'), ('99','离职')), default=\"00\", blank=False, null=False)\n\n \n def get_absolute_url(self):\n from django.urls import reverse\n # return reverse('PersonListView', kwargs={'pk': self.pk})\n return reverse('PersonListView')\n\n class Meta:\n ordering = [\"-entryDate\"]\n def __str__(self):\n return self.userName\n\n#从公司的花名册表单中读取员工数据,更新到数据库中\ndef import_data_excel(fileName):\n pass\n#薪资调整记录\nclass Salary(models.Model):\n \"\"\"\n 员工薪资调整的详细数据\n \"\"\"\n #员工\n person = models.ForeignKey(Person,on_delete=models.CASCADE , verbose_name=\"员工\")\n #调薪生效日期,也就是说薪资是在几月份进行生效的\n applyDate = models.DateField(\"生效月份\", default=date.today)\n #调薪幅度\n adjustRange = models.IntegerField(\"调薪幅度\", default=0)\n #调整后薪资\n salaryFinal = models.IntegerField(\"调整后薪资\", default=0)\n #调薪日期\n adjustDate = models.DateField(\"调薪日期\", default=date.today)\n #备注\n notes = models.CharField(\"备注\", max_length=200, blank=True, null=True)\n #此处表示表名字\n verbose_name = \"薪资调整数据\"\n def __str__(self):\n return self.person\n\n#员工绩效考评记录\nclass Performace(models.Model):\n \"\"\"\n 员工绩效考核表\n Employee performance evaluation review\n \"\"\"\n #关联员工表数据,多对一 ;外键要定义在‘多’的一方\n person = models.ForeignKey(Person,on_delete=models.CASCADE, verbose_name=\"员工\")\n\n #绩效考察周期\n dateRange = models.CharField(verbose_name =\"考核周期\", max_length=10, default=\"2018Q1\", blank=True, null=True) \n\n #绩效得分 \n total = models.IntegerField(verbose_name =\"绩效得分\",default=0,blank=True, null=True)\n\n #绩效结果\n result = models.CharField(verbose_name =\"绩效结果\", max_length=10, blank=True, null=True)\n\n #绩效考评人\n appraisers = models.CharField(verbose_name =\"考评人\", max_length=10, blank=True, null=True)\n\n #备注\n notes = models.CharField(verbose_name = \"备注\", max_length=200, blank=True, null=True)\n\n def __str__(self):\n return \"\"\n\nclass PerformaceDetail(models.Model):\n \"\"\"\n 员工绩效考评明细项记录表\n \"\"\"\n\n #关联员工表数据,多对一 ;外键要定义在‘多’的一方\n person = models.ForeignKey(Person,on_delete=models.CASCADE, verbose_name=\"员工\")\n #绩效考察周期\n dateRange = models.CharField(verbose_name =\"考核周期\", max_length=10, default=\"2018Q1\", blank=True, null=True)\n \n #KPI的指标项\n kpi = models.CharField(verbose_name =\"考核项\", max_length=50, default=\"考核指标项内容\")\n kpiValue= models.DecimalField(verbose_name=\"考核项得分\", max_digits=5, decimal_places=2, default=0.00)\n\n\n def __str__(self):\n return \"\"\n" }, { "alpha_fraction": 0.6681715846061707, "alphanum_fraction": 0.6741911172866821, "avg_line_length": 41.870967864990234, "blob_id": "e41f02cc4758a409e78f6d75f656182ff7b6ba5f", "content_id": "76ea13f4b7fc5d9caa4e4312637313a63d72eeba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1329, "license_type": "no_license", "max_line_length": 98, "num_lines": 31, "path": "/HR/urls.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "\"\"\"RMSite URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom django.views.generic import TemplateView\nfrom . import views\nimport debug_toolbar\n\nurlpatterns = [\n # path('', views.HR_Info),\n path('__debug__/', include(debug_toolbar.urls)),\n path('', views.PersonListView.as_view(), name=\"PersonListView\"),\n path('OK', TemplateView.as_view(template_name=\"HR/success.html\") , name=\"success\"),\n path('add/', views.PersonAddView.as_view(), name=\"PersonAddView\"),\n path('<int:pk>/', views.PersonUpdateView.as_view(), name=\"PersonUpdateView\"),\n path('del/<int:pk>', views.PersonDelView.as_view(), name=\"PersonDelView\"),\n \n]\n" }, { "alpha_fraction": 0.552581250667572, "alphanum_fraction": 0.5602294206619263, "avg_line_length": 30.3799991607666, "blob_id": "618b779009c972354b908d32930abab73f254a79", "content_id": "03d99187a193e409ee07ec8e7bbfc42a5d0b604f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1797, "license_type": "no_license", "max_line_length": 115, "num_lines": 50, "path": "/RMSite/viewsTest.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom HR.models import Person\n\ndef testImport(request):\n return HttpResponse(\"该功能关闭\")\n # import_Excel()\n # return HttpResponse(\"import data finlished.\")\n\nfrom openpyxl import load_workbook\ndef import_Excel():\n wb = load_workbook(r\"E:\\OneDrive\\Work\\billjc\\区域研发中心\\人力资源\\在职&离职名单\\南京在职&amp;离职名单--2018.5.11.xlsx\",data_only=True)\n sht = wb[\"DU1-DU5\"]\n # colIDX_SRC=[\"A\",\"B\"]\n # colIDX_DES=[\"A\",\"B\"]\n # 花名册Excel表格中,列名称对应的数据库字段属性,key是列名,value是字段属性\n colIDX_Fields_Mapping = {\n \"B\":\"workNo\",\n \"C\":\"userName\",\n \"E\":\"IDNo\",\n \"F\":\"sex\", #性别字段\n \"G\":\"entryDate\", # 到岗日期/入职日期\n \"M\":\"depart\",\n \"P\":\"productUnit\",\n \"Q\":\"projectName\",\n \"V\":\"mobilePhone\",\n \"X\":\"email\",\n \"Z\":\"workNoExt\",\n \"AA\":\"emailExt\",\n \"AC\":\"provinceBirth\",\n \"AD\":\"cityBirth\",\n \"AG\":\"birthDay\",\n \"AH\":\"maritalStatus\",\n \"AJ\":\"graduatedSchool\", #毕业院校\n \"AM\":\"education\", #学历\n \"AO\":\"profession\", # 大学专业名称\n \"AR\":\"graduatedDay\", # 毕业时间\n \"AW\":\"address\",\n }\n usedRowCount = sht.max_row\n # usedRowCount = 10\n #数据从第二行开始读取,第一行是标题\n for row in range(2,usedRowCount):\n p = Person()\n for colName,fieldName in colIDX_Fields_Mapping.items():\n print(colName,fieldName)\n #动态设置对象的属性值\n p.__setattr__ (fieldName, sht[\"%s%i\" % (colName,row)].value)\n # pars[fieldName]=sht[\"%s%i\" % (colName,row)].value\n p.save()\n" }, { "alpha_fraction": 0.5130876898765564, "alphanum_fraction": 0.5506988763809204, "avg_line_length": 66.8448257446289, "blob_id": "8fe896b8fe6896c1139ead0704d3cd6e2ef5ee24", "content_id": "b408ca27ee6aab9ee4c27e08fe5d139e71a9a4e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4179, "license_type": "no_license", "max_line_length": 464, "num_lines": 58, "path": "/HR/migrations/0001_initial.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.5 on 2018-05-07 15:32\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Person',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('userName', models.CharField(default='无名氏', max_length=15, verbose_name='姓名')),\n ('workNo', models.CharField(max_length=15, verbose_name='公司工号')),\n ('workNoExt', models.CharField(max_length=15, null=True, verbose_name='华为工号')),\n ('mobilePhone', models.CharField(default='00000000000', max_length=15, verbose_name='手机号码')),\n ('IDNo', models.CharField(max_length=18, verbose_name='身份证')),\n ('email', models.EmailField(max_length=50, null=True, verbose_name='电子邮箱')),\n ('emailExt', models.EmailField(max_length=50, null=True, verbose_name='华为邮箱')),\n ('sex', models.CharField(choices=[('0', '女'), ('1', '男')], default='1', max_length=1, verbose_name='性别')),\n ('level', models.CharField(choices=[('00', '00'), ('1B', '1B'), ('1A', '1A'), ('2B', '2B'), ('2A', '2A'), ('3B', '3B'), ('3A', '3A'), ('4B', '4B'), ('4A', '4A'), ('5B', '5B'), ('5A', '5A'), ('6B', '6B'), ('6A', '6A'), ('7B', '7B'), ('7A', '7A'), ('8B', '8B'), ('8A', '8A'), ('9B', '9B'), ('9A', '9A'), ('10B', '10B'), ('10A', '10A'), ('11B', '11B'), ('11A', '11A'), ('12B', '12B'), ('12A', '12A')], default='1', max_length=4, verbose_name='岗位级别')),\n ('entryDate', models.DateField(default=datetime.date.today, verbose_name='入职日期')),\n ('depart', models.CharField(default='0', max_length=10, verbose_name='部门')),\n ('productUnit', models.CharField(default='0', max_length=10, verbose_name='产品线')),\n ('projectName', models.CharField(default='0', max_length=20, verbose_name='项目组名')),\n ('provinceBirth', models.CharField(default='江苏省', max_length=20, verbose_name='籍贯省份')),\n ('cityBirth', models.CharField(default='南京市', max_length=20, verbose_name='籍贯市')),\n ('birthDay', models.DateField(default=datetime.date.today, verbose_name='出生日期')),\n ('maritalStatus', models.CharField(choices=[('0', '未婚'), ('1', '已婚'), ('2', '离异')], default='0', max_length=1, verbose_name='婚姻状况')),\n ('address', models.CharField(max_length=200, verbose_name='住址')),\n ('graduatedSchool', models.CharField(default='大学', max_length=20, verbose_name='毕业学校')),\n ('education', models.CharField(choices=[('0', '小学'), ('1', '初中'), ('2', '高中'), ('3', '大专'), ('4', '本科'), ('5', '研究生')], default='4', max_length=1, verbose_name='学历')),\n ('profession', models.CharField(default='', max_length=20, null=True, verbose_name='专业')),\n ('graduatedDay', models.DateField(default=datetime.date.today, verbose_name='毕业日期')),\n ],\n options={\n 'ordering': ['id'],\n },\n ),\n migrations.CreateModel(\n name='Salary',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('adjustDate', models.DateField(default=datetime.date.today, verbose_name='调薪日期')),\n ('adjustRange', models.IntegerField(default=0, verbose_name='调薪幅度')),\n ('salaryFinal', models.IntegerField(default=0, verbose_name='调整后薪资')),\n ('notes', models.CharField(blank=True, max_length=200, null=True, verbose_name='备注')),\n ('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='HR.Person', verbose_name='员工')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7358490824699402, "alphanum_fraction": 0.7358490824699402, "avg_line_length": 12.25, "blob_id": "32a67dad40a9005b5cd62abe71e9fb08679f99ff", "content_id": "3aef6b437e8e088246729df13c56cc49f6da574c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "no_license", "max_line_length": 22, "num_lines": 4, "path": "/README.md", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "---\n#requirements.txt 文件说明\n---\n说明这个项目所依赖的Python lib库\n" }, { "alpha_fraction": 0.5463917255401611, "alphanum_fraction": 0.5567010045051575, "avg_line_length": 20.66666603088379, "blob_id": "516afc5967b8def932e31d27244c4a746a404d14", "content_id": "a7c085a42b0233bc8d2e7909ba9060c3c7da1ea3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 228, "license_type": "no_license", "max_line_length": 58, "num_lines": 9, "path": "/RMSite/Templates/test.html", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "{% extends \"base_site.html\" %}\n{% block title %}\n 一些小程序测试入口界面\n{% endblock title %}\n{% block body %}\n <ul>\n <li><H1><a href=\"/test/import\">导入人员信息</a> </H1></li>\n </ul>\n{% endblock body %}" }, { "alpha_fraction": 0.638277530670166, "alphanum_fraction": 0.639712929725647, "avg_line_length": 26.81333351135254, "blob_id": "6d532e97151b7e4e525247fbef7ee90cd622f531", "content_id": "d3b21764c4e797ec18a448d8870f0e165f04eac4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2156, "license_type": "no_license", "max_line_length": 72, "num_lines": 75, "path": "/HR/views.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.views import generic\nfrom django.urls import reverse_lazy\n\nfrom .forms import personForm\nfrom .models import Person\n\n\n# Create your views here.\ndef index(request):\n now = datetime.datetime.now()\n html = \"<html><body>HR应用主页<p>现在时间是%s.</body></html>\" % now\n return HttpResponse(html)\n\ndef infoHR(request):\n return render(request,\"HR/HR_list.html\")\n\nclass PersonListView(generic.ListView):\n model = Person\n context_object_name = 'person_list'\n template_name='HR/HR_list.html'\n #设置了分页的记录数就自动开启了分页功能\n paginate_by=10 \n \n #获取查询值\n def get_queryset(self):\n\n try:\n searchctx = self.request.GET[\"userName\"]\n except KeyError:\n searchctx = \"\"\n \n # searchctx1 = self.kwargs[\"userName\"]\n if searchctx == \"\":\n qs = Person.objects.all()\n else:\n qs = Person.objects.filter(userName__contains=searchctx)\n return qs\n\n def get_context_data(self, **kwargs):\n context = super(PersonListView, self).get_context_data(**kwargs)\n context[\"Author\"]=\"xiedaolin.DELEX\"\n return context\n\n\n# class personUpdateView(generic.UpdateView):\n# model = Person\n# # fields = [\"userName\",\"workNo\"]\n# fields = \"__all__\"\n# template_name=\"HR/HR_detail.html\" \n# success_url = 'OK'\n\n# def form_valid(self, form):\n# # This method is called when valid form data has been POSTed.\n# # It should return an HttpResponse.\n# return super().form_valid(form)\n\nclass PersonAddView(generic.edit.CreateView):\n model=Person\n template_name=\"HR/HR_detail.html\" \n fields=\"__all__\"\n success_url = \"OK\"\n # success_url = reverse_lazy('success')\nclass PersonUpdateView(generic.edit.UpdateView):\n model = Person\n template_name=\"HR/HR_detail.html\" \n fields = \"__all__\"\n success_url = \"HR/OK\"\nclass PersonDelView(generic.edit.DeleteView):\n model = Person\n template_name=\"HR/HR_Person_Del.html\"\n success_url = \"/HR/\"\n " }, { "alpha_fraction": 0.439453125, "alphanum_fraction": 0.439453125, "avg_line_length": 18, "blob_id": "a1ac38211daf3221048297cc480ea13085d684f2", "content_id": "0b4654ac489c3a41e0eb78f06c36a3c69c103dfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 572, "license_type": "no_license", "max_line_length": 42, "num_lines": 27, "path": "/HR/Templates/HR/HR_Person_Del.html", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "{% extends \"base_site.html\" %} \n{% block title %} \n人员信息列表 \n{% endblock title %} \n{#父模板中body区块定义覆盖#} \n{% block body %}\n<form method=\"POST\">\n {% csrf_token %} \n <div class=\"form-group\"></div>\n 你是否要删除以下人员\n <br>\n \n <P>\n {{ object.userName }}\n </P>\n <P>\n {{ object.workNo }}\n </P>\n <P>\n {{ object.IDNo }}\n </P>\n <br>\n <input type=\"submit\" value=\"是的\" />\n <button>返回</button>\n </div> \n</form>\n{% endblock body %}" }, { "alpha_fraction": 0.6781609058380127, "alphanum_fraction": 0.6781609058380127, "avg_line_length": 23.285715103149414, "blob_id": "c2b67dbc719a28ec0ed34b23a8dd5d14f3747406", "content_id": "42b9f006bff74c6e39d91ddd8c33f357c953d330", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 36, "num_lines": 7, "path": "/HR/forms.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm\nfrom HR.models import Person\n\nclass personForm(ModelForm):\n class Meta:\n model = Person\n fields=[\"userName\",\"workNo\"]\n " }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 30.375, "blob_id": "58fe55592936a35641df4014b8ab010359488414", "content_id": "7dc9b16b52bd63114110eacbfb56c10b1b15a0d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 61, "num_lines": 8, "path": "/HR/admin.py", "repo_name": "xiedaolin2000/RM_BJC", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Person,Performace,PerformaceDetail,Salary\n\n# Register your models here.\nadmin.site.register(Person)\nadmin.site.register(Performace)\nadmin.site.register(PerformaceDetail)\nadmin.site.register(Salary)\n\n" } ]
13
brennenstenson/misc-
https://github.com/brennenstenson/misc-
0cf850e10d0a01f549ae868f13babfa8c1208add
118602195fc67ec1a65f3e5a44cfe57b2e1f727a
87f71933568a55102cff0a146cc88be19c0035cf
refs/heads/master
2020-03-18T22:12:42.640809
2018-05-29T17:42:18
2018-05-29T17:42:18
135,331,993
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6066339015960693, "alphanum_fraction": 0.6307125091552734, "avg_line_length": 36, "blob_id": "56e699986bbc938018a363be63960f4e7eaffae0", "content_id": "59335d8cbdc4d94f40637bf6b776c2d4c137b348", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4070, "license_type": "no_license", "max_line_length": 158, "num_lines": 110, "path": "/HW03.py", "repo_name": "brennenstenson/misc-", "src_encoding": "UTF-8", "text": "def tax():\n \n socialSecurityTax = 0\n federalIncomeTax = 0\n grossPay = 0\n ## we do not need to declare these variable yet.\n\n \n employeeName = input(\"Give the name of the employee:\")\n hourlyRate = float(input(\"Give the hour rate:\"))\n hoursWorked = float(input(\"Give the number of hours worked:\"))\n\n if hoursWorked > 40:\n hoursWorked = hoursWorked + ((hoursWorked-40) * 1.5)\n\n # we need to make every additional hour after 40 hours be treated as overtime hours, which is equivalent to 1.5 hours.\n # this declaration says we will take the number of hours worked after 40, and multiply them by 1.5\n \n else:\n hoursWorked = hoursWorked\n\t\t##this is redundant. of course i = i. you don't need to state this. \n\n grossPay = int(hoursWorked * hourlyRate)\n \n ##taxTotal = int(socialSecurityTax + federalIncomeTax) \n ##netIncome = int(grossPay - taxTotal)\n ## we need to move this variable down to when we actually calculate socialSecurityTax.\n\n\n if grossPay < 2000:\n socialSecurityTax = grossPay * .062\n else:\n socialSecurityTax = 124\n # here I changed the <= to <. This is because we can simplify our if/else statement to check only if it is less, and if not then set equal to 124.\n\n \n\n\n if grossPay < 500:\n federalIncomeTax = grossPay * .15\n elif grossPay > 1000:\n federalIncomeTax = grossPay * .25 + 175\n else:\n federalIncomeTax = grossPay * .20 + 75\n\n ## there is a logic issue here with the homework parameters itself.\n ##\n ## a discrete logic would be:\n ## if a < 500\n ## elif 500 <= a < 1000\n ## else\n ##\n ## this logic is poorly specified in the assignment.\n ## e.g., what does the table in the assignment say about if we have a gross income of exactly 500?\n ##\n ## the above logic gives a clearer direction and is better defined.\n ## also, rather than going from small to big to medium, lets go from small to medium to big. \n ## this may be more costly at runtime, but we need to write programs so that other people can easily read them, and that starts with clear logic.\n \n \n \n\n ##taxTotal = int(socialSecurityTax + federalIncomeTax) \n ##netIncome = int(grossPay - taxTotal)\n # even better, let us simplify netIncome\n\n netIncome = int(grossPay - (socialSecurityTax + federalIncomeTax))\n\n print(employeeName, \" had a gross pay of $\", grossPay, \".\",sep = \"\")\n print(\"Social Security tax deduction is $\", socialSecurityTax, \".\",sep=\"\")\n print(\"Federal tax deduction is $\", federalIncomeTax, \".\",sep=\"\")\n print(\"Net pay is $\", netIncome, \".\",sep=\"\")\n\n # note for this, we are returning a float for both socialSecurityTax and federalIncomeTax. let's only cast it as an int once. this will be done below.\n\n\n\n \n# lets take all of this and remove the comments now, to give us a clear view of our logic.\n\ndef main():\n employeeName = input(\"Give the name of the employee:\")\n hourlyRate = float(input(\"Give the hour rate:\"))\n hoursWorked = float(input(\"Give the number of hours worked:\"))\n\n if hoursWorked > 40:\n hoursWorked = hoursWorked + ((hoursWorked-40) * 1.5)\n\n grossPay = int(round(hoursWorked * hourlyRate))\n \n if grossPay < 2000:\n socialSecurityTax = grossPay * .062\n else:\n socialSecurityTax = 124\n\n if grossPay < 500:\n federalIncomeTax = grossPay * .15\n elif 500 <= grossPay < 1000:\n federalIncomeTax = grossPay * .20 + 75\n else:\n federalIncomeTax = grossPay * .25 + 175\n\n netIncome = int(round(grossPay - (socialSecurityTax + federalIncomeTax)))\n\n print(employeeName, \" had a gross pay of $\", grossPay, \".\",sep = \"\")\n print(\"Social Security tax deduction is $\", int(round(socialSecurityTax)), \".\",sep=\"\")\n print(\"Federal tax deduction is $\", int(round(federalIncomeTax)), \".\",sep=\"\")\n print(\"Net pay is $\", netIncome, \".\",sep=\"\")\n\nmain()\n" } ]
1
aleperno/tp1tda
https://github.com/aleperno/tp1tda
8e6c0bc35e7225f36dd7d0bf2d33ce23ff5f86b8
e822db34d47369e046a3ccaaf97e0ea1f2a4c71f
a93b7cd9890025baa50535f3d90532ce33e01457
refs/heads/master
2021-01-23T12:32:25.938337
2013-10-16T13:41:17
2013-10-16T13:41:17
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6355748176574707, "alphanum_fraction": 0.6505039930343628, "avg_line_length": 26.498245239257812, "blob_id": "a51b2ffaf08b5b1bde0709a52311940f860a6083", "content_id": "cead5890f56afaa628825de0be8c898fba52cf2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7837, "license_type": "no_license", "max_line_length": 106, "num_lines": 285, "path": "/Graph.py", "repo_name": "aleperno/tp1tda", "src_encoding": "UTF-8", "text": "\"\"\"Graph.py\nDescription: simple & undirected graph implementation for course 75.29 Teoria de\nAlgoritmos @ University of Buenos Aires\n\nAuthors:\nMedrano, Lautaro\nPernin, Alejandro\n\"\"\"\n\n#NotUsed\nclass Edge:\n\n\tdef __init__(self, vertex1, vertex2):\n\t\tself.vertex1 = vertex1\n\t\tself.vertex2 = vertex2\n\t\tself.label = ''\n\t\n\tdef __str__(self):\n\t\ts = \"%s <-> %s \" % (self.vertex1, self.vertex2)\n\t\treturn s\n\nclass Vertex:\n\n\tdef __init__(self, key):\n\t\tself.key = key\n\n\t\t#To be used on DFS\n\t\tself.father = None\n\t\tself.visited = False\n\n\tdef __eq__(self,other):\n\t\treturn self.key == other.key\n\n\tdef __str__(self):\n\t\treturn self.key\n\n\tdef isVisited(self):\n\t\treturn self.visited\n\n\tdef visit(self,father):\n\t\tif not father:\n\t\t\tf=''\n\t\telse:\n\t\t\tf= father.key\n\t\t#print \"Visitando %s desde %s\" % (self.key, f)\n\t\tself.visited=True\n\t\tself.father=father\n\nclass Graph:\n\n\tdef __init__(self):\n\t\t#Standalone initialization\n\t\tself.vertices = {}\n\t\tself.adjacencies = {}\n\n\t\tself.comp = []\n\n\t\tself.res = []\n\n\tdef __str__(self):\n\t\t#Prints graph as 'vertex: [edges]'\n\t\ts = ''\n\t\tfor v in self.vertices.keys():\n\t\t\t#First character on the line is the vertex\n\t\t\ts += \"%s: \" % v\n\t\t\tfor a in self.adjacencies[v]:\n\t\t\t\ts += \"%s,\" % a\n\t\t\ts += \"\\n\"\n\t\treturn s\n\n\tdef printResult(self):\n\t\tcount = 1\n\t\tfor line in self.res:\n\t\t\tprint \"Arista%s: %s\" % (count,line)\n\t\t\tcount += 1\n\t\tif count == 1:\n\t\t\t#There were no results\n\t\t\tprint \"Ya se cumple la robustez requerida\"\n\n\t#O(1)\n\tdef countVertices(self):\n\t\treturn len(self.getAllVertex())\n\n\t#O(1)\n\tdef isVertex(self, vertex):\n\t\treturn self.vertices.has_key(vertex.key)\n\n\t#O(1)\n\tdef addVertex(self, vertex):\n\t\tif not self.isVertex(vertex): #O(1)\n\t\t\tself.vertices[vertex.key] = vertex #O(1)\n\t\t\tself.adjacencies[vertex.key] = {} #O(1)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t#NotUsed\n\tdef delVertex(self, vertex):\n\t\tif self.isVertex(vertex):\n\t\t\tself.vertices.pop(vertex.key)\n\t\t\tself.adjacencies.pop(vertex.key)\n\n\t\t\t#Now I must delete all adjacencies references to the vertex\n\t\t\tfor lin in self.adjacencies.values():\n\t\t\t\ttry:\n\t\t\t\t\tl.remove(vertex)\n\t\t\t\texcept ValueError:\n\t\t\t\t\t#DoNothing\n\t\t\t\t \tcontinue\n\n\t#O(1)\n\tdef getAllVertex(self):\n\t\t#Returns all the vertices\n\t\treturn self.vertices.values()\n\n\t#O(1)\n\tdef getAllNeighbours(self, vertex):\n\t\t#Returns list containing all the neighbours keys of the vertex\n\t\tif self.isVertex(vertex): #O(1)\n\t\t\treturn self.adjacencies[vertex.key].keys() #O(1)\n\t\telse:\n\t\t\tprint \"vertex not in grahp\"\n\t\t\treturn False\n\n\t#O(1)\n\tdef addAdjacency(self, vertex, adj):\n\t\t#Checks if it isnt already a adjacency.\n\t\ta = self.vertices[adj.key] #O(1)\n\t\tif not self.adjacencies[vertex.key].has_key(a.key): #O(1)\n\t\t\tself.adjacencies[vertex.key][a.key]=None #O(1)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t#O(1)\n\tdef isEdge(self,vertex1,vertex2):\n\t\t#print \"Chequeando adyacencia entre %s y %s\" % (vertex1,vertex2)\n\t\tif self.adjacencies[vertex2.key].has_key(vertex1.key): #O(1)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t#O(1)\n\tdef addEdge(self, vertex1, vertex2):\n\t\t#First checks if there is vertex exists\n\t\tif (self.isVertex(vertex1) and self.isVertex(vertex2)): #O(1) \n\t\t\t#As the intended graph is undirected, A>B and B>A should be made.\n\t\t\tself.addAdjacency(vertex1,vertex2) #O(1)\n\t\t\tself.addAdjacency(vertex2,vertex1) #O(1)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t#O(1) NOT USED\n\tdef delEdge(self, vertex1, vertex2):\n\t\t#As it is undirected, both references must be deleted\n\t\ttry:\n\t\t\tself.graph[vertex2.value].pop(vertex1.value) #O(1)\n\t\t\tself.graph[vertex1.value].pop(vertex2.value) #O(1) \n\t\t\treturn True\n\t\texcept KeyError:\n\t\t\t#Either vertex not in graph or no edge\n\t\t\tprint \"Error while deleting edge\"\n\t\t\treturn False\n\n\t\"\"\"\n\tThe common DFS running time is O(V+E) V:Vertices, E:Edges. ('Introduction to Algorithms' Second Edition -\n\tThomas Cormen page 543).\n\tAs I add a cycle over the list 'l', hence I only add a element when a vertex is being visited,\n\tevery call to the cycle will empty the list\tand the operations inside the cycle are O(1) at the\n\twhole DFS this cycle will add O(V).\n\tSumming\n\tO(V+E) + O(V) = O(V+V+E) = O(2V+E) = O(2V) + O(E) = 2O(V) + O(E) = O(V) + O(E) = O(V+E)\n\t[O(kg)=O(g) if k is constant and nonzero]\n\t\"\"\"\n\tdef rdfs(self):\n\t\tl=[]\t\n\t\tfor vert in self.getAllVertex(): #O(V)\n\t\t\tif not vert.isVisited():\n\t\t\t\tself.dfsvisit(None,vert,l)\n\n\tdef dfsvisit(self,father,vert,l):\n\t\tvert.visit(father) #O(1)\n\t\tl.append(vert) #O(1)\n\n\t\t\"\"\"At most I will go through every edge\"\"\"\n\t\tfor key_vecino in self.getAllNeighbours(vert): #O(E)\n\t\t\tvecino = self.vertices[key_vecino]\n\t\t\tif not vecino.isVisited():\n\t\t\t\tself.dfsvisit(vert,vecino,l)\n\t\t\telif (vert.father != None) and (vert.father != vecino): #O(1)\n\t\t\t\t\"\"\"If the vertex's neighbour im trying to visit is already visited\n\t\t\t\tand it is not the vertex's father, It means there I have reached a loop.\n\t\t\t\tSo I proceed to save the loop \n\t\t\t\t\"\"\"\n\t\t\t\taux = []\n\n\t\t\t\t\"\"\"As the only time a element is included in the list is when visited,\n\t\t\t\tat most the list will include all the vertices\"\"\"\n\t\t\t\twhile len(l)>0: #O(V)\n\t\t\t\t\tv = l.pop() #O(1)\n\t\t\t\t\taux.append(v) #O(1)\n\t\t\t\t\tif v.key == vecino.key: #O(1)\n\t\t\t\t\t\tbreak\n\t\t\t\tif aux:\n\t\t\t\t\tself.comp.append(aux) #O(1)\n\t#O(cant)\n\tdef addEdgesSets(self,laux,cant):\n\t\tfor i in range(cant):\n\t\t\ttry:\n\t\t\t\tv1 = laux[i][0]\n\t\t\t\tv2 = laux[i][1]\n\t\t\t\tself.addEdge(v1,v2)\n\t\t\t\ts = \"%s , %s\" % (v1.key , v2.key)\n\t\t\t\tself.res.append(s)\n\t\t\texcept IndexError:\n\t\t\t\t#There are no more available edges to add\n\t\t\t\treturn\n\n\t#O(cant)\n\tdef addEdgesVertex(self,vertex,cant):\n\t\tfor i in self.getAllVertex():\n\t\t\tif not cant:\n\t\t\t\t#No edges to add\n\t\t\t\treturn\n\t\t\tif i == vertex :\n\t\t\t\tcontinue\n\t\t\telif not self.isEdge(vertex,i):\n\t\t\t\tself.addEdge(vertex,i)\n\t\t\t\ts = \"%s , %s\" % (vertex.key , i.key)\n\t\t\t\tself.res.append(s)\n\t\t\t\tcant -= 1\n\n\t#O(|set1|*|set2|)\n\tdef edgesInSets(self,set1,set2,laux):\n\t\tcount=0\n\t\tfor i in set1:\n\t\t\tfor j in set2:\n\t\t\t\tif self.isEdge(i,j):\n\t\t\t\t\tcount +=1\n\t\t\t\telse:\n\t\t\t\t\t#Saves the no-edges to be used if more edges are required\n\t\t\t\t\tlaux.append((i,j)) #O(1)\n\t\treturn count\n\n\t\"\"\"O(V^2)+O(V^2) = O(V^2) \"\"\"\n\tdef setStrenght(self,svalue):\n\t\tcant = len(self.comp)\n\t\tres = 0\n\t\taux = {}\n\t\t#First analyze the strength from the set point of view (see report)\n\t\t\"\"\"\n\t\tThe worst case in terms of sets quantities is the best case in terms of sets size and\n\t\tvice versa. The annlysis of each case resulted that each wors case has a O(V^2) running time.\n\t\tquant * {quant * (size * size) + (size * (V-size))}\n\t\t-Worst case in terms of quant, is when having the most ammount of loops, each loop has a \n\t\tminimum size of 3 vertices so, at most i'll have V/3 loops of size 3.\n\t\tV/3 * {V/3 * (3 * 3) + (3 * V-3)} \n\t\tApplying O() properties, the running time is O(V^2)\n\t\t-Worst case in terms of size, is when having two loops, each with half of the vertices.\n\t\t2 * {2 (V/2 * V/2) + (V/2 * V/2)}\n\t\tApplying O() properties, the running time is O(V^2)\n\t\t\"\"\"\n\t\tfor li in self.comp: #Depends on sets quantity, O(|self.comp|)\n\t\t\tcont = 0\n\t\t\tlaux = []\n\t\t\tfor lj in self.comp: # Depends on sets quantity, O(|self.comp|)\n\t\t\t\t#See how many edges to other sets there are\n\t\t\t\tif li==lj:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tcont += self.edgesInSets(li,lj,laux)#Depends on sets size,O(|li|*|lj|)\n\t\t\tif cont < svalue:\n\t\t\t\t#The set has less edges to other sets than the required strength\n\t\t\t\tcant = svalue - cont #The required ammount of edges to be added to comply the requirements\n\t\t\t\tself.addEdgesSets(laux,cant) #Worst case O(|li|*V-|li|), for each vertex, add edge to all other vertex\n\n\t\t\"\"\"Upper bound O(V^2)\"\"\"\n\t\t#Now analize the strenght from the vertex point of view:\n\t\tfor vertex in self.getAllVertex(): #O(V)\n\t\t\tncount = len(self.getAllNeighbours(vertex)) #O(1)\n\t\t\tif (ncount < svalue):\n\t\t\t\t#The vertex has less neighbours than the required strength\n\t\t\t\tcant = svalue - ncount #Ammount of edges to be added\n\t\t\t\tself.addEdgesVertex(vertex,cant) #Worst case O(V-1) if i have to complete the graph " }, { "alpha_fraction": 0.6295641660690308, "alphanum_fraction": 0.6466431021690369, "avg_line_length": 20.78205108642578, "blob_id": "c63bceb1c6edf2e508137a28c24e85321aa2e10e", "content_id": "44b80321f2794711a7494397066727c908dfc01d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1698, "license_type": "no_license", "max_line_length": 85, "num_lines": 78, "path": "/tdatp1.py", "repo_name": "aleperno/tp1tda", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\"\"\"Prueba cargar un grafo desde un archivo y lo imprime\"\"\"\n\nimport sys\nfrom Graph import *\n\ndef usage():\n\tprint \"Usage: python test.py #strenght <filename>\"\n\tprint \"Usage: ./test.py #strenght <filename>\"\n\ndef checkConditions(graph,strenght):\n\t\"\"\"As the graph should be simple and connected, at the most\n\teach vertex on graph will have V-1 edges (complete graph case)\n\t\"\"\"\n\n\tv=graph.countVertices()\n\tmaximo = (v-1)\n\tif(int(strenght)>maximo):\n\t\tprint \"No es posible la robustez pedida, el maximo es %s, ver condiciones\" % maximo\n\t\treturn False\n\treturn True\n\ndef loadGraph():\n\tgraph = Graph()\n\ttry:\n\t\taux = open(sys.argv[2])\n\t\tfor line in aux:\n\t\t\tline = line.replace(':',',').replace('\\n','').split(',')\n\t\t\tv1 = Vertex(line[0])\n\t\t\tgraph.addVertex(v1)\n\t\t\tfor n in range(1,len(line)):\n\t\t\t\tif not line[n]:\n\t\t\t\t\tcontinue\n\t\t\t\tv2 = Vertex(line[n])\n\t\t\t\tif (not graph.isVertex(v2)):\n\t\t\t\t\tgraph.addVertex(v2)\n\t\t\t\tgraph.addEdge(v1,v2)\n\t\treturn graph\n\n\texcept KeyError:\n\t\tprint \"An error has occurred\"\n\texcept IndexError:\n\t\tusage()\n\texcept IOError:\n\t\tprint \"Verify parameters, input file does not exist\"\n\treturn False\n\ndef main():\n\tprint \"Teoria y Algoritmos 1 - [75.29]\"\n\tprint \"TP1 - Robustez en Grafos\"\n\tprint \"Autores: Alejandro Pernin (92216) y Lautaro Medrano (90009)\\n\"\n\n\tprint \"Grafo ingresado:\\n\"\n\tg = loadGraph()\n\tif not g:\n\t\treturn\n\tprint g\n\trobustez = sys.argv[1]\n\tprint \"Se requiere robustez %s\" % robustez\n\tif checkConditions(g,robustez):\n\t\t#print \"probando dfs\\n\"\n\t\tg.rdfs()\n\t\t\n#\t\tfor i in g.comp:\n#\t\t\ts = '['\n#\t\t\tfor j in i:\n#\t\t\t\ts += \"'%s',\" % j.key\n#\t\t\ts += \"]\\n\"\n#\t\t\tprint s\n\telse:\n\t\treturn\n\n\tg.setStrenght(int(robustez))\n\tprint \"Resultado:\"\n\tg.printResult()\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.707446813583374, "alphanum_fraction": 0.75, "avg_line_length": 13.461538314819336, "blob_id": "9591f9d27f3b4a53f1e0b52976982168813cab2d", "content_id": "9d00cd5a5d6a0c9440ea266670c4b32952e54cd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 190, "license_type": "no_license", "max_line_length": 62, "num_lines": 13, "path": "/README.md", "repo_name": "aleperno/tp1tda", "src_encoding": "UTF-8", "text": "tp1tda\n======\n\nTp1\n\n12/10/13\nPor ahora para probar el programa deberias ejecutar\n\npython test.py sarasa \nó\n./test.py sarasa\n\nPor ahora las pocas cosas que están hechas parecen andar bien.\n" }, { "alpha_fraction": 0.5823389291763306, "alphanum_fraction": 0.620525062084198, "avg_line_length": 14.55555534362793, "blob_id": "81e9c0f70d68a1bbe92606917259d012942c02e5", "content_id": "222a1a688884c8129a73f7bcabeafae7691f2736", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 32, "num_lines": 27, "path": "/test1.py", "repo_name": "aleperno/tp1tda", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys\nfrom Graph import *\n\ndef main():\n\tv1 = Vertex('A')\n\tv2 = Vertex('B')\n\tv3 = Vertex('C')\n\te1 = Edge(v1,v3)\n\te = Edge(v1,v2)\n\tprint e\n\tg = Graph()\n\tg.addVertex(v1)\n\tg.addVertex(v2)\n\tg.addVertex(v3)\n\tprint g.addEdge(e)\n\tprint g.addEdge(e1)\n\tprint g\n\tprint \"Will try to delete edge\"\n\tprint g.delEdge(v1,v2)\n\tprint g\n\tv4 = Vertex('A')\n\tg.delVertex(v4)\n\tprint g\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.45348837971687317, "alphanum_fraction": 0.5058139562606812, "avg_line_length": 14, "blob_id": "de40bdb119f76e2f8414c8137d3cb1916fcb464a", "content_id": "e106ed2c9960804ba01f3ead234700e517707386", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 345, "license_type": "no_license", "max_line_length": 51, "num_lines": 23, "path": "/autotests.sh", "repo_name": "aleperno/tp1tda", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncount=1\n\ntest(){\necho \"################################\"\necho \"# Prueba$count #\"\necho \"################################\"\n\n./tdatp1.py $1 grafoej$2\ncount=$((count+1))\necho -e \"Presione enter para la siguiente prueba\\n\"\nread opcion\n}\n\ntest 2 3\ntest 4 3\ntest 3 1\ntest 40 1\ntest 6 2 \ntest 3 2\n\necho \"No hay más pruebas\"" } ]
5
Dubaidogfish/uk_number_ones
https://github.com/Dubaidogfish/uk_number_ones
c5a70b8c2278230f1423b31621d0c395736fd7be
82cb6237214f1d00889a95d34b726ebc6ab01f75
e4f940d5be40ec726007ccc8e10f70f5568d8030
refs/heads/master
2020-04-17T07:51:28.051323
2016-08-29T08:40:37
2016-08-29T08:40:37
66,826,457
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5686274766921997, "alphanum_fraction": 0.5898692607879639, "avg_line_length": 34.882354736328125, "blob_id": "39e346bf2042856a2989645d7a738b972a7d7d6a", "content_id": "22a729d62638a475259feced52da4e7ad77c313f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 612, "license_type": "no_license", "max_line_length": 113, "num_lines": 17, "path": "/scraper.py", "repo_name": "Dubaidogfish/uk_number_ones", "src_encoding": "UTF-8", "text": "import scraperwiki\nfrom bs4 import BeautifulSoup\n\nfor x in range(1960,2013):\n html = scraperwiki.scrape(\"http://www.officialcharts.com/all-the-number-ones-singles-list/_/\" + str(x) + \"/\")\n import lxml.html\n root = lxml.html.fromstring(html)\n for tr in root.cssselect(\"table.chart tr.entry\"):\n tds = tr.cssselect(\"td\")\n \n data = {\n 'date' : tds[0].text_content(),\n 'artist' : tds[1].text_content(),\n 'title' : tds[2].text_content(),\n 'weeks' : int(tds[3].text_content())\n }\n scraperwiki.sqlite.save(unique_keys=['date'], data=data)\n\n\n" } ]
1
IvanovoSU/SportsManagerBackend
https://github.com/IvanovoSU/SportsManagerBackend
a374912af75d4d56cb3e67df1d296ea679673d45
9f7d2c6ff33feb8d2c33a14d5a28e3d0b5556fbf
eb011feac599b03b18d7f5a4d5913c73a45e4ec5
refs/heads/master
2020-04-24T08:08:41.254722
2019-05-13T20:42:01
2019-05-13T20:42:01
171,821,622
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4262567460536957, "alphanum_fraction": 0.4362276792526245, "avg_line_length": 28, "blob_id": "f055206e1e5a2b628ef386235c4608f1fd7535a4", "content_id": "94a7a06e5673d39571ecc0d2296b8809cf716582", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2526, "license_type": "permissive", "max_line_length": 90, "num_lines": 83, "path": "/mainPattern/templates/mainPattern/home.html", "repo_name": "IvanovoSU/SportsManagerBackend", "src_encoding": "UTF-8", "text": "{% extends \"mainPattern/wrapper.html\" %}\n\n\n{% block title %}Главная страница{% endblock %}\n{%load staticfiles %}\n{%block head %}\n<link rel=\"stylesheet\" href=\"{% static 'css/home-style.css' %}\" type=\"text/css\">\n{% endblock %}\n\n{% block header %}\n{% include 'mainPattern/includes/header.html' %}\n{% endblock %}\n\n{% block content %}\n <div class=\"wrapper fadeInDown\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-md-9\">\n <div class=\"row sportsmen\">\n Спортсмены %count%\n </div>\n <div class=\"row search\">\n <input type=\"search\" name=\"search\" placeholder=\"Начните вводить любое имя\"/>\n </div>\n <div class=\"row sportsman\">\n <div class=\"col-md-2\">\n <p>01.12.2004</p>\n </div>\n <div class=\"col-md-10\">\n <p>Владимир Владимирович Путин</p>\n <div class=\"info-block\">\n Дополнительная информация\n </div>\n </div>\n </div>\n <div class=\"row sportsman\">\n <div class=\"col-md-2\">\n <p>01.12.2005</p>\n </div>\n <div class=\"col-md-10\">\n <p>Дмитрий Анатольевич Медведев</p>\n </div>\n </div>\n </div>\n\n <div class=\"col-md-3 options\">\n <div class=\"row\">\n <p>Дата рождения</p>\n </div>\n <div class=\"row\">\n <select name=\"year\">\n <option value=\"year-none\">Год рождения</option>\n {% for i in years reversed %}\n <option value=\"{{i}}\">{{i}}</option>\n {% endfor %}\n </select>\n </div>\n <div class=\"row\">\n <select name=\"month\">\n <option value=\"month-none\">Месяц рождения</option>\n {% for i in months %}\n <option value=\"{{i}}\">{{i}}</option>\n {% endfor %}\n </select>\n </div>\n <div class=\"row\">\n <select name=\"day\">\n <option value=\"day-none\">День рождения</option>\n {% for i in days %}\n <option value=\"{{i}}\">{{i}}</option>\n {% endfor %}\n </select>\n </div>\n </div>\n </div>\n </div>\n </div>\n{% endblock %}\n\n{% block footer %}\n{% include 'mainPattern/includes/footer.html' %}\n{% endblock %}\n" }, { "alpha_fraction": 0.6345810890197754, "alphanum_fraction": 0.6345810890197754, "avg_line_length": 34.0625, "blob_id": "866aad8db59083bfbf39687206da10d75c4c42de", "content_id": "0586ecb127c21d792acb164143f5768314a1bba9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1186, "license_type": "permissive", "max_line_length": 138, "num_lines": 32, "path": "/mainPattern/templates/mainPattern/login.html", "repo_name": "IvanovoSU/SportsManagerBackend", "src_encoding": "UTF-8", "text": "{% extends 'mainPattern/wrapper.html' %}\n{% block title %}Авторизация{% endblock %}\n{% load staticfiles %}\n{% block head %}\n<link rel=\"stylesheet\" href=\"{% static 'css/login-style.css' %}\" type=\"text/css\">\n<link href=\"https://fonts.googleapis.com/css?family=Sniglet\" rel=\"stylesheet\">\n{% endblock %}\n\n{% block content %}\n<div class=\"wrapper fadeInDown\">\n\t<div class=\"homepage\">\n\t <button class=\"btn btn-outline-primary btn-lg underlineHover\" type=\"button\" name=\"button\" ><a href=\"/\">Главная страница</a></button> \n\t</div>\n <div id=\"formContent\">\n <div class=\"fadeIn first\">\n <img src=\"{% static 'image/user.svg'%}\" id=\"icon\" />\n <span id=\"login-text\"> Вход в панель управления:</span>\n </div>\n\n <form>\n <input type=\"text\" id=\"email\" class=\"fadeIn second\" name=\"Email\" placeholder=\"E-mail\">\n <input type=\"text\" id=\"password\" class=\"fadeIn third\" name=\"Pass\" placeholder=\"Пароль\">\n <input type=\"submit\" class=\"fadeIn fourth\" value=\"Войти\">\n </form>\n\n <div id=\"formFooter\">\n <a class=\"underlineHover\" href=\"#\">Забыли пароль?</a>\n </div>\n\n </div>\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.7731958627700806, "alphanum_fraction": 0.7731958627700806, "avg_line_length": 18.399999618530273, "blob_id": "7f2cdbae345ff69cfb511b64f9499dae854d895e", "content_id": "3bdff050aa866c85f205bf02f86c8258aec9aad8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 97, "license_type": "permissive", "max_line_length": 35, "num_lines": 5, "path": "/mainPattern/apps.py", "repo_name": "IvanovoSU/SportsManagerBackend", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass MainpatternConfig(AppConfig):\n name = 'mainPattern'\n" }, { "alpha_fraction": 0.6330472230911255, "alphanum_fraction": 0.6716738343238831, "avg_line_length": 34.846153259277344, "blob_id": "e0cd19f3a62d527245b4b80882044ce34cd1b619", "content_id": "61ad42e8d663a494377493026c825e9d52a373d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 466, "license_type": "permissive", "max_line_length": 130, "num_lines": 13, "path": "/mainPattern/views.py", "repo_name": "IvanovoSU/SportsManagerBackend", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom random import randint\n\ndef index(request):\n years = range(1902, 2006);\n months = range(1, 13);\n days = range(1, 32,)\n background = randint(1, 6);\n return render(request, 'mainPattern/home.html', {'years': years, 'months' : months, 'days': days, 'background' : background,})\n\ndef login(request):\n background = randint(1, 6);\n return render(request, 'mainPattern/login.html', {'background' : background,})\n" } ]
4
hanu16aug/Algorithms
https://github.com/hanu16aug/Algorithms
0ce249d35cfede0a9a9ffd4ac23aee6ac69cf28c
fd38627df5b63ca6b2c8613442e8e9721b77d1b8
5eff7afe33ffe79fc17cd1851a6eda317b0e504d
refs/heads/master
2018-10-08T21:36:39.240567
2018-06-22T19:15:16
2018-06-22T19:15:16
135,376,588
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.45836636424064636, "alphanum_fraction": 0.48215702176094055, "avg_line_length": 32.18421173095703, "blob_id": "45763058e067527c8265d14d702d39329202ad8d", "content_id": "cd9124a23d240b78571c0e3a2db636f0c7f98a32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1261, "license_type": "no_license", "max_line_length": 79, "num_lines": 38, "path": "/Sorting/Merge.py", "repo_name": "hanu16aug/Algorithms", "src_encoding": "UTF-8", "text": "def mergeSort(A, result, start, end):\n print('Processing ' + str(start) + ' to ' + str(end - 1))\n if end - start < 2:\n return\n if end - start == 2:\n if result[start] > result[start + 1]:\n print('Swapping.. ' + str(start) + ' nd ' + str(start + 1))\n result[start], result[start + 1] = result[start + 1], result[start]\n print(str(id(result)) + ':' + str(result))\n return\n mid = (start + end) // 2\n mergeSort(result, A, start, mid)\n mergeSort(result, A, mid, end)\n idx = start\n i = start\n j = mid\n print(str(id(A)) + ':' + str(A))\n print(str(id(result)) + ':' + str(result))\n print('Merging... ' + str(start) + ' to ' + str(end - 1))\n while idx < end:\n if j >= end or (i < mid and A[i] < A[j]):\n result[idx] = A[i]\n i = i + 1\n else:\n result[idx] = A[j]\n j = j + 1\n idx = idx + 1\n print(str(id(result)) + ':' + str(result))\n print('Merge done.')\n\n\narr = [8, 2, 6, 4, 9, 3, 7, 5, 1, 12, 10, 19, 14]\ncopy = list(arr)\nprint(str(id(arr)) + ':' + str(arr))\nprint(str(id(copy)) + ':' + str(copy))\nmergeSort(copy, arr, 0, len(arr))\nprint(str(id(arr)) + ':' + str(arr))\nprint(str(id(copy)) + ':' + str(copy))\n" }, { "alpha_fraction": 0.3456464409828186, "alphanum_fraction": 0.37203165888786316, "avg_line_length": 23.266666412353516, "blob_id": "66058e73b7076548e9ebc3a3c073f53197cec15c", "content_id": "fcd91ab628aeb686daf981e6aacc10ef98cfa2a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 68, "num_lines": 15, "path": "/Sorting/Selection.py", "repo_name": "hanu16aug/Algorithms", "src_encoding": "UTF-8", "text": "def sort(A):\r\n \"\"\"Selection sort\"\"\"\r\n for i in range(len(A)):\r\n min = i\r\n for j in range(min + 1, len(A)):\r\n if A[j] < A[min]:\r\n min = j\r\n if min != i:\r\n # print('Swapping ' + str(A[i]) + ' <-> ' + str(A[min]))\r\n A[i], A[min] = A[min], A[i]\r\n\r\n\r\narr = [2, 8, 6, 3, 4, 9, 7, 1, 0]\r\nsort(arr)\r\nprint(arr)\r\n" }, { "alpha_fraction": 0.48764997720718384, "alphanum_fraction": 0.5052928924560547, "avg_line_length": 26.34000015258789, "blob_id": "f83c0668d49e69bb31c5af08b3bc58a930b6f94c", "content_id": "3c0b31cab795d9ade206de96662689b2db4f5582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1417, "license_type": "no_license", "max_line_length": 67, "num_lines": 50, "path": "/Graphs/Graph.py", "repo_name": "hanu16aug/Algorithms", "src_encoding": "UTF-8", "text": "class Graph:\r\n def __init__(self):\r\n \"\"\"Initalize graph structure such that keys are vertices\"\"\"\r\n self.edges = {}\r\n\r\n def addVertex(self, v):\r\n \"\"\"Add a key to the dictionary\"\"\"\r\n if v not in self.edges:\r\n self.edges[v] = []\r\n\r\n def addEdges(self, from_v, to_u):\r\n \"\"\"Adds an edge v to u and u to v\"\"\"\r\n if from_v not in self.edges:\r\n self.edges[from_v] = []\r\n if to_u not in self.edges:\r\n self.edges[to_u] = []\r\n if from_v not in self.edges[to_u]:\r\n self.edges[to_u].append(from_v)\r\n if to_u not in self.edges[from_v]:\r\n self.edges[from_v].append(to_u)\r\n\r\n def isEdge(self, from_v, to_u):\r\n \"\"\"Checks if v,u is an edge or not\"\"\"\r\n if from_v not in self.edges:\r\n return False\r\n if to_u not in self.edges:\r\n return False\r\n return to_u in self.edges[from_v]\r\n\r\n\r\ng = Graph()\r\ng.addEdges(1, 2)\r\ng.addEdges(2, 3)\r\nprint(g.isEdge(1, 3))\r\nprint(g.isEdge(2, 3))\r\n\r\n\r\ndef loadEdges(data):\r\n \"\"\"Creates graph from a adjacency list representation\"\"\"\r\n g = Graph()\r\n for v in simple:\r\n for u in simple[v]:\r\n print(\"Adding edge \" + str(v) + \" <-> \" + str(u))\r\n g.addEdges(v, u)\r\n return g\r\n\r\n\r\nsimple = {1: [2, 3, 5], 2: [1, 4], 3: [1], 4: [2, 5], 5: [4, 1]}\r\ng = loadEdges(simple)\r\nprint(g.isEdge(4, 5))\r\n" }, { "alpha_fraction": 0.3290322721004486, "alphanum_fraction": 0.37419354915618896, "avg_line_length": 21.14285659790039, "blob_id": "4052da68d1a3a8d149a2399b7aadae1ff9887c4a", "content_id": "7645be59cf9d085ac2145d59830c4cedfccd1256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/Sorting/Bubble.py", "repo_name": "hanu16aug/Algorithms", "src_encoding": "UTF-8", "text": "def sort(A):\n \"\"\"Bubble Sort\"\"\"\n for i in range(len(A)):\n # print(i)\n for j in range(0, len(A) - i - 1):\n # print(j, end='')\n if A[j] > A[j + 1]:\n A[j], A[j + 1] = A[j + 1], A[j]\n print(A)\n\n\narr = [2, 8, 6, 3, 4, 9, 7, 1, 0]\nsort(arr)\nprint(arr)\n" }, { "alpha_fraction": 0.6063492298126221, "alphanum_fraction": 0.6634920835494995, "avg_line_length": 23.230770111083984, "blob_id": "521ce2e4212be8ed3cf1cdc79399c756620c4e81", "content_id": "763236d85860c4c4087743274e3d4be5206cfcfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "no_license", "max_line_length": 56, "num_lines": 13, "path": "/Graphs/GraphDraw.py", "repo_name": "hanu16aug/Algorithms", "src_encoding": "UTF-8", "text": "import networkx as nx\nimport matplotlib.pyplot as plt\n\nAGraph = nx.Graph()\nNodes = range(1, 5)\nEdges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5)]\nAGraph.add_nodes_from(Nodes)\nAGraph.add_edges_from(Edges)\nAGraph.add_node(6)\nAGraph.add_edge(1, 6)\nAGraph.add_node(7)\nnx.draw(AGraph, with_labels=True)\nplt.show()\n" }, { "alpha_fraction": 0.5386266112327576, "alphanum_fraction": 0.5729613900184631, "avg_line_length": 16.259260177612305, "blob_id": "073bb1c96401c0a6f95e70dbff6f39178e65bd73", "content_id": "10a2e23e5e85ef0913257dafc071b1ff8c5b5fd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 466, "license_type": "no_license", "max_line_length": 47, "num_lines": 27, "path": "/Mathematical/xPowN.py", "repo_name": "hanu16aug/Algorithms", "src_encoding": "UTF-8", "text": "from time import time\nfrom datetime import datetime\n\n\ndef exponent(x, n):\n if n == 0:\n return 1\n if n == 1:\n return x\n if n % 2: # If n is odd number\n return x * exponent(x * x, (n - 1) / 2)\n\n return exponent(x * x, n / 2)\n\n\nstart = time()\nprint(exponent(2, 100))\nprint(time() - start)\n\nstart = time()\nprint(2**3)\nprint(time() - start)\nprint(True ^ True)\nprint((2))\nprint(ord('a'))\nprint(str(datetime.now().date()))\nprint(type(12))\n" }, { "alpha_fraction": 0.3885135054588318, "alphanum_fraction": 0.43918919563293457, "avg_line_length": 16.41176414489746, "blob_id": "407787f9de8ad2002c7295fc62a943b907e1431c", "content_id": "f6c41f7acb49bb134aed4ee58f643607e7b663fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "no_license", "max_line_length": 34, "num_lines": 17, "path": "/Sorting/Insertion.py", "repo_name": "hanu16aug/Algorithms", "src_encoding": "UTF-8", "text": "def sort(A):\n \"\"\"Insertion Sort\"\"\"\n for i in range(1, len(A)):\n insert(A, i, A[i])\n\n\ndef insert(A, idx, value):\n j = idx - 1\n while j >= 0 and A[j] > value:\n A[j + 1] = A[j]\n j = j - 1\n A[j + 1] = value\n\n\narr = [2, 8, 6, 3, 4, 9, 7, 1, 0]\nsort(arr)\nprint(arr)\n" }, { "alpha_fraction": 0.46194925904273987, "alphanum_fraction": 0.49399200081825256, "avg_line_length": 25.740739822387695, "blob_id": "79fe65b31aaa8a25502968c7e61f6b573fb0efec", "content_id": "0734bece3dfef6eafe3dd7f224e57ab3e4832bd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 749, "license_type": "no_license", "max_line_length": 65, "num_lines": 27, "path": "/Sorting/Quick.py", "repo_name": "hanu16aug/Algorithms", "src_encoding": "UTF-8", "text": "def quickSort(A, low, high):\r\n \"\"\"Quick Sort\"\"\"\r\n if low < high:\r\n # Get the pivot\r\n pi = pivot(A, low, high)\r\n # Quick sort elements to the left of the pivot index\r\n quickSort(A, low, pi - 1)\r\n # Quick sort elements to the right of the pivot index\r\n quickSort(A, pi + 1, high)\r\n\r\n\r\ndef pivot(A, low, high):\r\n \"\"\"Returns the pivoted index after arranging the elements.\"\"\"\r\n target = A[high]\r\n i = low - 1\r\n for j in range(low, high):\r\n if A[j] < target:\r\n i = i + 1\r\n A[i], A[j] = A[j], A[i]\r\n i = i + 1\r\n A[i], A[high] = A[high], A[i]\r\n return i\r\n\r\n\r\narr = [8, 2, 6, 4, 14, 3, 7, 5, 1, 12, 10, 19, 9]\r\nquickSort(arr, 0, len(arr) - 1)\r\nprint(arr)\r\n" } ]
8
madnanit/molssi-tapia-camp
https://github.com/madnanit/molssi-tapia-camp
51d27daaa3771dda9538844f432ba2e4aaaa2878
c864dd2a99d54dba4082daa301923e6816bd2041
2cd20cef96bbb8cb3cc9b812d3c7e7489a0bbe68
refs/heads/master
2020-06-03T13:42:52.844188
2019-06-12T15:27:49
2019-06-12T15:27:49
191,590,416
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6425855755805969, "alphanum_fraction": 0.6707224249839783, "avg_line_length": 33.605262756347656, "blob_id": "3162988778dfc6144027b48476ca1240ff5d673f", "content_id": "b837b4f98fa7ca68d080bfbdeb2aaebada9967f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1315, "license_type": "no_license", "max_line_length": 95, "num_lines": 38, "path": "/geometry_analysis_2.py", "repo_name": "madnanit/molssi-tapia-camp", "src_encoding": "UTF-8", "text": "import os\nimport numpy\n\ndef calculate_distance(coords1,coords2):\n# this function has two parameters. It returns the distance b/w atoms.\n \"\"\"\n this function has two parameters. It returns the distance b/w atoms.\n \"\"\"\n x_distance = coords1[0] - coords2[0]\n y_distance = coords1[1] - coords2[1]\n z_distance = coords1[2] - coords2[2]\n xy_distance = numpy.sqrt(x_distance**2 + y_distance**2 + z_distance**2)\n return xy_distance\n\ndef bond_check2(blength, minimum=0, maxmimum=1.5):\n if blength > minimum and blength < maxmimum:\n return True\n else:\n return False\n# a function that checks the distance within a range and returns whether it is true or false\n# it is based on the distance and we can define the min and max and their default value as well\n\nposition_file = os.path.join('water.xyz')\npositions = numpy.genfromtxt(fname=position_file, dtype='unicode', skip_header=2)\natoms = positions[:,0]\ndata = positions[:,1:]\ndata = data.astype(numpy.float)\natom_num = len(atoms)\n\nfor atm1 in range(0,atom_num):\n for atm2 in range(0, atom_num):\n if atm2 > atm1:\n\n xy_distance = calculate_distance(data[atm1], data[atm2])\n\n if bond_check2(xy_distance, maxmimum=2) is True:\n\n print(F'{atoms[atm1]} to {atoms[atm2]} = {xy_distance:.3f}')\n" }, { "alpha_fraction": 0.7578475475311279, "alphanum_fraction": 0.7578475475311279, "avg_line_length": 28.733333587646484, "blob_id": "eaeed3169a27d07d53bc805dba3711b44beb5574", "content_id": "296ae8061021e3d8f20da29b13302c8986b359a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 446, "license_type": "no_license", "max_line_length": 100, "num_lines": 15, "path": "/README.md", "repo_name": "madnanit/molssi-tapia-camp", "src_encoding": "UTF-8", "text": "# MolSSI Workshop at Rice University, Tapia Center\n\nThis repository contains material for the MolSSI workshop at the Rice University, Tapia Center Camp.\n\n## This repository contains:\n- raw data files (e.g. ???.xyz , ???.csv)\n- png files generated by the python code we wrote\n- Jupyter notebooks\n- and the git repository\n\n## Jupyter notebooks contain these topics:\n- Python Syntax\n- File Parsing\n- Plotting\n- Geometry analysis project & Functions\n" } ]
2
aboustati/PythonMisc
https://github.com/aboustati/PythonMisc
991b97cd607e31662901121804645065fbdd90b8
f5bff8752e0816ee2c0c6decf71b024d47c326d6
36eeeaaca9a7d47a5a18cdf567892dd80ab1676b
refs/heads/master
2021-01-11T16:35:54.114934
2016-12-16T13:35:29
2016-12-16T13:35:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6942538619041443, "alphanum_fraction": 0.6985419988632202, "avg_line_length": 34.33333206176758, "blob_id": "964a2d92a3e019243092fab22421a28ff7f7bf12", "content_id": "f78c8b8eab8b4a0b788ca9cc8e143d0ab308563d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 2332, "license_type": "no_license", "max_line_length": 279, "num_lines": 66, "path": "/results/results.lua", "repo_name": "aboustati/PythonMisc", "src_encoding": "UTF-8", "text": "require \"lsqlite3\"\nrequire 'sys'\n\nlocal results = {}\n\nfilename = os.getenv(\"JR_RESULTSFILE\") or \"results.sqlite\"\ncon = sqlite3.open(filename)\nfilecontents = \"\"\n\nfunction append_file_to_filecontents_string(f)\n local ff = io.open(f,\"r\")\n local content = ff:read(\"*all\")\n ff:close()\n filecontents = filecontents .. f ..\"\\n\"..content\nend\n\nfunction check(x)\n if x~=sqlite3.OK then\n error(con:errmsg())\n end\nend\n\n--if sql is a statement which doesn't return results,\n--resultless(sql, param1, param2) executes it with the given parameters\nfunction resultless(st, ...)\n local s = con:prepare(st)\n assert(s)\n s:bind_values(...)\n local res = s:step()\n if res~=sqlite3.DONE then\n error(con:errmsg())\n end\n s:finalize()\nend\n\nfunction results.startRun(repnname, repnlength, continuation, batchTr, batchTe, layertype, layers, width, architecture, solver, callerFilePath)\n if \"table\" == type(callerFilePath) then\n for i,name in ipairs(callerFilePath) do\n append_file_to_filecontents_string(name)\n end\n else\n append_file_to_filecontents_string(callerFilePath)\n end\n local setup=[[create table if not exists RUNS(COUNT INTEGER PRIMARY KEY, TIME TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL, REPN TEXT, REPNLENGTH INT, CONTINUATION TEXT, BATCHTR INT, BATCHTE INT, LAYERTYPE TEXT, LAYERS INT, WIDTH INT, ARCHITECTURE TEXT, SOLVER TEXT, CODE TEXT) ;\n create table if not exists STEPS(STEP INTEGER PRIMARY KEY, RUN int, OBJECTIVE real, TRAINACC real, TESTOBJECTIVE real, TESTACC REAL );\n create table if not exists TIMES(RUN INT, TIME real)\n ]]\n check(con:exec(setup))\n local infoquery = \"insert into RUNS (REPN, REPNLENGTH, CONTINUATION, BATCHTR, BATCHTE, LAYERTYPE, LAYERS, WIDTH, ARCHITECTURE, SOLVER, CODE) VALUES (?,?,?,?,?,?,?,?,?,?,?)\"\n local info = {repnname, repnlength, continuation, batchTr, batchTe, layertype, layers, width, architecture, solver, filecontents}\n resultless(infoquery,unpack(info))\n nrun = con:last_insert_rowid()\n sys.tic()\n nsteps = 0\n filecontents = nil\nend\n\nfunction results.step(obj,train,objte,test)\n nsteps = 1+nsteps\n resultless(\"insert into steps values (NULL, ?, ?, ?, ?, ?)\", nrun,obj,train,objte, test)\n if nsteps == 10 then\n resultless(\"insert into TIMES VALUES (?,?)\", nrun, sys.toc())\n end\nend\n\nreturn results\n" }, { "alpha_fraction": 0.7938144207000732, "alphanum_fraction": 0.7955326437950134, "avg_line_length": 40.64285659790039, "blob_id": "11140a22bfbd78b4affcc431b77b83bfab09bd18", "content_id": "a8c2e72a773596b6a564535daff48ba3609bbffc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 582, "license_type": "no_license", "max_line_length": 127, "num_lines": 14, "path": "/README.md", "repo_name": "aboustati/PythonMisc", "src_encoding": "UTF-8", "text": "# PythonMisc\nSome fairly standalone python scripts\n\n* readSketchnet: tool to read data from the sketch-a-net dataset http://cybertron.cg.tu-berlin.de/eitz/projects/classifysketch/\n\n* oncampus: Should graphs be sent from a warwick computer to the screen or a file.\n\n* shapes: function for printing the \"shape\" of something like a tuple of lists of numpy arrays\n\n* tinisMultiRun: script for parallelizing another script across the 4 GPUs you get on tinis\n\n* tinisDummyProgram: a demo program for tinisMultiRun\n\n* results: code for managing results of long neural network training runs" }, { "alpha_fraction": 0.7441471815109253, "alphanum_fraction": 0.7458193898200989, "avg_line_length": 48.83333206176758, "blob_id": "0edae7b3b3767e3704cbafa61f0c883456426375", "content_id": "92db403452ed67ef7633f4c7cf51e2b471295585", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 598, "license_type": "no_license", "max_line_length": 156, "num_lines": 12, "path": "/oncampus.py", "repo_name": "aboustati/PythonMisc", "src_encoding": "UTF-8", "text": "#This module is intended to be run on a linux machine on the Warwick campus\n#it provides two boolean variables:\n# oncampus : whether you are sitting on campus (which implies you probably have a very fast connection to this machine)\n# draw : whetheer it would be a good idea to try to plot graphs to the screen. This will be false if you are offcampus or are using SSH without X forwarding\nimport os, subprocess, string\n\nif \"SSH_CLIENT\" in os.environ:\n oncampus = -1 < subprocess.check_output([\"who\", \"-m\"]).find(b\"warwick\")\nelse:\n oncampus = True\n\ndraw = oncampus and \"DISPLAY\" in os.environ\n" } ]
3
RikDuijm/e-commerce
https://github.com/RikDuijm/e-commerce
01b8879c805f438ea0b6ba8c3ae53393791791b6
3f21ac60af6ba81932dac024faa1fa119df1877a
f82fb1285f62d935e5285b545c6638c0f4750028
refs/heads/master
2022-12-01T18:48:23.999317
2019-12-05T16:07:55
2019-12-05T16:07:55
224,640,137
0
0
null
2019-11-28T11:38:52
2019-12-05T16:08:10
2022-11-22T04:52:37
Python
[ { "alpha_fraction": 0.6712533831596375, "alphanum_fraction": 0.6712533831596375, "avg_line_length": 47.449275970458984, "blob_id": "5162c6c031e8bbaf8332ab52b9dc6ce8c90512c1", "content_id": "4ec9236c486aaf1479788596918dae0dbccac3f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3343, "license_type": "no_license", "max_line_length": 190, "num_lines": 69, "path": "/accounts/views.py", "repo_name": "RikDuijm/e-commerce", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect, reverse\nfrom django.contrib import auth, messages\nfrom django.contrib.auth.decorators import login_required \nfrom django.contrib.auth.models import User\nfrom accounts.forms import UserLoginForm, UserRegistrationForm\nimport os\n\n# Create your views here.\ndef index(request):\n \"\"\"return the index.html file\"\"\"\n print(os.environ.get(\"EMAIL_ADDRESS\"))\n print(os.environ.get(\"EMAIL_PASSWORD\"))\n return render(request, \"index.html\")\n\n@login_required # required to only allow access to the logout page if user is authenticated; Django automatically redirects to login page if logged out user tries to enter logout page by url\ndef logout(request):\n \"\"\"Log the user out\"\"\"\n auth.logout(request)\n messages.success(request, \"You have successfully been logged out\")\n return redirect(reverse('index'))\n\ndef login(request):\n \"\"\"Return a login page\"\"\"\n if request.user.is_authenticated: # check if user is logged in and if so, redirect him to homepage. Otherwise still able to enter login page through url \n return redirect(reverse('index'))\n\n if request.method == \"POST\":\n login_form = UserLoginForm(request.POST) \n # if request method is equal to POST then create an instance of the user login form, so a new login form will be created with the data posted from the form on the UI \n if login_form.is_valid(): #check if data is valid, this is a method. \n user = auth.authenticate(username=request.POST['username'], # this will authenticate the user, whether or not this user has provided the username and password \n password=request.POST['password'])\n if user:\n auth.login(user=user, request=request) # Then our authenticate function will return a user object so if we have a user then we'll log him in.\n messages.success(request, \"You have successfully logged in!\") \n return redirect(reverse('index'))\n else:\n login_form.add_error(None, \"Your username or password is incorrect\")\n else:\n login_form = UserLoginForm() # otherwise we're just going to create an empty object \n return render(request, 'login.html', {'login_form': login_form})\n\ndef registration(request):\n \"\"\"Render the registration page\"\"\"\n if request.user.is_authenticated:\n return redirect(reverse('index'))\n\n if request.method == \"POST\":\n registration_form = UserRegistrationForm(request.POST)\n\n if registration_form.is_valid():\n registration_form.save()\n\n user = auth.authenticate(username=request.POST['username'],\n password=request.POST['password1'])\n if user:\n auth.login(user=user, request=request)\n messages.success(request, \"You have successfully registered\")\n else:\n messages.error(request, \"Unable to register your account at this time\")\n else:\n registration_form = UserRegistrationForm()\n return render(request, 'registration.html', {\n \"registration_form\": registration_form}) \n\ndef user_profile(request):\n \"\"\"\"The user's profile page\"\"\"\n user = User.objects.get(email=request.user.email)\n return render(request, 'profile.html', {\"profile\": user})\n" }, { "alpha_fraction": 0.7637130618095398, "alphanum_fraction": 0.7637130618095398, "avg_line_length": 25.44444465637207, "blob_id": "323832c21152fd62c0a89006fa19c96117b602ef", "content_id": "4f05fcc3df8a3060e039c7fe72ac1c293f7a717b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 237, "license_type": "no_license", "max_line_length": 121, "num_lines": 9, "path": "/README.md", "repo_name": "RikDuijm/e-commerce", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.org/RikDuijm/e-commerce.svg?branch=master)](https://travis-ci.org/RikDuijm/e-commerce)\n\n# Code Institute\n\nWelcome RikDuijm,\n\nWe have preinstalled all of the tools you need to get started.\n\nHappy coding!" } ]
2
Woofka/ant-colony-optimization
https://github.com/Woofka/ant-colony-optimization
d8a2872870ea79c7a9206c6e306849d702384dce
02754e04f704433c5a42f454d90f067d971d323e
67a8e12629aad020a9fc81d5d9736c753cd1ce55
refs/heads/master
2022-04-10T10:06:19.219490
2020-03-12T17:32:18
2020-03-12T17:32:18
174,822,578
0
0
null
2019-03-10T12:47:12
2019-04-01T11:26:26
2019-04-01T11:30:33
Python
[ { "alpha_fraction": 0.586856484413147, "alphanum_fraction": 0.5999425053596497, "avg_line_length": 54.08064651489258, "blob_id": "c33dc126b3684e51ace6cf464fef73908e863324", "content_id": "e0124661cf2579e9d80307a306d150d53e2f37ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8169, "license_type": "no_license", "max_line_length": 178, "num_lines": 124, "path": "/aco.py", "repo_name": "Woofka/ant-colony-optimization", "src_encoding": "UTF-8", "text": "import random\r\n\r\n\r\nclass AntColony:\r\n def __init__(self, antsNum, alpha, beta, pheromoneQantity, pheromoneElite, pheromoneEvaporation):\r\n self.antsNum = antsNum # количество муравьев в колонии\r\n self.alpha = alpha # степень влияния эвристического расстояния на выбор пути\r\n self.beta = beta # степень влияния концентрации феромона на выбор пути\r\n self.pheromoneQantity = pheromoneQantity # множитель количества феромона, оставляемого муравьями\r\n self.pheromoneElite = pheromoneElite # множитель усиления наилучшего пути (феромон элитных муравьев)\r\n self.pheromoneEvaporation = pheromoneEvaporation # доля испаряющегося феромона\r\n self.verticesNum = 0 # число вершин матрицы\r\n self.matrixCost = [] # матрица смежности со стоимостью пути\r\n self.matrixPheromone = [] # матрица смежности с концентрациями феромона\r\n self.antsRoutes = [] # список маршрутов, пройденных муравьями\r\n self.routesCosts = [] # список стоимостей соответствующих маршрутов\r\n self.bestRoute = [] # кратчайший маршрут\r\n self.bestRouteCost = 0 # стоимость кратчайшего маршрута\r\n\r\n def routeCost(self, route):\r\n \"\"\"\r\n Возвращает стоимость маршрута <route> согласно матрице смежности <self.matrixCost>\r\n Где <route> - последовательность прохождения вершин графа, например: [1, 3, 2, 1]\r\n \"\"\"\r\n cost = 0\r\n for k in range(len(route) - 1):\r\n cost += self.matrixCost[route[k + 1]][route[k]]\r\n return cost\r\n\r\n def readMatrix(self):\r\n \"\"\" Считывает матрицу смежности <self.matrixCost> из stdin и инициализирует кол-во вершин графа <self.verticesNum> \"\"\"\r\n row = input()\r\n self.matrixCost.append(list(map(int, row.split())))\r\n self.verticesNum = len(self.matrixCost[0])\r\n for i in range(self.verticesNum - 1):\r\n row = input()\r\n self.matrixCost.append(list(map(int, row.split())))\r\n\r\n def initPhMap(self):\r\n \"\"\" Инициализирует случайную матрицу смежности <self.matrixPheromone>, содержащую концентрации феромона от 0.01 до 0.05 \"\"\"\r\n self.matrixPheromone = [[0 if i == j else random.randint(10, 50) / 1000 for i in range(self.verticesNum)] for j in range(self.verticesNum)]\r\n\r\n def initAnts(self):\r\n \"\"\" Инициализирует начальное положение муравьев в <self.antsRoutes> и длины их маршрутов <self.routesLengths> \"\"\"\r\n self.antsRoutes = [[i % self.verticesNum] if i > self.verticesNum - 1 else [i] for i in range(self.antsNum)]\r\n self.routesCosts = [0 for i in range(self.antsNum)]\r\n\r\n def initBestRoute(self):\r\n \"\"\" Инициализирует начальный кратчайший маршрут <self.bestRoute> и его стоимость <self.bestRouteCost> \"\"\"\r\n self.bestRoute = [i for i in range(self.verticesNum)]\r\n self.bestRoute.append(0)\r\n self.bestRouteCost = self.routeCost(self.bestRoute)\r\n\r\n def calculateRoutes(self):\r\n \"\"\" Для каждого k-го муравья в колонии просчитывает маршрут <self.antsRoutes[k]> и вычисляет его стоимость <self.routesCosts[k]> \"\"\"\r\n for k in range(self.antsNum):\r\n for y in range(self.verticesNum - 2):\r\n i = self.antsRoutes[k][-1]\r\n sumValue = 0.0\r\n probability = []\r\n for j in range(self.verticesNum):\r\n if j not in self.antsRoutes[k]:\r\n TauNu = (1 / self.matrixCost[j][i]) ** self.alpha * self.matrixPheromone[j][i] ** self.beta # величина целесообразности перехода из вершины i в вершину j\r\n sumValue += TauNu\r\n probability.append([TauNu, j])\r\n previousValue = 0\r\n randomInteger = random.randint(0, 99)\r\n if sumValue == 0.0:\r\n sumValue += 0.000001\r\n for z in probability:\r\n z[0] = previousValue + 100 * z[0] / sumValue # вероятность перехода из вершины i в вершину j на отрезке от 0 до 100\r\n previousValue = z[0]\r\n if randomInteger <= z[0]: # если случайное число попало в текущий промежуток на отрезке\r\n self.antsRoutes[k].append(z[1])\r\n break\r\n for j in range(self.verticesNum): # нахождение последней непосещенной вершины\r\n if j not in self.antsRoutes[k]:\r\n self.antsRoutes[k].append(j)\r\n self.antsRoutes[k].append(self.antsRoutes[k][0])\r\n break\r\n self.routesCosts[k] = self.routeCost(self.antsRoutes[k]) # замыкание маршрута\r\n\r\n def updateBestRoute(self):\r\n \"\"\" Обновляет кратчайший машрут <self.bestRoute> и его стоимость <self.bestRouteCost> \"\"\"\r\n bestAnt = -1\r\n bestCost = self.bestRouteCost\r\n for k in range(self.antsNum):\r\n if self.routesCosts[k] < bestCost:\r\n bestAnt = k\r\n bestCost = self.routesCosts[k]\r\n if bestAnt != -1:\r\n self.bestRouteCost = self.routesCosts[bestAnt]\r\n self.bestRoute = self.antsRoutes[bestAnt]\r\n\r\n def updatePheromone(self):\r\n \"\"\" Обновляет концентрации феромонов в матрице <self.matrixPheromone> \"\"\"\r\n deltaMatrixPheromone = [[0.0 for i in range(self.verticesNum)] for j in range(self.verticesNum)]\r\n for k in range(self.antsNum):\r\n for i in range(len(self.antsRoutes[k]) - 1):\r\n deltaMatrixPheromone[self.antsRoutes[k][i + 1]][self.antsRoutes[k][i]] += self.pheromoneQantity / self.routesCosts[k]\r\n deltaMatrixPheromone[self.antsRoutes[k][0]][self.antsRoutes[k][-1]] += self.pheromoneQantity / self.routesCosts[k]\r\n self.antsRoutes[k] = [self.antsRoutes[k][-1]]\r\n for i in range(len(self.bestRoute) - 1):\r\n deltaMatrixPheromone[self.bestRoute[i + 1]][self.bestRoute[i]] += self.pheromoneElite * self.pheromoneQantity / self.bestRouteCost\r\n for j in range(self.verticesNum):\r\n for i in range(self.verticesNum):\r\n self.matrixPheromone[j][i] = (1 - self.pheromoneEvaporation) * self.matrixPheromone[j][i] + deltaMatrixPheromone[j][i]\r\n\r\n def aco(self, tmax):\r\n \"\"\" Основной цикл муравьиного алгоритма. Ищет кратчайший маршрут в течение <tmax> итераций \"\"\"\r\n self.readMatrix()\r\n self.initPhMap()\r\n self.initAnts()\r\n self.initBestRoute()\r\n for t in range(tmax):\r\n self.calculateRoutes()\r\n self.updateBestRoute()\r\n self.updatePheromone()\r\n\r\n\r\n# ----- MAIN PROGRAM -----\r\ncolony = AntColony(antsNum=20, alpha=0.311, beta=1, pheromoneQantity=0.645, pheromoneElite=1.6, pheromoneEvaporation=0.86)\r\ncolony.aco(tmax=500)\r\nprint(colony.bestRouteCost)\r\n" }, { "alpha_fraction": 0.7689793109893799, "alphanum_fraction": 0.7849618792533875, "avg_line_length": 47.29824447631836, "blob_id": "bddad57b14708d7db9b32f87f2f1360e0a826351", "content_id": "5ff3687896a496e4618eb7f89a0f99ea21682c01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4563, "license_type": "no_license", "max_line_length": 138, "num_lines": 57, "path": "/README.md", "repo_name": "Woofka/ant-colony-optimization", "src_encoding": "UTF-8", "text": "# Муравьиный алгоритм (ant colony optimization)\nПрограмма написана Соболевым Владимиром на Python.\n\nДанная программа решает задачу коммивояжера с применением муравьиного алгоритма.\nПрограмма чувствительна к параметрам и необходимо экспериментальным путем подбирать их для каждой задачи.\n\nАлгоритм работы в псевдокоде:\n1. Инициализация параметров:\n antsNum - кол-во муравьев в колонии\n alpha - степень влияния эвристического расстояния на выбор пути\n beta - степень влияния концентрации феромона на выбор пути\n pheromoneQantity - множитель количества феромона, оставляемого муравьями\n pheromoneElite - множитель усиления наилучшего пути (феромон элитных муравьев)\n pheromoneEvaporation - доля испаряющегося феромона\n tmax - кол-во итераций до завершения работы алгоритма (время жизни колонии)\n2. Ввод матрицы смежности с весами ребер\n3. Инициализация начальной концентрации феромона\n4. Размещение муравьев\n5. Выбор начального кратчайшего маршрута и определение его стоимости\n6. Цикл по времени жизни колонии\n 7. Цикл по всем муравьям\n 8. Построить маршрут и рассчитать его длину\n 9. Конец цикла по муравьям\n 10. Проверка всех маршрутов на лучшее решение по сравнению с кратчайшим маршрутом\n 11. В случае, если есть решение лучше, обновить кратчайший маршрут и его стоимость\n 12. Цикл по всем рёбрам\n 13. Обновить концентрации феромона на ребре\n 14. Конец цикла по рёбрам\n15. Конец цикла по времени\n16. Вывести стоимость кратчайшего пути\n\nВыбор очередной вершины j происходит следующим образом:\n1. Для каждой доступной для перехода вершины (есть ребро (i,j) и j ещё не была посещена) рассчитывается значение TauNu по формуле\n TauNu = Nu^alpha * Tau^beta,\nгде:\n Nu = 1/<вес ребра (i,j)>,\n Tau = <концентрация феромона на ребре (i,j)>\n2. Одновременно с этим вычисляется sumValue - сумма всех TauNu\n3. Для каждой вершины j рассчитывается вероятность перехода в эту вершину по формуле\n p = 100 * TauNu / sumValue\n4. Вероятности представляются как промежутки отрезка от 0 до 100\n5. Генерируется случайное число от 0 до 100 и в зависимости от попадания в тот или иной промежуток на отрезке выбирается следующая вершина\n\nОбновление феромона на ребре (i,j) происходит следующим образом:\n1. Рассчитывается deltaTau - суммарное кол-во феромона, оставленное всеми муравьями на этом ребре\n где для k-го муравья deltaTau(k) = Q/<вес ребра (i,j)>\n где Q = pheromoneQantity\n2. К deltaTau прибавляется значение TauE - кол-во феромона, оставляемого так называемыми элитными муравьями\n TauE = E * Q / bestcost\nгде:\n Q = pheromoneQantity\n E = pheromoneElite\n bestcost = <стоимость кратчайшего пути>\n3. Рассчитывается новое значение концетрации феромона Tau'\n Tau' = (1 - p) * Tau + deltaTau\nгде:\n p = pheromoneEvaporation\n" } ]
2
ParkyGit/Lunabotics-Motion-Tracking
https://github.com/ParkyGit/Lunabotics-Motion-Tracking
5036187c6f499eaf50d9a617d63011a2b59a7f54
a827bba0851a7f82d6b49ef2a8685d3df0c28856
6863f179848e2bbbc070238abcb36948f43600b7
refs/heads/master
2023-04-18T22:29:12.958699
2021-05-02T23:40:49
2021-05-02T23:40:49
338,146,260
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 24.45098114013672, "blob_id": "911c3be6d8eb88e4ea4d19f678aa3b3dba204356", "content_id": "ea34fb38e6b8467a568a8ddb205024ab339832c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1298, "license_type": "no_license", "max_line_length": 93, "num_lines": 51, "path": "/static_tests.py", "repo_name": "ParkyGit/Lunabotics-Motion-Tracking", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 4 10:48:03 2021\n\n@author: vargh\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom skimage import data\nfrom scipy.ndimage import fourier_shift\nimport cv2\n\nimage = data.camera()\nrows,cols = image.shape\nshift = (-25, 15)\n# The shift corresponds to the pixel offset relative to the reference image\nM = np.float32([[1,0,15],[0,1,-25]])\noffset_image = cv2.warpAffine(image,M,(cols,rows))\nprint(\"Known offset (y, x): {}\".format(shift))\n\nimage = np.float32(image)\noffset_image = np.float32(offset_image)\n\ndispbuiltin = cv2.phaseCorrelate(image, offset_image)[0]\nprint(\"Calculated Offset (Built In) - (y,x): %f, %f\"%(dispbuiltin[1], dispbuiltin[0]))\n\nf1 = np.fft.fft2(image)\nf2 = np.fft.fft2(offset_image)\n\ncross_power_spect = np.multiply(f1 , np.conjugate(f2))/abs(np.multiply(f1, np.conjugate(f2)))\n\npeakgraph = np.fft.ifft2(cross_power_spect)\n\ndetected_shift = np.where(peakgraph == np.amax(peakgraph))\n\nif detected_shift[0][0] > cols//2:\n y_shift = detected_shift[0][0] - cols\nelse:\n y_shift = detected_shift[0][0]\n\nif detected_shift[1][0] > rows//2:\n x_shift = detected_shift[1][0] - rows\nelse:\n x_shift = detected_shift[1][0]\n\nprint(\"Calculated Offset (Custom) - (y,x): %f, %f\"%(y_shift, x_shift))\n\n\ninput('Press ENTER to exit')\n" } ]
1
cdalvaro/machine-learning-notebooks
https://github.com/cdalvaro/machine-learning-notebooks
1ff37b4241e46d90169e6c195c72f07563e9e093
ec0e5331d28acf3db1efb73312f966a0535376f7
75e7204c4c748808dc8ebe3bc823e589ae678bfb
refs/heads/main
2022-12-30T21:52:29.064728
2020-10-23T06:10:48
2020-10-23T06:10:48
264,998,160
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6168763041496277, "alphanum_fraction": 0.6174004077911377, "avg_line_length": 35, "blob_id": "080fc5982b3f5e79273041a19f2248130b136cd4", "content_id": "079d6cbea964a1bbc05cf4806cf29037ecd2d074", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1924, "license_type": "permissive", "max_line_length": 83, "num_lines": 53, "path": "/notebooks/strips/cdalvaro/actions/push_box.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_action import BaseAction\nfrom ..element import Box, Monkey\nfrom ..properties import AtLevel, GroundLevel, AtPosition\n\n\nclass PushBox(BaseAction):\n\n def __init__(self, from_position: int, to_position: int):\n \"\"\"\n Clase con la acción de empujar la caja.\n\n Esta clase modeliza la operación de empujar la caja de una posición a otra.\n\n Args:\n from_position (int): Posición desde la que se va a mover el elemento.\n to_position (int): Posición a la que se va a mover el elemento.\n \"\"\"\n name = f\"{Monkey()} empuja la {Box()} de {from_position} a {to_position}\"\n weight = 1\n\n super().__init__(name, weight)\n self.from_position: int = from_position\n self.to_position: int = to_position\n\n self._set_precondition()\n self._set_add_list()\n self._set_remove_list()\n\n def _set_precondition(self):\n \"\"\"\n * La caja se encuentra en la posición de partida\n * El mono se encuentra en la posición de partida\n * El mono está en el nivel inferior\n \"\"\"\n self.precondition.add(AtPosition(Box(), self.from_position))\n self.precondition.add(AtPosition(Monkey(), self.from_position))\n self.precondition.add(AtLevel(Monkey(), GroundLevel(), self.from_position))\n\n def _set_add_list(self):\n \"\"\"\n * La caja estará en la nueva posición\n * El mono estará en la nueva posición\n \"\"\"\n self.add_list.add(AtPosition(Box(), self.to_position))\n self.add_list.add(AtPosition(Monkey(), self.to_position))\n\n def _set_remove_list(self):\n \"\"\"\n * La caja dejará de estar en la posición de origen\n * El mono dejará de estar en la posición de origen\n \"\"\"\n self.remove_list.add(AtPosition(Box(), self.from_position))\n self.remove_list.add(AtPosition(Monkey(), self.from_position))\n" }, { "alpha_fraction": 0.6012269854545593, "alphanum_fraction": 0.6036809682846069, "avg_line_length": 27.10344886779785, "blob_id": "fd77ee19ff7c44276eac65960650c385e1b5eb51", "content_id": "2d7a2649e381349531008f7857c4e95b8beb4a76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 816, "license_type": "permissive", "max_line_length": 88, "num_lines": 29, "path": "/notebooks/strips/cdalvaro/properties/base_property.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from typing import Set, TypeVar\n\nProperties = TypeVar('Properties', bound=Set['BaseProperty'])\n\n\nclass BaseProperty:\n\n def __init__(self, description: str, weight: int = 0):\n \"\"\"\n Clase base para modelizar una propiedad de un estado.\n\n Args:\n description (str): Atributo privado con la descripción de la propiedad.\n weight (int, optional): El peso que tiene asociada la propiedad. Default: 0.\n \"\"\"\n self.description: str = description\n self.weight: int = weight\n\n def __str__(self) -> str:\n return self.description\n\n def __repr__(self) -> str:\n return self.__str__()\n\n def __eq__(self, other) -> bool:\n return self.description == other.description\n\n def __hash__(self) -> int:\n return hash(self.description)\n" }, { "alpha_fraction": 0.5772755146026611, "alphanum_fraction": 0.5791081190109253, "avg_line_length": 26.28333282470703, "blob_id": "cbf8bd002e6becf372000ae9186d4e1e0dd24b51", "content_id": "e79b0bdadfd1abf7d7cf1822312334fe317d7799", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1638, "license_type": "permissive", "max_line_length": 77, "num_lines": 60, "path": "/notebooks/strips/cdalvaro/properties/at_level.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_property import BaseProperty\nfrom ..element import Element\nfrom ..singleton import Singleton\n\n\nclass Level:\n\n def __init__(self, level: int, name: str):\n \"\"\"\n Clase base para modelizar un nivel.\n\n Args:\n level (int): Valor del nivel.\n name (str): Nombre del nivel.\n \"\"\"\n self.level: int = level\n self.name: str = name\n\n def __str__(self) -> str:\n return self.name\n\n def __eq__(self, other) -> bool:\n return self.level == other.level\n\n\nclass TopLevel(Level, metaclass=Singleton):\n\n def __init__(self):\n \"\"\" Clase singleton para representar el nivel superior. \"\"\"\n super().__init__(1, 'Superior')\n\n\nclass GroundLevel(Level, metaclass=Singleton):\n\n def __init__(self):\n \"\"\" Clase singleton para representar el nivel inferior. \"\"\"\n super().__init__(0, 'Inferior')\n\n\nclass AtLevel(BaseProperty):\n\n def __init__(self, element: Element, level: Level, position: int = None):\n \"\"\"\n Clase para modelizar la propiedad de posición vertical.\n\n Args:\n element (Element): Objeto que se encuentra en el nivel indicado.\n level (Level): Nivel en el que se encuentra el objeto.\n \"\"\"\n name = f\"{element}EnNivel{level}\"\n if level == TopLevel():\n if position is None:\n raise ValueError(\"Missing position at top level\")\n name += f\"EnPosicion{position}\"\n weight = 0\n\n super().__init__(name, weight)\n self.element: Element = element\n self.level: Level = level\n self.position: int = position\n" }, { "alpha_fraction": 0.8203883767127991, "alphanum_fraction": 0.8203883767127991, "avg_line_length": 40.20000076293945, "blob_id": "daaf1f86a9edb2e539bdca41d9e7f42b3fc99f09", "content_id": "a704569ea2c55dd46aff7e0c75c272059bf614fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "permissive", "max_line_length": 70, "num_lines": 5, "path": "/notebooks/strips/cdalvaro/__init__.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .actions import GetBanana, MoveHorizontally, ChangeLevel, PushBox\nfrom .heuristic import Heuristic\nfrom .element import Element, Banana, Box, Monkey\nfrom .state import State\nfrom .strips import Strips\n" }, { "alpha_fraction": 0.776203989982605, "alphanum_fraction": 0.7889518141746521, "avg_line_length": 50.65853500366211, "blob_id": "e5cff8e956d076c72f0d7f50e6e85418d7e5ae3a", "content_id": "65eaa61ff84157a2817a12f18971de6a45978f60", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2121, "license_type": "permissive", "max_line_length": 150, "num_lines": 41, "path": "/README.md", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "# Machine Learning Notebooks\n\n[![Python][python_badge]][python_link]\n[![Jupyter][jupyter_badge]][jupyter_link]\n[![Keras][keras_badge]][keras_link]\n[![License: MIT][mit_badge]][mit_license]\n\nThis repository contains a series of Jupyter Notebooks with different kind of machine learning topics.\n\n🚧 Currently all notebooks are written in Spanish but I plan to translate them to English in a near future.\n\n## General\n\n- [Naive Bayes Classifier](notebooks/naive-bayes-classifier/naive-bayes-classifier.ipynb)\n- [Clustering Techniques](notebooks/clustering-techniques/clustering-techniques.ipynb)\n- [Outlier Detection](notebooks/outlier-detection/outlier-detection.ipynb)\n- [Support Vector Machines (SVM) VS Neural Network](notebooks/support-vector-machine-vs-neural-network/support-vector-machine-vs-nerual-network.ipynb)\n- [Random Forest Classifier and Regressor](notebooks/random-forest/random-forest.ipynb)\n\n## Neural Networks\n\n- [Introduction to Neural Networks with TensowFlow and Keras](notebooks/introduction-to-neural-networks/introduction-to-neural-networks.ipynb)\n- [Practical Aspects of Neural Networks](notebooks/practical-aspects-of-neural-networks/practical-aspects-of-neural-networks.ipynb)\n- [Convolutional Neural Networks (CNN)](notebooks/convolutional-neural-networks/convolutional-neural-networks.ipynb)\n\n## Action models\n\n- [STRIPS](notebooks/strips/strips.ipynb)\n\n## Image Processing\n\n- [Mathematical Morphology](notebooks/mathematical-morphology/mathematical-morphology.ipynb)\n\n[python_badge]: https://img.shields.io/badge/Python-3.7-3776AB?style=flat-square&logo=Python\n[python_link]: https://docs.python.org/3.7/contents.html \"Python 3.7\"\n[jupyter_badge]: https://img.shields.io/badge/Jupyter-Notebook-F37626?style=flat-square&logo=Jupyter\n[jupyter_link]: https://jupyter.org \"Jupyter Notebook\"\n[keras_badge]: https://img.shields.io/badge/Keras-2.2-D00000?style=flat-square&logo=Keras&logoColor=D00000\n[keras_link]: https://keras.io/api/ \"Keras API\"\n[mit_badge]: https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square\n[mit_license]: https://opensource.org/licenses/MIT \"License: MIT\"\n" }, { "alpha_fraction": 0.5572519302368164, "alphanum_fraction": 0.5928753018379211, "avg_line_length": 31.75, "blob_id": "68a9d1a8acaf0e377a43f8a268a00962d99acc59", "content_id": "b2d7285a4142e1b4daa27cfb1dc0bda008f713a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "permissive", "max_line_length": 60, "num_lines": 12, "path": "/notebooks/strips/cdalvaro/singleton.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "class Singleton(type):\n \"\"\"\n Metaclase para implementar el patrón de diseño Singleton\n https://stackoverflow.com/a/6798042/3398062\n \"\"\"\n _instances = dict()\n\n def __call__(self, *args, **kwargs):\n if self not in self._instances:\n self._instances[self] = super(\n Singleton, self).__call__(*args, **kwargs)\n return self._instances[self]\n" }, { "alpha_fraction": 0.6414052248001099, "alphanum_fraction": 0.6420680284500122, "avg_line_length": 35.5, "blob_id": "481621a844a3fe0c80cbd6bdda6c057614146008", "content_id": "85eda68022ad6fc1447741d2da8598102b80a209", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4570, "license_type": "permissive", "max_line_length": 107, "num_lines": 124, "path": "/notebooks/strips/cdalvaro/actions/base_action.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from abc import abstractmethod\nfrom typing import List, TypeVar, Union\n\nfrom ..properties import Properties\nfrom ..state import State\n\nActions = TypeVar('Actions', bound=List['BaseAction'])\n\n\nclass BaseAction:\n verbose: bool = False\n\n def __init__(self, name: str, weight: int = 0):\n \"\"\"\n Clase base para modelizar una acción que aplica sobre un estado.\n\n Args:\n name (str): Nombre que describe la acción.\n weight (int, optional): El peso que tiene asociada la acción. Default: 0.\n \"\"\"\n self.name: str = name\n self.weight: int = weight\n self.precondition: Properties = set()\n self.add_list: Properties = set()\n self.remove_list: Properties = set()\n\n def can_apply(self, state: State, reverse: bool) -> bool:\n \"\"\"\n Método para comprobar si la acción se puede aplicar sobre el estado indicado.\n\n Comprueba que las propiedades de precondición de la acción se encuentren\n entre las propiedas del estado indicado.\n\n Puede aplicarse en el sentido inverso con `reverse=True` para comprobar\n si la acción puede revertirse desde el estado proporcionado.\n\n Args:\n state (State): Estado sobre el que se quiere comprobar la viabilidad de la acción.\n reverse (bool): Determina si la comprobación es en sentido de aplicar o revertir.\n\n Returns:\n bool: True si la acción se puede aplicar sobre el estado, o False en caso contario.\n \"\"\"\n if reverse:\n # Comprueba que alguna de las propiedades que añade la acción\n # esté entre las propiedades del estado a conseguir.\n return len(self.add_list.intersection(state.properties)) > 0\n\n # Todas las precondiciones de la acción deben estar contenidas\n # en las propiedades del estado sobre el que se aplicaría la acción.\n return self.precondition.intersection(state.properties) == self.precondition\n\n def apply(self, state: State, reverse: bool = False) -> Union[State, None]:\n \"\"\"\n Devuelve un nuevo estado a patir de aplicar sobre el estado indicado la acción.\n\n También puede usarse para generar el pseudo-estado a partir del cuál\n aplicando la acción se puede generar el estado indicado.\n\n Args:\n state (State): El estado sobre el que se aplica la acción.\n reverse (bool, optional): Revierte la acción aplicada sobre el estado dado.\n\n Returns:\n State: El estado resultante de aplicar la acción sobre el estado de partida.\n \"\"\"\n if not self.can_apply(state, reverse):\n return None\n\n if BaseAction.verbose and not reverse:\n print(f\"Aplicando: {self} sobre el estado {state}\")\n\n if reverse:\n # Añade las propiedades de precondición y las que serían eliminadas\n # en caso de aplicarse la acción en sentido normal y se eliminan\n # las propiedades que añadiría la acción.\n properties = state.properties.union(self.remove_list | self.precondition)\n properties = properties.difference(self.add_list)\n else:\n # Se añaden las propiedades de la lista de añadir\n # y se eliminan las propiedades de la lista de eliminar.\n properties = state.properties.union(self.add_list)\n properties = properties.difference(self.remove_list)\n\n return State(properties)\n\n @abstractmethod\n def _set_precondition(self):\n \"\"\"\n Método privado abstracto para establecer las propiedades de precondición.\n\n Cada clase hija de esta clase debe implementarlo.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _set_add_list(self):\n \"\"\"\n Método privado abstracto para establecer las propiedades que se añadirán trás ejecutar la acción.\n\n Cada clase hija de esta clase debe implementarlo.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _set_remove_list(self):\n \"\"\"\n Método privado abstracto para establecer las propiedades que se eliminarán trás ejecutar la acción.\n\n Cada clase hija de esta clase debe implementarlo.\n \"\"\"\n raise NotImplementedError\n\n def __str__(self) -> str:\n return self.name\n\n def __repr__(self) -> str:\n return self.__str__()\n\n def __eq__(self, other) -> bool:\n return self.name == other.name\n\n def __hash__(self) -> int:\n return hash(self.name)\n" }, { "alpha_fraction": 0.6253504157066345, "alphanum_fraction": 0.6263515949249268, "avg_line_length": 37.41538619995117, "blob_id": "f40d51264fef0fc54f375ac041995ea761e96026", "content_id": "ae2e818a1647246c010e97c69d1d11dd1967dc48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5021, "license_type": "permissive", "max_line_length": 117, "num_lines": 130, "path": "/notebooks/strips/cdalvaro/heuristic.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from typing import List\n\nfrom .actions import BaseAction, Actions, GetBanana, MoveHorizontally, ChangeLevel, PushBox\nfrom .element import Banana, Monkey\nfrom .properties import BaseProperty, Properties, AtPosition, TopLevel, GroundLevel\nfrom .state import State\n\n\nclass Heuristic:\n\n def __init__(self, initial_state: State):\n \"\"\"\n Clase con la heurística para determinar las posibles acciones\n a aplicar y el orden en el que hacerlo.\n\n Args:\n initial_state (State): Estado de partida del problema.\n \"\"\"\n self.initial_state = initial_state\n\n @staticmethod\n def possible_actions(state: State) -> Actions:\n \"\"\"\n Método para calcular las posibles acciones a partir de un estado.\n\n Args:\n state (State): El estado de partida.\n\n Returns:\n Actions: Las acciones que se pueden tomar desde el estado.\n \"\"\"\n actions = list()\n positions = [1, 2, 3]\n\n # Se generan todas las combinaciones posibles de movimiento del mono y de empujar la caja.\n for _from in positions:\n for _to in positions:\n if _from != _to:\n actions.append(MoveHorizontally(Monkey(), _from, _to))\n actions.append(PushBox(_from, _to))\n\n # Se generan todas las combinaciones posibles para que el mono suba y baje de la caja.\n levels = [TopLevel(), GroundLevel()]\n for _from in positions:\n for level in levels:\n actions.append(ChangeLevel(_from, level))\n\n # Añade la acción que lleva a conseguir el plátano en función de la ubicación de éste.\n for prop in state.properties:\n if type(prop) == AtPosition and prop.element == Banana():\n actions.append(GetBanana(prop.position))\n\n return actions\n\n def choose_actions(self, state: State, goal: State) -> Actions:\n \"\"\"\n Método para elegir en orden de preferencia las posibles acciones que\n llevan desde un estado de partida a un estado objetivo.\n\n Primero genera todas las posibles acciones de movimiento:\n - Moverse horizontalmente.\n - Moverse verticalmente.\n - Subir/Bajar de la caja.\n - La acción que permite conseguir el plátano en función de la posición de éste.\n\n Después se seleccionan aquellas acciones que en su lista de añadir\n tengan al menos una propiedad del estado objetivo.\n\n Args:\n state (State): El estado de partida.\n goal (State): El estado objetivo.\n\n Returns:\n Actions: la lista de acciones a realizar.\n \"\"\"\n actions = self.possible_actions(state)\n\n # Se descartan aquellas acciones que no puedan generar el estado objetivo\n actions = list(set(filter(lambda ac: len(ac.add_list.intersection(goal.properties)) > 0,\n actions)))\n\n # Se ordenan las acciones de mayor a menor peso.\n actions.sort(\n key=lambda ac: (\n # Peso de las propiedades de la acción.\n # Se calcula como la suma de los pesos de las propiedades del pseudo-estado previo a aplicar\n # la acción que se está evaluando y que intersectan con las propiedades del estado inicial.\n self._properties_weight(ac, goal),\n\n # Para resolver 'empates' entre propiedades se tiene en cuenta en segundo lugar el peso de la acción.\n ac.weight\n ), reverse=True)\n\n return actions\n\n @staticmethod\n def sort_properties(properties: Properties) -> List[BaseProperty]:\n \"\"\"\n Método estático para ordenar un conjunto de propiedades por sus pesos.\n\n Args:\n properties (Properties): El conjunto de propiedades a ordenar.\n\n Returns:\n List[BaseProperty]: Lista de propiedades ordenadas por pesos de menor a mayor.\n \"\"\"\n properties = list(properties)\n properties.sort(key=lambda prop: prop.weight)\n\n return properties\n\n def _properties_weight(self, action: BaseAction, goal: State) -> int:\n \"\"\"\n Método privado para calcular el peso total de las propiedades del pseudo-estado\n que aplicándole la acción indicada genera el estado proporcionado.\n\n Args:\n action (BaseAction): La acción que debe generar el estado `goal`\n goal (State): El estado que genera la acción al aplicarse sobre el pseudo-estado calculado.\n\n Returns:\n int: La suma de los pesos de las propiedades del pseudo-estado calculado\n que intersectan con las propiedades del estado inicial del problema.\n \"\"\"\n prev_state = action.apply(goal, reverse=True)\n if prev_state is None:\n return 0\n\n properties = prev_state.properties.intersection(self.initial_state.properties)\n return sum(list(map(lambda prop: prop.weight, properties)))\n" }, { "alpha_fraction": 0.5956931114196777, "alphanum_fraction": 0.5981157422065735, "avg_line_length": 40.27777862548828, "blob_id": "0b81ad82fc061aa1eb97bb66c3cbeb6ad4f5e5bc", "content_id": "e016adedca13b0f9c5cdb744ac56cae9e9e7c1d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3744, "license_type": "permissive", "max_line_length": 97, "num_lines": 90, "path": "/notebooks/strips/cdalvaro/strips.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from typing import Union\nfrom random import shuffle\n\nfrom .actions import BaseAction, Actions\nfrom .heuristic import Heuristic\nfrom .state import State\n\n\nclass Strips:\n # Límite de iteraciones en el que se tendrá en cuenta el orden\n # establecido por la heurística en la búsqueda de acciones.\n efficiency_limit: int = 10\n\n def __init__(self, initial_state: State, goal: State, heuristic: Heuristic):\n \"\"\"\n Clase que implementa la generación de planes de acción basada en STRIPS.\n\n Args:\n initial_state (State): Estado inicial del que parte el problema.\n goal (State): Estado objetivo que debe alcanzar la planificación.\n heuristic (Heuristic): Instancia de heurística para determinar las acciones del plan.\n \"\"\"\n self.initial_state: State = initial_state\n self.goal: State = goal\n self.heuristic: Heuristic = heuristic\n\n def get_plan(self) -> Union[Actions, bool]:\n \"\"\"\n Método que implementa la lógica para la búsqueda del plan.\n\n Returns:\n Union[Actions, bool]: Devuelve el conjunto de acciones ordenadas que\n componen el plan o False indicando que no ha sido posible elaborar un plan.\n \"\"\"\n plan: Actions = list()\n\n state = self.initial_state\n targets = list(self.goal.properties)\n\n iteration_counter = 0\n show_warning = True\n\n while len(targets) > 0:\n iteration_counter += 1\n\n # Se extrae el primer objetivo de la lista de objetivos.\n target = targets.pop(0)\n\n # Si el objetivo a explorar se trata de una acción:\n # - Se aplica la acción sobre el estado actual y si se puede generar un\n # nuevo estado válido se actualiza el estado actual y se añade la acción al plan.\n if issubclass(type(target), BaseAction):\n new_state = target.apply(state)\n if new_state is not None:\n state = new_state\n plan.append(target)\n\n # Si no es una acción, entonces es una propiedad.\n else:\n\n # Si el objetivo es una propiedad del estado actual:\n # - No se hace nada y se explora el siguiente objetivo de la lista.\n if target in state.properties:\n continue\n\n # Se generan las posibles acciones que pueden dar lugar desde el estado\n # actual un estado que tiene como propiedad el objetivo que se está estudiando.\n actions = self.heuristic.choose_actions(state, State({target}))\n if len(actions) == 0:\n # Si no hay acciones posibles, no se ha conseguido elaborar\n # la planificación y se devuelve False\n return False\n\n if iteration_counter > self.efficiency_limit:\n # Se anula el orden calculado por la heurística si el número\n # de iteraciones es alto para evitar bucles infinitos\n if show_warning:\n print(\"AVISO: La heurística no está encontrando soluciones eficientes\")\n show_warning = False\n shuffle(actions)\n\n # Se añade la primera acción devuelta por la heurística a la lista de objetivos.\n action = actions.pop(0)\n targets.insert(0, action)\n\n # Además de añadir la acción, se anteponen sus precondiciones\n # para buscar las acciones que generen estas precondiciones.\n targets = self.heuristic.sort_properties(action.precondition) + targets\n\n return plan\n" }, { "alpha_fraction": 0.8358974456787109, "alphanum_fraction": 0.8358974456787109, "avg_line_length": 38, "blob_id": "ac057e6007cf80a5c558a3b7c6343181d03aa6ab", "content_id": "66604ab0a40d31513ad4adc6fa6f3967a8939a52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 195, "license_type": "permissive", "max_line_length": 47, "num_lines": 5, "path": "/notebooks/strips/cdalvaro/actions/__init__.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_action import BaseAction, Actions\nfrom .get_banana import GetBanana\nfrom .move_horizontally import MoveHorizontally\nfrom .change_level import ChangeLevel\nfrom .push_box import PushBox\n" }, { "alpha_fraction": 0.6073059439659119, "alphanum_fraction": 0.6079582571983337, "avg_line_length": 31.617021560668945, "blob_id": "24a4ef967e5a95e5dd733dffb9467c3ac54d9979", "content_id": "945bea242ff39657998ef4c4d79c2abfdaa5dd95", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1546, "license_type": "permissive", "max_line_length": 75, "num_lines": 47, "path": "/notebooks/strips/cdalvaro/actions/get_banana.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_action import BaseAction\nfrom ..element import Banana, Box, Monkey\nfrom ..properties import AtLevel, TopLevel, AtPosition, Has\n\n\nclass GetBanana(BaseAction):\n\n def __init__(self, position: int):\n \"\"\"\n Clase con la acción de conseguir un plátano.\n\n Esta clase modeliza la acción de que el mono consiga el plátano.\n\n Args:\n position (int): Posición en la que el mono consigue el plátano.\n \"\"\"\n name = f\"{Monkey()} consigue {Banana()} en posición {position}\"\n weight = 4\n\n super().__init__(name, weight)\n self.position: int = position\n\n self._set_precondition()\n self._set_add_list()\n self._set_remove_list()\n\n def _set_precondition(self):\n \"\"\"\n * La caja se encuentra en la posición: 'position'\n * El mono se encuentra en la posición: 'position'\n * El mono se encuentra en el nivel superior\n * El plátano se encuentra en la posición: 'position'\n \"\"\"\n self.precondition.add(AtPosition(Box(), self.position))\n self.precondition.add(AtPosition(Monkey(), self.position))\n self.precondition.add(AtPosition(Banana(), self.position))\n self.precondition.add(AtLevel(Monkey(), TopLevel(), self.position))\n\n def _set_add_list(self):\n \"\"\"\n * El mono tendrá el plátano\n \"\"\"\n self.add_list.add(Has(Monkey(), Banana()))\n\n def _set_remove_list(self):\n \"\"\" (No se elimina ninguna propiedad) \"\"\"\n self.remove_list.clear()\n" }, { "alpha_fraction": 0.63271164894104, "alphanum_fraction": 0.6370157599449158, "avg_line_length": 33.849998474121094, "blob_id": "70bd1c344511dd3a80278640de10f853da0820cc", "content_id": "7e0a09a30af70721d9e667a527065fac11a05d47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 700, "license_type": "permissive", "max_line_length": 86, "num_lines": 20, "path": "/notebooks/strips/cdalvaro/properties/at_position.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_property import BaseProperty\nfrom ..element import Element, Banana, Monkey\n\n\nclass AtPosition(BaseProperty):\n\n def __init__(self, element: Element, position: int):\n \"\"\"\n Clase para modelizar la propiedad de posición hotizontal.\n\n Args:\n element (Element): Elemento que se encuentra en la posición indicada.\n position (int): Entero con la posición en la que se encuentra el elemento.\n \"\"\"\n name = f\"{element}EnPosicion{position}\"\n weight = 1 if element == Banana() else 2 if element == Monkey() else 3\n\n super().__init__(name, weight)\n self.element: Element = element\n self.position: int = position\n" }, { "alpha_fraction": 0.6220122575759888, "alphanum_fraction": 0.6225680708885193, "avg_line_length": 34.97999954223633, "blob_id": "eedf284efc477fa9099f76c8da75dc8c42e6617f", "content_id": "80495a3c17b031acdef9f973a8dbd29cc2872a8f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1807, "license_type": "permissive", "max_line_length": 87, "num_lines": 50, "path": "/notebooks/strips/cdalvaro/actions/move_horizontally.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_action import BaseAction\nfrom ..element import Element, Monkey\nfrom ..properties import AtLevel, GroundLevel, AtPosition\n\n\nclass MoveHorizontally(BaseAction):\n\n def __init__(self, element: Element, from_position: int, to_position: int):\n \"\"\"\n Clase con la acción de movimiento horizontal.\n\n Esta clase modeliza el movimiento de un elemento en el plano horizontal.\n\n Args:\n element (Element): Elemento que se va a mover.\n from_position (int): Posición desde la que se va a mover el elemento.\n to_position (int): Posición a la que se va a mover el elemento.\n \"\"\"\n name = f\"Mueve {element} de {from_position} a {to_position}\"\n weight = 2\n\n super().__init__(name, weight)\n self.element: Element = element\n self.from_position: int = from_position\n self.to_position: int = to_position\n\n self._set_precondition()\n self._set_add_list()\n self._set_remove_list()\n\n def _set_precondition(self):\n \"\"\"\n * El elemento se encuentra en la posición: 'from_position'\n * Si el elemento es el mono, el mono se encuentra en el nivel inferior\n \"\"\"\n self.precondition.add(AtPosition(self.element, self.from_position))\n if type(self.element) == Monkey:\n self.precondition.add(AtLevel(Monkey(), GroundLevel(), self.from_position))\n\n def _set_add_list(self):\n \"\"\"\n * El elemento se encontrará en la posición: 'to_position'\n \"\"\"\n self.add_list.add(AtPosition(self.element, self.to_position))\n\n def _set_remove_list(self):\n \"\"\"\n * El elemento dejará de estar en la posición: 'from_position'\n \"\"\"\n self.remove_list.add(AtPosition(self.element, self.from_position))\n" }, { "alpha_fraction": 0.5938864350318909, "alphanum_fraction": 0.5938864350318909, "avg_line_length": 24.44444465637207, "blob_id": "cb69fe275ad101fab07b676ebda135941fde4a1c", "content_id": "94f41042820f5f2921b126546695198b1c7baf84", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "permissive", "max_line_length": 96, "num_lines": 18, "path": "/notebooks/strips/cdalvaro/state.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .properties import Properties\n\n\nclass State:\n\n def __init__(self, properties: Properties = None):\n \"\"\"\n Clase para definir un estado.\n\n Args:\n properties (Properties, optional): Propiedades que definen el estado. Default: None.\n \"\"\"\n if properties is None:\n properties = set()\n self.properties: Properties = properties\n\n def __str__(self) -> str:\n return str(self.properties)\n" }, { "alpha_fraction": 0.5238663554191589, "alphanum_fraction": 0.5238663554191589, "avg_line_length": 17.217391967773438, "blob_id": "df9922eec36ce70ca8aedee0e57bc2e266c7b9b4", "content_id": "e9da3d01139d681dc3d642519829c39bd2f4f25b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 849, "license_type": "permissive", "max_line_length": 55, "num_lines": 46, "path": "/notebooks/strips/cdalvaro/element.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .singleton import Singleton\n\n\nclass Element:\n\n def __init__(self, name: str):\n \"\"\"\n Clase para representar un elemento genérico.\n\n Args:\n name (str): Nombre del objeto representado.\n \"\"\"\n self.name: str = name\n\n def __str__(self) -> str:\n return self.name\n\n def __eq__(self, other) -> bool:\n return self.name == other.name\n\n\nclass Monkey(Element, metaclass=Singleton):\n\n def __init__(self):\n \"\"\"\n Clase singleton mono.\n \"\"\"\n super().__init__(\"🐒\")\n\n\nclass Banana(Element, metaclass=Singleton):\n \"\"\"\n Clase singleton plátano.\n \"\"\"\n\n def __init__(self):\n super().__init__(\"🍌\")\n\n\nclass Box(Element, metaclass=Singleton):\n \"\"\"\n Clase singleton caja.\n \"\"\"\n\n def __init__(self):\n super().__init__(\"📦\")\n" }, { "alpha_fraction": 0.6025179624557495, "alphanum_fraction": 0.6043165326118469, "avg_line_length": 26.799999237060547, "blob_id": "24037068551dc1c545d09c927108149192255bdf", "content_id": "d9021be730433c5674ee7815247b48621f77a363", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "permissive", "max_line_length": 65, "num_lines": 20, "path": "/notebooks/strips/cdalvaro/properties/has.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_property import BaseProperty\nfrom ..element import Element\n\n\nclass Has(BaseProperty):\n\n def __init__(self, owner: Element, element: Element):\n \"\"\"\n Clase para modelizar la propiedad de tener plátano.\n\n Args:\n owner (Element): Elemento que posee al otro elemento.\n element (Element): Elemento posesión del owner.\n \"\"\"\n name = f\"{owner}Tiene{element}\"\n weight = 0\n\n super().__init__(name, weight)\n self.owner: Element = owner\n self.element: Element = element\n" }, { "alpha_fraction": 0.8117647171020508, "alphanum_fraction": 0.8117647171020508, "avg_line_length": 33, "blob_id": "d29b4d7643565c8292e8e3e14be64fbcc54827ea", "content_id": "83f0423a0b192b2d7f89ba5b316405ae17a195f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 170, "license_type": "permissive", "max_line_length": 59, "num_lines": 5, "path": "/notebooks/strips/cdalvaro/properties/__init__.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_property import BaseProperty, Properties\n\nfrom .at_position import AtPosition\nfrom .at_level import AtLevel, Level, TopLevel, GroundLevel\nfrom .has import Has\n" }, { "alpha_fraction": 0.8079602122306824, "alphanum_fraction": 0.8079602122306824, "avg_line_length": 42.69565200805664, "blob_id": "de5f991e9971104a20dea616e5faa0621e9f0551", "content_id": "6a6ed533d33de21057f1d9ea83e2fd33f406302e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1005, "license_type": "permissive", "max_line_length": 140, "num_lines": 23, "path": "/notebooks/README.md", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "# Notebooks\n\n## General\n\n- [Naive Bayes Classifier](naive-bayes-classifier/naive-bayes-classifier.ipynb)\n- [Clustering Techniques](clustering-techniques/clustering-techniques.ipynb)\n- [Outlier Detection](outlier-detection/outlier-detection.ipynb)\n- [Support Vector Machines (SVM) VS Neural Network](support-vector-machine-vs-neural-network/support-vector-machine-vs-nerual-network.ipynb)\n- [Random Forest Classifier and Regressor](random-forest/random-forest.ipynb)\n\n## Neural Networks\n\n- [Introduction to Neural Networks with TensowFlow and Keras](introduction-to-neural-networks/introduction-to-neural-networks.ipynb)\n- [Practical Aspects of Neural Networks](practical-aspects-of-neural-networks/practical-aspects-of-neural-networks.ipynb)\n- [Convolutional Neural Networks (CNN)](convolutional-neural-networks/convolutional-neural-networks.ipynb)\n\n## Action models\n\n- [STRIPS](strips/strips.ipynb)\n\n## Image Processing\n\n- [Mathematical Morphology](mathematical-morphology/mathematical-morphology.ipynb)\n" }, { "alpha_fraction": 0.6136363744735718, "alphanum_fraction": 0.6142045259475708, "avg_line_length": 34.20000076293945, "blob_id": "fdd5ae19cea3547821cad1f9027bc81b1cd953fe", "content_id": "fd3e4a9510b3b5ccd225a622c4d95f7c2f74c784", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1769, "license_type": "permissive", "max_line_length": 88, "num_lines": 50, "path": "/notebooks/strips/cdalvaro/actions/change_level.py", "repo_name": "cdalvaro/machine-learning-notebooks", "src_encoding": "UTF-8", "text": "from .base_action import BaseAction\nfrom ..element import Box, Monkey\nfrom ..properties import Level, TopLevel, GroundLevel, AtPosition, AtLevel\n\n\nclass ChangeLevel(BaseAction):\n\n def __init__(self, position: int, to_level: Level):\n \"\"\"\n Clase con la acción de cambiar de nivel.\n\n Esta clase modeliza el movimiento del mono para cambiar de nivel.\n\n Args:\n position (int): Posición horizontal en la que se encuentra el mono.\n to_level (Level): Nivel en el que finalizará el mono.\n \"\"\"\n name = f\"Cambia {Monkey()} al nivel {to_level} en posición {position}\"\n weight = 3\n\n super().__init__(name, weight)\n self.position: int = position\n self.to_level: Level = to_level\n self.from_level: Level = GroundLevel() if to_level == TopLevel() else TopLevel()\n\n self._set_precondition()\n self._set_add_list()\n self._set_remove_list()\n\n def _set_precondition(self):\n \"\"\"\n * La caja se encuentra en la posición 'position'\n * El mono se encuentra en la posición 'position'\n * El mono está en el nivel opuesto al que se va a mover\n \"\"\"\n self.precondition.add(AtPosition(Box(), self.position))\n self.precondition.add(AtPosition(Monkey(), self.position))\n self.precondition.add(AtLevel(Monkey(), self.from_level, self.position))\n\n def _set_add_list(self):\n \"\"\"\n * El mono estará en el nivel objetivo\n \"\"\"\n self.add_list.add(AtLevel(Monkey(), self.to_level, self.position))\n\n def _set_remove_list(self):\n \"\"\"\n * El mono dejará de estar en el nivel de origen\n \"\"\"\n self.remove_list.add(AtLevel(Monkey(), self.from_level, self.position))\n" } ]
19
codelectron/virtualSPI
https://github.com/codelectron/virtualSPI
0c7ecb5ac4f8dcdf9dc159ed7b1dcaf899a2ecc5
d74163516ac531a3773cc4817e527568bb92d5cf
2c27f5dd7927633e2b62e96379637bf5597f4b42
refs/heads/master
2021-01-01T15:52:38.864200
2017-07-19T13:41:51
2017-07-19T13:41:51
97,720,438
4
0
null
null
null
null
null
[ { "alpha_fraction": 0.5554311275482178, "alphanum_fraction": 0.5739081501960754, "avg_line_length": 27.259492874145508, "blob_id": "d9912af97caee42898eecf05e9ffe44b30ae9537", "content_id": "3ae82d26d25be9a21306f992a8d8fc023775d30f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8930, "license_type": "no_license", "max_line_length": 78, "num_lines": 316, "path": "/virtual_spi.py", "repo_name": "codelectron/virtualSPI", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom __future__ import print_function, absolute_import, division\n\nimport logging\n\nfrom collections import defaultdict\nfrom errno import ENOENT\nfrom stat import S_IFDIR, S_IFLNK, S_IFREG\nfrom sys import argv, exit\nfrom time import time\n\nfrom fuse import FUSE, FuseOSError, Operations, LoggingMixIn, fuse_get_context\nimport ctypes\n\n_IOC_NRBITS =\t8\n_IOC_TYPEBITS =\t8\n\n_IOC_SIZEBITS =\t14\n_IOC_DIRBITS =\t2\n\n_IOC_NRMASK = (1 << _IOC_NRBITS) - 1\n_IOC_TYPEMASK = (1 << _IOC_TYPEBITS) - 1\n_IOC_SIZEMASK = (1 << _IOC_SIZEBITS) - 1\n_IOC_DIRMASK = (1 << _IOC_DIRBITS) - 1\n\n_IOC_NRSHIFT =\t 0\n_IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS\n_IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS\n_IOC_DIRSHIFT =\t _IOC_SIZESHIFT + _IOC_SIZEBITS\n\n# ...and for the drivers/sound files...\n# Direction bits\n\n_IOC_NONE = 0\n_IOC_WRITE = 1\n_IOC_READ = 2\n\nIOC_IN = _IOC_WRITE << _IOC_DIRSHIFT\nIOC_OUT = _IOC_READ << _IOC_DIRSHIFT\nIOC_INOUT = (_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT\nIOCSIZE_MASK = _IOC_SIZEMASK << _IOC_SIZESHIFT\nIOCSIZE_SHIFT = _IOC_SIZESHIFT\n\n\n\ndef _IOC(dir, type, nr, size):\n return (dir << _IOC_DIRSHIFT) | \\\n (type << _IOC_TYPESHIFT) | \\\n (nr << _IOC_NRSHIFT) | \\\n (size << _IOC_SIZESHIFT)\n\ndef _IOC_TYPECHECK(t):\n return ctypes.sizeof(t)\n\n\n# used to create ioctl numbers\n\ndef _IO(type, nr):\n return _IOC(_IOC_NONE, type, nr, 0)\n\ndef _IOR(type, nr, size):\n return _IOC(_IOC_READ, type, nr, _IOC_TYPECHECK(size))\n\ndef _IOW(type, nr, size):\n return _IOC(_IOC_WRITE, type, nr, _IOC_TYPECHECK(size))\n\ndef _IOWR(type,nr,size):\n return _IOC(_IOC_READ|_IOC_WRITE, type, nr, _IOC_TYPECHECK(size))\n\ndef _IOR_BAD(type,nr,size):\n return _IOC(_IOC_READ, type, nr, sizeof(size))\n\ndef _IOW_BAD(type,nr,size):\n return _IOC(_IOC_WRITE,type,nr, sizeof(size))\n\ndef _IOWR_BAD(type,nr,size):\n return _IOC(_IOC_READ|_IOC_WRITE, type, nr, sizeof(size))\n\n\n####### SPI Definitions ####### \n\n\n\nSPI_CPHA = 0x01\nSPI_CPOL = 0x02\n\nSPI_MODE_0 = 0\nSPI_MODE_1 = SPI_CPHA\nSPI_MODE_2 = SPI_CPOL\nSPI_MODE_3 = SPI_CPOL | SPI_CPHA\n\nSPI_CS_HIGH = 0x04\nSPI_LSB_FIRST = 0x08\nSPI_3WIRE = 0x10\nSPI_LOOP = 0x20\nSPI_NO_CS = 0x40\nSPI_READY = 0x80\n\n\n# IOCTL commands */\n\nSPI_IOC_MAGIC = 107 # ord('k')\n\n\nclass spi_ioc_transfer(ctypes.Structure):\n \"\"\"<linux/spi/spidev.h> struct spi_ioc_transfer\"\"\"\n\n _fields_ = [\n (\"tx_buf\", ctypes.c_uint64),\n (\"rx_buf\", ctypes.c_uint64),\n (\"len\", ctypes.c_uint32),\n (\"speed_hz\", ctypes.c_uint32),\n (\"delay_usecs\", ctypes.c_uint16),\n (\"bits_per_word\", ctypes.c_uint8),\n (\"cs_change\", ctypes.c_uint8),\n (\"pad\", ctypes.c_uint32)]\n\n __slots__ = [name for name, type in _fields_]\n\n\n# not all platforms use <asm-generic/ioctl.h> or _IOC_TYPECHECK() ...\ndef SPI_MSGSIZE(N):\n if ((N)*(ctypes.sizeof(spi_ioc_transfer))) < (1 << _IOC_SIZEBITS):\n return (N)*(ctypes.sizeof(spi_ioc_transfer))\n else:\n return 0\n\ndef SPI_IOC_MESSAGE(N):\n return _IOW(SPI_IOC_MAGIC, 0, ctypes.c_char*SPI_MSGSIZE(N))\n\n\n# Read / Write of SPI mode (SPI_MODE_0..SPI_MODE_3)\nSPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, ctypes.c_uint8)\nSPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, ctypes.c_uint8)\n\n# Read / Write SPI bit justification\nSPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, ctypes.c_uint8)\nSPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, ctypes.c_uint8)\n\n# Read / Write SPI device word length (1..N)\nSPI_IOC_RD_BITS_PER_WORD = _IOR(SPI_IOC_MAGIC, 3, ctypes.c_uint8)\nSPI_IOC_WR_BITS_PER_WORD = _IOW(SPI_IOC_MAGIC, 3, ctypes.c_uint8)\n\n# Read / Write SPI device default max speed hz\nSPI_IOC_RD_MAX_SPEED_HZ = _IOR(SPI_IOC_MAGIC, 4, ctypes.c_uint32)\nSPI_IOC_WR_MAX_SPEED_HZ = _IOW(SPI_IOC_MAGIC, 4, ctypes.c_uint32)\n\n\nRES1=SPI_IOC_MESSAGE(1)\nRES2=SPI_IOC_MESSAGE(2)\nRES3=SPI_IOC_MESSAGE(3)\nRES4=SPI_IOC_MESSAGE(4)\nRES5=SPI_IOC_MESSAGE(5)\nRES6=SPI_IOC_MESSAGE(6)\n\nif not hasattr(__builtins__, 'bytes'):\n bytes = str\n\nclass VirtualSPI(LoggingMixIn, Operations):\n 'Example memory filesystem. Supports only one level of files.'\n\n def __init__(self):\n self.files = {}\n self.data = defaultdict(bytes)\n self.fd = 0\n now = time()\n self.files['/'] = dict(st_mode=(S_IFDIR | 0o755), st_ctime=now,\n st_mtime=now, st_atime=now, st_nlink=2)\n\n def chmod(self, path, mode):\n self.files[path]['st_mode'] &= 0o770000\n self.files[path]['st_mode'] |= mode\n return 0\n\n def chown(self, path, uid, gid):\n self.files[path]['st_uid'] = uid\n self.files[path]['st_gid'] = gid\n\n def create(self, path, mode):\n self.files[path] = dict(st_mode=(S_IFREG | mode), st_nlink=1,\n st_size=0, st_ctime=time(), st_mtime=time(),\n st_atime=time())\n\n self.fd += 1\n return self.fd\n\n def getattr(self, path, fh=None):\n# if path not in self.files:\n# raise FuseOSError(ENOENT)\n vspi = fuse_get_context()\n if path == '/':\n st = dict(st_mode=(S_IFDIR | 0o755), st_nlink=2)\n elif path == '/vspidev':\n #size = len('%s\\n' % vspi)\n size = 40\n st = dict(st_mode=(S_IFREG | 0o444), st_size=size)\n else:\n raise FuseOSError(ENOENT)\n st['st_ctime'] = st['st_mtime'] = st['st_atime'] = time()\n return st\n #return self.files[path]\n\n def getxattr(self, path, name, position=0):\n attrs = self.files[path].get('attrs', {})\n\n try:\n return attrs[name]\n except KeyError:\n return '' # Should return ENOATTR\n\n def listxattr(self, path):\n attrs = self.files[path].get('attrs', {})\n return attrs.keys()\n\n def mkdir(self, path, mode):\n self.files[path] = dict(st_mode=(S_IFDIR | mode), st_nlink=2,\n st_size=0, st_ctime=time(), st_mtime=time(),\n st_atime=time())\n\n self.files['/']['st_nlink'] += 1\n\n def open(self, path, flags):\n self.fd += 1\n return self.fd\n\n def read(self, path, size, offset, fh):\n return \"Its an SPI device, dont read, use ioctl\\n\".encode('utf-8')\n# return self.data[path][offset:offset + size]\n\n def readdir(self, path, fh):\n #return ['.', '..'] + [x[1:] for x in self.files if x != '/']\n\treturn ['.', '..', 'vspidev']\n\n def readlink(self, path):\n return self.data[path]\n\n def removexattr(self, path, name):\n attrs = self.files[path].get('attrs', {})\n\n try:\n del attrs[name]\n except KeyError:\n pass # Should return ENOATTR\n\n def rename(self, old, new):\n self.files[new] = self.files.pop(old)\n\n def rmdir(self, path):\n self.files.pop(path)\n self.files['/']['st_nlink'] -= 1\n\n def setxattr(self, path, name, value, options, position=0):\n # Ignore options\n attrs = self.files[path].setdefault('attrs', {})\n attrs[name] = value\n\n def statfs(self, path):\n return dict(f_bsize=512, f_blocks=4096, f_bavail=2048)\n\n def symlink(self, target, source):\n self.files[target] = dict(st_mode=(S_IFLNK | 0o777), st_nlink=1,\n st_size=len(source))\n\n self.data[target] = source\n\n def truncate(self, path, length, fh=None):\n self.data[path] = self.data[path][:length]\n self.files[path]['st_size'] = length\n\n def unlink(self, path):\n self.files.pop(path)\n\n def utimens(self, path, times=None):\n now = time()\n atime, mtime = times if times else (now, now)\n self.files[path]['st_atime'] = atime\n self.files[path]['st_mtime'] = mtime\n\n\n\n def write(self, path, data, offset, fh):\n self.data[path] = self.data[path][:offset] + data\n self.files[path]['st_size'] = len(self.data[path])\n return len(data)\n\n def ioctl(self, path, cmd, arg, fh, flags, data):\n print(cmd)\n if (cmd == SPI_IOC_WR_MODE):\n print(\"SPI_IOC_WR_MODE\")\n if (cmd == SPI_IOC_RD_MODE):\n print(\"SPI_IOC_RD_MODE\")\n if (cmd == SPI_IOC_WR_BITS_PER_WORD):\n print(\"SPI_IOC_WR_BITS_PER_WORD\")\n if (cmd == SPI_IOC_RD_BITS_PER_WORD):\n print(\"SPI_IOC_RD_BITS_PER_WORD\")\n if (cmd == SPI_IOC_WR_MAX_SPEED_HZ):\n print(\"SPI_IOC_WR_MAX_SPEED_HZ\")\n if (cmd == SPI_IOC_RD_MAX_SPEED_HZ):\n print(\"SPI_IOC_RD_MAX_SPEED_HZ\")\n if (cmd == RES1):\n print(\"1 SPI_IOC_MESSAGE\")\n return 1\n if (cmd == RES2):\n print(\"2 SPI_IOC_MESSAGE\")\n return 2\n print(\"IOCTL\")\n return 0 \n\n\nif __name__ == '__main__':\n if len(argv) != 2:\n print('usage: %s <mountpoint>' % argv[0])\n exit(1)\n\n logging.basicConfig(level=logging.DEBUG)\n fuse = FUSE(VirtualSPI(), argv[1], foreground=True)\n" } ]
1
shilpapatkar27/facedetection
https://github.com/shilpapatkar27/facedetection
d40ab60c687a98f61b47d8a1980ec01813e41d18
33d5784b721b92ab3d4b913e8f265d8722dd248c
c7f93a514b39e5b8b708bcb0127187718fd2d81f
refs/heads/main
2023-06-12T18:43:53.933026
2021-07-04T14:22:44
2021-07-04T14:22:44
381,084,449
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6775362491607666, "alphanum_fraction": 0.717391312122345, "avg_line_length": 25.285715103149414, "blob_id": "3f2aee7938e8ce109f436a831754e1c1273eb504", "content_id": "b256ffa0d26bb0ae0a4e74322e54ed87a62508a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 552, "license_type": "no_license", "max_line_length": 75, "num_lines": 21, "path": "/script1.py", "repo_name": "shilpapatkar27/facedetection", "src_encoding": "UTF-8", "text": "import cv2\n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\ncap = cv2.VideoCapture(\"elon.jpg\")\n\nres, img = cap.read()\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# detect the faces od different size in the input image\nfaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\nfor (x,y,w,h) in faces:\n #to draw rectangle in face\n cv2.rectangle(img, (x,y), (x+w, y+h),(255, 255, 0),2)\n\ncv2.imshow('img',img)\nk = cv2.waitKey(0)\n#Close the window\ncap.release()\n#Deallocate any associated memory usage\ncv2.destroyAllWindows()\n" } ]
1
NamanG-upta/GDB
https://github.com/NamanG-upta/GDB
4b694cdc3b21ea7f6afdae5517fbed1cf58037d3
eb3ba0f833d04875540364ce1c4785264c37c831
42d1ee979f2bdd1d8533148feeab71d90ec2c97a
refs/heads/main
2023-05-15T20:18:03.397041
2021-06-12T19:50:41
2021-06-12T19:50:41
343,206,960
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5867074131965637, "alphanum_fraction": 0.5954927206039429, "avg_line_length": 33.228759765625, "blob_id": "18638eaeb619a4717299f51b32141e19684c4218", "content_id": "88040f7a16396491818a08608ed5ab1b0be12cf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5236, "license_type": "no_license", "max_line_length": 285, "num_lines": 153, "path": "/board/views.py", "repo_name": "NamanG-upta/GDB", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom django.contrib import auth\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom .models import *\nimport os\n\n\n@login_required(login_url=\"login\")\ndef updateTask(request, pk,id):\n print(\"inside here\")\n # user = User.objects.get(id=request.user.id)\n task = Task.objects.get(id=pk,user__id=id)\n\n if request.method == 'POST':\n task = Task.objects.get(id=pk,user__id=id)\n task.complete = True\n task.save()\n startbtn(request,pk,id)\n return redirect(home)\n\n return render(request, 'update_task.html', {'task':task} )\n\n\n@login_required(login_url=\"login\")\ndef startbtn(request,pk,id):\n print(\"idsssssssss = \", pk, id)\n user = User.objects.get(id=id)\n task = Task.objects.get(id=pk,user=user)\n task.working = True\n task.save()\n\n os.system('cmd /k \"cd c:\\ST\\STM32CubeIDE_1.6.1\\STM32CubeIDE\\plugins\\com.st.stm32cube.ide.mcu.externaltools.stlink-gdb-server.win32_1.6.0.202101291314&& cd tools&& cd bin&&ST-LINK_gdbserver.exe -d -p 61235 -v -cp \"C:\\ST\\STM32CubeIDE_1.6.1\\STM32CubeIDE\\plugins\\myprog\\/tools\\/bin\"\"')\n\n return redirect(home)\n\n\n@login_required(login_url=\"login\")\ndef stopbtn(request, pk,id):\n user = User.objects.get(id=id)\n task = Task.objects.get(id=pk,user=user)\n task.working = False\n task.save()\n os.system('cmd /k \"exit()\"')\n return redirect(home)\n\n\n@login_required(login_url=\"login\")\ndef home(request):\n user = User.objects.get(id=request.user.id)\n\n if len(Task.objects.filter(user=user)) == 0 :\n admin_usr = User.objects.filter(is_superuser=True).first()\n tasks = Task.objects.filter(user=admin_usr)\n\n for curr_task in tasks:\n tsk = Task(\n title=curr_task.title,\n desc=curr_task.desc,\n complete=False,\n working=False,\n user=user,\n board_id=curr_task.board_id,\n ip_address=curr_task.ip_address\n )\n tsk.save()\n\n objs = Task.objects.filter(user=user)\n all_objs = Task.objects.all()\n print('2222', all_objs)\n if user.is_superuser == True:\n context = {'tasks':all_objs,'user':user}\n return render(request, \"index.html\", context)\n else:\n context = {'tasks':objs,'user':user}\n return render(request, \"index.html\", context)\n \n objs = Task.objects.filter(user=user)\n context = {'tasks':objs,'user':user}\n all_objs = Task.objects.all()\n print('outsideeeee = ', all_objs)\n if user.is_superuser == True:\n context = {'tasks':all_objs,'user':user}\n return render(request, \"index.html\", context)\n else:\n return render(request, \"index.html\", context)\n\n\n@login_required(login_url=\"login\")\ndef go(request):\n return render(request,\"help.html\")\n\n\ndef signup(request):\n if request.method == \"POST\":\n # fetching the name of the user\n name = request.POST[\"username\"]\n institute = request.POST[\"institute\"]\n contact = request.POST[\"contact\"]\n email = request.POST[\"email\"]\n name = request.POST['Name']\n if request.POST[\"password\"] == request.POST[\"passwordagain\"]:\n # if passwords matched check if user exist previously or not\n try:\n # user already exist\n user = User.objects.get(username=name)\n return render(\n request,\n \"register.html\",\n {\"error\": \"Username has Already been Taken\", \"user\": user},\n )\n except User.DoesNotExist:\n # create a user and redirect to home\n user = User.objects.create_user(\n username=name, password=request.POST[\"password\"],email=email,first_name=name\n )\n user.save()\n newuser = NewUser(institute_name=institute,contact=contact,user=user)\n newuser.save()\n return redirect(home)\n else:\n return render(\n request, \"register.html\", {\"error\": \"Passwords Don't Matched\"}\n )\n return render(request, \"register.html\")\n\n\ndef login(request):\n if request.method == \"POST\":\n name = request.POST[\"username\"]\n pas = request.POST[\"password\"]\n user = authenticate(request,username=name,password=pas)\n\n # checking if user exist and credentials are correct\n if user is not None:\n if user.is_staff:\n auth.login(request, user)\n return redirect(home)\n # return render(request, \"index.html\")\n else:\n return render(request, \"home.html\", {\"error\": \"Your request is under approval\"})\n else:\n return render(request, \"home.html\", {\"error\": \"Invalid Credentials\"})\n else:\n return render(request, \"home.html\")\n\n\ndef logout(request):\n auth.logout(request)\n return redirect(home)" }, { "alpha_fraction": 0.640625, "alphanum_fraction": 0.640625, "avg_line_length": 38.46154022216797, "blob_id": "c924a25d0ca2a37ac2191ea28f1f82062f4fee9a", "content_id": "9d6409649355226e4fc2c726ed6e42fdbf4965e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 77, "num_lines": 13, "path": "/board/urls.py", "repo_name": "NamanG-upta/GDB", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name=\"home\"),\n path(\"signup\", views.signup, name=\"signup\"),\n path(\"login\", views.login, name=\"login\"),\n path(\"logout\", views.logout, name=\"logout\"),\n path(\"help\", views.go, name=\"help\"),\n\tpath('update_task/<str:pk>/<str:id>', views.updateTask, name=\"update_task\"),\n path('startbtn/<str:pk>/<str:id>', views.startbtn, name=\"startbtn\"),\n path('stopbtn/<str:pk>/<str:id>', views.stopbtn, name=\"stopbtn\"),\n]" }, { "alpha_fraction": 0.7561174631118774, "alphanum_fraction": 0.7724306583404541, "avg_line_length": 33.08333206176758, "blob_id": "979f511c47a883ca4e019d0507bfccdcc6a4284e", "content_id": "491b20c60e0beba61e9c25107538fb237efb07e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1226, "license_type": "no_license", "max_line_length": 86, "num_lines": 36, "path": "/board/models.py", "repo_name": "NamanG-upta/GDB", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom django.contrib.auth.models import AbstractUser, PermissionsMixin, BaseUserManager\nfrom django.conf import settings\n\n\nclass NewUser(models.Model):\n\tuser = models.OneToOneField(User, on_delete=models.CASCADE)\n\tcontact = models.CharField(max_length=20, blank=True)\n\tinstitute_name = models.CharField(max_length=200, blank=True)\n\n\tdef __str__(self):\n\t\treturn self.user.first_name\n\nclass helptext(models.Model):\n\tuser = models.ForeignKey(User, on_delete=models.CASCADE)\n\ttext = models.TextField(max_length=500,blank=True, null=True)\n\n\tdef __str__(self):\n\t\treturn self.text\n\n\nclass Task(models.Model):\n\ttitle = models.CharField(max_length=200)\n\tdesc = models.CharField(max_length=500)\n\tcomplete = models.BooleanField(default=False)\n\tworking = models.BooleanField(default=False)\n\tuser = models.ForeignKey(User, on_delete=models.CASCADE)\n\tboard_id = models.CharField(max_length=200, blank=True, null=True)\n\tip_address = models.CharField(max_length=200,blank=True, null=True) \n\tcreated = models.DateTimeField(auto_now_add=True)\n\n\tdef __str__(self):\n\t\treturn self.title" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.5802139043807983, "avg_line_length": 19.77777862548828, "blob_id": "cd3667e7fb8ba3456d5769700a0e58475ab9042f", "content_id": "b43da9c1764542fa338489a34db7f3c5c9a6035e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/board/migrations/0003_task_working.py", "repo_name": "NamanG-upta/GDB", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-06-06 14:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('board', '0002_helptext'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='task',\n name='working',\n field=models.BooleanField(default=False),\n ),\n ]\n" }, { "alpha_fraction": 0.4466403126716614, "alphanum_fraction": 0.6837944388389587, "avg_line_length": 13.882352828979492, "blob_id": "091ddfa48e28b48d9961b49cbf2b7e8e81eb7766", "content_id": "94c6bb8273726fc674f26f41631f6ba358b56a17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 253, "license_type": "no_license", "max_line_length": 18, "num_lines": 17, "path": "/requirements.txt", "repo_name": "NamanG-upta/GDB", "src_encoding": "UTF-8", "text": "asgiref==3.3.1\nblessings==1.7\nbpython==0.21\ncertifi==2020.12.5\nchardet==4.0.0\ncurtsies==0.3.5\ncwcwidth==0.1.4\nDjango==3.1.7\ngreenlet==1.0.0\nidna==2.10\nPygments==2.8.0\npytz==2021.1\npyxdg==0.27\nrequests==2.25.1\nsix==1.15.0\nsqlparse==0.4.1\nurllib3==1.26.3\n" }, { "alpha_fraction": 0.6579185724258423, "alphanum_fraction": 0.6579185724258423, "avg_line_length": 24.136363983154297, "blob_id": "4d7b6f9ce5be5ac7e28d97e0ab6c73bb3543079a", "content_id": "cd66117b2808da910dbbe2041b05f475d140774c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1105, "license_type": "no_license", "max_line_length": 55, "num_lines": 44, "path": "/board/admin.py", "repo_name": "NamanG-upta/GDB", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Task,NewUser,helptext\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.forms import TextInput, Textarea\n\nclass NewUseradmin(admin.ModelAdmin):\n model = NewUser\n list_filter = ('user', 'institute_name', 'contact')\n list_display = ('user','institute_name', 'contact')\n\nadmin.site.register(NewUser,NewUseradmin)\n\n\nclass TaskAdmin(admin.ModelAdmin):\n list_display = (\n \"title\",\n \"desc\",\n \"complete\",\n \"user\",\n \"board_id\",\n \"ip_address\",\n )\n\n list_filter = (\n \"user\",\n \"board_id\",\n \"complete\",\n )\n\n def has_view_permission(self, request, obj=None):\n return request.user.is_staff\n\n def has_delete_permission(self, request, obj=None):\n return request.user.is_superuser\n\n def has_change_permission(self, request, obj=None):\n return request.user.is_superuser\n\n def has_add_permission(self, request, obj=None):\n return request.user.is_superuser\n\n\nadmin.site.register(Task, TaskAdmin)" }, { "alpha_fraction": 0.5310173630714417, "alphanum_fraction": 0.5880893468856812, "avg_line_length": 21.38888931274414, "blob_id": "3d5de3c4f9b52c260bcc8310111dc41b0758474e", "content_id": "3a88342d95a02aa6615ac453bc42ee9502ab767d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 74, "num_lines": 18, "path": "/board/migrations/0004_auto_20210612_1850.py", "repo_name": "NamanG-upta/GDB", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.10 on 2021-06-12 18:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('board', '0003_task_working'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='task',\n name='board_id',\n field=models.CharField(blank=True, max_length=200, null=True),\n ),\n ]\n" } ]
7
Gavin-Lijy/signac-paper
https://github.com/Gavin-Lijy/signac-paper
defe7517eed062b35d3cb7ba2776d4d8ece2e48f
cbe23a293aa0846e84023ec2e5487c9dfa59e0a2
bc335fa35b91271f23887a4802f253a30cfb10c7
refs/heads/master
2023-01-09T05:11:40.181022
2020-11-11T20:05:41
2020-11-11T20:05:41
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6193951964378357, "alphanum_fraction": 0.6757038831710815, "avg_line_length": 29, "blob_id": "ddb873c0cd97daf4a8defb819904679b7c1799d4", "content_id": "fcc456225cfccd6bdd2c58ad3dfda45064673264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 959, "license_type": "no_license", "max_line_length": 79, "num_lines": 32, "path": "/code/biccn_downsampling/downsample_biccn.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "library(Signac)\nlibrary(Rsamtools)\nset.seed(1234)\n\n# load the full BICCN dataset\nbiccn <- readRDS(\"objects/biccn.rds\")\n\n# randomly sample different numbers of cells\ndownsamples <- c(50000, 100000, 200000, 300000, 400000, 500000, 600000, 700000)\n\ncells.select <- sapply(X = downsamples, FUN = function(x) {\n sample(x = colnames(x = biccn), replace = FALSE, size = x)\n})\n\n# create downsampled fragment files\nfor (i in seq_along(along.with = downsamples)) {\n ds <- format(x = downsamples[[i]], scientific = FALSE)\n outfile <- paste0(\"data/biccn/downsampling/\", ds, \".bed.gz\")\n frag.dest <- paste0(\"data/biccn/downsampling/\", ds, \".rds\")\n FilterCells(\n fragments = \"data/biccn/fragments.sort.bed.gz\",\n cells = cells.select[[i]],\n outfile = outfile,\n verbose = TRUE\n )\n frags <- CreateFragmentObject(\n path = outfile,\n cells = cells.select[[i]],\n validate.fragments = FALSE\n )\n saveRDS(object = frags, file = frag.dest, version = 2)\n}" }, { "alpha_fraction": 0.7567567825317383, "alphanum_fraction": 0.7783783674240112, "avg_line_length": 27.538461685180664, "blob_id": "a16bc2f9622ace6842b6e2275e992f555bee7873", "content_id": "d385182b381b20aaaafd85adadbe074464977e27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 370, "license_type": "no_license", "max_line_length": 66, "num_lines": 13, "path": "/code/biccn_downsampling/get_annotations.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "library(Signac)\nlibrary(EnsDb.Mmusculus.v79)\nlibrary(GenomeInfoDb)\n\n# extract gene annotations from EnsDb\nannotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Mmusculus.v79)\n\n# change to UCSC style since the data was mapped to hg19\nseqlevelsStyle(annotations) <- 'UCSC'\ngenome(annotations) <- \"mm10\"\n\n# save\nsaveRDS(object = annotations, file = \"data/biccn/annotations.rds\")" }, { "alpha_fraction": 0.5872042179107666, "alphanum_fraction": 0.6178790330886841, "avg_line_length": 30.69444465637207, "blob_id": "3dae4c8790ef6f5673287053841a2551d158cdc4", "content_id": "980248d0c6202f8d4429b20fa508213c6cba9d99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 89, "num_lines": 36, "path": "/code/figure3.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(patchwork)\n\ndimplot_list <- readRDS(\"figures/dimplot_downsample_pbmc.rds\")\nknn_list <- readRDS(\"figures/knn_purity_pbmc.rds\")\n\nknn_df <- data.frame()\nfor (i in seq_along(knn_list)) {\n ds_level <- as.factor(unlist(strsplit(names(knn_list)[i], \"_\"))[1])\n method <- unlist(strsplit(names(knn_list)[i], \"_\"))[2]\n method <- ifelse(test = method == 1, \"log(TF*IDF)\", \"TF*log(IDF)\")\n frc <- knn_list[[i]]\n dft <- data.frame(\"downsample\" = ds_level, \"method\" = method, \"knn\" = frc) \n knn_df <- rbind(knn_df, dft)\n}\n\nknn_box <- ggplot(\n data = knn_df,\n mapping = aes(x = as.factor(downsample), y = knn, fill = method)) +\n geom_boxplot(outlier.shape = NA) +\n theme_classic() + \n scale_x_discrete(limits = levels(knn_df$downsample)) +\n ylab(\"KNN purity\") +\n xlab(\"Fraction counts retained\")\n\nplots_use <- c(\"1_1\", \"0.6_1\", \"0.2_1\", \"1_2\", \"0.6_2\", \"0.2_2\")\n\np <- wrap_plots(\n dimplot_list[plots_use],\n nrow = 2,\n guides = \"collect\"\n) & xlab(\"UMAP1\") & ylab(\"UMAP2\")\n\nfig2 <- p / knn_box + plot_layout(heights = c(3, 1))\n\nggsave(filename = \"figures/figure3.png\", plot = fig2, height = 10, width = 15, dpi = 300)\n" }, { "alpha_fraction": 0.5490828156471252, "alphanum_fraction": 0.5612295269966125, "avg_line_length": 20.457447052001953, "blob_id": "f2e362973fb6bba7fe877e55417fa5c2409a2e50", "content_id": "d745332325265b0935423dca397d86e834e3f329", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4034, "license_type": "no_license", "max_line_length": 97, "num_lines": 188, "path": "/Snakefile", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "datasets = [\"pbmc\", \"biccn\", \"mito\"]\n\nrule all:\n input:\n \"figures/figure2.png\",\n \"figures/figure3.png\",\n \"figures/figure4.png\",\n \"figures/figure5a.png\",\n \"figures/figure5b.png\"\n\n# ------- Install -------\n\nrule install:\n output: \"install.done\"\n threads: 4\n shell:\n \"\"\"\n Rscript install_r_packages.R\n touch install.done\n \"\"\"\n\n# ------- Data download -------\n\nrule download:\n input:\n \"datasets/{dset}.txt\"\n output:\n \"data/{dset}/done.txt\"\n message: \"Download datasets\"\n shell:\n \"\"\"\n wget -i {input} -P data/{wildcards.dset}\n touch data/{wildcards.dset}/done.txt\n \"\"\"\n\nrule download_gtex:\n input:\n \"datasets/gtex.txt\"\n output:\n \"data/gtex/GTEx_v8_finemapping_CAVIAR/CAVIAR_Results_v8_GTEx_LD_HighConfidentVariants.gz\"\n shell:\n \"\"\"\n wget -i {input} -P data/gtex\n cd data/gtex\n tar -xvf GTEx_v8_finemapping_CAVIAR.tar\n rm GTEx_v8_finemapping_CAVIAR.tar\n \"\"\"\n\n# ------- Data processing -------\n\nrule process:\n input:\n \"data/{dset}/done.txt\",\n \"install.done\"\n output:\n \"objects/{dset}.rds\"\n message: \"Process data\"\n shell: \"Rscript code/process_{wildcards.dset}.R\"\n\nrule gather_benchmark_timings:\n input:\n \"data/biccn/downsampling/svd_50000.rds\"\n output:\n \"data/biccn/timings.tsv\"\n message: \"Collating benchmark data\"\n shell: \"Rscript code/biccn_downsampling/collate_timings.R\"\n\n# ------- Downsampling -------\n\nrule downsample:\n input:\n \"objects/biccn.rds\"\n output:\n \"data/biccn/downsampling/50000.rds\"\n message: \"Downsample BICCN fragment file\"\n threads: 1\n shell: \"Rscript code/biccn_downsampling/downsample_biccn.R\"\n\nrule create_annotations:\n input: \"install.done\"\n output: \"data/biccn/annotations.rds\"\n message: \"Extracting annotations\"\n threads: 1\n shell: \"Rscript code/biccn_downsampling/get_annotations.R\"\n\nrule benchmark:\n input:\n \"data/biccn/downsampling/50000.rds\",\n \"data/biccn/annotations.rds\"\n output:\n \"data/biccn/downsampling/svd_50000.rds\"\n message: \"Running benchmarks\"\n threads: 8\n shell: \"bash code/biccn_downsampling/benchmark.sh\"\n\nrule tfidf_downsampling:\n input:\n \"objects/pbmc.rds\"\n output:\n \"figures/dimplot_downsample_pbmc.rds\"\n shell:\n \"\"\"\n Rscript code/pbmc_downsampling/run_pbmc_downsample.R\n \"\"\"\n\n# ------- Links -------\n\nrule links:\n input:\n \"objects/pbmc.rds\"\n output:\n \"objects/pbmc_links.rds\"\n threads: 8\n shell:\n \"\"\"\n Rscript code/link_peaks.R\n \"\"\"\n\n# ------- Analysis -------\n\nrule analyze_eqtl:\n input:\n \"objects/pbmc.rds\",\n \"objects/pbmc_links.rds\",\n \"data/gtex/GTEx_v8_finemapping_CAVIAR/CAVIAR_Results_v8_GTEx_LD_HighConfidentVariants.gz\"\n output:\n \"eqtl.done\"\n shell:\n \"\"\"\n Rscript code/analyze_pbmc.R\n touch eqtl.done\n \"\"\"\n\nrule analyze_pbmc:\n input:\n \"objects/pbmc.rds\",\n \"objects/pbmc_links.rds\",\n \"eqtl.done\"\n output:\n \"figures/tss_enrichment.rds\"\n shell:\n \"\"\"\n Rscript code/analyze_pbmc.R\n \"\"\"\n\n# ------- Figures -------\n\nrule fig2:\n input:\n \"figures/tss_enrichment.rds\"\n output:\n \"figures/figure2.png\"\n shell:\n \"\"\"\n Rscript code/figure2.R\n \"\"\"\n\nrule fig3:\n input:\n \"figures/dimplot_downsample_pbmc.rds\"\n output:\n \"figures/figure3.png\"\n shell:\n \"\"\"\n Rscript code/figure3.R\n \"\"\"\n\nrule fig4:\n input:\n \"objects/mito.rds\"\n output:\n \"figures/figure4.png\"\n shell:\n \"\"\"\n Rscript code/figure4.R\n \"\"\"\n\nrule fig5:\n input:\n \"objects/biccn.rds\",\n \"data/biccn/timings.tsv\"\n output:\n \"figures/figure5a.png\",\n \"figures/figure5b.png\"\n shell:\n \"\"\"\n Rscript code/figure5.R\n \"\"\"\n" }, { "alpha_fraction": 0.5450748205184937, "alphanum_fraction": 0.5948485732078552, "avg_line_length": 19.52142906188965, "blob_id": "9692dc3aa43062394108a8b3fb0275d9c157f601", "content_id": "ec5b512b3d71d3d2ea463d64e37912ab74180b02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2873, "license_type": "no_license", "max_line_length": 105, "num_lines": 140, "path": "/code/process_biccn.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "library(Signac)\nlibrary(Seurat)\nlibrary(GenomicRanges)\nlibrary(BSgenome.Mmusculus.UCSC.mm10)\nlibrary(EnsDb.Mmusculus.v79)\nlibrary(Matrix)\nlibrary(future)\nplan(\"multiprocess\", workers = 4)\noptions(future.globals.maxSize = 50 * 1024 ^ 3)\n\n\nannotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Mmusculus.v79)\nseqlevelsStyle(annotations) <- \"UCSC\"\ngenome(annotations) <- \"mm10\"\n\nfragment.counts <- CountFragments(\n fragments = \"data/biccn/fragments.sort.bed.gz\"\n)\n\ncells <- fragment.counts[fragment.counts$frequency_count > 1500, ]$CB\n\nrm(fragment.counts)\ngc()\n\nfrags <- CreateFragmentObject(\n path = \"data/biccn/fragments.sort.bed.gz\",\n cells = cells,\n validate.fragments = FALSE\n)\n\n# load peaks\nunified.peaks <- read.table(\"data/biccn/unified_peaks.bed\", sep = \"\\t\", header = TRUE)\nunified.peaks <- makeGRangesFromDataFrame(unified.peaks)\n\n# quantify\ncounts <- FeatureMatrix(\n fragments = frags,\n features = unified.peaks,\n cells = cells\n)\n\nrsums <- rowSums(counts)\ncsums <- colSums(counts)\ncounts <- counts[rsums > 100, csums > 1000]\ngc()\n\n# create seurat object\nbiccn_assay <- CreateChromatinAssay(\n counts = counts,\n fragments = frags,\n genome = \"mm10\",\n annotation = annotations\n)\n\nbiccn <- CreateSeuratObject(\n counts = biccn_assay,\n assay = \"ATAC\",\n project = \"BICCN\"\n)\n\nrm(biccn_assay)\ngc()\n\n# QC\nbiccn <- NucleosomeSignal(biccn, n = 1e9)\nbiccn <- TSSEnrichment(biccn)\n\n# Dim reduc\nbiccn <- FindTopFeatures(biccn)\nbiccn <- RunTFIDF(biccn)\nbiccn <- RunSVD(biccn, n = 100)\nbiccn <- RunUMAP(biccn, reduction = \"lsi\", dims = 2:100)\n\n# Clustering\n# biccn <- FindNeighbors(biccn, reduction = \"lsi\", dims = 2:100)\n# biccn <- FindClusters(biccn, algorithm = 3)\n\n# Add region information\n\nregions <- c(\n \"1A\" = \"MOs-1\",\n \"1B\" = \"ORB\",\n \"1C\" = \"MOB\",\n \"2A\" = \"LIMBIC-1\",\n \"2B\" = \"MOs-2\",\n \"2C\" = \"MOp-1\",\n \"2D\" = \"PIR-1\",\n \"2E\" = \"AON\",\n \"3A\" = \"LIMBIC-2\",\n \"3B\" = \"MOs-3\",\n \"3C\" = \"MOp-2\",\n \"3D\" = \"AI\",\n \"3E\" = \"PIR-2\",\n \"3F\" = \"ACB-1\",\n \"4A\" = \"LIMBIC-3\",\n \"4B\" = \"MOp-3\",\n \"4C\" = \"SSp-1\",\n \"4D\" = \"CP-1\",\n \"4E\" = \"ACB-2\",\n \"4F\" = \"PIR-3\",\n \"4G\" = \"LSX-1\",\n \"4H\" = \"PAL-1\",\n \"5A\" = \"LIMBIC-4\",\n \"5B\" = \"SSp-2\",\n \"5C\" = \"SSs-1\",\n \"5D\" = \"MOp-4\",\n \"5E\" = \"CP-2\",\n \"5F\" = \"ACB-3\",\n \"5G\" = \"PIR-4\",\n \"5H\" = \"PAL-2\",\n \"5J\" = \"LSX-2\",\n \"6A\" = \"LIMBIC-5\",\n \"6B\" = \"SSp-3\",\n \"6C\" = \"SSs-2\",\n \"6D\" = \"PIR-5\",\n \"7B\" = \"SSp-4\",\n \"8B\" = \"SSp-5\",\n \"8E\" = \"CA-1\",\n \"8J\" = \"DG-1\",\n \"9A\" = \"Other\",\n \"9B\" = \"Other\",\n \"9D\" = \"Other\",\n \"9H\" = \"CA-2\",\n \"9J\" = \"DG-2\",\n \"10C\" = \"Other\",\n \"10G\" = \"Other\",\n \"11B\" = \"Other\",\n \"10E\" = \"CA-3\",\n \"10F\" = \"DG-3\",\n \"11E\" = \"CA-4\",\n \"11F\" = \"DG-4\"\n)\n\n# add region\nbiccn$region <- regions[biccn$orig.ident]\n\n# add coarse-level region\nbiccn$broad_region <- sapply(biccn$region, function(x) unlist(strsplit(x, split = \"-\", fixed = TRUE))[1])\n\nsaveRDS(object = biccn, file = \"objects/biccn.rds\")\n" }, { "alpha_fraction": 0.6051000952720642, "alphanum_fraction": 0.6527645587921143, "avg_line_length": 36.13274383544922, "blob_id": "76308eea7834d33e3b78e6b7a4c2fa18b23da06a", "content_id": "43c5eb2680ab6866c22ec7e6dca7be192fa2e307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4196, "license_type": "no_license", "max_line_length": 134, "num_lines": 113, "path": "/code/figure5.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "library(Signac)\nlibrary(Seurat)\nlibrary(ggplot2)\nlibrary(patchwork)\n\nbiccn <- readRDS(\"objects/biccn.rds\")\ntimings <- read.table(\"data/biccn/timings.tsv\")\ntimings$Cores <- as.factor(timings$Cores)\n\n# featurematrix timings\nruntime_fmat <- ggplot(data = timings[timings$Step == \"FeatureMatrix\", ], mapping = aes(x = Cells, y = Runtime / 60, color = Cores)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Runtime (minutes)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n scale_y_continuous(breaks = seq(0, 300, 60)) +\n theme_bw() +\n ggtitle(label = \"FeatureMatrix\", subtitle = \"315,334 peaks\")\n\nmem_fmat <- ggplot(data = timings[timings$Step == \"FeatureMatrix\", ], mapping = aes(x = Cells, y = Memory / 1024^2, color = Cores)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Max memory (Gb)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n scale_y_continuous(breaks = seq(0, 150, 25)) +\n theme_bw()\n\nfmat <- (runtime_fmat | mem_fmat) + plot_layout(guides = \"collect\")\n\n# nucleosome signal timings\nruntime_ns <- ggplot(data = timings[timings$Step == \"NucleosomeSignal\", ], mapping = aes(x = Cells, y = Runtime / 60)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Runtime (minutes)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n theme_bw() +\n ggtitle(\"NucleosomeSignal\")\n\nmem_ns <- ggplot(data = timings[timings$Step == \"NucleosomeSignal\", ], mapping = aes(x = Cells, y = Memory / 1024^2)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Max memory (Gb)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 100000)) +\n theme_bw()\n\nns <- runtime_ns | mem_ns\n\n# tss enrichment timings\nruntime_tss <- ggplot(data = timings[timings$Step == \"TSSEnrichment\", ], mapping = aes(x = Cells, y = Runtime / 60)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Runtime (minutes)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n theme_bw() +\n ggtitle(\"TSSEnrichment\")\n\nmem_tss <- ggplot(data = timings[timings$Step == \"TSSEnrichment\", ], mapping = aes(x = Cells, y = Memory / 1024^2)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Max memory (Gb)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n theme_bw()\n\ntss <- runtime_tss | mem_tss\n\n# tf-idf timings\nruntime_tfidf <- ggplot(data = timings[timings$Step == \"RunTFIDF\", ], mapping = aes(x = Cells, y = Runtime / 60)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Runtime (minutes)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n theme_bw() +\n ggtitle(\"RunTFIDF\")\n\nmem_tfidf <- ggplot(data = timings[timings$Step == \"RunTFIDF\", ], mapping = aes(x = Cells, y = Memory / 1024^2)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Max memory (Gb)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n theme_bw()\n\ntfidf <- runtime_tfidf | mem_tfidf\n\n# svd timings\nruntime_svd <- ggplot(data = timings[timings$Step == \"RunSVD\", ], mapping = aes(x = Cells, y = Runtime / 60)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Runtime (minutes)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n theme_bw() +\n ggtitle(\"RunSVD\")\n\nmem_svd <- ggplot(data = timings[timings$Step == \"RunSVD\", ], mapping = aes(x = Cells, y = Memory / 1024^2)) +\n geom_point() +\n geom_smooth(se = FALSE) +\n ylab(\"Max memory (Gb)\") +\n scale_x_continuous(labels = scales::comma, breaks = seq(0, 700000, 200000)) +\n theme_bw()\n\nrunsvd <- runtime_svd | mem_svd\n\n# max memory use for steps other than FeatureMatrix just refects the difference in\n# object size for different number of cells, rather than scaling of the function\n# itself\n\n# collate all runtime panels\nruntimes <- fmat / (runtime_ns | runtime_tss) / (runtime_tfidf | runtime_svd)\n\n# biccn dimplot\ndp <- DimPlot(biccn, group.by = \"broad_region\", pt.size = 0.1)\n\nggsave(filename = \"figures/figure5a.png\", plot = dp, height = 12, width = 14, dpi = 200)\nggsave(filename = \"figures/figure5b.png\", plot = runtimes, height = 8, width = 6, dpi = 300)\n" }, { "alpha_fraction": 0.689217746257782, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 23.894737243652344, "blob_id": "bdb1a9588072719582844812c65c2d41d2e29f7a", "content_id": "52900406872ac29f782c0094929ac233265ed618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 473, "license_type": "no_license", "max_line_length": 126, "num_lines": 19, "path": "/README.md", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "## Signac paper\n\nCode to reproduce analyses shown in [Stuart et al. 2020, bioRxiv](https://www.biorxiv.org/content/10.1101/2020.11.09.373613v1)\n\nTo run the workflow, first create a new conda environment containing the dependencies:\n\n```\nmamba env create -f environment.yaml\n```\n\nThe entire workflow can be run by executing:\n\n```\nsnakemake --cores 8\n```\n\nFor information about the Signac package, see the [Signac repository](https://github.com/timoast/signac)\n\n![](dag.svg)\n" }, { "alpha_fraction": 0.6189258098602295, "alphanum_fraction": 0.6376811861991882, "avg_line_length": 32.514286041259766, "blob_id": "c065cb903c5e833f8853912201d0f7e0d7c00720", "content_id": "3125b1bff91acf0789b7b014a0c60357f35f14b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 94, "num_lines": 35, "path": "/install_r_packages.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "options(repos = c(\"CRAN\" = \"https://cran.rstudio.com/\"))\noptions(Ncpus = 4)\n\ninstall.packages(\n pkgs = c(\"remotes\", \"BiocManager\", \"tidyr\", \"dplyr\", \"patchwork\")\n)\nBiocManager::install()\nBiocManager::install(pkgs = c(\"GenomeInfoDbData\", \"HSMMSingleCell\", \"GO.db\"))\nsetRepositories(ind = 1:2)\n\nremotes::install_github(repo = \"satijalab/seurat\", ref = \"release/4.0.0\", dependencies = TRUE)\nremotes::install_github(repo = \"timoast/signac\", ref = \"develop\", dependencies = TRUE)\nremotes::install_github(repo = \"jlmelville/uwot\")\nremotes::install_github(repo = \"mojaveazure/seurat-disk\")\n\nBiocManager::install(\n pkgs = c(\"EnsDb.Mmusculus.v79\",\n \"BSgenome.Mmusculus.UCSC.mm10\",\n \"TFBSTools\",\n \"JASPAR2020\",\n \"EnsDb.Hsapiens.v86\",\n \"BSgenome.Hsapiens.UCSC.hg38\",\n \"EnsDb.Hsapiens.v75\",\n \"DropletUtils\",\n \"chromVAR\",\n \"HDF5Array\",\n \"DelayedMatrixStats\",\n \"batchelor\",\n \"scater\"\n )\n )\n\nremotes::install_github('satijalab/seurat-wrappers')\nremotes::install_github('cole-trapnell-lab/leidenbase')\nremotes::install_github('cole-trapnell-lab/monocle3')\n" }, { "alpha_fraction": 0.6688963174819946, "alphanum_fraction": 0.6943143606185913, "avg_line_length": 56.5, "blob_id": "5d509466d43f1fc3b19c097358f2992b6b062972", "content_id": "3d4ef7f1bceae2b2fe57c2e35723b6f7783ac648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2990, "license_type": "no_license", "max_line_length": 107, "num_lines": 52, "path": "/code/figure2.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(patchwork)\n\n# load figures\ntss_plot <- readRDS(\"figures/tss_enrichment.rds\")\nnucleosome_plot <- readRDS(\"figures/nucleosome_signal.rds\") + ggtitle(\"Nucleosome signal\")\njoint_dimplot <- readRDS(\"figures/pbmc_join_dimplot.rds\") + NoLegend() + xlab(\"UMAP 1\") + ylab(\"UMAP 2\")\nmp <- readRDS(\"figures/motifplot.rds\")\ntf_chromvar <- readRDS(\"figures/chromvar_vln.rds\")\ntf_expression <- readRDS(\"figures/tf_rna_vln.rds\")\nfp <- readRDS(\"figures/footprint.rds\")\ncovplot <- readRDS(\"figures/coverage_plot.rds\")\ngene_per_link_plot <- readRDS(\"figures/genes_per_link_plot.rds\")\nlink_per_gene_plot <- readRDS(\"figures/link_per_gene_plot.rds\")\ndistplot_positive <- readRDS(\"figures/distance_positive.rds\")\ndistplot_negative <- readRDS(\"figures/distance_negative.rds\")\n\ntf_chromvar <- tf_chromvar & theme(text = element_text(size = 12), axis.text = element_text(size = 12))\ntf_expression <- tf_expression & theme(text = element_text(size = 12), axis.text = element_text(size = 12))\nlnkplot <- gene_per_link_plot / link_per_gene_plot\ndistances <- distplot_positive / distplot_negative\ntop.panel <- ((nucleosome_plot / tss_plot) | joint_dimplot | covplot) + plot_layout(widths = c(1, 3, 4)) &\n theme(text = element_text(size = 12), axis.text = element_text(size = 12))\npanel1 <- (mp / wrap_plots(tf_chromvar) / tf_expression & xlab(\"\")) & theme(text = element_text(size = 12))\n\nggsave(filename = \"figures/figure2.png\", plot = top.panel, width = 16, height = 5, units = \"in\")\nggsave(filename = \"figures/figure2_2.png\", plot = panel1, width = 6, height = 6, units = \"in\")\nggsave(filename = \"figures/figure2_3.png\", plot = fp, width = 4, height = 6, units = 'in')\nggsave(filename = \"figures/figure2_4.png\", plot = lnkplot, width = 5, height = 6, units = 'in')\nggsave(filename = \"figures/figure2_5.png\", plot = distances, width = 4, height = 6, units = 'in')\n\nlinked_1 <- readRDS(\"figures/linked_covplot1.rds\")\nlinked_2 <- readRDS(\"figures/linked_covplot2.rds\")\n\nlower.panel <- (linked_1 | linked_2) &\n theme(text = element_text(size = 10), axis.text = element_text(size = 10))\n\nggsave(filename = \"figures/figure2_6.png\", plot = lower.panel, width = 16, height = 5, units = \"in\")\n\n## supplementary figure 1\ncp <- readRDS(\"figures/cellranger_peakcalling.rds\")\nmissed <- readRDS(\"figures/macs2_pseudobulk.rds\")\nmissed_peak_count <- readRDS(\"figures/missed_peak_count.rds\")\nsupfig1 <- missed | (missed_peak_count / plot_spacer()) | cp\nggsave(filename = \"figures/figs1.png\", plot = supfig1, height = 8, width = 15, units = \"in\")\n\n## supplementary figure 2\natac_dimplot <- readRDS(\"figures/pbmc_atac_dimplot.rds\") + NoLegend() + xlab(\"UMAP 1\") + ylab(\"UMAP 2\")\nrna_dimplot <- readRDS(\"figures/pbmc_rna_dimplot.rds\") + NoLegend() + xlab(\"UMAP 1\") + ylab(\"UMAP 2\")\nsupfig2 <- ((atac_dimplot + ggtitle(\"DNA accessibility\")) | (rna_dimplot + ggtitle(\"Gene expression\"))) +\n plot_layout(guides = \"collect\")\nggsave(filename = \"figures/sup_figure_2.png\", plot = supfig2, height = 8, width = 16)\n" }, { "alpha_fraction": 0.6041038036346436, "alphanum_fraction": 0.6297525763511658, "avg_line_length": 37.53488540649414, "blob_id": "17f80b4275dbb852dd213bd0248fc67a19c76d8b", "content_id": "15a8bf1e8a2bfd460cec4cda09cad992623c7a86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3314, "license_type": "no_license", "max_line_length": 116, "num_lines": 86, "path": "/code/biccn_downsampling/collate_timings.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "downsamples <- c('50000', '100000', '200000', '300000', '400000', '500000', '600000', '700000')\ncores <- c(1, 2, 4, 8)\n\nresults_df <- data.frame()\nfor (i in downsamples) {\n for (j in cores) {\n max_resident_mem <- readLines(con = paste0(\"data/biccn/benchmarks/featmat_mem_\", i, \"_\", j, \".txt\"))[10]\n max_resident_mem <- strsplit(max_resident_mem, \"\\tMaximum resident set size (kbytes): \", fixed = TRUE)[[1]][[2]]\n runtime <- readLines(con = paste0(\"data/biccn/benchmarks/featmat_runtime_\", i, \"_\", j, \".txt\"))\n runtime <- sapply(runtime, as.numeric, USE.NAMES = FALSE)\n result <- data.frame(\n \"Cells\" = i,\n \"Cores\" = j,\n \"Step\" = \"FeatureMatrix\",\n \"Memory\" = max_resident_mem,\n \"Runtime\" = runtime\n )\n results_df <- rbind(results_df, result)\n }\n}\n\nfor (i in downsamples) {\n max_resident_mem <- readLines(con = paste0(\"data/biccn/benchmarks/nucleosome_mem_\", i, \".txt\"))[10]\n max_resident_mem <- strsplit(max_resident_mem, \"\\tMaximum resident set size (kbytes): \", fixed = TRUE)[[1]][[2]]\n runtime <- readLines(con = paste0(\"data/biccn/benchmarks/nucleosome_runtime_\", i, \".txt\"))\n runtime <- sapply(runtime, as.numeric, USE.NAMES = FALSE)\n result <- data.frame(\n \"Cells\" = i,\n \"Cores\" = 1,\n \"Step\" = \"NucleosomeSignal\",\n \"Memory\" = max_resident_mem,\n \"Runtime\" = runtime\n )\n results_df <- rbind(results_df, result)\n}\n\nfor (i in downsamples) {\n max_resident_mem <- readLines(con = paste0(\"data/biccn/benchmarks/tss_mem_\", i, \".txt\"))[10]\n max_resident_mem <- strsplit(max_resident_mem, \"\\tMaximum resident set size (kbytes): \", fixed = TRUE)[[1]][[2]]\n runtime <- readLines(con = paste0(\"data/biccn/benchmarks/tss_runtime_\", i, \".txt\"))\n runtime <- sapply(runtime, as.numeric, USE.NAMES = FALSE)\n result <- data.frame(\n \"Cells\" = i,\n \"Cores\" = 1,\n \"Step\" = \"TSSEnrichment\",\n \"Memory\" = max_resident_mem,\n \"Runtime\" = runtime\n )\n results_df <- rbind(results_df, result)\n}\n\nfor (i in downsamples) {\n max_resident_mem <- readLines(con = paste0(\"data/biccn/benchmarks/tfidf_mem_\", i, \".txt\"))[10]\n max_resident_mem <- strsplit(max_resident_mem, \"\\tMaximum resident set size (kbytes): \", fixed = TRUE)[[1]][[2]]\n runtime <- readLines(con = paste0(\"data/biccn/benchmarks/tfidf_runtime_\", i, \".txt\"))\n runtime <- sapply(runtime, as.numeric, USE.NAMES = FALSE)\n result <- data.frame(\n \"Cells\" = i,\n \"Cores\" = 1,\n \"Step\" = \"RunTFIDF\",\n \"Memory\" = max_resident_mem,\n \"Runtime\" = runtime\n )\n results_df <- rbind(results_df, result)\n}\n\nfor (i in downsamples) {\n max_resident_mem <- readLines(con = paste0(\"data/biccn/benchmarks/svd_mem_\", i, \".txt\"))[10]\n max_resident_mem <- strsplit(max_resident_mem, \"\\tMaximum resident set size (kbytes): \", fixed = TRUE)[[1]][[2]]\n runtime <- readLines(con = paste0(\"data/biccn/benchmarks/svd_runtime_\", i, \".txt\"))\n runtime <- sapply(runtime, as.numeric, USE.NAMES = FALSE)\n result <- data.frame(\n \"Cells\" = i,\n \"Cores\" = 1,\n \"Step\" = \"RunSVD\",\n \"Memory\" = max_resident_mem,\n \"Runtime\" = runtime\n )\n results_df <- rbind(results_df, result)\n}\n\nresults_df$Cells <- as.numeric(results_df$Cells)\nresults_df$Cores <- as.factor(results_df$Cores)\nresults_df$Memory <- as.numeric(results_df$Memory)\n\nwrite.table(x = results_df, file = \"data/biccn/timings.tsv\")\n" }, { "alpha_fraction": 0.6216092109680176, "alphanum_fraction": 0.6358620524406433, "avg_line_length": 32.984375, "blob_id": "73044ed3019da00004d1abfe1858e216c5e420ac", "content_id": "35a632c747e30743b309fc44b537853d59bc2ee0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2175, "license_type": "no_license", "max_line_length": 86, "num_lines": 64, "path": "/code/pbmc_downsampling/run_pbmc_downsample.R", "repo_name": "Gavin-Lijy/signac-paper", "src_encoding": "UTF-8", "text": "library(Signac)\nlibrary(Seurat)\nlibrary(DropletUtils)\nlibrary(ggplot2)\nlibrary(RANN)\n\nset.seed(1234)\n\natac.assay <- \"ATAC\"\npbmc <- readRDS(\"objects/pbmc.rds\")\ncounts <- GetAssayData(pbmc, slot = \"counts\", assay = atac.assay)\n\n# downsample counts\nds_level <- rev(seq(0.2, 1, 0.2))\nmethod_use <- c(1, 2)\n\ndimplot_list <- list()\nhist_list <- list()\npurity_list <- list()\norder.use <- colnames(pbmc)\n\n# use cell types defined by RNA\nclustering.use <- \"celltype\"\nclusters <- pbmc[[clustering.use]][[1]]\n\nknn_purity <- function(embeddings, clusters, k = 100) {\n nn <- nn2(data = embeddings, k = k + 1)$nn.idx[, 2:k] # remove self-neighbor\n # find percentage of neighbors that are of the same cluster\n nn_purity <- vector(mode = \"numeric\", length = length(x = clusters))\n for (i in seq_len(length.out = nrow(x = nn))) {\n nn_purity[i] <- sum(clusters[nn[i, ]] == clusters[i]) / k\n }\n return(nn_purity)\n}\n\nDefaultAssay(pbmc) <- atac.assay\nobj <- pbmc\nfor (d in ds_level) {\n counts_use <- downsampleMatrix(x = counts, prop = d)\n obj <- SetAssayData(obj, slot = \"counts\", assay = atac.assay, new.data = counts_use)\n for (m in method_use) {\n key <- paste(d, m, sep = \"_\")\n message(key)\n obj <- RunTFIDF(object = obj, assay = atac.assay, method = m)\n nonzero_vals <- GetAssayData(object = obj, assay = atac.assay, slot = \"data\")@x\n nz_hist <- ggplot(data = data.frame(nzv = nonzero_vals),\n mapping = aes(x = nzv)) +\n geom_histogram(bins = 100) +\n theme_bw() +\n xlab(\"Non-zero TF-IDF values\")\n obj <- RunSVD(obj)\n obj <- RunUMAP(obj, reduction = \"lsi\", dims = 2:30, reduction.name = \"dsumap\")\n dp <- DimPlot(obj, group.by = clustering.use, reduction = \"dsumap\")\n emb <- Embeddings(object = obj, reduction = \"lsi\")[order.use, 2:30]\n nn <- knn_purity(embeddings = emb, clusters = clusters, k = 100)\n dimplot_list[[key]] <- dp\n hist_list[[key]] <- nz_hist\n purity_list[[key]] <- nn\n }\n}\n\nsaveRDS(object = dimplot_list, file = \"figures/dimplot_downsample_pbmc.rds\")\nsaveRDS(object = hist_list, file = \"figures/hist_downsample_pbmc.rds\")\nsaveRDS(object = purity_list, file = \"figures/knn_purity_pbmc.rds\")\n" } ]
11
AmyBrowneDesigns/cc_TDD_compare_homework
https://github.com/AmyBrowneDesigns/cc_TDD_compare_homework
65cf867ba9670dec64bba3339d24b82faffa32d2
ddb2ffb8233ec80fd5a850bf9ba57383562304ef
151583be3c39fe21691e37c7de14732958dba8c2
refs/heads/master
2022-12-21T23:29:57.350386
2020-09-16T20:27:13
2020-09-16T20:27:13
296,140,560
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6397351026535034, "alphanum_fraction": 0.6927152276039124, "avg_line_length": 41, "blob_id": "d289e53441fb9e39e841e7a65c0bd3bd0738cfd8", "content_id": "a6a0261df20b2554b0d47a64e33f5f7a4096b795", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 152, "num_lines": 18, "path": "/tests/compare_test.py", "repo_name": "AmyBrowneDesigns/cc_TDD_compare_homework", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom src.compare import compare\nfrom src.compare import compare\n\nclass TestCompare(unittest.TestCase):\n\n def test_compare_3_1_returns_3_is_greater_than_1(self):\n self.assertEqual(\"3 is greater than 1\", compare(3, 1))\n\n def test_compare_3_5_returns_3_is_less_than_5(self):\n self.assertEqual(\"3 is less than 5\", compare(3, 5))\n\n def test_compare_10_10returns_10__10(self):\n self.assertEqual(\"10 is equal to 10\", compare(10, 10))\n # return the string \"first_number is less than second_number\" if the first number is less than the second (e.g. compare(3, 5) => \"3 is less than 5\")\n\n # return the string \"both numbers are equal\" if the two numbers are equal(e.g. compare(10, 10) == \"both numbers are equal\")" }, { "alpha_fraction": 0.6257668733596802, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 39.75, "blob_id": "57e17143bdb28eac72b415a24cd277d8b84add9a", "content_id": "f5e9fdc94aee4fcf4a0b09e5ca7e0747bb5ecd2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 148, "num_lines": 12, "path": "/src/compare.py", "repo_name": "AmyBrowneDesigns/cc_TDD_compare_homework", "src_encoding": "UTF-8", "text": "\ndef compare(num_1, num_2):\n return f\"{num_1} is greater than {num_2}\"\n\ndef compare(num_1, num_2):\n return f\"{num_1} is less than {num_2}\"\n\ndef compare(num_1, num_2):\n return f\"{num_1} is equal to {num_2}\"\n\n# return the string \"first_number is less than second_number\" if the first number is less than the second (e.g. compare(3, 5) => \"3 is less than 5\")\n\n# return the string \"both numbers are equal\" if the two numbers are equal(e.g. compare(10, 10) == \"both numbers are equal\")" } ]
2
E-code804/FantasyFootball_Draft_Simulator
https://github.com/E-code804/FantasyFootball_Draft_Simulator
a2ac7d92e3598fe3f2789c11fdf945a4595d60ef
176e88e8db0d50cf417c61f298953c09ac0becff
69e405a276ee673b3e50f308ce6f10ef5171476c
refs/heads/main
2023-08-02T13:59:30.182091
2021-09-14T19:11:19
2021-09-14T19:11:19
406,429,838
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48574015498161316, "alphanum_fraction": 0.5448921322822571, "avg_line_length": 52.878047943115234, "blob_id": "e7bded5263483f5d421c434222e59f9e65294012", "content_id": "c5ea4472f97ad455134a8a0365c051e5ed11dc6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6627, "license_type": "no_license", "max_line_length": 721, "num_lines": 123, "path": "/FantasySim.py", "repo_name": "E-code804/FantasyFootball_Draft_Simulator", "src_encoding": "UTF-8", "text": "import pygame\nimport os\nimport time\nimport datetime\nimport random\n\npygame.init()\npygame.font.init()\n\nWIDTH, HEIGHT = 1350, 775\nteam1, team2, team3, team4, team5, = {}, {}, {}, {}, {}\nlist_of_teams = [team1, team2, team3, team4, team5]\ndraft_boards = [pygame.image.load(\"Team1_turn.png\"), pygame.image.load(\"Team2_turn.png\"), pygame.image.load(\"Team3_turn.png\"), pygame.image.load(\"Team4_turn.png\"), pygame.image.load(\"Team5_turn.png\")]\nplayer_ranking_imgs = {\"Christian McCafferey\" : \"cmac.png\", \"Dalvin Cook\" : \"cook.png\", \"Saquon Barkley\" : \"saquon.png\", \"Ezekiel Elliot\" : \"zeke.png\", \"Derrick Henry\" : \"henry.png\", \"Davante Adams\" : \"davante.png\", \"Travis Kelce\" : \"kelce.png\", \"Stefon Diggs\" : \"diggs.png\", \"Calvin Ridley\" : \"ridely.png\", \"Darren Waller\" : \"waller.png\", \"DeAndre Hopkins\" : \"dhop.png\", \"Justin Jefferson\" : \"justin.png\", \"George Kittle\" : \"kittle.png\", \"Patrick Mahomes\" : \"mahomes.png\", \"T.J. Hockenson\" : \"hock.png\", \"Josh Allen\" : \"allen.png\", \"Mark Andrews\" : \"andrews.png\", \"Lamar Jackson\" : \"lamar.png\", \"Dak Prescott\" : \"dak.png\", \"Russel Wilson\" : \"russel.png\"}\nplayer_ranking_pts = {\"Christian McCafferey\" : [350, WIDTH, 254, 287], \"Dalvin Cook\" : [350, WIDTH, 287, 322], \"Saquon Barkley\" : [350, WIDTH, 322, 359], \"Ezekiel Elliot\" : [350, WIDTH, 359, 394], \"Derrick Henry\" : [350, WIDTH, 394, 429], \"Davante Adams\" : [350, WIDTH, 429, 464], \"Travis Kelce\" : [350, WIDTH, 464, 499], \"Stefon Diggs\" : [350, WIDTH, 499, 534], \"Calvin Ridley\" : [350, WIDTH, 534, 569], \"Darren Waller\" : [350, WIDTH, 569, 604], \"DeAndre Hopkins\" : [350, WIDTH, 604, 639], \"Justin Jefferson\" : [350, WIDTH, 639, 674], \"George Kittle\" : [350, WIDTH, 674, 709], \"Patrick Mahomes\" : [350, WIDTH, 709, 744], \"T.J. Hockenson\" : [350, WIDTH, 744, 779], \"Josh Allen\" : [350, WIDTH, 779, 814], \"Mark Andrews\" : [350, WIDTH, 814, 849], \"Lamar Jackson\" : [350, WIDTH, 849, 884], \"Dak Prescott\" : [350, WIDTH, 884, 919], \"Russel Wilson\" : [350, WIDTH, 919, 954]}\nplayer_rankings = {\"Christian McCafferey\" : \"1\", \"Dalvin Cook\" : \"2\", \"Saquon Barkley\" : \"3\", \"Ezekiel Elliot\" : \"4\", \"Derrick Henry\" : \"5\", \"Davante Adams\" : \"5\", \"Travis Kelce\" : \"6\", \"Stefon Diggs\" : \"7\", \"Calvin Ridley\" : \"8\", \"Darren Waller\" : \"9\", \"DeAndre Hopkins\" : \"10\", \"Justin Jefferson\" : \"11\", \"George Kittle\" : \"12\", \"Patrick Mahomes\" : \"13\", \"T.J. Hockenson\" : \"14\", \"Josh Allen\" : \"15\", \"Mark Andrews\" : \"16\", \"Lamar Jackson\" : \"17\", \"Dak Prescott\" : \"18\", \"Russel Wilson\" : \"20\"}\n\nmain_font = pygame.font.SysFont(\"comicsans\", 30)\nwin = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Fantasy Draft Room\")\n\n# Takes the current drafter to determine which UI to display, and displays\n# all current available players on to the main screen.\ndef display_player(current_drafter):\n win.blit(draft_boards[current_drafter], (0,0))\n rank_x, name_x, y, remove_player = 397, 472, 263, \"\"\n\n for player in player_rankings.keys():\n # In main, when a user confirms to draft a player, that same player's\n # rank will be turned to None, indicating that he no longer will be displayed\n if player_rankings[player] == None:\n remove_player = player\n # If a player has y coordinates larger than the drafted player,\n # move players after up 35 points.\n for x in player_ranking_pts.keys():\n if player_ranking_pts[player][2] < player_ranking_pts[x][2]:\n player_ranking_pts[x][2] -= 35\n player_ranking_pts[x][3] -= 35\n player_ranking_pts.pop(player)\n else:\n # When there's no None type, simply display players as they come.\n rank = main_font.render(player_rankings[player], 1, (0,0,0))\n name = main_font.render(player, 1, (0,0,0))\n win.blit(rank, (397,y))\n win.blit(name, (472,y))\n y += 35\n if remove_player != \"\":\n player_rankings.pop(remove_player)\n\n# Displays and updates the drafted teams real time\ndef display_teams():\n x1, x2, x3, x4, x5, y = 385, 585, 785, 985, 1185, 275\n win.blit(pygame.image.load(\"Team_Display.png\"), (0,0))\n team_pictures(x1, y, team1)\n team_pictures(x2, y, team2)\n team_pictures(x3, y, team3)\n team_pictures(x4, y, team4)\n team_pictures(x5, y, team5)\n\n# Refactored Code for displaying each player from each team\ndef team_pictures(x, y, team):\n for player in team:\n win.blit(pygame.transform.scale(pygame.image.load(team[player]), (125, 100)), (x, y))\n y += 125\n\n# Utilize x,y points to determine if a player is selected by drafter.\n# the selected player will then appear at top of screen with draft button\n# return True to indicate that the drafter is ready to draft a player\ndef selectable_player(x,y, current_drafter):\n for player_pts in player_ranking_pts.keys():\n if player_ranking_pts[player_pts][0] < x < player_ranking_pts[player_pts][1] and player_ranking_pts[player_pts][2] < y < player_ranking_pts[player_pts][3]:\n win.blit(draft_boards[current_drafter], (0,0))\n display_player(current_drafter)\n win.blit(pygame.transform.scale(pygame.image.load(player_ranking_imgs[player_pts]), (125,100)), (408, 5))\n win.blit(pygame.image.load(\"draft_button.png\"), (50, 5))\n return True, player_pts\n\ndef main():\n # now = datetime.datetime.now()\n # sec = now.strftime(\"%S\")\n # while sec != 40:\n # current = sec\n # if current != sec:\n # print(sec)\n # now = datetime.datetime.now()\n # sec = now.strftime(\"%S\")\n run = True\n start, round = 0, 1\n display_player(start)\n will_draft, player = False, \"\"\n while run: # can prob put the time in here while it updates\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n elif event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n if 854 < pos[0] < 1350 and 115 < pos[1] < 215:\n display_teams()\n elif 350 < pos[0] < 853 and 115 < pos[1] < 215:\n display_player(start)\n elif not will_draft:\n will_draft, player = selectable_player(pos[0], pos[1], start)\n else:\n if 656 < pos[0] < 856 and 40 < pos[1] < 90:\n player_rankings[player] = None\n list_of_teams[start][player] = player_ranking_imgs[player]\n if round % 2 == 0:\n start -= 1\n else:\n start += 1\n if start == 5:\n round += 1\n start -= 1\n elif start == -1:\n round += 1\n start += 1\n display_player(start)\n will_draft = False\n #now = datetime.datetime.now()\n #time_label\n\nmain()\n" }, { "alpha_fraction": 0.8351648449897766, "alphanum_fraction": 0.8351648449897766, "avg_line_length": 44.5, "blob_id": "00453ead01d8763f5f227c58ebc510b87a12c0c5", "content_id": "12d6d84f7b5aa27cb4c4ce8ff0368b20fb016364", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 91, "license_type": "no_license", "max_line_length": 56, "num_lines": 2, "path": "/README.md", "repo_name": "E-code804/FantasyFootball_Draft_Simulator", "src_encoding": "UTF-8", "text": "# FantasyFootball_Draft_Simulator\nMiniture version of a full scale Fantasy Football draft.\n" } ]
2
boiimakillu/KahootPY
https://github.com/boiimakillu/KahootPY
47216203278c6c6273be70e0b70ba9b4c27532d3
c8d7a03a766bf061015a178cd7df2382906f91ae
8b1904fb0996c4a236649bc95c1096e5990a0f12
refs/heads/master
2023-04-07T09:25:37.427836
2021-04-22T02:52:45
2021-04-22T02:52:45
360,373,596
0
0
MIT
2021-04-22T02:54:01
2021-04-15T17:43:43
2021-02-18T21:32:11
null
[ { "alpha_fraction": 0.6295652389526367, "alphanum_fraction": 0.6295652389526367, "avg_line_length": 22.95833396911621, "blob_id": "964b5a8ea88ae439a702d5a6e72c02f72384dab8", "content_id": "13c34afb0f55bec6608b4bbdda2f8e2253bdcc8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 575, "license_type": "permissive", "max_line_length": 49, "num_lines": 24, "path": "/KahootPY/src/util/errors.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "# All of these are the same, just different names\n\nclass GameLockedError(Exception):\n def __init__(self,data):\n super().__init__(data)\n\nclass JoinFailError(Exception):\n def __init__(self,data):\n super().__init__(data)\n\nclass TeamJoinError(Exception):\n def __init__(self,data):\n super().__init__(data)\n\nclass SendFailException(Exception):\n def __init__(self,data):\n super().__init__(data)\n\nclass AnswerFailException(Exception):\n def __init__(self,data):\n super().__init__(data)\n\nclass InvalidPINException(Exception):\n pass\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6284722089767456, "avg_line_length": 40.14285659790039, "blob_id": "db2b940be5128387819399374e533a6f8673dc74", "content_id": "4855b2f044a5ce7ed38ba1d7b617b783f7fe67aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "permissive", "max_line_length": 110, "num_lines": 7, "path": "/KahootPY/src/modules/quizStart.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from json import loads\n\ndef main(self):\n def handler(message):\n if message[\"channel\"] == \"/service/player\" and message.get(\"data\") and message[\"data\"].get(\"id\") == 9:\n self._emit(\"QuizStart\",loads(message[\"data\"][\"content\"]))\n self.handlers[\"quizStart\"] = handler\n" }, { "alpha_fraction": 0.5264323353767395, "alphanum_fraction": 0.5305839776992798, "avg_line_length": 44.162498474121094, "blob_id": "97aa43bd2f7ee7d2f20eacf7561e4ccfcd9ac349", "content_id": "ccbea5a8821710c43d15e72de884b35685979395", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3613, "license_type": "permissive", "max_line_length": 132, "num_lines": 80, "path": "/KahootPY/src/modules/main.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from ..assets.LiveJoinPacket import LiveJoinPacket\nfrom ..assets.LiveJoinTeamPacket import LiveJoinTeamPacket\nfrom ..assets.LiveTwoStepAnswer import LiveTwoStepAnswer\nfrom ..assets.LiveLeavePacket import LiveLeavePacket\nimport asyncio\nimport time\nimport math\nimport json\n\ndef main(self):\n self.classes[\"LiveTwoStepAnswer\"] = LiveTwoStepAnswer\n self.classes[\"LiveJoinPacket\"] = LiveJoinPacket\n self.classes[\"LiveJoinTeamPacket\"] = LiveJoinTeamPacket\n self.classes[\"LiveLeavePacket\"] = LiveLeavePacket\n def TwoFactor(message):\n if message[\"channel\"] == \"/service/player\" and message.get(\"data\") and not self.connected:\n if message[\"data\"].get(\"id\") == 53:\n self.twoFactorResetTime = int(time.time() * 1000)\n self.emit(\"TwoFactorReset\")\n elif message[\"data\"].get(\"id\") == 51:\n self.emit(\"TwoFactorWrong\")\n elif message[\"data\"].get(\"id\") == 52:\n self.connected = True\n self.emit(\"TwoFactorCorrect\")\n if self.lastEvent:\n self.emit(self.lastEvent[0],self.lastEvent[1])\n self.lastEvent = None\n self.twoFactorResetTime = None\n self.handlers[\"TwoFactor\"] = TwoFactor\n\n async def Join(message):\n if message[\"channel\"] == \"/service/status\":\n self.emit(\"status\",message[\"data\"])\n if message[\"data\"][\"status\"] == \"LOCKED\":\n self.disconnectReason = \"Game Locked\"\n await self.leave(True)\n return\n self.disconnectReason = message.get(\"description\")\n await self.leave(True)\n elif message[\"channel\"] == \"/service/controller\" and message.get(\"data\") and message[\"data\"].get(\"type\") == \"loginResponse\":\n if message[\"data\"].get(\"error\"):\n if str(message[\"data\"].get(\"description\")).lower() != \"duplicate name\":\n self.disconnectReason = message.get(\"description\")\n await self.leave(True)\n else:\n self.cid = message[\"data\"][\"cid\"]\n if self.settings.get(\"gameMode\") == \"team\":\n await asyncio.sleep(1)\n if team != False:\n try:\n await self.joinTeam(team,True)\n except Exception:\n pass\n self.emit(\"Joined\")\n if not self.settings[\"twoFactorAuth\"]:\n self.connected = True\n else:\n self.emit(\"TwoFactorReset\")\n else:\n self.emit(\"Joined\")\n if self.settings[\"twoFactorAuth\"]:\n self.emit(\"TwoFactorReset\")\n else:\n self.emit(\"Joined\")\n if not self.settings[\"twoFactorAuth\"]:\n self.connected = True\n else:\n self.emit(\"TwoFactorReset\")\n self.handlers[\"Join\"] = Join\n\n def Disconnect(message):\n if message[\"channel\"] == \"/service/player\" and message.get(\"data\") and message[\"data\"].get(\"id\") == 10:\n content = json.loads(message[\"data\"][\"content\"])\n if content.get(\"kickCode\"):\n self.disconnectReason = \"Kicked\"\n else:\n self.disconnectReason = \"Session Ended\"\n loop = asyncio.get_event_loop()\n loop.create_task(self.leave(True))\n self.handlers[\"Disconnect\"] = Disconnect\n" }, { "alpha_fraction": 0.6151078939437866, "alphanum_fraction": 0.6187050342559814, "avg_line_length": 38.71428680419922, "blob_id": "2e0f0dd4c26f8d22b9615e4313f4a31832d1ac37", "content_id": "3805e0e181233babd0d6e7b4a931220722377c64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "permissive", "max_line_length": 110, "num_lines": 7, "path": "/KahootPY/src/modules/timeOver.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "import json\n\ndef main(self):\n def handle(message):\n if message[\"channel\"] == \"/service/player\" and message.get(\"data\") and message[\"data\"].get(\"id\") == 4:\n self._emit(\"TimeOver\",json.loads(message[\"data\"][\"content\"]))\n self.handlers[\"timeOver\"] = handle\n" }, { "alpha_fraction": 0.5097451210021973, "alphanum_fraction": 0.5142428874969482, "avg_line_length": 34.105262756347656, "blob_id": "e8fe093738b466ea7279cbe2a8d5b2edc062cdb3", "content_id": "a4deba74680eacaefdd53dc60c1aba6621eb1a21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "permissive", "max_line_length": 79, "num_lines": 19, "path": "/KahootPY/src/assets/LiveFeedbackPacket.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from .LiveBaseMessage import LiveBaseMessage\nimport json as JSON\n\nclass LiveFeedbackPacket(LiveBaseMessage):\n def __init__(self,client,fun,learning,recommend,overall):\n super().__init__(\"/service/controller\",{\n \"id\": 11,\n \"type\": \"message\",\n \"gameid\": client.gameid,\n \"host\": \"kahoot.it\",\n \"content\": JSON.dumps({\n \"totalScore\": (client.data and client.data[\"totalScore\"]) or 0,\n \"fun\": fun,\n \"learning\": learning,\n \"recommend\": recommend,\n \"overall\": overall,\n \"nickname\": client.name\n })\n })\n" }, { "alpha_fraction": 0.6158854365348816, "alphanum_fraction": 0.6354166865348816, "avg_line_length": 31, "blob_id": "80f225932517dfd01dbadfb4d14097c8b1506c31", "content_id": "bf377a101ed9f595ca9ca30f4d90aa63e8ee937a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 768, "license_type": "permissive", "max_line_length": 66, "num_lines": 24, "path": "/KahootPY/src/modules/answer.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "import asyncio\nimport json\nimport time\nimport math\nfrom ..assets.LiveQuestionAnswer import LiveQuestionAnswer\nfrom ..util.errors import AnswerFailException\n\nloop = asyncio.get_event_loop()\n\ndef main(self):\n async def answer(choice):\n wait = int(time.time() * 1000) - self.questionStartTime\n if math.isnan(wait):\n wait = 0\n if wait < 250:\n await asyncio.sleep((250 - wait) / 1000)\n promise = loop.create_future()\n def waiter(result):\n if not result or not result.get(\"successful\"):\n promise.set_exception(AnswerFailException(result))\n else:\n promise.set_result(result)\n await self._send(LiveQuestionAnswer(self,choice),waiter)\n return promise\n" }, { "alpha_fraction": 0.4430147111415863, "alphanum_fraction": 0.4577205777168274, "avg_line_length": 29.22222137451172, "blob_id": "a7be1de30718c08b985ccc07870d50c3037ca9d3", "content_id": "4cbb548ef04aa3252d96fb5f8b906adbadefd0da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "permissive", "max_line_length": 48, "num_lines": 18, "path": "/KahootPY/src/assets/LiveJoinPacket.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from .LiveBaseMessage import LiveBaseMessage\nimport json\n\nclass LiveJoinPacket(LiveBaseMessage):\n def __init__(self,client,name):\n super().__init__(\"/service/controller\",{\n \"gameid\": client.gameid,\n \"host\": \"kahoot.it\",\n \"name\": name or \"Guido Rossum\",\n \"type\": \"login\",\n \"content\": json.dumps({\n \"userAgent\": client.userAgent,\n \"screen\": {\n \"width\": 1920,\n \"height\": 1080\n }\n })\n })\n" }, { "alpha_fraction": 0.6346414089202881, "alphanum_fraction": 0.6427605152130127, "avg_line_length": 29.79166603088379, "blob_id": "d3e9a8b67b1d64387887cb94f43179770582f60b", "content_id": "7a160903428edcd6fe9e927a5847cd5889f55f14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "permissive", "max_line_length": 71, "num_lines": 24, "path": "/setup.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"KahootPY\",\n version=\"1.0.0\",\n author=\"theusaf\",\n author_email=\"[email protected]\",\n description=\"A python package to interact with Kahoot!\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/theusaf/KahootPY\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n keywords=[\"kahoot\",\"bot\"],\n install_requires=[\"websockets\",\"pymitter\",\"requests\",\"user_agent\"],\n)\n" }, { "alpha_fraction": 0.44516128301620483, "alphanum_fraction": 0.4557184875011444, "avg_line_length": 34.52083206176758, "blob_id": "543344a18a1f51ea6162b6fcaf7d1318701b799e", "content_id": "b516252d05fbe6b830957c2c934dd1b6294d4963", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1705, "license_type": "permissive", "max_line_length": 96, "num_lines": 48, "path": "/KahootPY/src/assets/LiveQuestionAnswer.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from .LiveBaseMessage import LiveBaseMessage\nimport math\nimport json\n\nclass LiveQuestionAnswer(LiveBaseMessage):\n def __init__(self,client,choice):\n question = (client.quiz and client.quiz[\"currentQuestion\"]) or {}\n type = question[\"gameBlockType\"] or \"quiz\"\n text = None\n if type == \"multiple_select_poll\" or type == \"multiple_select_quiz\" or type == \"jumble\":\n if not isinstance(choice,list):\n if math.isnan(choice):\n choice = [0,1,2,3]\n else:\n choice = [int(choice)]\n if type == \"jumble\" and len(choice) != 4:\n choice = [0,1,2,3]\n elif type == \"word_cloud\" or type == \"open_ended\":\n text = str(choice)\n else:\n if math.isnan(choice):\n choice = 0\n choice = int(choice)\n content = {\n \"gameid\": client.gameid,\n \"host\": \"kahoot.it\",\n \"id\": 45,\n \"type\": \"message\"\n }\n if text:\n content[\"content\"] = json.dumps({\n \"text\": text,\n \"questionIndex\": question.get(\"questionIndex\") or 0,\n \"meta\": {\n \"lag\": client._timesync.get(\"l\") or 30\n },\n \"type\": type\n })\n else:\n content[\"content\"] = json.dumps({\n \"choice\": choice,\n \"questionIndex\": question.get(\"questionIndex\") or 0,\n \"meta\": {\n \"lag\": client._timesync.get(\"l\") or 30\n },\n \"type\": type\n })\n super().__init__(\"/service/controller\",content)\n" }, { "alpha_fraction": 0.6398348808288574, "alphanum_fraction": 0.6480908393859863, "avg_line_length": 24.5, "blob_id": "f438a5faee9eed488afde032a682ea60f530b8a8", "content_id": "7b5dc08b923ca0b56cc9ea33e9446b5f9f4c0fb6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 969, "license_type": "permissive", "max_line_length": 82, "num_lines": 38, "path": "/examples/basic_usage.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from kahoot import client\npin = 473403\nbot = client()\n# bot.loggingMode = True\nbot.join(pin,\"KahootPY\",[\"a\",\"b\",\"c\"])\ndef joined():\n print(\"joined\")\nbot.on(\"ready\",joined)\ndef badname():\n print(\"invalid name\")\n bot.leave()\nbot.on(\"invalidName\",badname)\ndef answer(q):\n print(\"Question started. Answering '0'\")\n q.answer(0)\nbot.on(\"questionStart\",answer)\ndef qs(q):\n print(\"Quiz Started: \" + q.name)\nbot.on(\"quiz\",qs)\ndef question(q):\n print(\"Question of type \" + q.type + \" got!\")\nbot.on(\"question\",question)\ndef rank(qe):\n print(\"Question Ended. In rank \" + qe.rank + \" with \" + qe.total + \" points.\")\nbot.on(\"questionEnd\",rank)\ndef end():\n print(\"disconnected\")\nbot.on(\"disconnect\",end)\ndef sub():\n print(\"answer submitted\")\nbot.on(\"questionSubmit\",sub)\ndef finishtext(fin):\n print(\"finished with \" + fin.metal + \" medal\")\nbot.on(\"finishText\",finishtext)\ndef done(dat):\n print(\"quiz finished\")\n print(dat)\nbot.on(\"finish\",done)\n" }, { "alpha_fraction": 0.625668466091156, "alphanum_fraction": 0.6390374302864075, "avg_line_length": 40.55555725097656, "blob_id": "c1df821582b13a82deecdb6b3b13e7fa624eae97", "content_id": "c84cd7c853b8faebaefc88697ddd7f956ce53148", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "permissive", "max_line_length": 110, "num_lines": 9, "path": "/KahootPY/src/modules/questionStart.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from json import loads\nfrom time import time\n\ndef main(self):\n def handler(message):\n if message[\"channel\"] == \"/service/player\" and message.get(\"data\") and message[\"data\"].get(\"id\") == 2:\n self.questionStartTime = int(time() * 1000)\n self._emit(\"QuestionStart\",loads(message[\"data\"][\"content\"]))\n self.handlers[\"questionStart\"] = handler\n" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 29, "blob_id": "77d30f5d5e3c0c971e6391211569af6aab2bb6d2", "content_id": "11dfd76ffc8a88a82178b6d549227563be156672", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "permissive", "max_line_length": 48, "num_lines": 12, "path": "/KahootPY/src/assets/LiveJoinTeamPacket.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from .LiveBaseMessage import LiveBaseMessage\nimport json\n\nclass LiveJoinTeamPacket(LiveBaseMessage):\n def __init__(self,client,team):\n super().__init__(\"/service/controller\",{\n \"gameid\": client.gameid,\n \"host\": \"kahoot.it\",\n \"content\": json.dumps(team),\n \"id\": 18,\n \"type\": \"message\"\n })\n" }, { "alpha_fraction": 0.5504538416862488, "alphanum_fraction": 0.5630005598068237, "avg_line_length": 31.017093658447266, "blob_id": "d8ba332973cfad283723c3fee940fa5824f2ca26", "content_id": "91ed5f28a3233cea1b4ff97b2e152c14d231b0ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3746, "license_type": "permissive", "max_line_length": 145, "num_lines": 117, "path": "/KahootPY/src/util/token.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "import urllib\nimport time\nimport re\nimport base64\nimport math\nimport requests\nimport urllib\nimport asyncio\nimport json as JSON\nfrom user_agent import generate_user_agent as UserAgent\nfrom errors import *\n\nloop = asyncio.get_event_loop()\n\nasync def requestChallenge(pin,client):\n options = {\n \"headers\": {\n \"User-Agent\": UserAgent(),\n \"Origin\": \"kahoot.it\",\n \"Referer\": \"https://kahoot.it\",\n \"Accept-Language\": \"en-US,en;q=0.8\",\n \"Accept\": \"*/*\"\n },\n \"host\": \"kahoot.it\",\n \"protocol\": \"https:\",\n \"path\": f\"/rest/challenges/pin/{pin}\"\n }\n url = (options.get(\"protocol\") or \"https:\") + \"//\" + (options.get(\"host\") or \"kahoot.it\") + (options.get(\"port\") or \"\") + options.get(\"path\")\n r = requests.request(options.get(\"method\") or \"GET\",url,headers=options.get(\"headers\"))\n try:\n data = r.json()\n out = {\n \"data\": {\n \"isChallenge\": True,\n \"twoFactorAuth\": False,\n \"kahootData\": data.get(\"kahoot\"),\n \"rawChallengeData\": data[\"challenge\"]\n }\n }\n out[\"data\"].update(data[\"challenge\"][\"game_options\"])\n return out\n except Exception as e:\n raise e\n\nasync def requestToken(pin,client):\n options = {\n \"headers\": {\n \"User-Agent\": UserAgent(),\n \"Origin\": \"kahoot.it\",\n \"Referer\": \"https://kahoot.it\",\n \"Accept-Language\": \"en-US,en;q=0.8\",\n \"Accept\": \"*/*\"\n },\n \"host\": \"kahoot.it\",\n \"protocol\": \"https:\",\n \"path\": f\"/reserve/session/{pin}/?{int(time.time() * 1000)}\"\n }\n url = (options.get(\"protocol\") or \"https:\") + \"//\" + (options.get(\"host\") or \"kahoot.it\") + (options.get(\"port\") or \"\") + options.get(\"path\")\n r = requests.request(options.get(\"method\") or \"GET\",url,headers=options.get(\"headers\"))\n if not r.headers.get(\"x-kahoot-session-token\"):\n raise InvalidPINException(\"Invalid PIN\")\n try:\n data = r.json()\n token = r.headers.get(\"x-kahoot-session-token\")\n token = decodeBase64(token)\n return {\n \"token\": token,\n \"data\": data\n }\n except Exception as e:\n raise e\n\ndef solveChallenge(challenge):\n # src: https://github.com/msemple1111/kahoot-hack/blob/master/main.py\n s1 = challenge.find('this,') + 7\n s2 = challenge.find(\"');\")\n message = challenge[s1:s2]\n s1 = challenge.find('var offset') + 13\n s2 = challenge.find('; if')\n offset = str(\"\".join(challenge[s1:s2].split()))\n offset = eval(offset)\n def repl(char, position):\n return chr((((ord(char)*position) + offset)% 77)+ 48)\n res = \"\"\n for i in range(0,len(message)):\n res+=repl(message[i],i)\n return res\n\n# Decode the token header\ndef decodeBase64(base):\n try:\n base += \"=\" * ((4 - len(base) % 4) % 4)\n return base64.b64decode(base).decode(\"utf-8\")\n except Exception as e:\n return e\n# complex stuff to get the actual token\ndef concatTokens(headerToken,challengeToken):\n token = \"\"\n for i in range(0,len(headerToken)):\n char = ord(headerToken[i])\n mod = ord(challengeToken[i % len(challengeToken)])\n decodedChar = char ^ mod\n token += chr(decodedChar)\n return token\n\nasync def resolve(pin,client):\n if math.isnan(int(pin)):\n raise InvalidPINException(\"Non-numberical PIN\")\n if str(pin)[0] == \"0\":\n return requestChallenge(pin,client)\n data = await requestToken(pin,client)\n token2 = solveChallenge(data[\"data\"][\"challenge\"])\n token = concatTokens(data[\"token\"],token2)\n return {\n \"token\": token,\n \"data\": data[\"data\"]\n }\n" }, { "alpha_fraction": 0.7237569093704224, "alphanum_fraction": 0.7237569093704224, "avg_line_length": 29.16666603088379, "blob_id": "bf7d23251e789c956633d84bca1d9fa132b86ea9", "content_id": "063c56af8a84f7360f40da5e427b19de0b7a324b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 181, "license_type": "permissive", "max_line_length": 51, "num_lines": 6, "path": "/KahootPY/src/assets/LiveLeavePacket.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from .LiveBaseMessage import LiveBaseMessage\nimport time\n\nclass LiveLeavePacket(LiveBaseMessage):\n def __init__(self,client):\n super().__init__(client,\"/meta/disconnect\")\n" }, { "alpha_fraction": 0.5166666507720947, "alphanum_fraction": 0.5214285850524902, "avg_line_length": 29, "blob_id": "fd826b97deaa8216285e69efd668f286fd8d6909", "content_id": "d25ec91df69eb85bbb11ed66469fb7cfa6deb303", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "permissive", "max_line_length": 48, "num_lines": 14, "path": "/KahootPY/src/assets/LiveTwoStepAnswer.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from .LiveBaseMessage import LiveBaseMessage\nimport json\n\nclass LiveTwoStepAnswer(LiveBaseMessage):\n def __init__(self,client,sequence):\n super().__init__(\"/service/controller\",{\n \"id\": 50,\n \"type\": \"message\",\n \"gameid\": client.gameid,\n \"host\": \"kahoot.it\",\n \"content\": json.dumps({\n \"sequence\": \"\".join(sequence)\n })\n })\n" }, { "alpha_fraction": 0.7475345134735107, "alphanum_fraction": 0.7573964595794678, "avg_line_length": 22.045454025268555, "blob_id": "8e069d79c89252bfef6897049f45137d304b335a", "content_id": "5d66243e83edd436108539ca74cc8ea039fb0604", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 507, "license_type": "permissive", "max_line_length": 125, "num_lines": 22, "path": "/README.md", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "**Note: The current version in this repository is incomplete and will not work**\n\n# About\nKahootPY is a library to interact with the Kahoot API. KahootPY supports joining and interacting with quizzes and challenges.\n\n# Installation\n\n`pip install -U KahootPY`\n\n# Usage\n\n```py\nfrom KahootPY import client\nbot = client()\nbot.join(12345,\"KahootPY\")\ndef joinHandle():\n pass\nbot.on(\"Joined\",joinHandle)\n```\n\n# Documentation:\nWork in progress. This is taking longer than expected because I am not good at python.\n" }, { "alpha_fraction": 0.5747212171554565, "alphanum_fraction": 0.5791821479797363, "avg_line_length": 32.625, "blob_id": "a7c1388030a5396092e654aefef179fa829e8ad4", "content_id": "91d5b6a043530eeb6b47e250a3f215783eaa10a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1345, "license_type": "permissive", "max_line_length": 86, "num_lines": 40, "path": "/KahootPY/src/modules/extraData.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "def main(self):\n self.data[\"totalScore\"] = 0\n self.data[\"streak\"] = 0\n self.data[\"rank\"] = 1\n def GameResetHandler():\n self.data[\"totalScore\"] = 0\n self.data[\"rank\"] = 0\n self.data[\"streak\"] = 0\n self.quiz = {}\n self.on(\"GameReset\",GameResetHandler)\n def QuestionStartHandler(event):\n event.update({\n \"type\": event[\"type\"],\n \"index\": event[\"questionIndex\"]\n })\n self.on(\"QuestionStart\",QuestionStartHandler)\n def QuizStartHandler(event):\n event.update({\n \"questionCount\": len(self.quiz[\"quizQuestionAnswers\"])\n })\n try:\n self.quiz.update(event)\n except Exception:\n pass\n self.on(\"QuizStart\",QuizStartHandler)\n def QuestionReadyHandler(event):\n event.update({\n \"type\": event[\"gameBlockType\"],\n \"index\": event[\"questionIndex\"]\n })\n try:\n self.quiz[\"currentQuestion\"].update(event)\n except Exception:\n pass\n self.on(\"QuestionReady\",QuestionReadyHandler)\n def QuestionEndHandler(event):\n self.data[\"totalScore\"] = event[\"totalScore\"]\n self.data[\"streak\"] = event[\"pointsData\"][\"answerStreakPoints\"][\"streakLevel\"]\n self.data[\"rank\"] = event[\"rank\"]\n self.on(\"QuestionEnd\",QuestionEndHandler)\n" }, { "alpha_fraction": 0.6999664902687073, "alphanum_fraction": 0.704101026058197, "avg_line_length": 31.01788902282715, "blob_id": "d1a5f1dac0449855568b553ad3e4ab1d29a7e5ea", "content_id": "63e1c0050e07042e55ff133e4aa29041f400869f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17898, "license_type": "permissive", "max_line_length": 226, "num_lines": 559, "path": "/Documentation.md", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "# Kahoot.js Documentation\n## Table of Contents\n1. [Classes](#classes)\n2. [Kahoot](#kahoot)\n - [Events](#kahoot.events)\n - [ready/joined](#kahoot.events.ready)\n - [quizStart/quiz](#kahoot.events.quiz)\n - [question](#kahoot.events.question)\n - [questionStart](#kahoot.events.questionStart)\n - [questionSubmit](#kahoot.events.questionSubmit)\n - [questionEnd](#kahoot.events.questionEnd)\n - [finish](#kahoot.events.finish)\n - [finishText](#kahoot.events.finishText)\n - [2Step](#kahoot.events.2Step)\n - [2StepFail](#kahoot.events.2StepFail)\n - [2StepSuccess](#kahoot.events.2StepSuccess)\n - [feedback](#kahoot.events.feedback)\n - [invalidName](#kahoot.events.invalidName)\n - [handshakeFailed](#kahoot.events.handshakeFailed)\n - [Methods](#kahoot.methods)\n - [join](#kahoot.methods.join)\n - [reconnect](#kahoot.methods.reconnect)\n - [answerQuestion](#kahoot.methods.answerQuestion)\n - [answer2Step](#kahoot.methods.answer2Step)\n - [leave](#kahoot.methods.leave)\n - [sendFeedback](#kahoot.methods.sendFeedback)\n - [Properties](#kahoot.properties)\n - [~~sendingAnswer~~](#kahoot.properties.sendingAnswer)\n - [token](#kahoot.properties.token)\n - [sessionID](#kahoot.properties.sessionID)\n - [name](#kahoot.properties.name)\n - [quiz](#kahoot.properties.quiz)\n - [nemesis](#kahoot.properties.nemesis)\n - [nemeses](#kahoot.properties.nemeses)\n - [totalScore](#kahoot.properties.totalScore)\n - [cid](#kahoot.properties.cid)\n - [team](#kahoot.properties.team)\n - [hasTwoFactorAuth](#kahoot.properties.hasTwoFactorAuth)\n - [usesNamerator](#kahoot.properties.usesNamerator)\n - [gamemode](#kahoot.properties.gamemode)\n - [loggingMode](#kahoot.properties.loggingMode)\n3. [Quiz](#quiz)\n - [Properties](#quiz.properties)\n - [client](#quiz.properties.client)\n - [name](#quiz.properties.name)\n - [type](#quiz.properties.type)\n - [currentQuestion](#quiz.properties.currentQuestion)\n - [questions](#quiz.properties.questions)\n - [questionCount](#quiz.properties.questionCount)\n - [answerCounts](#quiz.properties.answerCounts)\n4. [Question](#question)\n - [Methods](#question.methods)\n - [answer](#question.methods.answer)\n - [Properties](#question.properties)\n - [client](#question.properties.client)\n - [quiz](#question.properties.quiz)\n - [index](#question.properties.index)\n - [timeLeft](#question.properties.timeLeft)\n - [type](#question.properties.type)\n - [~~usesStoryBlocks~~](#question.properties.usesStoryBlocks)\n - [ended](#question.properties.ended)\n - [number](#question.properties.number)\n - [gamemode](#question.properties.gamemode)\n5. [QuestionEndEvent](#questionendevent)\n - [Properties](#questionendevent.properties)\n - [client](#questionendevent.properties.client)\n - [quiz](#questionendevent.properties.quiz)\n - [question](#questionendevent.properties.question)\n - [correctAnswer](#questionendevent.properties.correctAnswer)\n - [correctAnswers](#questionendevent.properties.correctAnswers)\n - [text](#questionendevent.properties.text)\n - [correct](#questionendevent.properties.correct)\n - [nemesis](#questionendevent.properties.nemesis)\n - [points](#questionendevent.properties.points)\n - [rank](#questionendevent.properties.rank)\n - [streak](#questionendevent.properties.streak)\n - [total](#questionendevent.properties.total)\n6. [QuestionSubmitEvent](#questionsubmitevent)\n - [Properties](#questionsubmitevent.properties)\n - [client](#questionsubmitevent.properties.client)\n - [quiz](#questionsubmitevent.properties.quiz)\n - [question](#questionsubmitevent.properties.question)\n7. [Nemesis](#nemesis)\n - [Properties](#nemesis.properties)\n - [name](#nemesis.properties.name)\n - [score](#nemesis.properties.score)\n - [exists](#nemesis.properties.exists)\n8. [FinishTextEvent](#finishtextevent)\n - [Properties](#finishtextevent.properties)\n - [metal](#finishtextevent.properties.metal)\n9. [QuizFinishEvent](#quizfinishevent)\n - [Properties](#quizfinishevent.properties)\n - [client](#quizfinishevent.properties.client)\n - [quiz](#quizfinishevent.properties.quiz)\n - [players](#quizfinishevent.properties.player)\n - [quizID](#quizfinishevent.properties.quizID)\n - [rank](#quizfinishevent.properties.rank)\n - [correct](#quizfinishevent.properties.correct)\n - [incorrect](#quizfinishevent.properties.incorrect)\n10. [Q and A](#qa)\n11. [Using Proxies](#qa.proxies)\n\n## Classes\n### Kahoot\n---\nThe kahoot client that interacts with kahoot's quiz api.\n<a name=\"kahoot.events\"></a>\n#### Events\n<a name=\"kahoot.events.ready\"></a>\n`on('ready')` and `on('joined')`\n- Emitted when the client joins the game.\n\n<a name=\"kahoot.events.quiz\"></a>\n`on('quizStart', Quiz)` and `on('quiz', Quiz)`\n- Emitted when the quiz starts for the client.\n- Passes a `Quiz` class.\n\n<a name=\"kahoot.events.question\"></a>\n`on('question', Question)`\n- Emitted when the client receives a new question.\n- This is **NOT** the same as the `questionStart` event, which is emitted after the question has started.\n- Passes a `Question` class.\n\n<a name=\"kahoot.events.questionStart\"></a>\n`on('questionStart', Question)`\n- Emitted when a question starts.\n - Questions can be answered using `Question.answer(data)`\n- Passes a `Question` class.\n\n<a name=\"kahoot.events.questionSubmit\"></a>\n`on('questionSubmit', QuestionSubmitEvent)`\n- Emitted when your answer has been submitted.\n- Passes a `QuestionSubmitEvent` class.\n\n<a name=\"kahoot.events.questionEnd\"></a>\n`on('questionEnd', QuestionEndEvent)`\n- Emitted when a question ends.\n- Passes a `QuestionEndEvent` class.\n\n<a name=\"kahoot.events.finish\"></a>\n`on('finish', QuizFinishEvent)`\n- Emitted when the quiz ends.\n- Passes a `QuizFinishEvent` class.\n\n<a name=\"kahoot.events.finishText\"></a>\n`on('finishText', FinishTextEvent)`\n- Emitted when the quiz finish text is sent.\n- Passes a `FinishTextEvent` class.\n\n<a name=\"kahoot.events.disconnect\"></a>\n`on('quizEnd')` and `on('disconnect')`\n- Emitted when the quiz closes, and the client is disconnected.\n\n<a name=\"kahoot.events.2Step\"></a>\n`on('2Step')`\n- Emitted when the 2 Step Auth is recieved\n- Emitted when the 2 Step Auth is refreshed\n\n<a name=\"kahoot.events.2StepFail\"></a>\n`on('2StepFail')`\n- Emitted when the 2 Step Auth is incorrect\n\n<a name=\"kahoot.events.2StepSuccess\"></a>\n`on('2Step')`\n- Emitted when the 2 Step Auth is correct\n\n<a name=\"kahoot.events.feedback\"></a>\n`on('feedback')`\n- Emitted when the host requests to see feedback.\n\n<a name=\"kahoot.events.invalidName\"></a>\n`on('invalidName')`\n- Emitted when the join name is a duplicate.\n\n<a name=\"kahoot.events.handshakeFailed\"></a>\n`on('handshakeFailed')`\n- Emitted when the the websocket connection failed/was blocked.\n\n<a name=\"kahoot.methods\"></a>\n#### Methods\n<a name=\"kahoot.methods.join\"></a>\n`join(sessionID, playerName, teamNames)`\n- Joins the game.\n- Parameters:\n - ***sessionID (Number)*** - The Kahoot session ID to join.\n - ***playerName (String)*** - The name of the user.\n - ***teamNames (Array) [String]*** - The names of the team members to be used in team game modes (optional).\n - Returns: `Promise`\n\n<a name=\"kahoot.methods.reconnect\"></a>\n`reconnect()`\n- Reconnects the bot.\n- Should be used if connection is lost (network issue).\n- Returns: `undefined`\n\n<a name=\"kahoot.methods.answerQuestion\"></a>\n`answerQuestion(id)`\n- Answers the current question.\n- Parameters:\n - ***id (Number|Array|String)***\n - for type \"quiz,\" use a number (0-3) to specify the choice.\n - for type \"open_ended\" and \"word_cloud,\" use a string to specify the answer.\n - for type \"jumble,\" use an array of numbers (0-3) to specify the order of items.\n - Returns: `Promise`\n\n<a name=\"kahoot.methods.answer2Step\"></a>\n`answer2Step(steps)`\n- Answers the 2 Step Auth.\n- Parameters:\n - ***steps (Array)***\n - An array of the steps for the 2 step authentification. (numbers 0-3)\n - Returns: `Promise`\n\n<a name=\"kahoot.methods.leave\"></a>\n`leave()`\n- Leaves the game.\n- Returns: `Promise`\n\n<a name=\"kahoot.methods.sendFeedback\"></a>\n`sendFeedback(fun, learning, recommend, overall)`\n- Sends feedback to the host.\n- Parameters:\n - ***fun (Number)***\n - A number to rate how much fun you had (1-5)\n - ***learning (Number)***\n - A number to rate if you learned anything (1 or 0)\n - ***recommend (Number)***\n - A number to rate if you would recommend (1 or 0)\n - ***overall (Number)***\n - A Number to rate how you felt (-1 - 1)\n - 1 = good\n - -1 = bad\n- Returns: `Promise`\n\n<a name=\"kahoot.properties\"></a>\n#### Properties\n<a name=\"kahoot.properties.sendingAnswer\"></a>\n`sendingAnswer (Boolean)`\n- Whether or not the client is currently sending an answer.\n\n<a name=\"kahoot.properties.token\"></a>\n`token (String)`\n- The client token of the user.\n\n<a name=\"kahoot.properties.sessionID\"></a>\n`sessionID (Number)`\n- The session ID of the quiz.\n\n<a name=\"kahoot.properties.name\"></a>\n`name (String)`\n- The user's name.\n\n<a name=\"kahoot.properties.quiz\"></a>\n`quiz (Quiz)`\n- The current quiz of the client.\n\n<a name=\"kahoot.properties.nemesis\"></a>\n`nemesis (Nemesis)`\n- The client's nemesis. (Will be `null` if the client does not have a nemesis.)\n\n<a name=\"kahoot.properties.nemeses\"></a>\n`nemeses (Nemesis Array)`\n- An array of all the client's past nemeses.\n\n<a name=\"kahoot.properties.totalScore\"></a>\n`totalScore (Number)`\n- The client's accumulated score.\n\n<a name=\"kahoot.properties.cid\"></a>\n`cid`\n- The client's client id.\n\n<a name=\"kahoot.properties.team\"></a>\n`team (Array) [String]`\n- The team member names.\n\n<a name=\"kahoot.properties.gamemode\"></a>\n`gamemode (String)`\n- The game mode of the kahoot.\n - `classic` - normal kahoot game.\n - `team` - kahoot game with teams.\n\n<a name=\"kahoot.properties.loggingMode\"></a>\n`loggingMode (Boolean)`\n- Whether to log the messages from and to the server. Defaults to false.\n\n<a name=\"kahoot.properties.usesNamerator\"></a>\n`usesNamerator (Boolean)`\n- Whether the kahoot is using the namerator.\n\n<a name=\"kahoot.properties.hasTwoFactorAuth\"></a>\n`hasTwoFactorAuth (Boolean)`\n- Whether the kahoot is using two factor authentification.\n\n### Quiz\n---\n<a name=\"quiz.properties\"></a>\n#### Properties\n<a name=\"quiz.properties.client\"></a>\n`client (Kahoot)`\n- The client the quiz is attached.\n\n<a name=\"quiz.properties.name\"></a>\n`name (String)`\n- The name of the quiz.\n - Note: this value may be `null` if you joined the quiz after it started\n\n<a name=\"quiz.properties.type\"></a>\n`type (String)`\n- The quiz type.\n\n<a name=\"quiz.properties.currentQuestion\"></a>\n`currentQuestion (Question)`\n- The current question the quiz is on.\n\n<a name=\"quiz.properties.questions\"></a>\n`questions (Question Array)`\n- An array of every single question in the quiz. New questions get added as they come in.\n\n<a name=\"quiz.properties.questionNumber\"></a>\n`questionCount (Number)`\n- The number of questions in the quiz.\n\n<a name=\"quiz.properties.answerCounts\"></a>\n`answerCounts (Array) [Number]`\n- An array that shows the # of choices per question in the quiz.\n\n### Question\n---\n<a name=\"question.methods\"></a>\n#### Methods\n<a name=\"question.methods.answer\"></a>\n`answer(number)`\n- Parameters:\n - ***number (Number)***\n - The question number to answer. (0 is the first answer, 1 is the second answer, etc.)\n\n<a name=\"question.properties\"></a>\n#### Properties\n<a name=\"question.properties.client\"></a>\n`client (Kahoot)`\n- The client attached to the question.\n\n<a name=\"question.properties.quiz\"></a>\n`quiz (Quiz)`\n- The quiz that the question for.\n\n<a name=\"question.properties.index\"></a>\n`index (Number)`\n- The index of the question.\n\n<a name=\"question.properties.timeLeft\"></a>\n`timeLeft (Number)`\n- The time left before the question starts.\n\n<a name=\"question.properties.type\"></a>\n`type (String)`\n- The question type.\n - \"quiz\" is the basic multiple choice quesiton.\n - \"survey\" is a poll, there aren't any points.\n - \"content\" is a slideshow, you don't need to answer this one.\n - \"jumble\" is a puzzle question, send an array of numbers to order the answers.\n - \"open_ended\" is a free response question; send text.\n - \"word_cloud\" is a free response poll; send text.\n\n<a name=\"question.properties.usesStoryBlocks\"></a>\n`usesStoryBlocks (Boolean)`\n- Whether or not the question uses 'Story Blocks'.\n- I still don't know what this means.\n\n<a name=\"question.properties.ended\"></a>\n`ended (Boolean)`\n- Whether or not the question has ended.\n\n<a name=\"question.properties.number\"></a>\n`number (Number)`\n- The number of the question.\n\n<a name=\"question.properties.gamemode\"></a>\n`gamemode (String)`\n- The game mode of the session. It can be either \"classic\" or \"team.\"\n\n### QuestionEndEvent\n---\n<a name=\"questionendevent.properties\"></a>\n#### Properties\n<a name=\"questionendevent.properties.client\"></a>\n`client (Kahoot)`\n- The client attached to the event.\n\n<a name=\"questionendevent.properties.quiz\"></a>\n`quiz (Quiz)`\n- The quiz that the event is attached to.\n\n<a name=\"questionendevent.properties.question\"></a>\n`question (Question)`\n- The question that the event is attached to.\n\n<a name=\"questionendevent.properties.correctAnswers\"></a>\n`correctAnswers (String Array)`\n- A list of the correct answers.\n\n<a name=\"questionendevent.properties.correctAnswer\"></a>\n`correctAnswer (String)`\n- The correct answer. (if there are multiple correct answers, this will be the first correct answer.)\n\n<a name=\"questionendevent.properties.text\"></a>\n`text (String)`\n- The text sent by Kahoot after a question has finished.\n\n<a name=\"questionendevent.properties.correct\"></a>\n`correct (Boolean)`\n- Whether or not the client got the question right.\n\n<a name=\"questionendevent.properties.nemesis\"></a>\n`nemesis (Nemesis)`\n- The client's nemesis. (Will be `null` if the client does not have a nemesis.)\n\n<a name=\"questionendevent.properties.points\"></a>\n`points (Number)`\n- The points earned from this question.\n\n<a name=\"questionendevent.properties.streak\"></a>\n`streak (Number)`\n- The current correct streak.\n\n<a name=\"questionendevent.properties.rank\"></a>\n`rank (Number)`\n- The rank of the client\n\n<a name=\"questionendevent.properties.total\"></a>\n`total (Number)`\n- The total score of the client\n\n### QuestionSubmitEvent\n---\n<a name=\"questionsubmitevent.properties\"></a>\n#### Properties\n<a name=\"questionsubmitevent.properties.client\"></a>\n`client (Kahoot)`\n- The client attached to the event.\n\n<a name=\"questionsubmitevent.properties.quiz\"></a>\n`quiz (Quiz)`\n- The quiz attached to the event.\n\n<a name=\"questionsubmitevent.properties.question\"></a>\n`question (Question)`\n- The question attached to the event.\n\n### Nemesis\n---\n<a name=\"nemesis.properties\"></a>\n#### Properties\n<a name=\"nemesis.properties.name\"></a>\n`name (String)`\n- The name of the nemesis user.\n\n<a name=\"nemesis.properties.score\"></a>\n`score (Number)`\n- The score of the nemesis user.\n\n<a name=\"nemesis.properties.isGhost\"></a>\n`isGhost (Boolean)`\n- Whether or not the nemesis user is a ghost player or not.\n\n<a name=\"nemesis.properties.exists\"></a>\n`exists (Boolean)`\n- Whether or not the nemesis exists (All other values will be `undefined` if this is `false`)\n\n### FinishTextEvent\n---\n<a name=\"finishtextevent.properties\"></a>\n#### Properties\n\n<a name=\"finishtextevent.properties.metal\"></a>\n`metal (String)`\n- The medal recieved after the quiz.\n\n### QuizFinishEvent\n---\n<a name=\"quizfinishevent.properties\"></a>\n#### Properties\n<a name=\"quizfinishevent.properties.client\"></a>\n`client (Kahoot)`\n- The client attached to the event.\n\n<a name=\"quizfinishevent.properties.quiz\"></a>\n`quiz (Quiz)`\n- The quiz attached to the event.\n\n<a name=\"quizfinishevent.properties.players\"></a>\n`players (Number)`\n- The number of players on the quiz.\n\n<a name=\"quizfinishevent.properties.quizID\"></a>\n`quizID (String)`\n- The ID of the quiz.\n- This is **ONLY** sent at the end of the quiz.\n\n<a name=\"quizfinishevent.properties.rank\"></a>\n`rank (Number)`\n- The client's ranking on the quiz.\n\n<a name=\"quizfinishevent.properties.correct\"></a>\n`correct (Number)`\n- The number of questions that were scored correct.\n\n<a name=\"quizfinishevent.properties.incorrect\"></a>\n`incorrect (Number)`\n- The number of questions that were scored incorrect.\n\n#### All events have a .rawEvent property, which contains the raw information from Kahoot.\n\n---\n<a name=\"qa\"></a>\n## Q and A\n<a name=\"qa.proxies\"></a>\n### Using Proxies\nThis package (**V1.2.12+**) now has support for use of proxies. This will request the session information using the proxy, but the websocket will still be directly connected.\nProxies can either be a **String** or an **Object** like so:\n```js\nconst proxy1 = \"http://cors-server.example.com/\";\nconst proxy2 = {\n proxy: \"http://other-server.example.com/path/\",\n options: {\n headers: {\n \"X-Requested-With\": \"foobar\"\n },\n method: \"POST\"\n },\n nopath: true\n};\n```\n#### Example Usage:\n```js\nconst kahootJS = require(\"kahoot.js-updated\");\nconst bots = [];\nfor(let i = 0; i < 10; ++i){\n let client;\n if(Math.round(Math.random())){\n client = new kahootJS(proxy1);\n }else{\n client = new kahootJS(proxy2);\n }\n client.join(pin);\n bots.push(client);\n}\n```\n#### The Proxy Option\nProxies must be in this format in order to work:<br/>\n`https://sub.domain.top/<path>/<query>`\n- The information is requested by appending the proxy to the start of the url:<br>\n`\"https://sub.domain.top/path/\" + \"https://kahoot.it/reserve/session/12345/?12418\"`\n- This can be prevented by using the nopath option.\n\nThe options is the [HTTP Request Options](https://nodejs.org/api/http.html#http_http_request_options_callback), which should only be used if the proxy service requires special headers to work. You can also set the method used.\n\n**Proxies are only used to specify HTTP requests for the tokens and for challenge games. If the websocket connection is blocked, you need to use a proxy/vpn for your server.**\n" }, { "alpha_fraction": 0.5314401388168335, "alphanum_fraction": 0.5385395288467407, "avg_line_length": 39.24489974975586, "blob_id": "3c2a12bcab8e25bf3bb187ce92080433feacc2aa", "content_id": "4e27f08c4539ce97ca77dc92f9673abb87e18c58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1972, "license_type": "permissive", "max_line_length": 111, "num_lines": 49, "path": "/KahootPY/src/modules/backup.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "import asyncio\nimport json\nfrom ..assets.LiveRequestData import LiveRequestData\n\nloop = asyncio.get_event_loop()\n\ndef main(self):\n async def requestRecoveryData():\n await asyncio.sleep(0.5)\n promise = loop.create_future()\n def waiter(r):\n promise.set_result(None)\n await self._send(LiveRequestData(self),waiter)\n self.requestRecoveryData = requestRecoveryData\n def handler(message):\n if message[\"channel\"] == \"/service/player\" and message.get(\"data\") and message[\"data\"].get(\"id\") == 17:\n recover = json.loads(message[\"data\"][\"content\"])\n self.emit(\"RecoveryData\",recover)\n if not len(self.quiz):\n def questionCount(self):\n return (self.get(\"quizQuestionAnswers\") and len(self[\"quizQuestionAnswers\"])) or 10\n self.quiz = {\n \"questionCount\": property(questionCount)\n }\n self.quiz[\"quizQuestionAnswers\"] = recover[\"defaultQuizData\"][\"quizQuestionAnswers\"]\n data = recover[\"data\"]\n state = recover[\"state\"]\n if state == 0:\n pass\n elif state == 1:\n self._emit(\"QuizStart\",data)\n elif state == 2:\n self._emit(\"QuestionReady\",data[\"getReady\"])\n elif state == 3:\n self._emit(\"QuestionStart\",data)\n elif state == 4 or state == 5:\n self._emit(\"TimeUp\",data)\n elif state == 6:\n self._emit(\"QuizEnd\",data)\n elif state == 7:\n self._emit(\"Feedback\")\n self.handlers[\"recovery\"] = handler\n def handler():\n if self.reconnectRecovery:\n loop.create_task(self.requestRecoveryData())\n self.on(\"Joined\",handler)\n def rrd():\n loop.create_task(self.requestRecoveryData())\n self.once(\"NameAccept\",rrd)\n" }, { "alpha_fraction": 0.5153374075889587, "alphanum_fraction": 0.5214723944664001, "avg_line_length": 28.636363983154297, "blob_id": "8feef50a424570cf5cf3460947ebe92adc921ed1", "content_id": "1bc5e99225d10e386edf42a4ccc02bf649a4fee3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 326, "license_type": "permissive", "max_line_length": 48, "num_lines": 11, "path": "/KahootPY/src/assets/LiveRequestData.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from .LiveBaseMessage import LiveBaseMessage\n\nclass LiveRequestData(LiveBaseMessage):\n def __init__(self,client):\n super().__init__(\"/service/controller\",{\n \"id\": 16,\n \"type\": \"message\",\n \"gameid\": client.gameid,\n \"host\": \"kahoot.it\",\n \"content\": \"\"\n })\n" }, { "alpha_fraction": 0.5248618721961975, "alphanum_fraction": 0.5248618721961975, "avg_line_length": 29.16666603088379, "blob_id": "3fcdb7f53dded1f500706a425615c4f3adbad4d4", "content_id": "af4f32d62d0b9c6f5d4282d82e17d2c616d4e059", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 181, "license_type": "permissive", "max_line_length": 41, "num_lines": 6, "path": "/KahootPY/src/assets/LiveBaseMessage.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "class LiveBaseMessage(dict):\n def __init__(self,channel,data=None):\n super().__init__()\n self[\"channel\"] = channel\n if data:\n self[\"data\"] = data\n" }, { "alpha_fraction": 0.6199324131011963, "alphanum_fraction": 0.6385135054588318, "avg_line_length": 39.82758712768555, "blob_id": "329e8e81e312cf83821cd66da37c899c4a5c320c", "content_id": "d4224278bea848aadebe0eedf4057f54c221ed48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1184, "license_type": "permissive", "max_line_length": 111, "num_lines": 29, "path": "/KahootPY/src/modules/feedback.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "import asyncio\nimport time\nimport json\nfrom ..assets.LiveFeedbackPacket import LiveFeedbackPacket\nfrom ..util.errors import SendFailException\n\nloop = asyncio.get_event_loop()\n\ndef main(self):\n def handler(message):\n if message[\"channel\"] == \"/service/player\" and message.get(\"data\") and message[\"data\"].get(\"id\") == 12:\n self.feedbackTime = int(time.time() * 1000)\n self._emit(\"Feedback\",json.loads(message[\"data\"][\"content\"]))\n self.handlers[\"feedback\"] = handler\n async def sendFeedback(fun,learn,recommend,overall):\n if str(self.gameid)[0] == \"0\":\n raise \"Cannot send feedback in Challenges\"\n wait = int(time.time() * 1000) - self.feedbackTime\n if wait < 500:\n await asyncio.sleep((500 - wait) / 1000)\n promise = loop.create_future()\n def waiter(result):\n if not result or not result.get(\"successful\"):\n promise.set_exception(SendFailException(result))\n else:\n promise.set_result(result)\n await self._send(LiveFeedbackPacket(self,fun,learn,recommend,overall),waiter)\n return promise\n self.sendFeedback = sendFeedback\n" }, { "alpha_fraction": 0.6351351141929626, "alphanum_fraction": 0.6385135054588318, "avg_line_length": 41.28571319580078, "blob_id": "13b18a2fc6b66460b2f4d94c27189567f81b4458", "content_id": "b88f31f6f842329e0b41fa41d3077d3c4daf66af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "permissive", "max_line_length": 110, "num_lines": 7, "path": "/KahootPY/src/modules/questionReady.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from json import loads\n\ndef main(self):\n def handler(message):\n if message[\"channel\"] == \"/service/player\" and message.get(\"data\") and message[\"data\"].get(\"id\") == 1:\n self._emit(\"QuestionReady\",loads(message[\"data\"][\"content\"]))\n self.handlers[\"QuestionReady\"] = handler\n" }, { "alpha_fraction": 0.5677225589752197, "alphanum_fraction": 0.5688148736953735, "avg_line_length": 39.241756439208984, "blob_id": "b1c1fd37a2917880aa37f5fba858c82f780cf3b0", "content_id": "1d5862f58f8e09659f05707c71787fd5caee55fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3662, "license_type": "permissive", "max_line_length": 209, "num_lines": 91, "path": "/KahootPY/__init__.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "import time, asyncio, importlib, ssl, json, inspect\nfrom pymitter import EventEmitter\nfrom aiocometd import Client\nfrom numbers import Number\nfrom .src.util.token import resolve\nfrom user_agent import generate_user_agent as UserAgent\n\nclass KahootClient(EventEmitter):\n def __init__(self):\n super().__init__()\n self.classes = {}\n self.connected = False\n self.data = {}\n self.gameid = None\n self.handlers = {}\n self.loggingMode = False\n self.name = None\n self.reconnectRecovery = None\n self.settings = {}\n self.socket = None\n self.twoFactorResetTime = None\n self.userAgent = UserAgent()\n self.quiz = {}\n for module in (\"answer\",\"backup\",\"extraData\",\"feedback\",\"gameReset\",\"main\",\"nameAccept\",\"podium\",\"questionEnd\",\"questionReady\",\"questionStart\",\"quizEnd\",\"quizStart\",\"teamAccept\",\"teamTalk\",\"timeOver\"):\n f = getattr(importlib.import_module(f\".src.modules.{module}\",\"KahootPY\"),\"main\")\n f(self)\n async def join(self,pin,name=None,team=[\"Player 1\",\"Player 2\",\"Player 3\",\"Player 4\"]):\n self.name = name\n loop = asyncio.get_event_loop()\n future = loop.create_future()\n async def go():\n self.gameid = pin\n data = await resolve(self.gameid,self)\n self.settings.update(data[\"data\"])\n token = data[\"token\"]\n client = Client(f\"wss://kahoot.it/cometd/{self.gameid}/{token}\")\n self.socket = client\n await client.open()\n await client.subscribe(\"/service/controller\")\n await client.subscribe(\"/service/status\")\n await client.subscribe(\"/service/player\")\n await self._send(self.classes[\"LiveJoinPacket\"](self,name))\n async for message in client:\n # Handle messages\n self._message(message)\n await client.close()\n loop.create_task(go())\n return await future\n def _message(self,message):\n if self.loggingMode:\n d = json.dumps(message)\n print(f\"RECV: {d}\")\n for i in self.handlers:\n if inspect.iscoroutinefunction(self.handlers[i]):\n loop = asyncio.get_event_loop()\n loop.create_task(self.handlers[i](message))\n else:\n self.handlers[i](message)\n async def _send(self,message,callback=None):\n if self.loggingMode:\n d = json.dumps(message)\n print(f\"SEND: {d}\")\n if self.socket and not self.socket.closed:\n success = True\n try:\n c = message[\"channel\"]\n m = message.get(\"data\")\n await self.socket.publish(c,m)\n except Exception as e:\n success = False\n if not callable(callback):\n return\n if success:\n callback(True)\n else:\n callback(False)\n async def leave(self,safe=False):\n await self._send(self.classes[\"LiveLeavePacket\"](self))\n def _emit(self,evt,payload=None):\n if not self.quiz:\n self.quiz = {}\n if payload and payload.get(\"quizQuestionAnswers\"):\n self.quiz[\"quizQuestionAnswers\"] = payload[\"quizQuestionAnswers\"]\n if payload and not payload.get(\"questionIndex\") is None:\n if not self.quiz.get(\"currentQuestion\"):\n self.quiz[\"currentQuestion\"] = {}\n self.quiz[\"currentQuestion\"].update(payload)\n if not self.connected:\n self.lastEvent = (evt,payload)\n else:\n self.emit(evt,payload)\n" }, { "alpha_fraction": 0.40429043769836426, "alphanum_fraction": 0.41749176383018494, "avg_line_length": 29.299999237060547, "blob_id": "c9d43c3a5e5ea614f0a6bf7110e18bc6f88e1c87", "content_id": "8611de37e44a1a9b8320d02e1fe7a1aa44983877", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 606, "license_type": "permissive", "max_line_length": 50, "num_lines": 20, "path": "/KahootPY/src/assets/LiveReconnectPacket.py", "repo_name": "boiimakillu/KahootPY", "src_encoding": "UTF-8", "text": "from .LiveBaseMessage import LiveBaseMessage\nimport json\n\nclass LiveReconnectPacket(LiveBaseMessage):\n def __init__(self,client,pin,cid):\n super().__init__(\"/service/controller\",{\n \"gameid\": str(pin),\n \"host\": \"kahoot.it\",\n \"content\": json.dumps({\n \"device\": {\n \"userAgent\": client.userAgent,\n \"screen\": {\n \"width\": 1980,\n \"height\": 1080\n }\n }\n }),\n \"cid\": str(cid),\n \"type\": \"relogin\"\n })\n" } ]
25
markzeng893/python
https://github.com/markzeng893/python
f3579a391eeb24de35239b8dcd20f6a636b79a0a
0a339338bbc44054413f80095a637204f273086c
7260614053c245b629fd5a0a1be4579544f16a05
refs/heads/master
2023-08-12T07:59:14.642854
2021-09-14T09:00:04
2021-09-14T09:00:04
406,294,507
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6973684430122375, "alphanum_fraction": 0.7302631735801697, "avg_line_length": 16, "blob_id": "2819fb22487d8520b65b36e52f92d6b11cf3faad", "content_id": "fccb5feec00c56e4cea436edc1078cf7756f6124", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 35, "num_lines": 9, "path": "/.py", "repo_name": "markzeng893/python", "src_encoding": "UTF-8", "text": "import numpy as np\nimport scipy.io\nimport matplotlib.pyplot as plt\n\n\nimage = train_x[0]\nimage = np.reshape(image, (32, 32))\nplt.imshow(image)\nplt.show()" }, { "alpha_fraction": 0.5891048312187195, "alphanum_fraction": 0.6033397316932678, "avg_line_length": 24.907800674438477, "blob_id": "1a1b671f4767fc4617c870d4cd3ff16ccfd05455", "content_id": "89ae32b9b3c4e65f0bd185e2b9b900016118ef53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3653, "license_type": "no_license", "max_line_length": 103, "num_lines": 141, "path": "/nn.py", "repo_name": "markzeng893/python", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom util import *\n# do not include any more libraries here!\n# do not put any code outside of functions!\n\n# Q 2.1.2\n# initialize b to 0 vector\n# b should be a 1D array, not a 2D array with a singleton dimension\n# we will do XW + b. \n# X be [Examples, Dimensions]\ndef initialize_weights(in_size,out_size,params,name=''):\n #W, b = None, None\n W = np.random.uniform(-1.0, 1.0, (in_size, out_size)) * ( np.sqrt(6) / np.sqrt(in_size + out_size))\n b = np.zeros(out_size)\n \n params['W' + name] = W\n params['b' + name] = b\n\n# Q 2.2.1\n# x is a matrix\n# a sigmoid activation function\ndef sigmoid(x):\n res = 1.0 / (1.0 + np.exp(-x))\n return res\n\n# Q 2.2.1\ndef forward(X,params,name='',activation=sigmoid):\n \"\"\"\n Do a forward pass\n\n Keyword arguments:\n X -- input vector [Examples x D]\n params -- a dictionary containing parameters\n name -- name of the layer\n activation -- the activation function (default is sigmoid)\n \"\"\"\n #pre_act, post_act = None, None\n # get the layer parameters\n W = params['W' + name]\n b = params['b' + name]\n\n pre_act = (X @ W + b)\n post_act = activation(pre_act)\n\n \n\n # store the pre-activation and post-activation values\n # these will be important in backprop\n params['cache_' + name] = (X, pre_act, post_act)\n\n return post_act\n\n# Q 2.2.2 \n# x is [examples,classes]\n# softmax should be done for each row\ndef softmax(x):\n ans = np.zeros(x.shape)\n for i in range(x.shape[0]):\n c = np.max(x[i])\n ans[i] = np.exp(x[i] - c) / np.sum(np.exp(x[i] - c)) \n\n return ans\n\n# Q 2.2.3\n# compute total loss and accuracy\n# y is size [examples,classes]\n# probs is size [examples,classes]\ndef compute_loss_and_acc(y, probs):\n\n #loss, acc = None, None\n count = 0\n loss = -np.sum(y * np.log(probs))\n #print (y[0], probs[0])\n for i in range (y.shape[0]):\n if (np.argmax(y[i]) == np.argmax(probs[i])):\n count += 1\n\n acc = count / y.shape[0]\n return loss, acc \n\n# we give this to you\n# because you proved it\n# it's a function of post_act\ndef sigmoid_deriv(post_act):\n res = post_act*(1.0-post_act)\n return res\n\n# Q 2.3.1\ndef backwards(delta,params,name='',activation_deriv=sigmoid_deriv):\n \"\"\"\n Do a backwards pass\n\n Keyword arguments:\n delta -- errors to backprop\n params -- a dictionary containing parameters\n name -- name of the layer\n activation_deriv -- the derivative of the activation_func\n \"\"\"\n grad_X, grad_W, grad_b = None, None, None\n # everything you may need for this layer\n W = params['W' + name]\n b = params['b' + name]\n X, pre_act, post_act = params['cache_' + name]\n # your code here\n # do the derivative through activation first\n # then compute the derivative W,b, and X\n\n deriv = activation_deriv(post_act)\n grad_X = np.zeros(X.shape)\n grad_W = np.zeros(W.shape)\n\n loss_y = delta * deriv\n for i in range(X.shape[0]):\n grad_W += np.dot(X[i].reshape(-1, 1), loss_y[i].reshape(1, -1))\n \n grad_X = np.dot(delta, W.T)\n grad_b = np.sum(loss_y, axis=0)\n\n\n # store the gradients\n params['grad_W' + name] = grad_W\n params['grad_b' + name] = grad_b\n return grad_X\n\n# Q 2.4.1\n# split x and y into random batches\n# return a list of [(batch1_x,batch1_y)...]\ndef get_random_batches(x,y,batch_size):\n batches = []\n shuffle = np.arange(x.shape[0])\n np.random.shuffle(shuffle)\n x = x[shuffle]\n y = y[shuffle]\n n = int(x.shape[0] / batch_size)\n x = np.array_split(x, n)\n y = np.array_split(y, n)\n for i in range(n):\n batches.append((x[i], y[i]))\n\n \n return batches\n" }, { "alpha_fraction": 0.6324408650398254, "alphanum_fraction": 0.6573953628540039, "avg_line_length": 30.79338836669922, "blob_id": "db6f1474cbfe44f97db31b20aa2e3629249ee4a9", "content_id": "9cfe7af4a1dfd67f9ca3c6c65636d17c8ec2c292", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3847, "license_type": "no_license", "max_line_length": 92, "num_lines": 121, "path": "/test_3.py", "repo_name": "markzeng893/python", "src_encoding": "UTF-8", "text": "import numpy as np\nimport scipy.io\nimport scipy\nfrom nn import *\nimport matplotlib.pyplot as plt\nfrom matplotlib import transforms\nimport pickle\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nimport string\n\ntrain_data = scipy.io.loadmat('../data/nist36_train.mat')\nvalid_data = scipy.io.loadmat('../data/nist36_valid.mat')\ntest_data = scipy.io.loadmat('../data/nist36_test.mat')\n\ntrain_x, train_y = train_data['train_data'], train_data['train_labels']\nvalid_x, valid_y = valid_data['valid_data'], valid_data['valid_labels']\ntest_x, test_y = test_data['test_data'], test_data['test_labels']\n\nmax_iters = 50\n# pick a batch size, learning rate\nbatch_size = 20\nlearning_rate = 5e-3 \nhidden_size = 64\n\n#img = train_x[0]\n#img = np.reshape(img, (32,32))\n#plt.imshow(img)\n#plt.show()\n\nbatches = get_random_batches(train_x,train_y,batch_size)\nbatch_num = len(batches)\n\nparams = {}\n\n# initialize layers here\n\ninitialize_weights(1024,64,params,'layer1')\ninitialize_weights(64,36,params,'output')\n\n# with default settings, you should get loss < 150 and accuracy > 80%\nfor itr in range(max_iters):\n total_loss = 0\n total_acc = 0\n avg_acc = 0\n for xb,yb in batches:\n # forward\n\n post_act = forward(xb, params, 'layer1', sigmoid)\n post_act = forward(post_act, params, 'output', softmax)\n\n # loss\n\n loss, acc = compute_loss_and_acc(yb, post_act)\n\n # be sure to add loss and accuracy to epoch totals \n\n total_loss += loss / batch_num\n total_acc += acc\n avg_acc = total_acc / batch_num\n\n # backward\n\n delta1 = post_act\n delta1[np.arange(post_act.shape[0]),np.argmax(yb, axis=1)] -= 1\n delta2 = backwards(delta1, params, 'output', linear_deriv)\n backwards(delta2, params, 'layer1', sigmoid_deriv)\n\n # apply gradient\n\n params['boutput'] -= learning_rate * params['grad_boutput']\n params['Woutput'] -= learning_rate * params['grad_Woutput']\n params['Wlayer1'] -= learning_rate * params['grad_Wlayer1']\n params['blayer1'] -= learning_rate * params['grad_blayer1']\n\n # training loop can be exactly the same as q2!\n\n #forward pass for validation data\n valid_post_act = forward(valid_x, params, 'layer1', sigmoid)\n valid_post_act = forward(valid_post_act, params, 'output', softmax)\n valid_loss, valid_acc = compute_loss_and_acc(valid_y, valid_post_act) \n\n if itr % 10 == 0 or itr == max_iters - 1:\n print(\"itr: {:02d} \\t loss: {:.2f} \\t acc : {:.2f}\".format(itr,total_loss,avg_acc))\n print(\"Validation loss: \", valid_loss, \" Validation accuracy: \", valid_acc)\n# run on validation set and report accuracy! should be above 75%\n\nprint('Validation accuracy: ',valid_acc)\n#if True: # view the data\n #for crop in xb:\n #plt.imshow(crop.reshape(32,32).T)\n #plt.show()\nsaved_params = {k:v for k,v in params.items() if '_' not in k}\nwith open('q3_weights.pickle', 'wb') as handle:\n pickle.dump(saved_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n# Q3.3\ntest_post_act = forward(test_x, params, 'layer1', sigmoid)\ntest_post_act = forward(test_post_act, params, 'output', softmax)\ntest_loss, test_acc = compute_loss_and_acc(test_y, test_post_act)\n\n# Q3.4\nconfusion_matrix = np.zeros((train_y.shape[1],train_y.shape[1]))\n\nsum = 0\n\nfor i in range(test_y.shape[0]):\n post_act_max = np.argmax(test_post_act[i])\n test_max = np.argmax(test_y[i])\n confusion_matrix[post_act_max][test_max] += 1\n\nsum = np.trace(confusion_matrix) \ntest_post_act_acc = sum / 1800\nprint (\"Test accuracy: \", test_post_act_acc)\n\n\n\nplt.imshow(confusion_matrix,interpolation='nearest')\nplt.grid(True)\nplt.xticks(np.arange(36),string.ascii_uppercase[:26] + ''.join([str(_) for _ in range(10)]))\nplt.yticks(np.arange(36),string.ascii_uppercase[:26] + ''.join([str(_) for _ in range(10)]))\nplt.show()\n" } ]
3
CleysonPH/school_api_drf
https://github.com/CleysonPH/school_api_drf
85e1b39246d8f205c3634dfdc083b779d3dc765c
9461bdfbcaf67379a05d97eb3e935e031022aefe
ee1d3fca5726527412ccc2e3fe71f85d9be2d1a1
refs/heads/master
2022-12-03T15:19:52.696336
2020-08-08T05:15:58
2020-08-08T05:15:58
285,954,069
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6060606241226196, "alphanum_fraction": 0.747474730014801, "avg_line_length": 19, "blob_id": "08cf56c90db651dbb70f24b2bbde33bcddbc17e3", "content_id": "85e1705a27d051b05e4d5b68854f4f7c6ed357cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 99, "license_type": "no_license", "max_line_length": 27, "num_lines": 5, "path": "/requirements.txt", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "Django==3.1\ndj-database-url==0.5.0\npython-decouple==3.3\ndjangorestframework==3.11.1\nMarkdown==3.2.2" }, { "alpha_fraction": 0.765194833278656, "alphanum_fraction": 0.765194833278656, "avg_line_length": 30.557376861572266, "blob_id": "53801d5a2419c6e260d1928ad8fa8d1a1399fd6d", "content_id": "ec0dacd483d254ceae1c935d7f4652077c01b5c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1925, "license_type": "no_license", "max_line_length": 76, "num_lines": 61, "path": "/school/views.py", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "from rest_framework import viewsets, generics\nfrom rest_framework.authentication import BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom school.models import Student, Course, Registration\nfrom school.serializer import (\n StudentSerializer,\n CourseSerializer,\n RegistrationSerializer,\n StudentRegistrationsSerializer,\n CourseRegistrationsSerializer,\n)\n\n\nclass StudentViewSet(viewsets.ModelViewSet):\n \"\"\"Show all students in the database\"\"\"\n\n queryset = Student.objects.all()\n serializer_class = StudentSerializer\n authentication_classes = [BasicAuthentication]\n permission_classes = [IsAuthenticated]\n\n\nclass CourseViewSet(viewsets.ModelViewSet):\n \"\"\"Show all courses in the database\"\"\"\n\n queryset = Course.objects.all()\n serializer_class = CourseSerializer\n authentication_classes = [BasicAuthentication]\n permission_classes = [IsAuthenticated]\n\n\nclass RegistrationViewSet(viewsets.ModelViewSet):\n \"\"\"Show all registrations in the the database\"\"\"\n\n queryset = Registration.objects.all()\n serializer_class = RegistrationSerializer\n authentication_classes = [BasicAuthentication]\n permission_classes = [IsAuthenticated]\n\n\nclass StudentRegistrations(generics.ListAPIView):\n \"\"\"Show the registrations of a specific student\"\"\"\n\n serializer_class = StudentRegistrationsSerializer\n authentication_classes = [BasicAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get_queryset(self):\n return Registration.objects.filter(student_id=self.kwargs.get(\"pk\"))\n\n\nclass CourseRegistrations(generics.ListAPIView):\n \"\"\"Show the students of a specific course\"\"\"\n\n serializer_class = CourseRegistrationsSerializer\n authentication_classes = [BasicAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get_queryset(self):\n return Registration.objects.filter(course_id=self.kwargs.get(\"pk\"))\n" }, { "alpha_fraction": 0.585971474647522, "alphanum_fraction": 0.5934202075004578, "avg_line_length": 24.983871459960938, "blob_id": "c2a026b31936922db9355c2d640417c93f7b59c4", "content_id": "7523c66abc1e8afbcec1e5d3247da6e8d08deb6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1621, "license_type": "no_license", "max_line_length": 80, "num_lines": 62, "path": "/school/models.py", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Student(models.Model):\n name = models.CharField(\"Nome\", max_length=50)\n rg = models.CharField(\"RG\", max_length=9)\n cpf = models.CharField(\"CPF\", max_length=11)\n birth_date = models.DateField(\n \"Data de Nascimento\", auto_now=False, auto_now_add=False\n )\n\n class Meta:\n verbose_name = \"Aluno\"\n verbose_name_plural = \"Alunos\"\n\n def __str__(self):\n return self.name\n\n\nclass Course(models.Model):\n LEVEL_CHOICES = ((\"B\", \"Básico\"), (\"I\", \"Intermediário\"), (\"A\", \"Avançado\"))\n\n code = models.CharField(\"Código\", max_length=10, unique=True)\n description = models.CharField(\"Descrição\", max_length=100)\n level = models.CharField(\n \"Nível\",\n max_length=1,\n choices=LEVEL_CHOICES,\n blank=False,\n null=False,\n default=\"B\",\n )\n\n class Meta:\n verbose_name = \"Curso\"\n verbose_name_plural = \"Cursos\"\n\n def __str__(self):\n return self.code\n\n\nclass Registration(models.Model):\n PERIOD_CHOICES = (\n (\"M\", \"Matutino\"),\n (\"V\", \"Verpertino\"),\n (\"N\", \"Noturno\"),\n )\n\n student = models.ForeignKey(\n \"school.Student\", verbose_name=\"Aluno\", on_delete=models.CASCADE\n )\n course = models.ForeignKey(\n \"school.Course\", verbose_name=\"Curso\", on_delete=models.CASCADE\n )\n period = models.CharField(\"Período\", max_length=1, choices=PERIOD_CHOICES)\n\n class Meta:\n verbose_name = \"Matrícula\"\n verbose_name_plural = \"Matrículas\"\n\n def __str__(self):\n return f\"{self.student} - {self.course}\"\n" }, { "alpha_fraction": 0.6680161952972412, "alphanum_fraction": 0.6680161952972412, "avg_line_length": 26.962265014648438, "blob_id": "2c238da56239d5b5d5d2093b2c77f61766f85ba3", "content_id": "cf8c7b194055a45beaa2ce3ac41a939558fef938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1482, "license_type": "no_license", "max_line_length": 84, "num_lines": 53, "path": "/school/serializer.py", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom rest_framework.validators import UniqueTogetherValidator\n\nfrom school.models import Student, Course, Registration\n\n\nclass StudentSerializer(serializers.ModelSerializer):\n class Meta:\n model = Student\n fields = \"__all__\"\n\n\nclass CourseSerializer(serializers.ModelSerializer):\n class Meta:\n model = Course\n fields = \"__all__\"\n\n\nclass RegistrationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Registration\n fields = \"__all__\"\n validators = [\n UniqueTogetherValidator(\n queryset=Registration.objects.all(),\n fields=[\"student\", \"period\"],\n message=\"A student can be only registered in one course per period\",\n )\n ]\n\n\nclass StudentRegistrationsSerializer(serializers.ModelSerializer):\n course = serializers.ReadOnlyField(source=\"course.description\")\n period = serializers.SerializerMethodField()\n\n class Meta:\n model = Registration\n fields = [\"course\", \"period\"]\n\n def get_period(self, obj):\n return obj.get_period_display()\n\n\nclass CourseRegistrationsSerializer(serializers.ModelSerializer):\n student = serializers.ReadOnlyField(source=\"student.name\")\n period = serializers.SerializerMethodField()\n\n class Meta:\n model = Registration\n fields = [\"student\", \"period\"]\n\n def get_period(self, obj):\n return obj.get_period_display()\n" }, { "alpha_fraction": 0.673652708530426, "alphanum_fraction": 0.6766467094421387, "avg_line_length": 26.83333396911621, "blob_id": "2fb6ef9bcd4a8f70573a16b8dd445dd1053e004e", "content_id": "df78939c2228e9015d386b1bb0e92e4352b5d2dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "no_license", "max_line_length": 60, "num_lines": 24, "path": "/school/admin.py", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom school.models import Student, Course, Registration\n\n\[email protected](Student)\nclass StudentModelAdmin(admin.ModelAdmin):\n list_display = [\"id\", \"name\", \"rg\", \"cpf\", \"birth_date\"]\n list_display_links = [\"id\", \"name\"]\n search_fields = [\"name\"]\n list_per_page = 20\n\n\[email protected](Course)\nclass CourseModelAdmin(admin.ModelAdmin):\n list_display = [\"id\", \"code\", \"description\"]\n list_display_links = [\"id\", \"code\"]\n search_fields = [\"code\"]\n\n\[email protected](Registration)\nclass RegistrationModelAdmin(admin.ModelAdmin):\n list_display = [\"id\", \"student\", \"course\", \"period\"]\n list_display_links = [\"id\"]\n" }, { "alpha_fraction": 0.6939024329185486, "alphanum_fraction": 0.6939024329185486, "avg_line_length": 24.625, "blob_id": "5500e979859b85dc3c7ddcebdc50f94c824bc1e8", "content_id": "fe8acc0334303d752c18df4de35f1a84846b72b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 820, "license_type": "no_license", "max_line_length": 78, "num_lines": 32, "path": "/school/urls.py", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "from django.urls import path, include\nfrom rest_framework import routers\n\nfrom school.views import (\n StudentViewSet,\n CourseViewSet,\n RegistrationViewSet,\n StudentRegistrations,\n CourseRegistrations,\n)\n\n\nrouter = routers.DefaultRouter()\nrouter.register(\"students\", StudentViewSet, basename=\"student\")\nrouter.register(\"courses\", CourseViewSet, basename=\"course\")\nrouter.register(\"registrations\", RegistrationViewSet, basename=\"registration\")\n\n\napp_name = \"school-api\"\nurlpatterns = [\n path(\"\", include(router.urls)),\n path(\n \"students/<int:pk>/registrations/\",\n StudentRegistrations.as_view(),\n name=\"student-registations-list\",\n ),\n path(\n \"courses/<int:pk>/registrations/\",\n CourseRegistrations.as_view(),\n name=\"course-registations-list\",\n ),\n]\n" }, { "alpha_fraction": 0.5855555534362793, "alphanum_fraction": 0.6066666841506958, "avg_line_length": 38.130435943603516, "blob_id": "5c7e72319f49b77972979b6656825392d42db979", "content_id": "cccc0ca609848cf5db5142aea177513fec64a83a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 901, "license_type": "no_license", "max_line_length": 151, "num_lines": 23, "path": "/school/migrations/0003_registration.py", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1 on 2020-08-07 22:02\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('school', '0002_course'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Registration',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('period', models.CharField(choices=[('M', 'Matutino'), ('V', 'Verpertino'), ('N', 'Noturno')], max_length=1, verbose_name='Período')),\n ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='school.course', verbose_name='Curso')),\n ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='school.student', verbose_name='Aluno')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5154525637626648, "alphanum_fraction": 0.5419425964355469, "avg_line_length": 33.846153259277344, "blob_id": "48a55c7c88616ab2958aa60c51ee08685a5d7c25", "content_id": "36aeec4888f86103cd3e16a11ba539ad4400de31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 913, "license_type": "no_license", "max_line_length": 163, "num_lines": 26, "path": "/school/migrations/0002_course.py", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1 on 2020-08-07 17:47\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('school', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Course',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('code', models.CharField(max_length=10, verbose_name='Código')),\n ('description', models.CharField(max_length=100, verbose_name='Descrição')),\n ('level', models.CharField(choices=[('B', 'Básico'), ('I', 'Intermediário'), ('A', 'Avançado')], default='B', max_length=1, verbose_name='Nível')),\n ],\n options={\n 'verbose_name': 'Curso',\n 'verbose_name_plural': 'Cursos',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5621761679649353, "alphanum_fraction": 0.6088082790374756, "avg_line_length": 21.705883026123047, "blob_id": "465c8ab919ba47a94b12a8754c85f19593d3954c", "content_id": "0e5d222d2132da5f91ca4404a0110ea5e76979d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 388, "license_type": "no_license", "max_line_length": 87, "num_lines": 17, "path": "/school/migrations/0004_auto_20200807_1907.py", "repo_name": "CleysonPH/school_api_drf", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1 on 2020-08-07 22:07\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('school', '0003_registration'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='registration',\n options={'verbose_name': 'Matrícula', 'verbose_name_plural': 'Matrículas'},\n ),\n ]\n" } ]
9
JamBro22/Speed
https://github.com/JamBro22/Speed
907292665d2fa17db235dc799e988364dcccca03
6b1ff8cc9cd586f03f7b07bfa88e84457597e6e9
8a3d88a5e4fb3139a983881391aa84821b904b90
refs/heads/master
2021-03-18T11:28:14.902580
2021-01-17T11:01:49
2021-01-17T11:01:49
247,071,463
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6606574654579163, "alphanum_fraction": 0.6659597158432007, "avg_line_length": 36.720001220703125, "blob_id": "70b41faafc92a636a9c69126c04155a821a28133", "content_id": "20fdc7e82248d43777d81d974e070e7008d70deb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 943, "license_type": "no_license", "max_line_length": 76, "num_lines": 25, "path": "/main.py", "repo_name": "JamBro22/Speed", "src_encoding": "UTF-8", "text": "# calculate demerit points based on speed\ndef calculate_demerit_points_for_speeding(current_speed, speed_limit):\n demerit_points = int((current_speed - speed_limit)/5)\n\n # if the speed travelled is less than the speed limit, return ok\n if current_speed <= speed_limit:\n return \"OK\"\n # if the speed travelled is more than the speed limit, return the points\n elif current_speed > speed_limit:\n # if the points exceed 12, return \"Time to go to jail\"\n if demerit_points > 12:\n return \"Time to go to jail!\"\n return \"Points: {}\".format(demerit_points)\n\n\n# run from main\nif __name__ == \"__main__\":\n # get current speed\n speed = int(input(\"Enter your current speed: \"))\n # get speed limit\n allowed_speed = int(input(\"Enter the speed limit: \"))\n\n # calculate demerit points and print results\n points = calculate_demerit_points_for_speeding(speed, allowed_speed)\n print(points)\n" }, { "alpha_fraction": 0.7757009267807007, "alphanum_fraction": 0.7757009267807007, "avg_line_length": 25.75, "blob_id": "7841e27bbd0260a894178bfc6cca33d0cc0fc3bc", "content_id": "54771e0cba6e06d9beb42d7690a196d3fe307d0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 107, "license_type": "no_license", "max_line_length": 79, "num_lines": 4, "path": "/README.md", "repo_name": "JamBro22/Speed", "src_encoding": "UTF-8", "text": "# Speed\nCreating a programme that evaluates the speeds of vehicles and their penalties.\n\n### Run from main\n" }, { "alpha_fraction": 0.6601123809814453, "alphanum_fraction": 0.6685393452644348, "avg_line_length": 34.70000076293945, "blob_id": "92b334e2da00275fd0028618e13210d6f31c2c79", "content_id": "3514ff0ec675137b9e34d73d42c30f6105973adb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 72, "num_lines": 10, "path": "/SPEEDY.py", "repo_name": "JamBro22/Speed", "src_encoding": "UTF-8", "text": "speed = int(input(\"What was your average speed in km/h? \\n\"))\nallowed_speed = int(input(\"What was the allowed speed on the road? \\n\"))\ndemerit_points = (speed - allowed_speed)/5\nif speed <= allowed_speed:\n print(\"OK\")\nif speed > allowed_speed:\n print(\"Points:\" )\n print(int(demerit_points))\nif demerit_points > 12:\n print(\"Time to go to jail!\")" } ]
3
jonasbn/Sublime-DarkLightModeSwitch
https://github.com/jonasbn/Sublime-DarkLightModeSwitch
08ab225747f9ef9c726f34ad874fdfc5a7a4dfcd
17b9053a730e414f574a32fb36d868f612747ca3
e31867f671b53bf27cb15bf74ad1562bd28baa4f
refs/heads/master
2021-01-12T00:23:28.754843
2017-01-12T06:46:16
2017-01-12T06:46:16
78,716,864
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6776315569877625, "alphanum_fraction": 0.6776315569877625, "avg_line_length": 32.77777862548828, "blob_id": "9d5dd8df12f8b27a069aab701f5e87fc90637aee", "content_id": "c1136e88ac4a6638a8a2addd861f0d67b629a67c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 913, "license_type": "permissive", "max_line_length": 95, "num_lines": 27, "path": "/DarkLightModeSwitch.py", "repo_name": "jonasbn/Sublime-DarkLightModeSwitch", "src_encoding": "UTF-8", "text": "import sublime\nimport sublime_plugin\n\n# view.run_command('DarkLightModeSwitch')\n# view.run_command('darklightmodeswitch')\n\nclass DarklightmodeswitchCommand(sublime_plugin.TextCommand):\n\n def run(self, edit):\n\n settings = sublime.load_settings(\"Preferences.sublime-settings\")\n current_color_scheme = settings.get(\"color_scheme\")\n\n if current_color_scheme == \"Packages/User/SublimeLinter/Solarized (Dark) (SL).tmTheme\":\n color_scheme = \"Packages/User/SublimeLinter/Solarized (Light) (SL).tmTheme\"\n else:\n color_scheme = \"Packages/User/SublimeLinter/Solarized (Dark) (SL).tmTheme\"\n\n settings.set(\"color_scheme\", color_scheme)\n \n sublime.save_settings(\"Preferences.sublime-settings\")\n\n self.log_to_console(\"current colour scheme: ´\" + current_color_scheme)\n\n def log_to_console(self, arg):\n arg = str(arg)\n print(arg)\n" } ]
1
kpaczewska/Sprawdzian
https://github.com/kpaczewska/Sprawdzian
7b4c3be3d639a1ae27b0d4add7908523c24b676f
69db5876c22b9c42e7bce6159f178de3cb83735f
6c5fb2a641cceb8547e8bf51bd88ff79a9f57c8e
refs/heads/master
2022-06-16T14:45:39.598182
2020-05-09T07:37:55
2020-05-09T07:37:55
262,511,354
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7338709831237793, "alphanum_fraction": 0.75, "avg_line_length": 19.83333396911621, "blob_id": "e1f83ef972a53bde8fb07a1924f89512669c7b66", "content_id": "aaecff24a651eb27796ef90d48c929c2bb80d17a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 126, "license_type": "no_license", "max_line_length": 41, "num_lines": 6, "path": "/spr_01.py", "repo_name": "kpaczewska/Sprawdzian", "src_encoding": "UTF-8", "text": "# Zadanie1\n# listy, słowniki, tuple, zbiory, stringi\n\n#Zadanie 2\n# mutowalne: słowniki, listy\n# niemutowalne: stringi, tuple" } ]
1
mattlavis-transform/create_quota_sheet
https://github.com/mattlavis-transform/create_quota_sheet
b81c2c9e9119f0e5d036aa2f004ef2f294735207
a5be12d3d0227e54e8f6135fae4becaed9c06ab9
84c85778b84e1f97c6563a61f73d9f9d08a2bbf0
refs/heads/master
2020-04-04T23:21:53.672936
2018-11-06T11:56:29
2018-11-06T11:56:29
156,356,165
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7033274173736572, "alphanum_fraction": 0.7043434381484985, "avg_line_length": 45.869049072265625, "blob_id": "3ae4efe14922b61ae9a3a76c26500e7500d667e6", "content_id": "aa454e0333bf53297e14c601f289ef7c8d1b0e49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3937, "license_type": "no_license", "max_line_length": 273, "num_lines": 84, "path": "/measure.py", "repo_name": "mattlavis-transform/create_quota_sheet", "src_encoding": "UTF-8", "text": "import functions\n\nclass measure(object):\n\tdef __init__(self, sMeasureTypeDescription, sMeasureTypeID, sMeasureSID, sGeographicalAreaID, sGoodsNomenclatureItemID, sAdditionalCodeTypeID, sAdditionalCodeID, sValidityStartDate, sValidityEndDate, sOrderNumber, sAdditionalCodeDescription, sGeographicalAreaDescription):\n\t\t# Get parameters from instantiator\n\t\tself.sMeasureTypeDescription = sMeasureTypeDescription\n\t\tself.sMeasureTypeID = sMeasureTypeID\n\t\tself.sMeasureSID = sMeasureSID\n\t\tself.sGeographicalAreaID = sGeographicalAreaID\n\t\tself.sGoodsNomenclatureItemID = sGoodsNomenclatureItemID\n\t\tself.sAdditionalCodeTypeID = sAdditionalCodeTypeID\n\t\tself.sAdditionalCodeID = sAdditionalCodeID\n\t\tself.sValidityStartDate = str(sValidityStartDate)\n\t\tself.sValidityEndDate = str(sValidityEndDate)\n\t\tself.sOrderNumber = sOrderNumber\n\t\tself.sAdditionalCodeDescription = sAdditionalCodeDescription\n\t\tself.sGeographicalAreaDescription = sGeographicalAreaDescription\n\t\tself.sMeasureTypeFull = \"\"\n\t\tself.sAdditionalCodeFull = \"\"\n\t\tself.sGeographicalAreaFull = \"\"\n\t\tself.sValidityDates = \"\"\n\t\tself.sOrderNumber = \"\"\n\t\tself.sComponents = \"\"\n\t\tself.sComponentsExcel = \"\"\n\t\tself.sConditions = \"\"\n\t\tself.sConditionsExcel = \"\"\n\t\tself.sFootnotes = \"\"\n\n\t\tself.sDelimiter = \"|\"\n\t\tself.sDelimiterExcel = \"\\n\"\n\t\t\n\t\tself.concatenateFields()\n\t\t\n\tdef concatenateFields(self):\n\t\tself.sMeasureTypeFull = \"[\" + str(self.sMeasureTypeID) + \"] \" + str(self.sMeasureTypeDescription)\n\t\tif str(self.sAdditionalCodeTypeID) == \"None\":\n\t\t\tself.sAdditionalCodeFull = \"\"\n\t\telse:\n\t\t\tself.sAdditionalCodeFull = \"[\" + str(self.sAdditionalCodeTypeID) + str(self.sAdditionalCodeID) + \"] \" + str(self.sAdditionalCodeDescription)\n\t\tself.sGeographicalAreaFull = \"[\" + str(self.sGeographicalAreaID) + \"] \" + str(self.sGeographicalAreaDescription)\n\t\t\n\t\tif self.sValidityStartDate != \"None\":\n\t\t\t#self.sValidityDates = self.sValidityStartDate\n\t\t\tself.sValidityDates = functions.fmtDate2(self.sValidityStartDate)\n\t\t\tif self.sValidityEndDate != \"None\":\n\t\t\t\tself.sValidityDates += \" - \" + functions.fmtDate2(self.sValidityEndDate)\n\n\tdef addComponents(self, lstMeasureComponents):\n\t\tfor mc in lstMeasureComponents:\n\t\t\tif mc.sMeasureSID == self.sMeasureSID:\n\t\t\t\tself.sComponents += mc.sExpression\n\t\t\t\tself.sComponents += \" \" + self.sDelimiter + \" \"\n\n\t\tself.sComponents = self.sComponents.strip()\n\t\tself.sComponents = self.sComponents.strip(self.sDelimiter)\n\t\tself.sComponents = self.sComponents.strip()\n\t\t\n\t\tself.sComponentsExcel = self.sComponents.replace(\" \" + self.sDelimiter + \" \", self.sDelimiterExcel)\n\n\tdef addFootnotes(self, lstFootnotes):\n\t\tfor f in lstFootnotes:\n\t\t\tif f.sMeasureSID == self.sMeasureSID:\n\t\t\t\tself.sFootnotes += f.sFootnoteFull\n\t\t\t\tself.sFootnotes += \" \" + self.sDelimiter + \" \"\n\t\tself.sFootnotes = self.sFootnotes.strip()\n\t\tself.sFootnotes = self.sFootnotes.strip(self.sDelimiter)\n\t\tself.sFootnotes = self.sFootnotes.strip()\n\n\t\tself.sComponentsExcel = self.sComponents.replace(\" \" + self.sDelimiter + \" \", self.sDelimiterExcel)\n\n\tdef addConditions(self, lstConditions):\n\t\ti = 1\n\t\tfor c in lstConditions:\n\t\t\tif c.sMeasureSID == self.sMeasureSID:\n\t\t\t\tself.sConditions += c.sConditionFull.replace(\"#\", str(i))\n\t\t\t\tself.sConditions += self.sDelimiter + self.sDelimiter\n\t\t\t\ti = i + 1\n\t\tself.sConditions = self.sConditions.strip()\n\t\tself.sConditions = self.sConditions.strip(self.sDelimiter)\n\t\tself.sConditions = self.sConditions.strip()\n\n\t\tself.sConditionsExcel = self.sConditions.replace(\" \" + self.sDelimiter + \" \", self.sDelimiterExcel)\n\t\tself.sConditionsExcel = self.sConditionsExcel.replace(self.sDelimiter, self.sDelimiterExcel)\n\t\tself.sConditionsExcel = self.sConditionsExcel.replace(\" : \" , \"\\n\")\n" }, { "alpha_fraction": 0.6377373933792114, "alphanum_fraction": 0.6631332039833069, "avg_line_length": 33.639060974121094, "blob_id": "bbabffe95e57ecb33d87bd2702e0f0088a726136", "content_id": "87d57db1db56c3cf9a28b4667eca1246aa390154", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22170, "license_type": "no_license", "max_line_length": 304, "num_lines": 640, "path": "/create_quota_single_sheet.py", "repo_name": "mattlavis-transform/create_quota_sheet", "src_encoding": "UTF-8", "text": "import psycopg2\nfrom docx import Document\nfrom docx.shared import Inches\nfrom docx.shared import Cm\nfrom docx.oxml.shared import OxmlElement, qn\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\nfrom docx.enum.text import WD_TAB_ALIGNMENT\nfrom docx.enum.text import WD_TAB_LEADER\nfrom docx.shared import Pt\nfrom docx.enum.style import WD_STYLE_TYPE\nimport os\nimport sys\nimport codecs\nfrom datetime import datetime\n\ndef writeOrderNumberDocument(sOrderNumber):\n\tglobal conn\n\tglobal lRow\n\t\n\t#sOrderNumber = \"090025\"\n\tprint (\"Creating document for quota \" + sOrderNumber)\n\tsFilename = \"C:\\\\projects\\\\create_quota_sheet\\\\word\\\\\" + sOrderNumber + \".docx\"\n\tdocument = Document()\n\tsections = document.sections\n\tmargin = 1.5\n\tfor section in sections:\n\t\tsection.top_margin = Cm(margin)\n\t\tsection.bottom_margin = Cm(margin)\n\t\tsection.left_margin = Cm(margin)\n\t\tsection.right_margin = Cm(margin)\n\t\n\t\t\n\t# Create styles\n\tmy_styles = document.styles\n\tp_style = my_styles.add_style('Normal in table', WD_STYLE_TYPE.PARAGRAPH)\n\tp_style.base_style = my_styles['Normal']\n\tp_style.font.name = \"Calibri\"\n\tp_style.paragraph_format.space_before = Pt(2)\n\tp_style.paragraph_format.space_after = Pt(2)\n\t\n\tp_style2 = my_styles.add_style('Small in table', WD_STYLE_TYPE.PARAGRAPH)\n\tp_style2.base_style = my_styles['Normal in table']\n\tp_style2.font.size = Pt(9)\n\t\n\th1_style = my_styles[\"Heading 1\"]\n\th1_style.paragraph_format.space_before = Pt(12)\n\t\n\t\n\t# The main title\n\tdocument.add_heading(\"Quota order number \" + sOrderNumber, level = 0)\n\t\n\t# Background information\n\tdocument.add_heading(\"About this quota\", level = 1)\n\tp = document.add_paragraph('The table below contains background information provided by Defra.')\n\tp.style = p_style2\n\tsSQL = \"\"\"SELECT * FROM ml.quota_extension WHERE quota_order_number_id = '\"\"\" + sOrderNumber + \"\"\"'\"\"\"\n\t\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trw = cur.fetchone()\n\ttable = document.add_table(rows = 10, cols = 2)\n\ttable.style = \"Table Grid\"\n\n\ttable.rows[0].cells[0].text = \"Defra description\"\n\ttable.rows[1].cells[0].text = \"Country\"\n\ttable.rows[2].cells[0].text = \"Application period\"\n\ttable.rows[3].cells[0].text = \"Overall quota volume\"\n\ttable.rows[4].cells[0].text = \"Unit\"\n\ttable.rows[5].cells[0].text = \"Method\"\n\ttable.rows[6].cells[0].text = \"Type\"\n\ttable.rows[7].cells[0].text = \"Mechanism\"\n\ttable.rows[8].cells[0].text = \"Sector\"\n\ttable.rows[9].cells[0].text = \"Comments\"\n\n\tif not(rw is None):\n\t\ttable.rows[0].cells[1].text = m_str(rw[1])\n\t\ttable.rows[1].cells[1].text = m_str(rw[3])\n\t\ttable.rows[2].cells[1].text = m_str(rw[4])\n\t\ttable.rows[3].cells[1].text = \"{:,}\".format(rw[5])\n\t\ttable.rows[4].cells[1].text = m_str(rw[6])\n\t\ttable.rows[5].cells[1].text = m_str(rw[7])\n\t\ttable.rows[6].cells[1].text = m_str(rw[8])\n\t\ttable.rows[7].cells[1].text = m_str(rw[9])\n\t\ttable.rows[8].cells[1].text = m_str(rw[10])\n\t\ttable.rows[9].cells[1].text = m_str(rw[11])\n\n\tfor i in range(10):\n\t\tr = table.rows[i].cells\n\t\tr[0].paragraphs[0].style = p_style2\n\t\tr[1].paragraphs[0].style = p_style2\n\t\n\n\tset_col_widths(table, (Cm(4.6), Cm(14)))\n\t\t\n\t# Regulations\n\tdocument.add_heading(\"Regulation(s)\", level = 1)\n\tp = document.add_paragraph('The table below lists the EU regulation(s) that has/have given rise to this quota and its associated measures.')\n\tp.style = p_style2\n\tsSQL = \"\"\"SELECT DISTINCT LEFT(m.measure_generating_regulation_id, 7) as regulation_id, r.title\n\tFROM measures m , ml.ml_regulation_titles r \n\tWHERE LEFT(m.measure_generating_regulation_id, 7) = r.regulation_id\n\tAND m.ordernumber IS NOT NULL\n\tAND m.validity_start_date > (CURRENT_DATE - 365)\n\tAND ordernumber = '\"\"\" + sOrderNumber + \"\"\"'\n\tORDER BY 1;\"\"\"\n\t\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trws = cur.fetchall()\n\ttable = document.add_table(rows = cur.rowcount + 1, cols = 2)\n\ttable.style = \"Light List\"\n\thdr_cells = table.rows[0].cells\n\tset_repeat_table_header(table.rows[0])\n\thdr_cells[0].text = 'EU Regulation ID'\n\thdr_cells[1].text = 'Title'\n\thdr_cells[0].paragraphs[0].style = p_style2\n\thdr_cells[1].paragraphs[0].style = p_style2\n\ti = 1\n\tfor rw in rws:\n\t\tregulation_id = rw[0]\n\t\ttitle = rw[1]\n\t\tr = table.rows[i].cells\n\t\tr[0].text = regulation_id\n\t\tr[1].text = title\n\t\tr[0].paragraphs[0].style = p_style2\n\t\tr[1].paragraphs[0].style = p_style2\n\t\ti = i + 1\n\n\tset_col_widths(table, (Cm(4), Cm(14.6)))\n\t\t\n\t# Geography\n\tdocument.add_heading(\"Geography\", level = 1)\n\tp = document.add_paragraph('The table below lists the geographies to which the quota applies.')\n\tp.style = p_style2\n\tsSQL = \"\"\"SELECT DISTINCT qono.geographical_area_id, ga.description\n\tFROM quota_order_numbers qon, quota_order_number_origins qono, ml.ml_geographical_areas ga\n\tWHERE qon.quota_order_number_sid = qono.quota_order_number_sid\n\tAND ga.geographical_area_id = qono.geographical_area_id\n\tAND (qono.validity_end_date IS NULL OR qono.validity_end_date > CURRENT_DATE)\n\tAND qon.quota_order_number_id = '\"\"\" + sOrderNumber + \"\"\"'\n\tORDER BY 1;\"\"\"\n\t\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trws = cur.fetchall()\n\ttable = document.add_table(rows = cur.rowcount + 1, cols = 2)\n\ttable.style = \"Light List\"\n\thdr_cells = table.rows[0].cells\n\tset_repeat_table_header(table.rows[0])\n\thdr_cells[0].text = 'Geographical area ID'\n\thdr_cells[1].text = 'Description'\n\thdr_cells[0].paragraphs[0].style = p_style2\n\thdr_cells[1].paragraphs[0].style = p_style2\n\ti = 1\n\tfor rw in rws:\n\t\tgeographical_area_id = rw[0]\n\t\tdescription = rw[1]\n\t\tr = table.rows[i].cells\n\t\tr[0].text = geographical_area_id\n\t\tr[1].text = description\n\t\tr[0].paragraphs[0].style = p_style2\n\t\tr[1].paragraphs[0].style = p_style2\n\t\ti = i + 1\n\n\tset_col_widths(table, (Cm(4), Cm(14.6)))\n\t\t\n\t\n\t# Geographical area exclusions\n\tdocument.add_heading(\"Geographical area exclusions\", level = 2)\n\tsSQL = \"\"\"\n\tSELECT qono.geographical_area_id, gaparent.description as origin, gachild.geographical_area_id as excluded_orgin_id, gachild.description as excluded_orgin\n\tFROM quota_order_numbers qon, quota_order_number_origin_exclusions qonoe, quota_order_number_origins qono, ml.ml_geographical_areas gaparent, ml.ml_geographical_areas gachild\n\tWHERE qonoe.quota_order_number_origin_sid = qono.quota_order_number_origin_sid\n\tAND qon.quota_order_number_sid = qono.quota_order_number_sid\n\tAND qono.geographical_area_id = gaparent.geographical_area_id\n\tAND qonoe.excluded_geographical_area_sid = gachild.geographical_area_sid\n\tAND (qono.validity_end_date IS NULL OR qono.validity_end_date > CURRENT_DATE)\n\tAND qon.quota_order_number_id = '\"\"\" + sOrderNumber + \"\"\"' ORDER BY 1, 3;\n\t\"\"\"\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trws = cur.fetchall()\n\tif cur.rowcount > 0:\n\t\tp = document.add_paragraph('The table below lists the exclusions from the aforementioned geographical areas.')\n\t\tp.style = p_style2\n\t\ttable = document.add_table(rows = cur.rowcount + 1, cols = 2)\n\t\ttable.style = \"Light List\"\n\t\thdr_cells = table.rows[0].cells\n\t\tset_repeat_table_header(table.rows[0])\n\t\thdr_cells[0].text = 'Parent area ID'\n\t\thdr_cells[1].text = 'Excluded area ID'\n\t\thdr_cells[0].paragraphs[0].style = p_style2\n\t\thdr_cells[1].paragraphs[0].style = p_style2\n\t\ti = 1\n\t\tfor rw in rws:\n\t\t\tgeographical_area_id1 = rw[0]\n\t\t\tdescription1 = rw[1]\n\t\t\tgeographical_area_id2 = rw[2]\n\t\t\tdescription2 = rw[3]\n\t\t\tr = table.rows[i].cells\n\t\t\tr[0].text = geographical_area_id1 + \" - \" + description1\n\t\t\tr[1].text = geographical_area_id2 + \" - \" + description2\n\t\t\tr[0].paragraphs[0].style = p_style2\n\t\t\tr[1].paragraphs[0].style = p_style2\n\t\t\ti = i + 1\n\t\t\n\t\tset_col_widths(table, (Cm(9.3), Cm(9.3)))\n\telse:\n\t\tp = document.add_paragraph('No geographical exclusions.')\n\t\tp.style = p_style2\n\t\t\n\n\t# Commodity codes\n\tdocument.add_heading(\"Commodity codes\", level = 1)\n\tp = document.add_paragraph('The table below lists the commodity codes to which this quota applies.')\n\tp.style = p_style2\n\tsSQL = \"\"\"\n\tSELECT DISTINCT m.goods_nomenclature_item_id, n.description\n\tFROM measures m, ml.ml_nomenclature_flat n\n\tWHERE n.product_line_suffix = '80'\n\tAND n.goods_nomenclature_item_id = m.goods_nomenclature_item_id\n\tAND m.ordernumber = '\"\"\" + sOrderNumber + \"\"\"'\n\tAND (m.validity_end_date IS NULL OR m.validity_end_date > CURRENT_DATE)\n\tAND m.validity_start_date > (CURRENT_DATE - 365)\n\tORDER BY 1;\n\t\"\"\"\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trws = cur.fetchall()\n\ttable = document.add_table(rows = cur.rowcount + 1, cols = 2)\n\ttable.style = \"Light List\"\n\thdr_cells = table.rows[0].cells\n\tset_repeat_table_header(table.rows[0])\n\thdr_cells[0].text = 'Commodity code'\n\thdr_cells[1].text = 'Description'\n\thdr_cells[0].paragraphs[0].style = p_style2\n\thdr_cells[1].paragraphs[0].style = p_style2\n\ti = 1\n\tfor rw in rws:\n\t\tcommcode = rw[0]\n\t\tdescription = rw[1]\n\t\tr = table.rows[i].cells\n\t\tr[0].text = commcode\n\t\tr[1].text = description\n\t\tr[0].paragraphs[0].style = p_style2\n\t\tr[1].paragraphs[0].style = p_style2\n\t\ti = i + 1\n\n\tset_col_widths(table, (Cm(3.5), Cm(15.1)))\n\t\n\t# Full list of measures\n\tdocument.add_heading(\"Measures and duties\", level = 1)\n\tsSQL = \"\"\"\n\tSELECT DISTINCT m.measure_type_id, mtd.description as measure_type, m.goods_nomenclature_item_id, mc.duty_expression_id, mc.duty_amount,\n\tmc.monetary_unit_code, mc.measurement_unit_code, mc.measurement_unit_qualifier_code, m.ordernumber, m.measure_sid\n\tFROM measures m, measure_components mc, measure_type_descriptions mtd, base_regulations r\n\tWHERE m.measure_sid = mc.measure_sid\n\tAND m.measure_generating_regulation_id = r.base_regulation_id\n\tAND m.measure_type_id = mtd.measure_type_id\n\tAND m.ordernumber IS NOT NULL\n\tAND r.effective_end_date IS NULL\n\tAND m.ordernumber = '\"\"\" + sOrderNumber + \"\"\"'\n\tAND m.stopped_flag = 'f'\n\tAND (m.validity_end_date > CURRENT_DATE OR m.validity_end_date IS NULL)\n\tORDER BY ordernumber, goods_nomenclature_item_id, duty_expression_id;\n\t\"\"\"\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\tif cur.rowcount == 0:\n\t\tp = document.add_paragraph('There are no current measures - please check with the policy owner (the measures may have just expired).')\n\t\tp.style = p_style2\n\telse:\n\t\tp = document.add_paragraph('The table below shows the measures that area applicable to goods in quota. In most cases, the duty will be 0%, however on occasion duties remain applicable. Please also be aware that on occasion, more than one measure type may apply to a single order number.')\n\t\tp.style = p_style2\n\t\trws = cur.fetchall()\n\t\ttable = document.add_table(rows = 1, cols = 3)\n\t\ttable.style = \"Light List\"\n\t\thdr_cells = table.rows[0].cells\n\t\tset_repeat_table_header(table.rows[0])\n\t\thdr_cells[0].text = 'Commodity code'\n\t\thdr_cells[1].text = 'Measure type'\n\t\thdr_cells[2].text = 'Applicable duty'\n\t\thdr_cells[0].paragraphs[0].style = p_style2\n\t\thdr_cells[1].paragraphs[0].style = p_style2\n\t\thdr_cells[2].paragraphs[0].style = p_style2\n\t\trdList = []\n\t\tfor rw in rws:\n\t\t\tmeasure_type_id = rw[0]\n\t\t\tmeasure_type = rw[1]\n\t\t\tgoods_nomenclature_item_id = rw[2]\n\t\t\tduty_expression_id = rw[3]\n\t\t\tduty_amount = str(rw[4])\n\t\t\tmonetary_unit_code = m_str(rw[5])\n\t\t\tmeasurement_unit_code = m_str(rw[6])\n\t\t\tmeasurement_unit_qualifier_code = m_str(rw[7])\n\t\t\tmeasure_sid = rw[9]\n\t\t\tdex = getDuty(duty_expression_id, duty_amount, monetary_unit_code, measurement_unit_code, measurement_unit_qualifier_code)\n\t\t\trdList.append([measure_type_id, measure_type, goods_nomenclature_item_id, dex, measure_sid, \"Active\"])\n\t\t\t\n\t\tmeasure_sid_old = rdList[0][4]\n\t\tfor x in range(1, len(rdList) - 1):\n\t\t\tmeasure_sid = rdList[x][4]\n\t\t\tif measure_sid == measure_sid_old:\n\t\t\t\trdList[x - 1][3] += rdList[x][3]\n\t\t\t\trdList[x][5] = \"Inactive\"\n\t\t\t\t\n\t\t\tmeasure_sid_old = measure_sid\n\n\t\tfor x in range(0, len(rdList) - 1):\n\t\t\tif rdList[x][5] == \"Active\":\n\t\t\t\n\t\t\t\trx = table.add_row()\n\t\t\t\trc = rx.cells\n\n\t\t\t\trc[0].text = rdList[x][2]\n\t\t\t\trc[1].text = rdList[x][0] + \" [\" + rdList[x][1] + \"]\"\n\t\t\t\trc[2].text = rdList[x][3]\n\t\t\t\t\n\t\t\t\trc[0].paragraphs[0].style = p_style2\n\t\t\t\trc[1].paragraphs[0].style = p_style2\n\t\t\t\trc[2].paragraphs[0].style = p_style2\n\t\tset_col_widths(table, (Cm(3.5), Cm(8.3), Cm(6.8)))\n\n\t###############################################################\n\t# Get the definition description\n\tdocument.add_heading(\"Quota definition description\", level = 1)\n\tp = document.add_paragraph(\"\"\"The table cell below identifies the description that the EU has applied to the quota definition periods listed below. There may be multiple descriptions, however to aid readability, only one is included. Where there are multiple descriptions, they are usually the same.\"\"\")\n\tp.style = p_style2\n\tsSQL = \"\"\"SELECT DISTINCT qd.description\n\tFROM measures m, quota_definitions qd, quota_order_numbers qon\n\tWHERE m.ordernumber = qd.quota_order_number_id\n\tAND m.ordernumber = qon.quota_order_number_id\n\tAND m.validity_start_date > (CURRENT_DATE - 365)\n\tAND qd.validity_start_date > (CURRENT_DATE - 365)\n\tAND m.ordernumber = '\"\"\" + sOrderNumber + \"\"\"'\n\tORDER BY 1 DESC LIMIT 1;\"\"\"\n\t\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trws = cur.fetchall()\n\n\ttable = document.add_table(rows = 1, cols = 1)\n\ttable.style = \"Table Grid\"\n\tfor rw in rws:\n\t\tdescription = rw[0]\n\t\tr = table.rows[0].cells\n\t\tr[0].text = description\n\t\tr[0].paragraphs[0].style = p_style2\n\n\t\n\n\t###############################################################\n\t# Get the definition periods\n\tdocument.add_heading(\"Quota definition periods\", level = 1)\n\tp = document.add_paragraph('The table below lists the quota definition periods applicable to this quota.')\n\tp.style = p_style2\n\tsSQL = \"\"\"SELECT DISTINCT qd.validity_start_date as defintion_start_date, qd.validity_end_date as defintion_end_date,\n\tqd.initial_volume, qd.measurement_unit_code, qd.maximum_precision, qd.critical_state, qd.critical_threshold, qd.monetary_unit_code, qd.measurement_unit_qualifier_code\n\tFROM measures m, quota_definitions qd, quota_order_numbers qon\n\tWHERE m.ordernumber = qd.quota_order_number_id\n\tAND m.ordernumber = qon.quota_order_number_id\n\tAND m.validity_start_date > (CURRENT_DATE - 365)\n\tAND qd.validity_start_date > (CURRENT_DATE - 365)\n\tAND m.ordernumber = '\"\"\" + sOrderNumber + \"\"\"'\n\tORDER BY 1, 2;\"\"\"\n\t\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trows_definitions = cur.fetchall()\n\n\ttable = document.add_table(rows = cur.rowcount + 1, cols = 7)\n\ttable.style = \"Light List\"\n\thdr_cells = table.rows[0].cells\n\tset_repeat_table_header(table.rows[0])\n\thdr_cells[0].text = 'Dates'\n\thdr_cells[1].text = 'Period type'\n\thdr_cells[2].text = 'Volume'\n\thdr_cells[3].text = 'Unit'\n\thdr_cells[4].text = 'Monetary unit'\n\thdr_cells[5].text = 'Critical state'\n\thdr_cells[6].text = 'Critical threshold'\n\tfor x in range(7):\n\t\thdr_cells[x].paragraphs[0].style = p_style2\n\n\ti = 0\n\tfor rw in rows_definitions:\n\t\ti = i + 1\n\t\tdefinition_start_date = fmtDate(rw[0])\n\t\tdefinition_end_date = fmtDate(rw[1])\n\t\tinitial_volume = \"{:,}\".format(rw[2])\n\t\tmeasurement_unit_code = m_str(rw[3])\n\t\tcritical_state = rw[5]\n\t\tcritical_threshold = m_str(rw[6])\n\t\tmonetary_unit_code = m_str(rw[7])\n\t\tmeasurement_unit_qualifier_code = m_str(rw[8])\n\t\t\n\t\tr = table.rows[i].cells\n\t\tr[0].text = definition_start_date + \" to \" + definition_end_date\n\t\tr[1].text = describe_period(rw[0], rw[1])\n\t\tr[2].text = str(initial_volume)\n\t\tr[3].text = measurement_unit_code + \" \" + measurement_unit_qualifier_code\n\t\tr[4].text = monetary_unit_code\n\t\tr[5].text = critical_state\n\t\tr[6].text = critical_threshold\n\n\t\tfor x in range(7):\n\t\t\tr[x].paragraphs[0].style = p_style2\n\n\tset_col_widths(table, (Cm(3.5), Cm(2.7), Cm(2.9), Cm(2.5), Cm(2.5), Cm(2.5), Cm(2.5)))\n\n\t###############################################################\n\t# Get the quota associations\n\tdocument.add_heading(\"Quota associations\", level = 1)\n\tsSQL = \"\"\"SELECT relation_type, coefficient, qdm.quota_order_number_id as main_id, qds.quota_order_number_id as sub_id\n\tFROM quota_associations qa, quota_definitions qdm, quota_definitions qds\n\tWHERE qa.main_quota_definition_sid = qdm.quota_definition_sid\n\tAND qa.sub_quota_definition_sid = qds.quota_definition_sid\n\tAND (qdm.quota_order_number_id = '\"\"\" + sOrderNumber + \"\"\"'\n\tOR qds.quota_order_number_id = '\"\"\" + sOrderNumber + \"\"\"')\n\tAND qdm.validity_end_date > CURRENT_DATE\n\tAND qds.validity_end_date > CURRENT_DATE\n\t\"\"\"\n\t\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trws = cur.fetchall()\n\tif cur.rowcount > 0:\n\t\tp = document.add_paragraph('The table below lists the quota associations applicable to this quota.')\n\t\tp.style = p_style2\n\t\ttable = document.add_table(rows = cur.rowcount + 1, cols = 4)\n\t\ttable.style = \"Light List\"\n\t\thdr_cells = table.rows[0].cells\n\t\tset_repeat_table_header(table.rows[0])\n\t\thdr_cells[0].text = 'Main order number'\n\t\thdr_cells[1].text = 'Sub order number'\n\t\thdr_cells[2].text = 'Relation type'\n\t\thdr_cells[3].text = 'Coefficient'\n\t\tfor x in range(4):\n\t\t\thdr_cells[x].paragraphs[0].style = p_style\n\n\t\ti = 0\n\t\tfor rw in rws:\n\t\t\ti = i + 1\n\t\t\trelation_type = rw[0]\n\t\t\tcoefficient = \"{:,}\".format(rw[1])\n\t\t\tmain_id = rw[2]\n\t\t\tsub_id = rw[3]\n\t\t\t\n\t\t\tr = table.rows[i].cells\n\t\t\tr[0].text = main_id\n\t\t\tr[1].text = sub_id\n\t\t\tr[2].text = relation_type\n\t\t\tr[3].text = coefficient\n\t\t\t\n\t\t\tfor x in range(4):\n\t\t\t\tr[x].paragraphs[0].style = p_style\n\telse:\n\t\tp = document.add_paragraph('There are no quota associations applicable to this quota.')\n\t\tp.style = p_style2\n\t\t\n\t###############################################################\n\t# Get the suspension periods\n\tdocument.add_heading(\"Suspension periods\", level = 1)\n\tp = document.add_paragraph('If you know of any quota suspension periods that are due to take effect, please enter the dates in the table below')\n\tp.style = p_style2\n\ttable = document.add_table(rows = 3, cols = 3)\n\ttable.style = \"Light List\"\n\thdr_cells = table.rows[0].cells\n\tset_repeat_table_header(table.rows[0])\n\thdr_cells[0].text = 'Suspension start'\n\thdr_cells[1].text = 'Suspension end'\n\thdr_cells[2].text = 'Reason'\n\tfor x in range(3):\n\t\tfor y in range(3):\n\t\t\trw = table.rows[y].cells\n\t\t\trw[x].paragraphs[0].style = p_style2\n\n\tdocument.save(sFilename)\n\t#sys.exit()\n\n\ndef m_str(s):\n\tif s is None:\n\t\treturn \"\"\n\telse:\n\t\treturn str(s)\n\t\ndef describe_period(definition_start_date, definition_end_date):\n\tperiod_length = definition_end_date - definition_start_date\n\tif period_length == 365:\n\t\tsOut = \"Annual\"\n\telif period_length in (28, 30, 31):\n\t\tsOut = \"One month\"\n\telif period_length in (88, 89, 90, 91, 92):\n\t\tsOut = \"Quarter\"\n\telse:\n\t\tiDayStart = definition_start_date.day\n\t\tiDayEnd = definition_end_date.day\n\t\tif iDayStart == 1 and iDayEnd >= 28:\n\t\t\tiMonthStart = definition_start_date.month\n\t\t\tiMonthEnd = definition_end_date.month\n\n\t\t\tiYearStart = definition_start_date.year\n\t\t\tiYearEnd = definition_end_date.year\n\n\t\t\tiMonths = (iMonthEnd - iMonthStart) + (12 * (iYearEnd - iYearStart)) + 1\n\t\t\tsOut = str(iMonths) + \" months\"\n\t\telse:\n\t\t\tsOut = \"Custom period\"\n\n\treturn sOut\n\ndef set_repeat_table_header(row):\n tr = row._tr\n trPr = tr.get_or_add_trPr()\n tblHeader = OxmlElement('w:tblHeader')\n tblHeader.set(qn('w:val'), \"true\")\n trPr.append(tblHeader)\n return row\n\ndef set_col_widths(table, widths):\n for row in table.rows:\n for idx, width in enumerate(widths):\n row.cells[idx].width = width\n\t\ndef fmtDate(d):\n\ttry:\n\t\td = datetime.strftime(d, '%d-%m-%y')\n\texcept:\n\t\td = \"\"\n\treturn d\n\ndef getDuty(duty_expression_id, duty_amount, monetary_unit_code, measurement_unit_code, measurement_unit_qualifier_code):\n\tif duty_expression_id == \"01\": # % or amount\n\t\treturn duty_amount + \"%\"\n\telif duty_expression_id in (\"04\", \"19\"): # + % or amount\n\t\ts = \" + \" + duty_amount\n\t\tif monetary_unit_code != \"\":\n\t\t\ts = s + \" \" + monetary_unit_code + \" / \" + getMeasurementUnit(measurement_unit_code)\n\t\t\tif measurement_unit_qualifier_code != \"\":\n\t\t\t\ts = s + \" \" + measurement_unit_qualifier_code\n\t\treturn s\n\telif duty_expression_id == \"14\": # + reduced agricultural component\n\t\treturn \" + reduced agricultural component\"\n\telif duty_expression_id in (\"17\", \"35\"): # Maximum\n\t\ts = \" up to a maximum of \" + duty_amount\n\t\tif monetary_unit_code != \"\":\n\t\t\ts = s + \" \" + monetary_unit_code + \" / \" + getMeasurementUnit(measurement_unit_code)\n\t\t\tif measurement_unit_qualifier_code != \"\":\n\t\t\t\ts = s + \" \" + measurement_unit_qualifier_code\n\t\treturn s\n\telif duty_expression_id == \"25\": # + reduced additional duty on sugar\n\t\treturn \" + reduced additional duty on sugar\"\n\telif duty_expression_id == \"29\": # + reduced additional duty on flour\n\t\treturn \" + reduced additional duty on flour\"\n\n\treturn duty_expression_id\n\t\n\ndef getMeasurementUnit(s):\n\tif s == \"ASV\":\n\t\treturn \"% vol/hl\" # 3302101000\n\tif s == \"NAR\":\n\t\treturn \"p/st\"\n\telif s == \"CCT\":\n\t\treturn \"ct/l\"\n\telif s == \"CEN\":\n\t\treturn \"100 p/st\"\n\telif s == \"CTM\":\n\t\treturn \"c/k\"\n\telif s == \"DTN\":\n\t\treturn \"100 kg\"\n\telif s == \"GFI\":\n\t\treturn \"gi F/S\"\n\telif s == \"GRM\":\n\t\treturn \"g\"\n\telif s == \"HLT\":\n\t\treturn \"hl\" # 2209009100\n\telif s == \"HMT\":\n\t\treturn \"100 m\" # 3706909900\n\telif s == \"KGM\":\n\t\treturn \"kg\"\n\telif s == \"KLT\":\n\t\treturn \"1,000 l\"\n\telif s == \"KMA\":\n\t\treturn \"kg met.am.\"\n\telif s == \"KNI\":\n\t\treturn \"kg N\"\n\telif s == \"KNS\":\n\t\treturn \"kg H2O2\"\n\telif s == \"KPH\":\n\t\treturn \"kg KOH\"\n\telif s == \"KPO\":\n\t\treturn \"kg K2O\"\n\telif s == \"KPP\":\n\t\treturn \"kg P2O5\"\n\telif s == \"KSD\":\n\t\treturn \"kg 90 % sdt\"\n\telif s == \"KSH\":\n\t\treturn \"kg NaOH\"\n\telif s == \"KUR\":\n\t\treturn \"kg U\"\n\telif s == \"LPA\":\n\t\treturn \"l alc. 100%\"\n\telif s == \"LTR\":\n\t\treturn \"l\"\n\telif s == \"MIL\":\n\t\treturn \"1,000 p/st\"\n\telif s == \"MTK\":\n\t\treturn \"m2\"\n\telif s == \"MTQ\":\n\t\treturn \"m3\"\n\telif s == \"MTR\":\n\t\treturn \"m\"\n\telif s == \"MWH\":\n\t\treturn \"1,000 kWh\"\n\telif s == \"NCL\":\n\t\treturn \"ce/el\"\n\telif s == \"NPR\":\n\t\treturn \"pa\"\n\telif s == \"TJO\":\n\t\treturn \"TJ\"\n\telif s == \"TNE\":\n\t\treturn \"t\" # 1005900020\n\t\t# return \"1000 kg\" # 1005900020\n\telse:\n\t\treturn s\n\t\nconn = psycopg2.connect(\"dbname=trade_tariff_1809 user=postgres password=zanzibar\")\n\nsSQL = \"\"\"SELECT DISTINCT m.ordernumber FROM measures m WHERE m.validity_start_date > (CURRENT_DATE - 365) ORDER BY 1;\"\"\"\ncur = conn.cursor()\ncur.execute(sSQL)\nrows_ordernumbers = cur.fetchall()\nfor rw in rows_ordernumbers:\n\tsOrderNumber = rw[0]\n\t#if sOrderNumber > \"090101\":\n\twriteOrderNumberDocument(sOrderNumber)\n\nconn.close()\n" }, { "alpha_fraction": 0.5932599306106567, "alphanum_fraction": 0.6116116046905518, "avg_line_length": 24.985549926757812, "blob_id": "4c035998d6538cc52ee289e8c6f9dbb65f430c08", "content_id": "d205bd7b2c62f03a397f70733534e20516ed05cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8991, "license_type": "no_license", "max_line_length": 142, "num_lines": 346, "path": "/functions.py", "repo_name": "mattlavis-transform/create_quota_sheet", "src_encoding": "UTF-8", "text": "from __future__ import with_statement\nimport psycopg2\nfrom contextlib import closing\nfrom zipfile import ZipFile, ZIP_DEFLATED\nfrom datetime import datetime\nimport os\nimport sys\nimport codecs\nimport re\n\ndef strNone(s):\n\ts = str(s)\n\tif s == \"None\":\n\t\ts = \"\"\n\treturn (s)\n\ndef fltNone(s):\n\tif s == None:\n\t\ts = 0.00\n\telse:\n\t\ts = float(s)\n\treturn (s)\n\ndef mShorten(s):\n s = s.replace(\"Hectokilogram\", \"100kg\")\n s = s.replace(\"Hectolitre\", \"h1\")\n s = s.replace(\"Minimum\", \"MIN\")\n s = s.replace(\"Maximum\", \"MAX\")\n s = s.replace(\"agricultural component\", \"EA\")\n s = s.replace(\" \", \" \")\n s = s.replace(\" %\", \"%\")\n return (s)\n\n\ndef formatFootnote(s):\n\tsOut = \"\"\n\ta = s.split(\"\\n\")\n\tfor ax in a:\n\t\tax.strip()\n\t\t#print (ax)\n\t\tif len(ax) > 0:\n\t\t\tlChar = ascii(ax[0])\n\t\t\tlChar = ord(ax[0])\n\t\t\tif lChar == 8226:\n\t\t\t\tsStyle = \"ListBulletinTable\"\n\t\t\telse:\n\t\t\t\tsStyle = \"NormalinTable\"\n\t\t\tax = ax.replace(chr(8226) + \"\\t\", \"\")\n\t\t\tax = ax.replace(\" \", \" \")\n\t\t\tsOut += \"<w:p><w:pPr><w:pStyle w:val=\\\"\" + sStyle + \"\\\"/></w:pPr><w:r><w:t>\" + ax + \"</w:t></w:r></w:p>\"\n\treturn (sOut)\n\ndef fmtDate(d):\n\ttry:\n\t\td = datetime.strftime(d, '%d/%m/%y')\n\texcept:\n\t\td = \"\"\n\treturn d\n\ndef fmtDate2(d):\n\td = str(d)\n\td = d[8:10] + \"/\" + d[5:7] + \"/\" + d[0:4]\n\t# d = datetime.strptime(d, '%d/%m/%y')\n\treturn d\n\t\ndef combineDuties(sExisting, sNew, sDutyExpression, sDutyExpressionDescription):\n\ts = \"\"\n\tif sDutyExpression == \"12\":\n\t\ts = sExisting + \" + EA\"\n\telif sDutyExpression == \"21\":\n\t\ts = sExisting + \" + ADSZ\"\n\telif sDutyExpression == \"27\":\n\t\ts = sExisting + \" + ADFM\"\n\telif sDutyExpression == \"15\":\n\t\ts = sExisting + \" MIN \" + sNew\n\telif sDutyExpression == \"17\":\n\t\ts = sExisting + \" MAX \" + sNew\n\telse:\n\t\ts = sExisting + \" + \" + sNew\n\t\n\t#print (sDutyExpression + s + \"IJOII\")\n\treturn s\n\n\ndef getSectionsChapters(conn):\n\tglobal rdSecChap\n\tsSQL = \"\"\"\n\tSELECT LEFT(gn.goods_nomenclature_item_id, 2) as chapter, cs.section_id\n\tFROM chapters_sections cs, goods_nomenclatures gn\n\tWHERE cs.goods_nomenclature_sid = gn.goods_nomenclature_sid\n\tAND gn.producline_suffix = '80'\n\tORDER BY 1\n\t\"\"\"\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trows_sections_chapters = cur.fetchall()\n\trdSecChap = []\n\tfor rd in rows_sections_chapters:\n\t\tsChapter = rd[0]\n\t\tiSection = rd[1]\n\t\n\t\trdSecChap.append([sChapter, iSection, 0])\n\t\t\n\tiLastSection = -1\n\tfor r in rdSecChap:\n\t\tiSection = r[1]\n\t\tif iSection != iLastSection:\n\t\t\tr[2] = 1\n\t\tiLastSection = iSection\n\n\t\ndef getAllMeasurementUnitQualifiers(conn):\n\tglobal rows_qualifiers\n\tsSQL = \"SELECT * FROM measurement_unit_qualifier_descriptions ORDER BY 1;\"\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trows_qualifiers = cur.fetchall()\n\ndef readTemplates(sDocumentType, sOrientation):\n\tglobal sDocumentXML, sHeading1XML, sHeading2XML, sHeading3XML, sHeading3XML, sTableXML, sTableRowXML, sFootnoteTableXML, sFootnoteTableRowXML\n\tglobal sFootnoteReferenceXML, sFootnotesXML, sFootnoteXML, sParaXML, sBulletXML, sBannerXML, sPageBreakXML\n\tpath = \"C:\\\\projects\\\\create_tariff_schedule\\\\xmlcomponents\\\\\"\n\n\t# Main document templates\n\tif sDocumentType == \"classification\":\n\t\tfDocument = open(path + \"document_classification.xml\", \"r\") \n\telse:\n\t\tif sOrientation == \"landscape\":\n\t\t\tfDocument = open(path + \"document_schedule_landscape.xml\", \"r\")\n\t\telse:\n\t\t\tfDocument = open(path + \"document_schedule.xml\", \"r\")\n\tsDocumentXML = fDocument.read()\n\n\t\"\"\"\n\tfTitle = open(path + \"title.xml\", \"r\") \n\tsTitleXML = fTitle.read()\n\t\"\"\"\n\n\tfFootnoteTable = open(path + \"table_footnote.xml\", \"r\") \n\tsFootnoteTableXML = fFootnoteTable.read()\n\n\tfFootnoteTableRow = open(path + \"tablerow_footnote.xml\", \"r\") \n\tsFootnoteTableRowXML = fFootnoteTableRow.read()\n\n\tfHeading1 = open(path + \"heading1.xml\", \"r\") \n\tsHeading1XML = fHeading1.read()\n\n\tfHeading2 = open(path + \"heading2.xml\", \"r\") \n\tsHeading2XML = fHeading2.read()\n\n\tfHeading3 = open(path + \"heading3.xml\", \"r\") \n\tsHeading3XML = fHeading3.read()\n\n\tfPara = open(path + \"paragraph.xml\", \"r\") \n\tsParaXML = fPara.read()\n\n\tfBullet = open(path + \"bullet.xml\", \"r\") \n\tsBulletXML = fBullet.read()\n\n\tfBanner = open(path + \"banner.xml\", \"r\") \n\tsBannerXML = fBanner.read()\n\n\tfPageBreak = open(path + \"pagebreak.xml\", \"r\") \n\tsPageBreakXML = fPageBreak.read()\n\n\tif (sDocumentType == \"classification\"):\n\t\tfTable = open(path + \"table_classification.xml\", \"r\") \n\t\tfTableRow = open(path + \"tablerow_classification.xml\", \"r\") \n\telse:\n\t\tif sOrientation == \"landscape\":\n\t\t\tfTable = open(path + \"table_schedule_landscape.xml\", \"r\") \n\t\t\tfTableRow = open(path + \"tablerow_schedule_landscape.xml\", \"r\") \n\t\telse:\n\t\t\tfTable = open(path + \"table_schedule.xml\", \"r\") \n\t\t\tfTableRow = open(path + \"tablerow_schedule.xml\", \"r\") \n\n\tsTableXML = fTable.read()\n\tsTableRowXML = fTableRow.read()\n\n\tfFootnoteReference = open(path + \"footnotereference.xml\", \"r\") \n\tsFootnoteReferenceXML = fFootnoteReference.read()\n\n\t# Footnote templates\n\tfFootnotes = open(path + \"footnotes.xml\", \"r\") \n\tsFootnotesXML = fFootnotes.read()\n\n\tfFootnote = open(path + \"footnote.xml\", \"r\") \n\tsFootnoteXML = fFootnote.read()\n\ndef getMeasurementUnit(s):\n\tif s == \"ASV\":\n\t\treturn \"% vol/hl\" # 3302101000\n\tif s == \"NAR\":\n\t\treturn \"p/st\"\n\telif s == \"CCT\":\n\t\treturn \"ct/l\"\n\telif s == \"CEN\":\n\t\treturn \"100 p/st\"\n\telif s == \"CTM\":\n\t\treturn \"c/k\"\n\telif s == \"DTN\":\n\t\treturn \"100 kg/net\"\n\telif s == \"GFI\":\n\t\treturn \"gi F/S\"\n\telif s == \"GRM\":\n\t\treturn \"g\"\n\telif s == \"HLT\":\n\t\treturn \"hl\" # 2209009100\n\telif s == \"HMT\":\n\t\treturn \"100 m\" # 3706909900\n\telif s == \"KGM\":\n\t\treturn \"kg\"\n\telif s == \"KLT\":\n\t\treturn \"1,000 l\"\n\telif s == \"KMA\":\n\t\treturn \"kg met.am.\"\n\telif s == \"KNI\":\n\t\treturn \"kg N\"\n\telif s == \"KNS\":\n\t\treturn \"kg H2O2\"\n\telif s == \"KPH\":\n\t\treturn \"kg KOH\"\n\telif s == \"KPO\":\n\t\treturn \"kg K2O\"\n\telif s == \"KPP\":\n\t\treturn \"kg P2O5\"\n\telif s == \"KSD\":\n\t\treturn \"kg 90 % sdt\"\n\telif s == \"KSH\":\n\t\treturn \"kg NaOH\"\n\telif s == \"KUR\":\n\t\treturn \"kg U\"\n\telif s == \"LPA\":\n\t\treturn \"l alc. 100%\"\n\telif s == \"LTR\":\n\t\treturn \"l\"\n\telif s == \"MIL\":\n\t\treturn \"1,000 p/st\"\n\telif s == \"MTK\":\n\t\treturn \"m2\"\n\telif s == \"MTQ\":\n\t\treturn \"m3\"\n\telif s == \"MTR\":\n\t\treturn \"m\"\n\telif s == \"MWH\":\n\t\treturn \"1,000 kWh\"\n\telif s == \"NCL\":\n\t\treturn \"ce/el\"\n\telif s == \"NPR\":\n\t\treturn \"pa\"\n\telif s == \"TJO\":\n\t\treturn \"TJ\"\n\telif s == \"TNE\":\n\t\treturn \"t\" # 1005900020\n\t\t# return \"1000 kg\" # 1005900020\n\telse:\n\t\treturn s\n\ndef addQual2(sSuppUnit, sQual, sQualDesc):\n\tif sQual == \"C\":\n\t\treturn sQualDesc + \" \" + sSuppUnit\n\telse:\n\t\treturn sSuppUnit + \" \" + sQualDesc\t\t\n\ndef getQual(sQual, intention):\n\tsQualDesc = \"\"\n\tif sQual == \"A\":\n\t\t# if intention == \"supplementary\":\n\t\tsQualDesc = \"tot/alc\" # Total alcohol\n\tif sQual == \"C\":\n\t\tif intention == \"supplementary\":\n\t\t\tsQualDesc = \"1 000\" # Total alcohol\n\telif sQual == \"E\":\n\t\tsQualDesc = \"eda\" # net of drained weight\n\telif sQual == \"G\":\n\t\tsQualDesc = \" br\" # Gross\n\telif sQual == \"M\":\n\t\tsQualDesc = \"mas\" # net of dry matter\n\telif sQual == \"P\":\n\t\tsQualDesc = \"/ lactic matter\" # of lactic matter\n\telif sQual == \"R\":\n\t\tsQualDesc = \"std qual\" # of the standard quality\n\telif sQual == \"S\":\n\t\tsQualDesc = \"/ raw sugar\"\n\telif sQual == \"T\":\n\t\tsQualDesc = \"/ dry lactic matter\" # of dry lactic matter\n\telif sQual == \"X\":\n\t\tsQualDesc = \"hl\" # Hectolitre\n\telif sQual == \"Z\":\n\t\tsQualDesc = \"% sacchar.\" # per 1% by weight of sucrose\n\treturn sQualDesc\n\ndef fmtMarkdown(s):\n\tglobal sHeading2XML, sHeading3XML, sParaXML, sBulletXML\n\ts = re.sub(\"<table.*</table>\", \"\", s, flags=re.DOTALL)\n\ts = re.sub(\"<sup>\", \"\", s, flags=re.DOTALL)\n\ts = re.sub(\"</sup>\", \"\", s, flags=re.DOTALL)\n\ts = re.sub(\"_\", \"\\\"\", s, flags=re.DOTALL)\n\tsOut = \"\"\n\ta = s.split(\"\\n\")\n\tfor ax in a:\n\t\tif ax[:2] == \"##\":\n\t\t\tsTemp = sHeading3XML\n\t\t\tsTemp = sTemp.replace(\"{HEADING}\", ax.strip())\n\t\t\tsTemp = sTemp.replace(\"\\.\", \".\")\n\t\t\tsTemp = sTemp.replace(\"##\", \"\")\n\t\t\tsOut += sTemp\n\t\telif ax[:4] == \" * \":\n\t\t\tsTemp = ax.strip()\n\t\t\tsTemp = sTemp.replace(\"* -\", \"\")\n\t\t\tsTemp = sTemp.replace(\"* \", \"\")\n\t\t\tsTemp = sTemp.replace(\"\\.\", \".\")\n\t\t\tsTemp = re.sub(\"^\\([a-z]\\) \", \"\", sTemp)\n\t\t\tsTemp = sBulletXML.replace(\"{TEXT}\", sTemp)\n\t\t\tsOut += sTemp\n\t\telif ax[:2] == \"* \":\n\t\t\tsTemp = sParaXML\n\t\t\tsTemp = sTemp.replace(\"{TEXT}\", ax.strip())\n\t\t\tsTemp = sTemp.replace(\"* \", \"\")\n\t\t\tsTemp = sTemp.replace(\"\\.\", \".\")\n\t\t\tsOut += sTemp\n\t\telif ax[:1] == \"*\":\n\t\t\tsTemp = sParaXML\n\t\t\tsTemp = sTemp.replace(\"{TEXT}\", ax.strip())\n\t\t\tsTemp = sTemp.replace(\"*\", \"\")\n\t\t\tsTemp = sTemp.replace(\"\\.\", \".\")\n\t\t\tsOut += sTemp\n\t\telse:\n\t\t\tsTemp = sParaXML\n\t\t\tsTemp = sTemp.replace(\"{TEXT}\", ax.strip())\n\t\t\tsTemp = sTemp.replace(\"* \", \"\")\n\t\t\tsTemp = sTemp.replace(\"\\.\", \".\")\n\t\t\tif sTemp != \"\\n\":\n\t\t\t\tsOut += sTemp\n\t\t\t\n\treturn (sOut)\n\t\ndef zipdir(basedir, archivename):\n\tassert os.path.isdir(basedir)\n\twith closing(ZipFile(archivename, \"w\", ZIP_DEFLATED)) as z:\n\t\tfor root, dirs, files in os.walk(basedir):\n\t\t\t#NOTE: ignore empty directories\n\t\t\tfor fn in files:\n\t\t\t\tabsfn = os.path.join(root, fn)\n\t\t\t\tzfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path\n\t\t\t\tz.write(absfn, zfn)\n" }, { "alpha_fraction": 0.6833333373069763, "alphanum_fraction": 0.7031111121177673, "avg_line_length": 33.35877990722656, "blob_id": "033ffa9350890443a17b7c6f7c56b8899b4ec907", "content_id": "72cbd42106cc8c38f64c02219f20634cff19877d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4500, "license_type": "no_license", "max_line_length": 183, "num_lines": 131, "path": "/create_quota_sheet.py", "repo_name": "mattlavis-transform/create_quota_sheet", "src_encoding": "UTF-8", "text": "import psycopg2\nfrom docx import Document\nfrom docx.shared import Inches\nfrom docx.shared import Cm\nfrom docx.oxml.shared import OxmlElement, qn\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\nfrom docx.enum.text import WD_TAB_ALIGNMENT\nfrom docx.enum.text import WD_TAB_LEADER\nimport os\nimport csv\nimport sys\nimport codecs\nimport re\nimport functions\nimport xlsxwriter\n\nfrom measure import measure\nfrom component import component\nfrom footnote import footnote\nfrom condition import condition\n\ndef writeOrderNumberRows(sOrderNumber):\n\tglobal conn \n\tglobal worksheet\n\tglobal lRow\n\t###############################################################\n\t# Get the definitions\n\tsSQL = \"\"\"SELECT DISTINCT qon.quota_order_number_sid, qd.validity_start_date as defintion_start_date, qd.validity_end_date as defintion_end_date,\n\tqd.initial_volume, qd.measurement_unit_code, qd.maximum_precision, qd.critical_state, qd.critical_threshold, qd.monetary_unit_code, qd.measurement_unit_qualifier_code, qd.description\n\tFROM measures m, quota_definitions qd, quota_order_numbers qon\n\tWHERE m.ordernumber = qd.quota_order_number_id\n\tAND m.ordernumber = qon.quota_order_number_id\n\tAND m.validity_start_date > (CURRENT_DATE - 365)\n\tAND qd.validity_start_date > (CURRENT_DATE - 365)\n\tAND m.ordernumber = '\"\"\" + sOrderNumber + \"\"\"'\n\tORDER BY 1, 2;\"\"\"\n\t\n\tcur = conn.cursor()\n\tcur.execute(sSQL)\n\trows_definitions = cur.fetchall()\n\t\n\t# Get the definitions\n\tfor m in rows_definitions:\n\t\tquota_order_number_sid = m[0]\n\t\tdefinition_start_date = m[1]\n\t\tdefinition_end_date = m[2]\n\t\tinitial_volume = m[3]\n\t\tmeasurement_unit_code = m[4]\n\t\tmaximum_precision = m[5]\n\t\tcritical_state = m[6]\n\t\tcritical_threshold = m[7]\n\t\tmonetary_unit_code = m[8]\n\t\tmeasurement_unit_qualifier_code = m[9]\n\t\tdescription = m[10]\n\n\t\tprint (sOrderNumber, lRow)\n\t\t\n\t\tworksheet.write(lRow, 0, sOrderNumber, cfWrap)\n\t\tworksheet.write(lRow, 1, quota_order_number_sid, cfWrap)\n\t\tworksheet.write(lRow, 2, definition_start_date, cfWrap)\n\t\tworksheet.write(lRow, 3, definition_end_date, cfWrap)\n\t\tworksheet.write(lRow, 4, initial_volume, cfWrap)\n\t\tworksheet.write(lRow, 5, measurement_unit_code, cfWrap)\n\t\tworksheet.write(lRow, 6, maximum_precision, cfWrap)\n\t\tworksheet.write(lRow, 7, critical_state, cfWrap)\n\t\tworksheet.write(lRow, 8, critical_threshold, cfWrap)\n\t\tworksheet.write(lRow, 9, monetary_unit_code, cfWrap)\n\t\tworksheet.write(lRow, 10, measurement_unit_qualifier_code, cfWrap)\n\t\tworksheet.write(lRow, 11, description, cfWrap)\n\t\tlRow = lRow + 1\n\n\t\nconn = psycopg2.connect(\"dbname=trade_tariff_1809 user=postgres password=zanzibar\")\n\nsSQL = \"\"\"SELECT DISTINCT m.ordernumber FROM measures m WHERE m.validity_start_date > (CURRENT_DATE - 365) ORDER BY 1;\"\"\"\ncur = conn.cursor()\ncur.execute(sSQL)\nrows_ordernumbers = cur.fetchall()\ni = 1\nlRow = 1\n\n# Write the Excel file\nsFilename = \"C:\\\\projects\\\\create_quota_sheet\\\\excel\\\\quotas.xlsx\"\n\nworkbook = xlsxwriter.Workbook(sFilename)\nworksheet = workbook.add_worksheet()\nbold = workbook.add_format({'bold': True, 'font_color': 'white', 'bg_color': 'black'})\nbold.set_font_size(9)\n\ncfWrap = workbook.add_format()\ncfWrap.set_text_wrap()\ncfWrap.set_align('left')\ncfWrap.set_align('top')\ncfWrap.set_font_size(9)\ncfWrap.set_font_name('Calibri')\n\nworksheet.write('A1', 'Order number', bold)\nworksheet.write('B1', 'Order number SID', bold)\nworksheet.write('C1', 'Definition start date', bold)\nworksheet.write('D1', 'Definition end date', bold)\nworksheet.write('E1', 'Initial volume', bold)\nworksheet.write('F1', 'Measurement unit code', bold)\nworksheet.write('G1', 'Maximum precision', bold)\nworksheet.write('H1', 'Critical state', bold)\nworksheet.write('I1', 'Critical threshold', bold)\nworksheet.write('J1', 'Monetary unit code', bold)\nworksheet.write('K1', 'Measurement unit qualifier code', bold)\nworksheet.write('L1', 'Description', bold)\n\nworksheet.set_column(\"A:A\", 12)\nworksheet.set_column(\"B:B\", 25)\nworksheet.set_column(\"C:D\", 15)\nworksheet.set_column(\"E:E\", 20)\nworksheet.set_column(\"F:F\", 20)\nworksheet.set_column(\"G:G\", 12)\nworksheet.set_column(\"H:H\", 32)\nworksheet.set_column(\"I:I\", 80)\nworksheet.set_column(\"J:J\", 60)\nworksheet.set_column(\"K:K\", 60)\nworksheet.set_column(\"L:L\", 60)\n\nfor m in rows_ordernumbers:\n\tsOrderNumber = m[0]\n\twriteOrderNumberRows(sOrderNumber)\n\ti = i + 1\n\tif i > 10:\n\t\tsys.exit()\n\nconn.close()\nworksheet.freeze_panes(1, 0)\nworkbook.close()" }, { "alpha_fraction": 0.6299182176589966, "alphanum_fraction": 0.6365407109260559, "avg_line_length": 33.21333312988281, "blob_id": "4e195f4cd9dd5309f798db8ebfc78e32e47a3499", "content_id": "0927061bfc46c845e48461502f29091cb294ab6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2567, "license_type": "no_license", "max_line_length": 182, "num_lines": 75, "path": "/component.py", "repo_name": "mattlavis-transform/create_quota_sheet", "src_encoding": "UTF-8", "text": "import functions\n\nclass component(object):\n\tdef __init__(self, sMeasureSID, iDutyAmount, sMonetaryUnitCode, iDutyExpressionID, sMonetaryUnitDescription, sMonetaryUnitQualifierDescription, sDutyExpressionDescription, sActive):\n\t\t# Get parameters from instantiator\n\t\tself.sMeasureSID = sMeasureSID\n\t\tself.iDutyAmount = functions.fltNone(iDutyAmount)\n\t\tself.sMonetaryUnitCode = functions.strNone(sMonetaryUnitCode)\n\t\tself.iDutyExpressionID = iDutyExpressionID\n\t\tself.sMonetaryUnitDescription = functions.strNone(sMonetaryUnitDescription)\n\t\tself.sMonetaryUnitQualifierDescription = functions.strNone(sMonetaryUnitQualifierDescription)\n\t\tself.sDutyExpressionDescription = functions.strNone(sDutyExpressionDescription)\n\t\tself.sActive = functions.strNone(sActive)\n\t\t\n\t\tself.sExpression = \"\"\n\t\tself.concatenateFields()\t\t\n\t\n\tdef concatenateFields(self):\n\t\ts = \"\"\n\t\t\n\t\t#print (self.sMeasureSID)\n\t\tif self.iDutyAmount > 0:\n\t\t\ts += \"{:.2f}\".format(self.iDutyAmount)\n\t\t\tif self.sDutyExpressionDescription != \"\":\n\t\t\t\ts = self.addDed(s)\n\t\t\t\tif self.sMonetaryUnitDescription != \"\":\n\t\t\t\t\ts += \" / \" + self.sMonetaryUnitDescription\n\t\t\t\t\tif self.sMonetaryUnitQualifierDescription != \"\":\n\t\t\t\t\t\ts += \" / \" + self.sMonetaryUnitQualifierDescription\n\t\telif self.iDutyAmount == -1:\n\t\t\tif self.sDutyExpressionDescription != \"\":\n\t\t\t\ts = self.addDed(s)\n\t\t\t\tif self.sMonetaryUnitDescription != \"\":\n\t\t\t\t\ts += \" / \" + self.sMonetaryUnitDescription\n\t\t\t\t\tif self.sMonetaryUnitQualifierDescription != \"\":\n\t\t\t\t\t\ts += \" / \" + self.sMonetaryUnitQualifierDescription\n\t\telse:\n\t\t\ts = \"0.00%\"\n\n\t\ts = functions.mShorten(s)\n\t\ts = \"[\" + self.iDutyExpressionID + \"] \" + s.strip()\n\t\tself.sExpression = s\n\t\t\n\tdef addDed(self, s):\n\t\ts = str(s)\n\t\tif s == \"None\":\n\t\t\ts = \"\"\n\t\tsWorking = \"\"\n\t\ts2 = \"\"\n\t\tsModifier = \"\"\n\t\tif self.sDutyExpressionDescription.find(\"+ \"):\n\t\t\tsWorking = \"+ \"\n\t\telif self.sDutyExpressionDescription.find(\"minus\"):\n\t\t\tsWorking = \"- \"\n\t\t\n\t\ts2 = self.sDutyExpressionDescription.replace(\"+ \", \"\")\n\t\ts2 = s2.replace(\"minus \", \"\")\n\t\t\n\t\tif self.sMonetaryUnitCode != \"\":\n\t\t\tsModifier = self.sMonetaryUnitCode\n\t\telse:\n\t\t\tif self.iDutyAmount != -1:\n\t\t\t\tsModifier = \"%\"\n\t\t\t\t\n\t\tif s2 == \"% or amount\":\n\t\t\ts2 = \"\"\n\t\t\t\n\t\tif s2 == \"Maximum\" or s2 == \"Minimum\":\n\t\t\tsWorking = sWorking + s2 + \" \" + s + \" \" + sModifier\n\t\telse:\n\t\t\tsWorking = sWorking + \" \" + str(s) + \" \" + str(sModifier) + \" \" + s2\n\t\t\n\t\tsWorking = sWorking.replace(\" \", \" \")\n\t \n\t\treturn (sWorking)\n\n" }, { "alpha_fraction": 0.7146892547607422, "alphanum_fraction": 0.7146892547607422, "avg_line_length": 34.45000076293945, "blob_id": "9d7c892c4e53c7c660c6f00690349a1cba1285cc", "content_id": "ac59a93df5189b8d164a3f78e28874ca79f9e129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 111, "num_lines": 20, "path": "/footnote.py", "repo_name": "mattlavis-transform/create_quota_sheet", "src_encoding": "UTF-8", "text": "import functions\n\nclass footnote(object):\n\tdef __init__(self, sMeasureSID, sFootnoteTypeID, sFootnoteID, sFootnoteDescription, sFootnoteTypeDescription):\n\t\t# Get parameters from instantiator\n\t\tself.sMeasureSID = sMeasureSID\n\t\tself.sFootnoteTypeID = sFootnoteTypeID\n\t\tself.sFootnoteID = sFootnoteID\n\t\tself.sFootnoteDescription = sFootnoteDescription\n\t\tself.sFootnoteTypeDescription = sFootnoteTypeDescription\n\t\t\n\t\tself.sFootnoteFull = \"\"\n\n\t\tself.concatenateFields()\n\t\t\n\tdef concatenateFields(self):\n\t\ts = \"\"\n\t\ts += self.sFootnoteTypeID\n\t\ts += self.sFootnoteID + \": (\" + self.sFootnoteTypeDescription + \") \" + self.sFootnoteDescription\n\t\tself.sFootnoteFull = s" }, { "alpha_fraction": 0.723789632320404, "alphanum_fraction": 0.7241379022598267, "avg_line_length": 57.51020431518555, "blob_id": "f4d76bd398edebf272838f2dde51c0b927387744", "content_id": "3c2c02676425ff220d3594a8eab018bf9bf64420", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2871, "license_type": "no_license", "max_line_length": 405, "num_lines": 49, "path": "/condition.py", "repo_name": "mattlavis-transform/create_quota_sheet", "src_encoding": "UTF-8", "text": "import functions\n\nclass condition(object):\n\tdef __init__(self, sMeasureSID, sMeasureConditionSID, sConditionCode, sConditionCodeDescription, sActionCode, sMeasureActionDescription, sConditionDutyAmount, sCertificateTypeCode, sCertificateTypeCodeDescription, sCertificateCode, sCertificateDescription, sMonetaryUnitCode, sMeasurementUnitCode, sMeasurementUnitQualifierCode, sMeasurementUnitCodeDescription, sMeasurementUnitQualifierCodeDescription):\n\t\t# Get parameters from instantiator\n\t\tself.sMeasureSID = sMeasureSID\n\t\tself.sMeasureConditionSID = sMeasureConditionSID\n\t\tself.sConditionCode = sConditionCode\n\t\tself.sConditionCodeDescription = sConditionCodeDescription\n\t\tself.sActionCode = sActionCode\n\t\tself.sMeasureActionDescription = sMeasureActionDescription\n\t\tself.sConditionDutyAmount = sConditionDutyAmount\n\t\tself.sCertificateTypeCode = sCertificateTypeCode\n\t\tself.sCertificateTypeCodeDescription = sCertificateTypeCodeDescription\n\t\tself.sCertificateCode = sCertificateCode\n\t\tself.sCertificateDescription = sCertificateDescription\n\t\tself.sMonetaryUnitCode = sMonetaryUnitCode\n\t\tself.sMeasurementUnitCode = sMeasurementUnitCode\n\t\tself.sMeasurementUnitQualifierCode = sMeasurementUnitQualifierCode\n\t\tself.sMeasurementUnitCodeDescription = sMeasurementUnitCodeDescription\n\t\tself.sMeasurementUnitQualifierCodeDescription = sMeasurementUnitQualifierCodeDescription\n\t\t\n\t\tself.sMUQ = \"\"\n\t\tself.sConditionFull = \"\"\n\n\t\tself.concatenateFields()\n\t\t\n\tdef concatenateFields(self):\n\t\tif self.sMeasurementUnitQualifierCode == None or self.sMeasurementUnitQualifierCodeDescription == None:\n\t\t\tself.sMUQ = \"\"\n\t\telse:\n\t\t\tself.sMUQ = self.sMeasurementUnitQualifierCode + self.sMeasurementUnitQualifierCodeDescription\n\t\t\t\n\t\tself.sConditionFull = \"\"\n\t\t# Condition statement\n\t\tself.sConditionFull += \"Condition [\" + self.sConditionCode + \"#] \" + self.sConditionCodeDescription + \" : \"\n\t\t# Document statement\n\t\tif self.sCertificateCode != None:\n\t\t\tself.sConditionFull += \"Document [\" + self.sCertificateTypeCode + \"] \"\t\t\n\t\t# Action statement\n\t\tif self.sActionCode != None:\n\t\t\tself.sConditionFull += \"Action [\" + self.sActionCode + \"] \" + self.sMeasureActionDescription + \" : \"\n\t\t# Requirement statement\n\t\tif self.sConditionDutyAmount != None:\n\t\t\tself.sConditionFull += \"Requirement - \" + \"{:.2f}\".format(self.sConditionDutyAmount)\n\t\t\tif self.sMeasurementUnitCodeDescription != None:\n\t\t\t\tself.sConditionFull += \" \" + self.sMeasurementUnitCodeDescription\n\t\t\t\tif self.sMeasurementUnitQualifierCodeDescription != None:\n\t\t\t\t\tself.sConditionFull += \" \" + self.sMeasurementUnitQualifierCodeDescription\n\t\t\t\n" } ]
7
BaksiLi/Quantum-Spin-Chain-Dynamics
https://github.com/BaksiLi/Quantum-Spin-Chain-Dynamics
6f433536fefb3de828131f00c9198944d2956701
2f99b385747a413d7c0b42a148f2b68bb1d5ab2f
a7b3c3ff2953a290cafe0af1723f4d099867269f
refs/heads/master
2020-09-13T14:04:41.228424
2019-08-14T21:00:14
2019-08-14T21:00:14
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 29, "blob_id": "f056774b1bd63565c84607cf1c1afb4d08274390", "content_id": "9ffda2558a190bc428ae91fbffefefb832eb2846", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 30, "license_type": "no_license", "max_line_length": 29, "num_lines": 1, "path": "/README.md", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "# Quantum-Spin-Chain-Dynamics\n" }, { "alpha_fraction": 0.6712172627449036, "alphanum_fraction": 0.6951080560684204, "avg_line_length": 40.904762268066406, "blob_id": "814bba4664cb64a5096a0271ce838a71216f2347", "content_id": "a2d6bd46d886ebaab047ce435eec2b2710bc836d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 206, "num_lines": 21, "path": "/Hamiltonian_test.py", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "import pytest\nfrom initialise import *\nfrom Hamiltonian import *\nimport pytest\n\ndef test_Hamiltonian_length_chain_1():\n chain_length = 1\n Spin_Operator_List = Spin_List_Creator(chain_length)\n dot = dot_product_spin_operators(chain_length, Spin_Operator_List, 0, 0)\n dot_actual = np.matmul(Sx, Sx) + np.matmul(Sy, Sy) + np.matmul(Sz, Sz)\n\n assert dot.size == 4\n assert np.array_equal(dot, dot_actual) == True\n\ndef test_Hamiltonian_length_chain_2():\n chain_length = 2\n Spin_Operator_List = Spin_List_Creator(chain_length)\n dot = dot_product_spin_operators(chain_length, Spin_Operator_List, 0, 1)\n dot_actual = np.matmul(Spin_Operator_List[0][0], Spin_Operator_List[1][0]) + np.matmul(Spin_Operator_List[0][1], Spin_Operator_List[1][1]) + np.matmul(Spin_Operator_List[0][2], Spin_Operator_List[1][2])\n\n assert np.array_equal(dot, dot_actual) == True" }, { "alpha_fraction": 0.6558670401573181, "alphanum_fraction": 0.670471727848053, "avg_line_length": 45.36186599731445, "blob_id": "afb28e87d21b53afa64c23b6a9a5462ee4fc14ef", "content_id": "43b32472ab591a014540f2fc88d55b66608d612b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11916, "license_type": "no_license", "max_line_length": 226, "num_lines": 257, "path": "/spin-chain-N.py", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.linalg import expm, sinm, cosm\nfrom matplotlib import pyplot as plt\nimport math\nfrom scipy.optimize import minimize\nfrom psopy import minimize as minimize_pso\nfrom psopy import init_feasible\nimport argparse\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#pauli matrices\nSx = np.array([[0, 1], [1, 0]])\nSy = np.array([[0, -1j], [1j, 0]])\nSz = np.array([[1, 0], [0, -1]])\n\n#up and down states\nup = np.array([[1], \n [0]])\ndown = np.array([[0],\n [1]])\n\nqubit_identity = np.identity(2)\n\ndef create_basis_state(chain_size, site):\n vector = np.zeros((chain_size, 1))\n vector[site - 1] = 1.\n return vector\n\ndef Hamiltonian_Constructor(chain_size, couplings):\n couplings_sum = 0.\n N = chain_size\n for coupling in couplings:\n couplings_sum += coupling\n H = np.zeros((N, N))\n H[0,0] = couplings_sum - 2 * couplings[0]\n H[N-1,N-1] = couplings_sum - 2 * couplings[N-2]\n for i in range(1, N-1):\n H[i,i] = couplings_sum - 2 * couplings[i-1] - 2 * couplings[i]\n for i in range(N-1):\n H[i,i+1] = 2 * couplings[i]\n H[i+1,i] = 2 * couplings[i]\n H = np.divide(H, np.average(couplings))\n return H\n\ndef time_evolution2(hamiltonian_matrix, time):\n \"\"\"\n Evolve the Hamiltonian for specific time interval\n \"\"\"\n time_scaled_matrix = -1j * time * hamiltonian_matrix\n time_evol = expm(time_scaled_matrix)\n return time_evol\n\ndef Calculate_Fidelity2(chain_size, initial_state, final_state, couplings, time):\n \"\"\"\n Calculate fidelity for given couplings over a given time. Outputs the probability of achieving \n that coupling\n \"\"\"\n Temp_Hamiltonian = Hamiltonian_Constructor(chain_size, couplings)\n time_evolved_matrix = time_evolution2(Temp_Hamiltonian, time)\n fidelity = np.matmul(final_state, np.matmul(time_evolved_matrix, initial_state))\n fidelity_value = fidelity.item()\n probability = fidelity_value * np.conj(fidelity_value)\n return probability\n\ndef plot_fidelity_overtime2(chain_size, initial_state, final_state, couplings, total_time, colour, line_title):\n \"\"\"\n Plots the fidelity over a given time with specified coupling\n \"\"\"\n x = np.arange(0, total_time, 0.1)\n y = np.zeros(x.size)\n for index, value in np.ndenumerate(x):\n y[index] = Calculate_Fidelity2(chain_length, initial, final, couplings, value)\n plt.ylabel(\"Fidelity\") \n plt.xlabel(\"Time • J\") \n plt.plot(x,y, colour, label = line_title)\n\ndef find_optimal_fidelity2(chain_size, initial_state, final_state, couplings, total_time):\n \"\"\"\n Finds the MAXIMUM fidelity achieved by the evolution when evolved over total_time\n \"\"\"\n times = np.arange(0, total_time, 0.1)\n fidelities = np.zeros(times.size)\n for index, value in np.ndenumerate(times):\n fidelities[index] = float(Calculate_Fidelity2(chain_length, initial, final, couplings, value))\n return np.amax(fidelities)\n\ndef turn_symmetric_couplings(couplings_values, chain_size, initial_state, final_state):\n number_couplings = chain_size - 1\n new_couplings = np.zeros(number_couplings)\n if number_couplings % 2 == 0:\n number_variable_couplings = int(number_couplings / 2) #half the size\n indicies = [i for i in range(number_variable_couplings)] + [number_couplings - 1 - i for i in range(number_variable_couplings)]\n np.put(new_couplings, indicies, couplings_values)\n if number_couplings % 2 == 1:\n number_variable_couplings = int((number_couplings + 1) / 2)\n indicies = [i for i in range(number_variable_couplings)] + [number_couplings - 1 - i for i in range(number_variable_couplings)]\n np.put(new_couplings, indicies, couplings_values)\n return new_couplings\n\ndef symmetric_chain_cost_function2(couplings_values, chain_size, initial_state, final_state):\n new_couplings = turn_symmetric_couplings(couplings_values, chain_size, initial_state, final_state)\n total_time = (10 * chain_size) / np.average(new_couplings)\n return (1 - find_optimal_fidelity2(chain_size, initial_state, final_state, new_couplings, total_time))\n\ndef return_fidelities2(chain_size, initial_state, final_state, couplings_initial, consts):\n \"\"\"\n # Final fidelity calculator. Should build the chain, calculate the fidelity over the chain and find the\n # optimisation.\n # Works only for chains of size > 3\n \"\"\"\n res = minimize_pso(symmetric_chain_cost_function2, couplings_initial, args = (chain_size, initial_state, final_state), constraints= None, options={'stable_iter' : 5, 'max_velocity' : 1, 'verbose' : True})\n print(f\"Best final fidelity: {1 - symmetric_chain_cost_function2(res.x, chain_size, initial_state, final_state)}\")\n print(f\"Final Couplings: {res.x}\")\n return res\n #result = minimize(symmetric_chain_cost_function, couplings_0, args = (chain_size, Spin_Operator_List, initial_state, final_state, evolution_time), method='nelder-mead', options={'xtol': 1e-8, 'disp': True})\n #print(result.x)\n\n\ndef plot_couplings(chain_size, couplings):\n x = range(1, chain_size)\n y = couplings\n chain_size_str = str(chain_size)\n plt.ylabel(\"Coupling value\") \n plt.xlabel(\"Site Position\") \n plt.title(\"Optimised couplings between sites for an \" + chain_size_str + \"-site chain\") \n plt.plot(x,y)\n plt.savefig('Couplings for ' + chain_size_str + '-site chain.png')\n plt.close()\n\nchain_length = 4\nchain_lenth_str = str(chain_length)\nnumber_couplings = chain_length - 1\ninitial = create_basis_state(chain_length, 1)\nfinal = create_basis_state(chain_length, chain_length).transpose()\nbasic_couplings = [1] * (chain_length - 1)\nif number_couplings % 2 == 0:\n number_variable_couplings = int(number_couplings / 2)\nif number_couplings % 2 == 1:\n number_variable_couplings = int((number_couplings + 1) / 2)\ncons = []\nfor i in range(number_variable_couplings):\n cons.append({'type' : 'ineq', 'fun' : lambda x: x[i]})\ncons = tuple(cons)\ninitial_couplings = init_feasible(cons, low=1., high=5., shape=(100, number_variable_couplings))\nresult = return_fidelities2(chain_length, initial, final, initial_couplings, cons)\nfinal_couplings = turn_symmetric_couplings(result.x, chain_length, initial, final)\nnormaliser = final_couplings[0]\nfinal_couplings = np.divide(final_couplings, final_couplings[0])\nprint(final_couplings)\nplot_fidelity_overtime2(chain_length, initial, final, basic_couplings, (10 * chain_length) / np.average(initial_couplings), 'b', 'Unoptimised Couplings')\nplot_fidelity_overtime2(chain_length, initial, final, final_couplings, (10 * chain_length) / np.average(final_couplings), 'r', 'Optimised Couplings')\nplt.legend(loc='best')\nplt.title('Fidelity over time for ' + chain_lenth_str + '-site spin chain')\nplt.savefig('Fidelity over time for ' + chain_lenth_str + '-site spin chain.png')\nplt.close()\nplot_couplings(chain_length, final_couplings)\n\n# \"\"\"\n\n# def plot_changing_fidelity(chain_size, evolution_time):\n# \"\"\"\n# #Try changing J2 to see what happens to the maximum fidelity achieved\n# \"\"\"\n# initial_state = create_initial_final_states(chain_size, True)\n# final_state = create_initial_final_states(chain_size, False)\n# final_state = final_state.transpose()\n# Spin_Operator_List = Spin_List_Creator(chain_size)\n# j2s = np.arange(0, 10, 0.1)\n# fidelities = np.zeros(j2s.size)\n# for index, j2_value in np.ndenumerate(j2s):\n# coupling_trial = [1, j2_value, 1]\n# fidelities[index] = find_optimal_fidelity(chain_size, coupling_trial, Spin_Operator_List, initial_state, final_state, evolution_time, XY_HAM = False)\n# best_fid = np.amax(fidelities)\n# first_j2_optimal = j2s[np.where(fidelities == best_fid)[0][0]]\n# print(best_fid)\n# print(first_j2_optimal)\n# print(initial_state)\n# print(final_state)\n# plt.ylabel(\"Fidelity\") \n# plt.xlabel(\"j2\")\n# plt.title(\"Best fidelity found for different j2s\") \n# plt.plot(j2s,fidelities)\n# plt.axvline(x=math.sqrt(2), color='r', linestyle='-') \n# plt.show()\n \n# #plot_changing_fidelity(4, 10)\n\n# def cost_function(couplings, chain_length, Spin_Operator_List, initial_state, final_state, total_time, XY_HAM = False):\n# \"\"\"\n# #Calculate the cost function in terms of fidelity for a given coupling over a given time, using the maximum achieved fidelity\n# \"\"\"\n# return (1 - find_optimal_fidelity(chain_length, couplings, Spin_Operator_List, initial_state, final_state, total_time, XY_HAM))\n\n# def symmetric_chain_cost_function(couplings_values, chain_size, Spin_Operator_List, initial_state, final_state, XY_HAM = False):\n# number_couplings = chain_size - 1\n# new_couplings = np.zeros(number_couplings)\n# if number_couplings % 2 == 0:\n# number_variable_couplings = int(number_couplings / 2) #half the size\n# indicies = [i for i in range(number_variable_couplings)] + [number_couplings - 1 - i for i in range(number_variable_couplings)]\n# np.put(new_couplings, indicies, couplings_values)\n# if number_couplings % 2 == 1:\n# number_variable_couplings = int((number_couplings + 1) / 2)\n# indicies = [i for i in range(number_variable_couplings)] + [number_couplings - 1 - i for i in range(number_variable_couplings)]\n# np.put(new_couplings, indicies, couplings_values)\n# total_time = (10 * chain_size) / np.average(new_couplings)\n# return (1 - find_optimal_fidelity(chain_size, new_couplings, Spin_Operator_List, initial_state, final_state, total_time, XY_HAM))\n\n\n# def return_fidelities(chain_size, couplings_0, consts):\n# \"\"\"\n# # Final fidelity calculator. Should build the chain, calculate the fidelity over the chain and find the\n# # optimisation.\n# # Works only for chains of size > 3\n# \"\"\"\n# initial_state = create_initial_final_states(chain_size, True)\n# final_state = create_initial_final_states(chain_size, False)\n# final_state = final_state.transpose()\n# Spin_Operator_List = Spin_List_Creator(chain_size)\n\n# res = minimize_pso(symmetric_chain_cost_function, couplings_0, args = (chain_size, Spin_Operator_List, initial_state, final_state), constraints= consts, options={'stable_iter' : 20, 'max_velocity' : 1, 'verbose' : True})\n# print(f\"Best final fidelity: {1 - symmetric_chain_cost_function(res.x, chain_size, Spin_Operator_List, initial_state, final_state, XY_HAM = False)}\")\n# print(f\"Final Couplings: {res.x}\")\n \n# #result = minimize(symmetric_chain_cost_function, couplings_0, args = (chain_size, Spin_Operator_List, initial_state, final_state, evolution_time), method='nelder-mead', options={'xtol': 1e-8, 'disp': True})\n# #print(result.x)\n\n# #couplings_0 = np.random.uniform(1, 2, (2, 2))\n# #return_fidelities(4, 1, couplings_0, cons)\n# \"\"\"\n# # def Main():\n# # parser = argparse.ArgumentParser()\n# # parser.add_argument(\"chain_size\", help = \"The number of quantum states in your chain\", type = int)\n# # parser.add_argument(\"particles\", help = \"The number of particles created in swarm\", type = int)\n# # args = parser.parse_args()\n# # number_couplings = args.chain_size - 1\n \n# # cons = []\n# # if number_couplings % 2 == 0:\n# # number_variable_couplings = int(number_couplings / 2)\n# # if number_couplings % 2 == 1:\n# # number_variable_couplings = int((number_couplings + 1) / 2)\n# # for i in range(number_variable_couplings):\n# # cons.append({'type' : 'ineq', 'fun' : lambda x: x[i]})\n# # cons = tuple(cons)\n# # print(cons)\n \n# #cons = ({'type' : 'ineq', 'fun' : lambda x: x[0]},\n# # {'type' : 'ineq', 'fun' : lambda x: x[1]})\n# \"\"\"\n \n# initial_couplings = init_feasible(cons, low=1., high=2., shape=(args.particles, number_variable_couplings))\n# return return_fidelities(args.chain_size, initial_couplings, cons)\n\n# if __name__ == '__main__':\n# Main()\n# \"\"\"" }, { "alpha_fraction": 0.6717284321784973, "alphanum_fraction": 0.6895935535430908, "avg_line_length": 44.71428680419922, "blob_id": "3338ead921b26f538a877bdd71cbf1e046b3775d", "content_id": "679261aefa7c81958afc3cef9dadca15196f4eca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2239, "license_type": "no_license", "max_line_length": 141, "num_lines": 49, "path": "/Hamiltonian.py", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.linalg import expm, sinm, cosm\nfrom initialise import *\n\ndef dot_product_spin_operators(chain_length, Spin_Operator_List, qubit_position_1, qubit_position_2):\n \"\"\"\n perform dot product of 2 spin operators (Sx, Sy, Sz) in 2 postions\n \"\"\"\n dot_product = np.zeros((2**chain_length, 2**chain_length))\n dot_product = dot_product.astype('complex128')\n for Spin_Operator in range(3):\n Spin_Operator_1 = Spin_Operator_List[qubit_position_1][Spin_Operator]\n Spin_Operator_2 = Spin_Operator_List[qubit_position_2][Spin_Operator]\n dot_product += np.matmul(Spin_Operator_1, Spin_Operator_2)\n return dot_product\n\ndef dot_product_spin_operators_XY(chain_length, Spin_Operator_List, qubit_position_1, qubit_position_2):\n \"\"\"\n Perform dot product of 2 spin operators (Sx, Sy) in 2 postions\n \"\"\"\n dot_product = np.zeros((2**chain_length, 2**chain_length))\n dot_product = dot_product.astype('complex128')\n for Spin_Operator in range(2):\n Spin_Operator_1 = Spin_Operator_List[qubit_position_1][Spin_Operator]\n Spin_Operator_2 = Spin_Operator_List[qubit_position_2][Spin_Operator]\n dot_product += np.matmul(Spin_Operator_1, Spin_Operator_2)\n return dot_product\n\ndef Heisenberg_Hamiltonian_Constructor(chain_length, couplings, XY_HAM = False):\n \"\"\"\n Create Heisenberg Hamiltonian with specific couplings and chain length\n \"\"\"\n Spin_Operator_List = Spin_List_Creator(chain_length)\n Heisenberg = np.zeros((2**chain_length, 2**chain_length))\n Heisenberg = Heisenberg.astype('complex128')\n for qubit_position, J in enumerate(couplings):\n if XY_HAM == False:\n Heisenberg = Heisenberg + (J * dot_product_spin_operators(chain_length, Spin_Operator_List, qubit_position, qubit_position+1))\n else:\n Heisenberg = Heisenberg + (J * dot_product_spin_operators_XY(chain_length, Spin_Operator_List, qubit_position, qubit_position+1))\n return Heisenberg\n\ndef time_evolution(hamiltonian_matrix, time):\n \"\"\"\n Evolve the Hamiltonian for specific time interval\n \"\"\"\n time_scaled_matrix = -1j * time * hamiltonian_matrix\n time_evol = expm(time_scaled_matrix)\n return time_evol" }, { "alpha_fraction": 0.666151762008667, "alphanum_fraction": 0.6801407337188721, "avg_line_length": 43.81922912597656, "blob_id": "7bb619ef5443f38574717684c72d5c056467abbd", "content_id": "05ab584b08f6050e217ac77af5d3383744e4b335", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11653, "license_type": "no_license", "max_line_length": 224, "num_lines": 260, "path": "/spin-chain.py", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.linalg import expm, sinm, cosm\nfrom matplotlib import pyplot as plt\nimport math\nfrom scipy.optimize import minimize\nfrom psopy import minimize as minimize_pso\nfrom psopy import init_feasible\nimport argparse\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#pauli matrices\nSx = np.array([[0, 1], [1, 0]])\nSy = np.array([[0, -1j], [1j, 0]])\nSz = np.array([[1, 0], [0, -1]])\n\n#up and down states\nup = np.array([[1], \n [0]])\ndown = np.array([[0],\n [1]])\n\nqubit_identity = np.identity(2)\n\ndef tensor_product_initialiser(number_particles, state, iterated_state, first):\n \"\"\"\n Creates a tensor product over a certain number of particles, with an initial state, and an iterated \n state that attaches however many times. If first is true, the initial state remains as the first state,\n otherwise it moves to last.\n \"\"\"\n states_created = 1\n while states_created < number_particles:\n if first == True:\n state = np.kron(state, iterated_state)\n else:\n state = np.kron(iterated_state, state)\n states_created += 1\n return state\n\ndef create_initial_final_states(chain_length, initial):\n \"\"\"\n Creates the initial and final states of the chain, initial being a boolean which we can set to True for\n the initial, False for the final.\n \"\"\"\n return tensor_product_initialiser(chain_length, up, down, initial)\n\ndef chain_operator_constructor(chain_length, chain_position, qubit_operator):\n \"\"\"\n Takes an operator acting on a single qubit, in a given position of the chain. Outputs the operator on the entire \n chain.\n \"\"\"\n operator_left = tensor_product_initialiser(chain_position, qubit_operator, qubit_identity, False)\n operator = tensor_product_initialiser(chain_length - chain_position + 1, operator_left, qubit_identity, True)\n return operator\n\n\ndef Spin_List_Creator(chain_length):\n \"\"\"\n Creates list of size chain_length of the Spin operators for each site, where S = [Sx, Sy, Sz]. Indexed from 0.\n \"\"\"\n Spin_List = []\n for qubit_chain_position in range(chain_length):\n Qubit_Spin_Array = np.array([chain_operator_constructor(chain_length, qubit_chain_position + 1, Sx), \n chain_operator_constructor(chain_length, qubit_chain_position + 1, Sy),\n chain_operator_constructor(chain_length, qubit_chain_position + 1, Sz)])\n Spin_List.append(Qubit_Spin_Array)\n return Spin_List\n\n\n\ndef dot_product_spin_operators(chain_length, Spin_Operator_List, qubit_position_1, qubit_position_2):\n \"\"\"\n perform dot product of 2 spin operators (Sx, Sy, Sz) in 2 postions\n \"\"\"\n dot_product = np.zeros((2**chain_length, 2**chain_length))\n dot_product = dot_product.astype('complex128')\n for Spin_Operator in range(3):\n Spin_Operator_1 = Spin_Operator_List[qubit_position_1][Spin_Operator]\n Spin_Operator_2 = Spin_Operator_List[qubit_position_2][Spin_Operator]\n dot_product += np.matmul(Spin_Operator_1, Spin_Operator_2)\n return dot_product\n\ndef dot_product_spin_operators_XY(chain_length, Spin_Operator_List, qubit_position_1, qubit_position_2):\n \"\"\"\n Perform dot product of 2 spin operators (Sx, Sy) in 2 postions\n \"\"\"\n dot_product = np.zeros((2**chain_length, 2**chain_length))\n dot_product = dot_product.astype('complex128')\n for Spin_Operator in range(2):\n Spin_Operator_1 = Spin_Operator_List[qubit_position_1][Spin_Operator]\n Spin_Operator_2 = Spin_Operator_List[qubit_position_2][Spin_Operator]\n dot_product += np.matmul(Spin_Operator_1, Spin_Operator_2)\n return dot_product\n\ndef Heisenberg_Hamiltonian_Constructor(chain_length, Spin_Operator_List, couplings, XY_HAM = False):\n \"\"\"\n Create Heisenberg Hamiltonian with specific couplings and chain length. If XY_HAM is True, will use the XY\n Hamiltonian instead of the Heisenberg.\n \"\"\"\n #Spin_Operator_List = Spin_List_Creator(chain_length)\n Heisenberg = np.zeros((2**chain_length, 2**chain_length))\n Heisenberg = Heisenberg.astype('complex128')\n for qubit_position, J in enumerate(couplings):\n if XY_HAM == False:\n Heisenberg = Heisenberg + (J * dot_product_spin_operators(chain_length, Spin_Operator_List, qubit_position, qubit_position+1))\n else:\n Heisenberg = Heisenberg + (J * dot_product_spin_operators_XY(chain_length, Spin_Operator_List, qubit_position, qubit_position+1))\n return Heisenberg\n\ndef time_evolution(hamiltonian_matrix, time):\n \"\"\"\n Evolve the Hamiltonian for specific time interval\n \"\"\"\n time_scaled_matrix = -1j * time * hamiltonian_matrix\n time_evol = expm(time_scaled_matrix)\n return time_evol\n\n\ndef Calculate_Fidelity(chain_length, Spin_Operator_List, initial_state, final_state, couplings, time, XY_HAM = False):\n \"\"\"\n Calculate fidelity for given couplings over a given time. Outputs the probability of achieving \n that coupling\n \"\"\"\n Temp_Hamiltonian = Heisenberg_Hamiltonian_Constructor(chain_length, Spin_Operator_List, couplings, XY_HAM)\n time_evolved_matrix = time_evolution(Temp_Hamiltonian, time)\n fidelity = np.matmul(final_state, np.matmul(time_evolved_matrix, initial_state))\n fidelity_value = fidelity.item()\n probability = fidelity_value * np.conj(fidelity_value)\n return probability\n\ndef plot_fidelity_overtime(chain_size, couplings, total_time):\n \"\"\"\n Plots the fidelity over a given time with specified coupling\n \"\"\"\n initial_state = create_initial_final_states(chain_size, True)\n final_state = create_initial_final_states(chain_size, False)\n final_state = final_state.transpose()\n Spin_Operator_List = Spin_List_Creator(chain_size)\n x = np.arange(0, total_time, 0.1)\n y = np.zeros(x.size)\n for index, value in np.ndenumerate(x):\n y[index] = Calculate_Fidelity(chain_size, Spin_Operator_List, initial_state, final_state, couplings, value, XY_HAM = False)\n plt.ylabel(\"Fidelity\") \n plt.xlabel(\"Time · J\") \n plt.title(\"Changing fidelity of state transfer for different times\") \n plt.plot(x,y) \n plt.show()\n plt.hold\n\n#plot_fidelity_overtime(4, [0.9813, 1.9624, 0.9813], 10)\nplot_fidelity_overtime(4, [1,1,1], 20)\n\ndef find_optimal_fidelity(chain_length, couplings, Spin_Operator_List, initial_state, final_state, total_time, XY_HAM = False):\n \"\"\"\n Finds the MAXIMUM fidelity achieved by the evolution when evolved over total_time\n \"\"\"\n times = np.arange(0, total_time, 0.1)\n fidelities = np.zeros(times.size)\n for index, value in np.ndenumerate(times):\n fidelities[index] = float(Calculate_Fidelity(chain_length, Spin_Operator_List, initial_state, final_state, couplings, value, XY_HAM))\n return np.amax(fidelities)\n\n\ndef plot_changing_fidelity(chain_size, evolution_time):\n \"\"\"\n #Try changing J2 to see what happens to the maximum fidelity achieved\n \"\"\"\n initial_state = create_initial_final_states(chain_size, True)\n final_state = create_initial_final_states(chain_size, False)\n final_state = final_state.transpose()\n Spin_Operator_List = Spin_List_Creator(chain_size)\n j2s = np.arange(0, 10, 0.1)\n fidelities = np.zeros(j2s.size)\n for index, j2_value in np.ndenumerate(j2s):\n coupling_trial = [1, j2_value, 1]\n fidelities[index] = find_optimal_fidelity(chain_size, coupling_trial, Spin_Operator_List, initial_state, final_state, evolution_time, XY_HAM = False)\n best_fid = np.amax(fidelities)\n first_j2_optimal = j2s[np.where(fidelities == best_fid)[0][0]]\n print(best_fid)\n print(first_j2_optimal)\n print(initial_state)\n print(final_state)\n plt.ylabel(\"Fidelity\") \n plt.xlabel(\"j2\")\n plt.title(\"Best fidelity found for different j2s\") \n plt.plot(j2s,fidelities)\n plt.axvline(x=math.sqrt(2), color='r', linestyle='-') \n plt.show()\n \n#plot_changing_fidelity(4, 10)\n\ndef cost_function(couplings, chain_length, Spin_Operator_List, initial_state, final_state, total_time, XY_HAM = False):\n \"\"\"\n #Calculate the cost function in terms of fidelity for a given coupling over a given time, using the maximum achieved fidelity\n \"\"\"\n return (1 - find_optimal_fidelity(chain_length, couplings, Spin_Operator_List, initial_state, final_state, total_time, XY_HAM))\n\ndef symmetric_chain_cost_function(couplings_values, chain_size, Spin_Operator_List, initial_state, final_state, XY_HAM = False):\n number_couplings = chain_size - 1\n new_couplings = np.zeros(number_couplings)\n if number_couplings % 2 == 0:\n number_variable_couplings = int(number_couplings / 2) #half the size\n indicies = [i for i in range(number_variable_couplings)] + [number_couplings - 1 - i for i in range(number_variable_couplings)]\n np.put(new_couplings, indicies, couplings_values)\n if number_couplings % 2 == 1:\n number_variable_couplings = int((number_couplings + 1) / 2)\n indicies = [i for i in range(number_variable_couplings)] + [number_couplings - 1 - i for i in range(number_variable_couplings)]\n np.put(new_couplings, indicies, couplings_values)\n total_time = (10 * chain_size) / np.average(new_couplings)\n return (1 - find_optimal_fidelity(chain_size, new_couplings, Spin_Operator_List, initial_state, final_state, total_time, XY_HAM))\n\n\ndef return_fidelities(chain_size, couplings_0, consts):\n \"\"\"\n Final fidelity calculator. Should build the chain, calculate the fidelity over the chain and find the\n optimisation.\n Works only for chains of size > 3\n \"\"\"\n initial_state = create_initial_final_states(chain_size, True)\n final_state = create_initial_final_states(chain_size, False)\n final_state = final_state.transpose()\n Spin_Operator_List = Spin_List_Creator(chain_size)\n\n res = minimize_pso(symmetric_chain_cost_function, couplings_0, args = (chain_size, Spin_Operator_List, initial_state, final_state), constraints= consts, options={'stable_iter' : 20, 'max_velocity' : 1, 'verbose' : True})\n print(f\"Best final fidelity: {1 - symmetric_chain_cost_function(res.x, chain_size, Spin_Operator_List, initial_state, final_state, XY_HAM = False)}\")\n print(f\"Final Couplings: {res.x}\")\n \n #result = minimize(symmetric_chain_cost_function, couplings_0, args = (chain_size, Spin_Operator_List, initial_state, final_state, evolution_time), method='nelder-mead', options={'xtol': 1e-8, 'disp': True})\n #print(result.x)\n\n#couplings_0 = np.random.uniform(1, 2, (2, 2))\n#return_fidelities(4, 1, couplings_0, cons)\n\"\"\"\ndef Main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"chain_size\", help = \"The number of quantum states in your chain\", type = int)\n parser.add_argument(\"particles\", help = \"The number of particles created in swarm\", type = int)\n args = parser.parse_args()\n number_couplings = args.chain_size - 1\n \n cons = []\n if number_couplings % 2 == 0:\n number_variable_couplings = int(number_couplings / 2)\n if number_couplings % 2 == 1:\n number_variable_couplings = int((number_couplings + 1) / 2)\n for i in range(number_variable_couplings):\n cons.append({'type' : 'ineq', 'fun' : lambda x: x[i]})\n cons = tuple(cons)\n print(cons)\n \n #cons = ({'type' : 'ineq', 'fun' : lambda x: x[0]},\n # {'type' : 'ineq', 'fun' : lambda x: x[1]})\n\n \n initial_couplings = init_feasible(cons, low=1., high=2., shape=(args.particles, number_variable_couplings))\n return return_fidelities(args.chain_size, initial_couplings, cons)\n\nif __name__ == '__main__':\n Main()\n\"\"\"" }, { "alpha_fraction": 0.6671717166900635, "alphanum_fraction": 0.6843434572219849, "avg_line_length": 38.599998474121094, "blob_id": "459f491e569b021ac70778c2150a6c3c803042bd", "content_id": "4b254cdf292f72279ab2d520b0057863cd58cbbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1980, "license_type": "no_license", "max_line_length": 135, "num_lines": 50, "path": "/optimisation.py", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "from Fidelity import *\nimport math\nimport numpy as np\n\n\ndef plot_changing_fidelity(evolution_time):\n \"\"\"\n #Try changing J2 to see what happens to the maximum fidelity achieved\n \"\"\"\n j2s = np.arange(0, 10, 0.1)\n fidelities = np.zeros(j2s.size)\n for index, j2_value in np.ndenumerate(j2s):\n coupling_trial = [1, j2_value, 1]\n fidelities[index] = find_optimal_fidelity(coupling_trial, evolution_time, XY_HAM = False)\n best_fid = np.amax(fidelities)\n first_j2_optimal = j2s[np.where(fidelities == best_fid)[0][0]]\n print(best_fid)\n print(first_j2_optimal)\n print(initial_state)\n print(final_state)\n plt.ylabel(\"Fidelity\") \n plt.xlabel(\"j2\")\n plt.title(\"Best fidelity found for different j2s\") \n plt.plot(j2s,fidelities)\n plt.axvline(x=math.sqrt(2), color='r', linestyle='-') \n plt.show()\n \n#plot_changing_fidelity(10)\n\ndef cost_function(couplings, total_time, XY_HAM = False):\n \"\"\"\n #Calculate the cost function in terms of fidelity for a given coupling over a given time, using the maximum achieved fidelity\n \"\"\"\n return (1 - find_optimal_fidelity(couplings, total_time, XY_HAM))\n\ndef return_fidelities(evolution_time, chain_size):\n initial_state = create_initial_final_states(chain_size, True)\n final_state = create_initial_final_states(chain_size, False)\n final_state = final_state.transpose()\n Spin_Operator_List = Spin_List_Creator(chain_size)\n number_couplings = chain_size - 1\n couplings = np.zeros(number_couplings)\n if chain_size % 2 == 1: #even no. of couplings\n number_variable_couplings = int(number_couplings / 2)\n coupling_values = np.full(number_variable_couplings, 1) #half the size\n indicies = [i for i in range(number_variable_couplings)] + [number_couplings - 1 - i for i in range(number_variable_couplings)]\n np.put(couplings, indicies, coupling_values)\n print(cost_function(couplings, evolution_time))\n\nreturn_fidelities(1, 11)\n" }, { "alpha_fraction": 0.6339370608329773, "alphanum_fraction": 0.6453765630722046, "avg_line_length": 37.87036895751953, "blob_id": "b87275386afb73a8a7f065bd5592952c7fdf3c88", "content_id": "32a67ea2e293f4ca26c129c22fbe8365b22f581a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2098, "license_type": "no_license", "max_line_length": 117, "num_lines": 54, "path": "/initialise.py", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "import numpy as np\n\n#pauli matrices\nSx = np.array([[0, 1], [1, 0]])\nSy = np.array([[0, -1j], [1j, 0]])\nSz = np.array([[1, 0], [0, -1]])\n\n#up and down states\nup = np.array([[1], \n [0]])\ndown = np.array([[0],\n [1]])\n\nqubit_identity = np.identity(2)\n\ndef tensor_product_initialiser(number_particles, state, iterated_state, first):\n \"\"\"\n Creates a tensor product over a certain number of particles, with an initial state, and an iterated \n state that attaches however many times. If first is true, the initial state remains as the first state,\n otherwise it moves to last.\n \"\"\"\n states_created = 1\n while states_created < number_particles:\n if first == True:\n state = np.kron(state, iterated_state)\n else:\n state = np.kron(iterated_state, state)\n states_created += 1\n return state\n\ndef create_initial_final_states(chain_length, initial):\n return tensor_product_initialiser(chain_length, up, down, initial)\n\ndef chain_operator_constructor(chain_length, chain_position, qubit_operator):\n \"\"\"\n Takes an operator acting on a single qubit, in a given position of the chain. Outputs the operator on the entire \n chain.\n \"\"\"\n operator_left = tensor_product_initialiser(chain_position, qubit_operator, qubit_identity, False)\n operator = tensor_product_initialiser(chain_length - chain_position + 1, operator_left, qubit_identity, True)\n return operator\n\n\ndef Spin_List_Creator(chain_length):\n \"\"\"\n Creates list of size chain_length of the Spin operators for each site, where S = [Sx, Sy, Sz]. Indexed from 0.\n \"\"\"\n Spin_List = []\n for qubit_chain_position in range(chain_length):\n Qubit_Spin_Array = np.array([chain_operator_constructor(chain_length, qubit_chain_position + 1, Sx), \n chain_operator_constructor(chain_length, qubit_chain_position + 1, Sy),\n chain_operator_constructor(chain_length, qubit_chain_position + 1, Sz)])\n Spin_List.append(Qubit_Spin_Array)\n return Spin_List" }, { "alpha_fraction": 0.6512554883956909, "alphanum_fraction": 0.6775608062744141, "avg_line_length": 46.358489990234375, "blob_id": "d80d22f43ae40383b4f3abbf4c39953af37865c2", "content_id": "d678687ff360cb233e25369ef49df6bdb0bbc690", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2509, "license_type": "no_license", "max_line_length": 126, "num_lines": 53, "path": "/initialise_test.py", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "import pytest\nfrom initialise import *\n\ndef test_length_1_chain():\n chain_length = 1\n initial_state = create_initial_final_states(chain_length, True)\n final_state = create_initial_final_states(chain_length, False)\n Spin_Operator_List = Spin_List_Creator(chain_length)\n\n assert initial_state.all() == final_state.all()\n assert Spin_Operator_List[0][0].all() == Sx.all()\n assert Spin_Operator_List[0][1].all() == Sy.all()\n assert Spin_Operator_List[0][2].all() == Sz.all()\n assert type(Spin_Operator_List) == list\n assert len(Spin_Operator_List) == chain_length\n\ndef test_length_2_chain():\n chain_length = 2\n initial_state = create_initial_final_states(chain_length, True)\n final_state = create_initial_final_states(chain_length, False)\n Spin_Operator_List = Spin_List_Creator(chain_length)\n Sx0_actual = np.kron(Sx, qubit_identity) #Test using kron function\n Sz1_actual = np.array([1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1]).reshape(4, 4) #Test building the matrix manually\n\n assert initial_state[1] == 1\n assert initial_state[2] == 0\n assert final_state[1] == 0\n assert final_state[2] == 1\n assert len(initial_state) == len(final_state)\n assert type(Spin_Operator_List) == list\n assert Spin_Operator_List[0][0].all() == Sx0_actual.all()\n assert Spin_Operator_List[1][2].all() == Sz1_actual.all()\n assert len(Spin_Operator_List) == chain_length\n\ndef test_length_3_chain():\n chain_length = 3\n initial_state = create_initial_final_states(chain_length, True)\n final_state = create_initial_final_states(chain_length, False)\n Spin_Operator_List = Spin_List_Creator(chain_length)\n Sy1_actual = np.kron(Sy, np.kron(qubit_identity, qubit_identity)) #Test using kron function\n Sz2_actual = np.kron(qubit_identity, np.kron(Sz, qubit_identity)) #Test using kron function\n Sx3_actual = np.kron(qubit_identity, np.kron(qubit_identity, Sy)) #Test using kron function\n\n assert len(initial_state) == len(final_state)\n assert len(initial_state) == 8\n assert type(Spin_Operator_List) == list\n #assert type(Spin_Operator_List[0]) == <class 'numpy.ndarray'>\n assert Spin_Operator_List[0][1].all() == Sy1_actual.all()\n assert Spin_Operator_List[1][2].all() == Sz2_actual.all()\n assert Spin_Operator_List[2][0].all() == Sx3_actual.all()\n assert len(Spin_Operator_List) == chain_length\n assert Spin_Operator_List[0][1].size == Sy1_actual.size\n assert Spin_Operator_List[1][1].size == Sy1_actual.size" }, { "alpha_fraction": 0.7015483379364014, "alphanum_fraction": 0.7090229392051697, "avg_line_length": 35.686275482177734, "blob_id": "1d203ed2274f90f559a7420edb1c533685835393", "content_id": "ff3799e1e47f8e732599ba953ec759fb20eafeec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1873, "license_type": "no_license", "max_line_length": 101, "num_lines": 51, "path": "/Fidelity.py", "repo_name": "BaksiLi/Quantum-Spin-Chain-Dynamics", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nimport math\nfrom initialise import *\nfrom Hamiltonian import *\n\ntotal_chain_length = 4\ninitial_state = create_initial_final_states(total_chain_length, True)\nfinal_state = create_initial_final_states(total_chain_length, False)\nfinal_state = final_state.transpose()\nSpin_Operator_List = Spin_List_Creator(total_chain_length)\ncouplings_initialise = [0, 0]\n\n\ndef Calculate_Fidelity(couplings, time, XY_HAM = False):\n \"\"\"\n Calculate fidelity for given couplings over a given time t. Outputs the probability of achieving \n that coupling\n \"\"\"\n Temp_Hamiltonian = Heisenberg_Hamiltonian_Constructor(total_chain_length, couplings, XY_HAM)\n time_evolved_matrix = time_evolution(Temp_Hamiltonian, time)\n fidelity = np.matmul(final_state, np.matmul(time_evolved_matrix, initial_state))\n fidelity_value = fidelity.item()\n probability = fidelity_value * np.conj(fidelity_value)\n return probability\n\ndef plot_fidelity_overtime(couplings, total_time):\n \"\"\"\n Plots the fidelity over a given time with specified coupling\n \"\"\"\n x = np.arange(0, total_time, 0.1)\n y = np.zeros(x.size)\n for index, value in np.ndenumerate(x):\n y[index] = Calculate_Fidelity(couplings, value, XY_HAM = False)\n plt.ylabel(\"Probability\") \n plt.xlabel(\"Time\") \n plt.title(\"Probability of perfect fidelity\") \n plt.plot(x,y) \n plt.show()\n\n#plot_fidelity_overtime([1, math.sqrt(2), 1], 20)\n\ndef find_optimal_fidelity(couplings, total_time, XY_HAM = False):\n \"\"\"\n Finds the MAXIMUM fidelity achieved by the evolution when evolved over total_time\n \"\"\"\n times = np.arange(0, total_time, 0.1)\n fidelities = np.zeros(times.size)\n for index, value in np.ndenumerate(times):\n fidelities[index] = Calculate_Fidelity(couplings, value, XY_HAM)\n return np.amax(fidelities)\n\n\n" } ]
9
jazzband/django-redis
https://github.com/jazzband/django-redis
3bf1c924636ec1a39a01dabb19903576bd6289af
361921841eb07315cc88ff83a1889fec43a89242
946ca09f0942a86f3f2253d9305e11f5f43bacdb
refs/heads/master
2023-09-02T15:42:45.013706
2023-08-21T16:55:33
2023-08-21T16:55:33
4,054,633
1,112
159
NOASSERTION
2012-04-17T16:29:49
2023-09-11T16:12:23
2023-09-12T09:58:34
Python
[ { "alpha_fraction": 0.5460724830627441, "alphanum_fraction": 0.5574018359184265, "avg_line_length": 28.422222137451172, "blob_id": "10ff20f703ddc2e8b3bd11b2418b626793a1d2a6", "content_id": "fc59a9ed5ff4201a973750385db83f266794e78d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1324, "license_type": "permissive", "max_line_length": 79, "num_lines": 45, "path": "/tests/settings/sqlite_sentinel.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "SECRET_KEY = \"django_tests_secret_key\"\n\nDJANGO_REDIS_CONNECTION_FACTORY = \"django_redis.pool.SentinelConnectionFactory\"\n\nSENTINELS = [(\"127.0.0.1\", 26379)]\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": [\"redis://default_service?db=5\"],\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"SENTINELS\": SENTINELS,\n },\n },\n \"doesnotexist\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://missing_service?db=1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"SENTINELS\": SENTINELS,\n },\n },\n \"sample\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://default_service?db=1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.SentinelClient\",\n \"SENTINELS\": SENTINELS,\n },\n },\n \"with_prefix\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://default_service?db=1\",\n \"KEY_PREFIX\": \"test-prefix\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"SENTINELS\": SENTINELS,\n },\n },\n}\n\nINSTALLED_APPS = [\"django.contrib.sessions\"]\n\nUSE_TZ = False\n" }, { "alpha_fraction": 0.7281795740127563, "alphanum_fraction": 0.7281795740127563, "avg_line_length": 24.0625, "blob_id": "98fba3a1bf1c902cabe0734df12cddbf88c9c499", "content_id": "06e62542f93f522a642b450aa225a11a1f6a490a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "permissive", "max_line_length": 65, "num_lines": 16, "path": "/django_redis/serializers/json.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import json\nfrom typing import Any\n\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nfrom .base import BaseSerializer\n\n\nclass JSONSerializer(BaseSerializer):\n encoder_class = DjangoJSONEncoder\n\n def dumps(self, value: Any) -> bytes:\n return json.dumps(value, cls=self.encoder_class).encode()\n\n def loads(self, value: bytes) -> Any:\n return json.loads(value.decode())\n" }, { "alpha_fraction": 0.718406617641449, "alphanum_fraction": 0.7293956279754639, "avg_line_length": 44.5, "blob_id": "5b050cf3d5b3c879e766068ed8f970893c49d496", "content_id": "794f5fe713dcfde503d6ef0ccd2246e7cc38260e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 728, "license_type": "permissive", "max_line_length": 90, "num_lines": 16, "path": "/RELEASING.rst", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "Preparing a Release\n===================\n\nThe following steps are needed to prepare a release:\n\n1. Make sure the VERSION in ``django_redis/__init__.py`` has been updated.\n2. Run ``towncrier build`` to update the ``CHANGELOG.rst`` with the\n news fragments for the release.\n3. Commit the changes for steps 1 and 2.\n4. Tag the commit with the same version as specified for VERSION in step 1.\n5. Wait for the `release action`_ to complete, which will upload the package\n to `django-redis jazzband`_, and when it's complete you can then release\n the package to PyPI.\n\n.. _release action: https://github.com/jazzband/django-redis/actions/workflows/release.yml\n.. _django-redis jazzband: https://jazzband.co/projects/django-redis\n" }, { "alpha_fraction": 0.6242566704750061, "alphanum_fraction": 0.6244131326675415, "avg_line_length": 32.80952453613281, "blob_id": "3df799b631459db5ae3921d8096fd5a3535933e1", "content_id": "44afa9436e242395009ea6ef94ce84f2e10405a2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6390, "license_type": "permissive", "max_line_length": 87, "num_lines": 189, "path": "/django_redis/pool.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from typing import Dict\nfrom urllib.parse import parse_qs, urlparse\n\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.module_loading import import_string\nfrom redis import Redis\nfrom redis.connection import DefaultParser, to_bool\nfrom redis.sentinel import Sentinel\n\n\nclass ConnectionFactory:\n # Store connection pool by cache backend options.\n #\n # _pools is a process-global, as otherwise _pools is cleared every time\n # ConnectionFactory is instantiated, as Django creates new cache client\n # (DefaultClient) instance for every request.\n\n _pools: Dict[str, Redis] = {}\n\n def __init__(self, options):\n pool_cls_path = options.get(\n \"CONNECTION_POOL_CLASS\", \"redis.connection.ConnectionPool\"\n )\n self.pool_cls = import_string(pool_cls_path)\n self.pool_cls_kwargs = options.get(\"CONNECTION_POOL_KWARGS\", {})\n\n redis_client_cls_path = options.get(\"REDIS_CLIENT_CLASS\", \"redis.client.Redis\")\n self.redis_client_cls = import_string(redis_client_cls_path)\n self.redis_client_cls_kwargs = options.get(\"REDIS_CLIENT_KWARGS\", {})\n\n self.options = options\n\n def make_connection_params(self, url):\n \"\"\"\n Given a main connection parameters, build a complete\n dict of connection parameters.\n \"\"\"\n\n kwargs = {\n \"url\": url,\n \"parser_class\": self.get_parser_cls(),\n }\n\n password = self.options.get(\"PASSWORD\", None)\n if password:\n kwargs[\"password\"] = password\n\n socket_timeout = self.options.get(\"SOCKET_TIMEOUT\", None)\n if socket_timeout:\n assert isinstance(\n socket_timeout, (int, float)\n ), \"Socket timeout should be float or integer\"\n kwargs[\"socket_timeout\"] = socket_timeout\n\n socket_connect_timeout = self.options.get(\"SOCKET_CONNECT_TIMEOUT\", None)\n if socket_connect_timeout:\n assert isinstance(\n socket_connect_timeout, (int, float)\n ), \"Socket connect timeout should be float or integer\"\n kwargs[\"socket_connect_timeout\"] = socket_connect_timeout\n\n return kwargs\n\n def connect(self, url: str) -> Redis:\n \"\"\"\n Given a basic connection parameters,\n return a new connection.\n \"\"\"\n params = self.make_connection_params(url)\n connection = self.get_connection(params)\n return connection\n\n def disconnect(self, connection):\n \"\"\"\n Given a not null client connection it disconnect from the Redis server.\n\n The default implementation uses a pool to hold connections.\n \"\"\"\n connection.connection_pool.disconnect()\n\n def get_connection(self, params):\n \"\"\"\n Given a now preformatted params, return a\n new connection.\n\n The default implementation uses a cached pools\n for create new connection.\n \"\"\"\n pool = self.get_or_create_connection_pool(params)\n return self.redis_client_cls(\n connection_pool=pool, **self.redis_client_cls_kwargs\n )\n\n def get_parser_cls(self):\n cls = self.options.get(\"PARSER_CLASS\", None)\n if cls is None:\n return DefaultParser\n return import_string(cls)\n\n def get_or_create_connection_pool(self, params):\n \"\"\"\n Given a connection parameters and return a new\n or cached connection pool for them.\n\n Reimplement this method if you want distinct\n connection pool instance caching behavior.\n \"\"\"\n key = params[\"url\"]\n if key not in self._pools:\n self._pools[key] = self.get_connection_pool(params)\n return self._pools[key]\n\n def get_connection_pool(self, params):\n \"\"\"\n Given a connection parameters, return a new\n connection pool for them.\n\n Overwrite this method if you want a custom\n behavior on creating connection pool.\n \"\"\"\n cp_params = dict(params)\n cp_params.update(self.pool_cls_kwargs)\n pool = self.pool_cls.from_url(**cp_params)\n\n if pool.connection_kwargs.get(\"password\", None) is None:\n pool.connection_kwargs[\"password\"] = params.get(\"password\", None)\n pool.reset()\n\n return pool\n\n\nclass SentinelConnectionFactory(ConnectionFactory):\n def __init__(self, options):\n # allow overriding the default SentinelConnectionPool class\n options.setdefault(\n \"CONNECTION_POOL_CLASS\", \"redis.sentinel.SentinelConnectionPool\"\n )\n super().__init__(options)\n\n sentinels = options.get(\"SENTINELS\")\n if not sentinels:\n raise ImproperlyConfigured(\n \"SENTINELS must be provided as a list of (host, port).\"\n )\n\n # provide the connection pool kwargs to the sentinel in case it\n # needs to use the socket options for the sentinels themselves\n connection_kwargs = self.make_connection_params(None)\n connection_kwargs.pop(\"url\")\n connection_kwargs.update(self.pool_cls_kwargs)\n self._sentinel = Sentinel(\n sentinels,\n sentinel_kwargs=options.get(\"SENTINEL_KWARGS\"),\n **connection_kwargs,\n )\n\n def get_connection_pool(self, params):\n \"\"\"\n Given a connection parameters, return a new sentinel connection pool\n for them.\n \"\"\"\n url = urlparse(params[\"url\"])\n\n # explicitly set service_name and sentinel_manager for the\n # SentinelConnectionPool constructor since will be called by from_url\n cp_params = dict(params)\n cp_params.update(service_name=url.hostname, sentinel_manager=self._sentinel)\n pool = super().get_connection_pool(cp_params)\n\n # convert \"is_master\" to a boolean if set on the URL, otherwise if not\n # provided it defaults to True.\n is_master = parse_qs(url.query).get(\"is_master\")\n if is_master:\n pool.is_master = to_bool(is_master[0])\n\n return pool\n\n\ndef get_connection_factory(path=None, options=None):\n if path is None:\n path = getattr(\n settings,\n \"DJANGO_REDIS_CONNECTION_FACTORY\",\n \"django_redis.pool.ConnectionFactory\",\n )\n\n cls = import_string(path)\n return cls(options or {})\n" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.5939849615097046, "avg_line_length": 23.18181800842285, "blob_id": "e59ffa61feba276a324c72aed3ce8a72c38d88e9", "content_id": "4cf54e93cc9ab413455ad343a8d8822e28803b74", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "permissive", "max_line_length": 78, "num_lines": 11, "path": "/django_redis/util.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "class CacheKey(str):\n \"\"\"\n A stub string class that we can use to check if a key was created already.\n \"\"\"\n\n def original_key(self) -> str:\n return self.rsplit(\":\", 1)[1]\n\n\ndef default_reverse_key(key: str) -> str:\n return key.split(\":\", 2)[2]\n" }, { "alpha_fraction": 0.6581512093544006, "alphanum_fraction": 0.6613999009132385, "avg_line_length": 36.414363861083984, "blob_id": "e608d347f008b3b21175449f7638851afa37b66a", "content_id": "743086576c3027b5fbc6ec1c66a5473852f0af6f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6772, "license_type": "permissive", "max_line_length": 88, "num_lines": 181, "path": "/tests/test_client.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from typing import Iterable\nfrom unittest.mock import Mock, call, patch\n\nimport pytest\nfrom django.core.cache import DEFAULT_CACHE_ALIAS\nfrom pytest_django.fixtures import SettingsWrapper\nfrom pytest_mock import MockerFixture\n\nfrom django_redis.cache import RedisCache\nfrom django_redis.client import DefaultClient, ShardClient\n\n\[email protected]\ndef cache_client(cache: RedisCache) -> Iterable[DefaultClient]:\n client = cache.client\n client.set(\"TestClientClose\", 0)\n yield client\n client.delete(\"TestClientClose\")\n\n\nclass TestClientClose:\n def test_close_client_disconnect_default(\n self, cache_client: DefaultClient, mocker: MockerFixture\n ):\n mock = mocker.patch.object(cache_client.connection_factory, \"disconnect\")\n cache_client.close()\n assert not mock.called\n\n def test_close_disconnect_settings(\n self,\n cache_client: DefaultClient,\n settings: SettingsWrapper,\n mocker: MockerFixture,\n ):\n settings.DJANGO_REDIS_CLOSE_CONNECTION = True\n mock = mocker.patch.object(cache_client.connection_factory, \"disconnect\")\n cache_client.close()\n assert mock.called\n\n def test_close_disconnect_settings_cache(\n self,\n cache_client: DefaultClient,\n mocker: MockerFixture,\n settings: SettingsWrapper,\n ):\n settings.CACHES[DEFAULT_CACHE_ALIAS][\"OPTIONS\"][\"CLOSE_CONNECTION\"] = True\n cache_client.set(\"TestClientClose\", 0)\n mock = mocker.patch.object(cache_client.connection_factory, \"disconnect\")\n cache_client.close()\n assert mock.called\n\n def test_close_disconnect_client_options(\n self, cache_client: DefaultClient, mocker: MockerFixture\n ):\n cache_client._options[\"CLOSE_CONNECTION\"] = True\n mock = mocker.patch.object(cache_client.connection_factory, \"disconnect\")\n cache_client.close()\n assert mock.called\n\n\nclass TestDefaultClient:\n @patch(\"test_client.DefaultClient.get_client\")\n @patch(\"test_client.DefaultClient.__init__\", return_value=None)\n def test_delete_pattern_calls_get_client_given_no_client(\n self, init_mock, get_client_mock\n ):\n client = DefaultClient()\n client._backend = Mock()\n client._backend.key_prefix = \"\"\n\n client.delete_pattern(pattern=\"foo*\")\n get_client_mock.assert_called_once_with(write=True)\n\n @patch(\"test_client.DefaultClient.make_pattern\")\n @patch(\"test_client.DefaultClient.get_client\", return_value=Mock())\n @patch(\"test_client.DefaultClient.__init__\", return_value=None)\n def test_delete_pattern_calls_make_pattern(\n self, init_mock, get_client_mock, make_pattern_mock\n ):\n client = DefaultClient()\n client._backend = Mock()\n client._backend.key_prefix = \"\"\n get_client_mock.return_value.scan_iter.return_value = []\n\n client.delete_pattern(pattern=\"foo*\")\n\n kwargs = {\"version\": None, \"prefix\": None}\n make_pattern_mock.assert_called_once_with(\"foo*\", **kwargs)\n\n @patch(\"test_client.DefaultClient.make_pattern\")\n @patch(\"test_client.DefaultClient.get_client\", return_value=Mock())\n @patch(\"test_client.DefaultClient.__init__\", return_value=None)\n def test_delete_pattern_calls_scan_iter_with_count_if_itersize_given(\n self, init_mock, get_client_mock, make_pattern_mock\n ):\n client = DefaultClient()\n client._backend = Mock()\n client._backend.key_prefix = \"\"\n get_client_mock.return_value.scan_iter.return_value = []\n\n client.delete_pattern(pattern=\"foo*\", itersize=90210)\n\n get_client_mock.return_value.scan_iter.assert_called_once_with(\n count=90210, match=make_pattern_mock.return_value\n )\n\n @patch(\"test_client.DefaultClient.make_pattern\")\n @patch(\"test_client.DefaultClient.get_client\", return_value=Mock())\n @patch(\"test_client.DefaultClient.__init__\", return_value=None)\n def test_delete_pattern_calls_pipeline_delete_and_execute(\n self, init_mock, get_client_mock, make_pattern_mock\n ):\n client = DefaultClient()\n client._backend = Mock()\n client._backend.key_prefix = \"\"\n get_client_mock.return_value.scan_iter.return_value = [\":1:foo\", \":1:foo-a\"]\n get_client_mock.return_value.pipeline.return_value = Mock()\n get_client_mock.return_value.pipeline.return_value.delete = Mock()\n get_client_mock.return_value.pipeline.return_value.execute = Mock()\n\n client.delete_pattern(pattern=\"foo*\")\n\n assert get_client_mock.return_value.pipeline.return_value.delete.call_count == 2\n get_client_mock.return_value.pipeline.return_value.delete.assert_has_calls(\n [call(\":1:foo\"), call(\":1:foo-a\")]\n )\n get_client_mock.return_value.pipeline.return_value.execute.assert_called_once()\n\n\nclass TestShardClient:\n @patch(\"test_client.DefaultClient.make_pattern\")\n @patch(\"test_client.ShardClient.__init__\", return_value=None)\n def test_delete_pattern_calls_scan_iter_with_count_if_itersize_given(\n self, init_mock, make_pattern_mock\n ):\n client = ShardClient()\n client._backend = Mock()\n client._backend.key_prefix = \"\"\n\n connection = Mock()\n connection.scan_iter.return_value = []\n client._serverdict = {\"test\": connection}\n\n client.delete_pattern(pattern=\"foo*\", itersize=10)\n\n connection.scan_iter.assert_called_once_with(\n count=10, match=make_pattern_mock.return_value\n )\n\n @patch(\"test_client.DefaultClient.make_pattern\")\n @patch(\"test_client.ShardClient.__init__\", return_value=None)\n def test_delete_pattern_calls_scan_iter(self, init_mock, make_pattern_mock):\n client = ShardClient()\n client._backend = Mock()\n client._backend.key_prefix = \"\"\n connection = Mock()\n connection.scan_iter.return_value = []\n client._serverdict = {\"test\": connection}\n\n client.delete_pattern(pattern=\"foo*\")\n\n connection.scan_iter.assert_called_once_with(\n match=make_pattern_mock.return_value\n )\n\n @patch(\"test_client.DefaultClient.make_pattern\")\n @patch(\"test_client.ShardClient.__init__\", return_value=None)\n def test_delete_pattern_calls_delete_for_given_keys(\n self, init_mock, make_pattern_mock\n ):\n client = ShardClient()\n client._backend = Mock()\n client._backend.key_prefix = \"\"\n connection = Mock()\n connection.scan_iter.return_value = [Mock(), Mock()]\n connection.delete.return_value = 0\n client._serverdict = {\"test\": connection}\n\n client.delete_pattern(pattern=\"foo*\")\n\n connection.delete.assert_called_once_with(*connection.scan_iter.return_value)\n" }, { "alpha_fraction": 0.6379310488700867, "alphanum_fraction": 0.6761399507522583, "avg_line_length": 29.626691818237305, "blob_id": "91c7112281e8a9401fe7355e81190e42dfbe9d6d", "content_id": "f802d1856a6b6888e51f29a2f78b2e69a6f72203", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 15835, "license_type": "permissive", "max_line_length": 225, "num_lines": 517, "path": "/CHANGELOG.rst", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "Changelog\n=========\n\n.. towncrier release notes start\n\ndjango-redis 5.3.0 (2023-06-16)\n===============================\n\nFeatures\n--------\n\n- Add support for django 4 (`#627 <https://github.com/jazzband/django-redis/issues/627>`_)\n\n\nBug Fixes\n---------\n\n- Access `django_redis.cache.DJANGO_REDIS_SCAN_ITERSIZE` and `django_redis.client.herd.CACHE_HERD_TIMEOUT` in runtime to not read Django settings in import time. (`#638 <https://github.com/jazzband/django-redis/issues/638>`_)\n- Skipping pickle serializer test for django >= 4.2 (`#646 <https://github.com/jazzband/django-redis/issues/646>`_)\n\n\nMiscellaneous\n-------------\n\n- Speed up deleting multiple keys by a pattern with pipelines and larger itersize (`#609 <https://github.com/jazzband/django-redis/issues/609>`_)\n- Print full exception traceback when logging ignored exceptions (`#611 <https://github.com/jazzband/django-redis/issues/611>`_)\n- Fix mypy linting (`#626 <https://github.com/jazzband/django-redis/issues/626>`_)\n- Added support for python 3.11 (`#633 <https://github.com/jazzband/django-redis/issues/633>`_)\n- Fix CI, running tox<4 to still support Python 3.6. (`#645 <https://github.com/jazzband/django-redis/issues/645>`_)\n- Dropped support for django 2.2 and 3.1 (`#649 <https://github.com/jazzband/django-redis/issues/649>`_)\n- Run actions & tox against Django 4..2 (`#668 <https://github.com/jazzband/django-redis/issues/668>`_)\n\n\ndjango-redis 5.2.0 (2021-12-22)\n===============================\n\nBug Fixes\n---------\n\n- Block use with broken redis-py 4.0.0 and 4.0.1 (`#542 <https://github.com/jazzband/django-redis/issues/542>`_)\n\n\nMiscellaneous\n-------------\n\n- Unblock redis-py >=4.0.2 (`#576 <https://github.com/jazzband/django-redis/issues/576>`_)\n- Add support for django 4 (`#579 <https://github.com/jazzband/django-redis/issues/579>`_)\n\n\nDjango_Redis 5.1.0 (2021-11-29)\n===============================\n\nFeatures\n--------\n\n- Add Python 3.10 to CI (`#536 <https://github.com/jazzband/django-redis/issues/536>`_)\n- Configured ``towncrier`` to generate the changelog. (`#548 <https://github.com/jazzband/django-redis/issues/548>`_)\n- Added ``django_redis.compressors.zstd.ZStdCompressor`` to provide ``pyzstd`` cache value compression. (`#551 <https://github.com/jazzband/django-redis/issues/551>`_)\n- Change pickle default version to Python default instead of highest version. (`#555 <https://github.com/jazzband/django-redis/issues/555>`_)\n- Add ``hiredis`` extra dependency to request ``redis[hiredis]``. (`#556 <https://github.com/jazzband/django-redis/issues/556>`_)\n- Add pexpireat to allow setting 'expire at' with millisecond precision. (`#564 <https://github.com/jazzband/django-redis/issues/564>`_)\n\n\nBug Fixes\n---------\n\n- Make expire, pexpire, expireat and persist return the redis client value (`#564 <https://github.com/jazzband/django-redis/issues/564>`_)\n\n\nMiscellaneous\n-------------\n\n- Convert most unittest class tests to pytest tests. (`#553 <https://github.com/jazzband/django-redis/issues/553>`_)\n- Update type comments to type annotations. (`#568 <https://github.com/jazzband/django-redis/issues/568>`_)\n- Pin redis-py to 3.x until 4.x breaking changes can be addressed. (`#570 <https://github.com/jazzband/django-redis/issues/570>`_)\n\n\nDocumentation\n-------------\n\n- Clarify redis primary name in sentinel documentation. (`#529 <https://github.com/jazzband/django-redis/issues/529>`_)\n- Add documentation on configuring self signed SSL certificates. (`#559 <https://github.com/jazzband/django-redis/issues/559>`_)\n\n\ndjango-redis 5.0.0 (2021-05-30)\n===============================\n\n- supporting django 3.1 and django 3.2\n- dropped support for python 3.5\n- added support for python 3.9\n- started type hinting the codebase\n- ensure connections are closed\n- fixed ``ShardClient`` ``.clear()`` method\n- ``.delete()`` now returns boolean from django 3.1 onwards\n- disconnect connection pools on ``.close()``\n- added support for redis sentinel\n- added ``.expire_at()`` method\n- fixed ``.incr()`` when ttl is ``None`` or when the number is larger than 64 bit\n- fixed ``.incr_version()`` when ttl is ``None``\n- added ``.pttl()`` method to the clients to support milli-second precision for\n ttl of a key\n- added ``.pexpire()`` method to the clients to support milli-second precision\n for setting expiry of a key\n\n\ndjango-redis 4.12.1 (2020-05-27)\n================================\n\n- No code changes.\n- Fixed a typo in setup.cfg metadata preventing a successful release.\n\n\ndjango-redis 4.12.0 (2020-05-27)\n================================\n\n- The project has moved to `Jazzband <https://jazzband.co/>`_. This is the\n first release under the new organization. The new repository URL is\n `<https://github.com/jazzband/django-redis>`_.\n- Removed support for end-of-life Django < 2.2.\n- Removed support for unmaintained redis-py 2.X.\n- Changed uses of deprecated ``smart_text()`` to ``smart_str()``.\n- Fixed deprecation warning with the msgpack serializer.\n- The ``.touch()`` method now uses the default timeout, to cache forever pass\n ``None``.\n- Subclasses of ``JSONSerializer`` can now override the ``encoder_class``\n attribute to change the JSON encoder. It defaults to ``DjangoJSONEncoder``.\n- Fixed ``DefaultClient.set()`` to work with empty ``Pipeline``.\n- The ``thread_local`` parameter is now forwarded to the Redis client.\n\n\ndjango-redis 4.11.0 (2019-12-13)\n================================\n\n- Removed support for Python 2.7 and 3.4.\n- Removed support for Django 2.0 and 2.1.\n- Added support for Python 3.8.\n- Added support for Django 2.2 and 3.0.\n- Changed msgpack-python soft dependency to msgpack.\n- Fixed ``.touch()`` method for sharded client.\n- Fixed prefix escaping for the sharded client.\n- Fixed ``.add()`` method to return a bool.\n\n\ndjango-redis 4.10.0 (2018-10-19)\n================================\n\n- Add support and testing for Django 2.1 and Python 3.7. No actual code changes\n were required.\n- Add support for redis-py 3.0.\n- Add touch command.\n\n\ndjango-redis 4.9.1 (2018-10-19)\n===============================\n\n- Pin redis version to 2.10.6\n\n\ndjango-redis 4.9.0 (2018-03-01)\n===============================\n\n- Add testing and support for Django 2.0. No actual code changes were required.\n- Escape ``KEY_PREFIX`` and ``VERSION`` when used in glob expressions.\n- Improve handling timeouts less than 1ms.\n- Remove fakeredis support.\n- Add datetime, date, time, and timedelta serialization support to the JSON\n serializer.\n- The deprecated feature of passing ``True`` as a timeout value is no longer\n supported.\n- Fix ``add()`` with a negative timeout to not store key (it is immediately\n invalid).\n- Remove support for Django < 1.11.\n- Add support for atomic incr if key is not set.\n\n\ndjango-redis 4.8.0 (2017-04-25)\n===============================\n\n- Drop deprecated exception with typo ConnectionInterrumped. Use\n ConnectionInterrupted instead.\n- Remove many workarounds related to old and not supported versions\n of django and redis-py.\n- Code cleaning and flake8 compliance fixes.\n- Add better impl for ``close`` method.\n- Fix compatibility warnings with python 3.6\n\n\ndjango-redis 4.7.0 (2017-01-02)\n===============================\n\n- Add the ability to enable write to replica servers when the primary server is\n not available.\n- Add ``itersize`` parameter to ``delete_pattern``.\n\n\ndjango-redis 4.6.0 (2016-11-02)\n===============================\n\n- Fix incorrect behavior of ``clear()`` method.\n\n\ndjango-redis 4.5.0 (2016-09-21)\n===============================\n\n- Now only support Django 1.8 and above. Support for older versions has been dropped.\n- Remove undocumented and deprecated support for old connection string format.\n- Add support for ``PASSWORD`` option (useful when the password contains url unsafe\n characters).\n- Make the package compatible with fake redis.\n- Fix compatibility issues with latest django version (1.10).\n\n\ndjango-redis 4.4.4 (2016-07-25)\n===============================\n\n- Fix possible race condition on incr implementation using\n lua script (thanks to @prokaktus).\n\n\ndjango-redis 4.4.3 (2016-05-17)\n===============================\n\n- Fix minor ttl inconsistencies.\n\n\ndjango-redis 4.4.2 (2016-04-21)\n===============================\n\n- Fix timeout bug (thanks to @skorokithakis)\n\n\ndjango-redis 4.4.1 (2016-04-13)\n===============================\n\n- Add additional check for avoid wrong exception on ``get_redis_connection``.\n\n\ndjango-redis 4.4.0 (2016-04-12)\n===============================\n\n- Make redis client pluggable (thanks to @arnuschky)\n- Add version number inside python module (thanks to @BertrandBordage)\n- Fix clear method (thanks to @ostcar)\n- Add the ability to specify key prefix on delete and delete_pattern.\n- BREAKING CHANGE: improved compression support (make it more plugable).\n\n\ndjango-redis 4.3.0 (2015-10-31)\n===============================\n\n- Improved exception handling in herd client (thanks to @brandoshmando)\n- Fix bug that not allows use generators on delete_many (thanks to @ostcar).\n- Remove obsolete code that makes hard dependency to mspack.\n\n\ndjango-redis 4.2.0 (2015-07-03)\n===============================\n\n- Add ``persist`` and ``expire`` methods.\n- Remove old and broken dummy client.\n- Expose a redis lock method.\n\n\ndjango-redis 4.1.0 (2015-06-15)\n===============================\n\n- Add plugable serializers architecture (thanks to @jdufresne)\n- Add json serializer (thanks to @jdufresne)\n- Add msgpack serializer (thanks to @uditagarwal)\n- Implement delete_pattern using iter_scan for better performance (thanks to @lenzenmi)\n\n\ndjango-redis 4.0.0\n==================\n\n- Remove usage of deprecated ``get_cache`` method.\n- Added connection option SOCKET_CONNECT_TIMEOUT. [Jorge C. Leitão].\n- Replace ``setex`` and friends with set, because it now supports all need for atomic.\n updates (thanks to @23doors) (re revert changes from 3.8.x branch).\n- Fix django 1.8 compatibilities.\n- Fix django 1.9 compatibilities.\n- BREAKING CHANGE: Now timeout=0 works as django specified (expires immediately)\n- Now requires redis server >= 2.8\n- BREAKING CHANGE: ``redis_cache`` is no longer a valid package name\n\n\ndjango-redis 3.8.4\n==================\n\n- Backport django 1.8 fixes from master.\n\n\ndjango-redis 3.8.3\n==================\n\n- Minor fix on regular expression for old url notation.\n\n\ndjango-redis 3.8.2\n==================\n\n- Revert some changes from 3.8.1 that are incompatible with redis server < 2.6.12\n\n\ndjango-redis 3.8.1\n==================\n\n- Fix documentation related to new url format.\n- Fix documentation parts that uses now removed functions.\n- Fix invalid url transformation from old format (password was not set properly)\n- Replace setex and friends with set, because it now supports all need for atomic\n updates (thanks to @23doors).\n\n\ndjango-redis 3.8.0\n==================\n\n- Add compression support. (Thanks to @alanjds)\n- Change package name from redis_cache to django_redis.\n- Add backward compatibility layer for redis_cache package name.\n- BACKWARD INCOMPATIBLE CHANGE: use StrictRedis instead of Redis class of redis-py\n- Add redis dummy backend for development purposes. (Thanks to @papaloizouc)\n- Now use redis native url notation for connection string (the own connection string\n notation is also supported but is marked as deprecated).\n- Now requires redis-py >= 2.10.0\n- Remove deprecated ``raw_cache`` property from backend.\n\n\ndjango-redis 3.7.2\n==================\n\n- Add missing forward of version parameter from ``add()`` to ``set()`` function. (by @fellowshipofone)\n\n\ndjango-redis 3.7.1\n==================\n\n- Improve docs (by @dkingman).\n- Fix missing imports on sentinel client (by @opapy).\n- Connection closing improvements on sentinel client (by @opapy).\n\n\ndjango-redis 3.7.0\n==================\n\n- Add support for django's ``KEY_FUNCTION`` and ``REVERSE_KEY_FUNCTION`` (by @teferi)\n- Accept float value for socket timeout.\n- Fix wrong behavior of ``DJANGO_REDIS_IGNORE_EXCEPTIONS`` with socket timeouts.\n- Backward incompatible change: now raises original exceptions instead of self defined.\n\n\ndjango-redis 3.6.2\n==================\n\n- Add ttl method purposed to be included in django core.\n- Add iter_keys method that uses redis scan methods for memory efficient keys retrieval.\n- Add version keyword parameter to keys.\n- Deprecate django 1.3.x support.\n\n\ndjango-redis 3.6.1\n==================\n\n- Fix wrong import on sentinel client.\n\n\ndjango-redis 3.6.0\n==================\n\n- Add pluggable connection factory.\n- Negative timeouts now works as expected.\n- Delete operation now returns a number of deleted items instead of None.\n\n\ndjango-redis 3.5.1\n==================\n\n- Fixed redis-py < 2.9.0 incompatibilities\n- Fixed runtests error with django 1.7\n\n\ndjango-redis 3.5.0\n==================\n\n- Removed: stats module (should be replaced with an other in future)\n- New: experimental client for add support to redis-sentinel.\n- Now uses a django ``DEFAULT_TIMEOUT`` constant instead of ``True``.\n Deprecation warning added for code that now uses ``True`` (unlikely).\n- Fix wrong forward of timeout on shard client.\n- Fix incr_version wrong behavior when using shard client (wrong client used for set new key).\n\n\ndjango-redis 3.4.0\n==================\n\n- Fix exception name from ConnectionInterrumped to\n ConnectionInterrupted maintaining an old exception class\n for backward compatibility (thanks Łukasz Langa (@ambv))\n\n- Fix wrong behavior for \"default\" parameter on get method\n when DJANGO_REDIS_IGNORE_EXCEPTIONS is True\n (also thanks to Łukasz Langa (@ambv)).\n\n- Now added support for replication setups to default client (it still\n experimental because is not tested in production environments).\n\n- Merged SimpleFailoverClient experimental client (only for\n experiment with it, not ready for use in production)\n\n- Django 1.6 cache changes compatibility. Explicitly passing in\n timeout=None no longer results in using the default timeout.\n\n- Major code cleaning. (Thanks to Bertrand Bordage @BertrandBordage)\n\n- Bugfixes related to some index error on hashring module.\n\n\ndjango-redis 3.3.0\n==================\n\n- Add SOCKET_TIMEOUT attribute to OPTIONS (thanks to @eclipticplane)\n\n\ndjango-redis 3.2.0\n==================\n\n- Changed default behavior of connection error exceptions: now by default\n raises exception on connection error is occurred.\n\nThanks to Mümin Öztürk:\n\n- cache.add now uses setnx redis command (atomic operation)\n- cache.incr and cache.decr now uses redis incrby command (atomic operation)\n\n\ndjango-redis 3.1.7\n==================\n\n- Fix python3 compatibility on utils module.\n\ndjango-redis 3.1.6\n==================\n\n- Add nx argument on set method for both clients (thanks to Kirill Zaitsev)\n\n\ndjango-redis 3.1.5\n==================\n\n- Bug fixes on sharded client.\n\n\ndjango-redis 3.1.4\n==================\n\n- Now reuse connection pool on massive use of ``get_cache`` method.\n\n\ndjango-redis 3.1.3\n==================\n\n- Fixed python 2.6 compatibility.\n\n\ndjango-redis 3.1.2\n==================\n\n- Now on call close() not disconnect all connection pool.\n\n\ndjango-redis 3.1.1\n==================\n\n- Fixed incorrect exception message on LOCATION has wrong format.\n (Thanks to Yoav Weiss)\n\n\ndjango-redis 3.1\n================\n\n- Helpers for access to raw redis connection.\n\n\ndjango-redis 3.0\n================\n\n- Python 3.2+ support.\n- Code cleaning and refactor.\n- Ignore exceptions (same behavior as memcached backend)\n- Pluggable clients.\n- Unified connection string.\n\n\ndjango-redis 2.2.2\n==================\n\n- Bug fixes on ``keys`` and ``delete_pattern`` methods.\n\n\ndjango-redis 2.2.1\n==================\n\n- Remove duplicate check if key exists on ``incr`` method.\n- Fix incorrect behavior of ``delete_pattern`` with sharded client.\n\n\ndjango-redis 2.2\n================\n\n- New ``delete_pattern`` method. Useful for delete keys using wildcard syntax.\n\n\ndjango-redis 2.1\n================\n\n- Many bug fixes.\n- Client side sharding.\n" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 34, "blob_id": "7d1576c828a3cb0030177be89acbed0d66d0e89e", "content_id": "ba40c4a86d0200fc68af606492433ccad2f016d2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "permissive", "max_line_length": 74, "num_lines": 6, "path": "/django_redis/client/__init__.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from .default import DefaultClient\nfrom .herd import HerdClient\nfrom .sentinel import SentinelClient\nfrom .sharded import ShardClient\n\n__all__ = [\"DefaultClient\", \"HerdClient\", \"SentinelClient\", \"ShardClient\"]\n" }, { "alpha_fraction": 0.5531095266342163, "alphanum_fraction": 0.5619152188301086, "avg_line_length": 30.327587127685547, "blob_id": "f756230fc423dc37d1769e1d494368b5d33dd7ad", "content_id": "be456f7e84c697199401209bb6bd1e5695593e2c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1817, "license_type": "permissive", "max_line_length": 84, "num_lines": 58, "path": "/django_redis/hash_ring.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import bisect\nimport hashlib\nfrom typing import Dict, Iterable, Iterator, List, Optional, Tuple\n\n\nclass HashRing:\n nodes: List[str] = []\n\n def __init__(self, nodes: Iterable[str] = (), replicas: int = 128) -> None:\n self.replicas: int = replicas\n self.ring: Dict[str, str] = {}\n self.sorted_keys: List[str] = []\n\n for node in nodes:\n self.add_node(node)\n\n def add_node(self, node: str) -> None:\n self.nodes.append(node)\n\n for x in range(self.replicas):\n _key = f\"{node}:{x}\"\n _hash = hashlib.sha256(_key.encode()).hexdigest()\n\n self.ring[_hash] = node\n self.sorted_keys.append(_hash)\n\n self.sorted_keys.sort()\n\n def remove_node(self, node: str) -> None:\n self.nodes.remove(node)\n for x in range(self.replicas):\n _hash = hashlib.sha256(f\"{node}:{x}\".encode()).hexdigest()\n del self.ring[_hash]\n self.sorted_keys.remove(_hash)\n\n def get_node(self, key: str) -> Optional[str]:\n n, i = self.get_node_pos(key)\n return n\n\n def get_node_pos(self, key: str) -> Tuple[Optional[str], Optional[int]]:\n if len(self.ring) == 0:\n return None, None\n\n _hash = hashlib.sha256(key.encode()).hexdigest()\n idx = bisect.bisect(self.sorted_keys, _hash)\n idx = min(idx - 1, (self.replicas * len(self.nodes)) - 1)\n return self.ring[self.sorted_keys[idx]], idx\n\n def iter_nodes(self, key: str) -> Iterator[Tuple[Optional[str], Optional[str]]]:\n if len(self.ring) == 0:\n yield None, None\n\n node, pos = self.get_node_pos(key)\n for k in self.sorted_keys[pos:]:\n yield k, self.ring[k]\n\n def __call__(self, key: str) -> Optional[str]:\n return self.get_node(key)\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 19.16666603088379, "blob_id": "4d83a687e983414942ff961c7d1e3612472e89a2", "content_id": "59ea7d8dbe47b6a4e87edf887d92793e01f57439", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "permissive", "max_line_length": 52, "num_lines": 12, "path": "/tests/conftest.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from typing import Iterable\n\nimport pytest\nfrom django.core.cache import cache as default_cache\n\nfrom django_redis.cache import BaseCache\n\n\[email protected]\ndef cache() -> Iterable[BaseCache]:\n yield default_cache\n default_cache.clear()\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 47.846153259277344, "blob_id": "3d69273dd3fbe004930dd634937deae022e201bc", "content_id": "0752408d3ad892cf5ac9c80055a6610c15f9b9ba", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 635, "license_type": "permissive", "max_line_length": 86, "num_lines": 13, "path": "/pyproject.toml", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "[tool.towncrier]\ndirectory = \"changelog.d\"\nfilename = \"CHANGELOG.rst\"\nissue_format = \"`#{issue} <https://github.com/jazzband/django-redis/issues/{issue}>`_\"\nname = \"django-redis\"\npackage = \"django_redis\"\ntype = [\n { name = \"Features\", directory = \"feature\", showcontent = true },\n { name = \"Bug Fixes\", directory = \"bugfix\", showcontent = true },\n { name = \"Miscellaneous\", directory = \"misc\", showcontent = true },\n { name = \"Documentation\", directory = \"doc\", showcontent = true },\n { name = \"Deprecations and Removals\", directory = \"removal\", showcontent = true },\n]\n" }, { "alpha_fraction": 0.5494012236595154, "alphanum_fraction": 0.576347291469574, "avg_line_length": 18.647058486938477, "blob_id": "43f5c9407ba06a25df4ccf6bb9460916e3e32e15", "content_id": "b890adb75eae4db3f74476675e907bd50757d357", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "permissive", "max_line_length": 50, "num_lines": 34, "path": "/tests/test_hashring.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import pytest\n\nfrom django_redis.hash_ring import HashRing\n\n\nclass Node:\n def __init__(self, id):\n self.id = id\n\n def __str__(self):\n return f\"node:{self.id}\"\n\n def __repr__(self):\n return f\"<Node {self.id}>\"\n\n\[email protected]\ndef hash_ring():\n return HashRing([Node(i) for i in range(3)])\n\n\ndef test_hashring(hash_ring):\n ids = []\n\n for key in [f\"test{x}\" for x in range(10)]:\n node = hash_ring.get_node(key)\n ids.append(node.id)\n\n assert ids == [0, 2, 1, 2, 2, 2, 2, 0, 1, 1]\n\n\ndef test_hashring_brute_force(hash_ring):\n for key in (f\"test{x}\" for x in range(10000)):\n assert hash_ring.get_node(key)\n" }, { "alpha_fraction": 0.6399217247962952, "alphanum_fraction": 0.6477494835853577, "avg_line_length": 24.549999237060547, "blob_id": "d67e7215c8cd16cb473b68d6b9de78da8b5fc113", "content_id": "b8c17bcf83115d6740049c350197f86a9c856684", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 511, "license_type": "permissive", "max_line_length": 59, "num_lines": 20, "path": "/django_redis/compressors/lzma.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import lzma\n\nfrom ..exceptions import CompressorError\nfrom .base import BaseCompressor\n\n\nclass LzmaCompressor(BaseCompressor):\n min_length = 100\n preset = 4\n\n def compress(self, value: bytes) -> bytes:\n if len(value) > self.min_length:\n return lzma.compress(value, preset=self.preset)\n return value\n\n def decompress(self, value: bytes) -> bytes:\n try:\n return lzma.decompress(value)\n except lzma.LZMAError as e:\n raise CompressorError(e)\n" }, { "alpha_fraction": 0.5958356261253357, "alphanum_fraction": 0.5968357920646667, "avg_line_length": 32.94444274902344, "blob_id": "b6254fa2f1ea6553ef8b8732deb1d87333c8cb9b", "content_id": "a30e177e9b6f9bdf99e91d96c0de2fefdb254a95", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10998, "license_type": "permissive", "max_line_length": 88, "num_lines": 324, "path": "/django_redis/client/sharded.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import re\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom typing import Union\n\nfrom redis.exceptions import ConnectionError\n\nfrom ..exceptions import ConnectionInterrupted\nfrom ..hash_ring import HashRing\nfrom ..util import CacheKey\nfrom .default import DEFAULT_TIMEOUT, DefaultClient\n\n\nclass ShardClient(DefaultClient):\n _findhash = re.compile(r\".*\\{(.*)\\}.*\", re.I)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n if not isinstance(self._server, (list, tuple)):\n self._server = [self._server]\n\n self._ring = HashRing(self._server)\n self._serverdict = self.connect()\n\n def get_client(self, *args, **kwargs):\n raise NotImplementedError\n\n def connect(self, index=0):\n connection_dict = {}\n for name in self._server:\n connection_dict[name] = self.connection_factory.connect(name)\n return connection_dict\n\n def get_server_name(self, _key):\n key = str(_key)\n g = self._findhash.match(key)\n if g is not None and len(g.groups()) > 0:\n key = g.groups()[0]\n name = self._ring.get_node(key)\n return name\n\n def get_server(self, key):\n name = self.get_server_name(key)\n return self._serverdict[name]\n\n def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().add(\n key=key, value=value, version=version, client=client, timeout=timeout\n )\n\n def get(self, key, default=None, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().get(key=key, default=default, version=version, client=client)\n\n def get_many(self, keys, version=None):\n if not keys:\n return {}\n\n recovered_data = OrderedDict()\n\n new_keys = [self.make_key(key, version=version) for key in keys]\n map_keys = dict(zip(new_keys, keys))\n\n for key in new_keys:\n client = self.get_server(key)\n value = self.get(key=key, version=version, client=client)\n\n if value is None:\n continue\n\n recovered_data[map_keys[key]] = value\n return recovered_data\n\n def set(\n self, key, value, timeout=DEFAULT_TIMEOUT, version=None, client=None, nx=False\n ):\n \"\"\"\n Persist a value to the cache, and set an optional expiration time.\n \"\"\"\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().set(\n key=key, value=value, timeout=timeout, version=version, client=client, nx=nx\n )\n\n def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None):\n \"\"\"\n Set a bunch of values in the cache at once from a dict of key/value\n pairs. This is much more efficient than calling set() multiple times.\n\n If timeout is given, that timeout will be used for the key; otherwise\n the default cache timeout will be used.\n \"\"\"\n for key, value in data.items():\n self.set(key, value, timeout, version=version)\n\n def has_key(self, key, version=None, client=None):\n \"\"\"\n Test if key exists.\n \"\"\"\n\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n key = self.make_key(key, version=version)\n try:\n return client.exists(key) == 1\n except ConnectionError as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def delete(self, key, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().delete(key=key, version=version, client=client)\n\n def ttl(self, key, version=None, client=None):\n \"\"\"\n Executes TTL redis command and return the \"time-to-live\" of specified key.\n If key is a non volatile key, it returns None.\n \"\"\"\n\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().ttl(key=key, version=version, client=client)\n\n def pttl(self, key, version=None, client=None):\n \"\"\"\n Executes PTTL redis command and return the \"time-to-live\" of specified key\n in milliseconds. If key is a non volatile key, it returns None.\n \"\"\"\n\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().pttl(key=key, version=version, client=client)\n\n def persist(self, key, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().persist(key=key, version=version, client=client)\n\n def expire(self, key, timeout, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().expire(key=key, timeout=timeout, version=version, client=client)\n\n def pexpire(self, key, timeout, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().pexpire(key=key, timeout=timeout, version=version, client=client)\n\n def pexpire_at(self, key, when: Union[datetime, int], version=None, client=None):\n \"\"\"\n Set an expire flag on a ``key`` to ``when`` on a shard client.\n ``when`` which can be represented as an integer indicating unix\n time or a Python datetime object.\n \"\"\"\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().pexpire_at(key=key, when=when, version=version, client=client)\n\n def expire_at(self, key, when: Union[datetime, int], version=None, client=None):\n \"\"\"\n Set an expire flag on a ``key`` to ``when`` on a shard client.\n ``when`` which can be represented as an integer indicating unix\n time or a Python datetime object.\n \"\"\"\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().expire_at(key=key, when=when, version=version, client=client)\n\n def lock(\n self,\n key,\n version=None,\n timeout=None,\n sleep=0.1,\n blocking_timeout=None,\n client=None,\n thread_local=True,\n ):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n key = self.make_key(key, version=version)\n return super().lock(\n key,\n timeout=timeout,\n sleep=sleep,\n client=client,\n blocking_timeout=blocking_timeout,\n thread_local=thread_local,\n )\n\n def delete_many(self, keys, version=None):\n \"\"\"\n Remove multiple keys at once.\n \"\"\"\n res = 0\n for key in [self.make_key(k, version=version) for k in keys]:\n client = self.get_server(key)\n res += self.delete(key, client=client)\n return res\n\n def incr_version(self, key, delta=1, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n if version is None:\n version = self._backend.version\n\n old_key = self.make_key(key, version)\n value = self.get(old_key, version=version, client=client)\n\n try:\n ttl = self.ttl(old_key, version=version, client=client)\n except ConnectionError as e:\n raise ConnectionInterrupted(connection=client) from e\n\n if value is None:\n raise ValueError(\"Key '%s' not found\" % key)\n\n if isinstance(key, CacheKey):\n new_key = self.make_key(key.original_key(), version=version + delta)\n else:\n new_key = self.make_key(key, version=version + delta)\n\n self.set(new_key, value, timeout=ttl, client=self.get_server(new_key))\n self.delete(old_key, client=client)\n return version + delta\n\n def incr(self, key, delta=1, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().incr(key=key, delta=delta, version=version, client=client)\n\n def decr(self, key, delta=1, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().decr(key=key, delta=delta, version=version, client=client)\n\n def iter_keys(self, key, version=None):\n raise NotImplementedError(\"iter_keys not supported on sharded client\")\n\n def keys(self, search, version=None):\n pattern = self.make_pattern(search, version=version)\n keys = []\n try:\n for server, connection in self._serverdict.items():\n keys.extend(connection.keys(pattern))\n except ConnectionError as e:\n # FIXME: technically all clients should be passed as `connection`.\n client = self.get_server(pattern)\n raise ConnectionInterrupted(connection=client) from e\n\n return [self.reverse_key(k.decode()) for k in keys]\n\n def delete_pattern(\n self, pattern, version=None, client=None, itersize=None, prefix=None\n ):\n \"\"\"\n Remove all keys matching pattern.\n \"\"\"\n pattern = self.make_pattern(pattern, version=version, prefix=prefix)\n kwargs = {\"match\": pattern}\n if itersize:\n kwargs[\"count\"] = itersize\n\n keys = []\n for server, connection in self._serverdict.items():\n keys.extend(key for key in connection.scan_iter(**kwargs))\n\n res = 0\n if keys:\n for server, connection in self._serverdict.items():\n res += connection.delete(*keys)\n return res\n\n def do_close_clients(self):\n for client in self._serverdict.values():\n self.disconnect(client=client)\n\n def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None, client=None):\n if client is None:\n key = self.make_key(key, version=version)\n client = self.get_server(key)\n\n return super().touch(key=key, timeout=timeout, version=version, client=client)\n\n def clear(self, client=None):\n for connection in self._serverdict.values():\n connection.flushdb()\n" }, { "alpha_fraction": 0.6172707676887512, "alphanum_fraction": 0.6185145974159241, "avg_line_length": 29.25806427001953, "blob_id": "60f609a3b4d76ee19e8a64db39ca3429fd9054e7", "content_id": "0b4d5890832e72d65b7c31c2133e575eb650c666", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5628, "license_type": "permissive", "max_line_length": 84, "num_lines": 186, "path": "/django_redis/cache.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import functools\nimport logging\nfrom typing import Any, Callable, Dict, Optional\n\nfrom django import VERSION as DJANGO_VERSION\nfrom django.conf import settings\nfrom django.core.cache.backends.base import BaseCache\nfrom django.utils.module_loading import import_string\n\nfrom .exceptions import ConnectionInterrupted\n\nCONNECTION_INTERRUPTED = object()\n\n\ndef omit_exception(\n method: Optional[Callable] = None, return_value: Optional[Any] = None\n):\n \"\"\"\n Simple decorator that intercepts connection\n errors and ignores these if settings specify this.\n \"\"\"\n\n if method is None:\n return functools.partial(omit_exception, return_value=return_value)\n\n @functools.wraps(method)\n def _decorator(self, *args, **kwargs):\n try:\n return method(self, *args, **kwargs)\n except ConnectionInterrupted as e:\n if self._ignore_exceptions:\n if self._log_ignored_exceptions:\n self.logger.exception(\"Exception ignored\")\n\n return return_value\n raise e.__cause__\n\n return _decorator\n\n\nclass RedisCache(BaseCache):\n def __init__(self, server: str, params: Dict[str, Any]) -> None:\n super().__init__(params)\n self._server = server\n self._params = params\n self._default_scan_itersize = getattr(\n settings, \"DJANGO_REDIS_SCAN_ITERSIZE\", 10\n )\n\n options = params.get(\"OPTIONS\", {})\n self._client_cls = options.get(\n \"CLIENT_CLASS\", \"django_redis.client.DefaultClient\"\n )\n self._client_cls = import_string(self._client_cls)\n self._client = None\n\n self._ignore_exceptions = options.get(\n \"IGNORE_EXCEPTIONS\",\n getattr(settings, \"DJANGO_REDIS_IGNORE_EXCEPTIONS\", False),\n )\n self._log_ignored_exceptions = getattr(\n settings, \"DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS\", False\n )\n self.logger = (\n logging.getLogger(getattr(settings, \"DJANGO_REDIS_LOGGER\", __name__))\n if self._log_ignored_exceptions\n else None\n )\n\n @property\n def client(self):\n \"\"\"\n Lazy client connection property.\n \"\"\"\n if self._client is None:\n self._client = self._client_cls(self._server, self._params, self)\n return self._client\n\n @omit_exception\n def set(self, *args, **kwargs):\n return self.client.set(*args, **kwargs)\n\n @omit_exception\n def incr_version(self, *args, **kwargs):\n return self.client.incr_version(*args, **kwargs)\n\n @omit_exception\n def add(self, *args, **kwargs):\n return self.client.add(*args, **kwargs)\n\n def get(self, key, default=None, version=None, client=None):\n value = self._get(key, default, version, client)\n if value is CONNECTION_INTERRUPTED:\n value = default\n return value\n\n @omit_exception(return_value=CONNECTION_INTERRUPTED)\n def _get(self, key, default, version, client):\n return self.client.get(key, default=default, version=version, client=client)\n\n @omit_exception\n def delete(self, *args, **kwargs):\n \"\"\"returns a boolean instead of int since django version 3.1\"\"\"\n result = self.client.delete(*args, **kwargs)\n return bool(result) if DJANGO_VERSION >= (3, 1, 0) else result\n\n @omit_exception\n def delete_pattern(self, *args, **kwargs):\n kwargs.setdefault(\"itersize\", self._default_scan_itersize)\n return self.client.delete_pattern(*args, **kwargs)\n\n @omit_exception\n def delete_many(self, *args, **kwargs):\n return self.client.delete_many(*args, **kwargs)\n\n @omit_exception\n def clear(self):\n return self.client.clear()\n\n @omit_exception(return_value={})\n def get_many(self, *args, **kwargs):\n return self.client.get_many(*args, **kwargs)\n\n @omit_exception\n def set_many(self, *args, **kwargs):\n return self.client.set_many(*args, **kwargs)\n\n @omit_exception\n def incr(self, *args, **kwargs):\n return self.client.incr(*args, **kwargs)\n\n @omit_exception\n def decr(self, *args, **kwargs):\n return self.client.decr(*args, **kwargs)\n\n @omit_exception\n def has_key(self, *args, **kwargs):\n return self.client.has_key(*args, **kwargs)\n\n @omit_exception\n def keys(self, *args, **kwargs):\n return self.client.keys(*args, **kwargs)\n\n @omit_exception\n def iter_keys(self, *args, **kwargs):\n return self.client.iter_keys(*args, **kwargs)\n\n @omit_exception\n def ttl(self, *args, **kwargs):\n return self.client.ttl(*args, **kwargs)\n\n @omit_exception\n def pttl(self, *args, **kwargs):\n return self.client.pttl(*args, **kwargs)\n\n @omit_exception\n def persist(self, *args, **kwargs):\n return self.client.persist(*args, **kwargs)\n\n @omit_exception\n def expire(self, *args, **kwargs):\n return self.client.expire(*args, **kwargs)\n\n @omit_exception\n def expire_at(self, *args, **kwargs):\n return self.client.expire_at(*args, **kwargs)\n\n @omit_exception\n def pexpire(self, *args, **kwargs):\n return self.client.pexpire(*args, **kwargs)\n\n @omit_exception\n def pexpire_at(self, *args, **kwargs):\n return self.client.pexpire_at(*args, **kwargs)\n\n @omit_exception\n def lock(self, *args, **kwargs):\n return self.client.lock(*args, **kwargs)\n\n @omit_exception\n def close(self, **kwargs):\n self.client.close(**kwargs)\n\n @omit_exception\n def touch(self, *args, **kwargs):\n return self.client.touch(*args, **kwargs)\n" }, { "alpha_fraction": 0.6585695147514343, "alphanum_fraction": 0.6855600476264954, "avg_line_length": 22.15625, "blob_id": "01a7ae1bb7ff87d4aec6cc3805fe26cb5d78c3fc", "content_id": "a00c9f784a2fd1961e30c59509b36c37d3c4b1af", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 741, "license_type": "permissive", "max_line_length": 63, "num_lines": 32, "path": "/.github/ISSUE_TEMPLATE/bug_report.md", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "---\nname: Bug report\nabout: Create a report to help us improve\nlabels: bug\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Stack trace**\nIf applicable, add stack trace to help explain your problem.\n\n**Environment (please complete the following information):**\n - Python version: [e.g. 3.5]\n - Django Redis Version: [e.g. 1.9.1]\n - Django Version: [e.g. 1.11.11]\n - Redis Version: [e.g. 2.5.0]\n - redis-py Version: [e.g. 3.5.0]\n\n**Additional context**\nAdd any other context about the problem here.\n" }, { "alpha_fraction": 0.703125, "alphanum_fraction": 0.703125, "avg_line_length": 42.9375, "blob_id": "c855a0319ce3cdb1013be3fbabde4e4b5a640096", "content_id": "76d317db4924f2c1f17c6df111299948ac16d3d4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 704, "license_type": "permissive", "max_line_length": 51, "num_lines": 16, "path": "/AUTHORS.rst", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "Andrei Antoukh / niwibe <https://github.com/niwibe>\nSean Bleier <https://github.com/sebleier>\nMatt Dennewitz <https://github.com/blackbrrr>\nJannis Leidel <https://github.com/jezdez>\nS. Angel / Twidi <https://github.com/twidi>\nNoah Kantrowitz / coderanger <https://github.com/coderanger>\nMartin Mahner / bartTC <https://github.com/bartTC>\nTimothée Peignier / cyberdelia <https://github.com/cyberdelia>\nLior Sion / liorsion <https://github.com/liorsion>\nAles Zoulek / aleszoulek <https://github.com/aleszoulek>\nJames Aylett / jaylett <https://github.com/jaylett>\nTodd Boland / boland <https://github.com/boland>\nDavid Zderic / dzderic <https://github.com/dzderic>\nKirill Zaitsev / teferi <https://github.com/teferi>\nJon Dufresne <https://github.com/jdufresne>\nAnès Foufa <https://github.com/AnesFoufa>\n" }, { "alpha_fraction": 0.6396760940551758, "alphanum_fraction": 0.6396760940551758, "avg_line_length": 19.58333396911621, "blob_id": "c5718e1a8957afc8a5e9d9b5d70b976a149f1d7e", "content_id": "a4e3ce261915d3062bf2eb5f0a10bc28531d9750", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "permissive", "max_line_length": 41, "num_lines": 12, "path": "/django_redis/serializers/base.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from typing import Any\n\n\nclass BaseSerializer:\n def __init__(self, options):\n pass\n\n def dumps(self, value: Any) -> bytes:\n raise NotImplementedError\n\n def loads(self, value: bytes) -> Any:\n raise NotImplementedError\n" }, { "alpha_fraction": 0.5243297219276428, "alphanum_fraction": 0.5809334516525269, "avg_line_length": 31.483871459960938, "blob_id": "843d47132b2651c506eaa5d76450023af5a8397b", "content_id": "9bac3a4c78f2552c93cd44e77c493ac9ace5c82c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1007, "license_type": "permissive", "max_line_length": 78, "num_lines": 31, "path": "/tests/settings/sqlite_herd.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "SECRET_KEY = \"django_tests_secret_key\"\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": [\"redis://127.0.0.1:6379?db=5\"],\n \"OPTIONS\": {\"CLIENT_CLASS\": \"django_redis.client.HerdClient\"},\n },\n \"doesnotexist\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:56379?db=1\",\n \"OPTIONS\": {\"CLIENT_CLASS\": \"django_redis.client.HerdClient\"},\n },\n \"sample\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379?db=1,redis://127.0.0.1:6379?db=1\",\n \"OPTIONS\": {\"CLIENT_CLASS\": \"django_redis.client.HerdClient\"},\n },\n \"with_prefix\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379?db=1\",\n \"OPTIONS\": {\"CLIENT_CLASS\": \"django_redis.client.HerdClient\"},\n \"KEY_PREFIX\": \"test-prefix\",\n },\n}\n\nINSTALLED_APPS = [\"django.contrib.sessions\"]\n\nUSE_TZ = False\n\nCACHE_HERD_TIMEOUT = 2\n" }, { "alpha_fraction": 0.6169642806053162, "alphanum_fraction": 0.6169642806053162, "avg_line_length": 34, "blob_id": "80270c70f64178cfffd8c72ff45906379512f8d6", "content_id": "c304360d8c069f90eddb7eef288bc81cd2d37419", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1120, "license_type": "permissive", "max_line_length": 87, "num_lines": 32, "path": "/django_redis/serializers/pickle.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import pickle\nfrom typing import Any\n\nfrom django.core.exceptions import ImproperlyConfigured\n\nfrom .base import BaseSerializer\n\n\nclass PickleSerializer(BaseSerializer):\n def __init__(self, options) -> None:\n self._pickle_version = pickle.DEFAULT_PROTOCOL\n self.setup_pickle_version(options)\n\n super().__init__(options=options)\n\n def setup_pickle_version(self, options) -> None:\n if \"PICKLE_VERSION\" in options:\n try:\n self._pickle_version = int(options[\"PICKLE_VERSION\"])\n if self._pickle_version > pickle.HIGHEST_PROTOCOL:\n raise ImproperlyConfigured(\n f\"PICKLE_VERSION can't be higher than pickle.HIGHEST_PROTOCOL:\"\n f\" {pickle.HIGHEST_PROTOCOL}\"\n )\n except (ValueError, TypeError):\n raise ImproperlyConfigured(\"PICKLE_VERSION value must be an integer\")\n\n def dumps(self, value: Any) -> bytes:\n return pickle.dumps(value, self._pickle_version)\n\n def loads(self, value: bytes) -> Any:\n return pickle.loads(value)\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.6521739363670349, "avg_line_length": 27.11111068725586, "blob_id": "50b81bdbce33761903dcc3a9abc0962e6e5f6e74", "content_id": "d476ec7d4e5ff44138536842f98d1cf48cde7377", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "permissive", "max_line_length": 48, "num_lines": 9, "path": "/django_redis/compressors/base.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "class BaseCompressor:\n def __init__(self, options):\n self._options = options\n\n def compress(self, value: bytes) -> bytes:\n raise NotImplementedError\n\n def decompress(self, value: bytes) -> bytes:\n raise NotImplementedError\n" }, { "alpha_fraction": 0.5855130553245544, "alphanum_fraction": 0.621730387210846, "avg_line_length": 22.66666603088379, "blob_id": "483bd2cdc891de701c081c7c96771932a9ea1bc8", "content_id": "97ab0987659a8ba74f68f51e9ff1d03f1d520813", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 497, "license_type": "permissive", "max_line_length": 95, "num_lines": 21, "path": "/tests/wait_for_redis.sh", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nCONTAINER=$1\nPORT=$2\n\nfor i in {1..60}; do\n if docker inspect \"$CONTAINER\" \\\n --format '{{.State.Health.Status}}' \\\n | grep -q starting; then\n sleep 1\n else\n if ! nc -z 127.0.0.1 $PORT &>/dev/null; then\n echo >&2 \"Port $PORT does not seem to be open, redis will not work with docker rootless!\"\n fi\n # exit successfully in case nc was not found or -z is not supported\n exit 0\n fi\ndone\n\necho >&2 \"Redis did not seem to start in ~60s, aborting\"\nexit 1\n" }, { "alpha_fraction": 0.5897819399833679, "alphanum_fraction": 0.5906370282173157, "avg_line_length": 27.524391174316406, "blob_id": "58423ea91cd674c076402a0bf3e69a85600c33ad", "content_id": "0c52480f58f2a6e7ed184f642a4e4af6848e8754", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4678, "license_type": "permissive", "max_line_length": 84, "num_lines": 164, "path": "/django_redis/client/herd.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import random\nimport socket\nimport time\nfrom collections import OrderedDict\n\nfrom django.conf import settings\nfrom redis.exceptions import ConnectionError, ResponseError, TimeoutError\n\nfrom ..exceptions import ConnectionInterrupted\nfrom .default import DEFAULT_TIMEOUT, DefaultClient\n\n_main_exceptions = (ConnectionError, ResponseError, TimeoutError, socket.timeout)\n\n\nclass Marker:\n \"\"\"\n Dummy class for use as\n marker for herded keys.\n \"\"\"\n\n pass\n\n\ndef _is_expired(x, herd_timeout: int) -> bool:\n if x >= herd_timeout:\n return True\n val = x + random.randint(1, herd_timeout)\n\n if val >= herd_timeout:\n return True\n return False\n\n\nclass HerdClient(DefaultClient):\n def __init__(self, *args, **kwargs):\n self._marker = Marker()\n self._herd_timeout = getattr(settings, \"CACHE_HERD_TIMEOUT\", 60)\n super().__init__(*args, **kwargs)\n\n def _pack(self, value, timeout):\n herd_timeout = (timeout or self._backend.default_timeout) + int(time.time())\n return self._marker, value, herd_timeout\n\n def _unpack(self, value):\n try:\n marker, unpacked, herd_timeout = value\n except (ValueError, TypeError):\n return value, False\n\n if not isinstance(marker, Marker):\n return value, False\n\n now = int(time.time())\n if herd_timeout < now:\n x = now - herd_timeout\n return unpacked, _is_expired(x, self._herd_timeout)\n\n return unpacked, False\n\n def set(\n self,\n key,\n value,\n timeout=DEFAULT_TIMEOUT,\n version=None,\n client=None,\n nx=False,\n xx=False,\n ):\n if timeout is DEFAULT_TIMEOUT:\n timeout = self._backend.default_timeout\n\n if timeout is None or timeout <= 0:\n return super().set(\n key,\n value,\n timeout=timeout,\n version=version,\n client=client,\n nx=nx,\n xx=xx,\n )\n\n packed = self._pack(value, timeout)\n real_timeout = timeout + self._herd_timeout\n\n return super().set(\n key, packed, timeout=real_timeout, version=version, client=client, nx=nx\n )\n\n def get(self, key, default=None, version=None, client=None):\n packed = super().get(key, default=default, version=version, client=client)\n val, refresh = self._unpack(packed)\n\n if refresh:\n return default\n\n return val\n\n def get_many(self, keys, version=None, client=None):\n if client is None:\n client = self.get_client(write=False)\n\n if not keys:\n return {}\n\n recovered_data = OrderedDict()\n\n new_keys = [self.make_key(key, version=version) for key in keys]\n map_keys = dict(zip(new_keys, keys))\n\n try:\n results = client.mget(*new_keys)\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n for key, value in zip(new_keys, results):\n if value is None:\n continue\n\n val, refresh = self._unpack(self.decode(value))\n recovered_data[map_keys[key]] = None if refresh else val\n\n return recovered_data\n\n def set_many(\n self, data, timeout=DEFAULT_TIMEOUT, version=None, client=None, herd=True\n ):\n \"\"\"\n Set a bunch of values in the cache at once from a dict of key/value\n pairs. This is much more efficient than calling set() multiple times.\n\n If timeout is given, that timeout will be used for the key; otherwise\n the default cache timeout will be used.\n \"\"\"\n if client is None:\n client = self.get_client(write=True)\n\n set_function = self.set if herd else super().set\n\n try:\n pipeline = client.pipeline()\n for key, value in data.items():\n set_function(key, value, timeout, version=version, client=pipeline)\n pipeline.execute()\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def incr(self, *args, **kwargs):\n raise NotImplementedError()\n\n def decr(self, *args, **kwargs):\n raise NotImplementedError()\n\n def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None, client=None):\n if client is None:\n client = self.get_client(write=True)\n\n value = self.get(key, version=version, client=client)\n if value is None:\n return False\n\n self.set(key, value, timeout=timeout, version=version, client=client)\n return True\n" }, { "alpha_fraction": 0.6561922430992126, "alphanum_fraction": 0.6654343605041504, "avg_line_length": 26.049999237060547, "blob_id": "3afddb4108be209c99766bd6d78b273781cee40f", "content_id": "ffcd47946d6d2f0c30b1082512469b945d2042bd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "permissive", "max_line_length": 48, "num_lines": 20, "path": "/django_redis/compressors/lz4.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from lz4.frame import compress as _compress\nfrom lz4.frame import decompress as _decompress\n\nfrom ..exceptions import CompressorError\nfrom .base import BaseCompressor\n\n\nclass Lz4Compressor(BaseCompressor):\n min_length = 15\n\n def compress(self, value: bytes) -> bytes:\n if len(value) > self.min_length:\n return _compress(value)\n return value\n\n def decompress(self, value: bytes) -> bytes:\n try:\n return _decompress(value)\n except Exception as e:\n raise CompressorError(e)\n" }, { "alpha_fraction": 0.6672794222831726, "alphanum_fraction": 0.6727941036224365, "avg_line_length": 26.200000762939453, "blob_id": "ea27a06fd802841938eb6479bdcd9ddae30f6883", "content_id": "f83bf322df8208085319bf8e8382c82b1dce805f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "permissive", "max_line_length": 79, "num_lines": 20, "path": "/django_redis/__init__.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "VERSION = (5, 3, 0)\n__version__ = \".\".join(map(str, VERSION))\n\n\ndef get_redis_connection(alias=\"default\", write=True):\n \"\"\"\n Helper used for obtaining a raw redis client.\n \"\"\"\n\n from django.core.cache import caches\n\n cache = caches[alias]\n\n if not hasattr(cache, \"client\"):\n raise NotImplementedError(\"This backend does not support this feature\")\n\n if not hasattr(cache.client, \"get_client\"):\n raise NotImplementedError(\"This backend does not support this feature\")\n\n return cache.client.get_client(write)\n" }, { "alpha_fraction": 0.5582740902900696, "alphanum_fraction": 0.5820808410644531, "avg_line_length": 31.71791648864746, "blob_id": "33d7ad30ac429d5b8f56e604796b261eaed76150", "content_id": "7f4beb70b815b8d01470f70ea11b4452ce70ff6d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25759, "license_type": "permissive", "max_line_length": 88, "num_lines": 787, "path": "/tests/test_backend.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import datetime\nimport threading\nimport time\nfrom datetime import timedelta\nfrom typing import Iterable, List, Union, cast\nfrom unittest.mock import patch\n\nimport pytest\nfrom django.core.cache import caches\nfrom django.test import override_settings\nfrom pytest_django.fixtures import SettingsWrapper\nfrom pytest_mock import MockerFixture\n\nfrom django_redis.cache import RedisCache\nfrom django_redis.client import ShardClient, herd\nfrom django_redis.serializers.json import JSONSerializer\nfrom django_redis.serializers.msgpack import MSGPackSerializer\n\n\[email protected]\ndef patch_itersize_setting() -> Iterable[None]:\n # destroy cache to force recreation with overriden settings\n del caches[\"default\"]\n with override_settings(DJANGO_REDIS_SCAN_ITERSIZE=30):\n yield\n # destroy cache to force recreation with original settings\n del caches[\"default\"]\n\n\nclass TestDjangoRedisCache:\n def test_setnx(self, cache: RedisCache):\n # we should ensure there is no test_key_nx in redis\n cache.delete(\"test_key_nx\")\n res = cache.get(\"test_key_nx\")\n assert res is None\n\n res = cache.set(\"test_key_nx\", 1, nx=True)\n assert bool(res) is True\n # test that second set will have\n res = cache.set(\"test_key_nx\", 2, nx=True)\n assert res is False\n res = cache.get(\"test_key_nx\")\n assert res == 1\n\n cache.delete(\"test_key_nx\")\n res = cache.get(\"test_key_nx\")\n assert res is None\n\n def test_setnx_timeout(self, cache: RedisCache):\n # test that timeout still works for nx=True\n res = cache.set(\"test_key_nx\", 1, timeout=2, nx=True)\n assert res is True\n time.sleep(3)\n res = cache.get(\"test_key_nx\")\n assert res is None\n\n # test that timeout will not affect key, if it was there\n cache.set(\"test_key_nx\", 1)\n res = cache.set(\"test_key_nx\", 2, timeout=2, nx=True)\n assert res is False\n time.sleep(3)\n res = cache.get(\"test_key_nx\")\n assert res == 1\n\n cache.delete(\"test_key_nx\")\n res = cache.get(\"test_key_nx\")\n assert res is None\n\n def test_unicode_keys(self, cache: RedisCache):\n cache.set(\"ключ\", \"value\")\n res = cache.get(\"ключ\")\n assert res == \"value\"\n\n def test_save_and_integer(self, cache: RedisCache):\n cache.set(\"test_key\", 2)\n res = cache.get(\"test_key\", \"Foo\")\n\n assert isinstance(res, int)\n assert res == 2\n\n def test_save_string(self, cache: RedisCache):\n cache.set(\"test_key\", \"hello\" * 1000)\n res = cache.get(\"test_key\")\n\n assert isinstance(res, str)\n assert res == \"hello\" * 1000\n\n cache.set(\"test_key\", \"2\")\n res = cache.get(\"test_key\")\n\n assert isinstance(res, str)\n assert res == \"2\"\n\n def test_save_unicode(self, cache: RedisCache):\n cache.set(\"test_key\", \"heló\")\n res = cache.get(\"test_key\")\n\n assert isinstance(res, str)\n assert res == \"heló\"\n\n def test_save_dict(self, cache: RedisCache):\n if isinstance(cache.client._serializer, (JSONSerializer, MSGPackSerializer)):\n # JSONSerializer and MSGPackSerializer use the isoformat for\n # datetimes.\n now_dt: Union[str, datetime.datetime] = datetime.datetime.now().isoformat()\n else:\n now_dt = datetime.datetime.now()\n\n test_dict = {\"id\": 1, \"date\": now_dt, \"name\": \"Foo\"}\n\n cache.set(\"test_key\", test_dict)\n res = cache.get(\"test_key\")\n\n assert isinstance(res, dict)\n assert res[\"id\"] == 1\n assert res[\"name\"] == \"Foo\"\n assert res[\"date\"] == now_dt\n\n def test_save_float(self, cache: RedisCache):\n float_val = 1.345620002\n\n cache.set(\"test_key\", float_val)\n res = cache.get(\"test_key\")\n\n assert isinstance(res, float)\n assert res == float_val\n\n def test_timeout(self, cache: RedisCache):\n cache.set(\"test_key\", 222, timeout=3)\n time.sleep(4)\n\n res = cache.get(\"test_key\")\n assert res is None\n\n def test_timeout_0(self, cache: RedisCache):\n cache.set(\"test_key\", 222, timeout=0)\n res = cache.get(\"test_key\")\n assert res is None\n\n def test_timeout_parameter_as_positional_argument(self, cache: RedisCache):\n cache.set(\"test_key\", 222, -1)\n res = cache.get(\"test_key\")\n assert res is None\n\n cache.set(\"test_key\", 222, 1)\n res1 = cache.get(\"test_key\")\n time.sleep(2)\n res2 = cache.get(\"test_key\")\n assert res1 == 222\n assert res2 is None\n\n # nx=True should not overwrite expire of key already in db\n cache.set(\"test_key\", 222, None)\n cache.set(\"test_key\", 222, -1, nx=True)\n res = cache.get(\"test_key\")\n assert res == 222\n\n def test_timeout_negative(self, cache: RedisCache):\n cache.set(\"test_key\", 222, timeout=-1)\n res = cache.get(\"test_key\")\n assert res is None\n\n cache.set(\"test_key\", 222, timeout=None)\n cache.set(\"test_key\", 222, timeout=-1)\n res = cache.get(\"test_key\")\n assert res is None\n\n # nx=True should not overwrite expire of key already in db\n cache.set(\"test_key\", 222, timeout=None)\n cache.set(\"test_key\", 222, timeout=-1, nx=True)\n res = cache.get(\"test_key\")\n assert res == 222\n\n def test_timeout_tiny(self, cache: RedisCache):\n cache.set(\"test_key\", 222, timeout=0.00001)\n res = cache.get(\"test_key\")\n assert res in (None, 222)\n\n def test_set_add(self, cache: RedisCache):\n cache.set(\"add_key\", \"Initial value\")\n res = cache.add(\"add_key\", \"New value\")\n assert res is False\n\n res = cache.get(\"add_key\")\n assert res == \"Initial value\"\n res = cache.add(\"other_key\", \"New value\")\n assert res is True\n\n def test_get_many(self, cache: RedisCache):\n cache.set(\"a\", 1)\n cache.set(\"b\", 2)\n cache.set(\"c\", 3)\n\n res = cache.get_many([\"a\", \"b\", \"c\"])\n assert res == {\"a\": 1, \"b\": 2, \"c\": 3}\n\n def test_get_many_unicode(self, cache: RedisCache):\n cache.set(\"a\", \"1\")\n cache.set(\"b\", \"2\")\n cache.set(\"c\", \"3\")\n\n res = cache.get_many([\"a\", \"b\", \"c\"])\n assert res == {\"a\": \"1\", \"b\": \"2\", \"c\": \"3\"}\n\n def test_set_many(self, cache: RedisCache):\n cache.set_many({\"a\": 1, \"b\": 2, \"c\": 3})\n res = cache.get_many([\"a\", \"b\", \"c\"])\n assert res == {\"a\": 1, \"b\": 2, \"c\": 3}\n\n def test_set_call_empty_pipeline(\n self,\n cache: RedisCache,\n mocker: MockerFixture,\n settings: SettingsWrapper,\n ):\n if isinstance(cache.client, ShardClient):\n pytest.skip(\"ShardClient doesn't support get_client\")\n\n pipeline = cache.client.get_client(write=True).pipeline()\n key = \"key\"\n value = \"value\"\n\n mocked_set = mocker.patch.object(pipeline, \"set\")\n cache.set(key, value, client=pipeline)\n\n if isinstance(cache.client, herd.HerdClient):\n default_timeout = cache.client._backend.default_timeout\n herd_timeout = (default_timeout + settings.CACHE_HERD_TIMEOUT) * 1000\n herd_pack_value = cache.client._pack(value, default_timeout)\n mocked_set.assert_called_once_with(\n cache.client.make_key(key, version=None),\n cache.client.encode(herd_pack_value),\n nx=False,\n px=herd_timeout,\n xx=False,\n )\n else:\n mocked_set.assert_called_once_with(\n cache.client.make_key(key, version=None),\n cache.client.encode(value),\n nx=False,\n px=cache.client._backend.default_timeout * 1000,\n xx=False,\n )\n\n def test_delete(self, cache: RedisCache):\n cache.set_many({\"a\": 1, \"b\": 2, \"c\": 3})\n res = cache.delete(\"a\")\n assert bool(res) is True\n\n res = cache.get_many([\"a\", \"b\", \"c\"])\n assert res == {\"b\": 2, \"c\": 3}\n\n res = cache.delete(\"a\")\n assert bool(res) is False\n\n @patch(\"django_redis.cache.DJANGO_VERSION\", (3, 1, 0, \"final\", 0))\n def test_delete_return_value_type_new31(self, cache: RedisCache):\n \"\"\"delete() returns a boolean instead of int since django version 3.1\"\"\"\n cache.set(\"a\", 1)\n res = cache.delete(\"a\")\n assert isinstance(res, bool)\n assert res is True\n res = cache.delete(\"b\")\n assert isinstance(res, bool)\n assert res is False\n\n @patch(\"django_redis.cache.DJANGO_VERSION\", new=(3, 0, 1, \"final\", 0))\n def test_delete_return_value_type_before31(self, cache: RedisCache):\n \"\"\"delete() returns a int before django version 3.1\"\"\"\n cache.set(\"a\", 1)\n res = cache.delete(\"a\")\n assert isinstance(res, int)\n assert res == 1\n res = cache.delete(\"b\")\n assert isinstance(res, int)\n assert res == 0\n\n def test_delete_many(self, cache: RedisCache):\n cache.set_many({\"a\": 1, \"b\": 2, \"c\": 3})\n res = cache.delete_many([\"a\", \"b\"])\n assert bool(res) is True\n\n res = cache.get_many([\"a\", \"b\", \"c\"])\n assert res == {\"c\": 3}\n\n res = cache.delete_many([\"a\", \"b\"])\n assert bool(res) is False\n\n def test_delete_many_generator(self, cache: RedisCache):\n cache.set_many({\"a\": 1, \"b\": 2, \"c\": 3})\n res = cache.delete_many(key for key in [\"a\", \"b\"])\n assert bool(res) is True\n\n res = cache.get_many([\"a\", \"b\", \"c\"])\n assert res == {\"c\": 3}\n\n res = cache.delete_many([\"a\", \"b\"])\n assert bool(res) is False\n\n def test_delete_many_empty_generator(self, cache: RedisCache):\n res = cache.delete_many(key for key in cast(List[str], []))\n assert bool(res) is False\n\n def test_incr(self, cache: RedisCache):\n if isinstance(cache.client, herd.HerdClient):\n pytest.skip(\"HerdClient doesn't support incr\")\n\n cache.set(\"num\", 1)\n\n cache.incr(\"num\")\n res = cache.get(\"num\")\n assert res == 2\n\n cache.incr(\"num\", 10)\n res = cache.get(\"num\")\n assert res == 12\n\n # max 64 bit signed int\n cache.set(\"num\", 9223372036854775807)\n\n cache.incr(\"num\")\n res = cache.get(\"num\")\n assert res == 9223372036854775808\n\n cache.incr(\"num\", 2)\n res = cache.get(\"num\")\n assert res == 9223372036854775810\n\n cache.set(\"num\", 3)\n\n cache.incr(\"num\", 2)\n res = cache.get(\"num\")\n assert res == 5\n\n def test_incr_no_timeout(self, cache: RedisCache):\n if isinstance(cache.client, herd.HerdClient):\n pytest.skip(\"HerdClient doesn't support incr\")\n\n cache.set(\"num\", 1, timeout=None)\n\n cache.incr(\"num\")\n res = cache.get(\"num\")\n assert res == 2\n\n cache.incr(\"num\", 10)\n res = cache.get(\"num\")\n assert res == 12\n\n # max 64 bit signed int\n cache.set(\"num\", 9223372036854775807, timeout=None)\n\n cache.incr(\"num\")\n res = cache.get(\"num\")\n assert res == 9223372036854775808\n\n cache.incr(\"num\", 2)\n res = cache.get(\"num\")\n assert res == 9223372036854775810\n\n cache.set(\"num\", 3, timeout=None)\n\n cache.incr(\"num\", 2)\n res = cache.get(\"num\")\n assert res == 5\n\n def test_incr_error(self, cache: RedisCache):\n if isinstance(cache.client, herd.HerdClient):\n pytest.skip(\"HerdClient doesn't support incr\")\n\n with pytest.raises(ValueError):\n # key does not exist\n cache.incr(\"numnum\")\n\n def test_incr_ignore_check(self, cache: RedisCache):\n if isinstance(cache.client, ShardClient):\n pytest.skip(\"ShardClient doesn't support argument ignore_key_check to incr\")\n if isinstance(cache.client, herd.HerdClient):\n pytest.skip(\"HerdClient doesn't support incr\")\n\n # key exists check will be skipped and the value will be incremented by\n # '1' which is the default delta\n cache.incr(\"num\", ignore_key_check=True)\n res = cache.get(\"num\")\n assert res == 1\n cache.delete(\"num\")\n\n # since key doesnt exist it is set to the delta value, 10 in this case\n cache.incr(\"num\", 10, ignore_key_check=True)\n res = cache.get(\"num\")\n assert res == 10\n cache.delete(\"num\")\n\n # following are just regression checks to make sure it still works as\n # expected with incr max 64 bit signed int\n cache.set(\"num\", 9223372036854775807)\n\n cache.incr(\"num\", ignore_key_check=True)\n res = cache.get(\"num\")\n assert res == 9223372036854775808\n\n cache.incr(\"num\", 2, ignore_key_check=True)\n res = cache.get(\"num\")\n assert res == 9223372036854775810\n\n cache.set(\"num\", 3)\n\n cache.incr(\"num\", 2, ignore_key_check=True)\n res = cache.get(\"num\")\n assert res == 5\n\n def test_get_set_bool(self, cache: RedisCache):\n cache.set(\"bool\", True)\n res = cache.get(\"bool\")\n\n assert isinstance(res, bool)\n assert res is True\n\n cache.set(\"bool\", False)\n res = cache.get(\"bool\")\n\n assert isinstance(res, bool)\n assert res is False\n\n def test_decr(self, cache: RedisCache):\n if isinstance(cache.client, herd.HerdClient):\n pytest.skip(\"HerdClient doesn't support decr\")\n\n cache.set(\"num\", 20)\n\n cache.decr(\"num\")\n res = cache.get(\"num\")\n assert res == 19\n\n cache.decr(\"num\", 20)\n res = cache.get(\"num\")\n assert res == -1\n\n cache.decr(\"num\", 2)\n res = cache.get(\"num\")\n assert res == -3\n\n cache.set(\"num\", 20)\n\n cache.decr(\"num\")\n res = cache.get(\"num\")\n assert res == 19\n\n # max 64 bit signed int + 1\n cache.set(\"num\", 9223372036854775808)\n\n cache.decr(\"num\")\n res = cache.get(\"num\")\n assert res == 9223372036854775807\n\n cache.decr(\"num\", 2)\n res = cache.get(\"num\")\n assert res == 9223372036854775805\n\n def test_version(self, cache: RedisCache):\n cache.set(\"keytest\", 2, version=2)\n res = cache.get(\"keytest\")\n assert res is None\n\n res = cache.get(\"keytest\", version=2)\n assert res == 2\n\n def test_incr_version(self, cache: RedisCache):\n cache.set(\"keytest\", 2)\n cache.incr_version(\"keytest\")\n\n res = cache.get(\"keytest\")\n assert res is None\n\n res = cache.get(\"keytest\", version=2)\n assert res == 2\n\n def test_ttl_incr_version_no_timeout(self, cache: RedisCache):\n cache.set(\"my_key\", \"hello world!\", timeout=None)\n\n cache.incr_version(\"my_key\")\n\n my_value = cache.get(\"my_key\", version=2)\n\n assert my_value == \"hello world!\"\n\n def test_delete_pattern(self, cache: RedisCache):\n for key in [\"foo-aa\", \"foo-ab\", \"foo-bb\", \"foo-bc\"]:\n cache.set(key, \"foo\")\n\n res = cache.delete_pattern(\"*foo-a*\")\n assert bool(res) is True\n\n keys = cache.keys(\"foo*\")\n assert set(keys) == {\"foo-bb\", \"foo-bc\"}\n\n res = cache.delete_pattern(\"*foo-a*\")\n assert bool(res) is False\n\n @patch(\"django_redis.cache.RedisCache.client\")\n def test_delete_pattern_with_custom_count(self, client_mock, cache: RedisCache):\n for key in [\"foo-aa\", \"foo-ab\", \"foo-bb\", \"foo-bc\"]:\n cache.set(key, \"foo\")\n\n cache.delete_pattern(\"*foo-a*\", itersize=2)\n\n client_mock.delete_pattern.assert_called_once_with(\"*foo-a*\", itersize=2)\n\n @patch(\"django_redis.cache.RedisCache.client\")\n def test_delete_pattern_with_settings_default_scan_count(\n self,\n client_mock,\n patch_itersize_setting,\n cache: RedisCache,\n settings: SettingsWrapper,\n ):\n for key in [\"foo-aa\", \"foo-ab\", \"foo-bb\", \"foo-bc\"]:\n cache.set(key, \"foo\")\n expected_count = settings.DJANGO_REDIS_SCAN_ITERSIZE\n\n cache.delete_pattern(\"*foo-a*\")\n\n client_mock.delete_pattern.assert_called_once_with(\n \"*foo-a*\", itersize=expected_count\n )\n\n def test_close(self, cache: RedisCache, settings: SettingsWrapper):\n settings.DJANGO_REDIS_CLOSE_CONNECTION = True\n cache.set(\"f\", \"1\")\n cache.close()\n\n def test_close_client(self, cache: RedisCache, mocker: MockerFixture):\n mock = mocker.patch.object(cache.client, \"close\")\n cache.close()\n assert mock.called\n\n def test_ttl(self, cache: RedisCache):\n cache.set(\"foo\", \"bar\", 10)\n ttl = cache.ttl(\"foo\")\n\n if isinstance(cache.client, herd.HerdClient):\n assert pytest.approx(ttl) == 12\n else:\n assert pytest.approx(ttl) == 10\n\n # Test ttl None\n cache.set(\"foo\", \"foo\", timeout=None)\n ttl = cache.ttl(\"foo\")\n assert ttl is None\n\n # Test ttl with expired key\n cache.set(\"foo\", \"foo\", timeout=-1)\n ttl = cache.ttl(\"foo\")\n assert ttl == 0\n\n # Test ttl with not existent key\n ttl = cache.ttl(\"not-existent-key\")\n assert ttl == 0\n\n def test_pttl(self, cache: RedisCache):\n # Test pttl\n cache.set(\"foo\", \"bar\", 10)\n ttl = cache.pttl(\"foo\")\n\n # delta is set to 10 as precision error causes tests to fail\n if isinstance(cache.client, herd.HerdClient):\n assert pytest.approx(ttl, 10) == 12000\n else:\n assert pytest.approx(ttl, 10) == 10000\n\n # Test pttl with float value\n cache.set(\"foo\", \"bar\", 5.5)\n ttl = cache.pttl(\"foo\")\n\n if isinstance(cache.client, herd.HerdClient):\n assert pytest.approx(ttl, 10) == 7500\n else:\n assert pytest.approx(ttl, 10) == 5500\n\n # Test pttl None\n cache.set(\"foo\", \"foo\", timeout=None)\n ttl = cache.pttl(\"foo\")\n assert ttl is None\n\n # Test pttl with expired key\n cache.set(\"foo\", \"foo\", timeout=-1)\n ttl = cache.pttl(\"foo\")\n assert ttl == 0\n\n # Test pttl with not existent key\n ttl = cache.pttl(\"not-existent-key\")\n assert ttl == 0\n\n def test_persist(self, cache: RedisCache):\n cache.set(\"foo\", \"bar\", timeout=20)\n assert cache.persist(\"foo\") is True\n\n ttl = cache.ttl(\"foo\")\n assert ttl is None\n assert cache.persist(\"not-existent-key\") is False\n\n def test_expire(self, cache: RedisCache):\n cache.set(\"foo\", \"bar\", timeout=None)\n assert cache.expire(\"foo\", 20) is True\n ttl = cache.ttl(\"foo\")\n assert pytest.approx(ttl) == 20\n assert cache.expire(\"not-existent-key\", 20) is False\n\n def test_pexpire(self, cache: RedisCache):\n cache.set(\"foo\", \"bar\", timeout=None)\n assert cache.pexpire(\"foo\", 20500) is True\n ttl = cache.pttl(\"foo\")\n # delta is set to 10 as precision error causes tests to fail\n assert pytest.approx(ttl, 10) == 20500\n assert cache.pexpire(\"not-existent-key\", 20500) is False\n\n def test_pexpire_at(self, cache: RedisCache):\n # Test settings expiration time 1 hour ahead by datetime.\n cache.set(\"foo\", \"bar\", timeout=None)\n expiration_time = datetime.datetime.now() + timedelta(hours=1)\n assert cache.pexpire_at(\"foo\", expiration_time) is True\n ttl = cache.pttl(\"foo\")\n assert pytest.approx(ttl, 10) == timedelta(hours=1).total_seconds()\n\n # Test settings expiration time 1 hour ahead by Unix timestamp.\n cache.set(\"foo\", \"bar\", timeout=None)\n expiration_time = datetime.datetime.now() + timedelta(hours=2)\n assert cache.pexpire_at(\"foo\", int(expiration_time.timestamp() * 1000)) is True\n ttl = cache.pttl(\"foo\")\n assert pytest.approx(ttl, 10) == timedelta(hours=2).total_seconds() * 1000\n\n # Test settings expiration time 1 hour in past, which effectively\n # deletes the key.\n expiration_time = datetime.datetime.now() - timedelta(hours=2)\n assert cache.pexpire_at(\"foo\", expiration_time) is True\n value = cache.get(\"foo\")\n assert value is None\n\n expiration_time = datetime.datetime.now() + timedelta(hours=2)\n assert cache.pexpire_at(\"not-existent-key\", expiration_time) is False\n\n def test_expire_at(self, cache: RedisCache):\n # Test settings expiration time 1 hour ahead by datetime.\n cache.set(\"foo\", \"bar\", timeout=None)\n expiration_time = datetime.datetime.now() + timedelta(hours=1)\n assert cache.expire_at(\"foo\", expiration_time) is True\n ttl = cache.ttl(\"foo\")\n assert pytest.approx(ttl, 1) == timedelta(hours=1).total_seconds()\n\n # Test settings expiration time 1 hour ahead by Unix timestamp.\n cache.set(\"foo\", \"bar\", timeout=None)\n expiration_time = datetime.datetime.now() + timedelta(hours=2)\n assert cache.expire_at(\"foo\", int(expiration_time.timestamp())) is True\n ttl = cache.ttl(\"foo\")\n assert pytest.approx(ttl, 1) == timedelta(hours=1).total_seconds() * 2\n\n # Test settings expiration time 1 hour in past, which effectively\n # deletes the key.\n expiration_time = datetime.datetime.now() - timedelta(hours=2)\n assert cache.expire_at(\"foo\", expiration_time) is True\n value = cache.get(\"foo\")\n assert value is None\n\n expiration_time = datetime.datetime.now() + timedelta(hours=2)\n assert cache.expire_at(\"not-existent-key\", expiration_time) is False\n\n def test_lock(self, cache: RedisCache):\n lock = cache.lock(\"foobar\")\n lock.acquire(blocking=True)\n\n assert cache.has_key(\"foobar\")\n lock.release()\n assert not cache.has_key(\"foobar\")\n\n def test_lock_released_by_thread(self, cache: RedisCache):\n lock = cache.lock(\"foobar\", thread_local=False)\n lock.acquire(blocking=True)\n\n def release_lock(lock_):\n lock_.release()\n\n t = threading.Thread(target=release_lock, args=[lock])\n t.start()\n t.join()\n\n assert not cache.has_key(\"foobar\")\n\n def test_iter_keys(self, cache: RedisCache):\n if isinstance(cache.client, ShardClient):\n pytest.skip(\"ShardClient doesn't support iter_keys\")\n\n cache.set(\"foo1\", 1)\n cache.set(\"foo2\", 1)\n cache.set(\"foo3\", 1)\n\n # Test simple result\n result = set(cache.iter_keys(\"foo*\"))\n assert result == {\"foo1\", \"foo2\", \"foo3\"}\n\n def test_iter_keys_itersize(self, cache: RedisCache):\n if isinstance(cache.client, ShardClient):\n pytest.skip(\"ShardClient doesn't support iter_keys\")\n\n cache.set(\"foo1\", 1)\n cache.set(\"foo2\", 1)\n cache.set(\"foo3\", 1)\n\n # Test limited result\n result = list(cache.iter_keys(\"foo*\", itersize=2))\n assert len(result) == 3\n\n def test_iter_keys_generator(self, cache: RedisCache):\n if isinstance(cache.client, ShardClient):\n pytest.skip(\"ShardClient doesn't support iter_keys\")\n\n cache.set(\"foo1\", 1)\n cache.set(\"foo2\", 1)\n cache.set(\"foo3\", 1)\n\n # Test generator object\n result = cache.iter_keys(\"foo*\")\n next_value = next(result)\n assert next_value is not None\n\n def test_primary_replica_switching(self, cache: RedisCache):\n if isinstance(cache.client, ShardClient):\n pytest.skip(\"ShardClient doesn't support get_client\")\n\n cache = cast(RedisCache, caches[\"sample\"])\n client = cache.client\n client._server = [\"foo\", \"bar\"]\n client._clients = [\"Foo\", \"Bar\"]\n\n assert client.get_client(write=True) == \"Foo\"\n assert client.get_client(write=False) == \"Bar\"\n\n def test_touch_zero_timeout(self, cache: RedisCache):\n cache.set(\"test_key\", 222, timeout=10)\n\n assert cache.touch(\"test_key\", 0) is True\n res = cache.get(\"test_key\")\n assert res is None\n\n def test_touch_positive_timeout(self, cache: RedisCache):\n cache.set(\"test_key\", 222, timeout=10)\n\n assert cache.touch(\"test_key\", 2) is True\n assert cache.get(\"test_key\") == 222\n time.sleep(3)\n assert cache.get(\"test_key\") is None\n\n def test_touch_negative_timeout(self, cache: RedisCache):\n cache.set(\"test_key\", 222, timeout=10)\n\n assert cache.touch(\"test_key\", -1) is True\n res = cache.get(\"test_key\")\n assert res is None\n\n def test_touch_missed_key(self, cache: RedisCache):\n assert cache.touch(\"test_key_does_not_exist\", 1) is False\n\n def test_touch_forever(self, cache: RedisCache):\n cache.set(\"test_key\", \"foo\", timeout=1)\n result = cache.touch(\"test_key\", None)\n assert result is True\n assert cache.ttl(\"test_key\") is None\n time.sleep(2)\n assert cache.get(\"test_key\") == \"foo\"\n\n def test_touch_forever_nonexistent(self, cache: RedisCache):\n result = cache.touch(\"test_key_does_not_exist\", None)\n assert result is False\n\n def test_touch_default_timeout(self, cache: RedisCache):\n cache.set(\"test_key\", \"foo\", timeout=1)\n result = cache.touch(\"test_key\")\n assert result is True\n time.sleep(2)\n assert cache.get(\"test_key\") == \"foo\"\n\n def test_clear(self, cache: RedisCache):\n cache.set(\"foo\", \"bar\")\n value_from_cache = cache.get(\"foo\")\n assert value_from_cache == \"bar\"\n cache.clear()\n value_from_cache_after_clear = cache.get(\"foo\")\n assert value_from_cache_after_clear is None\n" }, { "alpha_fraction": 0.6301200985908508, "alphanum_fraction": 0.6400933861732483, "avg_line_length": 29.74871826171875, "blob_id": "fa1a98f7f20e358721b1201c567f3d92387e6d2b", "content_id": "ccf323b1aad99fdd1629a7d0cf2852b856e2d0f1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 29980, "license_type": "permissive", "max_line_length": 162, "num_lines": 975, "path": "/README.rst", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "==============================\nRedis cache backend for Django\n==============================\n\n.. image:: https://jazzband.co/static/img/badge.svg\n :target: https://jazzband.co/\n :alt: Jazzband\n\n.. image:: https://github.com/jazzband/django-redis/actions/workflows/ci.yml/badge.svg\n :target: https://github.com/jazzband/django-redis/actions/workflows/ci.yml\n :alt: GitHub Actions\n\n.. image:: https://codecov.io/gh/jazzband/django-redis/branch/master/graph/badge.svg\n :target: https://codecov.io/gh/jazzband/django-redis\n :alt: Coverage\n\n.. image:: https://img.shields.io/pypi/v/django-redis.svg?style=flat\n :target: https://pypi.org/project/django-redis/\n\nThis is a `Jazzband <https://jazzband.co>`_ project. By contributing you agree\nto abide by the `Contributor Code of Conduct\n<https://jazzband.co/about/conduct>`_ and follow the `guidelines\n<https://jazzband.co/about/guidelines>`_.\n\nIntroduction\n------------\n\ndjango-redis is a BSD licensed, full featured Redis cache and session backend\nfor Django.\n\nWhy use django-redis?\n~~~~~~~~~~~~~~~~~~~~~\n\n- Uses native redis-py url notation connection strings\n- Pluggable clients\n- Pluggable parsers\n- Pluggable serializers\n- Primary/secondary support in the default client\n- Comprehensive test suite\n- Used in production in several projects as cache and session storage\n- Supports infinite timeouts\n- Facilities for raw access to Redis client/connection pool\n- Highly configurable (can emulate memcached exception behavior, for example)\n- Unix sockets supported by default\n\nRequirements\n~~~~~~~~~~~~\n\n- `Python`_ 3.6+\n- `Django`_ 2.2+\n- `redis-py`_ 3.0+\n- `Redis server`_ 2.8+\n\n.. _Python: https://www.python.org/downloads/\n.. _Django: https://www.djangoproject.com/download/\n.. _redis-py: https://pypi.org/project/redis/\n.. _Redis server: https://redis.io/download\n\nUser guide\n----------\n\nInstallation\n~~~~~~~~~~~~\n\nInstall with pip:\n\n.. code-block:: console\n\n $ python -m pip install django-redis\n\nConfigure as cache backend\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo start using django-redis, you should change your Django cache settings to\nsomething like:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n }\n }\n\ndjango-redis uses the redis-py native URL notation for connection strings, it\nallows better interoperability and has a connection string in more \"standard\"\nway. Some examples:\n\n- ``redis://[[username]:[password]]@localhost:6379/0``\n- ``rediss://[[username]:[password]]@localhost:6379/0``\n- ``unix://[[username]:[password]]@/path/to/socket.sock?db=0``\n\nThree URL schemes are supported:\n\n- ``redis://``: creates a normal TCP socket connection\n- ``rediss://``: creates a SSL wrapped TCP socket connection\n- ``unix://`` creates a Unix Domain Socket connection\n\nThere are several ways to specify a database number:\n\n- A ``db`` querystring option, e.g. ``redis://localhost?db=0``\n- If using the ``redis://`` scheme, the path argument of the URL, e.g.\n ``redis://localhost/0``\n\nWhen using `Redis' ACLs <https://redis.io/topics/acl>`_, you will need to add the\nusername to the URL (and provide the password with the Cache ``OPTIONS``).\nThe login for the user ``django`` would look like this:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://django@localhost:6379/0\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"PASSWORD\": \"mysecret\"\n }\n }\n }\n\nAn alternative would be write both username and password into the URL:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://django:mysecret@localhost:6379/0\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n }\n }\n\nIn some circumstances the password you should use to connect Redis\nis not URL-safe, in this case you can escape it or just use the\nconvenience option in ``OPTIONS`` dict:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"PASSWORD\": \"mysecret\"\n }\n }\n }\n\nTake care, that this option does not overwrites the password in the uri, so if\nyou have set the password in the uri, this settings will be ignored.\n\nConfigure as session backend\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nDjango can by default use any cache backend as session backend and you benefit\nfrom that by using django-redis as backend for session storage without\ninstalling any additional backends:\n\n.. code-block:: python\n\n SESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\n SESSION_CACHE_ALIAS = \"default\"\n\nTesting with django-redis\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\ndjango-redis supports customizing the underlying Redis client (see \"Pluggable\nclients\"). This can be used for testing purposes.\n\nIn case you want to flush all data from the cache after a test, add the\nfollowing lines to your test class:\n\n.. code-block:: python\n\n from django_redis import get_redis_connection\n\n def tearDown(self):\n get_redis_connection(\"default\").flushall()\n\nAdvanced usage\n--------------\n\nPickle version\n~~~~~~~~~~~~~~\n\nFor almost all values, django-redis uses pickle to serialize objects.\n\nThe ``pickle.DEFAULT_PROTOCOL`` version of pickle is used by default to ensure safe upgrades and compatibility across Python versions.\nIf you want set a concrete version, you can do it, using ``PICKLE_VERSION`` option:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n # ...\n \"OPTIONS\": {\n \"PICKLE_VERSION\": -1 # Will use highest protocol version available\n }\n }\n }\n\nSocket timeout\n~~~~~~~~~~~~~~\n\nSocket timeout can be set using ``SOCKET_TIMEOUT`` and\n``SOCKET_CONNECT_TIMEOUT`` options:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n # ...\n \"OPTIONS\": {\n \"SOCKET_CONNECT_TIMEOUT\": 5, # seconds\n \"SOCKET_TIMEOUT\": 5, # seconds\n }\n }\n }\n\n``SOCKET_CONNECT_TIMEOUT`` is the timeout for the connection to be established\nand ``SOCKET_TIMEOUT`` is the timeout for read and write operations after the\nconnection is established.\n\nCompression support\n~~~~~~~~~~~~~~~~~~~\n\ndjango-redis comes with compression support out of the box, but is deactivated\nby default. You can activate it setting up a concrete backend:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n # ...\n \"OPTIONS\": {\n \"COMPRESSOR\": \"django_redis.compressors.zlib.ZlibCompressor\",\n }\n }\n }\n\nLet see an example, of how make it work with *lzma* compression format:\n\n.. code-block:: python\n\n import lzma\n\n CACHES = {\n \"default\": {\n # ...\n \"OPTIONS\": {\n \"COMPRESSOR\": \"django_redis.compressors.lzma.LzmaCompressor\",\n }\n }\n }\n\n*Lz4* compression support (requires the lz4 library):\n\n.. code-block:: python\n\n import lz4\n\n CACHES = {\n \"default\": {\n # ...\n \"OPTIONS\": {\n \"COMPRESSOR\": \"django_redis.compressors.lz4.Lz4Compressor\",\n }\n }\n }\n\n*Zstandard (zstd)* compression support (requires the pyzstd library):\n\n.. code-block:: python\n\n import pyzstd\n\n CACHES = {\n \"default\": {\n # ...\n \"OPTIONS\": {\n \"COMPRESSOR\": \"django_redis.compressors.zstd.ZStdCompressor\",\n }\n }\n }\n\nMemcached exceptions behavior\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn some situations, when Redis is only used for cache, you do not want\nexceptions when Redis is down. This is default behavior in the memcached\nbackend and it can be emulated in django-redis.\n\nFor setup memcached like behaviour (ignore connection exceptions), you should\nset ``IGNORE_EXCEPTIONS`` settings on your cache configuration:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n # ...\n \"OPTIONS\": {\n \"IGNORE_EXCEPTIONS\": True,\n }\n }\n }\n\nAlso, you can apply the same settings to all configured caches, you can set the global flag in\nyour settings:\n\n.. code-block:: python\n\n DJANGO_REDIS_IGNORE_EXCEPTIONS = True\n\nLog Ignored Exceptions\n~~~~~~~~~~~~~~~~~~~~~~\n\nWhen ignoring exceptions with ``IGNORE_EXCEPTIONS`` or\n``DJANGO_REDIS_IGNORE_EXCEPTIONS``, you may optionally log exceptions using the\nglobal variable ``DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS`` in your settings file::\n\n DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True\n\nIf you wish to specify the logger in which the exceptions are output, simply\nset the global variable ``DJANGO_REDIS_LOGGER`` to the string name and/or path\nof the desired logger. This will default to ``__name__`` if no logger is\nspecified and ``DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS`` is ``True``::\n\n DJANGO_REDIS_LOGGER = 'some.specified.logger'\n\nInfinite timeout\n~~~~~~~~~~~~~~~~\n\ndjango-redis comes with infinite timeouts support out of the box. And it\nbehaves in same way as django backend contract specifies:\n\n- ``timeout=0`` expires the value immediately.\n- ``timeout=None`` infinite timeout\n\n.. code-block:: python\n\n cache.set(\"key\", \"value\", timeout=None)\n\nGet ttl (time-to-live) from key\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWith Redis, you can access to ttl of any stored key, for it, django-redis\nexposes ``ttl`` function.\n\nIt returns:\n\n- 0 if key does not exists (or already expired).\n- None for keys that exists but does not have any expiration.\n- ttl value for any volatile key (any key that has expiration).\n\n.. code-block:: pycon\n\n >>> from django.core.cache import cache\n >>> cache.set(\"foo\", \"value\", timeout=25)\n >>> cache.ttl(\"foo\")\n 25\n >>> cache.ttl(\"not-existent\")\n 0\n\nWith Redis, you can access to ttl of any stored key in milliseconds, for it, django-redis\nexposes ``pttl`` function.\n\n.. code-block:: pycon\n\n >>> from django.core.cache import cache\n >>> cache.set(\"foo\", \"value\", timeout=25)\n >>> cache.pttl(\"foo\")\n 25000\n >>> cache.pttl(\"not-existent\")\n 0\n\nExpire & Persist\n~~~~~~~~~~~~~~~~\n\nAdditionally to the simple ttl query, you can send persist a concrete key or\nspecify a new expiration timeout using the ``persist`` and ``expire`` methods:\n\n.. code-block:: pycon\n\n >>> cache.set(\"foo\", \"bar\", timeout=22)\n >>> cache.ttl(\"foo\")\n 22\n >>> cache.persist(\"foo\")\n True\n >>> cache.ttl(\"foo\")\n None\n\n.. code-block:: pycon\n\n >>> cache.set(\"foo\", \"bar\", timeout=22)\n >>> cache.expire(\"foo\", timeout=5)\n True\n >>> cache.ttl(\"foo\")\n 5\n\nThe ``expire_at`` method can be used to make the key expire at a specific moment in time.\n\n.. code-block:: pycon\n\n >>> cache.set(\"foo\", \"bar\", timeout=22)\n >>> cache.expire_at(\"foo\", datetime.now() + timedelta(hours=1))\n True\n >>> cache.ttl(\"foo\")\n 3600\n\nThe ``pexpire_at`` method can be used to make the key expire at a specific moment in time with milliseconds precision:\n\n.. code-block:: pycon\n\n >>> cache.set(\"foo\", \"bar\", timeout=22)\n >>> cache.pexpire_at(\"foo\", datetime.now() + timedelta(milliseconds=900, hours=1))\n True\n >>> cache.ttl(\"foo\")\n 3601\n >>> cache.pttl(\"foo\")\n 3600900\n\nThe ``pexpire`` method can be used to provide millisecond precision:\n\n.. code-block:: pycon\n\n >>> cache.set(\"foo\", \"bar\", timeout=22)\n >>> cache.pexpire(\"foo\", timeout=5500)\n True\n >>> cache.pttl(\"foo\")\n 5500\n\nLocks\n~~~~~\n\nIt also supports the Redis ability to create Redis distributed named locks. The\nLock interface is identical to the ``threading.Lock`` so you can use it as\nreplacement.\n\n.. code-block:: python\n\n with cache.lock(\"somekey\"):\n do_some_thing()\n\nScan & Delete keys in bulk\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ndjango-redis comes with some additional methods that help with searching or\ndeleting keys using glob patterns.\n\n.. code-block:: pycon\n\n >>> from django.core.cache import cache\n >>> cache.keys(\"foo_*\")\n [\"foo_1\", \"foo_2\"]\n\nA simple search like this will return all matched values. In databases with a\nlarge number of keys this isn't suitable method. Instead, you can use the\n``iter_keys`` function that works like the ``keys`` function but uses Redis\nserver side cursors. Calling ``iter_keys`` will return a generator that you can\nthen iterate over efficiently.\n\n.. code-block:: pycon\n\n >>> from django.core.cache import cache\n >>> cache.iter_keys(\"foo_*\")\n <generator object algo at 0x7ffa9c2713a8>\n >>> next(cache.iter_keys(\"foo_*\"))\n \"foo_1\"\n\nFor deleting keys, you should use ``delete_pattern`` which has the same glob\npattern syntax as the ``keys`` function and returns the number of deleted keys.\n\n.. code-block:: pycon\n\n >>> from django.core.cache import cache\n >>> cache.delete_pattern(\"foo_*\")\n\nTo achieve the best performance while deleting many keys, you should set ``DJANGO_REDIS_SCAN_ITERSIZE`` to a relatively\nhigh number (e.g., 100_000) by default in Django settings or pass it directly to the ``delete_pattern``.\n\n\n.. code-block:: pycon\n\n >>> from django.core.cache import cache\n >>> cache.delete_pattern(\"foo_*\", itersize=100_000)\n\nRedis native commands\n~~~~~~~~~~~~~~~~~~~~~\n\ndjango-redis has limited support for some Redis atomic operations, such as the\ncommands ``SETNX`` and ``INCR``.\n\nYou can use the ``SETNX`` command through the backend ``set()`` method with the\n``nx`` parameter:\n\n.. code-block:: pycon\n\n >>> from django.core.cache import cache\n >>> cache.set(\"key\", \"value1\", nx=True)\n True\n >>> cache.set(\"key\", \"value2\", nx=True)\n False\n >>> cache.get(\"key\")\n \"value1\"\n\nAlso, the ``incr`` and ``decr`` methods use Redis atomic operations when the\nvalue that a key contains is suitable for it.\n\nRaw client access\n~~~~~~~~~~~~~~~~~\n\nIn some situations your application requires access to a raw Redis client to\nuse some advanced features that aren't exposed by the Django cache interface.\nTo avoid storing another setting for creating a raw connection, django-redis\nexposes functions with which you can obtain a raw client reusing the cache\nconnection string: ``get_redis_connection(alias)``.\n\n.. code-block:: pycon\n\n >>> from django_redis import get_redis_connection\n >>> con = get_redis_connection(\"default\")\n >>> con\n <redis.client.Redis object at 0x2dc4510>\n\nWARNING: Not all pluggable clients support this feature.\n\nConnection pools\n~~~~~~~~~~~~~~~~\n\nBehind the scenes, django-redis uses the underlying redis-py connection pool\nimplementation, and exposes a simple way to configure it. Alternatively, you\ncan directly customize a connection/connection pool creation for a backend.\n\nThe default redis-py behavior is to not close connections, recycling them when\npossible.\n\nConfigure default connection pool\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe default connection pool is simple. For example, you can customize the\nmaximum number of connections in the pool by setting ``CONNECTION_POOL_KWARGS``\nin the ``CACHES`` setting:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n # ...\n \"OPTIONS\": {\n \"CONNECTION_POOL_KWARGS\": {\"max_connections\": 100}\n }\n }\n }\n\nYou can verify how many connections the pool has opened with the following\nsnippet:\n\n.. code-block:: python\n\n from django_redis import get_redis_connection\n\n r = get_redis_connection(\"default\") # Use the name you have defined for Redis in settings.CACHES\n connection_pool = r.connection_pool\n print(\"Created connections so far: %d\" % connection_pool._created_connections)\n\nSince the default connection pool passes all keyword arguments it doesn't use\nto its connections, you can also customize the connections that the pool makes\nby adding those options to ``CONNECTION_POOL_KWARGS``:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n # ...\n \"OPTIONS\": {\n \"CONNECTION_POOL_KWARGS\": {\"max_connections\": 100, \"retry_on_timeout\": True}\n }\n }\n }\n\nUse your own connection pool subclass\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nSometimes you want to use your own subclass of the connection pool. This is\npossible with django-redis using the ``CONNECTION_POOL_CLASS`` parameter in the\nbackend options.\n\n.. code-block:: python\n\n from redis.connection import ConnectionPool\n\n class MyOwnPool(ConnectionPool):\n # Just doing nothing, only for example purpose\n pass\n\n.. code-block:: python\n\n # Omitting all backend declaration boilerplate code.\n\n \"OPTIONS\": {\n \"CONNECTION_POOL_CLASS\": \"myproj.mypool.MyOwnPool\",\n }\n\nCustomize connection factory\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIf none of the previous methods satisfies you, you can get in the middle of the\ndjango-redis connection factory process and customize or completely rewrite it.\n\nBy default, django-redis creates connections through the\n``django_redis.pool.ConnectionFactory`` class that is specified in the global\nDjango setting ``DJANGO_REDIS_CONNECTION_FACTORY``.\n\n.. code-block:: python\n\n class ConnectionFactory(object):\n def get_connection_pool(self, params: dict):\n # Given connection parameters in the `params` argument, return new\n # connection pool. It should be overwritten if you want do\n # something before/after creating the connection pool, or return\n # your own connection pool.\n pass\n\n def get_connection(self, params: dict):\n # Given connection parameters in the `params` argument, return a\n # new connection. It should be overwritten if you want to do\n # something before/after creating a new connection. The default\n # implementation uses `get_connection_pool` to obtain a pool and\n # create a new connection in the newly obtained pool.\n pass\n\n def get_or_create_connection_pool(self, params: dict):\n # This is a high layer on top of `get_connection_pool` for\n # implementing a cache of created connection pools. It should be\n # overwritten if you want change the default behavior.\n pass\n\n def make_connection_params(self, url: str) -> dict:\n # The responsibility of this method is to convert basic connection\n # parameters and other settings to fully connection pool ready\n # connection parameters.\n pass\n\n def connect(self, url: str):\n # This is really a public API and entry point for this factory\n # class. This encapsulates the main logic of creating the\n # previously mentioned `params` using `make_connection_params` and\n # creating a new connection using the `get_connection` method.\n pass\n\nUse the sentinel connection factory\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIn order to facilitate using `Redis Sentinels`_, django-redis comes with a\nbuilt in sentinel connection factory, which creates sentinel connection pools.\nIn order to enable this functionality you should add the following:\n\n\n.. code-block:: python\n\n # Enable the alternate connection factory.\n DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory'\n\n # These sentinels are shared between all the examples, and are passed\n # directly to redis Sentinel. These can also be defined inline.\n SENTINELS = [\n ('sentinel-1', 26379),\n ('sentinel-2', 26379),\n ('sentinel-3', 26379),\n ]\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n # The hostname in LOCATION is the primary (service / master) name\n \"LOCATION\": \"redis://service_name/db\",\n \"OPTIONS\": {\n # While the default client will work, this will check you\n # have configured things correctly, and also create a\n # primary and replica pool for the service specified by\n # LOCATION rather than requiring two URLs.\n \"CLIENT_CLASS\": \"django_redis.client.SentinelClient\",\n\n # Sentinels which are passed directly to redis Sentinel.\n \"SENTINELS\": SENTINELS,\n\n # kwargs for redis Sentinel (optional).\n \"SENTINEL_KWARGS\": {},\n\n # You can still override the connection pool (optional).\n \"CONNECTION_POOL_CLASS\": \"redis.sentinel.SentinelConnectionPool\",\n },\n },\n\n # A minimal example using the SentinelClient.\n \"minimal\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n\n # The SentinelClient will use this location for both the primaries\n # and replicas.\n \"LOCATION\": \"redis://minimal_service_name/db\",\n\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.SentinelClient\",\n \"SENTINELS\": SENTINELS,\n },\n },\n\n # A minimal example using the DefaultClient.\n \"other\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": [\n # The DefaultClient is [primary, replicas...], but with the\n # SentinelConnectionPool it only requires one \"is_master=0\".\n \"redis://other_service_name/db?is_master=1\",\n \"redis://other_service_name/db?is_master=0\",\n ],\n \"OPTIONS\": {\"SENTINELS\": SENTINELS},\n },\n\n # A minimal example only using only replicas in read only mode (and\n # the DefaultClient).\n \"readonly\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://readonly_service_name/db?is_master=0\",\n \"OPTIONS\": {\"SENTINELS\": SENTINELS},\n },\n }\n\n.. _Redis Sentinels: https://redis.io/topics/sentinel\n\nPluggable parsers\n~~~~~~~~~~~~~~~~~\n\nredis-py (the Python Redis client used by django-redis) comes with a pure\nPython Redis parser that works very well for most common task, but if you want\nsome performance boost, you can use hiredis.\n\nhiredis is a Redis client written in C and it has its own parser that can be\nused with django-redis.\n\n.. code-block:: python\n\n \"OPTIONS\": {\n \"PARSER_CLASS\": \"redis.connection.HiredisParser\",\n }\n\nNote: if using version 5 of redis-py, use ``\"redis.connection._HiredisParser\"`` for the ``PARSER_CLASS`` due to an internal rename of classes within that package.\n\nPluggable clients\n~~~~~~~~~~~~~~~~~\n\ndjango-redis is designed for to be very flexible and very configurable. For it,\nit exposes a pluggable backends that make easy extend the default behavior, and\nit comes with few ones out the box.\n\nDefault client\n^^^^^^^^^^^^^^\n\nAlmost all about the default client is explained, with one exception: the\ndefault client comes with replication support.\n\nTo connect to a Redis replication setup, you should change the ``LOCATION`` to\nsomething like:\n\n.. code-block:: python\n\n \"LOCATION\": [\n \"redis://127.0.0.1:6379/1\",\n \"redis://127.0.0.1:6378/1\",\n ]\n\nThe first connection string represents the primary server and the rest to\nreplica servers.\n\nWARNING: Replication setup is not heavily tested in production environments.\n\nShard client\n^^^^^^^^^^^^\n\nThis pluggable client implements client-side sharding. It inherits almost all\nfunctionality from the default client. To use it, change your cache settings to\nsomething like this:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": [\n \"redis://127.0.0.1:6379/1\",\n \"redis://127.0.0.1:6379/2\",\n ],\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.ShardClient\",\n }\n }\n }\n\nWARNING: Shard client is still experimental, so be careful when using it in\nproduction environments.\n\nHerd client\n^^^^^^^^^^^\n\nThis pluggable client helps dealing with the thundering herd problem. You can read more about it\non link: `Wikipedia <https://en.wikipedia.org/wiki/Thundering_herd_problem>`_\n\nLike previous pluggable clients, it inherits all functionality from the default client, adding some\nadditional methods for getting/setting keys.\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.HerdClient\",\n }\n }\n }\n\nThis client exposes additional settings:\n\n- ``CACHE_HERD_TIMEOUT``: Set default herd timeout. (Default value: 60s)\n\nPluggable serializer\n~~~~~~~~~~~~~~~~~~~~\n\nThe pluggable clients serialize data before sending it to the server. By\ndefault, django-redis serializes the data using the Python ``pickle`` module.\nThis is very flexible and can handle a large range of object types.\n\nTo serialize using JSON instead, the serializer ``JSONSerializer`` is also\navailable.\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"SERIALIZER\": \"django_redis.serializers.json.JSONSerializer\",\n }\n }\n }\n\nThere's also support for serialization using `MsgPack`_ (that requires the\nmsgpack library):\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"SERIALIZER\": \"django_redis.serializers.msgpack.MSGPackSerializer\",\n }\n }\n }\n\n.. _MsgPack: https://msgpack.org/\n\nPluggable Redis client\n~~~~~~~~~~~~~~~~~~~~~~\n\ndjango-redis uses the Redis client ``redis.client.StrictClient`` by default. It\nis possible to use an alternative client.\n\nYou can customize the client used by setting ``REDIS_CLIENT_CLASS`` in the\n``CACHES`` setting. Optionally, you can provide arguments to this class by\nsetting ``REDIS_CLIENT_KWARGS``.\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"OPTIONS\": {\n \"REDIS_CLIENT_CLASS\": \"my.module.ClientClass\",\n \"REDIS_CLIENT_KWARGS\": {\"some_setting\": True},\n }\n }\n }\n\n\nClosing Connections\n~~~~~~~~~~~~~~~~~~~\n\nThe default django-redis behavior on close() is to keep the connections to Redis server.\n\nYou can change this default behaviour for all caches by the ``DJANGO_REDIS_CLOSE_CONNECTION = True``\nin the django settings (globally) or (at cache level) by setting ``CLOSE_CONNECTION: True`` in the ``OPTIONS``\nfor each configured cache.\n\nSetting True as a value will instruct the django-redis to close all the connections (since v. 4.12.2), irrespectively of its current usage.\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"CLOSE_CONNECTION\": True,\n }\n }\n }\n\nSSL/TLS and Self-Signed certificates\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn case you encounter a Redis server offering a TLS connection using a\nself-signed certificate you may disable certification verification with the\nfollowing:\n\n.. code-block:: python\n\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"rediss://127.0.0.1:6379/1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"CONNECTION_POOL_KWARGS\": {\"ssl_cert_reqs\": None}\n }\n }\n }\n\n\nLicense\n-------\n\n.. code-block:: text\n\n Copyright (c) 2011-2015 Andrey Antukh <[email protected]>\n Copyright (c) 2011 Sean Bleier\n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS`` AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" }, { "alpha_fraction": 0.7042253613471985, "alphanum_fraction": 0.7042253613471985, "avg_line_length": 20.846153259277344, "blob_id": "4dc7fd9bd874f16779381697738a1e8e4c3cff9a", "content_id": "d41591f6fde12a8c20be4ede1ea2978e997d2e5f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "permissive", "max_line_length": 46, "num_lines": 13, "path": "/django_redis/serializers/msgpack.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from typing import Any\n\nimport msgpack\n\nfrom .base import BaseSerializer\n\n\nclass MSGPackSerializer(BaseSerializer):\n def dumps(self, value: Any) -> bytes:\n return msgpack.dumps(value)\n\n def loads(self, value: bytes) -> Any:\n return msgpack.loads(value, raw=False)\n" }, { "alpha_fraction": 0.6352705359458923, "alphanum_fraction": 0.6412825584411621, "avg_line_length": 23.950000762939453, "blob_id": "28d3f36519e5ed2914df6b33348de904baf08ff0", "content_id": "014fc77e57fb5da3c69ae1c8acf12999436ba3c3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "permissive", "max_line_length": 52, "num_lines": 20, "path": "/django_redis/compressors/zlib.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import zlib\n\nfrom ..exceptions import CompressorError\nfrom .base import BaseCompressor\n\n\nclass ZlibCompressor(BaseCompressor):\n min_length = 15\n preset = 6\n\n def compress(self, value: bytes) -> bytes:\n if len(value) > self.min_length:\n return zlib.compress(value, self.preset)\n return value\n\n def decompress(self, value: bytes) -> bytes:\n try:\n return zlib.decompress(value)\n except zlib.error as e:\n raise CompressorError(e)\n" }, { "alpha_fraction": 0.6857483386993408, "alphanum_fraction": 0.6891273856163025, "avg_line_length": 34.181819915771484, "blob_id": "ebdbb4bdeebd5b37a553d0ae49ab7e5c48eb78fd", "content_id": "652a03d5c4af9ed56cf9c42cc0c120f4a9167708", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5031, "license_type": "permissive", "max_line_length": 88, "num_lines": 143, "path": "/tests/test_cache_options.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import copy\nfrom typing import Iterable, cast\n\nimport pytest\nfrom django.core.cache import caches\nfrom pytest import LogCaptureFixture\nfrom pytest_django.fixtures import SettingsWrapper\nfrom redis.exceptions import ConnectionError\n\nfrom django_redis.cache import RedisCache\nfrom django_redis.client import ShardClient\n\n\ndef make_key(key: str, prefix: str, version: str) -> str:\n return f\"{prefix}#{version}#{key}\"\n\n\ndef reverse_key(key: str) -> str:\n return key.split(\"#\", 2)[2]\n\n\[email protected]\ndef ignore_exceptions_cache(settings: SettingsWrapper) -> RedisCache:\n caches_setting = copy.deepcopy(settings.CACHES)\n caches_setting[\"doesnotexist\"][\"OPTIONS\"][\"IGNORE_EXCEPTIONS\"] = True\n caches_setting[\"doesnotexist\"][\"OPTIONS\"][\"LOG_IGNORED_EXCEPTIONS\"] = True\n settings.CACHES = caches_setting\n settings.DJANGO_REDIS_IGNORE_EXCEPTIONS = True\n settings.DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True\n return cast(RedisCache, caches[\"doesnotexist\"])\n\n\ndef test_get_django_omit_exceptions_many_returns_default_arg(\n ignore_exceptions_cache: RedisCache,\n):\n assert ignore_exceptions_cache._ignore_exceptions is True\n assert ignore_exceptions_cache.get_many([\"key1\", \"key2\", \"key3\"]) == {}\n\n\ndef test_get_django_omit_exceptions(\n caplog: LogCaptureFixture, ignore_exceptions_cache: RedisCache\n):\n assert ignore_exceptions_cache._ignore_exceptions is True\n assert ignore_exceptions_cache._log_ignored_exceptions is True\n\n assert ignore_exceptions_cache.get(\"key\") is None\n assert ignore_exceptions_cache.get(\"key\", \"default\") == \"default\"\n assert ignore_exceptions_cache.get(\"key\", default=\"default\") == \"default\"\n\n assert len(caplog.records) == 3\n assert all(\n record.levelname == \"ERROR\" and record.msg == \"Exception ignored\"\n for record in caplog.records\n )\n\n\ndef test_get_django_omit_exceptions_priority_1(settings: SettingsWrapper):\n caches_setting = copy.deepcopy(settings.CACHES)\n caches_setting[\"doesnotexist\"][\"OPTIONS\"][\"IGNORE_EXCEPTIONS\"] = True\n settings.CACHES = caches_setting\n settings.DJANGO_REDIS_IGNORE_EXCEPTIONS = False\n cache = cast(RedisCache, caches[\"doesnotexist\"])\n assert cache._ignore_exceptions is True\n assert cache.get(\"key\") is None\n\n\ndef test_get_django_omit_exceptions_priority_2(settings: SettingsWrapper):\n caches_setting = copy.deepcopy(settings.CACHES)\n caches_setting[\"doesnotexist\"][\"OPTIONS\"][\"IGNORE_EXCEPTIONS\"] = False\n settings.CACHES = caches_setting\n settings.DJANGO_REDIS_IGNORE_EXCEPTIONS = True\n cache = cast(RedisCache, caches[\"doesnotexist\"])\n assert cache._ignore_exceptions is False\n with pytest.raises(ConnectionError):\n cache.get(\"key\")\n\n\[email protected]\ndef key_prefix_cache(\n cache: RedisCache, settings: SettingsWrapper\n) -> Iterable[RedisCache]:\n caches_setting = copy.deepcopy(settings.CACHES)\n caches_setting[\"default\"][\"KEY_PREFIX\"] = \"*\"\n settings.CACHES = caches_setting\n yield cache\n\n\[email protected]\ndef with_prefix_cache() -> Iterable[RedisCache]:\n with_prefix = cast(RedisCache, caches[\"with_prefix\"])\n yield with_prefix\n with_prefix.clear()\n\n\nclass TestDjangoRedisCacheEscapePrefix:\n def test_delete_pattern(\n self, key_prefix_cache: RedisCache, with_prefix_cache: RedisCache\n ):\n key_prefix_cache.set(\"a\", \"1\")\n with_prefix_cache.set(\"b\", \"2\")\n key_prefix_cache.delete_pattern(\"*\")\n assert key_prefix_cache.has_key(\"a\") is False\n assert with_prefix_cache.get(\"b\") == \"2\"\n\n def test_iter_keys(\n self, key_prefix_cache: RedisCache, with_prefix_cache: RedisCache\n ):\n if isinstance(key_prefix_cache.client, ShardClient):\n pytest.skip(\"ShardClient doesn't support iter_keys\")\n\n key_prefix_cache.set(\"a\", \"1\")\n with_prefix_cache.set(\"b\", \"2\")\n assert list(key_prefix_cache.iter_keys(\"*\")) == [\"a\"]\n\n def test_keys(self, key_prefix_cache: RedisCache, with_prefix_cache: RedisCache):\n key_prefix_cache.set(\"a\", \"1\")\n with_prefix_cache.set(\"b\", \"2\")\n keys = key_prefix_cache.keys(\"*\")\n assert \"a\" in keys\n assert \"b\" not in keys\n\n\ndef test_custom_key_function(cache: RedisCache, settings: SettingsWrapper):\n caches_setting = copy.deepcopy(settings.CACHES)\n caches_setting[\"default\"][\"KEY_FUNCTION\"] = \"test_cache_options.make_key\"\n caches_setting[\"default\"][\"REVERSE_KEY_FUNCTION\"] = \"test_cache_options.reverse_key\"\n settings.CACHES = caches_setting\n\n if isinstance(cache.client, ShardClient):\n pytest.skip(\"ShardClient doesn't support get_client\")\n\n for key in [\"foo-aa\", \"foo-ab\", \"foo-bb\", \"foo-bc\"]:\n cache.set(key, \"foo\")\n\n res = cache.delete_pattern(\"*foo-a*\")\n assert bool(res) is True\n\n keys = cache.keys(\"foo*\")\n assert set(keys) == {\"foo-bb\", \"foo-bc\"}\n # ensure our custom function was actually called\n assert {k.decode() for k in cache.client.get_client(write=False).keys(\"*\")} == (\n {\"#1#foo-bc\", \"#1#foo-bb\"}\n )\n" }, { "alpha_fraction": 0.6310272812843323, "alphanum_fraction": 0.6457023024559021, "avg_line_length": 24.105262756347656, "blob_id": "34ddbfd68365a080d229ac511b17715d9838ddd4", "content_id": "81dffebe080ee346462aab0b68d29be1ff2250b1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 477, "license_type": "permissive", "max_line_length": 62, "num_lines": 19, "path": "/tests/test_connection_string.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import pytest\n\nfrom django_redis import pool\n\n\[email protected](\n \"connection_string\",\n [\n \"unix://tmp/foo.bar?db=1\",\n \"redis://localhost/2\",\n \"rediss://localhost:3333?db=2\",\n ],\n)\ndef test_connection_strings(connection_string: str):\n cf = pool.get_connection_factory(\n path=\"django_redis.pool.ConnectionFactory\", options={}\n )\n res = cf.make_connection_params(connection_string)\n assert res[\"url\"] == connection_string\n" }, { "alpha_fraction": 0.638557493686676, "alphanum_fraction": 0.64544278383255, "avg_line_length": 37.70448684692383, "blob_id": "b894e08789c4d2a7e6dd1fdcc54aae765cb52a18", "content_id": "36745035fb1e9cf9e4782bbcb5922a09c5f4a4cf", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14669, "license_type": "permissive", "max_line_length": 109, "num_lines": 379, "path": "/tests/test_session.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import base64\nimport unittest\nfrom datetime import timedelta\nfrom typing import Optional, Type\n\nimport django\nimport pytest\nfrom django.conf import settings\nfrom django.contrib.sessions.backends.base import SessionBase\nfrom django.contrib.sessions.backends.cache import SessionStore as CacheSession\nfrom django.core.cache import DEFAULT_CACHE_ALIAS, caches\nfrom django.test import override_settings\nfrom django.utils import timezone\n\nfrom django_redis.serializers.msgpack import MSGPackSerializer\n\nSessionType = Type[SessionBase]\n\n\n# Copied from Django's sessions test suite. Keep in sync with upstream.\n# https://github.com/django/django/blob/main/tests/sessions_tests/tests.py\nclass SessionTestsMixin:\n # This does not inherit from TestCase to avoid any tests being run with this\n # class, which wouldn't work, and to allow different TestCase subclasses to\n # be used.\n\n backend: Optional[SessionType] = None # subclasses must specify\n\n def setUp(self):\n self.session = self.backend()\n\n def tearDown(self):\n # NB: be careful to delete any sessions created; stale sessions fill up\n # the /tmp (with some backends) and eventually overwhelm it after lots\n # of runs (think buildbots)\n self.session.delete()\n\n def test_new_session(self):\n self.assertIs(self.session.modified, False)\n self.assertIs(self.session.accessed, False)\n\n def test_get_empty(self):\n self.assertIsNone(self.session.get(\"cat\"))\n\n def test_store(self):\n self.session[\"cat\"] = \"dog\"\n self.assertIs(self.session.modified, True)\n self.assertEqual(self.session.pop(\"cat\"), \"dog\")\n\n def test_pop(self):\n self.session[\"some key\"] = \"exists\"\n # Need to reset these to pretend we haven't accessed it:\n self.accessed = False\n self.modified = False\n\n self.assertEqual(self.session.pop(\"some key\"), \"exists\")\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, True)\n self.assertIsNone(self.session.get(\"some key\"))\n\n def test_pop_default(self):\n self.assertEqual(\n self.session.pop(\"some key\", \"does not exist\"), \"does not exist\"\n )\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, False)\n\n def test_pop_default_named_argument(self):\n self.assertEqual(\n self.session.pop(\"some key\", default=\"does not exist\"), \"does not exist\"\n )\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, False)\n\n def test_pop_no_default_keyerror_raised(self):\n with self.assertRaises(KeyError):\n self.session.pop(\"some key\")\n\n def test_setdefault(self):\n self.assertEqual(self.session.setdefault(\"foo\", \"bar\"), \"bar\")\n self.assertEqual(self.session.setdefault(\"foo\", \"baz\"), \"bar\")\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, True)\n\n def test_update(self):\n self.session.update({\"update key\": 1})\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, True)\n self.assertEqual(self.session.get(\"update key\"), 1)\n\n def test_has_key(self):\n self.session[\"some key\"] = 1\n self.session.modified = False\n self.session.accessed = False\n self.assertIn(\"some key\", self.session)\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, False)\n\n def test_values(self):\n self.assertEqual(list(self.session.values()), [])\n self.assertIs(self.session.accessed, True)\n self.session[\"some key\"] = 1\n self.session.modified = False\n self.session.accessed = False\n self.assertEqual(list(self.session.values()), [1])\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, False)\n\n def test_keys(self):\n self.session[\"x\"] = 1\n self.session.modified = False\n self.session.accessed = False\n self.assertEqual(list(self.session.keys()), [\"x\"])\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, False)\n\n def test_items(self):\n self.session[\"x\"] = 1\n self.session.modified = False\n self.session.accessed = False\n self.assertEqual(list(self.session.items()), [(\"x\", 1)])\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, False)\n\n def test_clear(self):\n self.session[\"x\"] = 1\n self.session.modified = False\n self.session.accessed = False\n self.assertEqual(list(self.session.items()), [(\"x\", 1)])\n self.session.clear()\n self.assertEqual(list(self.session.items()), [])\n self.assertIs(self.session.accessed, True)\n self.assertIs(self.session.modified, True)\n\n def test_save(self):\n self.session.save()\n self.assertIs(self.session.exists(self.session.session_key), True)\n\n def test_delete(self):\n self.session.save()\n self.session.delete(self.session.session_key)\n self.assertIs(self.session.exists(self.session.session_key), False)\n\n def test_flush(self):\n self.session[\"foo\"] = \"bar\"\n self.session.save()\n prev_key = self.session.session_key\n self.session.flush()\n self.assertIs(self.session.exists(prev_key), False)\n self.assertNotEqual(self.session.session_key, prev_key)\n self.assertIsNone(self.session.session_key)\n self.assertIs(self.session.modified, True)\n self.assertIs(self.session.accessed, True)\n\n def test_cycle(self):\n self.session[\"a\"], self.session[\"b\"] = \"c\", \"d\"\n self.session.save()\n prev_key = self.session.session_key\n prev_data = list(self.session.items())\n self.session.cycle_key()\n self.assertIs(self.session.exists(prev_key), False)\n self.assertNotEqual(self.session.session_key, prev_key)\n self.assertEqual(list(self.session.items()), prev_data)\n\n def test_cycle_with_no_session_cache(self):\n self.session[\"a\"], self.session[\"b\"] = \"c\", \"d\"\n self.session.save()\n prev_data = self.session.items()\n self.session = self.backend(self.session.session_key)\n self.assertIs(hasattr(self.session, \"_session_cache\"), False)\n self.session.cycle_key()\n self.assertCountEqual(self.session.items(), prev_data)\n\n def test_save_doesnt_clear_data(self):\n self.session[\"a\"] = \"b\"\n self.session.save()\n self.assertEqual(self.session[\"a\"], \"b\")\n\n def test_invalid_key(self):\n # Submitting an invalid session key (either by guessing, or if the db has\n # removed the key) results in a new key being generated.\n try:\n session = self.backend(\"1\")\n session.save()\n self.assertNotEqual(session.session_key, \"1\")\n self.assertIsNone(session.get(\"cat\"))\n session.delete()\n finally:\n # Some backends leave a stale cache entry for the invalid\n # session key; make sure that entry is manually deleted\n session.delete(\"1\")\n\n def test_session_key_empty_string_invalid(self):\n \"\"\"Falsey values (Such as an empty string) are rejected.\"\"\"\n self.session._session_key = \"\"\n self.assertIsNone(self.session.session_key)\n\n def test_session_key_too_short_invalid(self):\n \"\"\"Strings shorter than 8 characters are rejected.\"\"\"\n self.session._session_key = \"1234567\"\n self.assertIsNone(self.session.session_key)\n\n def test_session_key_valid_string_saved(self):\n \"\"\"Strings of length 8 and up are accepted and stored.\"\"\"\n self.session._session_key = \"12345678\"\n self.assertEqual(self.session.session_key, \"12345678\")\n\n def test_session_key_is_read_only(self):\n def set_session_key(session):\n session.session_key = session._get_new_session_key()\n\n with self.assertRaises(AttributeError):\n set_session_key(self.session)\n\n # Custom session expiry\n def test_default_expiry(self):\n # A normal session has a max age equal to settings\n self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)\n\n # So does a custom session with an idle expiration time of 0 (but it'll\n # expire at browser close)\n self.session.set_expiry(0)\n self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)\n\n def test_custom_expiry_seconds(self):\n modification = timezone.now()\n\n self.session.set_expiry(10)\n\n date = self.session.get_expiry_date(modification=modification)\n self.assertEqual(date, modification + timedelta(seconds=10))\n\n age = self.session.get_expiry_age(modification=modification)\n self.assertEqual(age, 10)\n\n def test_custom_expiry_timedelta(self):\n modification = timezone.now()\n\n # Mock timezone.now, because set_expiry calls it on this code path.\n original_now = timezone.now\n try:\n timezone.now = lambda: modification\n self.session.set_expiry(timedelta(seconds=10))\n finally:\n timezone.now = original_now\n\n date = self.session.get_expiry_date(modification=modification)\n self.assertEqual(date, modification + timedelta(seconds=10))\n\n age = self.session.get_expiry_age(modification=modification)\n self.assertEqual(age, 10)\n\n def test_custom_expiry_datetime(self):\n modification = timezone.now()\n\n self.session.set_expiry(modification + timedelta(seconds=10))\n\n date = self.session.get_expiry_date(modification=modification)\n self.assertEqual(date, modification + timedelta(seconds=10))\n\n age = self.session.get_expiry_age(modification=modification)\n self.assertEqual(age, 10)\n\n def test_custom_expiry_reset(self):\n self.session.set_expiry(None)\n self.session.set_expiry(10)\n self.session.set_expiry(None)\n self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)\n\n def test_get_expire_at_browser_close(self):\n # Tests get_expire_at_browser_close with different settings and different\n # set_expiry calls\n with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False):\n self.session.set_expiry(10)\n self.assertIs(self.session.get_expire_at_browser_close(), False)\n\n self.session.set_expiry(0)\n self.assertIs(self.session.get_expire_at_browser_close(), True)\n\n self.session.set_expiry(None)\n self.assertIs(self.session.get_expire_at_browser_close(), False)\n\n with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True):\n self.session.set_expiry(10)\n self.assertIs(self.session.get_expire_at_browser_close(), False)\n\n self.session.set_expiry(0)\n self.assertIs(self.session.get_expire_at_browser_close(), True)\n\n self.session.set_expiry(None)\n self.assertIs(self.session.get_expire_at_browser_close(), True)\n\n def test_decode(self):\n # Ensure we can decode what we encode\n data = {\"a test key\": \"a test value\"}\n encoded = self.session.encode(data)\n self.assertEqual(self.session.decode(encoded), data)\n\n def test_decode_failure_logged_to_security(self):\n bad_encode = base64.b64encode(b\"flaskdj:alkdjf\").decode(\"ascii\")\n with self.assertLogs(\"django.security.SuspiciousSession\", \"WARNING\") as cm:\n self.assertEqual({}, self.session.decode(bad_encode))\n # The failed decode is logged.\n self.assertIn(\"corrupted\", cm.output[0])\n\n def test_actual_expiry(self):\n # this doesn't work with JSONSerializer (serializing timedelta)\n with override_settings(\n SESSION_SERIALIZER=\"django.contrib.sessions.serializers.PickleSerializer\"\n ):\n self.session = self.backend() # reinitialize after overriding settings\n\n # Regression test for #19200\n old_session_key = None\n new_session_key = None\n try:\n self.session[\"foo\"] = \"bar\"\n self.session.set_expiry(-timedelta(seconds=10))\n self.session.save()\n old_session_key = self.session.session_key\n # With an expiry date in the past, the session expires instantly.\n new_session = self.backend(self.session.session_key)\n new_session_key = new_session.session_key\n self.assertNotIn(\"foo\", new_session)\n finally:\n self.session.delete(old_session_key)\n self.session.delete(new_session_key)\n\n def test_session_load_does_not_create_record(self):\n \"\"\"\n Loading an unknown session key does not create a session record.\n Creating session records on load is a DOS vulnerability.\n \"\"\"\n session = self.backend(\"someunknownkey\")\n session.load()\n\n self.assertIsNone(session.session_key)\n self.assertIs(session.exists(session.session_key), False)\n # provided unknown key was cycled, not reused\n self.assertNotEqual(session.session_key, \"someunknownkey\")\n\n def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self):\n \"\"\"\n Sessions shouldn't be resurrected by a concurrent request.\n \"\"\"\n from django.contrib.sessions.backends.base import UpdateError\n\n # Create new session.\n s1 = self.backend()\n s1[\"test_data\"] = \"value1\"\n s1.save(must_create=True)\n\n # Logout in another context.\n s2 = self.backend(s1.session_key)\n s2.delete()\n\n # Modify session in first context.\n s1[\"test_data\"] = \"value2\"\n with self.assertRaises(UpdateError):\n # This should throw an exception as the session is deleted, not\n # resurrect the session.\n s1.save()\n\n self.assertEqual(s1.load(), {})\n\n\nclass SessionTests(SessionTestsMixin, unittest.TestCase):\n backend = CacheSession\n\n @pytest.mark.skipif(\n django.VERSION >= (4, 2),\n reason=\"PickleSerializer is removed as of https://code.djangoproject.com/ticket/29708\", # noqa: E501\n )\n def test_actual_expiry(self):\n if isinstance(\n caches[DEFAULT_CACHE_ALIAS].client._serializer, MSGPackSerializer\n ):\n self.skipTest(\"msgpack serializer doesn't support datetime serialization\")\n super().test_actual_expiry()\n" }, { "alpha_fraction": 0.6774193644523621, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 10.75, "blob_id": "a0c8b707e15ccc1c526b529e8d5793077b7110ae", "content_id": "bb58d92f7990f6180d200508d28ac6424e8511cd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 93, "license_type": "permissive", "max_line_length": 28, "num_lines": 8, "path": "/.github/ISSUE_TEMPLATE/question.md", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "---\nname: Question\nabout: Create question to us\ntitle: ''\nlabels: question\nassignees: ''\n\n---" }, { "alpha_fraction": 0.615160346031189, "alphanum_fraction": 0.615160346031189, "avg_line_length": 27.58333396911621, "blob_id": "e8a1004aa66981f90d237dee4a2aab236dc63c42", "content_id": "be9614511247b2ab530dd0cb8fccf67209b3e54a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "permissive", "max_line_length": 50, "num_lines": 12, "path": "/django_redis/exceptions.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "class ConnectionInterrupted(Exception):\n def __init__(self, connection, parent=None):\n self.connection = connection\n\n def __str__(self) -> str:\n error_type = type(self.__cause__).__name__\n error_msg = str(self.__cause__)\n return f\"Redis {error_type}: {error_msg}\"\n\n\nclass CompressorError(Exception):\n pass\n" }, { "alpha_fraction": 0.6681788563728333, "alphanum_fraction": 0.6707712411880493, "avg_line_length": 36.63414764404297, "blob_id": "038b711adab65b6a963d19e6ca42ab453b5b4ecc", "content_id": "709f4e5338e3a5274f5fa6fb61e3cd8a77e76d13", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1543, "license_type": "permissive", "max_line_length": 84, "num_lines": 41, "path": "/django_redis/client/sentinel.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from urllib.parse import parse_qs, urlencode, urlparse, urlunparse\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom redis.sentinel import SentinelConnectionPool\n\nfrom .default import DefaultClient\n\n\ndef replace_query(url, query):\n return urlunparse((*url[:4], urlencode(query, doseq=True), url[5]))\n\n\nclass SentinelClient(DefaultClient):\n \"\"\"\n Sentinel client which uses the single redis URL specified by the CACHE's\n LOCATION to create a LOCATION configuration for two connection pools; One\n pool for the primaries and another pool for the replicas, and upon\n connecting ensures the connection pool factory is configured correctly.\n \"\"\"\n\n def __init__(self, server, params, backend):\n if isinstance(server, str):\n url = urlparse(server)\n primary_query = parse_qs(url.query, keep_blank_values=True)\n replica_query = dict(primary_query)\n primary_query[\"is_master\"] = [1]\n replica_query[\"is_master\"] = [0]\n\n server = [replace_query(url, i) for i in (primary_query, replica_query)]\n\n super().__init__(server, params, backend)\n\n def connect(self, *args, **kwargs):\n connection = super().connect(*args, **kwargs)\n if not isinstance(connection.connection_pool, SentinelConnectionPool):\n raise ImproperlyConfigured(\n \"Settings DJANGO_REDIS_CONNECTION_FACTORY or \"\n \"CACHE[].OPTIONS.CONNECTION_POOL_CLASS is not configured correctly.\"\n )\n\n return connection\n" }, { "alpha_fraction": 0.6898148059844971, "alphanum_fraction": 0.6898148059844971, "avg_line_length": 23, "blob_id": "cd0965843a01c49ec68315915dc469b10a1d3335", "content_id": "4946886fed82288d89d4f979800ef79673c60b6f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "permissive", "max_line_length": 48, "num_lines": 9, "path": "/django_redis/compressors/identity.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "from .base import BaseCompressor\n\n\nclass IdentityCompressor(BaseCompressor):\n def compress(self, value: bytes) -> bytes:\n return value\n\n def decompress(self, value: bytes) -> bytes:\n return value\n" }, { "alpha_fraction": 0.7235293984413147, "alphanum_fraction": 0.7235293984413147, "avg_line_length": 41.5, "blob_id": "6a137361f0d841689760e1ece3080b1678fd5677", "content_id": "4b91465e1ffa1387c1e631636a35a98b4a708efc", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 340, "license_type": "permissive", "max_line_length": 78, "num_lines": 8, "path": "/CONTRIBUTING.rst", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": ".. image:: https://jazzband.co/static/img/jazzband.svg\n :target: https://jazzband.co/\n :alt: Jazzband\n\nThis is a `Jazzband <https://jazzband.co>`_ project. By contributing you agree\nto abide by the `Contributor Code of Conduct\n<https://jazzband.co/about/conduct>`_ and follow the `guidelines\n<https://jazzband.co/about/guidelines>`_.\n" }, { "alpha_fraction": 0.5507329702377319, "alphanum_fraction": 0.5529913902282715, "avg_line_length": 30.30205726623535, "blob_id": "bf52fcae8a85d1d36dbbe0f159c4572f397afa2d", "content_id": "6886b46b13fa6c905d1d9f7c3954d8b917ea5d23", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24353, "license_type": "permissive", "max_line_length": 88, "num_lines": 778, "path": "/django_redis/client/default.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import random\nimport re\nimport socket\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom typing import Any, Dict, Iterator, List, Optional, Union\n\nfrom django.conf import settings\nfrom django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache, get_key_func\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.module_loading import import_string\nfrom redis import Redis\nfrom redis.exceptions import ConnectionError, ResponseError, TimeoutError\n\nfrom .. import pool\nfrom ..exceptions import CompressorError, ConnectionInterrupted\nfrom ..util import CacheKey\n\n_main_exceptions = (TimeoutError, ResponseError, ConnectionError, socket.timeout)\n\nspecial_re = re.compile(\"([*?[])\")\n\n\ndef glob_escape(s: str) -> str:\n return special_re.sub(r\"[\\1]\", s)\n\n\nclass DefaultClient:\n def __init__(self, server, params: Dict[str, Any], backend: BaseCache) -> None:\n self._backend = backend\n self._server = server\n self._params = params\n\n self.reverse_key = get_key_func(\n params.get(\"REVERSE_KEY_FUNCTION\")\n or \"django_redis.util.default_reverse_key\"\n )\n\n if not self._server:\n raise ImproperlyConfigured(\"Missing connections string\")\n\n if not isinstance(self._server, (list, tuple, set)):\n self._server = self._server.split(\",\")\n\n self._clients: List[Optional[Redis]] = [None] * len(self._server)\n self._options = params.get(\"OPTIONS\", {})\n self._replica_read_only = self._options.get(\"REPLICA_READ_ONLY\", True)\n\n serializer_path = self._options.get(\n \"SERIALIZER\", \"django_redis.serializers.pickle.PickleSerializer\"\n )\n serializer_cls = import_string(serializer_path)\n\n compressor_path = self._options.get(\n \"COMPRESSOR\", \"django_redis.compressors.identity.IdentityCompressor\"\n )\n compressor_cls = import_string(compressor_path)\n\n self._serializer = serializer_cls(options=self._options)\n self._compressor = compressor_cls(options=self._options)\n\n self.connection_factory = pool.get_connection_factory(options=self._options)\n\n def __contains__(self, key: Any) -> bool:\n return self.has_key(key)\n\n def get_next_client_index(\n self, write: bool = True, tried: Optional[List[int]] = None\n ) -> int:\n \"\"\"\n Return a next index for read client. This function implements a default\n behavior for get a next read client for a replication setup.\n\n Overwrite this function if you want a specific\n behavior.\n \"\"\"\n if tried is None:\n tried = list()\n\n if tried and len(tried) < len(self._server):\n not_tried = [i for i in range(0, len(self._server)) if i not in tried]\n return random.choice(not_tried)\n\n if write or len(self._server) == 1:\n return 0\n\n return random.randint(1, len(self._server) - 1)\n\n def get_client(\n self,\n write: bool = True,\n tried: Optional[List[int]] = None,\n show_index: bool = False,\n ):\n \"\"\"\n Method used for obtain a raw redis client.\n\n This function is used by almost all cache backend\n operations for obtain a native redis client/connection\n instance.\n \"\"\"\n index = self.get_next_client_index(write=write, tried=tried)\n\n if self._clients[index] is None:\n self._clients[index] = self.connect(index)\n\n if show_index:\n return self._clients[index], index\n else:\n return self._clients[index]\n\n def connect(self, index: int = 0) -> Redis:\n \"\"\"\n Given a connection index, returns a new raw redis client/connection\n instance. Index is used for replication setups and indicates that\n connection string should be used. In normal setups, index is 0.\n \"\"\"\n return self.connection_factory.connect(self._server[index])\n\n def disconnect(self, index=0, client=None):\n \"\"\"delegates the connection factory to disconnect the client\"\"\"\n if not client:\n client = self._clients[index]\n return self.connection_factory.disconnect(client) if client else None\n\n def set(\n self,\n key: Any,\n value: Any,\n timeout: Optional[float] = DEFAULT_TIMEOUT,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n nx: bool = False,\n xx: bool = False,\n ) -> bool:\n \"\"\"\n Persist a value to the cache, and set an optional expiration time.\n\n Also supports optional nx parameter. If set to True - will use redis\n setnx instead of set.\n \"\"\"\n nkey = self.make_key(key, version=version)\n nvalue = self.encode(value)\n\n if timeout is DEFAULT_TIMEOUT:\n timeout = self._backend.default_timeout\n\n original_client = client\n tried: List[int] = []\n while True:\n try:\n if client is None:\n client, index = self.get_client(\n write=True, tried=tried, show_index=True\n )\n\n if timeout is not None:\n # Convert to milliseconds\n timeout = int(timeout * 1000)\n\n if timeout <= 0:\n if nx:\n # Using negative timeouts when nx is True should\n # not expire (in our case delete) the value if it exists.\n # Obviously expire not existent value is noop.\n return not self.has_key(key, version=version, client=client)\n else:\n # redis doesn't support negative timeouts in ex flags\n # so it seems that it's better to just delete the key\n # than to set it and than expire in a pipeline\n return bool(\n self.delete(key, client=client, version=version)\n )\n\n return bool(client.set(nkey, nvalue, nx=nx, px=timeout, xx=xx))\n except _main_exceptions as e:\n if (\n not original_client\n and not self._replica_read_only\n and len(tried) < len(self._server)\n ):\n tried.append(index)\n client = None\n continue\n raise ConnectionInterrupted(connection=client) from e\n\n def incr_version(\n self,\n key: Any,\n delta: int = 1,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ) -> int:\n \"\"\"\n Adds delta to the cache version for the supplied key. Returns the\n new version.\n \"\"\"\n\n if client is None:\n client = self.get_client(write=True)\n\n if version is None:\n version = self._backend.version\n\n old_key = self.make_key(key, version)\n value = self.get(old_key, version=version, client=client)\n\n try:\n ttl = self.ttl(old_key, version=version, client=client)\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n if value is None:\n raise ValueError(\"Key '%s' not found\" % key)\n\n if isinstance(key, CacheKey):\n new_key = self.make_key(key.original_key(), version=version + delta)\n else:\n new_key = self.make_key(key, version=version + delta)\n\n self.set(new_key, value, timeout=ttl, client=client)\n self.delete(old_key, client=client)\n return version + delta\n\n def add(\n self,\n key: Any,\n value: Any,\n timeout: Any = DEFAULT_TIMEOUT,\n version: Optional[Any] = None,\n client: Optional[Redis] = None,\n ) -> bool:\n \"\"\"\n Add a value to the cache, failing if the key already exists.\n\n Returns ``True`` if the object was added, ``False`` if not.\n \"\"\"\n return self.set(key, value, timeout, version=version, client=client, nx=True)\n\n def get(\n self,\n key: Any,\n default=None,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ) -> Any:\n \"\"\"\n Retrieve a value from the cache.\n\n Returns decoded value if key is found, the default if not.\n \"\"\"\n if client is None:\n client = self.get_client(write=False)\n\n key = self.make_key(key, version=version)\n\n try:\n value = client.get(key)\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n if value is None:\n return default\n\n return self.decode(value)\n\n def persist(\n self, key: Any, version: Optional[int] = None, client: Optional[Redis] = None\n ) -> bool:\n if client is None:\n client = self.get_client(write=True)\n\n key = self.make_key(key, version=version)\n\n return client.persist(key)\n\n def expire(\n self,\n key: Any,\n timeout,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ) -> bool:\n if client is None:\n client = self.get_client(write=True)\n\n key = self.make_key(key, version=version)\n\n return client.expire(key, timeout)\n\n def pexpire(self, key, timeout, version=None, client=None) -> bool:\n if client is None:\n client = self.get_client(write=True)\n\n key = self.make_key(key, version=version)\n\n # Temporary casting until https://github.com/redis/redis-py/issues/1664\n # is fixed.\n return bool(client.pexpire(key, timeout))\n\n def pexpire_at(\n self,\n key: Any,\n when: Union[datetime, int],\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ) -> bool:\n \"\"\"\n Set an expire flag on a ``key`` to ``when``, which can be represented\n as an integer indicating unix time or a Python datetime object.\n \"\"\"\n if client is None:\n client = self.get_client(write=True)\n\n key = self.make_key(key, version=version)\n\n return bool(client.pexpireat(key, when))\n\n def expire_at(\n self,\n key: Any,\n when: Union[datetime, int],\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ) -> bool:\n \"\"\"\n Set an expire flag on a ``key`` to ``when``, which can be represented\n as an integer indicating unix time or a Python datetime object.\n \"\"\"\n if client is None:\n client = self.get_client(write=True)\n\n key = self.make_key(key, version=version)\n\n return client.expireat(key, when)\n\n def lock(\n self,\n key,\n version: Optional[int] = None,\n timeout=None,\n sleep=0.1,\n blocking_timeout=None,\n client: Optional[Redis] = None,\n thread_local=True,\n ):\n if client is None:\n client = self.get_client(write=True)\n\n key = self.make_key(key, version=version)\n return client.lock(\n key,\n timeout=timeout,\n sleep=sleep,\n blocking_timeout=blocking_timeout,\n thread_local=thread_local,\n )\n\n def delete(\n self,\n key: Any,\n version: Optional[int] = None,\n prefix: Optional[str] = None,\n client: Optional[Redis] = None,\n ) -> int:\n \"\"\"\n Remove a key from the cache.\n \"\"\"\n if client is None:\n client = self.get_client(write=True)\n\n try:\n return client.delete(self.make_key(key, version=version, prefix=prefix))\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def delete_pattern(\n self,\n pattern: str,\n version: Optional[int] = None,\n prefix: Optional[str] = None,\n client: Optional[Redis] = None,\n itersize: Optional[int] = None,\n ) -> int:\n \"\"\"\n Remove all keys matching pattern.\n \"\"\"\n\n if client is None:\n client = self.get_client(write=True)\n\n pattern = self.make_pattern(pattern, version=version, prefix=prefix)\n\n try:\n count = 0\n pipeline = client.pipeline()\n\n for key in client.scan_iter(match=pattern, count=itersize):\n pipeline.delete(key)\n count += 1\n pipeline.execute()\n\n return count\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def delete_many(\n self, keys, version: Optional[int] = None, client: Optional[Redis] = None\n ):\n \"\"\"\n Remove multiple keys at once.\n \"\"\"\n\n if client is None:\n client = self.get_client(write=True)\n\n keys = [self.make_key(k, version=version) for k in keys]\n\n if not keys:\n return\n\n try:\n return client.delete(*keys)\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def clear(self, client: Optional[Redis] = None) -> None:\n \"\"\"\n Flush all cache keys.\n \"\"\"\n\n if client is None:\n client = self.get_client(write=True)\n\n try:\n client.flushdb()\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def decode(self, value: Union[bytes, int]) -> Any:\n \"\"\"\n Decode the given value.\n \"\"\"\n try:\n value = int(value)\n except (ValueError, TypeError):\n try:\n value = self._compressor.decompress(value)\n except CompressorError:\n # Handle little values, chosen to be not compressed\n pass\n value = self._serializer.loads(value)\n return value\n\n def encode(self, value: Any) -> Union[bytes, Any]:\n \"\"\"\n Encode the given value.\n \"\"\"\n\n if isinstance(value, bool) or not isinstance(value, int):\n value = self._serializer.dumps(value)\n value = self._compressor.compress(value)\n return value\n\n return value\n\n def get_many(\n self, keys, version: Optional[int] = None, client: Optional[Redis] = None\n ) -> OrderedDict:\n \"\"\"\n Retrieve many keys.\n \"\"\"\n\n if client is None:\n client = self.get_client(write=False)\n\n if not keys:\n return OrderedDict()\n\n recovered_data = OrderedDict()\n\n map_keys = OrderedDict((self.make_key(k, version=version), k) for k in keys)\n\n try:\n results = client.mget(*map_keys)\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n for key, value in zip(map_keys, results):\n if value is None:\n continue\n recovered_data[map_keys[key]] = self.decode(value)\n return recovered_data\n\n def set_many(\n self,\n data: Dict[Any, Any],\n timeout: Optional[float] = DEFAULT_TIMEOUT,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ) -> None:\n \"\"\"\n Set a bunch of values in the cache at once from a dict of key/value\n pairs. This is much more efficient than calling set() multiple times.\n\n If timeout is given, that timeout will be used for the key; otherwise\n the default cache timeout will be used.\n \"\"\"\n if client is None:\n client = self.get_client(write=True)\n\n try:\n pipeline = client.pipeline()\n for key, value in data.items():\n self.set(key, value, timeout, version=version, client=pipeline)\n pipeline.execute()\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def _incr(\n self,\n key: Any,\n delta: int = 1,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ignore_key_check: bool = False,\n ) -> int:\n if client is None:\n client = self.get_client(write=True)\n\n key = self.make_key(key, version=version)\n\n try:\n try:\n # if key expired after exists check, then we get\n # key with wrong value and ttl -1.\n # use lua script for atomicity\n if not ignore_key_check:\n lua = \"\"\"\n local exists = redis.call('EXISTS', KEYS[1])\n if (exists == 1) then\n return redis.call('INCRBY', KEYS[1], ARGV[1])\n else return false end\n \"\"\"\n else:\n lua = \"\"\"\n return redis.call('INCRBY', KEYS[1], ARGV[1])\n \"\"\"\n value = client.eval(lua, 1, key, delta)\n if value is None:\n raise ValueError(\"Key '%s' not found\" % key)\n except ResponseError:\n # if cached value or total value is greater than 64 bit signed\n # integer.\n # elif int is encoded. so redis sees the data as string.\n # In this situations redis will throw ResponseError\n\n # try to keep TTL of key\n timeout = self.ttl(key, version=version, client=client)\n\n # returns -2 if the key does not exist\n # means, that key have expired\n if timeout == -2:\n raise ValueError(\"Key '%s' not found\" % key)\n value = self.get(key, version=version, client=client) + delta\n self.set(key, value, version=version, timeout=timeout, client=client)\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n return value\n\n def incr(\n self,\n key: Any,\n delta: int = 1,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ignore_key_check: bool = False,\n ) -> int:\n \"\"\"\n Add delta to value in the cache. If the key does not exist, raise a\n ValueError exception. if ignore_key_check=True then the key will be\n created and set to the delta value by default.\n \"\"\"\n return self._incr(\n key=key,\n delta=delta,\n version=version,\n client=client,\n ignore_key_check=ignore_key_check,\n )\n\n def decr(\n self,\n key: Any,\n delta: int = 1,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ) -> int:\n \"\"\"\n Decreace delta to value in the cache. If the key does not exist, raise a\n ValueError exception.\n \"\"\"\n return self._incr(key=key, delta=-delta, version=version, client=client)\n\n def ttl(\n self, key: Any, version: Optional[int] = None, client: Optional[Redis] = None\n ) -> Optional[int]:\n \"\"\"\n Executes TTL redis command and return the \"time-to-live\" of specified key.\n If key is a non volatile key, it returns None.\n \"\"\"\n if client is None:\n client = self.get_client(write=False)\n\n key = self.make_key(key, version=version)\n if not client.exists(key):\n return 0\n\n t = client.ttl(key)\n\n if t >= 0:\n return t\n elif t == -1:\n return None\n elif t == -2:\n return 0\n else:\n # Should never reach here\n return None\n\n def pttl(self, key, version=None, client=None):\n \"\"\"\n Executes PTTL redis command and return the \"time-to-live\" of specified key.\n If key is a non volatile key, it returns None.\n \"\"\"\n if client is None:\n client = self.get_client(write=False)\n\n key = self.make_key(key, version=version)\n if not client.exists(key):\n return 0\n\n t = client.pttl(key)\n\n if t >= 0:\n return t\n elif t == -1:\n return None\n elif t == -2:\n return 0\n else:\n # Should never reach here\n return None\n\n def has_key(\n self, key: Any, version: Optional[int] = None, client: Optional[Redis] = None\n ) -> bool:\n \"\"\"\n Test if key exists.\n \"\"\"\n\n if client is None:\n client = self.get_client(write=False)\n\n key = self.make_key(key, version=version)\n try:\n return client.exists(key) == 1\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def iter_keys(\n self,\n search: str,\n itersize: Optional[int] = None,\n client: Optional[Redis] = None,\n version: Optional[int] = None,\n ) -> Iterator[str]:\n \"\"\"\n Same as keys, but uses redis >= 2.8 cursors\n for make memory efficient keys iteration.\n \"\"\"\n\n if client is None:\n client = self.get_client(write=False)\n\n pattern = self.make_pattern(search, version=version)\n for item in client.scan_iter(match=pattern, count=itersize):\n yield self.reverse_key(item.decode())\n\n def keys(\n self, search: str, version: Optional[int] = None, client: Optional[Redis] = None\n ) -> List[Any]:\n \"\"\"\n Execute KEYS command and return matched results.\n Warning: this can return huge number of results, in\n this case, it strongly recommended use iter_keys\n for it.\n \"\"\"\n\n if client is None:\n client = self.get_client(write=False)\n\n pattern = self.make_pattern(search, version=version)\n try:\n return [self.reverse_key(k.decode()) for k in client.keys(pattern)]\n except _main_exceptions as e:\n raise ConnectionInterrupted(connection=client) from e\n\n def make_key(\n self, key: Any, version: Optional[Any] = None, prefix: Optional[str] = None\n ) -> CacheKey:\n if isinstance(key, CacheKey):\n return key\n\n if prefix is None:\n prefix = self._backend.key_prefix\n\n if version is None:\n version = self._backend.version\n\n return CacheKey(self._backend.key_func(key, prefix, version))\n\n def make_pattern(\n self, pattern: str, version: Optional[int] = None, prefix: Optional[str] = None\n ) -> CacheKey:\n if isinstance(pattern, CacheKey):\n return pattern\n\n if prefix is None:\n prefix = self._backend.key_prefix\n prefix = glob_escape(prefix)\n\n if version is None:\n version = self._backend.version\n version_str = glob_escape(str(version))\n\n return CacheKey(self._backend.key_func(pattern, prefix, version_str))\n\n def close(self, **kwargs):\n close_flag = self._options.get(\n \"CLOSE_CONNECTION\",\n getattr(settings, \"DJANGO_REDIS_CLOSE_CONNECTION\", False),\n )\n if close_flag:\n self.do_close_clients()\n\n def do_close_clients(self):\n \"\"\"default implementation: Override in custom client\"\"\"\n num_clients = len(self._clients)\n for idx in range(num_clients):\n self.disconnect(index=idx)\n self._clients = [None] * num_clients\n\n def touch(\n self,\n key: Any,\n timeout: Optional[float] = DEFAULT_TIMEOUT,\n version: Optional[int] = None,\n client: Optional[Redis] = None,\n ) -> bool:\n \"\"\"\n Sets a new expiration for a key.\n \"\"\"\n\n if timeout is DEFAULT_TIMEOUT:\n timeout = self._backend.default_timeout\n\n if client is None:\n client = self.get_client(write=True)\n\n key = self.make_key(key, version=version)\n if timeout is None:\n return bool(client.persist(key))\n else:\n # Convert to milliseconds\n timeout = int(timeout * 1000)\n return bool(client.pexpire(key, timeout))\n" }, { "alpha_fraction": 0.6480331420898438, "alphanum_fraction": 0.6521739363670349, "avg_line_length": 24.421052932739258, "blob_id": "f764f8b21fd36a7ddd007bd678a6930f7bc1f504", "content_id": "ddf49d0dee1f531ca4dd3485114091e434ffa6e5", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "permissive", "max_line_length": 48, "num_lines": 19, "path": "/django_redis/compressors/zstd.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import pyzstd\n\nfrom ..exceptions import CompressorError\nfrom .base import BaseCompressor\n\n\nclass ZStdCompressor(BaseCompressor):\n min_length = 15\n\n def compress(self, value: bytes) -> bytes:\n if len(value) > self.min_length:\n return pyzstd.compress(value)\n return value\n\n def decompress(self, value: bytes) -> bytes:\n try:\n return pyzstd.decompress(value)\n except pyzstd.ZstdError as e:\n raise CompressorError(e)\n" }, { "alpha_fraction": 0.687635600566864, "alphanum_fraction": 0.688720166683197, "avg_line_length": 34.46154022216797, "blob_id": "9a2342b8fd19bb46d14e7fdac7cb0806ce9c7995", "content_id": "b3c77ec05a1338d975f7f28f5aa209f4939af481", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 922, "license_type": "permissive", "max_line_length": 81, "num_lines": 26, "path": "/tests/test_serializers.py", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "import pickle\n\nimport pytest\nfrom django.core.exceptions import ImproperlyConfigured\n\nfrom django_redis.serializers.pickle import PickleSerializer\n\n\nclass TestPickleSerializer:\n def test_invalid_pickle_version_provided(self):\n with pytest.raises(\n ImproperlyConfigured, match=\"PICKLE_VERSION value must be an integer\"\n ):\n PickleSerializer({\"PICKLE_VERSION\": \"not-an-integer\"})\n\n def test_setup_pickle_version_not_explicitly_specified(self):\n serializer = PickleSerializer({})\n assert serializer._pickle_version == pickle.DEFAULT_PROTOCOL\n\n def test_setup_pickle_version_too_high(self):\n with pytest.raises(\n ImproperlyConfigured,\n match=f\"PICKLE_VERSION can't be higher than pickle.HIGHEST_PROTOCOL:\"\n f\" {pickle.HIGHEST_PROTOCOL}\",\n ):\n PickleSerializer({\"PICKLE_VERSION\": pickle.HIGHEST_PROTOCOL + 1})\n" }, { "alpha_fraction": 0.5983740091323853, "alphanum_fraction": 0.6390243768692017, "avg_line_length": 22.20754623413086, "blob_id": "bb3799717fdafa1233498d633daa2296d608e611", "content_id": "00bf2b0384af5ccb16ae70d1151be4aa07d365b2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1230, "license_type": "permissive", "max_line_length": 71, "num_lines": 53, "path": "/tests/start_redis.sh", "repo_name": "jazzband/django-redis", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# This command will start redis for both the CI and for local testing\n\nif ! command -v docker &> /dev/null; then\n echo >&2 \"Docker is required but was not found.\"\n exit 1\nfi\n\nARGS=()\nPORT=6379\nSENTINEL=0\nwhile (($# > 0)); do\n case \"$1\" in\n --sentinel)\n # setup a redis sentinel\n CONF=$(mktemp -d)\n ARGS=(\"${ARGS[@]}\" \"$CONF/redis.conf\" --sentinel)\n PORT=26379\n SENTINEL=1\n\n cat > \"$CONF/redis.conf\" <<EOF\nsentinel monitor default_service 127.0.0.1 6379 1\nsentinel down-after-milliseconds default_service 3200\nsentinel failover-timeout default_service 10000\nsentinel parallel-syncs default_service 1\nEOF\n\n chmod 777 \"$CONF\"\n chmod 666 \"$CONF/redis.conf\"\n\n shift\n ;;\n esac\ndone\n\n# open a unix socket for socket tests\nif [[ $SENTINEL == 0 ]]; then\n # make sure the file doesn't already exist\n rm -f /tmp/redis.sock\n ARGS=(\"${ARGS[@]}\" --unixsocket /tmp/redis.sock --unixsocketperm 777)\nfi\n\n# start redis\ndocker run \\\n --health-cmd \"redis-cli -p $PORT:$PORT ping\" \\\n --health-interval 10s \\\n --health-retries 5 \\\n --health-timeout 5s \\\n --network host \\\n --user $(id -u):$(id -g) \\\n --volume /tmp:/tmp \\\n --detach redis:latest redis-server \"${ARGS[@]}\"\n" } ]
41
Sunil1821/FastAIPractise
https://github.com/Sunil1821/FastAIPractise
2f310defe62d0d7035586ab3bdc1c8dacd2a1fe4
0528cecb086ff5d0ff36dd6a30a7f8d39afd8b97
812cb375bbdc4b6cc676579c587e2fe3354dd2dd
refs/heads/master
2022-12-16T05:07:27.638107
2020-09-26T06:46:05
2020-09-26T06:46:05
298,728,918
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6134320497512817, "alphanum_fraction": 0.6240084767341614, "avg_line_length": 35.36538314819336, "blob_id": "ad89ca65f0f96c904cd870beb9eec1838968b326", "content_id": "ddb6c0ef3edc8b47167045dfda0f60ce8b0b3af3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1891, "license_type": "permissive", "max_line_length": 77, "num_lines": 52, "path": "/lesson1FlaskApp/downloadFromGoogleDrive.py", "repo_name": "Sunil1821/FastAIPractise", "src_encoding": "UTF-8", "text": "#taken from this StackOverflow answer: https://stackoverflow.com/a/39225039\n\nimport requests\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nGOOGLE_DOC_URL = \"https://docs.google.com/uc?export=download\"\n\nclass GoogleDriveDownloader: \n\n def __init__(self, fileId, destination):\n self._fileid = fileId\n self._destination = destination\n self._session = requests.Session()\n self.logger = logging.getLogger(\"GoogleDriveDownloader\") \n\n def download_file_from_google_drive(self):\n id = self._fileid\n destination = self._destination\n response = self._session.get(GOOGLE_DOC_URL, params={\n 'id': id}, stream=True)\n token = self.get_confirm_token(response)\n\n if token:\n params = { 'id' : id, 'confirm' : token }\n response = self._session.get(\n GOOGLE_DOC_URL, params=params, stream=True)\n\n self.logger.info(f\"downloading file : {self._destination}\")\n self.save_response_content(response)\n self.logger.info(f\"download complete for file : {self._destination}\")\n return destination\n \n def get_confirm_token(self, response):\n for key, value in response.cookies.items():\n if key.startswith('download_warning'):\n return value\n return None\n\n def save_response_content(self, response):\n CHUNK_SIZE = 32768\n destination = self._destination\n with open(destination, \"wb\") as f:\n for chunk in response.iter_content(CHUNK_SIZE):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n\nif __name__ == \"__main__\":\n destination = 'export.pkl'\n googleDriveFileId = '1Z3SvYdGNR_k7yrtGWgU73r2W_tMVL3XE'\n gd = GoogleDriveDownloader(googleDriveFileId, destination)\n gd.download_file_from_google_drive()\n" }, { "alpha_fraction": 0.6579822897911072, "alphanum_fraction": 0.6679601073265076, "avg_line_length": 28.57377052307129, "blob_id": "a42a077bfea016862141b1f1c9ac7ff9082ccce4", "content_id": "88db7b735b5b8511971575832a9685f26b1c40e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1804, "license_type": "permissive", "max_line_length": 101, "num_lines": 61, "path": "/lesson1FlaskApp/app.py", "repo_name": "Sunil1821/FastAIPractise", "src_encoding": "UTF-8", "text": "from flask import Flask\n\nimport fastbook\nfastbook.setup_book()\n\n#hide\nfrom fastbook import *\nfrom fastai.vision.all import *\nfrom utils import *\nfrom downloadFromGoogleDrive import GoogleDriveDownloader\n\nfrom flask import request, redirect, render_template\n\nimport os, sys\napp = Flask(__name__)\n\nGOOGLE_DRIVE_MODEL_FILE_ID = '1Z3SvYdGNR_k7yrtGWgU73r2W_tMVL3XE'\n# to get this click on share with people and copy link \n# Model location : https://drive.google.com/file/d/1Z3SvYdGNR_k7yrtGWgU73r2W_tMVL3XE/view?usp=sharing\n\n\napp.config[\"IMAGE_UPLOADS\"] = \"img\"\napp.config[\"ALLOWED_IMAGE_EXTENSIONS\"] = [\"JPEG\", \"JPG\", \"PNG\", \"GIF\"]\nmodel = None\n\[email protected](\"/\")\ndef upload_image():\n # return \"hello world\"\n return render_template(\"index.html\")\n\n\[email protected](\"/classify\", methods=[\"POST\"])\ndef classify():\n if request.files:\n image = request.files[\"image\"]\n filename = image.filename\n \n img_path = os.path.join(app.config[\"IMAGE_UPLOADS\"], filename)\n image.save(img_path)\n print(f\"Image saved @ : {img_path}\")\n res = model.predict(img_path)\n Prediction_Result = {}\n Prediction_Result[\"label\"] = res[0]\n probabilities = [\"%.4f\" % float(e) for e in list(res[2])]\n labels = model.dls.vocab\n Prediction_Result[\"result\"] = list(zip(labels, probabilities))\n return Prediction_Result\n\nif __name__ == \"__main__\":\n if not os.path.exists(app.config[\"IMAGE_UPLOADS\"]):\n sys.path.mkdir(app.config[\"IMAGE_UPLOADS\"])\n\n path = Path()\n modelLocation = path/\"lesson1.pkl\"\n googleDrive = GoogleDriveDownloader(GOOGLE_DRIVE_MODEL_FILE_ID, str(modelLocation))\n \n if not modelLocation.exists():\n googleDrive.download_file_from_google_drive()\n \n model = load_learner(modelLocation)\n app.run()\n" }, { "alpha_fraction": 0.5869565010070801, "alphanum_fraction": 0.739130437374115, "avg_line_length": 10.75, "blob_id": "57af5586ec7c9fddd52f9c57a5e246612c81f6ae", "content_id": "8a4679618bc29fdf2b22a02878538aeb023a787c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 46, "license_type": "permissive", "max_line_length": 16, "num_lines": 4, "path": "/lesson1FlaskApp/requirements.txt", "repo_name": "Sunil1821/FastAIPractise", "src_encoding": "UTF-8", "text": "Flask\nfastcore==1.0.9 \nfastai==1.0.42\nfastbook" }, { "alpha_fraction": 0.752525269985199, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 27.14285659790039, "blob_id": "29c53c62f36e2ed4e3dcbbb0a8b35dae2c8e0c2d", "content_id": "9dd5e43c0ca5b200effe54605de3fc2848e08fb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 198, "license_type": "permissive", "max_line_length": 93, "num_lines": 7, "path": "/mynotes/chapter2.md", "repo_name": "Sunil1821/FastAIPractise", "src_encoding": "UTF-8", "text": "# Chapter 2 : Computer Vision\n\n![image info](important_definitions.png)\n\n![image info](Datablock.png)\n\n[Colab](https://colab.research.google.com/drive/1APtZTXPCoHmlvN6AInUixeqbKIV7iQSv?authuser=1)\n\n" }, { "alpha_fraction": 0.8160919547080994, "alphanum_fraction": 0.8160919547080994, "avg_line_length": 42.5, "blob_id": "dcccc91ff6aae81cd8e836c089058eb58dbe7ede", "content_id": "65a23ffcddea682608d867b00d0886d6657d9b8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 87, "license_type": "permissive", "max_line_length": 69, "num_lines": 2, "path": "/README.md", "repo_name": "Sunil1821/FastAIPractise", "src_encoding": "UTF-8", "text": "# FastAIPractise\nRepository for self practice of the learning from the FAST AI course.\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.7098214030265808, "avg_line_length": 20.70967674255371, "blob_id": "1f8d5e4f6b9456035187035c7b0e204bc5e49305", "content_id": "6f0c62a1a25862c8295b768dec9c7f0509e91f91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 672, "license_type": "permissive", "max_line_length": 60, "num_lines": 31, "path": "/lesson1FlaskApp/install.sh", "repo_name": "Sunil1821/FastAIPractise", "src_encoding": "UTF-8", "text": "#! /usr/bin/bash\n\n### Automation script to setup a FAST AI supported flask app\ngit init\npython3 -m venv env\nsource env/bin/activate\necho \"setting up files\"\ntouch app.py utils.py .gitignore README.md requirements.txt\necho \"installing Flask\"\npython3 -m pip3 install Flask\necho \"installing fastcore\"\npip3 install -Uqq fastcore==1.0.9 \necho \"installing fastai\"\npip3 install -Uqq fastai==1.0.42 \necho \"installing fastbook\"\npip3 install -Uqq fastbook\n\necho '''from flask import Flask\napp = Flask(__name__)\n\n\[email protected](\"/\")\ndef hello():\n return \"Hello World!\"\n\nif __name__ == \"__main__\":\n app.run()''' > \"app.py\"\n\n# python3 -m pip freeze > requirements.txt\n\npython3 app.py" } ]
6
quantheory/E3SMTimestepStudy
https://github.com/quantheory/E3SMTimestepStudy
ad9fbba3b6632b9d96116f02ec00858a127eb214
3f0111cfe9b082e62c98d64a42a8659d891e5e69
7d285cf874bca6cf88b16783cad0a3d88a92a0b8
refs/heads/master
2023-04-12T23:29:51.734284
2022-10-22T22:30:37
2022-10-22T22:30:37
256,311,777
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5222844481468201, "alphanum_fraction": 0.5471444725990295, "avg_line_length": 33.08396911621094, "blob_id": "9ff20185b77d83c8f116eb7a35bd4c33c8d94fa4", "content_id": "d8bbc517a04a25e8b5f6700548d7e66a5ec6a1e1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4465, "license_type": "permissive", "max_line_length": 82, "num_lines": 131, "path": "/write_precip_histogram.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom os.path import join\n\nimport numpy as np\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import day_str, time_str\n\nCASE_NAME = \"timestep_ctrl\"\nCASE_DIR = \"/p/lscratchh/santos36/ACME/{}/run\".format(CASE_NAME)\nOUTPUT_DIR = \"/p/lustre2/santos36/timestep_precip/\"\nNUM_BINS = 101\nBINS_BOUNDS = (-2., 3.) # Bins between 10^-2 and 10^3 mm/day of precip.\n\nbins = np.logspace(BINS_BOUNDS[0], BINS_BOUNDS[1], NUM_BINS-1)\n\nSTART_YEAR = 3\nSTART_MONTH = 8\nEND_YEAR = 3\nEND_MONTH = 12\n\nmonth_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nnmonths = (END_YEAR - START_YEAR) * 12 - (START_MONTH - 1) + END_MONTH\nimonths = list(range(nmonths))\ncurr_month = START_MONTH\ncurr_year = START_YEAR\nmonths = []\nyears = []\nfor i in range(nmonths):\n months.append(curr_month)\n years.append(curr_year)\n curr_month += 1\n if curr_month > 12:\n curr_month = 1\n curr_year += 1\n\nfilename_template = \"{}.cam.h0.{}-{}-{}-{}.nc\"\n\nfirst_file_name = filename_template.format(CASE_NAME, \"00\"+day_str(START_YEAR),\n day_str(START_MONTH), day_str(1),\n time_str(0))\nfirst_file = nc4.Dataset(join(CASE_DIR, first_file_name), 'r')\nncol = len(first_file.dimensions['ncol'])\nlat = first_file['lat'][:]\nlon = first_file['lon'][:]\narea = first_file['area'][:]\nfirst_file.close()\n\nprec_vars = (\"PRECC\", \"PRECL\", \"PRECT\")# \"PRECSC\", \"PRECSL\")\n\nfor i in range(nmonths):\n year = years[i]\n year_string = \"00\" + day_str(year)\n month = months[i]\n month_string = day_str(month)\n\n print(\"On year {}, month {}.\".format(year, month))\n\n ndays = month_days[month-1]\n\n out_file_template = \"{}.freq.{}-{}.nc\"\n\n out_file_name = out_file_template.format(CASE_NAME, year_string, month_string)\n\n out_file = nc4.Dataset(join(OUTPUT_DIR, out_file_name), 'w')\n out_file.createDimension(\"ncol\", ncol)\n out_file.createDimension(\"nbins\", NUM_BINS)\n\n out_file.createVariable(\"lat\", 'f8', (\"ncol\",))\n out_file.variables[\"lat\"][:] = lat\n out_file.createVariable(\"lon\", 'f8', (\"ncol\",))\n out_file.variables[\"lon\"][:] = lon\n out_file.createVariable(\"area\", 'f8', (\"ncol\",))\n out_file.variables[\"area\"][:] = area\n\n out_file.createVariable(\"bin_lower_bounds\", 'f8', (\"nbins\",))\n out_file.variables[\"bin_lower_bounds\"][0] = 0.\n out_file.variables[\"bin_lower_bounds\"][1:] = bins[:]\n\n var_dict = {}\n for varname in prec_vars:\n num_name = \"{}_num\".format(varname)\n out_file.createVariable(num_name, 'u4', (\"ncol\", \"nbins\"))\n out_file[num_name].units = \"1\"\n amount_name = \"{}_amount\".format(varname)\n out_file.createVariable(amount_name, 'f8', (\"ncol\", \"nbins\"))\n out_file[amount_name].units = \"mm/day\"\n\n var_dict[num_name] = np.zeros((ncol, NUM_BINS), dtype = np.uint32)\n var_dict[amount_name] = np.zeros((ncol, NUM_BINS))\n\n out_file.sample_num = np.uint32(ndays * 24)\n\n for day in range(1, ndays + 1):\n print(\"On day {}.\".format(day))\n day_string = day_str(day)\n for hour in range(0, 24):\n time_string = time_str(hour * 3600)\n in_file_name = filename_template.format(CASE_NAME, year_string,\n month_string, day_string,\n time_string)\n in_file = nc4.Dataset(join(CASE_DIR, in_file_name), 'r')\n\n for varname in prec_vars:\n if varname == \"PRECT\":\n var = in_file[\"PRECC\"][0,:] + in_file[\"PRECL\"][0,:]\n else:\n var = in_file[varname][0,:]\n var = var * 1000. * 86400.\n num_name = \"{}_num\".format(varname)\n amount_name = \"{}_amount\".format(varname)\n for i in range(ncol):\n bin_idx = 0\n for n in range(NUM_BINS-1):\n if bins[n] > var[i]:\n break\n bin_idx += 1\n var_dict[num_name][i, bin_idx] += 1\n var_dict[amount_name][i, bin_idx] += var[i]\n\n in_file.close()\n\n for varname in prec_vars:\n num_name = \"{}_num\".format(varname)\n amount_name = \"{}_amount\".format(varname)\n out_file.variables[num_name][:] = var_dict[num_name]\n out_file.variables[amount_name][:] = var_dict[amount_name]\n\n out_file.close()\n" }, { "alpha_fraction": 0.4931506812572479, "alphanum_fraction": 0.698630154132843, "avg_line_length": 35.5, "blob_id": "2f1b9366e73f086a3026286657c746ff687b32f3", "content_id": "5a978f480ee4532327144a72d9165cbdc4b54dd5", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 584, "license_type": "permissive", "max_line_length": 97, "num_lines": 16, "path": "/regrid_daily_avgs.sh", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nREMAP_FILE=/usr/gdata/climdat/maps/map_ne30np4_to_fv128x256_aave.20160301.nc\nIN_DIR=/p/lscratchh/santos36/timestep_daily_avgs\nOUT_DIR=/p/lscratchh/santos36/timestep_daily_avgs_lat_lon\nCASE_NAMES=\"timestep_presaer_cld_10s_lower_tau2\"\n#DAYS=\"01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\"\nDAYS=\"01 02 03 04 05 06 07 08 09 10 11 12 13 14 15\"\n\nfor case_name in $CASE_NAMES; do\n date\n echo \"On case $case_name\"\n for day in $DAYS; do\n ncremap -m $REMAP_FILE -O $OUT_DIR $IN_DIR/$case_name.0001-01-$day.nc\n done\ndone\n" }, { "alpha_fraction": 0.5572758316993713, "alphanum_fraction": 0.5860289335250854, "avg_line_length": 38.17328643798828, "blob_id": "6f51f44ebd8ddd2dfcb714ad5334538c373cdc49", "content_id": "53c9bb15c1756454cce0870d15759a340709a37b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10851, "license_type": "permissive", "max_line_length": 134, "num_lines": 277, "path": "/plot_compare_3D_zonal_avg_daily.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import E3SMCaseOutput, day_str\n\ncmap = plt.get_cmap('coolwarm')\n\ndef forward(a):\n a = np.deg2rad(a)\n return np.sin(a)\n\ndef inverse(a):\n a = np.arcsin(a)\n return np.rad2deg(a)\n\nSTART_DAY = 3\nEND_DAY = 15\n\nDAILY_FILE_LOC=\"/p/lscratchh/santos36/timestep_daily_avgs_lat_lon\"\n\nUSE_PRESAER = True\n\ndays = list(range(START_DAY, END_DAY+1))\nndays = len(days)\n\nsuffix = '_d{}-{}'.format(day_str(START_DAY), day_str(END_DAY))\n\nsuffix += '_zonal'\n\nlog_file = open(\"plot_zonal_log{}.txt\".format(suffix), 'w')\n\nif USE_PRESAER:\n REF_CASE = E3SMCaseOutput(\"timestep_presaer_ctrl\", \"CTRLPA\", DAILY_FILE_LOC, START_DAY, END_DAY)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_presaer_all_10s\", \"ALL10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s\", \"CLUBBMICRO10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_ZM_10s\", \"ZM10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s_ZM_10s\", \"CLUBBMICRO10ZM10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_cld_10s\", \"CLD10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_ZM_10s_lower_tau\", \"ZM10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s_ZM_10s_lower_tau\", \"CLUBBMICRO10ZM10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_cld_10s_lower_tau\", \"CLD10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_all_10s_lower_tau\", \"ALL10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n ]\nelse:\n REF_CASE = E3SMCaseOutput(\"timestep_ctrl\", \"CTRL\", DAILY_FILE_LOC, START_DAY, END_DAY)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_all_10s\", \"ALL10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_dyn_10s\", \"DYN10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_MG2_10s\", \"MICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_10s\", \"CLUBB10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_10s_MG2_10s\", \"CLUBB10MICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_Strang\", \"CLUBBMICROSTR\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_Strang_60s\", \"CLUBBMICROSTR60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_10s\", \"CLUBBMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_60s\", \"CLUBBMICRO60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_ZM_10s\", \"ZM10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_ZM_300s\", \"ZM300\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_rad_10s\", \"ALLRAD10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_300s\", \"ALL300\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_precip_grad\", \"PFMG\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_precip_grad_CLUBB_MG2_10s\", \"PFMGCLUBBMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n ]\n\nrfile0 = nc4.Dataset(REF_CASE.get_daily_file_name(START_DAY), 'r')\nlat = rfile0['lat'][:]\nlon = rfile0['lon'][:]\nilev = rfile0['ilev'][:]\nnlat = len(lat)\nnlon = len(lon)\nnlev = len(ilev) - 1\nrfile0.close()\n\ndef get_overall_averages(ref_case, test_cases, days, varnames, scales):\n case_num = len(test_cases)\n day_num = len(days)\n ref_means = dict()\n for name in varnames:\n ref_means[name] = np.zeros((nlev, nlat, nlon))\n test_means = []\n diff_means = []\n for case in test_cases:\n next_test_means = dict()\n next_diff_means = dict()\n for name in varnames:\n next_test_means[name] = np.zeros((nlev, nlat, nlon))\n next_diff_means[name] = np.zeros((nlev, nlat, nlon))\n test_means.append(next_test_means)\n diff_means.append(next_diff_means)\n\n varnames_read = [name for name in varnames if name != \"PRECT\" and name != \"TAU\"]\n if \"PRECT\" in varnames:\n if \"PRECL\" not in varnames:\n varnames_read.append(\"PRECL\")\n if \"PRECC\" not in varnames:\n varnames_read.append(\"PRECC\")\n if \"TAU\" in varnames:\n if \"TAUX\" not in varnames:\n varnames_read.append(\"TAUX\")\n if \"TAUY\" not in varnames:\n varnames_read.append(\"TAUY\")\n\n for day in days:\n ref_daily, test_daily, diff_daily = ref_case.compare_daily_averages(test_cases, day, varnames_read)\n if \"PRECT\" in varnames:\n ref_daily[\"PRECT\"] = ref_daily[\"PRECL\"] + ref_daily[\"PRECC\"]\n for icase in range(case_num):\n test_daily[icase][\"PRECT\"] = test_daily[icase][\"PRECL\"] + test_daily[icase][\"PRECC\"]\n diff_daily[icase][\"PRECT\"] = diff_daily[icase][\"PRECL\"] + diff_daily[icase][\"PRECC\"]\n if \"TAU\" in varnames:\n ref_daily[\"TAU\"] = np.sqrt(ref_daily[\"TAUX\"]**2 + ref_daily[\"TAUY\"]**2)\n for icase in range(case_num):\n test_daily[icase][\"TAU\"] = np.sqrt(test_daily[icase][\"TAUX\"]**2 + test_daily[icase][\"TAUY\"]**2)\n diff_daily[icase][\"TAU\"] = test_daily[icase][\"TAU\"] - ref_daily[\"TAU\"]\n for name in varnames:\n for jlev in range(nlev):\n ref_means[name][jlev,:,:] += ref_daily[name][jlev,:,:]\n for icase in range(case_num):\n test_means[icase][name][jlev,:,:] += test_daily[icase][name][jlev,:,:]\n diff_means[icase][name][jlev,:,:] += diff_daily[icase][name][jlev,:,:]\n\n for name in varnames:\n ref_means[name] *= scales[name]/day_num\n for icase in range(case_num):\n test_means[icase][name] *= scales[name]/day_num\n diff_means[icase][name] *= scales[name]/day_num\n\n return (ref_means, test_means, diff_means)\n\n\nplot_names = {\n 'AQRAIN': 'rain mixing ratio',\n 'AQSNOW': 'snow mixing ratio',\n 'AREI': 'ice effective radius',\n 'AREL': 'droplet effective radius',\n 'CLDICE': 'cloud ice mixing ratio',\n 'CLDLIQ': 'cloud liquid mixing ratio',\n 'CLOUD': \"cloud fraction\",\n 'Q': \"specific humidity\",\n 'QRL': 'longwave heating rate',\n 'QRS': 'shortwave heating rate',\n 'RELHUM': \"relative humidity\",\n 'T': \"temperature\",\n 'U': \"zonal wind\",\n 'V': \"meridional wind\",\n}\n\nunits = {\n 'AQRAIN': r'$mg/kg$',\n 'AQSNOW': r'$mg/kg$',\n 'AREI': r'micron',\n 'AREL': r'micron',\n 'CLDICE': r'$g/kg$',\n 'CLDLIQ': r'$g/kg$',\n 'CLOUD': r'fraction',\n 'Q': r'$g/kg$',\n 'QRL': r'$K/day$',\n 'QRS': r'$K/day$',\n 'RELHUM': r'%',\n 'T': r'$K$',\n 'U': r'$m/s$',\n 'V': r'$m/s$',\n}\nvarnames = list(units.keys())\nscales = dict()\nfor name in varnames:\n scales[name] = 1.\nscales['AQRAIN'] = 1.e6\nscales['AQSNOW'] = 1.e6\nscales['CLDICE'] = 1000.\nscales['CLDLIQ'] = 1000.\nscales['Q'] = 1000.\nscales['QRL'] = 86400.\nscales['QRS'] = 86400.\n\ndiff_lims = {\n 'AQSNOW': 4.,\n 'AREI': 5.,\n 'AREL': 2.,\n 'CLDLIQ': 0.01,\n 'CLOUD': 0.1,\n 'QRL': 2.,\n 'QRS': 0.3,\n 'RELHUM': 15.,\n 'T': 2.,\n}\n\nPLOT_TOP = 100.\nitop = 0\nfor level in ilev:\n if level > PLOT_TOP:\n break\n itop += 1\n\ndef zonal_average(x):\n return np.mean(x[itop:,:,:], axis=2)\n\nref_means, test_means, diff_means = get_overall_averages(REF_CASE, TEST_CASES, days, varnames, scales)\n\nplot_ilev = ilev[itop:]\n\nfor name in varnames:\n plot_name = name\n if name in plot_names:\n plot_name = plot_names[name]\n\n ref_plot_var = zonal_average(ref_means[name])\n clim_val = [ref_plot_var.min(), ref_plot_var.max()]\n clim_diff = 0.\n for icase in range(len(TEST_CASES)):\n test_plot_var = zonal_average(test_means[icase][name])\n diff_plot_var = zonal_average(diff_means[icase][name])\n clim_val[0] = min(clim_val[0], test_plot_var.min())\n clim_val[1] = max(clim_val[1], test_plot_var.max())\n clim_diff = max(clim_diff, - diff_plot_var.min())\n clim_diff = max(clim_diff, diff_plot_var.max())\n\n if name in diff_lims:\n clim_diff = diff_lims[name]\n\n plt.pcolor(lat[1:], plot_ilev, ref_plot_var[:,1:-1])\n ax = plt.gca()\n ylim = ax.get_ylim()\n ax.set_ylim([ylim[1], ylim[0]])\n plt.ylabel(\"Pressure (mb)\")\n ax.set_xscale('function', functions=(forward, inverse))\n ax.set_xticks([60., 30., 15., 0., -15., -30., -60.])\n ax.set_xticklabels(['60N', '30N', '15N', '0', '15S', '30S', '60S'])\n plt.axis('tight')\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.title(\"{} for case {}\\n({}, days {}-{})\".format(plot_name, REF_CASE.short_name, units[name],\n START_DAY, END_DAY))\n plt.savefig('{}_{}{}.png'.format(name, REF_CASE.short_name, suffix))\n plt.close()\n\n for icase in range(len(TEST_CASES)):\n test_plot_var = zonal_average(test_means[icase][name])\n diff_plot_var = zonal_average(diff_means[icase][name])\n case_name = TEST_CASES[icase].short_name\n\n plt.pcolor(lat[1:], plot_ilev, test_plot_var[:,1:-1])\n ax = plt.gca()\n ylim = ax.get_ylim()\n ax.set_ylim([ylim[1], ylim[0]])\n plt.ylabel(\"Pressure (mb)\")\n ax.set_xscale('function', functions=(forward, inverse))\n ax.set_xticks([60., 30., 15., 0., -15., -30., -60.])\n ax.set_xticklabels(['60N', '30N', '15N', '0', '15S', '30S', '60S'])\n plt.axis('tight')\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.title(\"{} for case {}\\n({}, days {}-{})\".format(plot_name, case_name, units[name],\n START_DAY, END_DAY))\n plt.savefig('{}_{}{}.png'.format(name, case_name, suffix))\n plt.close()\n\n plt.pcolor(lat[1:], plot_ilev, diff_plot_var[:,1:-1], cmap=cmap)\n ax = plt.gca()\n ylim = ax.get_ylim()\n ax.set_ylim([ylim[1], ylim[0]])\n plt.ylabel(\"Pressure (mb)\")\n ax.set_xscale('function', functions=(forward, inverse))\n ax.set_xticks([60., 30., 15., 0., -15., -30., -60.])\n ax.set_xticklabels(['60N', '30N', '15N', '0', '15S', '30S', '60S'])\n plt.axis('tight')\n plt.colorbar()\n plt.clim(-clim_diff, clim_diff)\n plt.title(\"Mean difference in {}\\nfor case {} ({}, days {}-{})\".format(plot_name, case_name, units[name],\n START_DAY, END_DAY))\n plt.savefig('{}_diff_{}{}.png'.format(name, case_name, suffix))\n plt.close()\n" }, { "alpha_fraction": 0.5466067790985107, "alphanum_fraction": 0.5711000561714172, "avg_line_length": 40.27814483642578, "blob_id": "28af2ae89245008d9a151afbd9db829266e84d8a", "content_id": "c3058f3541fb0505cda167e97a98c6501d84ad6d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18699, "license_type": "permissive", "max_line_length": 137, "num_lines": 453, "path": "/plot_daily_means.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom functools import partial\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import E3SMCaseOutput, day_str\n\nSTART_DAY = 1\nEND_DAY = 15\nEND_ZM10S_DAY = 19\n\nSTART_AVG_DAY = 3\nEND_AVG_DAY = 15\n\nDAILY_FILE_LOC=\"/p/lscratchh/santos36/timestep_daily_avgs/\"\n\nFOCUS_PRECIP = False\nUSE_PRESAER = True\nLAND_ONLY = False\nOCEAN_ONLY = False # Note that this includes ocean and sea-ice grid cells\nTROPICS_ONLY = False\nMIDLATITUDES_ONLY = False\n\nassert not (FOCUS_PRECIP and USE_PRESAER), \\\n \"no precipitation-specific prescribed aerosol run set has been defined\"\n\nassert not (LAND_ONLY and OCEAN_ONLY), \\\n \"can't do only land and only ocean\"\n\nassert not (TROPICS_ONLY and MIDLATITUDES_ONLY), \\\n \"can't do only tropics and only midlatitudes\"\n\ndays = list(range(START_DAY, END_DAY+1))\nndays = len(days)\nnavgdays = END_AVG_DAY - START_AVG_DAY + 1\n\nsuffix = '_d{}-{}'.format(day_str(START_DAY), day_str(END_DAY))\nif FOCUS_PRECIP:\n suffix += '_precip'\nif USE_PRESAER:\n suffix += '_presaer'\nif LAND_ONLY:\n sfc_suffix = 'lnd'\nelif OCEAN_ONLY:\n sfc_suffix = 'ocn'\nelse:\n sfc_suffix = ''\nif TROPICS_ONLY:\n suffix += '_{}tropics'.format(sfc_suffix)\nelif MIDLATITUDES_ONLY:\n suffix += '_{}midlats'.format(sfc_suffix)\nelif sfc_suffix != '':\n suffix += '_{}'.format(sfc_suffix)\n\nlog_file = open(\"plot_daily_log{}.txt\".format(suffix), 'w')\n\nif USE_PRESAER:\n REF_CASE = E3SMCaseOutput(\"timestep_presaer_ctrl\", \"CTRLPA\", DAILY_FILE_LOC, START_DAY, END_DAY)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_presaer_ZM_10s\", \"ZM10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_ZM_10s_lower_tau\", \"ZM10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s\", \"CLUBBMICRO10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s_ZM_10s\", \"CLUBBMICRO10ZM10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s_ZM_10s_lower_tau\", \"CLUBBMICRO10ZM10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_cld_10s\", \"CLD10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_cld_10s_lower_tau\", \"CLD10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_cld_10s_lower_tau2\", \"CLD10LT2PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_all_10s\", \"ALL10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_all_10s_lower_tau\", \"ALL10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n ]\n STYLES = {\n \"CLUBBMICRO10PA\": ('indigo', '-'),\n \"ALL10PA\": ('dimgrey', '-'),\n \"ZM10PA\": ('g', '-'),\n \"CLUBBMICRO10ZM10PA\": ('saddlebrown', '-'),\n \"CLD10PA\": ('slateblue', '-'),\n \"ALL10LTPA\": ('dimgrey', '-.'),\n \"ZM10LTPA\": ('g', '-.'),\n \"CLUBBMICRO10ZM10LTPA\": ('saddlebrown', '-.'),\n \"CLD10LTPA\": ('slateblue', '-.'),\n \"CLD10LT2PA\": ('slateblue', ':'),\n }\nelif FOCUS_PRECIP:\n REF_CASE = E3SMCaseOutput(\"timestep_ctrl\", \"CTRL\", DAILY_FILE_LOC, START_DAY, END_DAY)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_precip_grad\", \"PFMG\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_CLUBB_10s\", \"CLUBB10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_CLUBB_10s_MG2_10s\", \"CLUBB10MICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_MG2_10s\", \"MICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_precip_grad_MG2_10s\", \"PFMGMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_CLUBB_MG2_60s\", \"CLUBBMICRO60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_10s\", \"CLUBBMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_precip_grad_CLUBB_MG2_10s\", \"PFMGCLUBBMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_all_300s\", \"ALL300\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_all_60s\", \"ALL60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_all_10s\", \"ALL10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n ]\n STYLES = {\n \"DYN10\": ('y', '-'),\n \"CLUBB10\": ('b', '-'),\n \"MICRO10\": ('r', '-'),\n \"CLUBB10MICRO10\": ('maroon', '-'),\n \"CLUBBMICROSTR\": ('m', '-'),\n \"CLUBBMICROSTR60\": ('m', '--'),\n \"CLUBBMICRO60\": ('indigo', '--'),\n \"CLUBBMICRO10\": ('indigo', '-'),\n \"ALL10\": ('dimgrey', '-'),\n \"ALL60\": ('dimgrey', '--'),\n \"ALL300\": ('dimgrey', ':'),\n \"ALLRAD10\": ('orange', '-'),\n \"PFMG\": ('k', '-.'),\n \"PFMGMICRO10\": ('r', '-.'),\n \"PFMGCLUBBMICRO10\": ('indigo', '-.'),\n }\nelse:\n REF_CASE = E3SMCaseOutput(\"timestep_ctrl\", \"CTRL\", DAILY_FILE_LOC, START_DAY, END_DAY)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_dyn_10s\", \"DYN10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_10s\", \"CLUBB10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_10s_MG2_10s\", \"CLUBB10MICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_CLUBB_MG2_Strang\", \"CLUBBMICROSTR\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_CLUBB_MG2_Strang_60s\", \"CLUBBMICROSTR60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_MG2_10s\", \"MICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_60s\", \"CLUBBMICRO60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_10s\", \"CLUBBMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_ZM_10s\", \"ZM10\", DAILY_FILE_LOC, START_DAY, END_ZM10S_DAY),\n# E3SMCaseOutput(\"timestep_ZM_300s\", \"ZM300\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_rad_10s\", \"ALLRAD10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_300s\", \"ALL300\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_60s\", \"ALL60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_10s\", \"ALL10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n ]\n STYLES = {\n \"DYN10\": ('y', '-'),\n \"CLUBB10\": ('b', '-'),\n \"MICRO10\": ('r', '-'),\n \"CLUBB10MICRO10\": ('maroon', '-'),\n \"CLUBBMICROSTR\": ('m', '-'),\n \"CLUBBMICROSTR60\": ('m', '--'),\n \"CLUBBMICRO60\": ('indigo', '--'),\n \"CLUBBMICRO10\": ('indigo', '-'),\n \"ALL10\": ('dimgrey', '-'),\n \"ALL60\": ('dimgrey', '--'),\n \"ALL300\": ('dimgrey', ':'),\n \"ALLRAD10\": ('orange', '-'),\n }\n\ncase_num = len(TEST_CASES)\n\nrfile0 = nc4.Dataset(REF_CASE.get_daily_file_name(START_DAY), 'r')\nnlev = len(rfile0.dimensions['lev'])\nncol = len(rfile0.dimensions['ncol'])\narea = rfile0['area'][:]\nif LAND_ONLY:\n landfrac = rfile0['LANDFRAC'][0,:]\n area *= landfrac\nelif OCEAN_ONLY:\n landfrac = rfile0['LANDFRAC'][0,:]\n area *= 1. - landfrac\n# For tropics_only cases, just use a weight of 0 for all other cases.\nif TROPICS_ONLY:\n lat = rfile0['lat'][:]\n for i in range(ncol):\n if np.abs(lat[i]) > 30.:\n area[i] = 0.\n# Same for midlatitudes.\nelif MIDLATITUDES_ONLY:\n lat = rfile0['lat'][:]\n for i in range(ncol):\n if np.abs(lat[i]) < 30. or np.abs(lat[i]) > 60.:\n area[i] = 0.\narea_sum = area.sum()\nweights = area/area_sum\nrfile0.close()\n\ndef calc_var_stats(ref_case, test_cases, day, varnames):\n varnames_read = [name for name in varnames if name != \"PRECT\" and name != \"TAU\"]\n if \"PRECT\" in varnames:\n if \"PRECL\" not in varnames:\n varnames_read.append(\"PRECL\")\n if \"PRECC\" not in varnames:\n varnames_read.append(\"PRECC\")\n if \"TAU\" in varnames:\n if \"TAUX\" not in varnames:\n varnames_read.append(\"TAUX\")\n if \"TAUY\" not in varnames:\n varnames_read.append(\"TAUY\")\n ref_time_avg, test_time_avgs, diff_time_avgs = ref_case.compare_daily_averages(test_cases, day, varnames_read)\n if \"PRECT\" in varnames:\n ref_time_avg[\"PRECT\"] = ref_time_avg[\"PRECL\"] + ref_time_avg[\"PRECC\"]\n for icase in range(case_num):\n test_time_avgs[icase][\"PRECT\"] = test_time_avgs[icase][\"PRECL\"] + test_time_avgs[icase][\"PRECC\"]\n diff_time_avgs[icase][\"PRECT\"] = diff_time_avgs[icase][\"PRECL\"] + diff_time_avgs[icase][\"PRECC\"]\n if \"TAU\" in varnames:\n ref_time_avg[\"TAU\"] = np.sqrt(ref_time_avg[\"TAUX\"]**2 + ref_time_avg[\"TAUY\"]**2)\n for icase in range(case_num):\n test_time_avgs[icase][\"TAU\"] = np.sqrt(test_time_avgs[icase][\"TAUX\"]**2 + test_time_avgs[icase][\"TAUY\"]**2)\n diff_time_avgs[icase][\"TAU\"] = test_time_avgs[icase][\"TAU\"] - ref_time_avg[\"TAU\"]\n ref_avg = dict()\n test_avgs = dict()\n diff_avgs = dict()\n rmses = dict()\n for varname in varnames:\n if varname in vars_3D:\n ref_avg[varname] = np.zeros((nlev,))\n for jlev in range(nlev):\n ref_avg[varname][jlev] = (ref_time_avg[varname][jlev,:] * weights).sum()\n else:\n ref_avg[varname] = (ref_time_avg[varname] * weights).sum()\n test_avgs[varname] = []\n diff_avgs[varname] = []\n rmses[varname] = []\n for i in range(len(test_cases)):\n if test_cases[i].day_is_available(day):\n if varname in vars_3D:\n test_avgs[varname].append(np.zeros((nlev,)))\n diff_avgs[varname].append(np.zeros((nlev,)))\n rmses[varname].append(np.zeros((nlev,)))\n for jlev in range(nlev):\n test_avgs[varname][-1][jlev] = (test_time_avgs[i][varname][jlev,:] * weights).sum()\n diff_avgs[varname][-1][jlev] = (diff_time_avgs[i][varname][jlev,:] * weights).sum()\n rmses[varname][-1][jlev] = np.sqrt((diff_time_avgs[i][varname][jlev,:]**2 * weights).sum())\n else:\n test_avgs[varname].append((test_time_avgs[i][varname] * weights).sum())\n diff_avgs[varname].append((diff_time_avgs[i][varname] * weights).sum())\n rmses[varname].append(np.sqrt((diff_time_avgs[i][varname]**2 * weights).sum()))\n assert np.isclose(diff_avgs[varname][i], test_avgs[varname][i] - ref_avg[varname]).all(), \\\n \"Problem with diff of variable {} from case {}\".format(varname, TEST_CASES[i].short_name)\n else:\n test_avgs[varname].append(None)\n diff_avgs[varname].append(None)\n rmses[varname].append(None)\n return (ref_avg, test_avgs, diff_avgs, rmses)\n\n# Possible ways to extract a 2D section start here:\ndef identity(x):\n return x\n\ndef slice_at(level, x):\n return x[:,level]\n\ndef plot_vars_over_time(names, units, scales, log_plot_names):\n ref_means = dict()\n test_means = dict()\n diff_means = dict()\n rmses = dict()\n for name in names:\n if name in vars_3D:\n ref_means[name] = np.zeros((ndays, nlev))\n test_means[name] = np.zeros((case_num, ndays, nlev))\n diff_means[name] = np.zeros((case_num, ndays, nlev))\n rmses[name] = np.zeros((case_num, ndays, nlev))\n else:\n ref_means[name] = np.zeros((ndays,))\n test_means[name] = np.zeros((case_num, ndays))\n diff_means[name] = np.zeros((case_num, ndays))\n rmses[name] = np.zeros((case_num, ndays))\n\n for iday in range(ndays):\n day = days[iday]\n print(\"On day: \", day, file=log_file, flush=True)\n ref_mean, test_case_means, diff_case_means, case_rmses = calc_var_stats(REF_CASE, TEST_CASES, day, names)\n for name in names:\n ref_means[name][iday] = ref_mean[name]*scales[name]\n for i in range(case_num):\n if TEST_CASES[i].day_is_available(day):\n test_means[name][i,iday] = test_case_means[name][i]*scales[name]\n diff_means[name][i,iday] = diff_case_means[name][i]*scales[name]\n rmses[name][i,iday] = case_rmses[name][i]*scales[name]\n\n for name in names:\n plot_name = name\n if name in plot_names:\n plot_name = plot_names[name]\n\n get_2D = identity\n if name in vars_3D:\n get_2D = partial(slice_at, nlev-1)\n\n if name in log_plot_names:\n plot_var = plt.semilogy\n else:\n plot_var = plt.plot\n for i in range(case_num):\n test_plot_var = get_2D(test_means[name][i])\n start_ind = TEST_CASES[i].start_day - START_DAY\n end_ind = TEST_CASES[i].end_day - START_DAY + 1\n plot_var(days[start_ind:end_ind],\n test_plot_var[start_ind:end_ind],\n label=TEST_CASES[i].short_name,\n color=STYLES[TEST_CASES[i].short_name][0],\n linestyle=STYLES[TEST_CASES[i].short_name][1])\n ref_plot_var = get_2D(ref_means[name])\n plot_var(days, ref_plot_var, label=REF_CASE.short_name, color='k')\n plt.axis('tight')\n plt.xlabel(\"day\")\n plt.ylabel(\"Mean {} ({})\".format(plot_name, units[name]))\n plt.savefig('{}_time{}.png'.format(name, suffix))\n plt.close()\n\n for i in range(case_num):\n diff_plot_var = get_2D(diff_means[name][i])\n start_ind = TEST_CASES[i].start_day - START_DAY\n end_ind = TEST_CASES[i].end_day - START_DAY + 1\n plot_var(days[start_ind:end_ind],\n diff_plot_var[start_ind:end_ind],\n label=TEST_CASES[i].short_name,\n color=STYLES[TEST_CASES[i].short_name][0],\n linestyle=STYLES[TEST_CASES[i].short_name][1])\n plt.axis('tight')\n plt.xlabel(\"day\")\n plt.ylabel(\"Mean {} difference ({})\".format(plot_name, units[name]))\n plt.savefig('{}_diff_time{}.png'.format(name, suffix))\n plt.close()\n\n for i in range(case_num):\n rmse_plot_var = get_2D(rmses[name][i])\n start_ind = TEST_CASES[i].start_day - START_DAY\n end_ind = TEST_CASES[i].end_day - START_DAY + 1\n plot_var(days[start_ind:end_ind],\n rmse_plot_var[start_ind:end_ind],\n label=TEST_CASES[i].short_name,\n color=STYLES[TEST_CASES[i].short_name][0],\n linestyle=STYLES[TEST_CASES[i].short_name][1])\n plt.axis('tight')\n plt.xlabel(\"day\")\n plt.ylabel(\"{} RMSE ({})\".format(plot_name, units[name]))\n plt.savefig('{}_rmse_time{}.png'.format(name, suffix))\n plt.close()\n\n print(name, \" has reference mean: \", sum(ref_plot_var[START_AVG_DAY-START_DAY:END_AVG_DAY-START_DAY+1])/navgdays,\n file=log_file)\n for i in range(case_num):\n case_name = TEST_CASES[i].short_name\n test_plot_var = get_2D(test_means[name][i])\n diff_plot_var = get_2D(diff_means[name][i])\n print(name, \" has case \", case_name, \" mean: \", sum(test_plot_var[START_AVG_DAY-START_DAY:END_AVG_DAY-START_DAY+1])/navgdays,\n file=log_file)\n print(name, \" has difference mean: \", sum(diff_plot_var[START_AVG_DAY-START_DAY:END_AVG_DAY-START_DAY+1])/navgdays,\n file=log_file)\n if USE_PRESAER and \"LT\" in case_name:\n compare_name = TEST_CASES[i-1].short_name\n compare_plot_var = get_2D(test_means[name][i-1])\n print(name, \" has mean difference from \", compare_name, \": \",\n sum(test_plot_var[START_AVG_DAY-START_DAY:END_AVG_DAY-START_DAY+1])/navgdays - \\\n sum(compare_plot_var[START_AVG_DAY-START_DAY:END_AVG_DAY-START_DAY+1])/navgdays,\n file=log_file)\n\nplot_names = {\n 'LWCF': \"longwave cloud forcing\",\n 'SWCF': \"shortwave cloud forcing\",\n 'PRECC': \"convective precipitation\",\n 'PRECL': \"large-scale precipitation\",\n 'PRECT': \"total precipitation\",\n 'TGCLDIWP': \"ice water path\",\n 'TGCLDLWP': \"liquid water path\",\n 'CLDTOT': \"cloud area fraction\",\n 'CLDLOW': \"low cloud area fraction\",\n 'CLDMED': \"mid-level cloud area fraction\",\n 'CLDHGH': \"high cloud area fraction\",\n 'LHFLX': \"latent heat flux\",\n 'SHFLX': \"sensible heat flux\",\n 'TAU': \"surface wind stress\",\n 'TS': \"surface temperature\",\n 'PSL': \"sea level pressure\",\n 'OMEGA500': \"vertical velocity at 500 mb\",\n 'U10': \"10 meter wind speed\",\n 'RELHUM': \"surface relative humidity\",\n 'Q': \"specific humidity\",\n 'CLDLIQ': \"lowest level cloud liquid\",\n 'TMQ': \"precipitable water\",\n 'CLOUD': \"lowest level cloud fraction\",\n 'T': \"lowest level temperature\",\n}\n\nunits = {\n 'LWCF': r'$W/m^2$',\n 'SWCF': r'$W/m^2$',\n 'PRECC': r'$mm/day$',\n 'PRECL': r'$mm/day$',\n 'PRECT': r'$mm/day$',\n 'TGCLDIWP': r'$g/m^2$',\n 'TGCLDLWP': r'$g/m^2$',\n 'AODABS': r'units?',\n 'AODUV': r'units?',\n 'AODVIS': r'units?',\n 'FLDS': r'$W/m^2$',\n 'FLNS': r'$W/m^2$',\n 'FLNSC': r'$W/m^2$',\n 'FLNT': r'$W/m^2$',\n 'FLNTC': r'$W/m^2$',\n 'FLUT': r'$W/m^2$',\n 'FLUTC': r'$W/m^2$',\n 'FSDS': r'$W/m^2$',\n 'FSDSC': r'$W/m^2$',\n 'FSNS': r'$W/m^2$',\n 'FSNSC': r'$W/m^2$',\n 'FSNT': r'$W/m^2$',\n 'FSNTC': r'$W/m^2$',\n 'FSNTOA': r'$W/m^2$',\n 'FSNTOAC': r'$W/m^2$',\n 'FSUTOA': r'$W/m^2$',\n 'FSUTOAC': r'$W/m^2$',\n 'CLDTOT': r'fraction',\n 'CLDLOW': r'fraction',\n 'CLDMED': r'fraction',\n 'CLDHGH': r'fraction',\n 'OMEGA500': r'Pa/s',\n 'LHFLX': r'$W/m^2$',\n 'SHFLX': r'$W/m^2$',\n 'TAU': r'$N/m^2$',\n 'TAUX': r'$N/m^2$',\n 'TAUY': r'$N/m^2$',\n 'TS': r'$K$',\n 'PSL': r'$Pa$',\n 'U10': r'$m/s$',\n 'RELHUM': r'%',\n 'Q': r'$g/kg$',\n 'CLDLIQ': r\"$g/kg$\",\n 'TMQ': r'$kg/m^2$',\n 'CLOUD': r'$fraction$',\n 'T': r'$K$',\n}\nnames = list(units.keys())\nscales = dict()\nfor name in names:\n scales[name] = 1.\nscales['TGCLDIWP'] = 1000.\nscales['TGCLDLWP'] = 1000.\nscales['PRECC'] = 1000.*86400.\nscales['PRECL'] = 1000.*86400.\nscales['PRECT'] = 1000.*86400.\nscales['Q'] = 1000.\nscales['CLDLIQ'] = 1000.\n\nvars_3D = [\n 'RELHUM',\n 'Q',\n 'CLDLIQ',\n 'T',\n 'CLOUD',\n]\n\nlog_plot_names = []#'AODABS', 'AODVIS', 'AODUV']\n\nplot_vars_over_time(names, units, scales, log_plot_names)\n\nlog_file.close()\n" }, { "alpha_fraction": 0.5442177057266235, "alphanum_fraction": 0.6604823470115662, "avg_line_length": 39.42499923706055, "blob_id": "2e05cd7e023a1db12f0afd8ff6ac801162abd09b", "content_id": "71aced27e85095882ab8055bf33fd2c0deb5b437", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1617, "license_type": "permissive", "max_line_length": 173, "num_lines": 40, "path": "/create_climos.sh", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nCASE_NAMES=\"timestep_ctrl\"\nMONTHS=\"01 02\"\nINPUT_DIR=/p/lscratchh/santos36/timestep_monthly_avgs_lat_lon\nOUTPUT_DIR=/p/lscratchh/santos36/timestep_monthly_avgs_lat_lon\n\nfor case_name in $CASE_NAMES; do\n echo \"On case $case_name\"\n for month in $MONTHS; do\n date\n echo \"On month $month.\"\n ncra $INPUT_DIR/$case_name.00{05,06,07}-$month.nc $OUTPUT_DIR/${case_name}_y04-y07_${month}_climo.nc\n done\ndone\n\nMONTHS=\"03 04 05 06 07 08 09 10 11 12\"\n\nfor case_name in $CASE_NAMES; do\n echo \"On case $case_name\"\n for month in $MONTHS; do\n date\n echo \"On month $month.\"\n ncra $INPUT_DIR/$case_name.00{04,05,06}-$month.nc $OUTPUT_DIR/${case_name}_y04-y07_${month}_climo.nc\n done\ndone\n\nfor case_name in $CASE_NAMES; do\n echo \"On case $case_name\"\n echo \"Seasonal average DJF\"\n ncra -w 31,31,28 $OUTPUT_DIR/${case_name}_y04-y07_{12,01,02}_climo.nc $OUTPUT_DIR/${case_name}_y04-y07_DJF_climo.nc\n echo \"Seasonal average MAM\"\n ncra -w 31,30,31 $OUTPUT_DIR/${case_name}_y04-y07_{03,04,05}_climo.nc $OUTPUT_DIR/${case_name}_y04-y07_MAM_climo.nc\n echo \"Seasonal average JJA\"\n ncra -w 30,31,31 $OUTPUT_DIR/${case_name}_y04-y07_{06,07,08}_climo.nc $OUTPUT_DIR/${case_name}_y04-y07_JJA_climo.nc\n echo \"Seasonal average SON\"\n ncra -w 30,31,30 $OUTPUT_DIR/${case_name}_y04-y07_{09,10,11}_climo.nc $OUTPUT_DIR/${case_name}_y04-y07_SON_climo.nc\n echo \"Annual average\"\n ncra -w 31,28,31,30,31,30,31,31,30,31,30,31 $OUTPUT_DIR/${case_name}_y04-y07_{01,02,03,04,05,06,07,08,09,10,11,12}_climo.nc $OUTPUT_DIR/${case_name}_y04-y07_ANN_climo.nc\ndone\n" }, { "alpha_fraction": 0.5296811461448669, "alphanum_fraction": 0.5544679164886475, "avg_line_length": 32.78916931152344, "blob_id": "5a0a88a70495549c337285aec4483be067d0165b", "content_id": "6658808a0af953103796ee1cb20136feefc999f2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17469, "license_type": "permissive", "max_line_length": 128, "num_lines": 517, "path": "/sfc_flux_timeseries.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom os.path import join\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nSTART_DAY = 1\nEND_DAY = 5\nTIME_STEP = 1800\nassert 86400 % TIME_STEP == 0, \"cannot fit even number of time steps in day\"\ntimes_per_day = 86400 // TIME_STEP\n\nMODEL = \"EAM\"\n\nDYCORE = \"SE\"\n\nCASE_NAMES = [\n \"e3sm_nopg_sfc_test\",\n# \"e3sm_TTexport_sfc_test\",\n \"e3sm_TTmod_sfc_test\",\n \"e3sm_TTboth_sfc_test\",\n# \"e3sm_BE_land_sfc_test\",\n# \"e3sm_BE_land_TTexport_sfc_test\",\n# \"e3sm_BE_land_energy_sfc_test\",\n# \"e3sm_TM_land_sfc_test\",\n# \"e3sm_TM_land_weddy_sfc_test\",\n# \"e3sm_BE_land_no_orogw_sfc_test\",\n# \"e3sm_BE_land_gw_bc_sfc_test\",\n \"e3sm_EQ_BE_land_sfc_test\",\n]\nSHORT_CASE_NAMES = [\n \"CTRL\",\n# \"TTEX\",\n \"TTCORR\",\n \"TTBOTH\",\n# \"BE\",\n# \"BETTEX\",\n# \"BEEN\",\n# \"TM\",\n# \"TMWE\",\n# \"BENOGW\",\n# \"BEBCGW\",\n \"EQBE\",\n]\nSTYLES = {\n \"CTRL\": ('k', '-'),\n \"TTEX\": ('b', '-'),\n \"TTCORR\": ('r', '-'),\n \"TTBOTH\": ('purple', '-'),\n \"BE\": ('orange', '-'),\n \"BETTEX\": ('g', '-'),\n \"BEEN\": ('brown', '-'),\n \"TM\": ('grey', '-'),\n \"TMWE\": ('darkmagenta', '-'),\n \"BENOGW\": ('skyblue', '-'),\n \"BEBCGW\": ('skyblue', '-'),\n \"EQBE\": ('saddlebrown', '-'),\n}\n\nHAVE_NO_TAUGW = {\"BENOGW\"}\nHAVE_WSRESP = {\"BE\", \"BETTEX\", \"BEEN\", \"TM\", \"TMWE\", \"BENOGW\", \"BEBCGW\", \"EQBE\"}\nHAVE_TQRESP = {\"BEEN\", \"TM\", \"TMWE\"}\nHAVE_TAU_EST = {\"EQBE\"}\nHAVE_TAUADJ = {\"TTBOTH\"}\n\nif MODEL == \"EAM\":\n OUTPUT_ROOT = \"/global/cscratch1/sd/santos/e3sm_scratch/cori-knl\"\n OUTPUT_DIRS = [\"{}/{}/run/\".format(OUTPUT_ROOT, case)\n for case in CASE_NAMES]\nelse:\n OUTPUT_ROOT = \"/global/cscratch1/sd/santos/archive\"\n OUTPUT_DIRS = [\"{}/{}/atm/hist\".format(OUTPUT_ROOT, case)\n for case in CASE_NAMES]\n\n\nsuffix = \"_fluxdiag\"\n\nlog_file = open(\"sfc_timeseries_log{}.txt\".format(suffix), 'w')\n\nout_file_template = \"{}.{}.h0.0001-01-{}-{}.nc\"\n\ndef day_str(day):\n \"Given an integer day, return the 2-digit day string used for file names.\"\n return \"{:02d}\".format(day)\n\ndef time_str(time):\n \"Given an integer time in seconds, return the 5-digit string used in file names.\"\n return \"{:05d}\".format(time)\n\ndef get_out_file_name(icase, day, time):\n \"\"\"Given a case index, day, and time, return atmosphere header file name.\"\"\"\n return join(OUTPUT_DIRS[icase],\n out_file_template.format(CASE_NAMES[icase], MODEL.lower(),\n day_str(day), time_str(time)))\n\nfirst_file_name = get_out_file_name(0, 1, 0)\nfirst_file = nc4.Dataset(first_file_name, 'r')\nif DYCORE == \"FV\":\n nlat = len(first_file.dimensions['lat'])\n nlon = len(first_file.dimensions['lon'])\nelse:\n ncol = len(first_file.dimensions['ncol'])\nnlev = len(first_file.dimensions['lev'])\nlat = first_file['lat'][:]\nlon = first_file['lon'][:]\nlev = first_file['lev'][:]\n\n# Find columns in box over South America.\nmin_lat = -20.\nmax_lat = 10.\nmin_lon = 280.\nmax_lon = 315.\n\nif DYCORE == 'FV':\n lat_set = set()\n lon_set = set()\n for i in range(nlat):\n if min_lat <= lat[i] <= max_lat:\n lat_set.add(i)\n for i in range(nlon):\n if min_lon <= lon[i] <= max_lon:\n lon_set.add(i)\n nlat_sa = len(lat_set)\n nlon_sa = len(lon_set)\nelse:\n column_set = set()\n for i in range(ncol):\n if min_lon <= lon[i] <= max_lon and min_lat <= lat[i] <= max_lat:\n column_set.add(i)\n ncol_sa = len(column_set)\n\nfirst_file.close()\n\n# Plot wind issues over SA.\nimport cartopy.crs as ccrs\n\n#TIME_CHECK = 57600\nTIME_CHECK = 81000\n#TIME_CHECK = 3600\n#TIME_CHECK = 54000\n#TIME_CHECK = 12*3600\n\nDAY_CHECK = END_DAY\n\nCASE_CHECK = 0\n\nLEVEL = nlev - 1\n\ncase = SHORT_CASE_NAMES[CASE_CHECK]\ntime_increment = TIME_STEP\n\nplot_box = [min_lon, max_lon, min_lat, max_lat]\n#plot_box = [285., 297., 1., 10.]\n\nmid_file_name = get_out_file_name(CASE_CHECK, DAY_CHECK, TIME_CHECK)\nmid_file = nc4.Dataset(mid_file_name, 'r')\n\nif DYCORE == 'FV':\n u1 = mid_file['U'][0,LEVEL,:,:]\n v1 = mid_file['V'][0,LEVEL,:,:]\n gwx1 = mid_file['TAUGWX'][0,:,:]\n gwy1 = mid_file['TAUGWY'][0,:,:]\nelse:\n u1 = mid_file['U'][0,LEVEL,:]\n v1 = mid_file['V'][0,LEVEL,:]\n gwx1 = mid_file['TAUGWX'][0,:]\n gwy1 = mid_file['TAUGWY'][0,:]\n\nax = plt.axes(projection=ccrs.PlateCarree())\nax.coastlines()\nax.set_extent(plot_box)\n\nplt.quiver(lon, lat, u1, v1,\n scale=100., scale_units='height', angles='xy')\nplt.savefig(\"UV_arrow1{}.png\".format(suffix))\nplt.close()\n\nmid_file.close()\n\nmid_file_name = get_out_file_name(CASE_CHECK, DAY_CHECK, TIME_CHECK + time_increment)\nmid_file = nc4.Dataset(mid_file_name, 'r')\n\nif DYCORE == 'FV':\n u2 = mid_file['U'][0,LEVEL,:,:]\n v2 = mid_file['V'][0,LEVEL,:,:]\n gwx2 = mid_file['TAUGWX'][0,:,:]\n gwy2 = mid_file['TAUGWY'][0,:,:]\nelse:\n u2 = mid_file['U'][0,LEVEL,:]\n v2 = mid_file['V'][0,LEVEL,:]\n gwx2 = mid_file['TAUGWX'][0,:]\n gwy2 = mid_file['TAUGWY'][0,:]\n\nax = plt.axes(projection=ccrs.PlateCarree())\nax.coastlines()\nax.set_extent(plot_box)\n\nplt.quiver(lon, lat, u2, v2,\n scale=100., scale_units='height', angles='xy')\nplt.savefig(\"UV_arrow2{}.png\".format(suffix))\nplt.close()\n\nmid_file.close()\n\nmid_file_name = get_out_file_name(CASE_CHECK, DAY_CHECK, TIME_CHECK + 2*time_increment)\nmid_file = nc4.Dataset(mid_file_name, 'r')\n\nif DYCORE == 'FV':\n u3 = mid_file['U'][0,LEVEL,:,:]\n v3 = mid_file['V'][0,LEVEL,:,:]\n gwx3 = mid_file['TAUGWX'][0,:,:]\n gwy3 = mid_file['TAUGWY'][0,:,:]\nelse:\n u3 = mid_file['U'][0,LEVEL,:]\n v3 = mid_file['V'][0,LEVEL,:]\n gwx3 = mid_file['TAUGWX'][0,:]\n gwy3 = mid_file['TAUGWY'][0,:]\n\nax = plt.axes(projection=ccrs.PlateCarree())\nax.coastlines()\nax.set_extent(plot_box)\n\nplt.quiver(lon, lat, u3, v3,\n scale=100., scale_units='height', angles='xy')\nplt.savefig(\"UV_arrow3{}.png\".format(suffix))\nplt.close()\n\nmid_file.close()\n\nud2 = u1 - 2*u2 + u3\nvd2 = v1 - 2*v2 + v3\n\ngwxd2 = gwx1 - 2*gwx2 + gwx3\ngwyd2 = gwy1 - 2*gwy2 + gwy3\n\n# Find column with large oscillations in wind speed\n# To force focus on a particular column, just set the number here.\nif DYCORE == 'FV':\n ifocus_lat = -1\n ifocus_lon = -1\nelse:\n ifocus = -1\n\nprint(\"Searching for oscillatory point.\", file=log_file, flush=True)\n\nUSE_GW_D2 = False\n\nif DYCORE == 'FV' and ifocus_lat == -1:\n maxd2 = 0.\n for ilat in lat_set:\n for ilon in lon_set:\n if USE_GW_D2:\n d2 = np.sqrt(gwxd2[ilat,ilon]*gwxd2[ilat,ilon] +\n gwyd2[ilat,ilon]*gwyd2[ilat,ilon])\n else:\n d2 = np.sqrt(ud2[ilat,ilon]*ud2[ilat,ilon] +\n vd2[ilat,ilon]*vd2[ilat,ilon])\n if d2 > maxd2:\n maxd2 = d2\n ifocus_lat = ilat\n ifocus_lon = ilon\n\n assert ifocus_lat >= 0, \"no focus column found\"\n assert ifocus_lon >= 0, \"no focus lon found\"\n\n print(\"Worst oscillations at (ilat, ilon) \", (ifocus_lat, ifocus_lon),\n \" at lat = \", lat[ifocus_lat], \", lon = \", lon[ifocus_lon],\n file=log_file, flush=True)\nelif ifocus == -1:\n maxd2 = 0.\n for icol in column_set:\n if USE_GW_D2:\n d2 = np.sqrt(gwxd2[icol]*gwxd2[icol] + gwyd2[icol]*gwyd2[icol])\n else:\n d2 = np.sqrt(ud2[icol]*ud2[icol] + vd2[icol]*vd2[icol])\n if d2 > maxd2:\n maxd2 = d2\n ifocus = icol\n\n assert ifocus >= 0, \"no focus column found\"\n\n print(\"Worst oscillations at column \", ifocus, \" at lat = \",\n lat[ifocus], \", lon = \", lon[ifocus], file=log_file, flush=True)\n\nax = plt.axes(projection=ccrs.PlateCarree())\nax.coastlines()\nax.set_extent(plot_box)\n\nif DYCORE == 'FV':\n plt.scatter(lon[ifocus_lon], lat[ifocus_lat])\nelse:\n plt.scatter(lon[ifocus], lat[ifocus])\n\nplt.quiver(lon, lat, ud2, vd2,\n scale=100., scale_units='height', angles='xy')\nplt.savefig(\"UV_D2_arrow{}.png\".format(suffix))\nplt.close()\n\nvariables = [\n {'name': 'RELHUM', 'units': r'%', 'ndim': 2},\n {'name': 'CLDLIQ', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'QFLX', 'units': r'$kg/m^2/s$', 'ndim': 1},\n {'name': 'LHFLX', 'units': r'$W/m^2$', 'ndim': 1},\n {'name': 'SHFLX', 'units': r'$W/m^2$', 'ndim': 1},\n {'name': 'TS', 'units': r'$K$', 'ndim': 1},\n {'name': 'T', 'units': r'$K$', 'ndim': 2},\n {'name': 'Q', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'U', 'units': r'$m/s$', 'ndim': 2},\n {'name': 'V', 'units': r'$m/s$', 'ndim': 2},\n {'name': 'U10', 'units': r'$m/s$', 'ndim': 1},\n {'name': 'PS', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUX', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUY', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUXadj', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUYadj', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUGWX', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUGWY', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'tresp', 'units': r'$Km^2/W$', 'ndim': 1},\n {'name': 'qresp', 'units': r'$m^2s/kg$', 'ndim': 1},\n {'name': 'wsresp', 'units': r'$m/s/Pa$', 'ndim': 1},\n {'name': 'tau_est', 'units': r'$Pa$', 'ndim': 1},\n]\n\nderived_variables = [\n {'name': 'TAU', 'units': r'$Pa$', 'ndim': 1,\n 'depends': ['TAUX', 'TAUY'],\n 'calc': (lambda var_dict: np.sqrt(var_dict['TAUX']**2 + var_dict['TAUY']**2)),\n },\n {'name': 'UREF_pred_diff','units': r'm/s', 'ndim': 1,\n 'depends': ['TAUX', 'TAUY', 'wsresp'],\n 'calc': (lambda var_dict: var_dict['wsresp'] * np.sqrt(var_dict['TAUX']**2 + var_dict['TAUY']**2)),\n },\n {'name': 'UREF_pred_diff_est','units': r'm/s', 'ndim': 1,\n 'depends': ['TAUX', 'TAUY', 'wsresp', 'tau_est'],\n 'calc': (lambda var_dict: var_dict['wsresp'] * (np.sqrt(var_dict['TAUX']**2 + var_dict['TAUY']**2) - var_dict['tau_est'])),\n },\n {'name': 'TAUadj', 'units': r'$Pa$', 'ndim': 1,\n 'depends': ['TAUX', 'TAUY', 'TAUXadj', 'TAUYadj'],\n 'calc': (lambda var_dict: np.sqrt(var_dict['TAUX']**2 + var_dict['TAUY']**2) -\n np.sqrt((var_dict['TAUX']-var_dict['TAUXadj'])**2 + (var_dict['TAUY']-var_dict['TAUYadj'])**2)),\n },\n {'name': 'TAUorig', 'units': r'$Pa$', 'ndim': 1,\n 'depends': ['TAUX', 'TAUY', 'TAUXadj', 'TAUYadj'],\n 'calc': (lambda var_dict: np.sqrt((var_dict['TAUX']-var_dict['TAUXadj'])**2 + (var_dict['TAUY']-var_dict['TAUYadj'])**2)),\n },\n]\n\nwsresp_variables = {'wsresp', 'UREF_pred_diff'}\ntqresp_variables = {'tresp', 'qresp'}\ntaugw_variables = {'TAUGWX', 'TAUGWY'}\ntau_est_variables = {'tau_est', 'UREF_pred_diff_est'}\ntauadj_variables = {'TAUXadj', 'TAUYadj', 'TAUadj', 'TAUorig'}\n\n# Check that dependencies are satisfied.\nvar_names = [var['name'] for var in variables]\nfor derived in derived_variables:\n for depend in derived['depends']:\n assert depend in var_names\n\nncases = len(CASE_NAMES)\nntimes = (END_DAY - START_DAY + 1) * times_per_day + 1\n\nout_vars = {}\nfor icase in range(ncases):\n case = SHORT_CASE_NAMES[icase]\n print(\"Processing case \", case)\n case_times_per_day = times_per_day\n case_ntimes = ntimes\n case_time_step = TIME_STEP\n out_vars[case] = {}\n for var in variables:\n if var['name'] in wsresp_variables and case not in HAVE_WSRESP:\n continue\n if var['name'] in tqresp_variables and case not in HAVE_TQRESP:\n continue\n if var['name'] in taugw_variables and case in HAVE_NO_TAUGW:\n continue\n if var['name'] in tau_est_variables and case not in HAVE_TAU_EST:\n continue\n if var['name'] in tauadj_variables and case not in HAVE_TAUADJ:\n continue\n out_vars[case][var['name']] = np.zeros((case_ntimes,))\n ita = 0\n for day in range(START_DAY, END_DAY+1):\n for it in range(case_times_per_day):\n out_file_name = get_out_file_name(icase, day, it*case_time_step)\n out_file = nc4.Dataset(out_file_name, 'r')\n for var in variables:\n varname = var['name']\n ndim = var['ndim']\n if varname in wsresp_variables and case not in HAVE_WSRESP:\n continue\n if varname in tqresp_variables and case not in HAVE_TQRESP:\n continue\n if varname in taugw_variables and case in HAVE_NO_TAUGW:\n continue\n if varname in tau_est_variables and case not in HAVE_TAU_EST:\n continue\n if varname in tauadj_variables and case not in HAVE_TAUADJ:\n continue\n if ndim == 1:\n if DYCORE == 'FV':\n out_vars[case][varname][ita] = out_file[varname][0,ifocus_lat,ifocus_lon]\n else:\n out_vars[case][varname][ita] = out_file[varname][0,ifocus]\n elif ndim == 2:\n if DYCORE == 'FV':\n out_vars[case][varname][ita] = out_file[varname][0,LEVEL,ifocus_lat,ifocus_lon]\n else:\n out_vars[case][varname][ita] = out_file[varname][0,LEVEL,ifocus]\n else:\n assert False, \\\n \"don't know what to do with ndim={}\".format(ndim)\n out_file.close()\n ita += 1\n # Last file is 0-th time of the next day.\n out_file_name = get_out_file_name(icase, END_DAY+1, 0)\n out_file = nc4.Dataset(out_file_name, 'r')\n for var in variables:\n varname = var['name']\n ndim = var['ndim']\n if varname in wsresp_variables and case not in HAVE_WSRESP:\n continue\n if varname in tqresp_variables and case not in HAVE_TQRESP:\n continue\n if varname in taugw_variables and case in HAVE_NO_TAUGW:\n continue\n if varname in tau_est_variables and case not in HAVE_TAU_EST:\n continue\n if varname in tauadj_variables and case not in HAVE_TAUADJ:\n continue\n if ndim == 1:\n if DYCORE == 'FV':\n out_vars[case][varname][ita] = out_file[varname][0,ifocus_lat,ifocus_lon]\n else:\n out_vars[case][varname][ita] = out_file[varname][0,ifocus]\n elif ndim == 2:\n if DYCORE == 'FV':\n out_vars[case][varname][ita] = out_file[varname][0,LEVEL,ifocus_lat,ifocus_lon]\n else:\n out_vars[case][varname][ita] = out_file[varname][0,LEVEL,ifocus]\n else:\n assert False, \\\n \"don't know what to do with ndim={}\".format(ndim)\n out_file.close()\n # Scale variables\n for var in variables:\n if var['name'] in wsresp_variables and case not in HAVE_WSRESP:\n continue\n if var['name'] in tqresp_variables and case not in HAVE_TQRESP:\n continue\n if var['name'] in taugw_variables and case in HAVE_NO_TAUGW:\n continue\n if var['name'] in tau_est_variables and case not in HAVE_TAU_EST:\n continue\n if var['name'] in tauadj_variables and case not in HAVE_TAUADJ:\n continue\n if 'scale' in var:\n out_vars[case][var['name']] *= var['scale']\n # Calculate derived variables\n for derived in derived_variables:\n if derived['name'] in wsresp_variables and case not in HAVE_WSRESP:\n continue\n if derived['name'] in tqresp_variables and case not in HAVE_TQRESP:\n continue\n if derived['name'] in taugw_variables and case in HAVE_NO_TAUGW:\n continue\n if derived['name'] in tau_est_variables and case not in HAVE_TAU_EST:\n continue\n if derived['name'] in tauadj_variables and case not in HAVE_TAUADJ:\n continue\n out_vars[case][derived['name']] = derived['calc'](out_vars[case])\n\n# Assumes Venezuelan time.\nTIME_OFFSET = 4.\ntimes = np.linspace(0., TIME_STEP*(ntimes - 1) / 3600., ntimes) - TIME_OFFSET\nfor var in variables + derived_variables:\n name = var['name']\n for icase in range(ncases):\n case = SHORT_CASE_NAMES[icase]\n if name in wsresp_variables and case not in HAVE_WSRESP:\n continue\n if name in tqresp_variables and case not in HAVE_TQRESP:\n continue\n if name in taugw_variables and case in HAVE_NO_TAUGW:\n continue\n if name in tau_est_variables and case not in HAVE_TAU_EST:\n continue\n if name in tauadj_variables and case not in HAVE_TAUADJ:\n continue\n case_times = times\n plt.plot(case_times, out_vars[case][name], color=STYLES[case][0],\n linestyle=STYLES[case][1])\n plt.axis('tight')\n plt.xlabel(\"Time (UTC-4:00)\")\n ticks = [\"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\"]\n # Bad hard-coding!\n if START_DAY - END_DAY + 1 == 1:\n plt.xticks(np.linspace(-3., 18., 8), ticks)\n# elif START_DAY - END_DAY + 1 == 2:\n# plt.xticks(np.linspace(-3., 42., 16),\n# [\"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\",\n# \"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\"])\n plt.grid(True)\n if 'display' in var:\n dname = var['display']\n else:\n dname = name\n plt.ylabel(\"{} ({})\".format(dname, var['units']))\n plt.savefig(\"{}_time{}.png\".format(name, suffix))\n plt.close()\n\nlog_file.close()\n" }, { "alpha_fraction": 0.6546463370323181, "alphanum_fraction": 0.7267683744430542, "avg_line_length": 47.06666564941406, "blob_id": "d53200115a1ff467d88e29bd69b91ae6edda4ae2", "content_id": "26de88ef0f656aa10ea80c30cc28805f4097dc4b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 721, "license_type": "permissive", "max_line_length": 114, "num_lines": 15, "path": "/regrid_precip_files.sh", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nREMAP_FILE=/usr/gdata/climdat/maps/map_ne30np4_to_fv128x256_aave.20160301.nc\nIN_DIR=/p/lscratchh/santos36/timestep_precip\nOUT_DIR=/p/lscratchh/santos36/timestep_precip_lat_lon\nCASE_NAMES=\"timestep_presaer_cld_10s_lower_tau2\"\n\nfor case_name in $CASE_NAMES; do\n date\n echo \"On case $case_name\"\n ncpdq -a nbins,ncol $IN_DIR/$case_name.freq.short.d03-d15.nc $IN_DIR/$case_name.freq.short.d03-d15_tmp.nc\n ncremap -m $REMAP_FILE -O $OUT_DIR $IN_DIR/$case_name.freq.short.d03-d15_tmp.nc\n ncpdq -a lat,lon,nbins $OUT_DIR/$case_name.freq.short.d03-d15_tmp.nc $OUT_DIR/$case_name.freq.short.d03-d15.nc\n rm $IN_DIR/$case_name.freq.short.d03-d15_tmp.nc $OUT_DIR/$case_name.freq.short.d03-d15_tmp.nc\ndone\n" }, { "alpha_fraction": 0.5334805250167847, "alphanum_fraction": 0.5611268877983093, "avg_line_length": 31.46757698059082, "blob_id": "e17508fb34a58ce6c47d2cfd88b70c253c2e44ef", "content_id": "ef03919148370b95b2a4a0337fc4f47a59f25e43", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9513, "license_type": "permissive", "max_line_length": 109, "num_lines": 293, "path": "/plot_precip_freq_daily.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom os.path import join\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import day_str\n\nOUTPUT_DIR = \"/p/lustre2/santos36/timestep_precip/\"\n\nFOCUS_PRECIP = True\nUSE_PRESAER = False\nLAND_TROPICS = False\nTROPICS_ONLY = False\n\nif LAND_TROPICS:\n TROPICS_ONLY = True\n\nassert not (FOCUS_PRECIP and USE_PRESAER), \\\n \"no precipitation-specific prescribed aerosol run set has been defined\"\n\nSTART_DAY = 3\nEND_DAY = 15\n\nif USE_PRESAER:\n REF_CASE_NAME = \"timestep_presaer_ctrl\"\n TEST_CASE_NAMES = [\n \"timestep_presaer_ZM_10s\",\n \"timestep_presaer_CLUBB_MG2_10s\",\n \"timestep_presaer_CLUBB_MG2_10s_ZM_10s\",\n \"timestep_presaer_cld_10s\",\n \"timestep_presaer_all_10s\",\n \"timestep_presaer_ZM_10s_lower_tau\",\n \"timestep_presaer_CLUBB_MG2_10s_ZM_10s_lower_tau\",\n \"timestep_presaer_cld_10s_lower_tau\",\n \"timestep_presaer_all_10s_lower_tau\",\n ]\n SHORT_TEST_CASE_NAMES = [\n \"ZM10PA\",\n \"CLUBBMICRO10PA\",\n \"CLUBBMICRO10ZM10PA\",\n \"CLD10PA\",\n \"ALL10PA\",\n \"ZM10LTPA\",\n \"CLUBBMICRO10ZM10LTPA\",\n \"CLD10LTPA\",\n \"ALL10LTPA\",\n ]\n STYLES = {\n \"CLUBBMICRO10PA\": ('indigo', '-'),\n \"ALL10PA\": ('dimgrey', '-'),\n \"ZM10PA\": ('g', '-'),\n \"CLUBBMICRO10ZM10PA\": ('saddlebrown', '-'),\n \"CLD10PA\": ('slateblue', '-'),\n \"ALL10LTPA\": ('dimgrey', '-.'),\n \"ZM10LTPA\": ('g', '-.'),\n \"CLUBBMICRO10ZM10LTPA\": ('saddlebrown', '-.'),\n \"CLD10LTPA\": ('slateblue', '-.'),\n }\nelif FOCUS_PRECIP:\n REF_CASE_NAME = \"timestep_ctrl\"\n TEST_CASE_NAMES = [\n \"timestep_MG2_10s\",\n# \"timestep_CLUBB_10s_MG2_10s\",\n# \"timestep_CLUBB_MG2_60s\",\n \"timestep_CLUBB_MG2_10s\",\n# \"timestep_all_10s\",\n# \"timestep_all_300s\",\n \"timestep_precip_grad\",\n \"timestep_precip_grad_MG2_10s\",\n \"timestep_precip_grad_CLUBB_MG2_10s\",\n ]\n SHORT_TEST_CASE_NAMES = [\n \"MICRO10\",\n# \"CLUBB10MICRO10\",\n# \"CLUBBMICRO60\",\n \"CLUBBMICRO10\",\n# \"ALL10\",\n# \"ALL300\",\n \"PFMG\",\n \"PFMGMICRO10\",\n \"PFMGCLUBBMICRO10\",\n ]\n STYLES = {\n \"MICRO10\": ('r', '-'),\n# \"CLUBB10MICRO10\": ('maroon', '-'),\n# \"CLUBBMICRO60\": ('indigo', '--'),\n \"CLUBBMICRO10\": ('indigo', '-'),\n# \"ALL10\": ('dimgrey', '-'),\n# \"ALL300\": ('dimgrey', ':'),\n \"PFMG\": ('k', '-.'),\n \"PFMGMICRO10\": ('r', '-.'),\n \"PFMGCLUBBMICRO10\": ('indigo', '-.'),\n }\nelse:\n REF_CASE_NAME = \"timestep_ctrl\"\n TEST_CASE_NAMES = [\n \"timestep_dyn_10s\",\n \"timestep_CLUBB_10s\",\n \"timestep_MG2_10s\",\n \"timestep_CLUBB_10s_MG2_10s\",\n \"timestep_CLUBB_MG2_Strang\",\n \"timestep_CLUBB_MG2_Strang_60s\",\n \"timestep_CLUBB_MG2_60s\",\n \"timestep_CLUBB_MG2_10s\",\n \"timestep_all_10s\",\n \"timestep_all_60s\",\n \"timestep_all_300s\",\n \"timestep_all_rad_10s\",\n ]\n SHORT_TEST_CASE_NAMES = [\n \"DYN10\",\n \"CLUBB10\",\n \"MICRO10\",\n \"CLUBB10MICRO10\",\n \"CLUBBMICROSTR\",\n \"CLUBBMICROSTR60\",\n \"CLUBBMICRO60\",\n \"CLUBBMICRO10\",\n \"ALL10\",\n \"ALL60\",\n \"ALL300\",\n \"ALLRAD10\",\n ]\n STYLES = {\n \"DYN10\": ('y', '-'),\n \"CLUBB10\": ('b', '-'),\n \"MICRO10\": ('r', '-'),\n \"CLUBB10MICRO10\": ('maroon', '-'),\n \"CLUBBMICROSTR\": ('m', '-'),\n \"CLUBBMICROSTR60\": ('m', '--'),\n \"CLUBBMICRO60\": ('indigo', '--'),\n \"CLUBBMICRO10\": ('indigo', '-'),\n \"ALL10\": ('dimgrey', '-'),\n \"ALL60\": ('dimgrey', '--'),\n \"ALL300\": ('dimgrey', ':'),\n \"ALLRAD10\": ('orange', '-'),\n }\n\nnum_tests = len(TEST_CASE_NAMES)\n\nsuffix = '_d{}-d{}'.format(day_str(START_DAY), day_str(END_DAY))\n\nif FOCUS_PRECIP:\n suffix += '_precip'\nif USE_PRESAER:\n suffix += '_presaer'\nif TROPICS_ONLY:\n if LAND_TROPICS:\n suffix += '_lndtropics'\n else:\n suffix += '_tropics'\n\nlog_file = open(\"plot_precip_log{}.txt\".format(suffix), 'w')\n\nout_file_template = \"{}.freq.short.d{}-d{}.nc\"\n\nfirst_file_name = out_file_template.format(REF_CASE_NAME, day_str(START_DAY),\n day_str(END_DAY))\n\nfirst_file = nc4.Dataset(join(OUTPUT_DIR, first_file_name), 'r')\nncol = len(first_file.dimensions['ncol'])\nnbins = len(first_file.dimensions['nbins'])\nbin_lower_bounds = first_file['bin_lower_bounds'][:]\nbin_width = np.log(bin_lower_bounds[2] / bin_lower_bounds[1])\nlat = first_file['lat'][:]\nlon = first_file['lon'][:]\narea = first_file['area'][:]\n# For tropics_only cases, just use a weight of 0 for all other columns.\nif TROPICS_ONLY:\n if LAND_TROPICS:\n # Just pick a random file with the same grid as the run.\n landfrac_file_name = '/p/lustre2/santos36/timestep_monthly_avgs/timestep_ctrl.0001-01.nc'\n landfrac_file = nc4.Dataset(landfrac_file_name, 'r')\n landfrac = landfrac_file['LANDFRAC'][0,:]\n for i in range(ncol):\n if np.abs(lat[i]) > 30.:\n area[i] = 0.\n else:\n area[i] *= landfrac[i]\n landfrac_file.close()\n else:\n for i in range(ncol):\n if np.abs(lat[i]) > 30.:\n area[i] = 0.\narea_sum = area.sum()\nweights = area/area_sum\nfirst_file.close()\n\nref_sample_num_total = 0\ntest_sample_num_totals = [0 for i in range(num_tests)]\n\nprec_vars = (\"PRECC\", \"PRECL\", \"PRECT\")\n\nref_num_avgs = {}\nref_amount_avgs = {}\nfor var in prec_vars:\n ref_num_avgs[var] = np.zeros((nbins,))\n ref_amount_avgs[var] = np.zeros((nbins,))\n\ntest_num_avgs = [{} for i in range (num_tests)]\ntest_amount_avgs = [{} for i in range (num_tests)]\nfor i in range(num_tests):\n for var in prec_vars:\n test_num_avgs[i][var] = np.zeros((nbins,))\n test_amount_avgs[i][var] = np.zeros((nbins,))\n\nout_file_name = out_file_template.format(REF_CASE_NAME, day_str(START_DAY),\n day_str(END_DAY))\nout_file = nc4.Dataset(join(OUTPUT_DIR, out_file_name), 'r')\n\nref_sample_num_total += out_file.sample_num\n\nfor var in prec_vars:\n num_name = \"{}_num\".format(var)\n amount_name = \"{}_amount\".format(var)\n for j in range(ncol):\n ref_num_avgs[var] += out_file[num_name][j,:] * weights[j]\n for j in range(ncol):\n ref_amount_avgs[var] += out_file[amount_name][j,:] * weights[j]\n\nfor i in range(num_tests):\n out_file_name = out_file_template.format(TEST_CASE_NAMES[i], day_str(START_DAY),\n day_str(END_DAY))\n out_file = nc4.Dataset(join(OUTPUT_DIR, out_file_name), 'r')\n\n test_sample_num_totals[i] += out_file.sample_num\n\n for var in prec_vars:\n num_name = \"{}_num\".format(var)\n amount_name = \"{}_amount\".format(var)\n for j in range(ncol):\n test_num_avgs[i][var] += out_file[num_name][j,:] * weights[j]\n for j in range(ncol):\n test_amount_avgs[i][var] += out_file[amount_name][j,:] * weights[j]\n\nfor var in prec_vars:\n ref_num_avgs[var] /= ref_sample_num_total\n ref_amount_avgs[var] /= ref_sample_num_total\n for i in range(num_tests):\n test_num_avgs[i][var] /= test_sample_num_totals[i]\n test_amount_avgs[i][var] /= test_sample_num_totals[i]\n\n# Threshold for precipitation to be considered \"extreme\", in mm/day.\nPRECE_THRESHOLD = 97.\nibinthresh = -1\nfor i in range(nbins):\n if bin_lower_bounds[i] > PRECE_THRESHOLD:\n ibinthresh = i\n break\nif ibinthresh == -1:\n print(\"Warning: extreme precip threshold greater than largest bin bound.\")\n\nfor var in prec_vars:\n # Leave out zero bin from loglog plot.\n plt.loglog(bin_lower_bounds[1:], ref_num_avgs[var][1:], 'k')\n for i in range(num_tests):\n plt.loglog(bin_lower_bounds[1:], test_num_avgs[i][var][1:],\n color=STYLES[SHORT_TEST_CASE_NAMES[i]][0],\n linestyle=STYLES[SHORT_TEST_CASE_NAMES[i]][1])\n plt.title(\"Frequency distribution of precipitation (days {}-{})\".format(\n day_str(START_DAY), day_str(END_DAY)))\n plt.xlabel(\"Precipitation intensity (mm/day)\")\n plt.ylabel(\"fraction\")\n plt.savefig(\"{}_freq{}.png\".format(var, suffix))\n plt.close()\n\n plt.semilogx(bin_lower_bounds[1:], ref_amount_avgs[var][1:] / bin_width, 'k')\n if var == \"PRECT\":\n print(\"Extreme precipitation rate for reference: \",\n ref_amount_avgs[var][ibinthresh:].sum(),\n file=log_file)\n for i in range(num_tests):\n plt.semilogx(bin_lower_bounds[1:], test_amount_avgs[i][var][1:] / bin_width,\n color=STYLES[SHORT_TEST_CASE_NAMES[i]][0],\n linestyle=STYLES[SHORT_TEST_CASE_NAMES[i]][1])\n if var == \"PRECT\":\n print(\"Extreme precipitation rate for \", SHORT_TEST_CASE_NAMES[i], \": \",\n test_amount_avgs[i][var][ibinthresh:].sum(), \"(Diff = \",\n test_amount_avgs[i][var][ibinthresh:].sum() - ref_amount_avgs[var][ibinthresh:].sum(), \")\",\n file=log_file)\n plt.title(\"Amounts of precipitation (days {}-{})\".format(\n day_str(START_DAY), day_str(END_DAY)))\n plt.xlabel(\"Precipitation intensity (mm/day)\")\n plt.ylabel(\"Average precipitation amount (mm/day)\")\n plt.savefig(\"{}_amount{}.png\".format(var, suffix))\n plt.close()\n\nlog_file.close()\n" }, { "alpha_fraction": 0.602809727191925, "alphanum_fraction": 0.6781609058380127, "avg_line_length": 36.28571319580078, "blob_id": "37ee7ee3bb59e9cc3823a340155467229346076b", "content_id": "588be35a063c25998754eea2c15cd25c4a660a6b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 783, "license_type": "permissive", "max_line_length": 76, "num_lines": 21, "path": "/regrid_precip_files_monthly.sh", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nREMAP_FILE=/usr/gdata/climdat/maps/map_ne30np4_to_fv128x256_aave.20160301.nc\nIN_DIR=/p/lscratchh/santos36/timestep_precip\nOUT_DIR=/p/lscratchh/santos36/timestep_precip_lat_lon\nCASE_NAMES=\"timestep_ctrl timestep_all_10s\"\n#MONTHS=\"01 02 03 04 05 06 07 08 09 10 11 12\"\nMONTHS=\"01 02\"\n\nfor case_name in $CASE_NAMES; do\n date\n echo \"On case $case_name\"\n for month in $MONTHS; do\n file_name=$case_name.freq.0004-$month.nc\n tmp_file_name=$case_name.freq.0004-$month-tmp.nc\n ncpdq -a nbins,ncol $IN_DIR/$file_name $IN_DIR/$tmp_file_name\n ncremap -m $REMAP_FILE -O $OUT_DIR $IN_DIR/$tmp_file_name\n ncpdq -a lat,lon,nbins $OUT_DIR/$tmp_file_name $OUT_DIR/$file_name\n rm $IN_DIR/$tmp_file_name $OUT_DIR/$tmp_file_name\n done\ndone\n" }, { "alpha_fraction": 0.5744373202323914, "alphanum_fraction": 0.5928143858909607, "avg_line_length": 37.74399948120117, "blob_id": "60802afcea69c1e76e980baa986ac716ae36e1c0", "content_id": "4f98ac7df09cf4cd53143ba9c5ade48844c38bbd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4843, "license_type": "permissive", "max_line_length": 132, "num_lines": 125, "path": "/plot_taylor_timestep.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os\n\n# Note: uses genutil from UV-CDAT.\nimport numpy as np\nimport genutil\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport utils\nimport core_parameter\nfrom taylor_diagram import TaylorDiagram\n\n# These functions taken from metrics in E3SM diags\ndef corr(model, obs, axis='xy'):\n corr = -np.infty\n try:\n corr = float(genutil.statistics.correlation(\n model, obs, axis=axis, weights='generate'))\n except Exception as err:\n print(err)\n\n return corr\n\ndef std(variable, axis='xy'):\n std = -np.infty\n try:\n std = float(genutil.statistics.std(\n variable, axis=axis, weights='generate'))\n except Exception as err:\n print(err)\n\n return std\n\nparameter = core_parameter.CoreParameter()\nparameter.test_data_path = '/p/lscratchh/santos36/timestep_monthly_avgs_lat_lon/'\nparameter.reference_data_path = '/p/lscratchh/santos36/timestep_monthly_avgs_lat_lon/'\nparameter.ref_name = 'timestep_ctrl'\nparameter.results_dir = '/g/g14/santos36/Timesteps/'\nparameter.seasons = ['ANN']\nparameter.variables = ['PRECT', 'PRECL', 'PRECC', 'PSL', 'SWCF', 'LWCF',\n 'TGCLDLWP', 'TGCLDIWP', 'CLDTOT', 'U10', 'OMEGA500', 'TS']\n\nref_data = utils.dataset.Dataset(parameter, ref=True)\n\nmarker = ['o', 'd', '+', 's', '>', '<', 'v', '^', 'x', 'h', 'X', 'H'] \ncolor = ['k', 'r', 'g', 'y', 'm']\n\nmatplotlib.rcParams.update({'font.size': 20})\nfig = plt.figure(figsize=(9,8))\nrefstd = 1.0\ntaylordiag = TaylorDiagram(refstd, fig=fig, rect=111, label=\"REF\")\nax = taylordiag._ax\n\ncase_colors = {\n 'timestep_all_10s': 'k',\n 'timestep_ctrl_ne16': 'r',\n 'timestep_ctrl_y04-y07': 'g',\n}\n\nfor season in parameter.seasons:\n # Will not actually work for multiple seasons as written due to having only\n # one figure.\n print('Season: {}'.format(season))\n\n for test_name in ('timestep_all_10s', 'timestep_ctrl_ne16', 'timestep_ctrl_y04-y07'):\n parameter.test_name = test_name\n test_data = utils.dataset.Dataset(parameter, test=True)\n\n irow = 0\n\n for var in parameter.variables:\n print('Variable: {}'.format(var))\n parameter.var_id = var\n\n mv1 = test_data.get_climo_variable(var, season)\n mv2 = ref_data.get_climo_variable(var, season)\n\n parameter.viewer_descr[var] = mv1.long_name if hasattr(\n mv1, 'long_name') else 'No long_name attr in test data.'\n\n region = 'global'\n if var == 'TS':\n region = 'land'\n land_frac = test_data.get_climo_variable('LANDFRAC', season)\n ocean_frac = test_data.get_climo_variable('OCNFRAC', season)\n\n mv1_domain = utils.general.select_region(region, mv1, land_frac, ocean_frac, parameter)\n mv2_domain = utils.general.select_region(region, mv2, land_frac, ocean_frac, parameter)\n\n metrics = dict()\n metrics['ref_regrid'] = {\n 'std': float(std(mv2_domain))\n }\n metrics['test_regrid'] = {\n 'std': float(std(mv1_domain))\n }\n metrics['misc'] = {\n 'corr': float(corr(mv1_domain, mv2_domain))\n }\n\n std_norm, correlation = metrics['test_regrid']['std']/metrics['ref_regrid']['std'], metrics['misc']['corr']\n taylordiag.add_sample(std_norm, correlation, marker=marker[irow], c=color[0], ms=10,\n label=parameter.viewer_descr[var], markerfacecolor='None',\n markeredgecolor=case_colors[test_name], linestyle='None')\n irow += 1\n\n if test_name == 'timestep_all_10s':\n # Add a legend to the figure.\n fig.legend(taylordiag.samplePoints,\n [\"Reference\", \"Total Precipitation\", \"Large-scale Precipitation\",\n \"Convective Precipitation\",\n \"Sea Level Pressure\", \"Shortwave Cloud Forcing\", \"Longwave Cloud Forcing\",\n \"Liquid Water Path\", \"Ice Water Path\",\n \"Cloud Fraction\",\n \"10m wind speed\", \"500 mb Vertical Velocity\", \"Land Surface Temperature\"],\n numpoints=1, loc='center right', bbox_to_anchor=(1.0, .75), prop={'size':10})\n# model_text = 'Test Model: ' + parameter.test_name\n# ax.text(0.6, 1, model_text, ha='left', va='center', transform=ax.transAxes, color=color[0], fontsize=12)\n# ax.text(0.6, 0.95, 'Ref. Model: ' + parameter.ref_name, ha='left', va='center', transform=ax.transAxes, color='k', fontsize=12)\n\n# plt.title(season + ': Spatial Variability', y=1.08)\n# plt.title('Taylor Diagram - Spatial Variability', y=1.08)\n fig.savefig(os.path.join(parameter.results_dir, season + '_metrics_taylor_diag_timesteps.png'))\n" }, { "alpha_fraction": 0.5971169471740723, "alphanum_fraction": 0.6012813448905945, "avg_line_length": 39.19313430786133, "blob_id": "df1285aa444b32f4fd662eb0719301eb658f976e", "content_id": "0e920f37a4647d7530b1d7abb5890f7025e3fa8b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9365, "license_type": "permissive", "max_line_length": 100, "num_lines": 233, "path": "/e3sm_case_output.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport numpy as np\nimport netCDF4 as nc4\n\ndef day_str(day):\n \"Given an integer day, return the 2-digit day string used for file names.\"\n return \"{:02d}\".format(day)\n\ndef time_str(time):\n \"Given an integer time in seconds, return the 5-digit string used in file names.\"\n return \"{:05d}\".format(time)\n\nclass E3SMCaseOutput:\n\n \"\"\"Class that contains information about an E3SM timestep study case.\n\n Methods:\n __init__\n get_daily_file_name\n get_daily_values\n day_is_available\n compare_daily_averages\n\n Properties:\n case_name\n short_name\n daily_dir\n \"\"\"\n\n def __init__(self, case_name, short_name, daily_dir, start_day, end_day):\n \"\"\"Initialize a case from case directory and human-readable name.\n\n All arguments are used to set the corresponding properties.\n \"\"\"\n self._case_name = case_name\n self._short_name = short_name\n self._daily_dir = daily_dir\n self._start_day = start_day\n self._end_day = end_day\n\n @property\n def case_name(self):\n \"\"\"Name of case (as understood by CIME).\"\"\"\n return self._case_name\n\n @property\n def short_name(self):\n \"\"\"Short human-readable name for log/plotting purposes.\"\"\"\n return self._short_name\n\n @property\n def daily_dir(self):\n \"\"\"Location of directory where daily averages are located.\"\"\"\n return self._daily_dir\n\n @property\n def start_day(self):\n \"\"\"First day for which output is available.\"\"\"\n return self._start_day\n\n @property\n def end_day(self):\n \"\"\"Last day for which output is available.\"\"\"\n return self._end_day\n\n def day_is_available(self, day):\n \"\"\"Returns True if the given day has available output for this case.\"\"\"\n return self.start_day <= day and self.end_day >= day\n\n def get_daily_file_name(self, day):\n \"\"\"Name of the file where the average values for a given day are stored.\n\n Arguments:\n day - Integer representing the desired day.\n \"\"\"\n assert self.day_is_available(day)\n return '{}/{}.0001-01-{}.nc'.format(self.daily_dir, self.case_name,\n day_str(day))\n\n def get_monthly_file_name(self, month, year):\n \"\"\"Name of the file where the average values for a given month are stored.\n\n Arguments:\n month - Integer representing the desired month.\n year - Integer representing year containing the desired month.\n \"\"\"\n #assert self.day_is_available(day)\n return '{}/{}.00{}-{}.nc'.format(self.daily_dir, self.case_name,\n day_str(year), day_str(month))\n\n def get_daily_values(self, day, varnames):\n \"\"\"Retrieve the daily averages for a set of variables.\n\n Arguments:\n day - Integer corresponding to the desired day.\n varnames - Names of variables being read in.\n\n The output of this function is a dictionary associating the variable\n names to arrays containing the associated values. The time dimension is\n removed from the output arrays, but the shape is otherwise untouched.\n \"\"\"\n assert self.day_is_available(day)\n variables = dict()\n ncfile = nc4.Dataset(self.get_daily_file_name(day), 'r')\n for varname in varnames:\n ncvar = ncfile[varname]\n var_dims = ncvar.get_dims()\n time_ind = -1\n for i in range(len(var_dims)):\n if var_dims[i].name == 'time':\n time_ind = i\n break\n new_dims = list(ncvar.shape)\n if time_ind != -1:\n del new_dims[time_ind]\n variables[varname] = np.zeros(new_dims)\n if time_ind == -1:\n variables[varname] = ncvar[...]\n else:\n variables[varname] = np.squeeze(ncvar, axis=time_ind)\n if \"missing_value\" in ncvar.ncattrs():\n miss = ncvar.missing_value\n # Following appears not to work due to rounding errors.\n # variables[varname] += np.where(variables[varname] == miss, 0., variables[varname])\n # Kludge for optical depths.\n variables[varname] = np.where(variables[varname] > 1.e35, 0., variables[varname])\n ncfile.close()\n return variables\n\n def get_monthly_values(self, month, year, varnames):\n \"\"\"Retrieve the monthly averages for a set of variables.\n\n Arguments:\n month - Integer corresponding to the desired month.\n year - Integer representing year containing the desired month.\n varnames - Names of variables being read in.\n\n The output of this function is a dictionary associating the variable\n names to arrays containing the associated values. The time dimension is\n removed from the output arrays, but the shape is otherwise untouched.\n \"\"\"\n # assert self.day_is_available(day)\n variables = dict()\n ncfile = nc4.Dataset(self.get_monthly_file_name(month, year), 'r')\n for varname in varnames:\n ncvar = ncfile[varname]\n var_dims = ncvar.get_dims()\n time_ind = -1\n for i in range(len(var_dims)):\n if var_dims[i].name == 'time':\n time_ind = i\n break\n new_dims = list(ncvar.shape)\n if time_ind != -1:\n del new_dims[time_ind]\n variables[varname] = np.zeros(new_dims)\n if time_ind == -1:\n variables[varname] = ncvar[...]\n else:\n variables[varname] = np.squeeze(ncvar, axis=time_ind)\n if \"missing_value\" in ncvar.ncattrs():\n miss = ncvar.missing_value\n # Following appears not to work due to rounding errors.\n # variables[varname] += np.where(variables[varname] == miss, 0., variables[varname])\n # Kludge for optical depths.\n variables[varname] = np.where(variables[varname] > 1.e35, 0., variables[varname])\n ncfile.close()\n return variables\n\n def compare_daily_averages(self, test_cases, day, varnames):\n \"\"\"Compares the daily averages of this case to a number of other cases.\n\n Arguments:\n test_cases - Other case objects to compare this case to.\n day - Integer corresponding to the desired day.\n varnames - Names of variables being read in.\n\n The output of this function is a tuple of size 3. The first output is a\n dictionary containing the average values for this case, as in the\n get_daily_values method. The second output is a list of dictionaries\n containing the output values for each test case, in the same order as\n they were given in the test_cases argument. The third output is a list\n of dictionaries corresponding to the differences between each test case\n and this case.\n\n For test cases that do not extend to the given day, the corresponding\n item in the second and third output lists will be None.\n\n \"\"\"\n ref_time_avg = self.get_daily_values(day, varnames)\n test_time_avgs = []\n diff_time_avgs = []\n for i in range(len(test_cases)):\n if test_cases[i].day_is_available(day):\n test_time_avgs.append(test_cases[i].get_daily_values(day, varnames))\n next_diff_time = dict()\n for varname in varnames:\n next_diff_time[varname] = test_time_avgs[i][varname] - ref_time_avg[varname]\n diff_time_avgs.append(next_diff_time)\n else:\n test_time_avgs.append(None)\n diff_time_avgs.append(None)\n return (ref_time_avg, test_time_avgs, diff_time_avgs)\n\n def compare_monthly_averages(self, test_cases, month, year, varnames):\n \"\"\"Compares the monthly averages of this case to a number of other cases.\n\n Arguments:\n test_cases - Other case objects to compare this case to.\n month - Integer corresponding to the desired month.\n year - Integer representing year containing the desired month.\n varnames - Names of variables being read in.\n\n The output of this function is a tuple of size 3. The first output is a\n dictionary containing the average values for this case, as in the\n get_monthly_values method. The second output is a list of dictionaries\n containing the output values for each test case, in the same order as\n they were given in the test_cases argument. The third output is a list\n of dictionaries corresponding to the differences between each test case\n and this case.\n\n \"\"\"\n ref_time_avg = self.get_monthly_values(month, year, varnames)\n test_time_avgs = []\n diff_time_avgs = []\n for i in range(len(test_cases)):\n test_time_avgs.append(test_cases[i].get_monthly_values(month, year, varnames))\n next_diff_time = dict()\n for varname in varnames:\n next_diff_time[varname] = test_time_avgs[i][varname] - ref_time_avg[varname]\n diff_time_avgs.append(next_diff_time)\n return (ref_time_avg, test_time_avgs, diff_time_avgs)\n" }, { "alpha_fraction": 0.5076412558555603, "alphanum_fraction": 0.5491318106651306, "avg_line_length": 34.92757034301758, "blob_id": "d02cfd704f412292dcb654c5bf8d91cf0a736c0e", "content_id": "2cfb81d9dc8fd434dff694cecbbd6dea7be29e10", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15377, "license_type": "permissive", "max_line_length": 131, "num_lines": 428, "path": "/plot_compare_2D_vars_monthly.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom os.path import join\n\nfrom functools import partial\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import basemap\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import E3SMCaseOutput, day_str\n\ncmap = plt.get_cmap('coolwarm')\nbmap = basemap.Basemap(lon_0=180.)\n\ndef forward(a):\n a = np.deg2rad(a)\n return np.sin(a)\n\ndef inverse(a):\n a = np.arcsin(a)\n return np.rad2deg(a)\n\nSTART_YEAR = 1\nSTART_MONTH = 3\nEND_YEAR = 4\nEND_MONTH = 2\n\nMONTHLY_FILE_LOC = \"/p/lscratchh/santos36/timestep_monthly_avgs_lat_lon\"\n\nUSE_PRESAER = False\n\nPLOT_FILE_TYPE = \"png\"\n\nnmonths = (END_YEAR - START_YEAR) * 12 - (START_MONTH - 1) + END_MONTH\nimonths = list(range(nmonths))\ncurr_month = START_MONTH\ncurr_year = START_YEAR\nmonths = []\nyears = []\nfor i in range(nmonths):\n months.append(curr_month)\n years.append(curr_year)\n curr_month += 1\n if curr_month > 12:\n curr_month = 1\n curr_year += 1\n\n\nsuffix = '_y{}m{}-y{}m{}'.format(day_str(START_YEAR),\n day_str(START_MONTH),\n day_str(END_YEAR),\n day_str(END_MONTH))\nif USE_PRESAER:\n suffix += '_presaer'\n\nlog_file = open(\"plot_2D_log{}.txt\".format(suffix), 'w')\n\nif USE_PRESAER:\n REF_CASE = E3SMCaseOutput(\"timestep_presaer_ctrl\", \"CTRLPA\", MONTHLY_FILE_LOC, START_MONTH, END_MONTH)\n TEST_CASES = [\n ]\nelse:\n REF_CASE = E3SMCaseOutput(\"timestep_ctrl\", \"CTRL\", MONTHLY_FILE_LOC, START_MONTH, END_MONTH)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_all_10s\", \"ALL10\", MONTHLY_FILE_LOC, START_MONTH, END_MONTH),\n ]\n\nrfile0 = nc4.Dataset(REF_CASE.get_monthly_file_name(START_MONTH, START_YEAR), 'r')\nlat = rfile0['lat'][:]\nlon = rfile0['lon'][:]\nlev = rfile0['lev'][:]\nnlat = len(lat)\nnlon = len(lon)\nnlev = len(lev)\nrfile0.close()\n\nmonth_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\nmonth_weights = [month_days[months[imonth] - 1] for imonth in imonths]\nweight_norm = sum(month_weights)\nmonth_weights = [weight / weight_norm for weight in month_weights]\n\ndef get_overall_averages(ref_case, test_cases, months, varnames, scales):\n case_num = len(test_cases)\n ref_means = dict()\n for name in varnames:\n if name in vars_3D:\n ref_means[name] = np.zeros((nlev, nlat, nlon))\n else:\n ref_means[name] = np.zeros((nlat, nlon))\n test_means = []\n diff_means = []\n for case in test_cases:\n next_test_means = dict()\n next_diff_means = dict()\n for name in varnames:\n if name in vars_3D:\n next_test_means[name] = np.zeros((nlev, nlat, nlon))\n next_diff_means[name] = np.zeros((nlev, nlat, nlon))\n else:\n next_test_means[name] = np.zeros((nlat, nlon))\n next_diff_means[name] = np.zeros((nlat, nlon))\n test_means.append(next_test_means)\n diff_means.append(next_diff_means)\n\n varnames_read = [name for name in varnames if name != \"PRECT\" and name != \"TAU\"]\n if \"PRECT\" in varnames:\n if \"PRECL\" not in varnames:\n varnames_read.append(\"PRECL\")\n if \"PRECC\" not in varnames:\n varnames_read.append(\"PRECC\")\n if \"TAU\" in varnames:\n if \"TAUX\" not in varnames:\n varnames_read.append(\"TAUX\")\n if \"TAUY\" not in varnames:\n varnames_read.append(\"TAUY\")\n\n for imonth in imonths:\n month = months[imonth]\n year = years[imonth]\n ref_monthly, test_monthly, diff_monthly = ref_case.compare_monthly_averages(test_cases, month, year, varnames_read)\n if \"PRECT\" in varnames:\n ref_monthly[\"PRECT\"] = ref_monthly[\"PRECL\"] + ref_monthly[\"PRECC\"]\n for icase in range(case_num):\n test_monthly[icase][\"PRECT\"] = test_monthly[icase][\"PRECL\"] + test_monthly[icase][\"PRECC\"]\n diff_monthly[icase][\"PRECT\"] = diff_monthly[icase][\"PRECL\"] + diff_monthly[icase][\"PRECC\"]\n if \"TAU\" in varnames:\n ref_monthly[\"TAU\"] = np.sqrt(ref_monthly[\"TAUX\"]**2 + ref_monthly[\"TAUY\"]**2)\n for icase in range(case_num):\n test_monthly[icase][\"TAU\"] = np.sqrt(test_monthly[icase][\"TAUX\"]**2 + test_monthly[icase][\"TAUY\"]**2)\n diff_monthly[icase][\"TAU\"] = test_monthly[icase][\"TAU\"] - ref_monthly[\"TAU\"]\n for name in varnames:\n if name in vars_3D:\n for ilev in range(nlev):\n ref_means[name][ilev,:,:] += month_weights[imonth] * ref_monthly[name][ilev,:,:]\n for icase in range(case_num):\n test_means[icase][name][ilev,:,:] += month_weights[imonth] * test_monthly[icase][name][ilev,:,:]\n diff_means[icase][name][ilev,:,:] += month_weights[imonth] * diff_monthly[icase][name][ilev,:,:]\n else:\n ref_means[name] += month_weights[imonth] * ref_monthly[name]\n for icase in range(case_num):\n test_means[icase][name] += month_weights[imonth] * test_monthly[icase][name]\n diff_means[icase][name] += month_weights[imonth] * diff_monthly[icase][name]\n\n for name in varnames:\n ref_means[name] *= scales[name]\n for icase in range(case_num):\n test_means[icase][name] *= scales[name]\n diff_means[icase][name] *= scales[name]\n\n return (ref_means, test_means, diff_means)\n\nplot_names = {\n 'LWCF': \"long wave cloud forcing\",\n 'SWCF': \"short wave cloud forcing\",\n 'PRECC': \"convective precipitation\",\n 'PRECL': \"large-scale precipitation\",\n 'PRECE': \"extreme precipitation\",\n 'PRECT': \"total precipitation\",\n 'TGCLDIWP': \"ice water path\",\n 'TGCLDLWP': \"liquid water path\",\n 'CLDTOT': \"cloud area fraction\",\n 'CLDLOW': \"low cloud area fraction\",\n 'CLDMED': \"mid-level cloud area fraction\",\n 'CLDHGH': \"high cloud area fraction\",\n 'LHFLX': \"latent heat flux\",\n 'SHFLX': \"sensible heat flux\",\n 'TAU': \"surface wind stress\",\n 'TS': \"surface temperature\",\n 'PSL': \"sea level pressure\",\n 'OMEGA500': \"vertical velocity at 500 mb\",\n 'U10': \"10 meter wind speed\",\n 'RELHUM': \"surface relative humidity\",\n 'Q': \"specific humidity\",\n 'CLDLIQ': \"lowest level cloud liquid\",\n 'T': \"lowest level temperature\",\n 'CLOUD': \"lowest level cloud fraction\",\n 'TMQ': \"precipitable water\",\n}\n\nunits = {\n 'LWCF': r'$W/m^2$',\n 'SWCF': r'$W/m^2$',\n 'PRECC': r'$mm/day$',\n 'PRECL': r'$mm/day$',\n 'PRECE': r'$mm/day$',\n 'PRECT': r'$mm/day$',\n 'TGCLDIWP': r'$g/m^2$',\n 'TGCLDLWP': r'$g/m^2$',\n 'AODABS': r'units?',\n 'AODUV': r'units?',\n 'AODVIS': r'units?',\n 'FLDS': r'$W/m^2$',\n 'FLNS': r'$W/m^2$',\n 'FLNSC': r'$W/m^2$',\n 'FLNT': r'$W/m^2$',\n 'FLNTC': r'$W/m^2$',\n 'FLUT': r'$W/m^2$',\n 'FLUTC': r'$W/m^2$',\n 'FSDS': r'$W/m^2$',\n 'FSDSC': r'$W/m^2$',\n 'FSNS': r'$W/m^2$',\n 'FSNSC': r'$W/m^2$',\n 'FSNT': r'$W/m^2$',\n 'FSNTC': r'$W/m^2$',\n 'FSNTOA': r'$W/m^2$',\n 'FSNTOAC': r'$W/m^2$',\n 'FSUTOA': r'$W/m^2$',\n 'FSUTOAC': r'$W/m^2$',\n 'CLDTOT': r'fraction',\n 'CLDLOW': r'fraction',\n 'CLDMED': r'fraction',\n 'CLDHGH': r'fraction',\n 'OMEGA500': r'Pa/s',\n 'LHFLX': r'$W/m^2$',\n 'SHFLX': r'$W/m^2$',\n 'TAU': r'$N/m^2$',\n 'TAUX': r'$N/m^2$',\n 'TAUY': r'$N/m^2$',\n 'TS': r'$K$',\n 'PSL': r'$Pa$',\n 'U10': r'$m/s$',\n 'RELHUM': r'%',\n 'Q': r'$g/kg$',\n 'CLDLIQ': r\"$g/kg$\",\n 'T': r'$K$',\n 'CLOUD': r'$fraction$',\n 'TMQ': r'$kg/m^2$',\n}\nvarnames = list(units.keys())\n# Only can plot extreme precipitation for a subset of months.\nvarnames.remove('PRECE')\nscales = dict()\nfor name in varnames:\n scales[name] = 1.\nscales['TGCLDIWP'] = 1000.\nscales['TGCLDLWP'] = 1000.\nscales['PRECC'] = 1000.*86400.\nscales['PRECL'] = 1000.*86400.\nscales['PRECE'] = 1000.*86400.\nscales['PRECT'] = 1000.*86400.\nscales['Q'] = 1000.\nscales['CLDLIQ'] = 1000.\n\ndiff_lims = {\n 'OMEGA500': 0.05,\n 'TAU': 0.1,\n 'PRECC': 4.,\n 'PRECL': 4.,\n 'PRECT': 4.,\n 'PSL': 200.\n}\n\nvars_3D = [\n 'RELHUM',\n 'Q',\n 'CLDLIQ',\n 'T',\n 'CLOUD',\n]\n\nPRECIP_OUTPUT_DIR = \"/p/lustre2/santos36/timestep_precip_lat_lon/\"\n\nout_file_template = \"{}.freq.00{}-{}.nc\"\n\n# Threshold for precipitation to be considered \"extreme\", in mm/day.\nPRECE_THRESHOLD = 97.\n\ndef get_prece(case_name):\n file_name = out_file_template.format(case_name, day_str(START_YEAR), day_str(START_MONTH))\n precip_file = nc4.Dataset(join(PRECIP_OUTPUT_DIR, file_name), 'r')\n nbins = len(precip_file.dimensions['nbins'])\n bin_lower_bounds = precip_file['bin_lower_bounds'][:]\n precip_file.close()\n ibinthresh = -1\n for i in range(nbins):\n if bin_lower_bounds[i] > PRECE_THRESHOLD:\n ibinthresh = i\n break\n if ibinthresh == -1:\n print(\"Warning: extreme precip threshold greater than largest bin bound.\")\n prece = np.zeros((nlat, nlon))\n for imonth in imonths:\n month = months[imonth]\n year = years[imonth]\n file_name = out_file_template.format(case_name, day_str(year), day_str(month))\n precip_file = nc4.Dataset(join(PRECIP_OUTPUT_DIR, file_name), 'r')\n prece += precip_file[\"PRECT_amount\"][:,:,ibinthresh:].sum(axis=2)\n precip_file.close()\n return prece\n\n# Possible ways to extract a 2D section start here:\ndef identity(x):\n return x\n\ndef slice_at(level, x):\n return x[level,:,:]\n\nprint(\"Reading model output.\")\n\nvarnames_readhist = [name for name in varnames if name != \"PRECE\"]\n\nref_means, test_means, diff_means = get_overall_averages(REF_CASE, TEST_CASES, months, varnames_readhist, scales)\n\nprint(\"Reading extreme precipitation.\")\nif \"PRECE\" in varnames:\n ref_means[\"PRECE\"] = get_prece(REF_CASE.case_name)\n for icase in range(len(TEST_CASES)):\n test_means[icase][\"PRECE\"] = get_prece(TEST_CASES[icase].case_name)\n diff_means[icase][\"PRECE\"] = test_means[icase][\"PRECE\"] - ref_means[\"PRECE\"]\n\n# Should have this actually read from the plot_monthly_means output.\ndiff_global_means = {\n 'CLDHGH': -0.013678454026188875,\n 'CLDMED': -0.013005294090188389,\n 'CLDLOW': -0.026605262766560816,\n 'LWCF': -1.9367562045847697,\n 'PRECC': -0.20614114936695113,\n 'PRECL': 0.2874759111487673,\n 'PRECT': 0.08133476183460554,\n 'RELHUM': -0.6616496805116635,\n 'SWCF': 5.4882057901660515,\n 'TGCLDIWP': -0.34243353479029425,\n 'TGCLDLWP': 0.4189776935777987,\n}\n\nfor name in varnames:\n plot_name = name\n if name in plot_names:\n plot_name = plot_names[name]\n\n get_2D = identity\n if name in [\"RELHUM\", \"Q\", \"CLDLIQ\", \"T\", \"CLOUD\"]:\n get_2D = partial(slice_at, nlev-1)\n\n ref_plot_var = get_2D(ref_means[name])\n clim_val = [ref_plot_var.min(), ref_plot_var.max()]\n clim_diff = 0.\n for icase in range(len(TEST_CASES)):\n test_plot_var = get_2D(test_means[icase][name])\n diff_plot_var = get_2D(diff_means[icase][name])\n clim_val[0] = min(clim_val[0], test_plot_var.min())\n clim_val[1] = max(clim_val[1], test_plot_var.max())\n clim_diff = max(clim_diff, - diff_plot_var.min())\n clim_diff = max(clim_diff, diff_plot_var.max())\n\n if name in diff_lims:\n clim_diff = diff_lims[name]\n\n plt.pcolormesh(lon[:], lat[:], ref_plot_var)\n bmap.drawcoastlines()\n ax = plt.gca()\n ax.set_xticks([0., 90., 180., 270., 360.])\n ax.set_xticklabels(['0', '90E', '180', '90W', '0'])\n ax.set_yscale('function', functions=(forward, inverse))\n ax.set_yticks([60., 45., 30., 15., 0., -15., -30., -45., -60.])\n ax.set_yticklabels(['60N', '45N', '30N', '15N', '0', '15S', '30S', '45S', '60S'])\n# ax.set_yticks([60., 30., 0., -30., -60.])\n# ax.set_yticklabels(['60N', '30N', '0', '30S', '60S'])\n plt.axis('tight')\n plt.xlim([0., 360.])\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.title(\"{} for case {}\\n({}, months {}/{} - {}/{})\".format(plot_name, REF_CASE.short_name, units[name],\n day_str(START_MONTH), day_str(START_YEAR),\n day_str(END_MONTH), day_str(END_YEAR)))\n plt.savefig('{}_{}{}.{}'.format(name, REF_CASE.short_name, suffix,\n PLOT_FILE_TYPE))\n plt.close()\n\n for icase in range(len(TEST_CASES)):\n test_plot_var = get_2D(test_means[icase][name])\n diff_plot_var = get_2D(diff_means[icase][name])\n case_name = TEST_CASES[icase].short_name\n\n plt.pcolormesh(lon[:], lat[:], test_plot_var)\n bmap.drawcoastlines()\n ax = plt.gca()\n ax.set_xticks([0., 90., 180., 270., 360.])\n ax.set_xticklabels(['0', '90E', '180', '90W', '0'])\n ax.set_yscale('function', functions=(forward, inverse))\n ax.set_yticks([60., 45., 30., 15., 0., -15., -30., -45., -60.])\n ax.set_yticklabels(['60N', '45N', '30N', '15N', '0', '15S', '30S', '45S', '60S'])\n# ax.set_yticks([60., 30., 0., -30., -60.])\n# ax.set_yticklabels(['60N', '30N', '0', '30S', '60S'])\n plt.axis('tight')\n plt.xlim([0., 360.])\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.title(\"{} for case {}\\n({}, months {}/{} - {}/{})\".format(plot_name, case_name, units[name],\n day_str(START_MONTH), day_str(START_YEAR),\n day_str(END_MONTH), day_str(END_YEAR)))\n plt.savefig('{}_{}{}.{}'.format(name, case_name, suffix,\n PLOT_FILE_TYPE))\n plt.close()\n\n plt.pcolormesh(lon[:], lat[:], diff_plot_var, cmap=cmap)\n bmap.drawcoastlines()\n ax = plt.gca()\n ax.set_xticks([0., 90., 180., 270., 360.])\n ax.set_xticklabels(['0', '90E', '180', '90W', '0'])\n ax.set_yscale('function', functions=(forward, inverse))\n ax.set_yticks([60., 45., 30., 15., 0., -15., -30., -45., -60.])\n ax.set_yticklabels(['60N', '45N', '30N', '15N', '0', '15S', '30S', '45S', '60S'])\n# ax.set_yticks([60., 30., 0., -30., -60.])\n# ax.set_yticklabels(['60N', '30N', '0', '30S', '60S'])\n plt.axis('tight')\n plt.xlim([0., 360.])\n plt.colorbar()\n plt.clim(-clim_diff, clim_diff)\n if name in diff_global_means:\n unit_string = units[name]\n if unit_string == 'fraction':\n unit_string = ''\n else:\n unit_string = \" \" + unit_string\n mean_string = 'mean {:.2g}'.format(diff_global_means[name]) + unit_string\n else:\n mean_string = units[name]\n plt.title(\"Mean difference in {} for\\ncase {} ({}, months {}/{} - {}/{})\".format(plot_name, case_name, mean_string,\n day_str(START_MONTH), day_str(START_YEAR),\n day_str(END_MONTH), day_str(END_YEAR)))\n plt.savefig('{}_diff_{}{}.{}'.format(name, case_name, suffix,\n PLOT_FILE_TYPE))\n plt.close()\n" }, { "alpha_fraction": 0.5204152464866638, "alphanum_fraction": 0.6477508544921875, "avg_line_length": 36.0512809753418, "blob_id": "de63fb3b28fd6885e9f3f2046e98bcdab60d3f6c", "content_id": "a239569b022b36c4640366b9473033c672511a93", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1445, "license_type": "permissive", "max_line_length": 151, "num_lines": 39, "path": "/create_precip_hourly.sh", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nCASE_NAMES=\"timestep_ctrl\"\nMONTHS=\"03 04 05 06 07 08 09 10 11 12\"\nOUTPUT_DIR=/p/lscratchh/santos36/timestep_precip\n\ntimes=\"00000 03600 07200 10800 14400 18000 21600 25200 28800 32400 36000 39600 43200 46800 50400 54000 57600 61200 64800 68400 72000 75600 79200 82800\"\n\nfor case_name in $CASE_NAMES; do\n echo \"On case $case_name\"\n case_dir=/p/lscratchh/santos36/ACME/$case_name/run\n for month in $MONTHS; do\n date\n echo \"On month $month.\"\n for time in $times; do\n echo \"Time $time.\"\n outfile=\"$OUTPUT_DIR/$case_name.hourly.0003-$month-$time.nc\"\n ncra -v PRECC,PRECL,PRECSC,PRECSL $case_dir/$case_name.cam.h0.0003-$month-*-$time.nc $outfile\n ncks -A -v lat,lon,area /p/lscratchh/santos36/timestep_monthly_avgs/timestep_ctrl.0001-01.nc $outfile\n done\n done\ndone\n\nMONTHS=\"01 02\"\n\nfor case_name in $CASE_NAMES; do\n echo \"On case $case_name\"\n case_dir=/p/lscratchh/santos36/ACME/$case_name/run\n for month in $MONTHS; do\n date\n echo \"On month $month.\"\n for time in $times; do\n echo \"Time $time.\"\n outfile=\"$OUTPUT_DIR/$case_name.hourly.0004-$month-$time.nc\"\n ncra -v PRECC,PRECL,PRECSC,PRECSL $case_dir/$case_name.cam.h0.0004-$month-*-$time.nc $outfile\n ncks -A -v lat,lon,area /p/lscratchh/santos36/timestep_monthly_avgs/timestep_ctrl.0001-01.nc $outfile\n done\n done\ndone\n" }, { "alpha_fraction": 0.5046005249023438, "alphanum_fraction": 0.5468707084655762, "avg_line_length": 32.77538299560547, "blob_id": "96bf67c1c5e97eeb494659ed0c0959714ed0a290", "content_id": "4a399b277cb6fc9b92ecbaa0da21903e865fa34d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10977, "license_type": "permissive", "max_line_length": 88, "num_lines": 325, "path": "/plot_water_budget_col.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom os.path import join\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import day_str, time_str\n\nNUM_DAYS = 1\nTIME_STEP = 1800\nassert 86400 % TIME_STEP == 0, \"cannot fit even number of time steps in day\"\ntimes_per_day = 86400 // TIME_STEP\n\nCASE_NAMES = [\n \"timestep_ctrl\",\n# \"timestep_MG2_10s\",\n \"timestep_CLUBB_10s_MG2_10s\",\n \"timestep_CLUBB_MG2_10s\",\n# \"timestep_CLUBB_MG2_10s_ftype1\",\n \"timestep_all_10s\",\n# \"timestep_dyn_10s\",\n# \"timestep_presaer_ctrl\",\n# \"timestep_presaer_CLUBB_MG2_10s\",\n# \"timestep_presaer_CLUBB_MG2_10s_ZM_10s\",\n# \"timestep_presaer_cld_10s\",\n# \"timestep_presaer_cld_10s_ftype1\",\n# \"timestep_presaer_all_10s\",\n]\nSHORT_CASE_NAMES = [\n \"CTRL\",\n# \"MICRO10\",\n \"CLUBB10MICRO10\",\n \"CLUBBMICRO10\",\n# \"CLUBBMICRO10FTYPE1\",\n \"ALL10\",\n# \"DYN10\",\n# \"CTRLPA\",\n# \"CLUBBMICRO10PA\",\n# \"CLUBBMICRO10ZM10PA\",\n# \"CLD10PA\",\n# \"CLD10FTYPE1PA\",\n# \"ALL10PA\",\n]\nSTYLES = {\n \"CTRL\": ('k', '-'),\n \"MICRO10\": ('r', '-'),\n \"CLUBB10MICRO10\": ('maroon', '-'),\n \"CLUBBMICRO10\": ('indigo', '-'),\n \"CLUBBMICRO10FTYPE1\": ('indigo', ':'),\n \"ALL10\": ('dimgrey', '-'),\n \"DYN10\": ('y', '-'),\n \"CTRLPA\": ('k', '-'),\n \"CLUBBMICRO10PA\": ('indigo', '-'),\n \"CLUBBMICRO10ZM10PA\": ('saddlebrown', '-'),\n \"CLD10PA\": ('slateblue', '-'),\n \"CLD10FTYPE1PA\": ('slateblue', ':'),\n \"ALL10PA\": ('dimgrey', '-'),\n}\nOUTPUT_DIRS = [\"/p/lustre2/santos36/ACME/{}/run/\".format(case)\n for case in CASE_NAMES]\n\nsuffix = \"\"\n\nlog_file = open(\"plot_water_budget_col_log{}.txt\".format(suffix), 'w')\n\nout_file_template = \"{}.cam.h0.0001-01-{}-{}.nc\"\n\ndef get_out_file_name(icase, day, time):\n \"\"\"Given a case index, day, and time, return CAM header file name.\"\"\"\n return join(OUTPUT_DIRS[icase],\n out_file_template.format(CASE_NAMES[icase],\n day_str(day), time_str(time)))\n\nfirst_file_name = get_out_file_name(0, 1, 0)\nfirst_file = nc4.Dataset(first_file_name, 'r')\nncol = len(first_file.dimensions['ncol'])\nnlev = len(first_file.dimensions['lev'])\nlat = first_file['lat'][:]\nlon = first_file['lon'][:]\nlev = first_file['lev'][:]\nilev = first_file['ilev'][:]\n\n# Find columns in box over South America.\nmin_lat = -20.\nmax_lat = 10.\nmin_lon = 280.\nmax_lon = 315.\ncolumn_set = set()\nfor i in range(ncol):\n if min_lon <= lon[i] <= max_lon and min_lat <= lat[i] <= max_lat:\n column_set.add(i)\n\nfirst_file.close()\n\nncol_sa = len(column_set)\ncolumn_list = sorted(list(column_set))\n\n# Max diff in CLDLIQ at surface for CLUBBMICRO10\n#ifocus = 28970\n# Max CLDLIQ at surface for CLUBBMICRO10\n#ifocus = 27898\n# Max precipitation in CTRL\n#ifocus = 29215\n# Max precipitation in CLUBBMICRO10 and CLUBBMICRO10PA\nifocus = 29488\n# Max precipitation in ALL10\n#ifocus = 29227\n# Large oscillations found here:\n#ifocus = 3913\n\n#ifocus = -1\n\nif ifocus == -1:\n # Look at precip in a particular run.\n print(\"Searching for largest average precipitation.\", file=log_file)\n itest = 1\n precl_total = np.zeros((ncol_sa,))\n for day in range(1, NUM_DAYS+1):\n for it in range(times_per_day):\n test_file_name = get_out_file_name(itest, day, it*TIME_STEP)\n test_file = nc4.Dataset(test_file_name, 'r')\n for icol in range(ncol_sa):\n precl_total[icol] += test_file['PRECL'][0,column_list[icol]]\n test_file.close()\n\n test_file_name = get_out_file_name(itest, NUM_DAYS+1, 0)\n test_file = nc4.Dataset(test_file_name, 'r')\n for icol in range(ncol_sa):\n precl_total[icol] += test_file['PRECL'][0,column_list[icol]]\n test_file.close()\n\n precl_max = 0.\n for icol in range(ncol_sa):\n if precl_max < precl_total[icol]:\n precl_max = precl_total[icol]\n ifocus = column_list[icol]\n\n assert ifocus != -1, \"Cloud liquid max difference not found!\"\n\nprint(\"Difference maximized at column \", ifocus, \" at lat = \",\n lat[ifocus], \", lon = \", lon[ifocus], file=log_file)\n\nfirst_file_name = get_out_file_name(0, 1, 0)\nfirst_file = nc4.Dataset(first_file_name, 'r')\np0 = first_file['P0']\nps = first_file['PS'][0,ifocus]\nhyam = first_file['hyam'][:]\nhybm = first_file['hybm'][:]\np = hyam * p0 + hybm * ps\nfirst_file.close()\n\nvariables = [\n {'name': 'RELHUM', 'units': r'%', 'ndim': 2},\n {'name': 'CLDLIQ', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'CLDICE', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'RAINQM', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'CMELIQ', 'units': r'$g/kg/d$', 'ndim': 2, 'scale': 86.4e6},\n {'name': 'PRAO', 'units': r'$g/kg/d$', 'ndim': 2, 'scale': 86.4e6},\n {'name': 'PRCO', 'units': r'$g/kg/d$', 'ndim': 2, 'scale': 86.4e6},\n {'name': 'QCSEDTEN', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'QRSEDTEN', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'EVAPPREC', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'T', 'units': r'$K$', 'ndim': 2},\n {'name': 'Q', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'U', 'units': r'$m/s$', 'ndim': 2},\n {'name': 'V', 'units': r'$m/s$', 'ndim': 2},\n {'name': 'OMEGA', 'units': r'$Pa/s$', 'ndim': 2},\n {'name': 'CLOUD', 'units': r'fraction', 'ndim': 2},\n {'name': 'DPDLFLIQ', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'DPDLFICE', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'QRL', 'units': r'$K/s$', 'ndim': 2},\n {'name': 'QRS', 'units': r'$K/s$', 'ndim': 2},\n {'name': 'Z3', 'units': r'$m$', 'ndim': 2},\n {'name': 'QCSEVAP', 'units': r'$g/kg/d$', 'ndim': 2, 'scale': 86.4e6},\n {'name': 'QISEVAP', 'units': r'$g/kg/d$', 'ndim': 2, 'scale': 86.4e6},\n]\n\ndef calc_rho(t):\n rho = np.zeros(t.shape)\n ntimes = t.shape[1]\n for i in range(ntimes):\n rho[:,i] = p / (287.058 * t[:,i])\n return rho\n\nderived_variables = [\n {'name': 'LWC', 'units': r'$g/m^3$', 'ndim': 2,\n 'depends': ['CLDLIQ', 'T'],\n 'calc': (lambda var_dict: var_dict['CLDLIQ'] * calc_rho(var_dict['T'])),\n },\n {'name': 'IWC', 'units': r'$g/m^3$', 'ndim': 2,\n 'depends': ['CLDICE', 'T'],\n 'calc': (lambda var_dict: var_dict['CLDICE'] * calc_rho(var_dict['T'])),\n },\n {'name': 'RAINPROD', 'units': r'$g/kg/d$', 'ndim': 2,\n 'depends': ['PRCO', 'PRAO'],\n 'calc': (lambda var_dict: var_dict['PRCO'] + var_dict['PRAO']),\n },\n {'name': 'WINDSPEED', 'units': r'$m/s$', 'ndim': 2,\n 'depends': ['U', 'V'],\n 'calc': (lambda var_dict: np.sqrt(var_dict['U']**2 + var_dict['V']**2)),}\n]\n\n# Check that dependencies are satisfied.\nvar_names = [var['name'] for var in variables]\nfor derived in derived_variables:\n for depend in derived['depends']:\n assert depend in var_names\n\nncases = len(CASE_NAMES)\nntimes = NUM_DAYS * times_per_day + 1\n\nout_vars = {}\nfor icase in range(ncases):\n case = SHORT_CASE_NAMES[icase]\n print(\"Processing case \", case)\n out_vars[case] = {}\n for var in variables:\n out_vars[case][var['name']] = np.zeros((nlev, ntimes))\n ita = 0\n for day in range(1, NUM_DAYS+1):\n for it in range(times_per_day):\n out_file_name = get_out_file_name(icase, day, it*TIME_STEP)\n out_file = nc4.Dataset(out_file_name, 'r')\n for var in variables:\n varname = var['name']\n ndim = var['ndim']\n if ndim == 2:\n out_vars[case][varname][:,ita] = out_file[varname][0,:,ifocus]\n else:\n assert False, \\\n \"don't know what to do with ndim={}\".format(ndim)\n out_file.close()\n ita += 1\n # Last file is 0-th time of the next day.\n out_file_name = get_out_file_name(icase, NUM_DAYS+1, 0)\n out_file = nc4.Dataset(out_file_name, 'r')\n for var in variables:\n varname = var['name']\n ndim = var['ndim']\n if ndim == 2:\n out_vars[case][varname][:,ita] = out_file[varname][0,:,ifocus]\n else:\n assert False, \\\n \"don't know what to do with ndim={}\".format(ndim)\n out_file.close()\n # Scale variables\n for var in variables:\n if 'scale' in var:\n out_vars[case][var['name']] *= var['scale']\n # Calculate derived variables\n for derived in derived_variables:\n out_vars[case][derived['name']] = derived['calc'](out_vars[case])\n\nPLOT_TOP = 700.\nitop = 0\nfor level in ilev:\n if level > PLOT_TOP:\n break\n itop += 1\n\nplot_ilev = ilev[itop:]\n\n# Assumes Venezuelan time.\nTIME_OFFSET = 4.\ntimes = np.linspace(0., TIME_STEP*(ntimes - 1) / 3600., ntimes) - TIME_OFFSET\nfor var in variables + derived_variables:\n name = var['name']\n clim_val = [1.e36, -1.e36]\n for icase in range(ncases):\n clim_val[0] = min(clim_val[0], out_vars[case][name][itop:,1:].min())\n clim_val[1] = max(clim_val[1], out_vars[case][name][itop:,1:].max())\n\n for icase in range(ncases):\n case = SHORT_CASE_NAMES[icase]\n plt.pcolor(times, plot_ilev, out_vars[case][name][itop:,1:])\n plt.axis('tight')\n plt.xlabel(\"Time (hr)\")\n # Bad hard-coding!\n if NUM_DAYS == 1:\n plt.xticks(np.linspace(-3., 18., 8),\n [\"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\"])\n elif NUM_DAYS == 2:\n plt.xticks(np.linspace(-3., 42., 16),\n [\"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\",\n \"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\"])\n plt.grid(True, axis='x')\n ax = plt.gca()\n ylim = ax.get_ylim()\n ax.set_ylim([ylim[1], ylim[0]])\n plt.ylabel(\"Pressure (hPa)\")\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.savefig(\"{}_{}_time_col{}.png\".format(name, case, suffix))\n plt.close()\n\nhtime = (15 * 3600) // TIME_STEP\n\nfor icase in range(ncases):\n case = SHORT_CASE_NAMES[icase]\n hodo_winds = np.zeros((2, 11))\n next_km = 1\n base_z3 = out_vars[case]['Z3'][nlev-1,htime]\n for jlev in range(nlev-1, -1, -1):\n this_z3 = out_vars[case]['Z3'][jlev,htime]\n next_z3 = out_vars[case]['Z3'][jlev-1,htime]\n if next_z3 > (1000.*next_km + base_z3):\n weight = (1000.*next_km + base_z3 - this_z3) / (next_z3 - this_z3)\n u = out_vars[case]['U'][jlev-1,htime]*weight + \\\n out_vars[case]['U'][jlev,htime]*(1.-weight)\n v = out_vars[case]['V'][jlev-1,htime]*weight + \\\n out_vars[case]['V'][jlev,htime]*(1.-weight)\n hodo_winds[0,next_km] = u\n hodo_winds[1,next_km] = v\n next_km += 1\n if next_km == 11:\n break\n plt.plot(hodo_winds[0,:], hodo_winds[1,:])\n plt.savefig(\"hodo_{}{}.png\".format(case, suffix))\n plt.close()\n\nlog_file.close()\n" }, { "alpha_fraction": 0.5304858684539795, "alphanum_fraction": 0.5515215992927551, "avg_line_length": 35.43968963623047, "blob_id": "2bea3c0fd7d3789c1a31eee7808cb7ab8027af57", "content_id": "accf0edf36195423456450a46564a74d0ab0f8a5", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9365, "license_type": "permissive", "max_line_length": 131, "num_lines": 257, "path": "/plot_compare_3D_zonal_avg_monthly.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import E3SMCaseOutput, day_str\n\ncmap = plt.get_cmap('coolwarm')\n\ndef forward(a):\n a = np.deg2rad(a)\n return np.sin(a)\n\ndef inverse(a):\n a = np.arcsin(a)\n return np.rad2deg(a)\n\nSTART_YEAR = 1\nSTART_MONTH = 3\nEND_YEAR = 4\nEND_MONTH = 2\n\nMONTHLY_FILE_LOC=\"/p/lscratchh/santos36/timestep_monthly_avgs_lat_lon\"\n\nnmonths = (END_YEAR - START_YEAR) * 12 - (START_MONTH - 1) + END_MONTH\nimonths = list(range(nmonths))\ncurr_month = START_MONTH\ncurr_year = START_YEAR\nmonths = []\nyears = []\nfor i in range(nmonths):\n months.append(curr_month)\n years.append(curr_year)\n curr_month += 1\n if curr_month > 12:\n curr_month = 1\n curr_year += 1\n\n\nsuffix = '_y{}m{}-y{}m{}'.format(day_str(START_YEAR),\n day_str(START_MONTH),\n day_str(END_YEAR),\n day_str(END_MONTH))\n\nsuffix += '_zonal'\n\nlog_file = open(\"plot_zonal_log{}.txt\".format(suffix), 'w')\n\nREF_CASE = E3SMCaseOutput(\"timestep_ctrl\", \"CTRL\", MONTHLY_FILE_LOC, START_MONTH, END_MONTH)\nTEST_CASES = [\n E3SMCaseOutput(\"timestep_all_10s\", \"ALL10\", MONTHLY_FILE_LOC, START_MONTH, END_MONTH),\n]\n\nrfile0 = nc4.Dataset(REF_CASE.get_monthly_file_name(START_MONTH, START_YEAR), 'r')\nlat = rfile0['lat'][:]\nlon = rfile0['lon'][:]\nilev = rfile0['ilev'][:]\nnlat = len(lat)\nnlon = len(lon)\nnlev = len(ilev) - 1\nrfile0.close()\n\nmonth_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\nmonth_weights = [month_days[months[imonth] - 1] for imonth in imonths]\nweight_norm = sum(month_weights)\nmonth_weights = [weight / weight_norm for weight in month_weights]\n\ndef get_overall_averages(ref_case, test_cases, months, varnames, scales):\n case_num = len(test_cases)\n ref_means = dict()\n for name in varnames:\n ref_means[name] = np.zeros((nlev, nlat, nlon))\n test_means = []\n diff_means = []\n for case in test_cases:\n next_test_means = dict()\n next_diff_means = dict()\n for name in varnames:\n next_test_means[name] = np.zeros((nlev, nlat, nlon))\n next_diff_means[name] = np.zeros((nlev, nlat, nlon))\n test_means.append(next_test_means)\n diff_means.append(next_diff_means)\n\n varnames_read = [name for name in varnames if name != \"PRECT\" and name != \"TAU\"]\n if \"PRECT\" in varnames:\n if \"PRECL\" not in varnames:\n varnames_read.append(\"PRECL\")\n if \"PRECC\" not in varnames:\n varnames_read.append(\"PRECC\")\n if \"TAU\" in varnames:\n if \"TAUX\" not in varnames:\n varnames_read.append(\"TAUX\")\n if \"TAUY\" not in varnames:\n varnames_read.append(\"TAUY\")\n\n for imonth in imonths:\n month = months[imonth]\n year = years[imonth]\n ref_monthly, test_monthly, diff_monthly = ref_case.compare_monthly_averages(test_cases, month, year, varnames_read)\n if \"PRECT\" in varnames:\n ref_monthly[\"PRECT\"] = ref_monthly[\"PRECL\"] + ref_monthly[\"PRECC\"]\n for icase in range(case_num):\n test_monthly[icase][\"PRECT\"] = test_monthly[icase][\"PRECL\"] + test_monthly[icase][\"PRECC\"]\n diff_monthly[icase][\"PRECT\"] = diff_monthly[icase][\"PRECL\"] + diff_monthly[icase][\"PRECC\"]\n if \"TAU\" in varnames:\n ref_monthly[\"TAU\"] = np.sqrt(ref_monthly[\"TAUX\"]**2 + ref_monthly[\"TAUY\"]**2)\n for icase in range(case_num):\n test_monthly[icase][\"TAU\"] = np.sqrt(test_monthly[icase][\"TAUX\"]**2 + test_monthly[icase][\"TAUY\"]**2)\n diff_monthly[icase][\"TAU\"] = test_monthly[icase][\"TAU\"] - ref_monthly[\"TAU\"]\n for name in varnames:\n for jlev in range(nlev):\n ref_means[name][jlev,:,:] += month_weights[imonth] * ref_monthly[name][jlev,:,:]\n for icase in range(case_num):\n test_means[icase][name][jlev,:,:] += month_weights[imonth] * test_monthly[icase][name][jlev,:,:]\n diff_means[icase][name][jlev,:,:] += month_weights[imonth] * diff_monthly[icase][name][jlev,:,:]\n\n for name in varnames:\n ref_means[name] *= scales[name]\n for icase in range(case_num):\n test_means[icase][name] *= scales[name]\n diff_means[icase][name] *= scales[name]\n\n return (ref_means, test_means, diff_means)\n\n\nplot_names = {\n 'AQRAIN': 'rain mixing ratio',\n 'AQSNOW': 'snow mixing ratio',\n 'AREI': 'ice effective radius',\n 'AREL': 'droplet effective radius',\n 'CLDICE': 'cloud ice mixing ratio',\n 'CLDLIQ': 'cloud liquid mixing ratio',\n 'CLOUD': \"cloud fraction\",\n 'Q': \"specific humidity\",\n 'QRL': 'longwave heating rate',\n 'QRS': 'shortwave heating rate',\n 'RELHUM': \"relative humidity\",\n 'T': \"temperature\",\n 'U': \"zonal wind\",\n}\n\nunits = {\n 'AQRAIN': r'$mg/kg$',\n 'AQSNOW': r'$mg/kg$',\n 'AREI': r'micron',\n 'AREL': r'micron',\n 'CLDICE': r'$g/kg$',\n 'CLDLIQ': r'$g/kg$',\n 'CLOUD': r'fraction',\n 'Q': r'$g/kg$',\n 'QRL': r'$K/day$',\n 'QRS': r'$K/day$',\n 'RELHUM': r'%',\n 'T': r'$K$',\n 'U': r'$m/s$'\n}\nvarnames = list(units.keys())\nscales = dict()\nfor name in varnames:\n scales[name] = 1.\nscales['AQRAIN'] = 1.e6\nscales['AQSNOW'] = 1.e6\nscales['CLDICE'] = 1000.\nscales['CLDLIQ'] = 1000.\nscales['Q'] = 1000.\nscales['QRL'] = 86400.\nscales['QRS'] = 86400.\n\nPLOT_TOP = 100.\nitop = 0\nfor level in ilev:\n if level > PLOT_TOP:\n break\n itop += 1\n\ndef zonal_average(x):\n return np.mean(x[itop:,:,:], axis=2)\n\nref_means, test_means, diff_means = get_overall_averages(REF_CASE, TEST_CASES, months, varnames, scales)\n\nplot_ilev = ilev[itop:]\n\nfor name in varnames:\n plot_name = name\n if name in plot_names:\n plot_name = plot_names[name]\n\n ref_plot_var = zonal_average(ref_means[name])\n clim_val = [ref_plot_var.min(), ref_plot_var.max()]\n clim_diff = 0.\n for icase in range(len(TEST_CASES)):\n test_plot_var = zonal_average(test_means[icase][name])\n diff_plot_var = zonal_average(diff_means[icase][name])\n clim_val[0] = min(clim_val[0], test_plot_var.min())\n clim_val[1] = max(clim_val[1], test_plot_var.max())\n clim_diff = max(clim_diff, - diff_plot_var.min())\n clim_diff = max(clim_diff, diff_plot_var.max())\n\n\n plt.pcolor(lat[1:], plot_ilev, ref_plot_var[:,1:-1])\n ax = plt.gca()\n ylim = ax.get_ylim()\n ax.set_ylim([ylim[1], ylim[0]])\n plt.ylabel(\"Pressure (mb)\")\n ax.set_xscale('function', functions=(forward, inverse))\n ax.set_xticks([60., 30., 15., 0., -15., -30., -60.])\n ax.set_xticklabels(['60N', '30N', '15N', '0', '15S', '30S', '60S'])\n plt.axis('tight')\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.title(\"{} for case {}\\n({}, months {}/{} - {}/{})\".format(plot_name, REF_CASE.short_name, units[name],\n day_str(START_MONTH), day_str(START_YEAR),\n day_str(END_MONTH), day_str(END_YEAR)))\n plt.savefig('{}_{}{}.png'.format(name, REF_CASE.short_name, suffix))\n plt.close()\n\n for icase in range(len(TEST_CASES)):\n test_plot_var = zonal_average(test_means[icase][name])\n diff_plot_var = zonal_average(diff_means[icase][name])\n case_name = TEST_CASES[icase].short_name\n\n plt.pcolor(lat[1:], plot_ilev, test_plot_var[:,1:-1])\n ax = plt.gca()\n ylim = ax.get_ylim()\n ax.set_ylim([ylim[1], ylim[0]])\n plt.ylabel(\"Pressure (mb)\")\n ax.set_xscale('function', functions=(forward, inverse))\n ax.set_xticks([60., 30., 15., 0., -15., -30., -60.])\n ax.set_xticklabels(['60N', '30N', '15N', '0', '15S', '30S', '60S'])\n plt.axis('tight')\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.title(\"{} for case {}\\n({}, months {}/{} - {}/{})\".format(plot_name, case_name, units[name],\n day_str(START_MONTH), day_str(START_YEAR),\n day_str(END_MONTH), day_str(END_YEAR)))\n plt.savefig('{}_{}{}.png'.format(name, case_name, suffix))\n plt.close()\n\n plt.pcolor(lat[1:], plot_ilev, diff_plot_var[:,1:-1], cmap=cmap)\n ax = plt.gca()\n ylim = ax.get_ylim()\n ax.set_ylim([ylim[1], ylim[0]])\n plt.ylabel(\"Pressure (mb)\")\n ax.set_xscale('function', functions=(forward, inverse))\n ax.set_xticks([60., 30., 15., 0., -15., -30., -60.])\n ax.set_xticklabels(['60N', '30N', '15N', '0', '15S', '30S', '60S'])\n plt.axis('tight')\n plt.colorbar()\n plt.clim(-clim_diff, clim_diff)\n plt.title(\"Mean difference in {}\\nfor case {} ({}, months {}/{} - {}/{})\".format(plot_name, case_name, units[name],\n day_str(START_MONTH), day_str(START_YEAR),\n day_str(END_MONTH), day_str(END_YEAR)))\n plt.savefig('{}_diff_{}{}.png'.format(name, case_name, suffix))\n plt.close()\n" }, { "alpha_fraction": 0.546527624130249, "alphanum_fraction": 0.5880385637283325, "avg_line_length": 37.410579681396484, "blob_id": "075e5bc7e92465b841f51c805e2f0b64205e0d41", "content_id": "398b87d20e45703d4f439513dab10a880cc5cbf0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15249, "license_type": "permissive", "max_line_length": 134, "num_lines": 397, "path": "/plot_compare_2D_vars.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom os.path import join\n\nfrom functools import partial\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import basemap\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import E3SMCaseOutput, day_str\n\nabs_cmap = plt.get_cmap('BuGn')\ncmap = plt.get_cmap('coolwarm')\nbmap = basemap.Basemap(lon_0=180.)\n\ndef forward(a):\n a = np.deg2rad(a)\n return np.sin(a)\n\ndef inverse(a):\n a = np.arcsin(a)\n return np.rad2deg(a)\n\nSTART_DAY = 3\nEND_DAY = 15\n\nDAILY_FILE_LOC = \"/p/lscratchh/santos36/timestep_daily_avgs_lat_lon\"\n\nUSE_PRESAER = False\n\ndays = list(range(START_DAY, END_DAY+1))\nndays = len(days)\n\nsuffix = '_d{}-{}'.format(day_str(START_DAY), day_str(END_DAY))\nif USE_PRESAER:\n suffix += '_presaer'\n\nlog_file = open(\"plot_2D_log{}.txt\".format(suffix), 'w')\n\nif USE_PRESAER:\n REF_CASE = E3SMCaseOutput(\"timestep_presaer_ctrl\", \"CTRLPA\", DAILY_FILE_LOC, START_DAY, END_DAY)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_presaer_all_10s\", \"ALL10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s\", \"CLUBBMICRO10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_ZM_10s\", \"ZM10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s_ZM_10s\", \"CLUBBMICRO10ZM10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_cld_10s\", \"CLD10PA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_ZM_10s_lower_tau\", \"ZM10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_CLUBB_MG2_10s_ZM_10s_lower_tau\", \"CLUBBMICRO10ZM10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_cld_10s_lower_tau\", \"CLD10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_presaer_all_10s_lower_tau\", \"ALL10LTPA\", DAILY_FILE_LOC, START_DAY, END_DAY),\n ]\nelse:\n REF_CASE = E3SMCaseOutput(\"timestep_ctrl\", \"CTRL\", DAILY_FILE_LOC, START_DAY, END_DAY)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_all_10s\", \"ALL10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_dyn_10s\", \"DYN10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_MG2_10s\", \"MICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_10s\", \"CLUBB10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_10s_MG2_10s\", \"CLUBB10MICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_Strang\", \"CLUBBMICROSTR\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_Strang_60s\", \"CLUBBMICROSTR60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_10s\", \"CLUBBMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_CLUBB_MG2_60s\", \"CLUBBMICRO60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_ZM_10s\", \"ZM10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n# E3SMCaseOutput(\"timestep_ZM_300s\", \"ZM300\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_rad_10s\", \"ALLRAD10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_300s\", \"ALL300\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_all_60s\", \"ALL60\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_precip_grad\", \"PFMG\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_precip_grad_MG2_10s\", \"PFMGMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n E3SMCaseOutput(\"timestep_precip_grad_CLUBB_MG2_10s\", \"PFMGCLUBBMICRO10\", DAILY_FILE_LOC, START_DAY, END_DAY),\n ]\n\nrfile0 = nc4.Dataset(REF_CASE.get_daily_file_name(START_DAY), 'r')\nlat = rfile0['lat'][:]\nlon = rfile0['lon'][:]\nlev = rfile0['lev'][:]\nnlat = len(lat)\nnlon = len(lon)\nnlev = len(lev)\nrfile0.close()\n\ndef get_overall_averages(ref_case, test_cases, days, varnames, scales):\n case_num = len(test_cases)\n day_num = len(days)\n ref_means = dict()\n for name in varnames:\n if name in vars_3D:\n ref_means[name] = np.zeros((nlev, nlat, nlon))\n else:\n ref_means[name] = np.zeros((nlat, nlon))\n test_means = []\n diff_means = []\n for case in test_cases:\n next_test_means = dict()\n next_diff_means = dict()\n for name in varnames:\n if name in vars_3D:\n next_test_means[name] = np.zeros((nlev, nlat, nlon))\n next_diff_means[name] = np.zeros((nlev, nlat, nlon))\n else:\n next_test_means[name] = np.zeros((nlat, nlon))\n next_diff_means[name] = np.zeros((nlat, nlon))\n test_means.append(next_test_means)\n diff_means.append(next_diff_means)\n\n varnames_read = [name for name in varnames if name != \"PRECT\" and name != \"TAU\"]\n if \"PRECT\" in varnames:\n if \"PRECL\" not in varnames:\n varnames_read.append(\"PRECL\")\n if \"PRECC\" not in varnames:\n varnames_read.append(\"PRECC\")\n if \"TAU\" in varnames:\n if \"TAUX\" not in varnames:\n varnames_read.append(\"TAUX\")\n if \"TAUY\" not in varnames:\n varnames_read.append(\"TAUY\")\n\n for day in days:\n ref_daily, test_daily, diff_daily = ref_case.compare_daily_averages(test_cases, day, varnames_read)\n if \"PRECT\" in varnames:\n ref_daily[\"PRECT\"] = ref_daily[\"PRECL\"] + ref_daily[\"PRECC\"]\n for icase in range(case_num):\n test_daily[icase][\"PRECT\"] = test_daily[icase][\"PRECL\"] + test_daily[icase][\"PRECC\"]\n diff_daily[icase][\"PRECT\"] = diff_daily[icase][\"PRECL\"] + diff_daily[icase][\"PRECC\"]\n if \"TAU\" in varnames:\n ref_daily[\"TAU\"] = np.sqrt(ref_daily[\"TAUX\"]**2 + ref_daily[\"TAUY\"]**2)\n for icase in range(case_num):\n test_daily[icase][\"TAU\"] = np.sqrt(test_daily[icase][\"TAUX\"]**2 + test_daily[icase][\"TAUY\"]**2)\n diff_daily[icase][\"TAU\"] = test_daily[icase][\"TAU\"] - ref_daily[\"TAU\"]\n for name in varnames:\n ref_means[name] += ref_daily[name]\n for icase in range(case_num):\n test_means[icase][name] += test_daily[icase][name]\n diff_means[icase][name] += diff_daily[icase][name]\n\n for name in varnames:\n ref_means[name] *= scales[name]/day_num\n for icase in range(case_num):\n test_means[icase][name] *= scales[name]/day_num\n diff_means[icase][name] *= scales[name]/day_num\n\n return (ref_means, test_means, diff_means)\n\nplot_names = {\n 'LWCF': \"long wave cloud forcing\",\n 'SWCF': \"short wave cloud forcing\",\n 'PRECC': \"convective precipitation\",\n 'PRECL': \"large-scale precipitation\",\n 'PRECE': \"extreme precipitation\",\n 'PRECT': \"total precipitation\",\n 'TGCLDIWP': \"ice water path\",\n 'TGCLDLWP': \"liquid water path\",\n 'CLDTOT': \"cloud area fraction\",\n 'CLDLOW': \"low cloud area fraction\",\n 'CLDMED': \"mid-level cloud area fraction\",\n 'CLDHGH': \"high cloud area fraction\",\n 'LHFLX': \"latent heat flux\",\n 'SHFLX': \"sensible heat flux\",\n 'TAU': \"surface wind stress\",\n 'TS': \"surface temperature\",\n 'PSL': \"sea level pressure\",\n 'OMEGA500': \"vertical velocity at 500 mb\",\n 'U10': \"10 meter wind speed\",\n 'RELHUM': \"surface relative humidity\",\n 'Q': \"specific humidity\",\n 'CLDLIQ': \"lowest level cloud liquid\",\n 'T': \"lowest level temperature\",\n 'CLOUD': \"lowest level cloud fraction\",\n 'TMQ': \"precipitable water\",\n}\n\nunits = {\n 'LWCF': r'$W/m^2$',\n 'SWCF': r'$W/m^2$',\n 'PRECC': r'$mm/day$',\n 'PRECL': r'$mm/day$',\n 'PRECE': r'$mm/day$',\n 'PRECT': r'$mm/day$',\n 'TGCLDIWP': r'$g/m^2$',\n 'TGCLDLWP': r'$g/m^2$',\n 'AODABS': r'units?',\n 'AODUV': r'units?',\n 'AODVIS': r'units?',\n 'FLDS': r'$W/m^2$',\n 'FLNS': r'$W/m^2$',\n 'FLNSC': r'$W/m^2$',\n 'FLNT': r'$W/m^2$',\n 'FLNTC': r'$W/m^2$',\n 'FLUT': r'$W/m^2$',\n 'FLUTC': r'$W/m^2$',\n 'FSDS': r'$W/m^2$',\n 'FSDSC': r'$W/m^2$',\n 'FSNS': r'$W/m^2$',\n 'FSNSC': r'$W/m^2$',\n 'FSNT': r'$W/m^2$',\n 'FSNTC': r'$W/m^2$',\n 'FSNTOA': r'$W/m^2$',\n 'FSNTOAC': r'$W/m^2$',\n 'FSUTOA': r'$W/m^2$',\n 'FSUTOAC': r'$W/m^2$',\n 'CLDTOT': r'fraction',\n 'CLDLOW': r'fraction',\n 'CLDMED': r'fraction',\n 'CLDHGH': r'fraction',\n 'OMEGA500': r'Pa/s',\n 'LHFLX': r'$W/m^2$',\n 'SHFLX': r'$W/m^2$',\n 'TAU': r'$N/m^2$',\n 'TAUX': r'$N/m^2$',\n 'TAUY': r'$N/m^2$',\n 'TS': r'$K$',\n 'PSL': r'$Pa$',\n 'U10': r'$m/s$',\n 'RELHUM': r'%',\n 'Q': r'$g/kg$',\n 'CLDLIQ': r\"$g/kg$\",\n 'T': r'$K$',\n 'CLOUD': r'$fraction$',\n 'TMQ': r'$kg/m^2$',\n}\nvarnames = list(units.keys())\nscales = dict()\nfor name in varnames:\n scales[name] = 1.\nscales['TGCLDIWP'] = 1000.\nscales['TGCLDLWP'] = 1000.\nscales['PRECC'] = 1000.*86400.\nscales['PRECL'] = 1000.*86400.\nscales['PRECE'] = 1000.*86400.\nscales['PRECT'] = 1000.*86400.\nscales['Q'] = 1000.\nscales['CLDLIQ'] = 1000.\n\ndiff_lims = {\n 'OMEGA500': 0.05,\n 'TAU': 0.1,\n 'PRECC': 10.,\n 'PRECL': 10.,\n 'PRECT': 10.,\n 'PSL': 200.\n}\n\nvars_3D = [\n 'RELHUM',\n 'Q',\n 'CLDLIQ',\n 'T',\n 'CLOUD',\n]\n\nPRECIP_OUTPUT_DIR = \"/p/lustre2/santos36/timestep_precip_lat_lon/\"\n\nout_file_template = \"{}.freq.short.d{}-d{}.nc\"\n\n# Threshold for precipitation to be considered \"extreme\", in mm/day.\nPRECE_THRESHOLD = 97.\n\ndef get_prece(case_name, start_day, end_day):\n file_name = out_file_template.format(case_name, day_str(start_day), day_str(end_day))\n precip_file = nc4.Dataset(join(PRECIP_OUTPUT_DIR, file_name), 'r')\n nbins = len(precip_file.dimensions['nbins'])\n bin_lower_bounds = precip_file['bin_lower_bounds'][:]\n ibinthresh = -1\n for i in range(nbins):\n if bin_lower_bounds[i] > PRECE_THRESHOLD:\n ibinthresh = i\n break\n if ibinthresh == -1:\n print(\"Warning: extreme precip threshold greater than largest bin bound.\")\n prece = precip_file[\"PRECT_amount\"][:,:,ibinthresh:].sum(axis=2)\n return prece\n\n# Possible ways to extract a 2D section start here:\ndef identity(x):\n return x\n\ndef slice_at(level, x):\n return x[level,:,:]\n\nprint(\"Reading model output.\")\n\nvarnames_readhist = [name for name in varnames if name != \"PRECE\"]\nref_means, test_means, diff_means = get_overall_averages(REF_CASE, TEST_CASES, days, varnames_readhist, scales)\n\nprint(\"Reading extreme precipitation.\")\nif \"PRECE\" in varnames:\n ref_means[\"PRECE\"] = get_prece(REF_CASE.case_name, START_DAY, END_DAY)\n for icase in range(len(TEST_CASES)):\n test_means[icase][\"PRECE\"] = get_prece(TEST_CASES[icase].case_name, START_DAY, END_DAY)\n diff_means[icase][\"PRECE\"] = test_means[icase][\"PRECE\"] - ref_means[\"PRECE\"]\n\n# Should have this actually read from the plot_daily_means output.\ndiff_global_means = {\n 'PRECL': {\n 'ALL10': 0.2612134688516978,\n 'MICRO10': 0.11923748066367695,\n 'CLUBB10MICRO10': 0.11881571958007726,\n 'CLUBBMICRO10': 0.19409486771529938,\n },\n}\n\nfor name in varnames:\n plot_name = name\n if name in plot_names:\n plot_name = plot_names[name]\n\n get_2D = identity\n if name in [\"RELHUM\", \"Q\", \"CLDLIQ\", \"T\", \"CLOUD\"]:\n get_2D = partial(slice_at, nlev-1)\n\n ref_plot_var = get_2D(ref_means[name])\n clim_val = [ref_plot_var.min(), ref_plot_var.max()]\n clim_diff = 0.\n for icase in range(len(TEST_CASES)):\n test_plot_var = get_2D(test_means[icase][name])\n diff_plot_var = get_2D(diff_means[icase][name])\n clim_val[0] = min(clim_val[0], test_plot_var.min())\n clim_val[1] = max(clim_val[1], test_plot_var.max())\n clim_diff = max(clim_diff, - diff_plot_var.min())\n clim_diff = max(clim_diff, diff_plot_var.max())\n\n if name in diff_lims:\n clim_diff = diff_lims[name]\n\n plt.pcolormesh(lon[:], lat[:], ref_plot_var, cmap=abs_cmap)\n bmap.drawcoastlines()\n ax = plt.gca()\n ax.set_xticks([0., 90., 180., 270., 360.])\n ax.set_xticklabels(['0', '90E', '180', '90W', '0'])\n ax.set_yscale('function', functions=(forward, inverse))\n ax.set_yticks([60., 45., 30., 15., 0., -15., -30., -45., -60.])\n ax.set_yticklabels(['60N', '45N', '30N', '15N', '0', '15S', '30S', '45S', '60S'])\n# ax.set_yticks([60., 30., 0., -30., -60.])\n# ax.set_yticklabels(['60N', '30N', '0', '30S', '60S'])\n plt.axis('tight')\n plt.xlim([0., 360.])\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.title(\"{} for case {}\\n({}, days {}-{})\".format(plot_name, REF_CASE.short_name, units[name], START_DAY, END_DAY))\n plt.savefig('{}_{}{}.png'.format(name, REF_CASE.short_name, suffix))\n plt.close()\n\n for icase in range(len(TEST_CASES)):\n test_plot_var = get_2D(test_means[icase][name])\n diff_plot_var = get_2D(diff_means[icase][name])\n case_name = TEST_CASES[icase].short_name\n\n plt.pcolormesh(lon[:], lat[:], test_plot_var, cmap=abs_cmap)\n bmap.drawcoastlines()\n ax = plt.gca()\n ax.set_xticks([0., 90., 180., 270., 360.])\n ax.set_xticklabels(['0', '90E', '180', '90W', '0'])\n ax.set_yscale('function', functions=(forward, inverse))\n ax.set_yticks([60., 45., 30., 15., 0., -15., -30., -45., -60.])\n ax.set_yticklabels(['60N', '45N', '30N', '15N', '0', '15S', '30S', '45S', '60S'])\n# ax.set_yticks([60., 30., 0., -30., -60.])\n# ax.set_yticklabels(['60N', '30N', '0', '30S', '60S'])\n plt.axis('tight')\n plt.xlim([0., 360.])\n plt.colorbar()\n plt.clim(clim_val[0], clim_val[1])\n plt.title(\"{} for case {}\\n({}, days {}-{})\".format(plot_name, case_name, units[name], START_DAY, END_DAY))\n plt.savefig('{}_{}{}.png'.format(name, case_name, suffix))\n plt.close()\n\n plt.pcolormesh(lon[:], lat[:], diff_plot_var, cmap=cmap)\n bmap.drawcoastlines()\n ax = plt.gca()\n ax.set_xticks([0., 90., 180., 270., 360.])\n ax.set_xticklabels(['0', '90E', '180', '90W', '0'])\n ax.set_yscale('function', functions=(forward, inverse))\n ax.set_yticks([60., 45., 30., 15., 0., -15., -30., -45., -60.])\n ax.set_yticklabels(['60N', '45N', '30N', '15N', '0', '15S', '30S', '45S', '60S'])\n# ax.set_yticks([60., 30., 0., -30., -60.])\n# ax.set_yticklabels(['60N', '30N', '0', '30S', '60S'])\n plt.axis('tight')\n plt.xlim([0., 360.])\n plt.colorbar()\n plt.clim(-clim_diff, clim_diff)\n if name in diff_global_means and case_name in diff_global_means[name]:\n unit_string = units[name]\n if unit_string == 'fraction':\n unit_string = ''\n else:\n unit_string = \" \" + unit_string\n mean_string = 'mean {:.2g}'.format(diff_global_means[name][case_name]) + unit_string\n else:\n mean_string = units[name]\n plt.title(\"Mean difference in {}\\nfor case {} ({}, days {}-{})\".format(plot_name, case_name, mean_string, START_DAY, END_DAY))\n plt.savefig('{}_diff_{}{}.png'.format(name, case_name, suffix))\n plt.close()\n" }, { "alpha_fraction": 0.7971698045730591, "alphanum_fraction": 0.8160377144813538, "avg_line_length": 41.400001525878906, "blob_id": "bc59fcdb9ea8f1808fb9fd3ae1ef482e341c2346", "content_id": "30a6b090aa744abd8891ab7b8aab0c60e21f17c8", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 212, "license_type": "permissive", "max_line_length": 79, "num_lines": 5, "path": "/README.md", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "# E3SM Timestep Study\n\nThis repository contains scripts used to examine output for a study on the\neffects of different time step sizes on physics parameterizations in EAMv1 (the\nE3SM Atmosphere Model version 1).\n" }, { "alpha_fraction": 0.6271604895591736, "alphanum_fraction": 0.6641975045204163, "avg_line_length": 26, "blob_id": "615b96178f2ee68312883623e4511f0de75bfd9a", "content_id": "b8d0843497bc7d46e5626af9d4343f2e49f18488", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 405, "license_type": "permissive", "max_line_length": 92, "num_lines": 15, "path": "/create_monthly_averages.sh", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nCASE_NAMES=\"timestep_ctrl\"\nMONTHS=\"01\"\nOUTPUT_DIR=/p/lscratchh/santos36/timestep_monthly_avgs\n\nfor case_name in $CASE_NAMES; do\n echo \"On case $case_name\"\n case_dir=/p/lscratchh/santos36/ACME/$case_name/run\n for month in $MONTHS; do\n date\n echo \"On month $month.\"\n ncra $case_dir/$case_name.cam.h0.0007-$month-* $OUTPUT_DIR/$case_name.0007-$month.nc\n done\ndone\n" }, { "alpha_fraction": 0.6087567806243896, "alphanum_fraction": 0.6392849683761597, "avg_line_length": 33.57638931274414, "blob_id": "ecb1fffb50560cc51f8c72750293f97c69ec5b0e", "content_id": "2382e9bf48aa28f7846eb3f9f9a7cddc023ea448", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4979, "license_type": "permissive", "max_line_length": 86, "num_lines": 144, "path": "/plot_SC_compare.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nCONTROL_FILE_NAME = \"/home/santos/Data/GATEIII_ctrl.cam.h0.1974-08-30-00000.nc\"\nTEST1_FILE_NAME = \"/home/santos/Data/GATEIII_ZM_10s.cam.h0.1974-08-30-00000.nc\"\nTEST2_FILE_NAME = \"/home/santos/Data/GATEIII_CLUBB_MG2_10s.cam.h0.1974-08-30-00000.nc\"\nCONTROL_DESC = \"Control\"\nTEST1_DESC = \"ZM at 10s\"\nTEST2_DESC = \"CLUBB and MG2 at 10s\"\nSUFFIX_CTRL = \"_ctrl\"\nSUFFIX1=\"_ZM_10s\"\nSUFFIX2=\"_CLUBB_MG2_10s\"\nPLOT_VARS = ['SWCF', 'PRECC', 'PRECL']\nSTEPS_IN_AVG = {\n 'SWCF': 48,\n 'PRECC': 6,\n 'PRECL': 6,\n}\nPLOT_VERT_VARS = ['CLDLIQ']\nSTEPS_IN_VERT_AVG = {\n 'CLDLIQ': 1,\n}\nDIFF_CMAP = plt.get_cmap('coolwarm')\n\n# GATEIII specific variables\nNUM_DAYS = 20\nSTEPS_PER_DAY = 48\n\ntotal_steps = NUM_DAYS*STEPS_PER_DAY\n\nctrl_file = nc4.Dataset(CONTROL_FILE_NAME, 'r')\ntest1_file = nc4.Dataset(TEST1_FILE_NAME, 'r')\ntest2_file = nc4.Dataset(TEST2_FILE_NAME, 'r')\n\ntimes = ctrl_file.variables['time'][:]\ntime_len = len(times)\n\nnlev = len(ctrl_file.dimensions['lev'])\nlev = ctrl_file.variables['lev'][:]\n\nfor var_name, avg_step in zip(PLOT_VARS, STEPS_IN_AVG):\n assert total_steps % avg_step == 0\n num_avg = total_steps // avg_step\n plot_times = np.linspace(0, NUM_DAYS+1, num_avg+1)\n\n var_units = ctrl_file.variables[var_name].units\n\n ctrl_var = ctrl_file.variables[var_name][:,0]\n test1_var = test1_file.variables[var_name][:,0]\n test2_var = test2_file.variables[var_name][:,0]\n\n filename = \"{}_compare.png\".format(var_name)\n\n ctrl_avg = np.zeros((num_avg,))\n test1_avg = np.zeros((num_avg,))\n test2_avg = np.zeros((num_avg,))\n for i in range(num_avg):\n ctrl_avg[i] = ctrl_var[i*avg_step:(i+1)*avg_step].sum()\n test1_avg[i] = test1_var[i*avg_step:(i+1)*avg_step].sum()\n test2_avg[i] = test2_var[i*avg_step:(i+1)*avg_step].sum()\n\n plt.plot(plot_times[1:], ctrl_avg, 'k', label=CONTROL_DESC)\n plt.plot(plot_times[1:], test1_avg, 'r', label=TEST1_DESC)\n plt.plot(plot_times[1:], test2_avg, 'b', label=TEST2_DESC)\n plt.title(\"{} comparison\".format(var_name))\n plt.xlabel(\"Days since model start\")\n plt.ylabel(\"{} ({})\".format(var_name, var_units))\n plt.legend(loc='best')\n plt.savefig(filename)\n plt.close()\n\nfor var_name, avg_step in zip(PLOT_VERT_VARS, STEPS_IN_VERT_AVG):\n assert total_steps % avg_step == 0\n num_avg = total_steps // avg_step\n plot_times = np.linspace(0, NUM_DAYS+1, num_avg+1)\n\n var_units = ctrl_file.variables[var_name].units\n\n ctrl_var = ctrl_file.variables[var_name][:,:,0]\n test1_var = test1_file.variables[var_name][:,:,0]\n test2_var = test2_file.variables[var_name][:,:,0]\n\n ctrl_filename = \"{}{}.png\".format(var_name, SUFFIX_CTRL)\n test1_filename = \"{}{}.png\".format(var_name, SUFFIX1)\n test2_filename = \"{}{}.png\".format(var_name, SUFFIX2)\n diff1_filename = \"{}_diff{}.png\".format(var_name, SUFFIX1)\n diff2_filename = \"{}_diff{}.png\".format(var_name, SUFFIX2)\n\n ctrl_avg = np.zeros((num_avg, nlev))\n test1_avg = np.zeros((num_avg, nlev))\n test2_avg = np.zeros((num_avg, nlev))\n for i in range(num_avg):\n for j in range(nlev):\n ctrl_avg[i,j] = ctrl_var[i*avg_step:(i+1)*avg_step,j].sum()\n test1_avg[i,j] = test1_var[i*avg_step:(i+1)*avg_step,j].sum()\n test2_avg[i,j] = test2_var[i*avg_step:(i+1)*avg_step,j].sum()\n\n diff1_avg = test1_avg - ctrl_avg\n diff2_avg = test2_avg - ctrl_avg\n\n plt.pcolor(plot_times, lev, ctrl_avg.T)\n plt.title(\"{} results from {}\".format(var_name, CONTROL_DESC))\n plt.xlabel(\"Days since model start\")\n plt.ylabel(\"Pressure (hPa)\".format(var_name, var_units))\n plt.colorbar()\n plt.savefig(ctrl_filename)\n plt.close()\n\n plt.pcolor(plot_times, lev, test1_avg.T)\n plt.title(\"{} results from {}\".format(var_name, TEST1_DESC))\n plt.xlabel(\"Days since model start\")\n plt.ylabel(\"Pressure (hPa)\".format(var_name, var_units))\n plt.colorbar()\n plt.savefig(test1_filename)\n plt.close()\n\n plt.pcolor(plot_times, lev, diff1_avg.T, cmap=DIFF_CMAP)\n plt.title(\"{} diff from {} to {}\".format(var_name, CONTROL_DESC, TEST1_DESC))\n plt.xlabel(\"Days since model start\")\n plt.ylabel(\"Pressure (hPa)\".format(var_name, var_units))\n plt.colorbar()\n plt.savefig(diff1_filename)\n plt.close()\n\n plt.pcolor(plot_times, lev, test2_avg.T)\n plt.title(\"{} results from {}\".format(var_name, TEST2_DESC))\n plt.xlabel(\"Days since model start\")\n plt.ylabel(\"Pressure (hPa)\".format(var_name, var_units))\n plt.colorbar()\n plt.savefig(test2_filename)\n plt.close()\n\n plt.pcolor(plot_times, lev, diff2_avg.T, cmap=DIFF_CMAP)\n plt.title(\"{} diff from {} to {}\".format(var_name, CONTROL_DESC, TEST2_DESC))\n plt.xlabel(\"Days since model start\")\n plt.ylabel(\"Pressure (hPa)\".format(var_name, var_units))\n plt.colorbar()\n plt.savefig(diff2_filename)\n plt.close()\n" }, { "alpha_fraction": 0.5221630930900574, "alphanum_fraction": 0.5666939616203308, "avg_line_length": 31.952808380126953, "blob_id": "2fb926b6f84a6da1227b7d046d0ca0525c4ec934", "content_id": "e15f9cf5645cc22f21a6715fb2f31027a0c3cb88", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14664, "license_type": "permissive", "max_line_length": 87, "num_lines": 445, "path": "/plot_water_budget_box.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom os.path import join\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import day_str, time_str\n\nSTART_DAY = 1\nEND_DAY = 1\nTIME_STEP = 1800\nassert 86400 % TIME_STEP == 0, \"cannot fit even number of time steps in day\"\ntimes_per_day = 86400 // TIME_STEP\n\nCASE_NAMES = [\n \"timestep_ctrl\",\n# \"timestep_MG2_10s\",\n \"timestep_CLUBB_10s_MG2_10s\",\n \"timestep_CLUBB_MG2_10s\",\n# \"timestep_CLUBB_MG2_10s_ftype1\",\n \"timestep_all_10s\",\n# \"timestep_all_300s\",\n# \"timestep_all_900s\",\n# \"timestep_ctrl_notms\",\n# \"timestep_ctrl_niter_change\",\n# \"timestep_ctrl_niter_change_smooth\",\n# \"timestep_smooth14\",\n# \"timestep_smooth35\",\n# \"timestep_300s_niter_change\",\n# \"timestep_dyn_10s\",\n# \"timestep_presaer_ctrl\",\n# \"timestep_presaer_CLUBB_MG2_10s\",\n# \"timestep_presaer_CLUBB_MG2_10s_ZM_10s\",\n# \"timestep_presaer_cld_10s\",\n# \"timestep_presaer_cld_10s_ftype1\",\n# \"timestep_presaer_all_10s\",\n# \"timestep_presaer_all_10s_lower_tau\",\n# \"timestep_presaer_all_10s_cld_5s\",\n]\nSHORT_CASE_NAMES = [\n \"CTRL\",\n# \"MICRO10\",\n \"CLUBB10MICRO10\",\n \"CLUBBMICRO10\",\n# \"CLUBBMICRO10FTYPE1\",\n \"ALL10\",\n# \"ALL300\",\n# \"ALL900\",\n# \"CTRLFLXAVG\",\n# \"CTRLNITERS\",\n# \"CTRLNITERSSMOOTH35\",\n# \"SMOOTH14\",\n# \"SMOOTH35\",\n# \"ALL300NITERS\",\n# \"DYN10\",\n# \"CTRLPA\",\n# \"CLUBBMICRO10PA\",\n# \"CLUBBMICRO10ZM10PA\",\n# \"CLD10PA\",\n# \"CLD10FTYPE1PA\",\n# \"ALL10PA\",\n# \"ALL10PALT\",\n# \"ALL10CLD5PA\",\n]\nSTYLES = {\n \"CTRL\": ('k', '-'),\n \"MICRO10\": ('r', '-'),\n \"CLUBB10MICRO10\": ('maroon', '-'),\n \"CLUBBMICRO10\": ('indigo', '-'),\n \"CLUBBMICRO10FTYPE1\": ('indigo', ':'),\n \"ALL10\": ('dimgrey', '-'),\n# \"ALL300\": ('dimgrey', ':'),\n \"ALL300\": ('g', '-'),\n \"ALL900\": ('k', '--'),\n \"CTRLFLXAVG\": ('k', ':'),\n \"CTRLNITERS\": ('orange', '-'),\n \"CTRLNITERSSMOOTH35\": ('orange', '--'),\n \"SMOOTH14\": ('r', '-'),\n \"SMOOTH35\": ('r', '-'),\n \"ALL300NITERS\": ('b', '-'),\n \"DYN10\": ('y', '-'),\n \"CTRLPA\": ('k', '-'),\n \"CLUBBMICRO10PA\": ('indigo', '-'),\n \"CLUBBMICRO10ZM10PA\": ('saddlebrown', '-'),\n \"CLD10PA\": ('slateblue', '-'),\n \"CLD10FTYPE1PA\": ('slateblue', ':'),\n \"ALL10PA\": ('dimgrey', '-'),\n \"ALL10PALT\": ('dimgrey', '-.'),\n \"ALL10CLD5PA\": ('slateblue', '-.'),\n}\nOUTPUT_DIRS = [\"/p/lustre2/santos36/ACME/{}/run/\".format(case)\n for case in CASE_NAMES]\n\nsuffix = \"\"\n\nlog_file = open(\"plot_water_budget_box_log{}.txt\".format(suffix), 'w')\n\nout_file_template = \"{}.cam.h0.0001-01-{}-{}.nc\"\n\ndef get_out_file_name(icase, day, time):\n \"\"\"Given a case index, day, and time, return CAM header file name.\"\"\"\n return join(OUTPUT_DIRS[icase],\n out_file_template.format(CASE_NAMES[icase],\n day_str(day), time_str(time)))\n\nfirst_file_name = get_out_file_name(0, 1, 0)\nfirst_file = nc4.Dataset(first_file_name, 'r')\nncol = len(first_file.dimensions['ncol'])\nnlev = len(first_file.dimensions['lev'])\nlat = first_file['lat'][:]\nlon = first_file['lon'][:]\nlev = first_file['lev'][:]\n\n# Find columns in box over South America.\nmin_lat = -20.\nmax_lat = 10.\nmin_lon = 280.\nmax_lon = 315.\ncolumn_set = set()\nfor i in range(ncol):\n if min_lon <= lon[i] <= max_lon and min_lat <= lat[i] <= max_lat:\n column_set.add(i)\n\nfirst_file.close()\n\nncol_sa = len(column_set)\n\n# Max diff in CLDLIQ at surface for CLUBBMICRO10\n#ifocus = 28970\n# Max CLDLIQ at surface for CLUBBMICRO10\n#ifocus = 27898\n# Max precipitation in CTRL\n#ifocus = 29215\n# Max precipitation in CLUBBMICRO10 and CLUBBMICRO10PA\nifocus = 29488\n# Max precipitation in ALL10\n#ifocus = 29227\n# Large oscillations at 1800\n#ifocus = 29520\n\n#ifocus = -1\n\nif ifocus == -1:\n # Look at lowest level CLDLIQ, to see where fog difference is most intense\n # between two cases.\n print(\"Searching for largest fog difference.\", file=log_file, flush=True)\n ictrl = 0\n itest = 2\n cldliq_maxdiff = 0.\n ifocus = -1\n for day in range(START_DAY, END_DAY+1):\n for it in range(times_per_day):\n ctrl_file_name = get_out_file_name(ictrl, day, it*TIME_STEP)\n ctrl_file = nc4.Dataset(ctrl_file_name, 'r')\n test_file_name = get_out_file_name(itest, day, it*TIME_STEP)\n test_file = nc4.Dataset(test_file_name, 'r')\n for icol in column_set:\n cldliq_diff = test_file['CLDLIQ'][0,nlev-1,icol] - \\\n ctrl_file['CLDLIQ'][0,nlev-1,icol]\n if cldliq_diff > cldliq_maxdiff:\n cldliq_maxdiff = cldliq_diff\n ifocus = icol\n ctrl_file.close()\n test_file.close()\n\n ctrl_file_name = get_out_file_name(ictrl, END_DAY+1, 0)\n ctrl_file = nc4.Dataset(ctrl_file_name, 'r')\n test_file_name = get_out_file_name(itest, END_DAY+1, 0)\n test_file = nc4.Dataset(test_file_name, 'r')\n for icol in column_set:\n cldliq_diff = test_file['CLDLIQ'][0,nlev-1,icol] - \\\n ctrl_file['CLDLIQ'][0,nlev-1,icol]\n if cldliq_diff > cldliq_maxdiff:\n cldliq_maxdiff = cldliq_diff\n ifocus = icol\n ctrl_file.close()\n test_file.close()\n\n assert ifocus != -1, \"Cloud liquid max difference not found!\"\n\n#print(\"Difference maximized at column \", ifocus, \" at lat = \",\n# lat[ifocus], \", lon = \", lon[ifocus], file=log_file, flush=True)\n\nvariables = [\n {'name': 'RELHUM', 'units': r'%', 'ndim': 2},\n {'name': 'CLDLIQ', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'RAINQM', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'LHFLX', 'units': r'$W/m^2$', 'ndim': 1},\n {'name': 'SHFLX', 'units': r'$W/m^2$', 'ndim': 1},\n {'name': 'CMELIQ', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'PRAO', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'PRCO', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'QCSEDTEN', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'QRSEDTEN', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'PRECL', 'units': r'$mm/day$', 'ndim': 1, 'scale': 1000.*86400.},\n {'name': 'PRECC', 'units': r'$mm/day$', 'ndim': 1, 'scale': 1000.*86400.},\n {'name': 'EVAPPREC', 'units': r'$kg/kg/s$', 'ndim': 2},\n {'name': 'T', 'units': r'$K$', 'ndim': 2},\n {'name': 'Q', 'units': r'$g/kg$', 'ndim': 2, 'scale': 1000.},\n {'name': 'U', 'units': r'$m/s$', 'ndim': 2},\n {'name': 'V', 'units': r'$m/s$', 'ndim': 2},\n {'name': 'OMEGA', 'units': r'$Pa/s$', 'ndim': 2},\n {'name': 'OMEGA500', 'units': r'$Pa/s$', 'ndim': 1, 'display': r'$\\omega_{500}$'},\n {'name': 'U10', 'units': r'$m/s$', 'ndim': 1},\n {'name': 'PSL', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'FSDS', 'units': r'$W/m^2$', 'ndim': 1},\n {'name': 'SWCF', 'units': r'$W/m^2$', 'ndim': 1},\n {'name': 'CLDLOW', 'units': r'fraction', 'ndim': 1},\n {'name': 'CAPE', 'units': r'$J/kg$', 'ndim': 1},\n {'name': 'TAUX', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUY', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUGWX', 'units': r'$Pa$', 'ndim': 1},\n {'name': 'TAUGWY', 'units': r'$Pa$', 'ndim': 1},\n]\n\nderived_variables = [\n {'name': 'PRECT', 'units': r'$mm/day$', 'ndim': 1,\n 'depends': ['PRECL', 'PRECC'],\n 'calc': (lambda var_dict: var_dict['PRECL'] + var_dict['PRECC']),\n 'display': \"Total Precipitation\",\n },\n {'name': 'TAU', 'units': r'$Pa$', 'ndim': 1,\n 'depends': ['TAUX', 'TAUY'],\n 'calc': (lambda var_dict: np.sqrt(var_dict['TAUX']**2 + var_dict['TAUY']**2)),\n },\n]\n\n# Check that dependencies are satisfied.\nvar_names = [var['name'] for var in variables]\nfor derived in derived_variables:\n for depend in derived['depends']:\n assert depend in var_names\n\nncases = len(CASE_NAMES)\nntimes = (END_DAY - START_DAY + 1) * times_per_day + 1\n\nLEVEL = nlev - 1\n\nout_vars = {}\nfor icase in range(ncases):\n case = SHORT_CASE_NAMES[icase]\n print(\"Processing case \", case)\n if case == \"ALL900\":\n case_times_per_day = times_per_day * 2\n case_ntimes = ntimes*2 - 1\n case_time_step = TIME_STEP // 2\n elif case == \"ALL300\" or case == \"ALL300NITERS\":\n case_times_per_day = times_per_day * 6\n case_ntimes = ntimes*6 - 5\n case_time_step = TIME_STEP // 6\n else:\n case_times_per_day = times_per_day\n case_ntimes = ntimes\n case_time_step = TIME_STEP\n out_vars[case] = {}\n for var in variables:\n out_vars[case][var['name']] = np.zeros((case_ntimes,))\n ita = 0\n for day in range(START_DAY, END_DAY+1):\n for it in range(case_times_per_day):\n out_file_name = get_out_file_name(icase, day, it*case_time_step)\n out_file = nc4.Dataset(out_file_name, 'r')\n for var in variables:\n varname = var['name']\n ndim = var['ndim']\n if ndim == 1:\n out_vars[case][varname][ita] = out_file[varname][0,ifocus]\n elif ndim == 2:\n out_vars[case][varname][ita] = out_file[varname][0,LEVEL,ifocus]\n else:\n assert False, \\\n \"don't know what to do with ndim={}\".format(ndim)\n out_file.close()\n ita += 1\n # Last file is 0-th time of the next day.\n out_file_name = get_out_file_name(icase, END_DAY+1, 0)\n out_file = nc4.Dataset(out_file_name, 'r')\n for var in variables:\n varname = var['name']\n ndim = var['ndim']\n if ndim == 1:\n out_vars[case][varname][ita] = out_file[varname][0,ifocus]\n elif ndim == 2:\n out_vars[case][varname][ita] = out_file[varname][0,LEVEL,ifocus]\n else:\n assert False, \\\n \"don't know what to do with ndim={}\".format(ndim)\n out_file.close()\n # Scale variables\n for var in variables:\n if 'scale' in var:\n out_vars[case][var['name']] *= var['scale']\n # Calculate derived variables\n for derived in derived_variables:\n out_vars[case][derived['name']] = derived['calc'](out_vars[case])\n\n# Assumes Venezuelan time.\nTIME_OFFSET = 4.\ntimes = np.linspace(0., TIME_STEP*(ntimes - 1) / 3600., ntimes) - TIME_OFFSET\ntimes900 = np.linspace(0., TIME_STEP*(ntimes - 1) / 3600., 2*ntimes - 1) - TIME_OFFSET\ntimes300 = np.linspace(0., TIME_STEP*(ntimes - 1) / 3600., 6*ntimes - 5) - TIME_OFFSET\nprint_vars = {\"PRECT\", \"PRECL\", \"PRECC\", \"OMEGA500\", \"CAPE\"}\nprint(\"time\", \",\", \",\".join(str(time % 24) for time in times), sep=\"\",\n file=log_file, flush=True)\nfor var in variables + derived_variables:\n name = var['name']\n for icase in range(ncases):\n case = SHORT_CASE_NAMES[icase]\n if case == \"ALL900\":\n case_times = times900\n elif case == \"ALL300\" or case == \"ALL300NITERS\":\n case_times = times300\n else:\n case_times = times\n if name in print_vars:\n print(name, \",\", case, \",\", \",\".join(str(x) for x in out_vars[case][name]),\n sep=\"\", file=log_file, flush=True)\n plt.plot(case_times, out_vars[case][name], color=STYLES[case][0],\n linestyle=STYLES[case][1])\n plt.axis('tight')\n plt.xlabel(\"Time (hr)\")\n # Bad hard-coding!\n if START_DAY - END_DAY + 1 == 1:\n plt.xticks(np.linspace(-3., 18., 8),\n [\"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\"])\n elif START_DAY - END_DAY + 1 == 2:\n plt.xticks(np.linspace(-3., 42., 16),\n [\"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\",\n \"2100\", \"0000\", \"0300\", \"0600\", \"0900\", \"1200\", \"1500\", \"1800\"])\n plt.grid(True)\n if 'display' in var:\n dname = var['display']\n else:\n dname = name\n plt.ylabel(\"{} ({})\".format(dname, var['units']))\n plt.savefig(\"{}_time_box{}.png\".format(name, suffix))\n plt.close()\n\n# Plot wind issues over SA.\nfrom mpl_toolkits import basemap\nbmap = basemap.Basemap(lon_0=180.)\n\n#TIME_CHECK = 57600\n#TIME_CHECK = 79200\nTIME_CHECK = 0\n#TIME_CHECK = 54000\n#TIME_CHECK = 12*3600\n\nDAY_CHECK = 2\n\nCASE_CHECK = 0\n\ncase = SHORT_CASE_NAMES[CASE_CHECK]\nif case == \"ALL900\":\n time_increment = TIME_STEP // 2\nelif case == \"ALL300\" or case == \"ALL300NITERS\":\n time_increment = TIME_STEP // 6\nelse:\n time_increment = TIME_STEP\n\n#plot_box = [min_lon, max_lon, min_lat, max_lat]\nplot_box = [285., 297., 1., 10.]\n\nmid_file_name = get_out_file_name(CASE_CHECK, DAY_CHECK, TIME_CHECK)\nmid_file = nc4.Dataset(mid_file_name, 'r')\n\nu1 = mid_file['U'][0,LEVEL,:]\nv1 = mid_file['V'][0,LEVEL,:]\n\n#plt.scatter(lon, lat, c=mid_file['PSL'][0,:])\n#plt.colorbar()\nplt.quiver(lon, lat, mid_file['U'][0,LEVEL,:], mid_file['V'][0,LEVEL,:],\n scale=100., scale_units='height', angles='xy')\nbmap.drawcoastlines()\nplt.axis(plot_box)\nplt.savefig(\"UV_arrow_box1{}.png\".format(suffix))\nplt.close()\n\nplt.scatter(lon, lat, c=mid_file['OMEGA500'][0,:])\nbmap.drawcoastlines()\nplt.axis(plot_box)\nplt.colorbar()\nplt.savefig(\"OMEGA500_box1{}.png\".format(suffix))\nplt.close()\n\nmid_file.close()\n\nmid_file_name = get_out_file_name(CASE_CHECK, DAY_CHECK, TIME_CHECK + time_increment)\nmid_file = nc4.Dataset(mid_file_name, 'r')\n\nu2 = mid_file['U'][0,LEVEL,:]\nv2 = mid_file['V'][0,LEVEL,:]\n\nplt.quiver(lon, lat, mid_file['U'][0,LEVEL,:], mid_file['V'][0,LEVEL,:],\n scale=100., scale_units='height', angles='xy')\nbmap.drawcoastlines()\nplt.axis(plot_box)\nplt.savefig(\"UV_arrow_box2{}.png\".format(suffix))\nplt.close()\n\nplt.scatter(lon, lat, c=mid_file['OMEGA500'][0,:])\nbmap.drawcoastlines()\nplt.axis(plot_box)\nplt.colorbar()\nplt.savefig(\"OMEGA500_box2{}.png\".format(suffix))\nplt.close()\n\nmid_file.close()\n\nmid_file_name = get_out_file_name(CASE_CHECK, DAY_CHECK, TIME_CHECK + 2*time_increment)\nmid_file = nc4.Dataset(mid_file_name, 'r')\n\nu3 = mid_file['U'][0,LEVEL,:]\nv3 = mid_file['V'][0,LEVEL,:]\n\nplt.quiver(lon, lat, mid_file['U'][0,LEVEL,:], mid_file['V'][0,LEVEL,:],\n scale=100., scale_units='height', angles='xy')\nbmap.drawcoastlines()\nplt.axis(plot_box)\nplt.savefig(\"UV_arrow_box3{}.png\".format(suffix))\nplt.close()\n\nplt.scatter(lon, lat, c=mid_file['OMEGA500'][0,:])\nbmap.drawcoastlines()\nplt.axis(plot_box)\nplt.colorbar()\nplt.savefig(\"OMEGA500_box3{}.png\".format(suffix))\nplt.close()\n\nmid_file.close()\n\nplt.scatter(lon[ifocus], lat[ifocus])\n\nplt.quiver(lon, lat, u1 - 2*u2 + u3, v1 - 2*v2 + v3,\n scale=100., scale_units='height', angles='xy')\nbmap.drawcoastlines()\nplt.axis(plot_box)\nplt.savefig(\"UV_D2_arrow_box{}.png\".format(suffix))\nplt.close()\n\nlog_file.close()\n" }, { "alpha_fraction": 0.5958142280578613, "alphanum_fraction": 0.6057881116867065, "avg_line_length": 31.8817195892334, "blob_id": "2cf9ba3f17489e0c25f65cb65d91abb997451678", "content_id": "310d03a2a06ea0330c44ddbf4414a9bc415e020d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6116, "license_type": "permissive", "max_line_length": 102, "num_lines": 186, "path": "/plot_precip_freq.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom os.path import join\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import day_str\n\nREF_CASE_NAME = \"timestep_ctrl\"\nTEST_CASE_NAME = \"timestep_all_10s\"\nOUTPUT_DIR = \"/p/lustre2/santos36/timestep_precip/\"\n\nLAND_TROPICS = True\nTROPICS_ONLY = False\n\nif LAND_TROPICS:\n TROPICS_ONLY = True\n\nSTART_YEAR = 3\nSTART_MONTH = 3\nEND_YEAR = 4\nEND_MONTH = 2\n\nsuffix = '_y{}m{}-y{}m{}'.format(day_str(START_YEAR),\n day_str(START_MONTH),\n day_str(END_YEAR),\n day_str(END_MONTH))\n\nif TROPICS_ONLY:\n if LAND_TROPICS:\n suffix += '_lndtropics'\n else:\n suffix += '_tropics'\n\nlog_file = open(\"plot_precip_log{}.txt\".format(suffix), 'w')\n\nnmonths = (END_YEAR - START_YEAR) * 12 - (START_MONTH - 1) + END_MONTH\nimonths = list(range(nmonths))\ncurr_month = START_MONTH\ncurr_year = START_YEAR\nmonths = []\nyears = []\nfor i in range(nmonths):\n months.append(curr_month)\n years.append(curr_year)\n curr_month += 1\n if curr_month > 12:\n curr_month = 1\n curr_year += 1\n\nout_file_template = \"{}.freq.{}-{}.nc\"\n\nfirst_file_name = out_file_template.format(REF_CASE_NAME, \"00\"+day_str(START_YEAR),\n day_str(START_MONTH))\n\nfirst_file = nc4.Dataset(join(OUTPUT_DIR, first_file_name), 'r')\nncol = len(first_file.dimensions['ncol'])\nnbins = len(first_file.dimensions['nbins'])\nbin_lower_bounds = first_file['bin_lower_bounds'][:]\nbin_width = np.log(bin_lower_bounds[2] / bin_lower_bounds[1])\nlat = first_file['lat'][:]\nlon = first_file['lon'][:]\narea = first_file['area'][:]\n# For tropics_only cases, just use a weight of 0 for all other columns.\nif TROPICS_ONLY:\n if LAND_TROPICS:\n # Just pick a random file with the same grid as the run.\n landfrac_file_name = '/p/lustre2/santos36/timestep_monthly_avgs/timestep_ctrl.0001-01.nc'\n landfrac_file = nc4.Dataset(landfrac_file_name, 'r')\n landfrac = landfrac_file['LANDFRAC'][0,:]\n for i in range(ncol):\n if np.abs(lat[i]) > 30.:\n area[i] = 0.\n else:\n area[i] *= landfrac[i]\n landfrac_file.close()\n else:\n for i in range(ncol):\n if np.abs(lat[i]) > 30.:\n area[i] = 0.\narea_sum = area.sum()\nweights = area/area_sum\nfirst_file.close()\n\nref_sample_num_total = 0\ntest_sample_num_total = 0\n\nprec_vars = (\"PRECC\", \"PRECL\", \"PRECT\")\n\nref_num_avgs = {}\nref_amount_avgs = {}\nfor var in prec_vars:\n ref_num_avgs[var] = np.zeros((nbins,))\n ref_amount_avgs[var] = np.zeros((nbins,))\n\ntest_num_avgs = {}\ntest_amount_avgs = {}\nfor var in prec_vars:\n test_num_avgs[var] = np.zeros((nbins,))\n test_amount_avgs[var] = np.zeros((nbins,))\n\nfor i in range(nmonths):\n year = years[i]\n year_string = \"00\" + day_str(year)\n month = months[i]\n month_string = day_str(month)\n\n print(\"On year {}, month {}.\".format(year, month))\n\n out_file_name = out_file_template.format(REF_CASE_NAME, year_string, month_string)\n out_file = nc4.Dataset(join(OUTPUT_DIR, out_file_name), 'r')\n\n ref_sample_num_total += out_file.sample_num\n\n for var in prec_vars:\n num_name = \"{}_num\".format(var)\n amount_name = \"{}_amount\".format(var)\n for j in range(ncol):\n ref_num_avgs[var] += out_file[num_name][j,:] * weights[j]\n for j in range(ncol):\n ref_amount_avgs[var] += out_file[amount_name][j,:] * weights[j]\n\n out_file_name = out_file_template.format(TEST_CASE_NAME, year_string, month_string)\n out_file = nc4.Dataset(join(OUTPUT_DIR, out_file_name), 'r')\n\n test_sample_num_total += out_file.sample_num\n\n for var in prec_vars:\n num_name = \"{}_num\".format(var)\n amount_name = \"{}_amount\".format(var)\n for j in range(ncol):\n test_num_avgs[var] += out_file[num_name][j,:] * weights[j]\n for j in range(ncol):\n test_amount_avgs[var] += out_file[amount_name][j,:] * weights[j]\n\nfor var in prec_vars:\n ref_num_avgs[var] /= ref_sample_num_total\n ref_amount_avgs[var] /= ref_sample_num_total\n test_num_avgs[var] /= test_sample_num_total\n test_amount_avgs[var] /= test_sample_num_total\n\n# Threshold for precipitation to be considered \"extreme\", in mm/day.\nPRECE_THRESHOLD = 97.\nibinthresh = -1\nfor i in range(nbins):\n if bin_lower_bounds[i] > PRECE_THRESHOLD:\n ibinthresh = i\n break\nif ibinthresh == -1:\n print(\"Warning: extreme precip threshold greater than largest bin bound.\")\n\nfor var in prec_vars:\n # Leave out zero bin from loglog plot.\n plt.loglog(bin_lower_bounds[1:], ref_num_avgs[var][1:], 'k')\n plt.loglog(bin_lower_bounds[1:], test_num_avgs[var][1:], 'r')\n plt.title(\"Frequency distribution of precipitation ({}/{}-{}/{})\".format(\n day_str(START_MONTH), day_str(START_YEAR),\n day_str(END_MONTH), day_str(END_YEAR)))\n plt.xlabel(\"Precipitation intensity (mm/day)\")\n plt.ylabel(\"fraction\")\n plt.savefig(\"{}_freq{}.png\".format(var, suffix))\n plt.close()\n\n plt.semilogx(bin_lower_bounds[1:], ref_amount_avgs[var][1:] / bin_width, 'k')\n plt.semilogx(bin_lower_bounds[1:], test_amount_avgs[var][1:] / bin_width, 'r')\n if var == \"PRECT\":\n print(\"Extreme precipitation rate for reference: \",\n ref_amount_avgs[var][ibinthresh:].sum(),\n file=log_file)\n print(\"Extreme precipitation rate for test: \",\n test_amount_avgs[var][ibinthresh:].sum(), \"(Diff = \",\n test_amount_avgs[var][ibinthresh:].sum() - ref_amount_avgs[var][ibinthresh:].sum(), \")\",\n file=log_file)\n plt.title(\"Amounts of precipitation ({}/{}-{}/{})\".format(\n day_str(START_MONTH), day_str(START_YEAR),\n day_str(END_MONTH), day_str(END_YEAR)))\n plt.xlabel(\"Precipitation intensity (mm/day)\")\n plt.ylabel(\"Average precipitation amount (mm/day)\")\n plt.savefig(\"{}_amount{}.png\".format(var, suffix))\n plt.close()\n\nlog_file.close()\n" }, { "alpha_fraction": 0.39393940567970276, "alphanum_fraction": 0.6727272868156433, "avg_line_length": 36.5, "blob_id": "33a0b9f4b9939ab189f2d5e3d887e30b44bcb035", "content_id": "e0e87f7560b40683806ad49526d4e52ddf603285", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 825, "license_type": "permissive", "max_line_length": 151, "num_lines": 22, "path": "/create_daily_averages.sh", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nCASE_NAMES=\"timestep_presaer_cld_10s_lower_tau2\"\n#DAYS=\"01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\"\nDAYS=\"01 02 03 04 05 06 07 08 09 10 11 12 13 14 15\"\nOUTPUT_DIR=/p/lscratchh/santos36/timestep_daily_avgs\n\ntimes=\"00000 03600 07200 10800 14400 18000 21600 25200 28800 32400 36000 39600 43200 46800 50400 54000 57600 61200 64800 68400 72000 75600 79200 82800\"\n\nfor case_name in $CASE_NAMES; do\n date\n echo \"On case $case_name\"\n case_dir=/p/lscratchh/santos36/ACME/$case_name/run\n for day in $DAYS; do\n filenames=\n for time in $times; do\n filenames=\"$filenames $case_dir/$case_name.cam.h0.0001-01-$day-$time.nc\"\n done\n echo \"On day $day.\"\n ncra -O $filenames $OUTPUT_DIR/$case_name.0001-01-$day.nc\n done\ndone\n" }, { "alpha_fraction": 0.5972568392753601, "alphanum_fraction": 0.6870324015617371, "avg_line_length": 33.869564056396484, "blob_id": "1617da20c6e3f25fb3c15543e67bca0f0d2ee90f", "content_id": "62db4904f0fe3efe2e1e4efede21ad3b2f93748e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 802, "license_type": "permissive", "max_line_length": 116, "num_lines": 23, "path": "/regrid_monthly_avgs.sh", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nREMAP_FILE_NE30=/usr/gdata/climdat/maps/map_ne16np4_to_ne30np4_aave.20160601.nc\nREMAP_FILE=/usr/gdata/climdat/maps/map_ne30np4_to_fv128x256_aave.20160301.nc\nIN_DIR=/p/lscratchh/santos36/timestep_monthly_avgs\nOUT_DIR=/p/lscratchh/santos36/timestep_monthly_avgs_lat_lon\nCASE_NAMES=\"timestep_ctrl\"\n#MONTHS=\"01 02 03 04 05 06 07 08 09 10 11 12\"\nMONTHS=\"01\"\nYEAR=\"0007\"\n\nfor case_name in $CASE_NAMES; do\n date\n echo \"On case $case_name\"\n filenames=\n for month in $MONTHS; do\n date\n echo \"On month $month\"\n filenames=\"$filenames $IN_DIR/$case_name.$YEAR-$month.nc\"\n# ncremap -m $REMAP_FILE_NE30 -o $IN_DIR/$case_name.$YEAR-$month.nc $IN_DIR/$case_name.cam.h0.$YEAR-$month.nc\n done\n ls $filenames | ncremap -p bck -j 12 -m $REMAP_FILE -O $OUT_DIR\ndone\n" }, { "alpha_fraction": 0.5448437929153442, "alphanum_fraction": 0.559818685054779, "avg_line_length": 34.09659194946289, "blob_id": "e070fc54b64185574a3174f4d7e8678d6e65d81e", "content_id": "ac6fa6cfe14a0fb17bf8807a6a1ca9a5f9cf504b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12354, "license_type": "permissive", "max_line_length": 150, "num_lines": 352, "path": "/plot_monthly_means.py", "repo_name": "quantheory/E3SMTimestepStudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom functools import partial\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport netCDF4 as nc4\n\nfrom e3sm_case_output import E3SMCaseOutput, day_str\n\nSTART_YEAR = 1\nSTART_MONTH = 1\nEND_YEAR = 4\nEND_MONTH = 2\n\nSTART_AVG_YEAR = 1\nSTART_AVG_MONTH = 3\nEND_AVG_YEAR = 4\nEND_AVG_MONTH = 2\n\nMONTHLY_FILE_LOC=\"/p/lscratchh/santos36/timestep_monthly_avgs/\"\n\nUSE_PRESAER=False\nLAND_TROPICS = True\nTROPICS_ONLY=False\nMIDLATITUDES_ONLY=False\n\nif LAND_TROPICS:\n TROPICS_ONLY = True\n\nassert not (TROPICS_ONLY and MIDLATITUDES_ONLY), \\\n \"can't do only tropics and only midlatitudes\"\n\nnmonths = (END_YEAR - START_YEAR) * 12 - (START_MONTH - 1) + END_MONTH\nimonths = list(range(nmonths))\ncurr_month = START_MONTH\ncurr_year = START_YEAR\nmonths = []\nyears = []\nfor i in range(nmonths):\n months.append(curr_month)\n years.append(curr_year)\n curr_month += 1\n if curr_month > 12:\n curr_month = 1\n curr_year += 1\nnavgmonths = (END_AVG_YEAR - START_AVG_YEAR) * 12 \\\n - (START_AVG_MONTH - 1) + END_AVG_MONTH\n\nsuffix = '_y{}m{}-y{}m{}'.format(day_str(START_YEAR),\n day_str(START_MONTH),\n day_str(END_YEAR),\n day_str(END_MONTH))\nif USE_PRESAER:\n suffix += '_presaer'\nif TROPICS_ONLY:\n if LAND_TROPICS:\n suffix += '_lndtropics'\n else:\n suffix += '_tropics'\nif MIDLATITUDES_ONLY:\n suffix += '_midlats'\n\nlog_file = open(\"plot_monthly_log{}.txt\".format(suffix), 'w')\n\nif USE_PRESAER:\n REF_CASE = E3SMCaseOutput(\"timestep_presaer_ctrl\", \"CTRLPA\", MONTHLY_FILE_LOC, START_MONTH, END_MONTH)\n TEST_CASES = [\n ]\nelse:\n REF_CASE = E3SMCaseOutput(\"timestep_ctrl\", \"CTRL\", MONTHLY_FILE_LOC, START_MONTH, END_MONTH)\n TEST_CASES = [\n E3SMCaseOutput(\"timestep_all_10s\", \"ALL10\", MONTHLY_FILE_LOC, START_MONTH, END_MONTH),\n ]\n\ncase_num = len(TEST_CASES)\n\nrfile0 = nc4.Dataset(REF_CASE.get_monthly_file_name(START_MONTH, START_YEAR), 'r')\nnlev = len(rfile0.dimensions['lev'])\nncol = len(rfile0.dimensions['ncol'])\narea = rfile0['area'][:]\n# For tropics_only cases, just use a weight of 0 for all other cases.\nif TROPICS_ONLY:\n lat = rfile0['lat'][:]\n if LAND_TROPICS:\n landfrac = rfile0['LANDFRAC'][0,:]\n for i in range(ncol):\n if np.abs(lat[i]) > 30.:\n area[i] = 0.\n else:\n area[i] *= landfrac[i]\n else:\n for i in range(ncol):\n if np.abs(lat[i]) > 30.:\n area[i] = 0.\n# Same for midlatitudes.\nelif MIDLATITUDES_ONLY:\n lat = rfile0['lat'][:]\n for i in range(ncol):\n if np.abs(lat[i]) < 30. or np.abs(lat[i]) > 60.:\n area[i] = 0.\narea_sum = area.sum()\nweights = area/area_sum\nrfile0.close()\n\ndef calc_var_stats(ref_case, test_cases, month, year, varnames):\n varnames_read = [name for name in varnames if name != \"PRECT\" and name != \"TAU\"]\n if \"PRECT\" in varnames:\n if \"PRECL\" not in varnames:\n varnames_read.append(\"PRECL\")\n if \"PRECC\" not in varnames:\n varnames_read.append(\"PRECC\")\n if \"TAU\" in varnames:\n if \"TAUX\" not in varnames:\n varnames_read.append(\"TAUX\")\n if \"TAUY\" not in varnames:\n varnames_read.append(\"TAUY\")\n ref_time_avg, test_time_avgs, diff_time_avgs = ref_case.compare_monthly_averages(test_cases, month, year, varnames_read)\n if \"PRECT\" in varnames:\n ref_time_avg[\"PRECT\"] = ref_time_avg[\"PRECL\"] + ref_time_avg[\"PRECC\"]\n for icase in range(case_num):\n test_time_avgs[icase][\"PRECT\"] = test_time_avgs[icase][\"PRECL\"] + test_time_avgs[icase][\"PRECC\"]\n diff_time_avgs[icase][\"PRECT\"] = diff_time_avgs[icase][\"PRECL\"] + diff_time_avgs[icase][\"PRECC\"]\n if \"TAU\" in varnames:\n ref_time_avg[\"TAU\"] = np.sqrt(ref_time_avg[\"TAUX\"]**2 + ref_time_avg[\"TAUY\"]**2)\n for icase in range(case_num):\n test_time_avgs[icase][\"TAU\"] = np.sqrt(test_time_avgs[icase][\"TAUX\"]**2 + test_time_avgs[icase][\"TAUY\"]**2)\n diff_time_avgs[icase][\"TAU\"] = test_time_avgs[icase][\"TAU\"] - ref_time_avg[\"TAU\"]\n ref_avg = dict()\n test_avgs = dict()\n diff_avgs = dict()\n rmses = dict()\n for varname in varnames:\n if varname in vars_3D:\n ref_avg[varname] = np.zeros((nlev,))\n for jlev in range(nlev):\n ref_avg[varname][jlev] = (ref_time_avg[varname][jlev,:] * weights).sum()\n else:\n ref_avg[varname] = (ref_time_avg[varname] * weights).sum()\n test_avgs[varname] = []\n diff_avgs[varname] = []\n rmses[varname] = []\n for i in range(len(test_cases)):\n if varname in vars_3D:\n test_avgs[varname].append(np.zeros((nlev,)))\n diff_avgs[varname].append(np.zeros((nlev,)))\n rmses[varname].append(np.zeros((nlev,)))\n for jlev in range(nlev):\n test_avgs[varname][-1][jlev] = (test_time_avgs[i][varname][jlev,:] * weights).sum()\n diff_avgs[varname][-1][jlev] = (diff_time_avgs[i][varname][jlev,:] * weights).sum()\n rmses[varname][-1][jlev] = np.sqrt((diff_time_avgs[i][varname][jlev,:]**2 * weights).sum())\n else:\n test_avgs[varname].append((test_time_avgs[i][varname] * weights).sum())\n diff_avgs[varname].append((diff_time_avgs[i][varname] * weights).sum())\n rmses[varname].append(np.sqrt((diff_time_avgs[i][varname]**2 * weights).sum()))\n assert np.isclose(diff_avgs[varname][i], test_avgs[varname][i] - ref_avg[varname]).all(), \\\n \"Problem with diff of variable {} from case {}\".format(varname, TEST_CASES[i].short_name)\n return (ref_avg, test_avgs, diff_avgs, rmses)\n\n# Possible ways to extract a 2D section start here:\ndef identity(x):\n return x\n\ndef slice_at(level, x):\n return x[:,level]\n\ndef plot_vars_over_time(names, units, scales, log_plot_names):\n ref_means = dict()\n test_means = dict()\n diff_means = dict()\n rmses = dict()\n for name in names:\n if name in vars_3D:\n ref_means[name] = np.zeros((nmonths, nlev))\n test_means[name] = np.zeros((case_num, nmonths, nlev))\n diff_means[name] = np.zeros((case_num, nmonths, nlev))\n rmses[name] = np.zeros((case_num, nmonths, nlev))\n else:\n ref_means[name] = np.zeros((nmonths,))\n test_means[name] = np.zeros((case_num, nmonths))\n diff_means[name] = np.zeros((case_num, nmonths))\n rmses[name] = np.zeros((case_num, nmonths))\n\n for imonth in range(nmonths):\n month = months[imonth]\n year = years[imonth]\n print(\"On month: \", month, \", year: \", year, file=log_file, flush=True)\n ref_mean, test_case_means, diff_case_means, case_rmses = calc_var_stats(REF_CASE, TEST_CASES, month, year, names)\n for name in names:\n ref_means[name][imonth] = ref_mean[name]*scales[name]\n for i in range(case_num):\n test_means[name][i,imonth] = test_case_means[name][i]*scales[name]\n diff_means[name][i,imonth] = diff_case_means[name][i]*scales[name]\n rmses[name][i,imonth] = case_rmses[name][i]*scales[name]\n\n for name in names:\n plot_name = name\n if name in plot_names:\n plot_name = plot_names[name]\n\n get_2D = identity\n if name == \"RELHUM\" or name == \"Q\" or name == \"T\":\n get_2D = partial(slice_at, nlev-1)\n\n if name in log_plot_names:\n plot_var = plt.semilogy\n else:\n plot_var = plt.plot\n ref_plot_var = get_2D(ref_means[name])\n plot_var(imonths, ref_plot_var, label=REF_CASE.short_name)\n for i in range(case_num):\n test_plot_var = get_2D(test_means[name][i])\n plot_var(imonths,\n test_plot_var,\n label=TEST_CASES[i].short_name)\n plt.axis('tight')\n plt.xlabel(\"month\")\n plt.ylabel(\"Mean {} ({})\".format(plot_name, units[name]))\n plt.savefig('{}_time{}.png'.format(name, suffix))\n plt.close()\n\n for i in range(case_num):\n diff_plot_var = get_2D(diff_means[name][i])\n plot_var(imonths,\n diff_plot_var,\n label=TEST_CASES[i].short_name)\n plt.axis('tight')\n plt.xlabel(\"month\")\n plt.ylabel(\"Mean {} difference ({})\".format(plot_name, units[name]))\n plt.savefig('{}_diff_time{}.png'.format(name, suffix))\n plt.close()\n\n for i in range(case_num):\n rmse_plot_var = get_2D(rmses[name][i])\n plot_var(imonths,\n rmse_plot_var,\n label=TEST_CASES[i].short_name)\n plt.axis('tight')\n plt.xlabel(\"month\")\n plt.ylabel(\"{} RMSE ({})\".format(plot_name, units[name]))\n plt.savefig('{}_rmse_time{}.png'.format(name, suffix))\n plt.close()\n\n month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n month_weights = [month_days[months[imonth] - 1] for imonth in imonths]\n weight_norm = sum(month_weights)\n month_weights = [weight / weight_norm for weight in month_weights]\n print(name, \" has reference mean: \", sum([ref_plot_var[imonth] * month_weights[imonth] for imonth in imonths]),\n file=log_file)\n for i in range(case_num):\n test_plot_var = get_2D(test_means[name][i])\n diff_plot_var = get_2D(diff_means[name][i])\n print(name, \" has case \", TEST_CASES[i].short_name, \" mean: \", sum([test_plot_var[imonth] * month_weights[imonth] for imonth in imonths]),\n file=log_file)\n print(name, \" has difference mean: \", sum([diff_plot_var[imonth] * month_weights[imonth] for imonth in imonths]),\n file=log_file)\n\nplot_names = {\n 'LWCF': \"long-wave cloud forcing\",\n 'SWCF': \"short wave cloud forcing\",\n 'PRECC': \"convective precipitation\",\n 'PRECL': \"large scale precipitation\",\n 'PRECT': \"total precipitation\",\n 'TGCLDIWP': \"ice water path\",\n 'TGCLDLWP': \"liquid water path\",\n 'CLDTOT': \"cloud area fraction\",\n 'CLDLOW': \"low cloud area fraction\",\n 'CLDMED': \"mid-level cloud area fraction\",\n 'CLDHGH': \"high cloud area fraction\",\n 'LHFLX': \"latent heat flux\",\n 'SHFLX': \"sensible heat flux\",\n 'TAU': \"surface wind stress\",\n 'TS': \"surface temperature\",\n 'PSL': \"sea level pressure\",\n 'OMEGA500': \"vertical velocity at 500 mb\",\n 'U10': \"10 meter wind speed\",\n 'RELHUM': \"surface relative humidity\",\n 'Q': \"surface specific humidity\",\n 'TMQ': \"precipitable water\",\n 'T': \"lowest level temperature\",\n}\n\nunits = {\n 'LWCF': r'$W/m^2$',\n 'SWCF': r'$W/m^2$',\n 'PRECC': r'$mm/day$',\n 'PRECL': r'$mm/day$',\n 'PRECT': r'$mm/day$',\n 'TGCLDIWP': r'$g/m^2$',\n 'TGCLDLWP': r'$g/m^2$',\n 'AODABS': r'units?',\n 'AODUV': r'units?',\n 'AODVIS': r'units?',\n 'FLDS': r'$W/m^2$',\n 'FLNS': r'$W/m^2$',\n 'FLNSC': r'$W/m^2$',\n 'FLNT': r'$W/m^2$',\n 'FLNTC': r'$W/m^2$',\n 'FLUT': r'$W/m^2$',\n 'FLUTC': r'$W/m^2$',\n 'FSDS': r'$W/m^2$',\n 'FSDSC': r'$W/m^2$',\n 'FSNS': r'$W/m^2$',\n 'FSNSC': r'$W/m^2$',\n 'FSNT': r'$W/m^2$',\n 'FSNTC': r'$W/m^2$',\n 'FSNTOA': r'$W/m^2$',\n 'FSNTOAC': r'$W/m^2$',\n 'FSUTOA': r'$W/m^2$',\n 'FSUTOAC': r'$W/m^2$',\n 'CLDTOT': r'fraction',\n 'CLDLOW': r'fraction',\n 'CLDMED': r'fraction',\n 'CLDHGH': r'fraction',\n 'OMEGA500': r'Pa/s',\n 'LHFLX': r'$W/m^2$',\n 'SHFLX': r'$W/m^2$',\n 'TAU': r'$N/m^2$',\n 'TAUX': r'$N/m^2$',\n 'TAUY': r'$N/m^2$',\n 'TS': r'$K$',\n 'PSL': r'$Pa$',\n 'U10': r'$m/s$',\n 'RELHUM': r'%',\n 'Q': r'$g/kg$',\n 'TMQ': r'$kg/m^2$',\n 'T': r'$K$',\n}\nnames = list(units.keys())\nscales = dict()\nfor name in names:\n scales[name] = 1.\nscales['TGCLDIWP'] = 1000.\nscales['TGCLDLWP'] = 1000.\nscales['PRECC'] = 1000.*86400.\nscales['PRECL'] = 1000.*86400.\nscales['PRECT'] = 1000.*86400.\nscales['Q'] = 1000.\n\nvars_3D = [\n 'RELHUM',\n 'Q',\n 'T',\n]\n\nlog_plot_names = []#'AODABS', 'AODVIS', 'AODUV']\n\nplot_vars_over_time(names, units, scales, log_plot_names)\n\nlog_file.close()\n" } ]
24
sauravsrijan/bookmarks
https://github.com/sauravsrijan/bookmarks
3a680232cef0c6967f3e817d9c99a59937232b53
de5bc24c050e9ca983e3de945fa93f588c40b570
6bab1a3b3b7de5dfd1d6ede385067e8af765ea36
refs/heads/master
2020-12-29T16:15:21.810398
2020-01-24T11:46:26
2020-01-24T11:46:26
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6502057909965515, "alphanum_fraction": 0.6662551164627075, "avg_line_length": 37.57143020629883, "blob_id": "a838672d78cfa9c098caf11cc83c6880dc276776", "content_id": "6fc6f2d983f5968e82ddf9cb69369908d4883daf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2430, "license_type": "no_license", "max_line_length": 151, "num_lines": 63, "path": "/main.py", "repo_name": "sauravsrijan/bookmarks", "src_encoding": "UTF-8", "text": "import argparse\nfrom bcolors import bcolors \nfrom actions.show import show \nfrom actions.add import add \n\nargumentparser = argparse.ArgumentParser(description=\"Bookmarks in command line!\") # skipcq: FLK-E501\nargumentparser.add_argument('--action', type=str, help=\"Choose action, can be: add or show\") # skipcq: FLK-E501\nargumentparser.add_argument('--folder', type=str, help=\"Choose folder where to do the action\") # skipcq: FLK-E501\nargumentparser.add_argument('--name', type=str, help=\"Name of the bookmark you want to add (if action=add) or see (if action=show)\") # skipcq: FLK-E501\nargumentparser.add_argument('--desc', type=str, help=\"Description of the bookmark you want to add (if action=add else its ignored)\") # skipcq: FLK-E501\nargumentparser.add_argument('--url', type=str, help=\"Url of the bookmark you want to add (if action=add) or see (if action=show)\") # skipcq: FLK-E501\n\nargs = argumentparser.parse_args()\n\nvalidactions = [\"show\", \"add\"]\naction = None\nfolder = None\n\n\n\ndef warn(t):\n print(bcolors.WARNING + \"Warning: \" + bcolors.ENDC + t)\ndef error(t):\n print(bcolors.FAIL + \"Error: \" + bcolors.ENDC + t)\n\ndef blank():\n print(\"\")\n print(\"\")\n\nif args.action:\n if args.action in validactions:\n action = args.action\n else:\n warn(args.action + \" is not a valid action, using default action: show\") # skipcq: FLK-E501\n action = \"show\"\nelse:\n warn(\"No action has been specified in --action argument, using default action: show\") # skipcq: FLK-E501\n action = \"show\"\n\nif args.folder:\n folder = args.folder\nelse:\n warn(\"No folder has been specified in --folder argument, using default folder: unsorted\") # skipcq: FLK-E501\n folder = \"unsorted\"\n blank()\n\nprint(bcolors.OKGREEN + \"ACTION:\" + bcolors.ENDC + action + bcolors.OKGREEN + \"; FOLDER:\" + bcolors.ENDC + folder) # skipcq: FLK-E501\n\nblank()\n\nif action == \"show\":\n show(folder)\nif action == \"add\":\n if args.name:\n if args.desc:\n if args.url:\n add(folder, args.name, args.url, args.desc)\n else:\n error('--url is empty, when action=add, you must specify an url using --url') # skipcq: FLK-E501 \n else:\n error('--desc is empty, when action=add, you must specify an description using --desc') # skipcq: FLK-E501\n else:\n error('--name is empty, when action=add, you must specify an name using --name') # skipcq: FLK-E501\n" }, { "alpha_fraction": 0.43145161867141724, "alphanum_fraction": 0.44112902879714966, "avg_line_length": 35.5, "blob_id": "c7244ae93f5a2fabc488626f73b6e3f95f01c1b5", "content_id": "1b86ccb97333a1b8d9a6562c984367b52329f889", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1240, "license_type": "no_license", "max_line_length": 135, "num_lines": 34, "path": "/actions/show.py", "repo_name": "sauravsrijan/bookmarks", "src_encoding": "UTF-8", "text": "from bcolors import bcolors\n\ndef show(folder):\n folder = folder\n path = \"bookmarks/\" + folder + \".txt\"\n try:\n with open(path) as fp:\n bookmarks = fp.read().split(\"\\n\")\n parsed = []\n for bookmark in bookmarks:\n \n \n if bookmark == '':\n pass\n else:\n\n url = bookmark.split(\":\")[0]\n name = bookmark.split(\":\")[1]\n description = bookmark.split(\":\")[2]\n \n\n parsed.append({\n \"url\": url,\n \"name\": name,\n \"description\": description,\n \"folder\": folder\n })\n for bookmark in parsed:\n print(bcolors.OKBLUE + bookmark[\"name\"] + bcolors.ENDC) # skipcq: FLK-E501\n print(bcolors.OKGREEN + \"URL: \" + bcolors.ENDC + bcolors.UNDERLINE + bookmark[\"url\"] + bcolors.ENDC) # skipcq: FLK-E501\n print(bcolors.OKGREEN + \"Description: \" + bcolors.ENDC + bookmark[\"description\"]) # skipcq: FLK-E501\n except IOError:\n with open(path, 'w+') as fp:\n show(folder)" }, { "alpha_fraction": 0.7347122430801392, "alphanum_fraction": 0.7356114983558655, "avg_line_length": 40.22222137451172, "blob_id": "52ef420931f9db4beb2357f6d646ff127a6ac609", "content_id": "48518d712ff6d3d6fa0ce3844147c4b2be7fbcee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 194, "num_lines": 27, "path": "/readme.md", "repo_name": "sauravsrijan/bookmarks", "src_encoding": "UTF-8", "text": "# **bookmarks** in the terminal\n\n## Basics:\nEvery time you run the script you need to specify a folder and an action. If you don't, the script will use the defaults values which are:\n**action=show**\n**folder=unsorted**. So it will show (print) the bookmarks in the unsorted folder\n\n## Usage:\n### Getting started\n```\npython3 main.py\n```\nThis will use the default action: `show` and the default folder: `unsorted` (as explained in the basics section)\n\n### Showing bookmarks from specific folders\n\nJust add `--folder <name of the folder>`. If there are no bookmarks in the folder, it will create a file to store them in `bookmarks/<folder name>.txt`\n\n### Adding bookmarks\n\nJust set `--action add` and specify `--folder` (otherwise it will use the default value, `unsorted`), `--name` with the name of the bookmark, `--url` with the url, `--desc` with the description.\n\nIf the selected folder does not exisit, it will create a file to store them in `bookmarks/<folder name>.txt`\n\n## Exporting and importing bookmarks \n\n`bookmarks/` folder is the folder you need to save put your bookmarks for exporting and importing" }, { "alpha_fraction": 0.4755244851112366, "alphanum_fraction": 0.4755244851112366, "avg_line_length": 27.700000762939453, "blob_id": "18b35406a7f379384a405894ba108719d8c1b47b", "content_id": "4542e89675139909747d5c91d2b5336f5bed7121", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "no_license", "max_line_length": 58, "num_lines": 10, "path": "/actions/add.py", "repo_name": "sauravsrijan/bookmarks", "src_encoding": "UTF-8", "text": "def add(folder, name, url, desc):\n \n folder = folder\n path = \"bookmarks/\" + folder + \".txt\"\n try:\n with open(path, 'a') as fp:\n fp.write(url + ':' + name + ':' + desc + '\\n')\n except IOError:\n with open(path, 'w+') as fp:\n show(folder)" } ]
4
bunya017/brokenChains
https://github.com/bunya017/brokenChains
970d1c65886b4f68023d4665a34f7fff2932d081
3e20c834efd7f0ade8e3abe7acf547c093f76758
cbc37c553833e6ff4bd0c5b473427aa99dc867d2
refs/heads/master
2020-04-05T22:08:56.866300
2020-02-10T11:03:47
2020-02-10T11:04:20
157,246,570
1
0
MIT
2018-11-12T16:56:05
2019-10-14T18:16:49
2019-10-14T18:16:57
Python
[ { "alpha_fraction": 0.5152542591094971, "alphanum_fraction": 0.5796610116958618, "avg_line_length": 23.58333396911621, "blob_id": "072b8fd1378eeb60ec0f10e515a040ce6e078323", "content_id": "ca58a461d812f779940b99bbc06a18918a528290", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 590, "license_type": "permissive", "max_line_length": 70, "num_lines": 24, "path": "/brokenChains/migrations/0005_auto_20200210_1202.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.10 on 2020-02-10 11:02\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brokenChains', '0004_auto_20181217_0105'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='habit',\n name='start_date',\n field=models.DateField(auto_now_add=True),\n ),\n migrations.AlterField(\n model_name='habit',\n name='stop_date',\n field=models.DateField(default=datetime.date(2020, 3, 2)),\n ),\n ]\n" }, { "alpha_fraction": 0.6622428894042969, "alphanum_fraction": 0.6768413782119751, "avg_line_length": 25.438596725463867, "blob_id": "9ed82dad9458c8b0e9fa28b79e931d9bdec8c9fb", "content_id": "32fd979b2f6cc94a84b5d9b446f01702906f01d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1507, "license_type": "permissive", "max_line_length": 89, "num_lines": 57, "path": "/README.rst", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "============\nBrokenChains\n============\n.. image:: https://travis-ci.org/bunya017/brokenChains.svg?branch=master\n :target: https://travis-ci.org/bunya017/brokenChains\n\nBrokenChains is a habit tracking api built with ``django``\nand ``djangoRestFramework``. Its an attempt to learn API\ndevelopment with djangorestframework.\n\n\nRequirements\n------------\n\n* Python 3.6+\n* Django 2.2+\n* djangorestframework 3.7+\n\n\nInstallation\n------------\n1. Create and activate a python virtual environment:\n * venv --your-env--\n2. Activate the virtual environment:\n * --your-env--/Scripts/activate\n * pip install -r requirements.txt\n3. Make and run migrations:\n * python manage.py makemigrations\n * python manage.py migrate\n\n\nUsage\n-----\nRun ``python manage.py runserver`` to start the server and\nopen ``http://localhost:8000/api`` on your browser\n\n``Note``: All actions require authentication/authorization.\n\n\nAPI Endpoints\n------------\n* ``POST /api-token-auth`` - Get authorization token\n* ``POST /api/users/signup`` - User registration\n* ``GET /api/habits`` - List habits\n* ``POST /api/habits`` - Create habit\n* ``GET /api/habits/{id}`` - Show habit detail\n* ``DELETE /api/habits/{id}`` - Delete habit\n* ``GET /api/sessions`` - List sessions\n* ``POST /api/sessions`` - Create session\n* ``GET /api/sessions/{id}`` - Show session detail\n* ``DELETE /api/sessions/{id}`` - Delete session\n\n\nToDo\n----\n- [x] Frontend Client: `brokenChains-Cli <https://github.com/bunya017/brokenChains-Cli>`_\n- [ ] Mobile Client\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 18.799999237060547, "blob_id": "805523bb7b2a81e633fda6ab4c39d07361359019", "content_id": "d90a0865599b69d729f8e59d05ad74bb87194f46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "permissive", "max_line_length": 36, "num_lines": 5, "path": "/brokenChains/apps.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass BrokenchainsConfig(AppConfig):\n name = 'brokenChains'\n" }, { "alpha_fraction": 0.7629440426826477, "alphanum_fraction": 0.7636405825614929, "avg_line_length": 33.19047546386719, "blob_id": "8e707f7cadaa2034028e2e8a22ccd2cbe79db25e", "content_id": "ce3c3a0a6e8047d7126bccadd1fc5a1f5a9cb907", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4307, "license_type": "permissive", "max_line_length": 93, "num_lines": 126, "path": "/brokenChains/views.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "from django.contrib.auth.models import User\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom django.utils.decorators import method_decorator\nfrom rest_framework import generics, permissions, serializers, status\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.authtoken.views import ObtainAuthToken as DRFObtainAuthToken\nfrom rest_framework.exceptions import APIException, NotAuthenticated, PermissionDenied\nfrom rest_framework.response import Response\nfrom .models import Habit, Session\nfrom .serializers import HabitSerializer, SessionSerializer, UserSerializer\n\n\n\nclass HabitList(generics.ListCreateAPIView):\n\tserializer_class = HabitSerializer\n\tpermission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\tdef get_queryset(self):\n\t\ttry:\n\t\t\tqueryset = Habit.objects.all().filter(owner=self.request.user)\n\t\texcept TypeError:\n\t\t\traise NotAuthenticated\n\t\telse:\n\t\t\treturn queryset\n\n\tdef perform_create(self, serializer):\n\t\tdata = serializer.validated_data\n\t\tname = data['name'].title()\n\t\tdetail = 'Oops! You have created a habit with this name: \\'' + data['name'] + '\\' already.'\n\t\tif Habit.objects.filter(owner=self.request.user, name=name).exists():\n\t\t\traise PermissionDenied(detail=detail)\n\t\tserializer.save(owner=self.request.user)\n\n\t@method_decorator(ensure_csrf_cookie)\n\tdef post(self, request, *args, **kwargs):\n\t\treturn self.create(request, *args, **kwargs)\n\n\nclass HabitDetail(generics.RetrieveDestroyAPIView):\n\tserializer_class = HabitSerializer\n\tpermission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\tdef get_queryset(self):\n\t\ttry:\n\t\t\tqueryset = Habit.objects.all().filter(owner=self.request.user)\n\t\texcept TypeError:\n\t\t\traise NotAuthenticated\n\t\telse:\n\t\t\treturn queryset\n\n\t@method_decorator(ensure_csrf_cookie)\n\tdef delete(self, request, *args, **kwargs):\n\t\treturn self.destroy(request, *args, **kwargs)\n\n\nclass SessionList(generics.ListCreateAPIView):\n\tserializer_class = SessionSerializer\n\tpermission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\tdef get_queryset(self):\n\t\ttry:\n\t\t\tqueryset = Session.objects.all().filter(habit__owner=self.request.user)\n\t\texcept TypeError:\n\t\t\traise NotAuthenticated\n\t\telse:\n\t\t\treturn queryset\n\n\t@method_decorator(ensure_csrf_cookie)\n\tdef post(self, request, *args, **kwargs):\n\t\treturn self.create(request, *args, **kwargs)\n\n\nclass SessionDetail(generics.RetrieveDestroyAPIView):\n\tserializer_class = SessionSerializer\n\tpermission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\tdef get_queryset(self):\n\t\ttry:\n\t\t\tqueryset = Session.objects.all().filter(habit__owner=self.request.user)\n\t\texcept TypeError:\n\t\t\traise NotAuthenticated\n\t\telse:\n\t\t\treturn queryset\n\n\t@method_decorator(ensure_csrf_cookie)\n\tdef delete(self, request, *args, **kwargs):\n\t\treturn self.destroy(request, *args, **kwargs)\n\n\nclass ObtainAuthToken(DRFObtainAuthToken):\n\n\t@method_decorator(ensure_csrf_cookie)\n\tdef post(self, request, *args, **kwargs):\n\t\tserializer = self.serializer_class(data=request.data, context={'request': request})\n\t\tserializer.is_valid(raise_exception=True)\n\t\tuser = serializer.validated_data['user']\n\t\ttoken, created = Token.objects.get_or_create(user=user)\n\t\treturn Response({'token': token.key})\n\n\nclass UserRegistration(generics.CreateAPIView):\n\tserializer_class = UserSerializer\n\tpermission_classes = (permissions.AllowAny,)\n\n\tdef perform_create(self, serializer):\n\t\tdata = serializer.validated_data\n\t\temail = data['email']\n\t\tif email == '':\n\t\t\traise serializers.ValidationError({'email': 'This field may not be blank.'})\n\t\telif User.objects.filter(email=email).exists():\n\t\t\traise serializers.ValidationError({'email': 'A user with that email already exists.'})\n\n\t\tserializer.save()\n\n\tdef create(self, request, *args, **kwargs): # <- here i forgot self\n\t\tserializer = self.get_serializer(data=request.data)\n\t\tserializer.is_valid(raise_exception=True)\n\t\tself.perform_create(serializer)\n\t\theaders = self.get_success_headers(serializer.data)\n\t\ttoken, created = Token.objects.get_or_create(user=serializer.instance)\n\t\tserialized_user = UserSerializer(token.user, context={'request': request})\n\t\treturn Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers)\n\n\t@method_decorator(ensure_csrf_cookie)\n\tdef post(self, request, *args, **kwargs):\n\t\treturn self.create(request, *args, **kwargs)" }, { "alpha_fraction": 0.7032442688941956, "alphanum_fraction": 0.7032442688941956, "avg_line_length": 26.605262756347656, "blob_id": "9c2d81b846d15a6aa888a039972bb6a5d50a693b", "content_id": "7ca5c1795721293cc5feacd40aec1f48b4f92681", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1048, "license_type": "permissive", "max_line_length": 89, "num_lines": 38, "path": "/brokenChains/serializers.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "from django.contrib.auth.models import User\nfrom rest_framework import serializers\nfrom .models import Habit, Session\n\n\n\nclass SessionSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Session\n\t\tfields = ('id', 'url', 'habit', 'name', 'text', 'date', 'is_complete')\n\t\tread_only_fields = ('name',)\n\n\nclass HabitSerializer(serializers.ModelSerializer):\n\towner = serializers.ReadOnlyField(source='owner.username')\n\tsessions = SessionSerializer(many=True, read_only=True)\n\n\tclass Meta:\n\t\tmodel = Habit\n\t\tfields = ('id', 'url', 'owner', 'name', 'goal', 'start_date', 'stop_date', 'sessions')\n\n\nclass UserSerializer(serializers.ModelSerializer):\n\thabits = HabitSerializer(many=True, read_only=True)\n\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = ('id', 'username', 'email', 'habits', 'password')\n\t\textra_kwargs = {'password': {'write_only': True}}\n\n\tdef create(self, validated_data):\n\t\tuser = User(\n\t\t\temail=validated_data['email'],\n\t\t\tusername=validated_data['username'],\n\t\t)\n\t\tuser.set_password(validated_data['password'])\n\t\tuser.save()\n\t\treturn user" }, { "alpha_fraction": 0.8018433451652527, "alphanum_fraction": 0.8018433451652527, "avg_line_length": 23.22222137451172, "blob_id": "bb5863f0140cf7681ed9449d8288ad483717eaca", "content_id": "ac49b4ce36f1c7c4df915bf68eb047ed38286128", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 217, "license_type": "permissive", "max_line_length": 53, "num_lines": 9, "path": "/brokenChains/admin.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Habit, Session\nfrom rest_framework.authtoken.admin import TokenAdmin\n\n\n\nTokenAdmin.raw_id_fields = ('user',)\nadmin.site.register(Habit)\nadmin.site.register(Session)" }, { "alpha_fraction": 0.5317220687866211, "alphanum_fraction": 0.5891238451004028, "avg_line_length": 18.47058868408203, "blob_id": "69955ef38f6cf818b1ed029d9f2fa6d548a93b64", "content_id": "a67fb0119c21be91392e72a53481e491c9ad0655", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "permissive", "max_line_length": 47, "num_lines": 17, "path": "/brokenChains/migrations/0002_auto_20181106_1723.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-11-06 16:23\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brokenChains', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterUniqueTogether(\n name='habit',\n unique_together=set(),\n ),\n ]\n" }, { "alpha_fraction": 0.7222541570663452, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 30.600000381469727, "blob_id": "3c8532971330519aab359334a8036f420b97fcd7", "content_id": "9c64661b6ac72bf69905ccfd82f6f13a81c423ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1739, "license_type": "permissive", "max_line_length": 90, "num_lines": 55, "path": "/brokenChains/models.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.utils import timezone\nfrom rest_framework.authtoken.models import Token\nimport datetime\n\n\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n\tif created:\n\t\tToken.objects.create(user=instance)\n\n\nclass Habit(models.Model):\n\tname = models.CharField(max_length=50)\n\towner = models.ForeignKey(User, related_name='habits', on_delete=models.CASCADE)\n\tgoal = models.CharField(max_length=150)\n\tstart_date = models.DateField(auto_now_add=True)\n\tstop_date = models.DateField(default=timezone.now().date() + datetime.timedelta(days=21))\n\n\tclass Meta:\n\t\tordering = ('start_date',)\n\t\tunique_together = ('owner', 'name')\n\n\tdef save(self, *args, **kwargs):\n\t\tself.name = self.name.title()\n\t\tself.goal = self.goal.title()\n\t\tsuper(Habit, self).save(*args, **kwargs)\n\n\tdef __str__(self):\n\t\treturn self.name.title()\n\n\nclass Session(models.Model):\n\thabit = models.ForeignKey(Habit, related_name='sessions', on_delete=models.CASCADE)\n\tname = models.CharField(max_length=50)\n\ttext = models.CharField(max_length=200, blank=True) # For additional notes\n\tdate = models.DateField(auto_now_add=True)\n\tis_complete = models.BooleanField(default=False)\n\n\tclass Meta:\n\t\tordering = ('date',)\n\t\tunique_together = ('habit', 'name')\n\n\tdef save(self, *args, **kwargs):\n\t\tsessions_count = Session.objects.filter(habit=self.habit).count()\n\t\tself.name = self.habit.name + \" - Day \" + str(sessions_count + 1)\n\t\tsuper(Session, self).save(*args, **kwargs)\n\n\tdef __str__(self):\n\t\treturn self.name.title()\n\t" }, { "alpha_fraction": 0.5090609788894653, "alphanum_fraction": 0.5831960439682007, "avg_line_length": 24.29166603088379, "blob_id": "ad5e8f11363dd5eaead7180f11dc9244f0c8e99f", "content_id": "1bb17cecf00135cbe97955c313a66ae6f0f4e584", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "permissive", "max_line_length": 72, "num_lines": 24, "path": "/brokenChains/migrations/0004_auto_20181217_0105.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.3 on 2018-12-17 00:05\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brokenChains', '0003_auto_20181106_1819'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='habit',\n name='start_date',\n field=models.DateField(default=datetime.date(2018, 12, 17)),\n ),\n migrations.AlterField(\n model_name='habit',\n name='stop_date',\n field=models.DateField(default=datetime.date(2019, 1, 7)),\n ),\n ]\n" }, { "alpha_fraction": 0.5392696261405945, "alphanum_fraction": 0.5517758727073669, "avg_line_length": 36.71697998046875, "blob_id": "5b157a100e56733e37821ef5356bc277cfb97f4b", "content_id": "dcd2eed0e0a024a48e79959ffa0ced7b1c94e6a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1999, "license_type": "permissive", "max_line_length": 142, "num_lines": 53, "path": "/brokenChains/migrations/0001_initial.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-11-05 18:10\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Habit',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ('goal', models.CharField(max_length=150)),\n ('start_date', models.DateField(auto_now_add=True)),\n ('stop_date', models.DateField(blank=True, null=True)),\n ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='habits', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ('start_date',),\n },\n ),\n migrations.CreateModel(\n name='Session',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ('text', models.CharField(blank=True, max_length=200)),\n ('date', models.DateField(auto_now_add=True)),\n ('is_complete', models.BooleanField(default=False)),\n ('habit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sessions', to='brokenChains.Habit')),\n ],\n options={\n 'ordering': ('date',),\n },\n ),\n migrations.AlterUniqueTogether(\n name='session',\n unique_together={('habit', 'name')},\n ),\n migrations.AlterUniqueTogether(\n name='habit',\n unique_together={('owner', 'name')},\n ),\n ]\n" }, { "alpha_fraction": 0.6739860773086548, "alphanum_fraction": 0.6884526014328003, "avg_line_length": 26.069929122924805, "blob_id": "eb576562ee8b09acd1d9d8d276f06b67e4b05379", "content_id": "9ff609ff962995cce33bf9fbb568b9f62b39bc1f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3871, "license_type": "permissive", "max_line_length": 79, "num_lines": 143, "path": "/brokenChains/tests.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "from django.contrib.auth .models import User\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom rest_framework.authtoken.models import Token\n\nfrom .models import Habit, Session\n\n\n\nclass UserRegistrationTest(APITestCase):\n\tdef test_user_registration(self):\n\t\t\"\"\"\n\t\tTest user can register.\n\t\t\"\"\"\n\t\tdata = {\n\t\t\t'username': 'testUser',\n\t\t\t'email': '[email protected]',\n\t\t\t'password': 'testPassword'\n\t\t}\n\t\turl = reverse('user-registration')\n\t\tresponse = self.client.post(url, data)\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n\nclass UserAuthenticationTests(APITestCase):\n\tdef setUp(self):\n\t\tself.user = User.objects.create_user('testUser', '[email protected]', 'testPassword')\n\t\tself.data = {\n\t\t\t'username': 'testUser',\n\t\t\t'password': 'testPassword'\n\t\t}\n\n\tdef test_get_user_auth_token(self):\n\t\t\"\"\"\n\t\tTest user can get authentication token.\n\t\t\"\"\"\n\t\turl = reverse('get-auth-token')\n\t\tresponse = self.client.post(url, self.data)\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\nclass CreateHabitTest(APITestCase):\n\tdef setUp(self):\n\t\tself.user = User.objects.create_user('testUser', '[email protected]', 'testPassword')\n\t\tself.client.login(username='testUser', password='testPassword')\n\t\tself.url = reverse('habits-list')\n\t\tself.data = {\n\t\t\t'name': 'study',\n\t\t\t'goal': 'to be literate.',\n\t\t\t'stop_date': '2018-12-30'\n\t\t}\n\n\tdef test_can_create_habit(self):\n\t\t\"\"\"\n\t\tTest user can create new habit.\n\t\t\"\"\"\n\t\tresponse = self.client.post(self.url, self.data)\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n\nclass ReadHabitTest(APITestCase):\n\tdef setUp(self):\n\t\tself.user = User.objects.create_user('testUser', '[email protected]', 'testPassword')\n\t\tself.client.login(username='testUser', password='testPassword')\n\t\tself.new_habit = Habit(\n\t\t\towner=self.user,\n\t\t\tname='Work out',\n\t\t\tgoal='physical fitness.',\n\t\t\tstop_date='2018-12-30'\n\t\t)\n\t\tself.new_habit.save()\n\n\tdef test_can_read_habits_list(self):\n\t\t\"\"\"\n\t\tTest user can read habits list.\n\t\t\"\"\"\n\t\tresponse = self.client.get(reverse('habits-list'))\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\tdef test_can_read_habit_detail(self):\n\t\t\"\"\"\n\t\tTest user can read habit detail.\n\t\t\"\"\"\n\t\tresponse = self.client.get(reverse('habit-detail', args=[self.new_habit.id]))\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\nclass CreateSessionTest(APITestCase):\n\tdef setUp(self):\n\t\tself.user = User.objects.create_user('testUser', '[email protected]', 'testPassword')\n\t\tself.client.login(username='testUser', password='testPassword')\n\t\tself.url = reverse('sessions-list')\n\t\tself.habit = Habit(\n\t\t\towner=self.user,\n\t\t\tname='Work out',\n\t\t\tgoal='physical fitness.',\n\t\t\tstop_date='2018-12-30'\n\t\t)\n\t\tself.habit.save()\n\t\tself.data = {\n\t\t\t'habit': self.habit.id,\n\t\t\t'text': 'finally started',\n\t\t}\n\n\tdef test_can_create_session(self):\n\t\t\"\"\"\n\t\tTest user can create new session.\n\t\t\"\"\"\n\t\tresponse = self.client.post(self.url, self.data)\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n\nclass ReadSessionTest(APITestCase):\n\tdef setUp(self):\n\t\tself.user = User.objects.create_user('testUser', '[email protected]', 'testPassword')\n\t\tself.client.login(username='testUser', password='testPassword')\n\t\tself.habit = Habit(\n\t\t\towner=self.user,\n\t\t\tname='Work out',\n\t\t\tgoal='physical fitness.',\n\t\t\tstop_date='2018-12-30'\n\t\t)\n\t\tself.habit.save()\n\t\tself.session = Session(\n\t\t\thabit=self.habit,\n\t\t\ttext='finally started'\n\t\t)\n\t\tself.session.save()\n\n\tdef test_can_read_sessions_list(self):\n\t\t\"\"\"\n\t\tTest user can read sessions list.\n\t\t\"\"\"\n\t\tresponse = self.client.get(reverse('sessions-list'))\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\tdef test_can_read_session_detail(self):\n\t\t\"\"\"\n\t\tTest user can read session detail.\n\t\t\"\"\"\n\t\tresponse = self.client.get(reverse('session-detail', args=[self.session.id]))\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n" }, { "alpha_fraction": 0.5635964870452881, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 23, "blob_id": "3b3cf0198ec0fb7e0b649bced5c28dfb05917887", "content_id": "0a017ba6441979fea8dcb4bd6912e6e472b2970d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 456, "license_type": "permissive", "max_line_length": 66, "num_lines": 19, "path": "/brokenChains/migrations/0003_auto_20181106_1819.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-11-06 17:19\n\nfrom django.conf import settings\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('brokenChains', '0002_auto_20181106_1723'),\n ]\n\n operations = [\n migrations.AlterUniqueTogether(\n name='habit',\n unique_together={('owner', 'name')},\n ),\n ]\n" }, { "alpha_fraction": 0.489130437374115, "alphanum_fraction": 0.7101449370384216, "avg_line_length": 16.25, "blob_id": "4942a0d5d8ca85c697b2b441d81ad25ea089ea8f", "content_id": "c353393f423f9ebc4b2147681a976a4226a3b65c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 276, "license_type": "permissive", "max_line_length": 27, "num_lines": 16, "path": "/requirements.txt", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "certifi==2019.11.28\nchardet==3.0.4\ncoreapi==2.3.3\ncoreschema==0.0.4\nDjango==2.2.10\ndjango-cors-headers==3.2.1\ndjangorestframework==3.11.0\nidna==2.8\nitypes==1.1.0\nJinja2==2.11.1\nMarkupSafe==1.1.1\npytz==2019.3\nrequests==2.22.0\nsqlparse==0.3.0\nuritemplate==3.0.1\nurllib3==1.25.8\n" }, { "alpha_fraction": 0.7037861943244934, "alphanum_fraction": 0.7037861943244934, "avg_line_length": 36.5, "blob_id": "b0019fadb62990d475f797fcb0d20ce8a647b433", "content_id": "701f78df70638f514413560945993e9a0a6a7d9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 449, "license_type": "permissive", "max_line_length": 83, "num_lines": 12, "path": "/brokenChains/urls.py", "repo_name": "bunya017/brokenChains", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\n\n\nurlpatterns = [\n\tpath('habits/', views.HabitList.as_view(), name='habits-list'),\n\tpath('habits/<int:pk>/', views.HabitDetail.as_view(), name='habit-detail'),\n\tpath('sessions/', views.SessionList.as_view(), name='sessions-list'),\n\tpath('sessions/<int:pk>/', views.SessionDetail.as_view(), name='session-detail'),\n\tpath('users/signup/', views.UserRegistration.as_view(), name='user-registration'),\n]" } ]
14
csloo/cats-of-chocolate
https://github.com/csloo/cats-of-chocolate
f1a4d264d11980e68a11e8f29ebd13e24b0869aa
907242d05ca3ec9394d1d5dd5e9eeef7c87fb5ca
2dc6afcc337b116bdc89d46531e4313637711b55
refs/heads/master
2020-12-24T16:24:11.998505
2016-03-11T05:38:31
2016-03-11T05:38:31
41,181,214
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6951219439506531, "alphanum_fraction": 0.7682926654815674, "avg_line_length": 17.478872299194336, "blob_id": "6fd3687cfdb49b355ea65de4b099d4e044744569", "content_id": "6cc532595613348a05f982fd49ad270a42aaecd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1312, "license_type": "no_license", "max_line_length": 33, "num_lines": 71, "path": "/Caitlyn.py", "repo_name": "csloo/cats-of-chocolate", "src_encoding": "UTF-8", "text": "import turtle\nourScreen = turtle.Screen()\nourTurtle = turtle.Turtle()\n\n\n\nourTurtle.color(\"brown\")\n\nourTurtle.color(\"blue\")\nourTurtle.color(\"red\")\nourTurtle.color(\"yellow\")\nourTurtle.color(\"purple\")\nourTurtle.color(\"pink\")\nourTurtle.color(\"black\")\nourTurtle.color(\"brown\")\nourTurtle.color(\"blue\")\nourTurtle.color(\"red\")\nourTurtle.color(\"yellow\")\nourTurtle.color(\"purple\")\nourTurtle.color(\"pink\")\nourTurtle.color(\"black\")\nourTurtle.pencolor(\"blue\")\nourTurtle.fd(100)\nourTurtle.lt(90)\nourTurtle.fd(100)\nourTurtle.lt(90)\nourTurtle.fd(100)\nourTurtle.lt(90)\nourTurtle.fd(100)\nourTurtle.rt(90)\nourTurtle.fd(100)\nourTurtle.rt(90)\nourTurtle.fd(100)\nourTurtle.rt(90)\nourTurtle.fd(100)\nourTurtle.lt(90)\nourTurtle.fd(100)\nourTurtle.rt(90)\nourTurtle.fd(100)\nourTurtle.lt(180)\nourTurtle.fd(200)\nourTurtle.lt(90)\nourTurtle.fd(100)\nourTurtle.rt(90)\nourTurtle.fd(110)\nourTurtle.rt(180)\nourTurtle.fd(200)\nourTurtle.fd(110)\nourTurtle.rt(90)\nourTurtle.color(\"green\")\nourScreen.Backgroundcolor(\"red\")\nourTurtle.reset()\nourTurtle.fd(100)\nourTurtle.lt(90)\nourTurtle.fd(100)\nourTurtle.lt(90)\nourTurtle.fd(100)\nourTurtle.lt(90)\nourTurtle.fd(100)\nourTurtle.shape(\"turtle\")\nourTurtle.fd(100)\nourTurtle.color(\"yellow\")\nourScreen.Backgroundcolor(\"blue\")\nourTurtle.lt(90)\nourTurtle.fd(100)\n\nourScreen.exitonclick()\n\n\n\nourScreen.exitonclick()\n" } ]
1
bang5115/hdetect
https://github.com/bang5115/hdetect
72a2f5a6c5cb1c9370337dcc928f6be2fa86d986
1dd34b129f9f32c0a7e0bf9016f293f0a676e4d2
4f57724735aec03cac8270243cd751121db9b595
refs/heads/master
2021-04-12T02:45:57.289407
2015-02-27T15:12:34
2015-02-27T15:12:34
31,423,410
0
0
null
2015-02-27T14:40:22
2015-01-15T11:06:53
2013-09-22T10:59:12
null
[ { "alpha_fraction": 0.7549341917037964, "alphanum_fraction": 0.7549341917037964, "avg_line_length": 54.272727966308594, "blob_id": "ba94d349a8caadb5573a8c496598885747e0e424", "content_id": "73f35c3cf3b304be70d1c5b38c2770f83ba2efd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 608, "license_type": "no_license", "max_line_length": 83, "num_lines": 11, "path": "/deploy.sh", "repo_name": "bang5115/hdetect", "src_encoding": "UTF-8", "text": "#!/bin/bash\nsource ~/ros_workspace/setup.bash\nroscd hdetect\nrsync -zv --exclude=.svn --exclude=CMakeCache.txt * summit:~/ros_workspace/hdetect/\nrsync -zvr --exclude=.svn msg summit:~/ros_workspace/hdetect/\nrsync -zvr --exclude=.svn src summit:~/ros_workspace/hdetect/\nrsync -zvr --exclude=.svn include summit:~/ros_workspace/hdetect\nrsync -zvr --exclude=.svn yaml summit:~/ros_workspace/hdetect/\nrsync -zvr --exclude=.svn calibration\\ parameters summit:~/ros_workspace/hdetect/\nrsync -zvr --exclude=.svn launches summit:~/ros_workspace/hdetect/\nrsync -zvr --exclude=.svn rviz summit:~/ros_workspace/hdetect/\n" }, { "alpha_fraction": 0.6498673558235168, "alphanum_fraction": 0.6498673558235168, "avg_line_length": 22.5625, "blob_id": "dbf0f152d811bf062207ab334ad9f2f4e5dd65f6", "content_id": "8a2af3ce5712f8786e518728b46f0d9dbac79ac7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 754, "license_type": "no_license", "max_line_length": 101, "num_lines": 32, "path": "/src/lib/Human.hpp", "repo_name": "bang5115/hdetect", "src_encoding": "UTF-8", "text": "#ifndef HUMAN_HPP\n#define HUMAN_HPP\n\n#include \"ros/ros.h\"\n#include <newmat/newmat.h>\n#include <geometry_msgs/Point.h>\n\nclass Human\n{\n public:\n int id;\n\n float score;\n float scorefollower;\n\n NEWMAT::ColumnVector state;\n NEWMAT::Matrix cov;\n\n NEWMAT::ColumnVector preState;\n float preTimestamp;\n\n // This four variables are used by the following process\n ros::Time firstTimestamp; // First detection time\n ros::Time firstFollowTimestamp; // First following process time\n float dist; // Distance to the robot\n\n Human(int id, float score, NEWMAT::ColumnVector state, NEWMAT::Matrix cov, int preTimestamp);\n\n geometry_msgs::Point toPoint();\n};\n\n#endif // HUMAN_HPP\n" }, { "alpha_fraction": 0.7627118825912476, "alphanum_fraction": 0.7627118825912476, "avg_line_length": 28.5, "blob_id": "be7038d36eeb6ebcb48218d7cbcabdaa9214046b", "content_id": "7e90115a505e37c80a5866720612816cddf5d77c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 59, "license_type": "no_license", "max_line_length": 29, "num_lines": 2, "path": "/src/hdetect/msg/__init__.py", "repo_name": "bang5115/hdetect", "src_encoding": "UTF-8", "text": "from ._ClusterClass import *\nfrom ._ClusteredScan import *\n" }, { "alpha_fraction": 0.670716404914856, "alphanum_fraction": 0.6723455786705017, "avg_line_length": 32.049232482910156, "blob_id": "ee2d552820fd924cd6324c3c323bcc6ff6a95ce0", "content_id": "f43060ea7af530e403ae02c78fae49144a4f1859", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 21483, "license_type": "no_license", "max_line_length": 152, "num_lines": 650, "path": "/Makefile", "repo_name": "bang5115/hdetect", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 2.8\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n.PHONY : default_target\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n# A target that is always out of date.\ncmake_force:\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/local/bin/cmake\n\n# The command to remove a file.\nRM = /usr/local/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The program to use to edit the cache.\nCMAKE_EDIT_COMMAND = /usr/local/bin/ccmake\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/kabamaru/ros_workspace/hdetect\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/kabamaru/ros_workspace/hdetect\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake cache editor...\"\n\t/usr/local/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n.PHONY : edit_cache/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/local/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n.PHONY : rebuild_cache/fast\n\n# The main all target\nall: cmake_check_build_system\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/kabamaru/ros_workspace/hdetect/CMakeFiles /home/kabamaru/ros_workspace/hdetect/CMakeFiles/progress.marks\n\t$(MAKE) -f CMakeFiles/Makefile2 all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/kabamaru/ros_workspace/hdetect/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\t$(MAKE) -f CMakeFiles/Makefile2 clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\t$(MAKE) -f CMakeFiles/Makefile2 preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\t$(MAKE) -f CMakeFiles/Makefile2 preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\t$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n#=============================================================================\n# Target rules for targets named ROSBUILD_genmsg_cpp\n\n# Build rule for target.\nROSBUILD_genmsg_cpp: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 ROSBUILD_genmsg_cpp\n.PHONY : ROSBUILD_genmsg_cpp\n\n# fast build rule for target.\nROSBUILD_genmsg_cpp/fast:\n\t$(MAKE) -f CMakeFiles/ROSBUILD_genmsg_cpp.dir/build.make CMakeFiles/ROSBUILD_genmsg_cpp.dir/build\n.PHONY : ROSBUILD_genmsg_cpp/fast\n\n#=============================================================================\n# Target rules for targets named ROSBUILD_genmsg_lisp\n\n# Build rule for target.\nROSBUILD_genmsg_lisp: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 ROSBUILD_genmsg_lisp\n.PHONY : ROSBUILD_genmsg_lisp\n\n# fast build rule for target.\nROSBUILD_genmsg_lisp/fast:\n\t$(MAKE) -f CMakeFiles/ROSBUILD_genmsg_lisp.dir/build.make CMakeFiles/ROSBUILD_genmsg_lisp.dir/build\n.PHONY : ROSBUILD_genmsg_lisp/fast\n\n#=============================================================================\n# Target rules for targets named ROSBUILD_genmsg_py\n\n# Build rule for target.\nROSBUILD_genmsg_py: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 ROSBUILD_genmsg_py\n.PHONY : ROSBUILD_genmsg_py\n\n# fast build rule for target.\nROSBUILD_genmsg_py/fast:\n\t$(MAKE) -f CMakeFiles/ROSBUILD_genmsg_py.dir/build.make CMakeFiles/ROSBUILD_genmsg_py.dir/build\n.PHONY : ROSBUILD_genmsg_py/fast\n\n#=============================================================================\n# Target rules for targets named ROSBUILD_gensrv_cpp\n\n# Build rule for target.\nROSBUILD_gensrv_cpp: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 ROSBUILD_gensrv_cpp\n.PHONY : ROSBUILD_gensrv_cpp\n\n# fast build rule for target.\nROSBUILD_gensrv_cpp/fast:\n\t$(MAKE) -f CMakeFiles/ROSBUILD_gensrv_cpp.dir/build.make CMakeFiles/ROSBUILD_gensrv_cpp.dir/build\n.PHONY : ROSBUILD_gensrv_cpp/fast\n\n#=============================================================================\n# Target rules for targets named ROSBUILD_gensrv_lisp\n\n# Build rule for target.\nROSBUILD_gensrv_lisp: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 ROSBUILD_gensrv_lisp\n.PHONY : ROSBUILD_gensrv_lisp\n\n# fast build rule for target.\nROSBUILD_gensrv_lisp/fast:\n\t$(MAKE) -f CMakeFiles/ROSBUILD_gensrv_lisp.dir/build.make CMakeFiles/ROSBUILD_gensrv_lisp.dir/build\n.PHONY : ROSBUILD_gensrv_lisp/fast\n\n#=============================================================================\n# Target rules for targets named clean-test-results\n\n# Build rule for target.\nclean-test-results: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 clean-test-results\n.PHONY : clean-test-results\n\n# fast build rule for target.\nclean-test-results/fast:\n\t$(MAKE) -f CMakeFiles/clean-test-results.dir/build.make CMakeFiles/clean-test-results.dir/build\n.PHONY : clean-test-results/fast\n\n#=============================================================================\n# Target rules for targets named detector\n\n# Build rule for target.\ndetector: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 detector\n.PHONY : detector\n\n# fast build rule for target.\ndetector/fast:\n\t$(MAKE) -f CMakeFiles/detector.dir/build.make CMakeFiles/detector.dir/build\n.PHONY : detector/fast\n\n#=============================================================================\n# Target rules for targets named headlessRT\n\n# Build rule for target.\nheadlessRT: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 headlessRT\n.PHONY : headlessRT\n\n# fast build rule for target.\nheadlessRT/fast:\n\t$(MAKE) -f CMakeFiles/headlessRT.dir/build.make CMakeFiles/headlessRT.dir/build\n.PHONY : headlessRT/fast\n\n#=============================================================================\n# Target rules for targets named laserLib\n\n# Build rule for target.\nlaserLib: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 laserLib\n.PHONY : laserLib\n\n# fast build rule for target.\nlaserLib/fast:\n\t$(MAKE) -f CMakeFiles/laserLib.dir/build.make CMakeFiles/laserLib.dir/build\n.PHONY : laserLib/fast\n\n#=============================================================================\n# Target rules for targets named lengine\n\n# Build rule for target.\nlengine: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 lengine\n.PHONY : lengine\n\n# fast build rule for target.\nlengine/fast:\n\t$(MAKE) -f CMakeFiles/lengine.dir/build.make CMakeFiles/lengine.dir/build\n.PHONY : lengine/fast\n\n#=============================================================================\n# Target rules for targets named lfeatures\n\n# Build rule for target.\nlfeatures: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 lfeatures\n.PHONY : lfeatures\n\n# fast build rule for target.\nlfeatures/fast:\n\t$(MAKE) -f CMakeFiles/lfeatures.dir/build.make CMakeFiles/lfeatures.dir/build\n.PHONY : lfeatures/fast\n\n#=============================================================================\n# Target rules for targets named lgeometry\n\n# Build rule for target.\nlgeometry: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 lgeometry\n.PHONY : lgeometry\n\n# fast build rule for target.\nlgeometry/fast:\n\t$(MAKE) -f CMakeFiles/lgeometry.dir/build.make CMakeFiles/lgeometry.dir/build\n.PHONY : lgeometry/fast\n\n#=============================================================================\n# Target rules for targets named projectTools\n\n# Build rule for target.\nprojectTools: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 projectTools\n.PHONY : projectTools\n\n# fast build rule for target.\nprojectTools/fast:\n\t$(MAKE) -f CMakeFiles/projectTools.dir/build.make CMakeFiles/projectTools.dir/build\n.PHONY : projectTools/fast\n\n#=============================================================================\n# Target rules for targets named rosbuild_precompile\n\n# Build rule for target.\nrosbuild_precompile: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 rosbuild_precompile\n.PHONY : rosbuild_precompile\n\n# fast build rule for target.\nrosbuild_precompile/fast:\n\t$(MAKE) -f CMakeFiles/rosbuild_precompile.dir/build.make CMakeFiles/rosbuild_precompile.dir/build\n.PHONY : rosbuild_precompile/fast\n\n#=============================================================================\n# Target rules for targets named rosbuild_premsgsrvgen\n\n# Build rule for target.\nrosbuild_premsgsrvgen: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 rosbuild_premsgsrvgen\n.PHONY : rosbuild_premsgsrvgen\n\n# fast build rule for target.\nrosbuild_premsgsrvgen/fast:\n\t$(MAKE) -f CMakeFiles/rosbuild_premsgsrvgen.dir/build.make CMakeFiles/rosbuild_premsgsrvgen.dir/build\n.PHONY : rosbuild_premsgsrvgen/fast\n\n#=============================================================================\n# Target rules for targets named rospack_genmsg\n\n# Build rule for target.\nrospack_genmsg: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 rospack_genmsg\n.PHONY : rospack_genmsg\n\n# fast build rule for target.\nrospack_genmsg/fast:\n\t$(MAKE) -f CMakeFiles/rospack_genmsg.dir/build.make CMakeFiles/rospack_genmsg.dir/build\n.PHONY : rospack_genmsg/fast\n\n#=============================================================================\n# Target rules for targets named rospack_genmsg_all\n\n# Build rule for target.\nrospack_genmsg_all: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 rospack_genmsg_all\n.PHONY : rospack_genmsg_all\n\n# fast build rule for target.\nrospack_genmsg_all/fast:\n\t$(MAKE) -f CMakeFiles/rospack_genmsg_all.dir/build.make CMakeFiles/rospack_genmsg_all.dir/build\n.PHONY : rospack_genmsg_all/fast\n\n#=============================================================================\n# Target rules for targets named rospack_genmsg_libexe\n\n# Build rule for target.\nrospack_genmsg_libexe: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 rospack_genmsg_libexe\n.PHONY : rospack_genmsg_libexe\n\n# fast build rule for target.\nrospack_genmsg_libexe/fast:\n\t$(MAKE) -f CMakeFiles/rospack_genmsg_libexe.dir/build.make CMakeFiles/rospack_genmsg_libexe.dir/build\n.PHONY : rospack_genmsg_libexe/fast\n\n#=============================================================================\n# Target rules for targets named rospack_gensrv\n\n# Build rule for target.\nrospack_gensrv: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 rospack_gensrv\n.PHONY : rospack_gensrv\n\n# fast build rule for target.\nrospack_gensrv/fast:\n\t$(MAKE) -f CMakeFiles/rospack_gensrv.dir/build.make CMakeFiles/rospack_gensrv.dir/build\n.PHONY : rospack_gensrv/fast\n\n#=============================================================================\n# Target rules for targets named test\n\n# Build rule for target.\ntest: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 test\n.PHONY : test\n\n# fast build rule for target.\ntest/fast:\n\t$(MAKE) -f CMakeFiles/test.dir/build.make CMakeFiles/test.dir/build\n.PHONY : test/fast\n\n#=============================================================================\n# Target rules for targets named test-future\n\n# Build rule for target.\ntest-future: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 test-future\n.PHONY : test-future\n\n# fast build rule for target.\ntest-future/fast:\n\t$(MAKE) -f CMakeFiles/test-future.dir/build.make CMakeFiles/test-future.dir/build\n.PHONY : test-future/fast\n\n#=============================================================================\n# Target rules for targets named test-results\n\n# Build rule for target.\ntest-results: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 test-results\n.PHONY : test-results\n\n# fast build rule for target.\ntest-results/fast:\n\t$(MAKE) -f CMakeFiles/test-results.dir/build.make CMakeFiles/test-results.dir/build\n.PHONY : test-results/fast\n\n#=============================================================================\n# Target rules for targets named test-results-run\n\n# Build rule for target.\ntest-results-run: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 test-results-run\n.PHONY : test-results-run\n\n# fast build rule for target.\ntest-results-run/fast:\n\t$(MAKE) -f CMakeFiles/test-results-run.dir/build.make CMakeFiles/test-results-run.dir/build\n.PHONY : test-results-run/fast\n\n#=============================================================================\n# Target rules for targets named tests\n\n# Build rule for target.\ntests: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 tests\n.PHONY : tests\n\n# fast build rule for target.\ntests/fast:\n\t$(MAKE) -f CMakeFiles/tests.dir/build.make CMakeFiles/tests.dir/build\n.PHONY : tests/fast\n\n#=============================================================================\n# Target rules for targets named visualizeRT\n\n# Build rule for target.\nvisualizeRT: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 visualizeRT\n.PHONY : visualizeRT\n\n# fast build rule for target.\nvisualizeRT/fast:\n\t$(MAKE) -f CMakeFiles/visualizeRT.dir/build.make CMakeFiles/visualizeRT.dir/build\n.PHONY : visualizeRT/fast\n\n#=============================================================================\n# Target rules for targets named visualizer\n\n# Build rule for target.\nvisualizer: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 visualizer\n.PHONY : visualizer\n\n# fast build rule for target.\nvisualizer/fast:\n\t$(MAKE) -f CMakeFiles/visualizer.dir/build.make CMakeFiles/visualizer.dir/build\n.PHONY : visualizer/fast\n\n# target to build an object file\nsrc/headlessRT.o:\n\t$(MAKE) -f CMakeFiles/headlessRT.dir/build.make CMakeFiles/headlessRT.dir/src/headlessRT.o\n.PHONY : src/headlessRT.o\n\n# target to preprocess a source file\nsrc/headlessRT.i:\n\t$(MAKE) -f CMakeFiles/headlessRT.dir/build.make CMakeFiles/headlessRT.dir/src/headlessRT.i\n.PHONY : src/headlessRT.i\n\n# target to generate assembly for a file\nsrc/headlessRT.s:\n\t$(MAKE) -f CMakeFiles/headlessRT.dir/build.make CMakeFiles/headlessRT.dir/src/headlessRT.s\n.PHONY : src/headlessRT.s\n\n# target to build an object file\nsrc/lib/detector.o:\n\t$(MAKE) -f CMakeFiles/detector.dir/build.make CMakeFiles/detector.dir/src/lib/detector.o\n.PHONY : src/lib/detector.o\n\n# target to preprocess a source file\nsrc/lib/detector.i:\n\t$(MAKE) -f CMakeFiles/detector.dir/build.make CMakeFiles/detector.dir/src/lib/detector.i\n.PHONY : src/lib/detector.i\n\n# target to generate assembly for a file\nsrc/lib/detector.s:\n\t$(MAKE) -f CMakeFiles/detector.dir/build.make CMakeFiles/detector.dir/src/lib/detector.s\n.PHONY : src/lib/detector.s\n\n# target to build an object file\nsrc/lib/laserLib.o:\n\t$(MAKE) -f CMakeFiles/laserLib.dir/build.make CMakeFiles/laserLib.dir/src/lib/laserLib.o\n.PHONY : src/lib/laserLib.o\n\n# target to preprocess a source file\nsrc/lib/laserLib.i:\n\t$(MAKE) -f CMakeFiles/laserLib.dir/build.make CMakeFiles/laserLib.dir/src/lib/laserLib.i\n.PHONY : src/lib/laserLib.i\n\n# target to generate assembly for a file\nsrc/lib/laserLib.s:\n\t$(MAKE) -f CMakeFiles/laserLib.dir/build.make CMakeFiles/laserLib.dir/src/lib/laserLib.s\n.PHONY : src/lib/laserLib.s\n\n# target to build an object file\nsrc/lib/lengine.o:\n\t$(MAKE) -f CMakeFiles/lengine.dir/build.make CMakeFiles/lengine.dir/src/lib/lengine.o\n.PHONY : src/lib/lengine.o\n\n# target to preprocess a source file\nsrc/lib/lengine.i:\n\t$(MAKE) -f CMakeFiles/lengine.dir/build.make CMakeFiles/lengine.dir/src/lib/lengine.i\n.PHONY : src/lib/lengine.i\n\n# target to generate assembly for a file\nsrc/lib/lengine.s:\n\t$(MAKE) -f CMakeFiles/lengine.dir/build.make CMakeFiles/lengine.dir/src/lib/lengine.s\n.PHONY : src/lib/lengine.s\n\n# target to build an object file\nsrc/lib/lfeatures.o:\n\t$(MAKE) -f CMakeFiles/lfeatures.dir/build.make CMakeFiles/lfeatures.dir/src/lib/lfeatures.o\n.PHONY : src/lib/lfeatures.o\n\n# target to preprocess a source file\nsrc/lib/lfeatures.i:\n\t$(MAKE) -f CMakeFiles/lfeatures.dir/build.make CMakeFiles/lfeatures.dir/src/lib/lfeatures.i\n.PHONY : src/lib/lfeatures.i\n\n# target to generate assembly for a file\nsrc/lib/lfeatures.s:\n\t$(MAKE) -f CMakeFiles/lfeatures.dir/build.make CMakeFiles/lfeatures.dir/src/lib/lfeatures.s\n.PHONY : src/lib/lfeatures.s\n\n# target to build an object file\nsrc/lib/lgeometry.o:\n\t$(MAKE) -f CMakeFiles/lgeometry.dir/build.make CMakeFiles/lgeometry.dir/src/lib/lgeometry.o\n.PHONY : src/lib/lgeometry.o\n\n# target to preprocess a source file\nsrc/lib/lgeometry.i:\n\t$(MAKE) -f CMakeFiles/lgeometry.dir/build.make CMakeFiles/lgeometry.dir/src/lib/lgeometry.i\n.PHONY : src/lib/lgeometry.i\n\n# target to generate assembly for a file\nsrc/lib/lgeometry.s:\n\t$(MAKE) -f CMakeFiles/lgeometry.dir/build.make CMakeFiles/lgeometry.dir/src/lib/lgeometry.s\n.PHONY : src/lib/lgeometry.s\n\n# target to build an object file\nsrc/lib/projectTools.o:\n\t$(MAKE) -f CMakeFiles/projectTools.dir/build.make CMakeFiles/projectTools.dir/src/lib/projectTools.o\n.PHONY : src/lib/projectTools.o\n\n# target to preprocess a source file\nsrc/lib/projectTools.i:\n\t$(MAKE) -f CMakeFiles/projectTools.dir/build.make CMakeFiles/projectTools.dir/src/lib/projectTools.i\n.PHONY : src/lib/projectTools.i\n\n# target to generate assembly for a file\nsrc/lib/projectTools.s:\n\t$(MAKE) -f CMakeFiles/projectTools.dir/build.make CMakeFiles/projectTools.dir/src/lib/projectTools.s\n.PHONY : src/lib/projectTools.s\n\n# target to build an object file\nsrc/lib/visualizer.o:\n\t$(MAKE) -f CMakeFiles/visualizer.dir/build.make CMakeFiles/visualizer.dir/src/lib/visualizer.o\n.PHONY : src/lib/visualizer.o\n\n# target to preprocess a source file\nsrc/lib/visualizer.i:\n\t$(MAKE) -f CMakeFiles/visualizer.dir/build.make CMakeFiles/visualizer.dir/src/lib/visualizer.i\n.PHONY : src/lib/visualizer.i\n\n# target to generate assembly for a file\nsrc/lib/visualizer.s:\n\t$(MAKE) -f CMakeFiles/visualizer.dir/build.make CMakeFiles/visualizer.dir/src/lib/visualizer.s\n.PHONY : src/lib/visualizer.s\n\n# target to build an object file\nsrc/visualizeRT.o:\n\t$(MAKE) -f CMakeFiles/visualizeRT.dir/build.make CMakeFiles/visualizeRT.dir/src/visualizeRT.o\n.PHONY : src/visualizeRT.o\n\n# target to preprocess a source file\nsrc/visualizeRT.i:\n\t$(MAKE) -f CMakeFiles/visualizeRT.dir/build.make CMakeFiles/visualizeRT.dir/src/visualizeRT.i\n.PHONY : src/visualizeRT.i\n\n# target to generate assembly for a file\nsrc/visualizeRT.s:\n\t$(MAKE) -f CMakeFiles/visualizeRT.dir/build.make CMakeFiles/visualizeRT.dir/src/visualizeRT.s\n.PHONY : src/visualizeRT.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... ROSBUILD_genmsg_cpp\"\n\t@echo \"... ROSBUILD_genmsg_lisp\"\n\t@echo \"... ROSBUILD_genmsg_py\"\n\t@echo \"... ROSBUILD_gensrv_cpp\"\n\t@echo \"... ROSBUILD_gensrv_lisp\"\n\t@echo \"... clean-test-results\"\n\t@echo \"... detector\"\n\t@echo \"... edit_cache\"\n\t@echo \"... headlessRT\"\n\t@echo \"... laserLib\"\n\t@echo \"... lengine\"\n\t@echo \"... lfeatures\"\n\t@echo \"... lgeometry\"\n\t@echo \"... projectTools\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... rosbuild_precompile\"\n\t@echo \"... rosbuild_premsgsrvgen\"\n\t@echo \"... rospack_genmsg\"\n\t@echo \"... rospack_genmsg_all\"\n\t@echo \"... rospack_genmsg_libexe\"\n\t@echo \"... rospack_gensrv\"\n\t@echo \"... test\"\n\t@echo \"... test-future\"\n\t@echo \"... test-results\"\n\t@echo \"... test-results-run\"\n\t@echo \"... tests\"\n\t@echo \"... visualizeRT\"\n\t@echo \"... visualizer\"\n\t@echo \"... src/headlessRT.o\"\n\t@echo \"... src/headlessRT.i\"\n\t@echo \"... src/headlessRT.s\"\n\t@echo \"... src/lib/detector.o\"\n\t@echo \"... src/lib/detector.i\"\n\t@echo \"... src/lib/detector.s\"\n\t@echo \"... src/lib/laserLib.o\"\n\t@echo \"... src/lib/laserLib.i\"\n\t@echo \"... src/lib/laserLib.s\"\n\t@echo \"... src/lib/lengine.o\"\n\t@echo \"... src/lib/lengine.i\"\n\t@echo \"... src/lib/lengine.s\"\n\t@echo \"... src/lib/lfeatures.o\"\n\t@echo \"... src/lib/lfeatures.i\"\n\t@echo \"... src/lib/lfeatures.s\"\n\t@echo \"... src/lib/lgeometry.o\"\n\t@echo \"... src/lib/lgeometry.i\"\n\t@echo \"... src/lib/lgeometry.s\"\n\t@echo \"... src/lib/projectTools.o\"\n\t@echo \"... src/lib/projectTools.i\"\n\t@echo \"... src/lib/projectTools.s\"\n\t@echo \"... src/lib/visualizer.o\"\n\t@echo \"... src/lib/visualizer.i\"\n\t@echo \"... src/lib/visualizer.s\"\n\t@echo \"... src/visualizeRT.o\"\n\t@echo \"... src/visualizeRT.i\"\n\t@echo \"... src/visualizeRT.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\t$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.8131977319717407, "alphanum_fraction": 0.8146861791610718, "avg_line_length": 42.815216064453125, "blob_id": "fa222fb4b2505080d93037bb646fdb8d47af5f00", "content_id": "536634bc138b5e5fd327da4a89f6660c20f71024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 4031, "license_type": "no_license", "max_line_length": 125, "num_lines": 92, "path": "/CMakeLists.txt", "repo_name": "bang5115/hdetect", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.4.6)\ninclude($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake)\n\n# Set the build type. Options are:\n# Coverage : w/ debug symbols, w/o optimization, w/ code-coverage\n# Debug : w/ debug symbols, w/o optimization\n# Release : w/o debug symbols, w/ optimization\n# RelWithDebInfo : w/ debug symbols, w/ optimization\n# MinSizeRel : w/o debug symbols, w/ optimization, stripped binaries\nset(ROS_BUILD_TYPE RelWithDebInfo)\n\nrosbuild_init()\n\n#set the default path for built executables to the \"bin\" directory\nset(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)\n#set the default path for built libraries to the \"lib\" directory\nset(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)\n#set(ROS_COMPILE_FLAG \"-fno-stack-protector\")\n\nrosbuild_add_boost_directories()\n\n\n# MESSAGES\nrosbuild_genmsg() \n\n# EXECUTABLE NODES\n\nrosbuild_add_executable(visualizeRT src/visualizeRT.cpp)\nrosbuild_add_executable(headlessRT src/headlessRT.cpp)\nrosbuild_add_executable(recognizeRT src/recognizeRT.cpp)\nrosbuild_add_executable(showRT src/showRT.cpp)\nrosbuild_link_boost(visualizeRT signals)\nrosbuild_link_boost(headlessRT signals)\nrosbuild_link_boost(recognizeRT signals)\nrosbuild_link_boost(showRT signals)\n\nrosbuild_add_executable(annotateData src/annotateData.cpp)\nrosbuild_link_boost(annotateData signals)\nrosbuild_add_executable(trainLaser src/trainLaser.cpp)\n#rosbuild_add_executable(detectTest src/detectTest.cpp)\n#rosbuild_add_executable(Calib_Matlab2ROS src/other/Calib_Matlab2ROS.cpp)\nrosbuild_add_executable(HumanFollowerRT src/HumanFollowerRT.cpp)\n\n# LIBRARIES\n\nfind_library(NEWMAT newmat /usr/lib)\n\nrosbuild_add_library(Header src/lib/Header.hpp src/lib/Header.cpp)\n\nrosbuild_add_library(Recognizer src/lib/Recognizer.hpp src/lib/Recognizer.cpp)\nrosbuild_add_library(ObjectTracking src/lib/ObjectTracking.cpp src/lib/ObjectTracking.hpp)\nrosbuild_add_library(Observation src/lib/Observation.cpp src/lib/Observation.hpp)\nrosbuild_add_library(Human src/lib/Human.cpp src/lib/Human.hpp)\n\nrosbuild_add_library(laserLib src/lib/laserLib.cpp include/hdetect/lib/laserLib.hpp)\nrosbuild_add_library(visualizer src/lib/visualizer.cpp include/hdetect/lib/visualizer.hpp)\nrosbuild_add_library(lgeometry src/lib/lgeometry.cpp include/hdetect/lib/lgeometry.hpp)\nrosbuild_add_library(lfeatures src/lib/lfeatures.cpp include/hdetect/lib/lfeatures.hpp)\nrosbuild_add_library(lengine src/lib/lengine.cpp include/hdetect/lib/lengine.hpp)\nrosbuild_add_library(projectTools src/lib/projectTools.cpp include/hdetect/lib/projectTools.hpp)\nrosbuild_add_library(detector src/lib/detector.cpp include/hdetect/lib/detector.hpp)\n\nrosbuild_add_library(annotator src/lib/annotator.cpp include/hdetect/lib/annotator.hpp)\nrosbuild_add_library(bagReader src/lib/bagReader.cpp include/hdetect/lib/bagReader.hpp include/hdetect/lib/bagSubscriber.hpp)\n\nrosbuild_add_library(HumanFollower src/lib/HumanFollower.cpp src/lib/HumanFollower.hpp)\n\n\n# GSL IS NEEDED FOR PEOPLE2D LIBRARY TO COMPILE\ninclude($ENV{ROS_ROOT}/core/rosbuild/FindPkgConfig.cmake)\npkg_check_modules(GSL REQUIRED gsl)\ninclude_directories(${GSL_INCLUDE_DIRS})\nlink_directories(${GLS_LIBRARY_DIRS})\n\n# LINK THE LIBRARIES\ntarget_link_libraries(lgeometry ${GSL_LIBRARIES})\ntarget_link_libraries(lfeatures ${GSL_LIBRARIES})\ntarget_link_libraries(lengine lgeometry lfeatures Header)\ntarget_link_libraries(laserLib lengine)\ntarget_link_libraries(detector laserLib projectTools)\ntarget_link_libraries(visualizer detector)\ntarget_link_libraries(Recognizer detector ObjectTracking Human Observation ${NEWMAT})\ntarget_link_libraries(HumanFollower Recognizer)\ntarget_link_libraries(HumanFollowerRT HumanFollower)\ntarget_link_libraries(visualizeRT visualizer lgeometry)\ntarget_link_libraries(headlessRT detector lgeometry)\ntarget_link_libraries(recognizeRT Recognizer lgeometry)\ntarget_link_libraries(showRT ${GSL_LIBRARIES})\n\ntarget_link_libraries(annotator visualizer)\ntarget_link_libraries(annotateData bagReader annotator)\n#target_link_libraries(detectTest visualizer)\n" }, { "alpha_fraction": 0.7810218930244446, "alphanum_fraction": 0.7912408709526062, "avg_line_length": 41.8125, "blob_id": "ecc68494471f7a1e4f483c23c41dec3007a2a78d", "content_id": "6ce00b58d2c8789265c17259724c0de41b6def69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 685, "license_type": "no_license", "max_line_length": 177, "num_lines": 16, "path": "/README.md", "repo_name": "bang5115/hdetect", "src_encoding": "UTF-8", "text": "hdetect\n=======\n\nA human detection package for ROS written in C++. Uses a combination of laser range finder and a computer vision module.\nThe vision module works with OpenCV's detector which uses Histogram of Oriented Gradients and Support Vector Machines. The laser processing module uses code swritten by L. Spinello. \n\nProject website: http://robcib.etsii.upm.es/index.php/en/projects-28/rotos\n\nYoutube video: http://youtu.be/W84ERQ0LYjM\n\n\n\nv0.4\n\nDetection is done only by the HoG detector. The laser is only used for localization and restricting the search space.\nThe module for extracting and annotating the laser clusters are almost finished and will be included in a future version.\n" } ]
6
YuhangSong/gmbrl
https://github.com/YuhangSong/gmbrl
e4e4e3849e41de10534cdb640f29098f1afff0aa
f1ab02f1d0fcaaa7396124b8fdd62f393ffe64a4
a5f2fdc846a81112acccb22a04cf195c53523bdf
refs/heads/master
2021-01-01T06:09:24.705808
2017-07-20T15:08:10
2017-07-20T15:08:10
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5887096524238586, "alphanum_fraction": 0.5927419066429138, "avg_line_length": 21.57575798034668, "blob_id": "5bdf070543f0c7960e19d16de47e7e170ab0b1e8", "content_id": "d22d29e7677989d8eec1666628ba4f0a3d257a8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 744, "license_type": "permissive", "max_line_length": 57, "num_lines": 33, "path": "/gsa_io.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "import config\nimport subprocess\nimport time\nimport numpy as np\n\ndef IsSubString(SubStrList,Str):\n\n flag=True\n for substr in SubStrList:\n if not(substr in Str):\n flag=False\n\n return flag\n\ndef GetFileList(FindPath,FlagStr=[]):\n\n import os\n FileList=[]\n FileNames=os.listdir(FindPath)\n if (len(FileNames)>0):\n for fn in FileNames:\n if (len(FlagStr)>0):\n if (IsSubString(FlagStr,fn)):\n fullfilename=os.path.join(FindPath,fn)\n FileList.append(fullfilename)\n else:\n fullfilename=os.path.join(FindPath,fn)\n FileList.append(fullfilename)\n\n if (len(FileList)>0):\n FileList.sort()\n\n return FileList" }, { "alpha_fraction": 0.5851318836212158, "alphanum_fraction": 0.5981396436691284, "avg_line_length": 36.78845977783203, "blob_id": "65ac09f624f709cd2e8c2fb809c7934054c54411", "content_id": "67676456a85612bbbd0ae1e9546e07566c784331", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13761, "license_type": "permissive", "max_line_length": 127, "num_lines": 364, "path": "/run_gan_predict.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport argparse\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nimport os\nimport numpy as np\nimport copy\n\nimport wgan_models.dcgan as dcgan\nimport wgan_models.mlp as mlp\nimport support_lib\nimport config\nimport subprocess\nimport time\nimport gsa_io\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', default='lsun', help='cifar10 | lsun | imagenet | folder | lfw ')\nparser.add_argument('--dataroot', default='../../dataset', help='path to dataset')\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=16)\nparser.add_argument('--batchSize', type=int, default=config.gan_batchsize, help='input batch size')\nparser.add_argument('--imageSize', type=int, default=config.gan_size, help='the height / width of the input image to network')\nparser.add_argument('--nc', type=int, default=config.gan_nc, help='input image channels')\nparser.add_argument('--nz', type=int, default=config.gan_nz, help='size of the latent z vector')\nparser.add_argument('--ngf', type=int, default=64)\nparser.add_argument('--ndf', type=int, default=64)\nparser.add_argument('--niter', type=int, default=25, help='number of epochs to train for')\nparser.add_argument('--lrD', type=float, default=0.00005, help='learning rate for Critic, default=0.00005')\nparser.add_argument('--lrG', type=float, default=0.00005, help='learning rate for Generator, default=0.00005')\nparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5')\nparser.add_argument('--cuda' , default=True, action='store_true', help='enables cuda')\nparser.add_argument('--ngpu' , type=int, default=config.gan_ngpu, help='number of GPUs to use')\nparser.add_argument('--netG_Cv', default=config.modeldir+'netG_Cv.pth', help=\"path to netG_Cv (to continue training)\")\nparser.add_argument('--netG_DeCv', default=config.modeldir+'netG_DeCv.pth', help=\"path to netG_DeCv (to continue training)\")\nparser.add_argument('--netD', default=config.modeldir+'netD.pth', help=\"path to netD (to continue training)\")\nparser.add_argument('--clamp_lower', type=float, default=-0.01)\nparser.add_argument('--clamp_upper', type=float, default=0.01)\nparser.add_argument('--Diters', type=int, default=5, help='number of D iters per each G iter')\nparser.add_argument('--noBN', action='store_true', help='use batchnorm or not (only for DCGAN)')\nparser.add_argument('--mlp_G', action='store_true', help='use MLP for G')\nparser.add_argument('--mlp_D', action='store_true', help='use MLP for D')\nparser.add_argument('--n_extra_layers', type=int, default=0, help='Number of extra layers on gen and disc')\nparser.add_argument('--experiment', default=config.logdir, help='Where to store samples and models')\nparser.add_argument('--adam', action='store_true', help='Whether to use adam (default is rmsprop)')\nopt = parser.parse_args()\nprint(opt)\n\nsubprocess.call([\"mkdir\", \"-p\", config.logdir])\nsubprocess.call([\"mkdir\", \"-p\", config.modeldir])\n\n# random seed for\nopt.manualSeed = random.randint(1, 10000) # fix seed\nprint(\"Random Seed: \", opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\n\ncudnn.benchmark = True\n\nif torch.cuda.is_available() and not opt.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\nngpu = int(opt.ngpu)\nnz = int(opt.nz)\nngf = int(opt.ngf)\nndf = int(opt.ndf)\nnc = int(opt.nc)\nn_extra_layers = int(opt.n_extra_layers)\n\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n'''create models'''\nnetG_Cv = dcgan.DCGAN_G_Cv(opt.imageSize, nz, nc, ngf, ngpu, n_extra_layers)\nnetG_DeCv = dcgan.DCGAN_G_DeCv(opt.imageSize, nz, nc, ngf, ngpu, n_extra_layers)\nnetD = dcgan.DCGAN_D(opt.imageSize, nz, nc, ndf, ngpu, n_extra_layers)\n\n'''init models'''\nnetG_Cv.apply(weights_init)\nnetG_DeCv.apply(weights_init)\nnetD.apply(weights_init)\n\n# do auto checkpoint\ntry:\n netG_Cv.load_state_dict(torch.load(opt.netG_Cv))\n print('Previous checkpoint for netG_Cv founded')\nexcept Exception, e:\n print('Previous checkpoint for netG_Cv unfounded')\ntry:\n netG_DeCv.load_state_dict(torch.load(opt.netG_DeCv))\n print('Previous checkpoint for netG_DeCv founded')\nexcept Exception, e:\n print('Previous checkpoint for netG_DeCv unfounded')\ntry:\n netD.load_state_dict(torch.load(opt.netD))\n print('Previous checkpoint for netD founded')\nexcept Exception, e:\n print('Previous checkpoint for netD unfounded')\n\n'''print the models'''\nprint(netG_Cv)\nprint(netG_DeCv)\nprint(netD)\n\ninputd = torch.FloatTensor(opt.batchSize, 4, opt.imageSize, opt.imageSize)\ninputd_real_part = torch.FloatTensor(opt.batchSize, 4, opt.imageSize, opt.imageSize)\ninputg = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize)\nnoise = torch.FloatTensor(opt.batchSize, nz, 1, 1)\nfixed_noise = torch.FloatTensor(opt.batchSize, nz, 1, 1).normal_(0, 1)\none = torch.FloatTensor([1])\nmone = one * -1\n\n'''load dataset'''\ndataset = np.load(config.dataset_path+config.dataset_name)['dataset']\ndataset_len = np.shape(dataset)[0]\nprint('dataset loaded, size: ' + str(np.shape(dataset)))\ndataset = torch.FloatTensor(dataset)\ndataset_sampler_indexs = torch.LongTensor(opt.batchSize).random_(0,dataset_len)\n\nif opt.cuda:\n netD.cuda()\n netG_Cv.cuda()\n netG_DeCv.cuda()\n inputd = inputd.cuda()\n inputg = inputg.cuda()\n one, mone = one.cuda(), mone.cuda()\n noise, fixed_noise = noise.cuda(), fixed_noise.cuda()\n # dataset = dataset.cuda()\n # dataset_sampler_indexs = dataset_sampler_indexs.cuda()\n\n# setup optimizer\nif opt.adam:\n optimizerD = optim.Adam(netD.parameters(), lr=opt.lrD, betas=(opt.beta1, 0.999))\n optimizerG = optim.Adam(netG.parameters(), lr=opt.lrG, betas=(opt.beta1, 0.999))\nelse:\n optimizerD = optim.RMSprop(netD.parameters(), lr = opt.lrD)\n optimizerG_Cv = optim.RMSprop(netG_Cv.parameters(), lr = opt.lrG)\n optimizerG_DeCv = optim.RMSprop(netG_DeCv.parameters(), lr = opt.lrG)\n\niteration_i = 0\ndataset_i = 0\n\nwhile True:\n\n ######################################################################\n ########################### Update D network #########################\n ######################################################################\n\n '''\n when train D network, paramters of D network in trained,\n reset requires_grad of D network to true.\n (they are set to False below in netG update)\n '''\n for p in netD.parameters():\n p.requires_grad = True\n\n '''\n train the discriminator Diters times\n Diters is set to 100 only on the first 25 generator iterations or\n very sporadically (once every 500 generator iterations).\n This helps to start with the critic at optimum even in the first iterations.\n There shouldn't be a major difference in performance, but it can help,\n especially when visualizing learning curves (since otherwise you'd see the\n loss going up until the critic is properly trained).\n This is also why the first 25 iterations take significantly longer than\n the rest of the training as well.\n '''\n if iteration_i < 25 or iteration_i % 500 == 0:\n Diters = 100\n else:\n Diters = opt.Diters\n\n '''\n start interation training of D network\n D network is trained for sevrel steps when \n G network is trained for one time\n '''\n j = 0\n while j < Diters:\n j += 1\n\n # clamp parameters to a cube\n for p in netD.parameters():\n p.data.clamp_(opt.clamp_lower, opt.clamp_upper)\n\n # next dataset\n dataset_i += 1\n\n ######## train D network with real #######\n\n ## random sample from dataset ##\n raw = torch.index_select(dataset,0,dataset_sampler_indexs.random_(0,dataset_len))\n image = [] \n for image_i in range(4):\n image += [raw.narrow(1,image_i,1)]\n state_prediction_gt = torch.cat(image,2)\n state_prediction_gt = torch.squeeze(state_prediction_gt,1)\n if opt.cuda:\n state_prediction_gt = state_prediction_gt.cuda()\n state = state_prediction_gt.narrow(1,0*nc,3*nc)\n prediction_gt = state_prediction_gt.narrow(1,3*nc,1*nc)\n\n ######### train D with real ########\n\n # reset grandient\n netD.zero_grad()\n\n # feed\n inputd.resize_as_(state_prediction_gt).copy_(state_prediction_gt)\n inputdv = Variable(inputd)\n\n # compute\n errD_real, outputD_real = netD(inputdv)\n errD_real.backward(one)\n\n ########### get fake #############\n\n # feed\n inputg.resize_as_(state).copy_(state)\n inputgv = Variable(inputg, volatile = True) # totally freeze netG\n\n # compute encoded\n encodedv = netG_Cv(inputgv)\n\n # compute noise\n noise.resize_(opt.batchSize, nz, 1, 1).normal_(0, 1)\n noisev = Variable(noise, volatile = True) # totally freeze netG\n\n # concate encodedv and noisev\n encodedv_noisev = torch.cat([encodedv,noisev],1)\n\n # predict\n prediction = netG_DeCv(encodedv_noisev)\n prediction = prediction.data\n \n ############ train D with fake ###########\n\n # get state_prediction\n state_prediction = torch.cat([state, prediction], 1)\n\n # feed\n inputd.resize_as_(state_prediction).copy_(state_prediction)\n inputdv = Variable(inputd)\n\n # compute\n errD_fake, outputD_fake = netD(inputdv)\n errD_fake.backward(mone)\n\n # optmize\n errD = errD_real - errD_fake\n optimizerD.step()\n\n ######################################################################\n ####################### End of Update D network ######################\n ######################################################################\n\n ######################################################################\n ########################## Update G network ##########################\n ######################################################################\n\n '''\n when train G networks, paramters in p network is freezed\n to avoid computation on grad\n this is reset to true when training D network\n '''\n for p in netD.parameters():\n p.requires_grad = False\n\n # reset grandient\n netG_Cv.zero_grad()\n netG_DeCv.zero_grad()\n\n # feed\n inputg.resize_as_(state).copy_(state)\n inputgv = Variable(inputg)\n\n # compute encodedv\n encodedv = netG_Cv(inputgv)\n\n # compute noisev\n noise.resize_(opt.batchSize, nz, 1, 1).normal_(0, 1)\n noisev = Variable(noise)\n\n # concate encodedv and noisev\n encodedv_noisev = torch.cat([encodedv,noisev],1)\n\n # predict\n prediction = netG_DeCv(encodedv_noisev)\n\n # get state_predictionv, this is a Variable cat \n statev_predictionv = torch.cat([Variable(state), prediction], 1)\n\n # feed, this state_predictionv is Variable\n inputdv = statev_predictionv\n\n # compute\n errG, _ = netD(inputdv)\n errG.backward(one)\n\n # optmize\n optimizerG_Cv.step()\n optimizerG_DeCv.step()\n\n ######################################################################\n ###################### End of Update G network #######################\n ######################################################################\n\n\n ######################################################################\n ########################### One Iteration ### ########################\n ######################################################################\n\n '''log result'''\n print('[iteration_i:%d][dataset_i:%d] Loss_D: %f Loss_G: %f Loss_D_real: %f Loss_D_fake %f'\n % (iteration_i, iteration_i,\n errD.data[0], errG.data[0], errD_real.data[0], errD_fake.data[0]))\n\n '''log image result'''\n if iteration_i % 100 == 0:\n\n '''function need for log image'''\n def sample2image(sample):\n if config.gan_nc is 1:\n c = sample / 3.0\n c = torch.unsqueeze(c,1)\n save = torch.cat([c,c,c],1)\n elif config.gan_nc is 3:\n save = []\n for image_i in range(4):\n save += [torch.unsqueeze(sample.narrow(0,image_i*3,3),0)]\n save = torch.cat(save,0)\n \n # save = save.mul(0.5).add(0.5)\n return save\n\n '''log real result'''\n vutils.save_image(sample2image(state_prediction_gt[0]), '{0}/real_samples_{1}.png'.format(opt.experiment, iteration_i))\n\n '''log perdict result'''\n vutils.save_image(sample2image(state_prediction[0]), '{0}/fake_samples_{1}.png'.format(opt.experiment, iteration_i))\n\n '''do checkpointing'''\n torch.save(netG_Cv.state_dict(), '{0}/{1}/netG_Cv.pth'.format(opt.experiment,config.gan_model_name_))\n torch.save(netG_DeCv.state_dict(), '{0}/{1}/netG_DeCv.pth'.format(opt.experiment,config.gan_model_name_))\n torch.save(netD.state_dict(), '{0}/{1}/netD.pth'.format(opt.experiment,config.gan_model_name_))\n\n iteration_i += 1\n ######################################################################\n ######################### End One in Iteration ######################\n ######################################################################\n\n \n" }, { "alpha_fraction": 0.4406140446662903, "alphanum_fraction": 0.44977107644081116, "avg_line_length": 33.073394775390625, "blob_id": "67642fd3db932880558c601da055d41dc40d69f2", "content_id": "915cb07854887219e1b30b24d8ae5feff8b4ebeb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3713, "license_type": "permissive", "max_line_length": 178, "num_lines": 109, "path": "/my_env.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "import numpy as np\nimport config\nimport time\ndef get_grid_observation(x, y):\n observation = np.ones((config.gan_size,config.gan_size))\n observation[x*(config.gan_size/config.grid_size):(x+1)*(config.gan_size/config.grid_size),y*(config.gan_size/config.grid_size):(y+1)*(config.gan_size/config.grid_size)] = 0.0\n observation = np.expand_dims(a=observation,\n axis=0)\n observation = np.concatenate((observation,observation,observation),\n axis=0)\n return observation\nclass env():\n def __init__(self):\n self.will_reset = False\n self.step = 0\n self.step_limit = config.grid_size*4\n\n def reset(self):\n ################# reset state ################\n self.cur_x = 0\n self.cur_y = 0\n ##############################################\n self.step = 0\n self.done = True\n self.reward = 0.0\n self.will_reset = False\n\n def if_win(self):\n ################# if win #####################\n win = self.cur_x is config.grid_target_x and self.cur_y is config.grid_target_y\n ##############################################\n return win\n\n def update_observation(self):\n ################# update observation #####################\n self.observation = get_grid_observation(self.cur_x,self.cur_y)\n ##########################################################\n\n def get_initial_observation(self):\n self.reset()\n self.update_observation()\n print('--------------------------------------')\n return self.observation\n\n def act(self, action):\n\n self.action = action\n self.step += 1\n \n if self.will_reset:\n self.reset()\n else:\n self.done = False\n\n ########################## update state #########################\n\n '''randomlize action'''\n action_dic = range(config.action_space)\n\n action_dic_p = np.zeros((config.action_space))\n for i in range(len(action_dic_p)):\n distance = abs(i-self.action)\n if distance > (config.action_space/2):\n distance = distance - (config.action_space/2)\n action_dic_p[i] = config.grid_action_random_discounter**(distance)\n action_dic_p = action_dic_p / np.sum(action_dic_p)\n\n self.action = np.random.choice(a=action_dic, \n p=action_dic_p)\n\n self.action = int(self.action)\n\n if self.action is 0:\n self.cur_x += 1\n elif self.action is 1:\n self.cur_x -= 1\n elif self.action is 2:\n self.cur_y += 1\n elif self.action is 3:\n self.cur_y -= 1\n else:\n print(s)\n\n if self.cur_x >= config.grid_size:\n self.cur_x = config.grid_size-1\n if self.cur_y >= config.grid_size:\n self.cur_y = config.grid_size-1\n if self.cur_x < 0:\n self.cur_x = 0\n if self.cur_y < 0:\n self.cur_y = 0\n\n time.sleep(config.lower_env_worker)\n\n ###########################################################\n\n '''judging done'''\n self.will_reset = False\n if self.if_win():\n self.reward = 1.0\n self.will_reset = True\n else:\n self.reward = 0.0\n if self.step > self.step_limit:\n self.will_reset = True\n\n self.update_observation()\n\n return self.observation, self.reward, self.done" }, { "alpha_fraction": 0.6272571086883545, "alphanum_fraction": 0.6306964755058289, "avg_line_length": 28.087499618530273, "blob_id": "e9810d48cd695470f4c2f8e53936283c8d8b0fdd", "content_id": "e8893cae21dedd07738e0e4a7252360f05a221a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2326, "license_type": "permissive", "max_line_length": 101, "num_lines": 80, "path": "/worker_train_gan.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nfrom collections import namedtuple\nimport numpy as np\nimport go_vncdriver\nimport tensorflow as tf\nfrom model import LSTMPolicy\nimport six.moves.queue as queue\nimport scipy.signal\nimport threading\nimport distutils.version\nimport config\nimport globalvar as GlobalVar\nimport argparse\nimport random\nimport os\nimport copy\nimport wgan_models.dcgan as dcgan\nimport wgan_models.mlp as mlp\nimport support_lib\nimport config\nimport subprocess\nimport time\nimport multiprocessing\nimport gan\nuse_tf12_api = distutils.version.LooseVersion(tf.VERSION) >= distutils.version.LooseVersion('0.12.0')\n\nclass GanTrainer():\n \"\"\"\n This thread runs gan training\n \"\"\"\n def __init__(self):\n \n self.gan = gan.gan() # create gan\n self.last_load_time = time.time() # record last_load_time as initialize time\n\n def load_data(self):\n self.load_time = time.time() # get this load time\n if (self.load_time-self.last_load_time) >= config.gan_worker_com_internal:\n\n '''if it is time to load'''\n print('Try loading data...')\n data = None\n try:\n data = np.load(config.datadir+'data.npz')['data'] # load data\n if np.shape(data)[0] is 0:\n return\n else:\n print('Data loaded: '+str(np.shape(data)))\n self.last_load_time = time.time() # record last load time\n np.savez(config.datadir+'data.npz',\n data=self.gan.empty_dataset_with_aux)\n except Exception, e:\n print('Load failed')\n print(str(Exception)+\": \"+str(e))\n\n if data is not None:\n self.gan.push_data(data) # push data to gan\n\n def run(self):\n\n while True:\n\n '''keep running'''\n self.load_data()\n self.gan.train()\n time.sleep(config.lower_gan_worker)\n\nif __name__ == \"__main__\":\n trainer = GanTrainer()\n trainer.run()" }, { "alpha_fraction": 0.4829457402229309, "alphanum_fraction": 0.5054263472557068, "avg_line_length": 33.5117073059082, "blob_id": "6668433a7070b10b63627b787b555c32be905a3a", "content_id": "10b63ac1d3fa39141c6ad464e40b722db350edaf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10320, "license_type": "permissive", "max_line_length": 90, "num_lines": 299, "path": "/wgan_models/dcgan.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport config\n\nclass DCGAN_D(nn.Module):\n\n '''\n deep conv GAN: D\n '''\n\n def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0):\n\n '''\n build the model\n '''\n\n # basic init\n super(DCGAN_D, self).__init__()\n self.ngpu = ngpu\n assert isize % 16 == 0, \"isize has to be a multiple of 16\"\n\n # starting main model\n main = nn.Sequential()\n\n # input is (4*nc) x isize x isize\n # the first (3*nc) channels are state, the 4th nc channel is prediction\n main.add_module('initial.conv.{0}-{1}'.format(4*nc, ndf),\n nn.Conv2d(4*nc, ndf, 4, 2, 1, bias=False))\n main.add_module('initial.relu.{0}'.format(ndf),\n nn.LeakyReLU(0.2, inplace=True))\n csize, cndf = isize / 2, ndf\n\n # keep conv till\n while csize > config.gan_dct:\n in_feat = cndf\n out_feat = cndf * 2\n main.add_module('pyramid.{0}-{1}.conv'.format(in_feat, out_feat),\n nn.Conv2d(in_feat, out_feat, 4, 2, 1, bias=False))\n main.add_module('pyramid.{0}.batchnorm'.format(out_feat),\n nn.BatchNorm2d(out_feat))\n main.add_module('pyramid.{0}.relu'.format(out_feat),\n nn.LeakyReLU(0.2, inplace=True))\n cndf = cndf * 2\n csize = csize / 2\n\n # state size K x 4 x 4\n main.add_module('final.{0}-{1}.conv'.format(cndf, 1),\n nn.Conv2d(cndf, 1, config.gan_dct, 1, 0, bias=False))\n\n # main model done\n self.main = main\n\n def forward(self, input):\n\n '''\n specific return when comute forward\n '''\n\n # compute output according to GPU parallel\n if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1:\n output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n else: \n output = self.main(input)\n\n # compute error\n error = output.mean(0)\n\n # return\n return error.view(1), output\n\nclass DCGAN_G_Cv(nn.Module):\n\n '''\n deep conv GAN: G\n '''\n\n def __init__(self, isize, nz, nc, ngf, ngpu, n_extra_layers=0):\n\n '''\n build model\n '''\n\n # basic intialize\n super(DCGAN_G_Cv, self).__init__()\n self.ngpu = ngpu\n assert isize % 16 == 0, \"isize has to be a multiple of 16\"\n\n # starting main model\n main = nn.Sequential()\n\n # input is (3*nc) x isize x isize\n # which is 3 sequential states\n # initial conv\n main.add_module('initial.conv_gc.{0}-{1}'.format(3*nc, ngf),\n nn.Conv2d(3*nc, ngf, 4, 2, 1, bias=False))\n main.add_module('initial.relu_gc.{0}'.format(ngf),\n nn.LeakyReLU(0.2, inplace=True))\n csize, cndf = isize / 2, ngf\n\n # conv till\n while csize > config.gan_gctc:\n in_feat = cndf\n out_feat = cndf * 2\n main.add_module('pyramid.{0}-{1}.conv_gc'.format(in_feat, out_feat),\n nn.Conv2d(in_feat, out_feat, 4, 2, 1, bias=False))\n main.add_module('pyramid.{0}.batchnorm_gc'.format(out_feat),\n nn.BatchNorm2d(out_feat))\n main.add_module('pyramid.{0}.relu_gc'.format(out_feat),\n nn.LeakyReLU(0.2, inplace=True))\n cndf = cndf * 2 \n csize = csize / 2\n\n # conv final to nz\n # state size. K x 4 x 4\n main.add_module('final.{0}-{1}.conv_gc'.format(cndf, nz),\n nn.Conv2d(cndf, nz, config.gan_gctc, 1, 0, bias=False))\n\n # main model done\n self.main = main\n\n def forward(self, input):\n\n '''\n specific forward comute\n '''\n\n # compute output according to gpu parallel\n if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1:\n output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n else: \n output = self.main(input)\n\n # return\n return output\n\nclass DCGAN_G_DeCv(nn.Module):\n\n '''\n deep conv GAN: G\n '''\n\n def __init__(self, isize, nz, nc, ngf, ngpu, n_extra_layers=0):\n\n '''\n build model\n '''\n\n # basic intialize\n super(DCGAN_G_DeCv, self).__init__()\n self.ngpu = ngpu\n assert isize % 16 == 0, \"isize has to be a multiple of 16\"\n\n # starting main model\n main = nn.Sequential()\n\n # compute initial cngf for deconv\n cngf, tisize = ngf//2, config.gan_gctd\n while tisize != isize:\n cngf = cngf * 2\n tisize = tisize * 2\n\n # initail deconv\n main.add_module('initial.{0}-{1}.conv_gd'.format(nz*2, cngf),\n nn.ConvTranspose2d(nz*2, cngf, config.gan_gctd, 1, 0, bias=False))\n main.add_module('initial.{0}.batchnorm_gd'.format(cngf),\n nn.BatchNorm2d(cngf))\n main.add_module('initial.{0}.relu_gd'.format(cngf),\n nn.ReLU(True))\n csize, cndf = config.gan_gctd, cngf\n\n # deconv till\n while csize < isize//2:\n main.add_module('pyramid.{0}-{1}.conv_gd'.format(cngf, cngf//2),\n nn.ConvTranspose2d(cngf, cngf//2, 4, 2, 1, bias=False))\n main.add_module('pyramid.{0}.batchnorm_gd'.format(cngf//2),\n nn.BatchNorm2d(cngf//2))\n main.add_module('pyramid.{0}.relu_gd'.format(cngf//2),\n nn.ReLU(True))\n cngf = cngf // 2\n csize = csize * 2\n\n # layer for final output\n main.add_module('final.{0}-{1}.conv_gd'.format(cngf, nc),\n nn.ConvTranspose2d(cngf, nc, 4, 2, 1, bias=False))\n main.add_module('final.{0}.tanh_gd'.format(nc),\n nn.Tanh())\n\n # main model done\n self.main = main\n\n def forward(self, input):\n\n '''\n specific forward comute\n '''\n\n # compute output according to gpu parallel\n if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1:\n output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n else: \n output = self.main(input)\n\n # return\n return output\n\n\nclass DCGAN_D_nobn(nn.Module):\n def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0):\n super(DCGAN_D_nobn, self).__init__()\n self.ngpu = ngpu\n assert isize % 16 == 0, \"isize has to be a multiple of 16\"\n\n main = nn.Sequential()\n # input is nc x isize x isize\n # input is nc x isize x isize\n main.add_module('initial.conv.{0}-{1}'.format(nc, ndf),\n nn.Conv2d(nc, ndf, 4, 2, 1, bias=False))\n main.add_module('initial.relu.{0}'.format(ndf),\n nn.LeakyReLU(0.2, inplace=True))\n csize, cndf = isize / 2, ndf\n\n # Extra layers\n for t in range(n_extra_layers):\n main.add_module('extra-layers-{0}.{1}.conv'.format(t, cndf),\n nn.Conv2d(cndf, cndf, 3, 1, 1, bias=False))\n main.add_module('extra-layers-{0}.{1}.relu'.format(t, cndf),\n nn.LeakyReLU(0.2, inplace=True))\n\n while csize > 4:\n in_feat = cndf\n out_feat = cndf * 2\n main.add_module('pyramid.{0}-{1}.conv'.format(in_feat, out_feat),\n nn.Conv2d(in_feat, out_feat, 4, 2, 1, bias=False))\n main.add_module('pyramid.{0}.relu'.format(out_feat),\n nn.LeakyReLU(0.2, inplace=True))\n cndf = cndf * 2\n csize = csize / 2\n\n # state size. K x 4 x 4\n main.add_module('final.{0}-{1}.conv'.format(cndf, 1),\n nn.Conv2d(cndf, 1, 4, 1, 0, bias=False))\n self.main = main\n\n\n def forward(self, input):\n if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1:\n output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n else: \n output = self.main(input)\n \n output = output.mean(0)\n return output.view(1)\n\nclass DCGAN_G_nobn(nn.Module):\n def __init__(self, isize, nz, nc, ngf, ngpu, n_extra_layers=0):\n super(DCGAN_G_nobn, self).__init__()\n self.ngpu = ngpu\n assert isize % 16 == 0, \"isize has to be a multiple of 16\"\n\n cngf, tisize = ngf//2, 4\n while tisize != isize:\n cngf = cngf * 2\n tisize = tisize * 2\n\n main = nn.Sequential()\n main.add_module('initial.{0}-{1}.convt'.format(nz, cngf),\n nn.ConvTranspose2d(nz, cngf, 4, 1, 0, bias=False))\n main.add_module('initial.{0}.relu'.format(cngf),\n nn.ReLU(True))\n\n csize, cndf = 4, cngf\n while csize < isize//2:\n main.add_module('pyramid.{0}-{1}.convt'.format(cngf, cngf//2),\n nn.ConvTranspose2d(cngf, cngf//2, 4, 2, 1, bias=False))\n main.add_module('pyramid.{0}.relu'.format(cngf//2),\n nn.ReLU(True))\n cngf = cngf // 2\n csize = csize * 2\n\n # Extra layers\n for t in range(n_extra_layers):\n main.add_module('extra-layers-{0}.{1}.conv'.format(t, cngf),\n nn.Conv2d(cngf, cngf, 3, 1, 1, bias=False))\n main.add_module('extra-layers-{0}.{1}.relu'.format(t, cngf),\n nn.ReLU(True))\n\n main.add_module('final.{0}-{1}.convt'.format(cngf, nc),\n nn.ConvTranspose2d(cngf, nc, 4, 2, 1, bias=False))\n main.add_module('final.{0}.tanh'.format(nc),\n nn.Tanh())\n self.main = main\n\n def forward(self, input):\n if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1:\n output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n else: \n output = self.main(input)\n return output \n" }, { "alpha_fraction": 0.6937269568443298, "alphanum_fraction": 0.6937269568443298, "avg_line_length": 23.636363983154297, "blob_id": "eb5cc59206bab880eee8c5e3beb672a96f37d858", "content_id": "83372f523a7634acb59dbaf9205587f0a5a0b228", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "permissive", "max_line_length": 31, "num_lines": 11, "path": "/globalvar.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "class GlobalVar: \n db_handle = None\n mq_client = None\ndef set_db_handle(db): \n GlobalVar.db_handle = db \ndef get_db_handle(): \n return GlobalVar.db_handle \ndef set_mq_client(mq_cli): \n GlobalVar.mq_client = mq_cli \ndef get_mq_client(): \n return GlobalVar.mq_client " }, { "alpha_fraction": 0.5675281286239624, "alphanum_fraction": 0.5908712148666382, "avg_line_length": 33.271427154541016, "blob_id": "214ca2b11b12b7cda386d13e075ea0ed4eaddeeb", "content_id": "c4ec3f2f2a2e79060e178bc3650e3b33b1ab163b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4798, "license_type": "permissive", "max_line_length": 124, "num_lines": 140, "path": "/grid_game.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "from pygame.locals import *\nimport pygame\nimport numpy as np\nimport cv2\nimport sys\n\n\nDIRECTION_UP, DIRECTION_DOWN, DIRECTION_LEFT, DIRECTION_RIGHT, DIRECTION_NONE = range(5)\n\nCOLOR_RED = (255,0,0)\nCOLOR_GREEN= (0,255,0)\nCOLOR_BLUE = (0,0,255)\nCOLOR_DARKBLUE = (0,0,128)\nCOLOR_WHITE = (255,255,255)\nCOLOR_BLACK = (0,0,0)\nCOLOR_PINK = (255,200,200)\n\nclass GameLogic(object):\n\n def __init__(self, width=4, height=4, wrap=True):\n self.width = width\n self.height = height\n self.player_pos = (0, 0)\n self.wrap = wrap\n self.dir_mapping_y = {DIRECTION_DOWN: 1, DIRECTION_UP: -1}\n self.dir_mapping_x = {DIRECTION_RIGHT: 1, DIRECTION_LEFT: -1}\n\n\n def move_player(self, direction):\n (x, y) = self.player_pos\n dx = self.dir_mapping_x.get(direction, 0)\n dy = self.dir_mapping_y.get(direction, 0)\n if not self.wrap:\n x = np.clip(x + dx, 0, self.width-1)\n y = np.clip(y + dy, 0, self.height-1)\n else:\n x = (x + dx) % self.width\n y = (y + dy) % self.height\n self.player_pos = (x, y)\n\n\n def generate_objects(self):\n return {'player': self.player_pos}\n\n\nclass Visualizer(object):\n\n def __init__(self, game_logic, block_size=50, fps=30, use_gui=False):\n self.game_logic = game_logic\n self.block_size = block_size\n self.fps = fps\n self.use_gui = use_gui\n if self.use_gui:\n self.screen = pygame.display.set_mode((game_logic.width * block_size, game_logic.height * block_size))\n else:\n self.screen = pygame.Surface((game_logic.width * block_size, game_logic.height * block_size))\n\n self.screen_pixels = np.zeros((block_size * game_logic.width, block_size * game_logic.height, 3), dtype=np.uint8)\n self.clock = pygame.time.Clock()\n self.action_mapping = {0: DIRECTION_NONE, 1: DIRECTION_LEFT, 2: DIRECTION_UP, 3: DIRECTION_DOWN, 4: DIRECTION_RIGHT}\n\n\n def draw_rect(self, (x, y), color):\n pygame.draw.rect(self.screen, color, (self.block_size*x, self.block_size*y, self.block_size, self.block_size), 0)\n\n\n def draw_screen(self):\n game_objects = self.game_logic.generate_objects()\n self.screen_pixels = self.generate_screen(game_objects)\n if self.use_gui:\n pygame.display.update()\n\n\n def generate_screen(self, game_objects):\n self.screen.fill(COLOR_WHITE)\n self.draw_rect(game_objects['player'], COLOR_BLUE)\n pixels = np.transpose(pygame.surfarray.array3d(self.screen), [1, 0, 2])[:, :, [2, 0, 1]]\n return pixels\n\n\n def generate_lowdim_screen(self, game_objects):\n (x, y) = game_objects['player']\n position = 4*y + x\n array = np.zeros([16], dtype=np.float32)\n array[position] = 1.\n return array\n\n def get_blue_shade(self, shade):\n combined_color = shade*np.array([0, 0, 255]) + (1-shade)*np.array([255, 255, 255])\n return tuple(combined_color.astype(np.uint8).tolist())\n\n def generate_screen_from_lowdim(self, lowdim):\n self.screen.fill(COLOR_WHITE)\n for i in range(16):\n y = i / 4\n x = i % 4\n self.draw_rect((x, y), self.get_blue_shade(lowdim[i]))\n return np.transpose(pygame.surfarray.array3d(self.screen), [1, 0, 2])[:, :, [2, 0, 1]]\n\n def perform_action(self, action_index, lowdim=False):\n if lowdim:\n old_screen = self.generate_lowdim_screen(self.game_logic.generate_objects())\n else:\n old_screen = self.screen_pixels.copy()\n direction = self.action_mapping[action_index]\n self.game_logic.move_player(direction)\n self.draw_screen()\n if lowdim:\n new_screen = self.generate_lowdim_screen(self.game_logic.generate_objects())\n else:\n new_screen = self.screen_pixels.copy()\n return old_screen, action_index, new_screen\n\n\n def run_with_human_player(self):\n while True:\n self.clock.tick(self.fps)\n dir = self.handle_human_input()\n self.game_logic.move_player(dir)\n self.draw_screen()\n\n\n def handle_human_input(self):\n dir = DIRECTION_NONE\n for event in pygame.event.get():\n if not hasattr(event, 'key'): continue\n if event.type == KEYDOWN:\n if event.key == K_RIGHT: dir = DIRECTION_RIGHT\n elif event.key == K_LEFT: dir = DIRECTION_LEFT\n elif event.key == K_UP: dir = DIRECTION_UP\n elif event.key == K_DOWN: dir = DIRECTION_DOWN\n elif event.key == K_ESCAPE: sys.exit(0)\n return dir\n\n\n\nif __name__ == '__main__':\n game = GameLogic(width=5, height=5)\n vis = Visualizer(game, use_gui=False)\n vis.run_with_human_player()\n" }, { "alpha_fraction": 0.5160142183303833, "alphanum_fraction": 0.5195729732513428, "avg_line_length": 13.789473533630371, "blob_id": "f0f55042e5026b0d9437ba77cad79348ac49268a", "content_id": "418b4bb30cbe4106f6369a0a47fa0574e75787f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "permissive", "max_line_length": 50, "num_lines": 19, "path": "/kill.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "import os\nimport config\nimport subprocess\n\ndef run():\n\n session = \"a3c\"\n\n cmds = [\n \"tmux kill-session -t {}\".format(session),\n ]\n '''excute cmds'''\n os.system(\"\\n\".join(cmds))\n\n subprocess.call([\"rm\", \"-r\", 'temp'])\n\n\nif __name__ == \"__main__\":\n run()\n" }, { "alpha_fraction": 0.5851627588272095, "alphanum_fraction": 0.6131718158721924, "avg_line_length": 24.843137741088867, "blob_id": "5c9b8895ff1f61006e65f560cf92dd8165ebe7ec", "content_id": "6d813b538f935f3bca12f9c43c89677214fe1002", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1321, "license_type": "permissive", "max_line_length": 123, "num_lines": 51, "path": "/config.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "# exp time\nt = 5\nlable = 'sto_noise_action_half'\n\n# mode\nrun_on = 'agent' # agent, video\n\ngan_size = 128\ngan_nc = 3\n\nif run_on is 'video':\n dataset_path = '../../dataset/'\n video_name_ = '3DPinball_1'\n video_name = video_name_+'.mp4'\n gan_predict_interval = 0.1\n dataset_name_ = video_name_+'_d'+str(gan_predict_interval).replace('.','')+'_c'+str(gan_size)+'_nc'+str(gan_nc)\n dataset_name = dataset_name_+'.npz'\nelif run_on is 'agent':\n dataset_name_ = 'agent'\n\n# gan model\ngan_batchsize = 64\ngan_nz = 256\ngan_ngpu = 2\ngan_dct = 4\ngan_gctc = 4\ngan_gctd = 4\ngan_model_name_ = 'bs'+str(gan_batchsize)+'_nz'+str(gan_nz)+'_dct'+str(gan_dct)+'_gctc'+str(gan_gctc)+'_gctd'+str(gan_gctd)\n\n# generate logdir according to config\nlogdir = '../../result/gmbrl_1/'+dataset_name_+'/'+gan_model_name_+'_l'+lable+'_t'+str(t)+'/'\nmodeldir = logdir+gan_model_name_+'/'\ndatadir = logdir+'data/'\n\nif run_on is 'agent':\n \"\"\"\n config rl env here\n \"\"\" \n overwirite_with_grid = True\n action_space = 4\n grid_size = 8\n grid_target_x = 4\n grid_target_y = 4\n grid_action_random_discounter = 0.3\n gan_worker_com_internal = 10\n gan_save_image_internal = 60*5\n gan_recent_dataset = 10\n lower_gan_worker = 0.0\n lower_env_worker = 0.0\n agent_learning = False\n agent_acting = False " }, { "alpha_fraction": 0.5041206479072571, "alphanum_fraction": 0.5172455906867981, "avg_line_length": 41.21907043457031, "blob_id": "63ca010cc7dee101bc4bf7d64ab26425de882246", "content_id": "8953397cb7ba12b09cd5bfee4a199c57b23f9076", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16381, "license_type": "permissive", "max_line_length": 129, "num_lines": 388, "path": "/run_wgan.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport argparse\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nimport os\nimport numpy as np\nimport copy\n\nimport wgan_models.dcgan as dcgan\nimport wgan_models.mlp as mlp\nimport support_lib\nimport config\nimport subprocess\nimport time\nimport gsa_io\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', default='lsun', help='cifar10 | lsun | imagenet | folder | lfw ')\nparser.add_argument('--dataroot', default='../../dataset', help='path to dataset')\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=16)\nparser.add_argument('--batchSize', type=int, default=config.gsa_batchsize, help='input batch size')\nparser.add_argument('--imageSize', type=int, default=config.gsa_size, help='the height / width of the input image to network')\nparser.add_argument('--nc', type=int, default=3, help='input image channels')\nparser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')\nparser.add_argument('--ngf', type=int, default=64)\nparser.add_argument('--ndf', type=int, default=64)\nparser.add_argument('--niter', type=int, default=25, help='number of epochs to train for')\nparser.add_argument('--lrD', type=float, default=0.00005, help='learning rate for Critic, default=0.00005')\nparser.add_argument('--lrG', type=float, default=0.00005, help='learning rate for Generator, default=0.00005')\nparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5')\nparser.add_argument('--cuda' , default=True, action='store_true', help='enables cuda')\nparser.add_argument('--ngpu' , type=int, default=1, help='number of GPUs to use')\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\nparser.add_argument('--netD', default='', help=\"path to netD (to continue training)\")\nparser.add_argument('--clamp_lower', type=float, default=-0.01)\nparser.add_argument('--clamp_upper', type=float, default=0.01)\nparser.add_argument('--Diters', type=int, default=5, help='number of D iters per each G iter')\nparser.add_argument('--noBN', action='store_true', help='use batchnorm or not (only for DCGAN)')\nparser.add_argument('--mlp_G', action='store_true', help='use MLP for G')\nparser.add_argument('--mlp_D', action='store_true', help='use MLP for D')\nparser.add_argument('--n_extra_layers', type=int, default=0, help='Number of extra layers on gen and disc')\nparser.add_argument('--experiment', default=config.logdir, help='Where to store samples and models')\nparser.add_argument('--adam', action='store_true', help='Whether to use adam (default is rmsprop)')\nopt = parser.parse_args()\nprint(opt)\n\n# Where to store samples and models\nif opt.experiment is None:\n opt.experiment = 'samples'\nos.system('mkdir {0}'.format(opt.experiment))\n\n# random seed for\nopt.manualSeed = random.randint(1, 10000) # fix seed\nprint(\"Random Seed: \", opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\n\ncudnn.benchmark = True\n\n# load dataset\nif torch.cuda.is_available() and not opt.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\nif opt.dataset in ['imagenet', 'folder', 'lfw']:\n # folder dataset\n dataset = dset.ImageFolder(root=opt.dataroot,\n transform=transforms.Compose([\n transforms.Scale(opt.imageSize),\n transforms.CenterCrop(opt.imageSize),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\nelif opt.dataset == 'lsun':\n dataset = dset.LSUN(db_path=opt.dataroot, classes=['bedroom_train'],\n transform=transforms.Compose([\n transforms.Scale(opt.imageSize),\n transforms.CenterCrop(opt.imageSize),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\nelif opt.dataset == 'cifar10':\n dataset = dset.CIFAR10(root=opt.dataroot, download=True,\n transform=transforms.Compose([\n transforms.Scale(opt.imageSize),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n )\nassert dataset\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batchSize,\n shuffle=True, num_workers=int(opt.workers))\n\nngpu = int(opt.ngpu)\nnz = int(opt.nz)\nngf = int(opt.ngf)\nndf = int(opt.ndf)\nnc = int(opt.nc)\nn_extra_layers = int(opt.n_extra_layers)\n\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n'''create netG'''\nif opt.noBN:\n netG = dcgan.DCGAN_G_nobn(opt.imageSize, nz, nc, ngf, ngpu, n_extra_layers)\nelif opt.mlp_G:\n netG = mlp.MLP_G(opt.imageSize, nz, nc, ngf, ngpu)\nelse:\n # in the paper. this is the best implementation\n netG = dcgan.DCGAN_G(opt.imageSize, nz, nc, ngf, ngpu, n_extra_layers)\n\nnetG.apply(weights_init)\n\n# load checkpoint if needed\nif opt.netG != '':\n netG.load_state_dict(torch.load(opt.netG))\nprint(netG)\n\nif opt.mlp_D:\n netD = mlp.MLP_D(opt.imageSize, nz, nc, ndf, ngpu)\nelse:\n netD = dcgan.DCGAN_D(opt.imageSize, nz, nc, ndf, ngpu, n_extra_layers)\n netD.apply(weights_init)\n\n# load checkpoint if needed\nif opt.netD != '':\n netD.load_state_dict(torch.load(opt.netD))\nprint(netD)\n\ninput = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize)\nnoise = torch.FloatTensor(opt.batchSize, nz, 1, 1)\nfixed_noise = torch.FloatTensor(opt.batchSize, nz, 1, 1).normal_(0, 1)\none = torch.FloatTensor([1])\nmone = one * -1\n\nif opt.cuda:\n netD.cuda()\n netG.cuda()\n input = input.cuda()\n one, mone = one.cuda(), mone.cuda()\n noise, fixed_noise = noise.cuda(), fixed_noise.cuda()\n\n# setup optimizer\nif opt.adam:\n optimizerD = optim.Adam(netD.parameters(), lr=opt.lrD, betas=(opt.beta1, 0.999))\n optimizerG = optim.Adam(netG.parameters(), lr=opt.lrG, betas=(opt.beta1, 0.999))\nelse:\n optimizerD = optim.RMSprop(netD.parameters(), lr = opt.lrD)\n optimizerG = optim.RMSprop(netG.parameters(), lr = opt.lrG)\n\nreal_cpu_recorder = []\nreal_cpu_recorder_path = []\ngen_iterations = 0\nfor epoch in range(opt.niter):\n \n data_iter = iter(dataloader)\n i = 0\n while i < len(dataloader):\n\n ######################################################################\n ########################### Update D network #########################\n ######################################################################\n\n '''\n when train D network, paramters of D network in trained,\n reset requires_grad of D network to true.\n (they are set to False below in netG update)\n '''\n for p in netD.parameters():\n p.requires_grad = True\n\n '''\n train the discriminator Diters times\n Diters is set to 100 only on the first 25 generator iterations or\n very sporadically (once every 500 generator iterations).\n This helps to start with the critic at optimum even in the first iterations.\n There shouldn't be a major difference in performance, but it can help,\n especially when visualizing learning curves (since otherwise you'd see the\n loss going up until the critic is properly trained).\n This is also why the first 25 iterations take significantly longer than\n the rest of the training as well.\n '''\n if gen_iterations < 25 or gen_iterations % 500 == 0:\n Diters = 100\n else:\n Diters = opt.Diters\n\n '''\n start interation training of D network\n D network is trained for sevrel steps when \n G network is trained for one time\n '''\n j = 0\n while j < Diters and i < len(dataloader):\n j += 1\n\n # clamp parameters to a cube\n for p in netD.parameters():\n p.data.clamp_(opt.clamp_lower, opt.clamp_upper)\n\n # next data\n data = data_iter.next()\n i += 1\n\n # train D network with real\n if config.enable_gsa:\n # # input gsa state\n # real_cpu = torch.FloatTensor(np.ones((64,3,64,64)))\n\n # load history\n real_cpu_loader = copy.deepcopy(real_cpu_recorder)\n real_cpu_loader_path = copy.deepcopy(real_cpu_recorder_path)\n # del history\n del real_cpu_recorder\n del real_cpu_recorder_path\n\n while True:\n\n # load a batch\n try:\n path_dic_of_requiring_file=gsa_io.GetFileList(FindPath=config.real_state_dir,\n FlagStr=['__requiring.npz'])\n except Exception, e:\n print('find file list fialed with error: '+str(Exception)+\": \"+str(e))\n continue\n\n for i in range(len(path_dic_of_requiring_file)):\n\n path_of_requiring_file = path_dic_of_requiring_file[i]\n\n if path_of_requiring_file.split('.np')[1] is not 'z':\n print('find npz temp file: '+path_of_requiring_file+'>>pass')\n continue\n\n try:\n requiring_state = np.load(path_of_requiring_file)['state']\n real_cpu_loader += [requiring_state]\n real_cpu_loader_path += [path_of_requiring_file]\n except Exception, e:\n print('load requiring_state error: '+str(Exception)+\": \"+str(e))\n continue\n\n subprocess.call([\"mv\", path_of_requiring_file, path_of_requiring_file.split('__')[0]+'__done.npz'])\n\n # cut\n if len(real_cpu_loader) >= opt.batchSize:\n\n print('load real_cpu_loader: '+str(np.shape(real_cpu_loader)))\n\n # load used part\n real_cpu = copy.deepcopy(real_cpu_loader)[0:opt.batchSize]\n print('load real_cpu: '+str(np.shape(real_cpu)))\n real_cpu=np.asarray(real_cpu)\n real_cpu = torch.FloatTensor(real_cpu)\n real_cpu_path = copy.deepcopy(real_cpu_loader_path)[0:opt.batchSize]\n\n # record uused part\n real_cpu_recorder = copy.deepcopy(real_cpu_loader)[opt.batchSize:-1]\n real_cpu_recorder_path = copy.deepcopy(real_cpu_loader_path)[opt.batchSize:-1]\n print('load real_cpu_recorder: '+str(np.shape(real_cpu_recorder)))\n\n # del loader\n del real_cpu_loader\n del real_cpu_loader_path\n\n # break out loader loop\n break\n else:\n # use data in dataloader\n real_cpu, _ = data\n\n \n\n netD.zero_grad()\n batch_size = real_cpu.size(0)\n\n if opt.cuda:\n real_cpu = real_cpu.cuda()\n\n input.resize_as_(real_cpu).copy_(real_cpu)\n inputv = Variable(input)\n\n errD_real, outputD_real = netD(inputv)\n print('real prob')\n print(errD_real)\n errD_real.backward(one)\n\n if config.enable_gsa:\n # # output the gsa reward\n # print(outputD_real[3,0,0,0])\n for real_cpu_path_i in range(len(real_cpu_path)):\n file = config.waiting_reward_dir+real_cpu_path[real_cpu_path_i].split('/')[-1].split('__')[0]+'__waiting.npz'\n np.savez(file,\n gsa_reward=[(-outputD_real[real_cpu_path_i,0,0,0]+1.0)*0.1])\n\n # train D network with fake\n noise.resize_(opt.batchSize, nz, 1, 1).normal_(0, 1)\n noisev = Variable(noise, volatile = True) # totally freeze netG\n fake = Variable(netG(noisev).data)\n inputv = fake\n errD_fake, _ = netD(inputv)\n print('fake prob')\n print(errD_fake)\n errD_fake.backward(mone)\n errD = errD_real - errD_fake\n optimizerD.step()\n\n ######################################################################\n ####################### End of Update D network ######################\n ######################################################################\n\n ######################################################################\n ########################## Update G network ##########################\n ######################################################################\n\n '''\n when train G networks, paramters in p network is freezed\n to avoid computation on grad\n this is reset to true when training D network\n '''\n for p in netD.parameters():\n p.requires_grad = False\n\n netG.zero_grad()\n\n '''\n in case our last batch was the tail batch of the dataloader,\n make sure we feed a full batch of noise\n '''\n noise.resize_(opt.batchSize, nz, 1, 1).normal_(0, 1)\n noisev = Variable(noise)\n fake = netG(noisev)\n errG, _ = netD(fake)\n errG.backward(one)\n optimizerG.step()\n\n ######################################################################\n ###################### End of Update G network #######################\n ######################################################################\n\n\n ######################################################################\n ########################### One in dataloader ########################\n ######################################################################\n\n gen_iterations += 1\n\n '''log result'''\n print('[%d/%d][%d/%d][%d] Loss_D: %f Loss_G: %f Loss_D_real: %f Loss_D_fake %f'\n % (epoch, opt.niter, i, len(dataloader), gen_iterations,\n errD.data[0], errG.data[0], errD_real.data[0], errD_fake.data[0]))\n if gen_iterations % 500 == 0:\n real_cpu = real_cpu.mul(0.5).add(0.5)\n vutils.save_image(real_cpu, '{0}/real_samples.png'.format(opt.experiment))\n fake = netG(Variable(fixed_noise, volatile=True))\n fake.data = fake.data.mul(0.5).add(0.5)\n vutils.save_image(fake.data, '{0}/fake_samples_{1}.png'.format(opt.experiment, gen_iterations))\n\n ######################################################################\n ######################### End One in dataloader ######################\n ######################################################################\n\n ######################################################################\n ############################# One in epoch ###########################\n ######################################################################\n\n '''do checkpointing'''\n torch.save(netG.state_dict(), '{0}/netG_epoch_{1}.pth'.format(opt.experiment, epoch))\n torch.save(netD.state_dict(), '{0}/netD_epoch_{1}.pth'.format(opt.experiment, epoch))\n\n ######################################################################\n ########################## End One in epoch ##########################\n ######################################################################\n" }, { "alpha_fraction": 0.6366330981254578, "alphanum_fraction": 0.6550089120864868, "avg_line_length": 26.177419662475586, "blob_id": "23433dd127ebd8707d79ce3d5599a0a1fbf23957", "content_id": "0f5b5f49d04334f86448298775303d097d99ec08", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1687, "license_type": "permissive", "max_line_length": 91, "num_lines": 62, "path": "/pre_dataset.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding=utf-8\nimport matplotlib as plt\nimport imageio\nimport numpy as np\nimport config\nimport cv2\nimport copy\nimport subprocess\nfile = config.video_name\ndataset_file = config.dataset_name\ndir = config.dataset_path\nfilename = dir + file\nvid = imageio.get_reader(filename, 'ffmpeg')\ninfo = vid.get_meta_data()\nnum_frame = info['nframes']\nsize = info['size']\nprint info\nnum_step = int(info['duration']/config.gan_predict_interval)\nframe_per_step = num_frame / num_step\nlllast_image = None\nllast_image = None\nlast_image = None\ndataset = []\nfor step in range(0, num_step):\n\n frame = step * frame_per_step\n\n image = np.asarray(vid.get_data(frame))/255.0\n\n c = []\n for color in range(3):\n temp = np.asarray(cv2.resize(image[:,:,color], (config.gan_size, config.gan_size)))\n temp = np.expand_dims(temp,0)\n c += [copy.deepcopy(temp)]\n\n if config.gan_nc is 1:\n image = np.asarray(np.add(c[0]*0.299,c[1]*0.587))\n image = np.asarray(np.add(image,c[2]*0.114))\n elif config.gan_nc is 3:\n image = np.concatenate((c[0],c[1],c[2]),0)\n\n print 'video>'+str(file)+'\\t'+'step>'+str(step)+'\\t'+'size>'+str(np.shape(image))\n \n if last_image is None or llast_image is None or lllast_image is None:\n pass\n else:\n pair = [lllast_image,llast_image,last_image,image]\n dataset += [copy.deepcopy(np.asarray(pair))]\n\n lllast_image = copy.deepcopy(llast_image)\n llast_image = copy.deepcopy(last_image)\n last_image = copy.deepcopy(image)\n\ndataset = np.asarray(dataset)\n\nprint 'genrate dataset with size>'+str(np.shape(dataset))\n\nnp.savez(dir+dataset_file,\n dataset=dataset)\n\nprint(s)\n\n\n" }, { "alpha_fraction": 0.5579250454902649, "alphanum_fraction": 0.5636887550354004, "avg_line_length": 26.539682388305664, "blob_id": "1adea643559927b45f652c951c96a3c9c5473f85", "content_id": "f21891796e8ad940ea94d08428cf9b1aa068b157", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1735, "license_type": "permissive", "max_line_length": 109, "num_lines": 63, "path": "/support_lib.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "import config\nimport subprocess\nimport time\nimport numpy as np\n\ndef fake_gsa():\n\n try:\n path_dic_of_requiring_file=GetFileList(FindPath=config.real_state_dir,\n FlagStr=['__requiring.npz'])\n except Exception, e:\n print(str(Exception)+\": \"+str(e))\n return\n\n for i in range(len(path_dic_of_requiring_file)):\n\n path_of_requiring_file = path_dic_of_requiring_file[i]\n\n if path_of_requiring_file.split('.np')[1] is not 'z':\n print(path_of_requiring_file)\n print('pass')\n continue\n\n try:\n requiring_state = np.load(path_of_requiring_file)['state']\n except Exception, e:\n print(str(Exception)+\": \"+str(e))\n continue\n\n subprocess.call([\"mv\", path_of_requiring_file, path_of_requiring_file.split('__')[0]+'__done.npz'])\n\n file = config.waiting_reward_dir+path_of_requiring_file.split('/')[-1].split('__')[0]+'__waiting.npz'\n np.savez(file,\n gsa_reward=[0.32])\n\ndef IsSubString(SubStrList,Str):\n\n flag=True\n for substr in SubStrList:\n if not(substr in Str):\n flag=False\n\n return flag\n\ndef GetFileList(FindPath,FlagStr=[]):\n\n import os\n FileList=[]\n FileNames=os.listdir(FindPath)\n if (len(FileNames)>0):\n for fn in FileNames:\n if (len(FlagStr)>0):\n if (IsSubString(FlagStr,fn)):\n fullfilename=os.path.join(FindPath,fn)\n FileList.append(fullfilename)\n else:\n fullfilename=os.path.join(FindPath,fn)\n FileList.append(fullfilename)\n\n if (len(FileList)>0):\n FileList.sort()\n\n return FileList\n" }, { "alpha_fraction": 0.5005170106887817, "alphanum_fraction": 0.512810230255127, "avg_line_length": 40.45000076293945, "blob_id": "404b90eef4729a9a2d5e9dde2b8d28044a22b110", "content_id": "50f779c142b2e46628a954428e8611a7ad99bf63", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17408, "license_type": "permissive", "max_line_length": 199, "num_lines": 420, "path": "/gan.py", "repo_name": "YuhangSong/gmbrl", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nfrom collections import namedtuple\nimport numpy as np\nimport go_vncdriver\nimport tensorflow as tf\nfrom model import LSTMPolicy\nimport six.moves.queue as queue\nimport scipy.signal\nimport threading\nimport distutils.version\nimport config\nimport globalvar as GlobalVar\nimport argparse\nimport random\nimport os\nimport copy\nimport wgan_models.dcgan as dcgan\nimport wgan_models.mlp as mlp\nimport support_lib\nimport config\nimport subprocess\nimport time\nimport multiprocessing\nuse_tf12_api = distutils.version.LooseVersion(tf.VERSION) >= distutils.version.LooseVersion('0.12.0')\n\nclass gan():\n \"\"\"\n This thread runs gan training\n \"\"\"\n def __init__(self):\n \n '''config'''\n self.cuda = True\n self.ngpu = config.gan_ngpu\n self.nz = config.gan_nz\n self.ngf = 64\n self.ndf = 64\n self.nc = config.gan_nc\n self.n_extra_layers = 0\n self.imageSize = config.gan_size\n self.lrD = 0.00005\n self.lrG = 0.00005\n self.batchSize = config.gan_batchsize\n self.Diters_ = 5\n self.clamp_lower = -0.01\n self.clamp_upper = 0.01\n self.experiment = config.logdir\n self.dataset_limit = 500\n\n self.empty_dataset_with_aux = np.zeros((0, 5, self.nc, self.imageSize, self.imageSize))\n\n '''random seed for torch'''\n self.manualSeed = random.randint(1, 10000) # fix seed\n print(\"Random Seed: \", self.manualSeed)\n random.seed(self.manualSeed)\n torch.manual_seed(self.manualSeed)\n\n cudnn.benchmark = True\n\n if torch.cuda.is_available() and not self.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n '''custom weights initialization called on netG and netD'''\n def weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n '''create models'''\n self.netG_Cv = dcgan.DCGAN_G_Cv(self.imageSize, self.nz, self.nc, self.ngf, self.ngpu, self.n_extra_layers)\n self.netG_DeCv = dcgan.DCGAN_G_DeCv(self.imageSize, self.nz, self.nc, self.ngf, self.ngpu, self.n_extra_layers)\n self.netD = dcgan.DCGAN_D(self.imageSize, self.nz, self.nc, self.ndf, self.ngpu, self.n_extra_layers)\n\n '''init models'''\n self.netG_Cv.apply(weights_init)\n self.netG_DeCv.apply(weights_init)\n self.netD.apply(weights_init)\n\n self.load_models()\n\n '''print the models'''\n print(self.netG_Cv)\n print(self.netG_DeCv)\n print(self.netD)\n\n self.inputd = torch.FloatTensor(self.batchSize, 4, self.imageSize, self.imageSize)\n self.inputd_real_part = torch.FloatTensor(self.batchSize, 4, self.imageSize, self.imageSize)\n self.inputg = torch.FloatTensor(self.batchSize, 3, self.imageSize, self.imageSize)\n self.inputg_action = torch.FloatTensor(self.batchSize, 1, 1, 1)\n self.noise = torch.FloatTensor(self.batchSize, self.nz/2, 1, 1)\n self.fixed_noise = torch.FloatTensor(self.batchSize, self.nz/2, 1, 1).normal_(0, 1)\n self.one = torch.FloatTensor([1])\n self.mone = self.one * -1\n\n '''dataset intialize'''\n self.dataset_image = torch.FloatTensor(np.zeros((1, 4, self.nc, self.imageSize, self.imageSize)))\n self.dataset_aux = torch.FloatTensor(np.zeros((1, 1, 1, 1)))\n\n '''convert tesors to cuda type'''\n if self.cuda:\n self.netD.cuda()\n self.netG_Cv.cuda()\n self.netG_DeCv.cuda()\n self.inputd = self.inputd.cuda()\n self.inputg = self.inputg.cuda()\n self.inputg_action = self.inputg_action.cuda()\n self.one, self.mone = self.one.cuda(), self.mone.cuda()\n self.noise, self.fixed_noise = self.noise.cuda(), self.fixed_noise.cuda()\n self.dataset_image = self.dataset_image.cuda()\n self.dataset_aux = self.dataset_aux.cuda()\n\n '''create optimizer'''\n self.optimizerD = optim.RMSprop(self.netD.parameters(), lr = self.lrD)\n self.optimizerG_Cv = optim.RMSprop(self.netG_Cv.parameters(), lr = self.lrG)\n self.optimizerG_DeCv = optim.RMSprop(self.netG_DeCv.parameters(), lr = self.lrG)\n\n self.iteration_i = 0\n self.last_save_model_time = 0\n self.last_save_image = 0\n\n def train(self):\n \"\"\"\n train one iteraction\n \"\"\"\n\n if self.dataset_image.size()[0] >= self.batchSize:\n\n '''only train when have enough dataset'''\n print('Train on dataset: '+str(int(self.dataset_image.size()[0])))\n\n ######################################################################\n ########################### Update D network #########################\n ######################################################################\n\n '''\n when train D network, paramters of D network in trained,\n reset requires_grad of D network to true.\n (they are set to False below in netG update)\n '''\n for p in self.netD.parameters():\n p.requires_grad = True\n\n '''\n train the discriminator Diters times\n Diters is set to 100 only on the first 25 generator iterations or\n very sporadically (once every 500 generator iterations).\n This helps to start with the critic at optimum even in the first iterations.\n There shouldn't be a major difference in performance, but it can help,\n especially when visualizing learning curves (since otherwise you'd see the\n loss going up until the critic is properly trained).\n This is also why the first 25 iterations take significantly longer than\n the rest of the training as well.\n '''\n if self.iteration_i < 25 or self.iteration_i % 500 == 0:\n Diters = 100\n else:\n Diters = self.Diters_\n\n '''\n start interation training of D network\n D network is trained for sevrel steps when \n G network is trained for one time\n '''\n j = 0\n while j < Diters:\n j += 1\n\n # clamp parameters to a cube\n for p in self.netD.parameters():\n p.data.clamp_(self.clamp_lower, self.clamp_upper)\n\n ######## train D network with real #######\n\n ## random sample from dataset ##\n raw = self.dataset_image.narrow( 0, self.dataset_image.size()[0] - self.batchSize, self.batchSize)\n action = self.dataset_aux.narrow(0, self.dataset_aux.size()[0] - self.batchSize, self.batchSize)\n state_prediction_gt = torch.cat([raw.narrow(1,0,1),raw.narrow(1,1,1),raw.narrow(1,2,1),raw.narrow(1,3,1)],2)\n state_prediction_gt = torch.squeeze(state_prediction_gt,1)\n state = state_prediction_gt.narrow(1,0*self.nc,3*self.nc)\n prediction_gt = state_prediction_gt.narrow(1,3*self.nc,1*self.nc)\n\n ######### train D with real ########\n\n # reset grandient\n self.netD.zero_grad()\n\n # feed\n self.inputd.resize_as_(state_prediction_gt).copy_(state_prediction_gt)\n inputdv = Variable(self.inputd)\n\n # compute\n errD_real, outputD_real = self.netD(inputdv)\n errD_real.backward(self.one)\n\n ########### get fake #############\n\n # feed\n self.inputg.resize_as_(state).copy_(state)\n inputgv = Variable(self.inputg, volatile = True) # totally freeze netG\n\n # compute encoded\n encodedv = self.netG_Cv(inputgv)\n\n # compute noise\n self.noise.resize_(self.batchSize, self.nz/2, 1, 1).normal_(0, 1)\n noisev = Variable(self.noise, volatile = True) # totally freeze netG\n\n # feed\n self.inputg_action.resize_as_(action).copy_(action)\n inputg_actionv = Variable(self.inputg_action, volatile = True) # totally freeze netG\n\n # concate encodedv, noisev, action\n concated = [inputg_actionv] * (self.nz/2)\n concated += [encodedv]\n concated += [noisev]\n encodedv_noisev_actionv = torch.cat(concated,1)\n\n # print(encodedv_noisev_actionv.size()) # (64L, 512L, 1L, 1L)\n\n # predict\n prediction = self.netG_DeCv(encodedv_noisev_actionv)\n prediction = prediction.data\n \n ############ train D with fake ###########\n\n # get state_prediction\n state_prediction = torch.cat([state, prediction], 1)\n\n # feed\n self.inputd.resize_as_(state_prediction).copy_(state_prediction)\n inputdv = Variable(self.inputd)\n\n # compute\n errD_fake, outputD_fake = self.netD(inputdv)\n errD_fake.backward(self.mone)\n\n # optmize\n errD = errD_real - errD_fake\n self.optimizerD.step()\n\n ######################################################################\n ####################### End of Update D network ######################\n ######################################################################\n\n ######################################################################\n ########################## Update G network ##########################\n ######################################################################\n\n '''\n when train G networks, paramters in p network is freezed\n to avoid computation on grad\n this is reset to true when training D network\n '''\n for p in self.netD.parameters():\n p.requires_grad = False\n\n # reset grandient\n self.netG_Cv.zero_grad()\n self.netG_DeCv.zero_grad()\n\n # feed\n self.inputg.resize_as_(state).copy_(state)\n inputgv = Variable(self.inputg)\n\n # compute encodedv\n encodedv = self.netG_Cv(inputgv)\n\n # compute noisev\n self.noise.resize_(self.batchSize, self.nz/2, 1, 1).normal_(0, 1)\n noisev = Variable(self.noise)\n\n # feed\n self.inputg_action.resize_as_(action).copy_(action)\n inputg_actionv = Variable(self.inputg_action)\n\n # concate encodedv and noisev\n concated = [inputg_actionv] * (self.nz/2)\n concated += [encodedv]\n concated += [noisev]\n encodedv_noisev_actionv = torch.cat(concated,1)\n\n # predict\n prediction = self.netG_DeCv(encodedv_noisev_actionv)\n\n # get state_predictionv, this is a Variable cat \n statev_predictionv = torch.cat([Variable(state), prediction], 1)\n\n # feed, this state_predictionv is Variable\n inputdv = statev_predictionv\n\n # compute\n errG, _ = self.netD(inputdv)\n errG.backward(self.one)\n\n # optmize\n self.optimizerG_Cv.step()\n self.optimizerG_DeCv.step()\n\n ######################################################################\n ###################### End of Update G network #######################\n ######################################################################\n\n\n ######################################################################\n ########################### One Iteration ### ########################\n ######################################################################\n\n '''log result'''\n print('[iteration_i:%d] Loss_D: %f Loss_G: %f Loss_D_real: %f Loss_D_fake %f'\n % (self.iteration_i,\n errD.data[0], errG.data[0], errD_real.data[0], errD_fake.data[0]))\n\n '''log image result and save models'''\n if (time.time()-self.last_save_model_time) > config.gan_worker_com_internal:\n self.save_models()\n self.last_save_model_time = time.time()\n\n if (time.time()-self.last_save_image) > config.gan_save_image_internal:\n self.save_sample(state_prediction_gt[0],'real')\n self.save_sample(state_prediction[0],'fake')\n self.last_save_image = time.time()\n\n self.iteration_i += 1\n ######################################################################\n ######################### End One in Iteration ######################\n ######################################################################\n\n else:\n\n '''dataset not enough'''\n print('Dataset not enough: '+str(int(self.dataset_image.size()[0])))\n\n time.sleep(config.gan_worker_com_internal)\n\n def push_data(self, data):\n \"\"\"\n push data to dataset which is a torch tensor\n \"\"\"\n\n data = torch.FloatTensor(data).cuda()\n data_image = data[:,0:4,:,:,:]\n data_aux = torch.squeeze(data[:,4:5,0:1,0:1,0:1],4)\n\n if self.dataset_image.size()[0] <= 1:\n self.dataset_image = data_image\n self.dataset_aux = data_aux\n else:\n insert_position = np.random.randint(1, \n high=self.dataset_image.size()[0]-2,\n size=None)\n\n self.dataset_image = torch.cat(seq=[self.dataset_image.narrow(0,0,insert_position), data_image, self.dataset_image.narrow(0,insert_position,self.dataset_image.size()[0]-insert_position)],\n dim=0)\n self.dataset_aux = torch.cat(seq=[self.dataset_aux.narrow( 0,0,insert_position), data_aux, self.dataset_aux.narrow( 0,insert_position,self.dataset_aux.size()[0]-insert_position)],\n dim=0)\n\n if self.dataset_image.size()[0] > self.dataset_limit:\n self.dataset_image = self.dataset_image.narrow( dimension=0,\n start=self.dataset_image.size()[0] - self.dataset_limit,\n length=self.dataset_limit)\n self.dataset_aux = self.dataset_aux.narrow(dimension=0,\n start=self.dataset_aux.size()[0] - self.dataset_limit,\n length=self.dataset_limit)\n\n def load_models(self):\n '''do auto checkpoint'''\n try:\n self.netG_Cv.load_state_dict(torch.load(config.modeldir+'netG_Cv.pth'))\n print('Previous checkpoint for netG_Cv founded')\n except Exception, e:\n print('Previous checkpoint for netG_Cv unfounded')\n try:\n self.netG_DeCv.load_state_dict(torch.load(config.modeldir+'netG_DeCv.pth'))\n print('Previous checkpoint for netG_DeCv founded')\n except Exception, e:\n print('Previous checkpoint for netG_DeCv unfounded')\n try:\n self.netD.load_state_dict(torch.load(config.modeldir+'netD.pth'))\n print('Previous checkpoint for netD founded')\n except Exception, e:\n print('Previous checkpoint for netD unfounded')\n\n def save_models(self):\n '''do checkpointing'''\n torch.save(self.netG_Cv.state_dict(), '{0}/{1}/netG_Cv.pth'.format(self.experiment,config.gan_model_name_))\n torch.save(self.netG_DeCv.state_dict(), '{0}/{1}/netG_DeCv.pth'.format(self.experiment,config.gan_model_name_))\n torch.save(self.netD.state_dict(), '{0}/{1}/netD.pth'.format(self.experiment,config.gan_model_name_))\n\n def save_sample(self,sample,name):\n\n '''function need for log image'''\n def sample2image(sample):\n if config.gan_nc is 1:\n c = sample / 3.0\n c = torch.unsqueeze(c,1)\n save = torch.cat([c,c,c],1)\n elif config.gan_nc is 3:\n save = []\n for image_i in range(4):\n save += [torch.unsqueeze(sample.narrow(0,image_i*3,3),0)]\n save = torch.cat(save,0)\n \n # save = save.mul(0.5).add(0.5)\n return save\n\n '''log real result'''\n vutils.save_image(sample2image(sample), ('{0}/'+name+'_{1}.png').format(self.experiment, self.iteration_i))" } ]
13
clberube/SlidersPhotos
https://github.com/clberube/SlidersPhotos
5a65a68d766a03b0f19575c27c5d318d18643c14
80bb787264f575b620f96cfa24fe384eb63cabd8
a8883f590cc426b752db4b5270f69ae77bf85ba2
refs/heads/master
2021-04-12T06:19:33.815661
2017-06-16T13:49:43
2017-06-16T13:49:43
94,502,380
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.7016006112098694, "avg_line_length": 41.01639175415039, "blob_id": "a878676c4a04be7a0653970fe2229f436a80e900", "content_id": "e8015f5e55b0fadcf01a0d813cc5d082b91e2252", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2644, "license_type": "no_license", "max_line_length": 131, "num_lines": 61, "path": "/sliders_photos.py", "repo_name": "clberube/SlidersPhotos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 15 23:36:51 2017\r\n\r\n@author: Charles\r\n\"\"\"\r\n\r\nimport Tkinter as tk\r\nfrom PIL import ImageTk, Image\r\n\r\n# Faire une liste des photos à importer\r\nphotos = [\"./Images/xfiles.jpg\",\r\n \"./Images/Coop_twinpeaks.png\",\r\n \"./Images/2001.jpg\",\r\n \"./Images/perruche.jpg\",\r\n \"./Images/RAFspitfire.jpg\",\r\n ]\r\n\r\ndef update_pic(n):\r\n \"\"\"\r\n Cette fonction met à jour la figure quand le slider bouge\r\n \"\"\"\r\n path = photos[int(n)] # Décide quelle figure afficher selon la valeur du slider\r\n #Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.\r\n image = Image.open(path)\r\n image.thumbnail(maxsize, Image.ANTIALIAS) # Réduit la taille de la figure\r\n pic = ImageTk.PhotoImage(image) # Converti la figure en objet pour tkinter\r\n pic_panel.configure(image=pic) # Met à jour la figure\r\n pic_panel.image = pic # Met à jour la figure\r\n pic_label.configure(text=path) # Met à jour le titre de la figure\r\n print path \r\n\r\n#This creates the main window of an application\r\nwindow = tk.Tk()\r\nwindow.title(\"Application utile\")\r\n#window.geometry(\"1024x768\") # Tu peux décider des dimensions de la fenêtre si tu veux les fixer\r\n#window.configure(background='black') # Tu peux changer la couleur du background avec ça\r\n\r\n# Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.\r\nimage = Image.open(photos[0]) # Utiliser la première photo dans la liste pour initialiser la fenêtre\r\nmaxsize = (800, 600) # Sert à réduire la taille de la figure pour qu'elle rentre dans le panneau\r\nimage.thumbnail(maxsize, Image.ANTIALIAS) # Réduit la taille de la figure\r\npic = ImageTk.PhotoImage(image) # Converti la figure en objet pour tkinter\r\n\r\n# The Label widget is a standard Tkinter widget used to display a text or image on the screen.\r\n# Faire un panneau pour mettre la figure dedans\r\npic_panel = tk.Label(window, width=800, height=600, image = pic) \r\n# Faire un panneau pour écrire le titre de la figure\r\npic_label = tk.Label(window, text=photos[0])\r\n# Faire le slider\r\nslider = tk.Scale(window, from_=0, to=len(photos)-1, length=500, \r\n orient=tk.HORIZONTAL, command=update_pic) # command passe la valeur du slider à la fonctin update_pic par défault\r\n\r\n# The grid geometry manager places widgets in rows or columns.\r\n# Placer les panneau à bonne place\r\npic_panel.grid(row=0, column=0)\r\npic_label.grid(row=1, column=0)\r\nslider.grid(row=2, column=0) # Placer le slider à bonne place\r\n\r\n#Start the GUI\r\nwindow.mainloop()\r\n" }, { "alpha_fraction": 0.8360655903816223, "alphanum_fraction": 0.8360655903816223, "avg_line_length": 29.5, "blob_id": "46261df546bf3f9d3c41fc7e161f1a4ebd30f99b", "content_id": "c405c189bc42976d2a0020df08a44968da1ee883", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 61, "license_type": "no_license", "max_line_length": 44, "num_lines": 2, "path": "/README.md", "repo_name": "clberube/SlidersPhotos", "src_encoding": "UTF-8", "text": "# SlidersPhotos\nApplication avec slider pour voir des photos\n" } ]
2
kyrod24/d6-roll
https://github.com/kyrod24/d6-roll
54b0f505714f10dfa1bb7847fd4419d7814b6d92
d673fc91b3a04f5b1e0624c03a23a12f4ee91084
ec58f747d9a135a835dd41208b919d39c16e8924
refs/heads/master
2021-01-06T01:44:44.537540
2020-02-17T20:30:34
2020-02-17T20:30:34
241,193,423
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7338709831237793, "alphanum_fraction": 0.7701612710952759, "avg_line_length": 81.33333587646484, "blob_id": "e760d11a43b5ea50bd291f75a10f8ed1d2a8cec6", "content_id": "aef0b10eb68b13ecc2603f7cd5b99523efaeed16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 248, "license_type": "no_license", "max_line_length": 149, "num_lines": 3, "path": "/README.md", "repo_name": "kyrod24/d6-roll", "src_encoding": "UTF-8", "text": "# d6-roll\nThis program was homework a homework problem for my coding class. The program is intended to simulate rolling a six-sided die until a \"6\" is rolled. \nRun this simulation 100,000 times and calculate the avg number of rolls to land a \"6\".\n\n" }, { "alpha_fraction": 0.6368754506111145, "alphanum_fraction": 0.6530612111091614, "avg_line_length": 30.577777862548828, "blob_id": "2315b21f6e289965a2673399ebe4da2f95855ae1", "content_id": "a8f840aa563ca7b0b7ceac7dc01853af19a89309", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1421, "license_type": "no_license", "max_line_length": 75, "num_lines": 45, "path": "/diceRoll.py", "repo_name": "kyrod24/d6-roll", "src_encoding": "UTF-8", "text": "import random\n\n#import random for accurate sim testing\n\n# ======Variables======\n # Every_roll is the total rolls for the entire simulation\n # sim_runs serves as a counter in the outside loop\n # dice_roll is the variable assignment of the die being rolled\n # num_of_rolls is how many rolls per sim sim_runs\n # x is how many times the sim is to be run\nEvery_roll = 0\nsim_runs = 0\ndice_roll = 0\nnum_of_rolls = 0\nx = 100000\n\n# ======Simulation======\n # Outside loop runs the simulation desired number of times\n # inside loop is the sim rolling the die until a \"6\" is rolled\n # using the random function and randint() operator\n # num_of_rolls increases by \"1\" until a \"6\" is rolled\n\nwhile sim_runs < x:\n while dice_roll != 6:\n dice_roll = random.randint(1, 6)\n num_of_rolls += 1\n\n# =====Looping variables======\n # Once inside loop condition is met, outside loops alters Variables\n # sim_runs increases by \"1\" for every simulation ran\n # Every_roll increases by the num_of_rolls from the most recent sim\n # dice_roll is reset to \"0\" otherwise inside loop will not simulate\n # num_of_rolls is reset to \"0\" otherwise is compounded\n\n sim_runs += 1\n Every_roll += num_of_rolls\n dice_roll = 0\n num_of_rolls = 0\n\n# ======Calculation======\n # Avg is the average number of rolls for the entire to program\n\nAvg = (Every_roll / x)\n\nprint(Avg)\n" } ]
2
stjordanis/VPNG
https://github.com/stjordanis/VPNG
a037110840fd285c6480c624600584bc6454a681
715fa3e7f70f5da8d5d2a8a4cb14256ee0bb4d92
1e7c10875cafd374f02e5c4dac96acae5377f7aa
refs/heads/master
2020-07-03T06:32:33.862418
2019-05-15T15:41:01
2019-05-15T15:41:01
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7276595830917358, "alphanum_fraction": 0.7914893627166748, "avg_line_length": 57.75, "blob_id": "ac9ba038c10b0cf62a7b729d054effd80c2d5712", "content_id": "97eb2d4097cd51902641842633315bc3e656dcd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 235, "license_type": "permissive", "max_line_length": 107, "num_lines": 4, "path": "/README.md", "repo_name": "stjordanis/VPNG", "src_encoding": "UTF-8", "text": "# The Variational Predictive Natural Gradient\nCode for my ICML 2019 paper [The Variational Predictive Natural Gradient](https://arxiv.org/abs/1903.02984)\n\nThe file vae.py contains the code for the VPNG experiment on VAE (Section 5.2).\n" }, { "alpha_fraction": 0.5672612190246582, "alphanum_fraction": 0.6195259094238281, "avg_line_length": 57.0517692565918, "blob_id": "9cad45c8ed05279a73e6a62a6b72a408462b0852", "content_id": "2f349a6cd115ad8f380150eeaca9722f213b12c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 42610, "license_type": "permissive", "max_line_length": 175, "num_lines": 734, "path": "/src/vae.py", "repo_name": "stjordanis/VPNG", "src_encoding": "UTF-8", "text": "import itertools\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom tensorflow.contrib import slim\nimport time\nfrom scipy.sparse.linalg import eigsh\n\nfrom tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets\n\nfrom tensorflow.python.client import timeline\n\n\nsg = tf.contrib.bayesflow.stochastic_graph\nst = tf.contrib.bayesflow.stochastic_tensor\ndistributions = tf.distributions\n\n\nflags = tf.app.flags\nflags.DEFINE_string('data_dir', '/tmp/dat/', 'Directory for data')\nflags.DEFINE_string('logdir', '/tmp/log/', 'Directory for logs')\n\nflags.DEFINE_integer('latent_dim', 100, 'Latent dimensionality of model')\nflags.DEFINE_integer('batch_size', 600, 'Minibatch size')\nflags.DEFINE_integer('validation_size', 0, 'Size of the validation set')\nflags.DEFINE_integer('train_subset_size', 10000, 'Size of the subset of the training set')\nflags.DEFINE_integer('n_samples', 1, 'Number of samples to save')\nflags.DEFINE_integer('n_samples_fisher', 10, 'Number of samples for fisher info')\nflags.DEFINE_integer('mc_samples', 10, 'Number of samples to compute expectations using Monte Carlo method')\nflags.DEFINE_integer('print_every', 100, 'Print every n iterations')\nflags.DEFINE_integer('hidden_size', 200, 'Hidden size for neural networks')\nflags.DEFINE_integer('n_iterations_r_fisher', 1500, 'number of iterations for r fisher info')\nflags.DEFINE_integer('n_iterations_q_fisher', 2000, 'number of iterations for q fisher info')\nflags.DEFINE_integer('n_iterations_normal', 3000, 'number of iterations for normal SGD')\nflags.DEFINE_integer('strides', 1, 'Pooling strides')\nflags.DEFINE_integer('figure_size', (27 + flags.FLAGS.strides) / flags.FLAGS.strides, 'Number of pixels in a row')\nflags.DEFINE_float('reg_ratio', 1e-1, 'Regularization Coefficient')\nflags.DEFINE_bool('profile', False, 'Do profiling on the training process or not')\nflags.DEFINE_float('learning_rate_r_fisher', 0.01, 'Learning rate for r fisher info')\nflags.DEFINE_float('learning_rate_q_fisher', 0.002, 'Learning rate for q fisher info')\nflags.DEFINE_float('learning_rate_normal', 0.003, 'Learning rate for normal SGD')\nflags.DEFINE_string('output_file_name_r_fisher', None, 'The output file path for fisher info')\nflags.DEFINE_string('output_file_name_q_fisher', None, 'The output file path for fisher info')\nflags.DEFINE_string('output_file_name_normal', None, 'The output file path for normal SGD')\nflags.DEFINE_float('num_eigs_ln_ratio', 4., 'Ratio for number of eigenvectors, with ln computation')\nflags.DEFINE_float('ema_decay', .9, 'Decay of exponential moving average')\nflags.DEFINE_float('Epsilon', 1e-6, 'Value for big Epsilon')\nflags.DEFINE_float('epsilon', 1e-8, 'Value for small epsilon')\nflags.DEFINE_float('init_scale', 0.1, 'Normal std value for variable initialization')\n\nFLAGS = flags.FLAGS\n\ndef my_eigsh_v2(A):\n n = np.shape(A)[0]\n num_eigs = int(FLAGS.num_eigs_ln_ratio * np.log(n))\n return eigsh(A, num_eigs)\n\ndef kronecker_prod_sum_matrix_solve_v3(A_sqrt_i, B_sqrt_i, C, D, V, M1_eigsh=False):\n # Solving the equation (A\\oprod B + C\\oprod D)x = vec(V).\n # Assume that A, B, C, D are positive semi-definite. Also, A, B are invertible.\n # A, B, C, D should be 2D tensors. V should be a tensor of size n * m,\n # where A, C are m * m and B, D are n * n matrices.\n M1 = tf.matmul(A_sqrt_i, tf.matmul(C, A_sqrt_i))\n M2 = tf.matmul(B_sqrt_i, tf.matmul(D, B_sqrt_i))\n if M1_eigsh:\n S1, E1 = tf.py_func(my_eigsh_v2, [(M1 + tf.transpose(M1)) / 2.0], [tf.float32] * 2)\n else:\n S1, E1 = tf.py_func(np.linalg.eigh, [(M1 + tf.transpose(M1)) / 2.0], [tf.float32] * 2)\n S2, E2 = tf.py_func(np.linalg.eigh, [(M2 + tf.transpose(M2)) / 2.0], [tf.float32] * 2)\n K1 = tf.matmul(A_sqrt_i, E1)\n K2 = tf.matmul(B_sqrt_i, E2)\n return tf.matmul(K2, tf.matmul(tf.matmul(tf.transpose(K2), tf.matmul(V, K1)) / (1.0\n - tf.reshape(S2, [-1, 1]) * tf.reshape(S1, [1, -1])), tf.transpose(K1)))\n\ndef weight_variable(shape, name, reuse=False, init_val_dict=None):\n if reuse:\n with tf.variable_scope(\"weights\", reuse=True):\n variable = tf.get_variable(name)\n else:\n if name in init_val_dict:\n init_val = init_val_dict[name]\n else:\n init_val = tf.truncated_normal(shape, stddev=FLAGS.init_scale)\n init_val_dict[name] = init_val\n with tf.variable_scope(\"weights\", reuse=False):\n variable = tf.get_variable(name, initializer=init_val)\n return variable\n\ndef inference_network(x, latent_dim, hidden_size, figure_size, init_val_dict=None):\n \"\"\"Construct an inference network parametrizing a Gaussian.\n Args:\n x: A batch of MNIST digits.\n latent_dim: The latent dimensionality.\n hidden_size: The size of the neural net hidden layers.\n Returns:\n mu: Mean parameters for the variational family Normal\n sigma: Standard deviation parameters for the variational family Normal\n \"\"\"\n h0 = slim.flatten(x)\n h0b = tf.concat([h0, tf.ones([tf.shape(h0)[0], 1])], 1)\n W0b = weight_variable([figure_size * figure_size + 1, hidden_size], \"W0bi\", init_val_dict=init_val_dict)\n h1 = tf.nn.relu(tf.matmul(h0b, W0b))\n h1b = tf.concat([h1, tf.ones([tf.shape(h1)[0], 1])], 1)\n W1b = weight_variable([hidden_size + 1, hidden_size], \"W1bi\", init_val_dict=init_val_dict)\n h2 = tf.nn.relu(tf.matmul(h1b, W1b))\n h2b = tf.concat([h2, tf.ones([tf.shape(h2)[0], 1])], 1)\n W2b = weight_variable([hidden_size + 1, latent_dim * 2], \"W2bi\", init_val_dict=init_val_dict)\n h3 = tf.matmul(h2b, W2b)\n q_mu = h3[:, :latent_dim]\n q_sigma_raw = h3[:, latent_dim:]\n return q_mu, q_sigma_raw, h2b, h2, h1b, h1, h0b, W2b, W1b, W0b\n\n\ndef generative_network(z, hidden_size, latent_dim, figure_size, reuse=False, need_reshape=False, init_val_dict=None):\n \"\"\"Build a generative network parametrizing the likelihood of the data\n Args:\n z: Samples of latent variables\n hidden_size: Size of the hidden state of the neural net\n Returns:\n bernoulli_logits: logits for the Bernoulli likelihood of the data\n \"\"\"\n W0b = weight_variable([latent_dim + 1, hidden_size], \"W0bg\", reuse=reuse, init_val_dict=init_val_dict)\n if need_reshape:\n h0b = tf.reshape(tf.concat([z, tf.ones([tf.shape(z)[0], tf.shape(z)[1], 1])], 2), [-1, latent_dim + 1])\n else:\n h0b = tf.concat([z, tf.ones([tf.shape(z)[0], 1])], 1)\n h1 = tf.nn.relu(tf.matmul(h0b, W0b))\n h1b = tf.concat([h1, tf.ones([tf.shape(h1)[0], 1])], 1)\n W1b = weight_variable([hidden_size + 1, hidden_size], \"W1bg\", reuse=reuse, init_val_dict=init_val_dict)\n h2 = tf.nn.relu(tf.matmul(h1b, W1b))\n h2b = tf.concat([h2, tf.ones([tf.shape(h2)[0], 1])], 1)\n W2b = weight_variable([hidden_size + 1, figure_size * figure_size], \"W2bg\", reuse=reuse, init_val_dict=init_val_dict)\n h3 = tf.matmul(h2b, W2b)\n if need_reshape:\n bernoulli_logits = tf.reshape(h3, [-1, tf.shape(z)[1], figure_size, figure_size, 1])\n else:\n bernoulli_logits = tf.reshape(h3, [-1, figure_size, figure_size, 1])\n return bernoulli_logits, h3, h2b, h2, h1b, h1, h0b, W2b, W1b, W0b\n\ndef train():\n with tf.name_scope('data'):\n x = tf.placeholder(tf.float32, [None, FLAGS.figure_size, FLAGS.figure_size, 1])\n tf.summary.image('data', x)\n\n iter_num = tf.placeholder(tf.int32, [])\n\n para_size = (FLAGS.figure_size * FLAGS.figure_size + 1) * FLAGS.hidden_size \\\n + (FLAGS.hidden_size + 1) * FLAGS.hidden_size \\\n + (FLAGS.hidden_size + 1) * FLAGS.latent_dim * 2 \\\n + (FLAGS.latent_dim + 1) * FLAGS.hidden_size \\\n + (FLAGS.hidden_size + 1) * FLAGS.hidden_size \\\n + (FLAGS.hidden_size + 1) * FLAGS.figure_size * FLAGS.figure_size\n\n print 'Total paramter size: ' + str(para_size)\n\n init_val_dict = {}\n\n with tf.variable_scope('variational_normal'):\n q_mu_, q_sigma_raw_, _, _, _, _, _, _, _, _ = inference_network(x=x,\n latent_dim=FLAGS.latent_dim,\n hidden_size=FLAGS.hidden_size,\n figure_size=FLAGS.figure_size,\n init_val_dict=init_val_dict)\n q_sigma_ = FLAGS.Epsilon + tf.nn.softplus(q_sigma_raw_)\n with st.value_type(st.SampleValue(FLAGS.mc_samples)):\n q_z_ = st.StochasticTensor(distributions.Normal(loc=q_mu_, scale=q_sigma_))\n\n with tf.variable_scope('variational_q_fisher'):\n q_mu__, q_sigma_raw__, h2bi__, h2i__, h1bi__, h1i__, h0bi__, W2bi__, W1bi__, W0bi__ = inference_network(x=x,\n latent_dim=FLAGS.latent_dim,\n hidden_size=FLAGS.hidden_size,\n figure_size=FLAGS.figure_size,\n init_val_dict=init_val_dict)\n q_sigma__ = FLAGS.Epsilon + tf.nn.softplus(q_sigma_raw__)\n with st.value_type(st.SampleValue(FLAGS.mc_samples)):\n q_z__ = st.StochasticTensor(distributions.Normal(loc=q_mu__, scale=q_sigma__))\n with st.value_type(st.SampleValue(FLAGS.n_samples_fisher)):\n q_z3__ = st.StochasticTensor(distributions.Normal(loc=q_mu__, scale=q_sigma__))\n\n with tf.variable_scope('variational_r_fisher'):\n q_mu, q_sigma_raw, h2bi, h2i, h1bi, h1i, h0bi, W2bi, W1bi, W0bi = inference_network(x=x,\n latent_dim=FLAGS.latent_dim,\n hidden_size=FLAGS.hidden_size,\n figure_size=FLAGS.figure_size,\n init_val_dict=init_val_dict)\n q_sigma = FLAGS.Epsilon + tf.nn.softplus(q_sigma_raw)\n with st.value_type(st.SampleValue(FLAGS.mc_samples)):\n q_z = st.StochasticTensor(distributions.Normal(loc=q_mu, scale=q_sigma))\n\n with tf.variable_scope('model_normal'):\n p_x_given_z_logits_ = generative_network(z=q_z_,\n hidden_size=FLAGS.hidden_size,\n latent_dim=FLAGS.latent_dim,\n figure_size=FLAGS.figure_size,\n reuse=False,\n need_reshape=True,\n init_val_dict=init_val_dict)[0]\n p_x_given_z_ = distributions.Bernoulli(logits=p_x_given_z_logits_)\n\n with tf.variable_scope('model_q_fisher'):\n p_x_given_z_logits__, _, _, _, _, _, _, W2bg__, W1bg__, W0bg__ = generative_network(z=q_z__,\n hidden_size=FLAGS.hidden_size,\n latent_dim=FLAGS.latent_dim,\n figure_size=FLAGS.figure_size,\n reuse=False,\n need_reshape=True,\n init_val_dict=init_val_dict)\n p_x_given_z__ = distributions.Bernoulli(logits=p_x_given_z_logits__)\n\n with tf.variable_scope('model_r_fisher'):\n p_x_given_z_logits = generative_network(z=q_z,\n hidden_size=FLAGS.hidden_size,\n latent_dim=FLAGS.latent_dim,\n figure_size=FLAGS.figure_size,\n reuse=False,\n need_reshape=True,\n init_val_dict=init_val_dict)[0]\n p_x_given_z = distributions.Bernoulli(logits=p_x_given_z_logits)\n\n p_z = distributions.Normal(loc=np.zeros(FLAGS.latent_dim, dtype=np.float32),\n scale=np.ones(FLAGS.latent_dim, dtype=np.float32))\n\n kl_ = tf.reduce_sum(distributions.kl_divergence(q_z_.distribution, p_z), 1)\n expected_log_likelihood_ = tf.reduce_sum(p_x_given_z_.log_prob(x),\n [0, 2, 3, 4]) / float(FLAGS.mc_samples)\n elbo_ = tf.reduce_mean(expected_log_likelihood_ - kl_)\n optimizer_ = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate_normal, epsilon=FLAGS.epsilon)\n \n kl__ = tf.reduce_sum(distributions.kl_divergence(q_z__.distribution, p_z), 1)\n expected_log_likelihood__ = tf.reduce_sum(p_x_given_z__.log_prob(x),\n [0, 2, 3, 4]) / float(FLAGS.mc_samples)\n elbo__ = tf.reduce_mean(expected_log_likelihood__ - kl__)\n optimizer__ = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate_q_fisher, epsilon=FLAGS.epsilon)\n \n kl = tf.reduce_sum(distributions.kl_divergence(q_z.distribution, p_z), 1)\n expected_log_likelihood = tf.reduce_sum(p_x_given_z.log_prob(x),\n [0, 2, 3, 4]) / float(FLAGS.mc_samples)\n elbo = tf.reduce_mean(expected_log_likelihood - kl)\n optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate_r_fisher, epsilon=FLAGS.epsilon)\n\n with st.value_type(st.SampleValue()):\n q_z3 = st.StochasticTensor(distributions.Normal(loc=q_mu, scale=q_sigma))\n with tf.variable_scope('model_r_fisher', reuse=True):\n p_x_given_z_logits3, h3g, h2bg, h2g, h1bg, h1g, h0bg, W2bg, W1bg, W0bg = generative_network(z=q_z3,\n hidden_size=FLAGS.hidden_size,\n latent_dim=FLAGS.latent_dim,\n figure_size=FLAGS.figure_size,\n reuse=True)\n train_op_ = optimizer_.minimize(-elbo_)\n \n (grad_W0bi__, grad_W1bi__, grad_W2bi__, grad_W0bg__, grad_W1bg__, grad_W2bg__) = tf.gradients(-elbo__, [W0bi__, W1bi__, W2bi__, W0bg__, W1bg__, W2bg__])\n h0bi_t__ = tf.transpose(h0bi__)\n h1bi_t__ = tf.transpose(h1bi__)\n h2bi_t__ = tf.transpose(h2bi__)\n ema__ = tf.train.ExponentialMovingAverage(decay=FLAGS.ema_decay, num_updates=iter_num)\n with tf.variable_scope('average_q'): \n A00b__ = tf.get_variable('A00b', shape=[FLAGS.figure_size * FLAGS.figure_size + 1, FLAGS.figure_size * FLAGS.figure_size + 1], initializer=tf.zeros_initializer())\n A01b__ = tf.get_variable('A01b', shape=[FLAGS.figure_size * FLAGS.figure_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A11b__ = tf.get_variable('A11b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A12b__ = tf.get_variable('A12b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A22b__ = tf.get_variable('A22b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n G11__ = tf.get_variable('G11', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G12__ = tf.get_variable('G12', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G22__ = tf.get_variable('G22', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G23__ = tf.get_variable('G23', shape=[FLAGS.hidden_size, FLAGS.latent_dim * 2], initializer=tf.zeros_initializer())\n G33_diag__ = tf.get_variable('G33_diag', shape=[FLAGS.latent_dim * 2], initializer=tf.zeros_initializer())\n ema_apply_op__ = ema__.apply([A00b__, A01b__, A11b__, A12b__, A22b__, G11__, G12__, G22__, G23__, G33_diag__])\n A00b_v__ = ema__.average(A00b__)\n A01b_v__ = ema__.average(A01b__)\n A11b_v__ = ema__.average(A11b__)\n A12b_v__ = ema__.average(A12b__)\n A22b_v__ = ema__.average(A22b__)\n G11_v__ = ema__.average(G11__)\n G12_v__ = ema__.average(G12__)\n G22_v__ = ema__.average(G22__)\n G23_v__ = ema__.average(G23__)\n G33_diag_v__ = ema__.average(G33_diag__)\n A00b_new__ = tf.matmul(h0bi_t__, h0bi__) / FLAGS.batch_size\n A01b_new__ = tf.matmul(h0bi_t__, h1bi__) / FLAGS.batch_size\n A11b_new__ = tf.matmul(h1bi_t__, h1bi__) / FLAGS.batch_size\n A12b_new__ = tf.matmul(h1bi_t__, h2bi__) / FLAGS.batch_size\n A22b_new__ = tf.matmul(h2bi_t__, h2bi__) / FLAGS.batch_size\n S_A00b__, E_A00b__ = tf.py_func(my_eigsh_v2, [(A00b_v__ + tf.transpose(A00b_v__)) / 2.0], [tf.float32] * 2)\n S_A00b_i__ = 1.0 / (S_A00b__ + FLAGS.reg_ratio)\n E_A00b_T__ = tf.transpose(E_A00b__)\n A00b_i__ = tf.matmul(E_A00b__ * S_A00b_i__, E_A00b_T__)\n A00b_sqrt_i__ = tf.matmul(E_A00b__ * tf.sqrt(S_A00b_i__), E_A00b_T__)\n S_A11b__, E_A11b__ = tf.py_func(np.linalg.eigh, [(A11b_v__ + tf.transpose(A11b_v__)) / 2.0], [tf.float32] * 2)\n S_A11b_i__ = 1.0 / (S_A11b__ + FLAGS.reg_ratio)\n E_A11b_T__ = tf.transpose(E_A11b__)\n A11b_i__ = tf.matmul(E_A11b__ * S_A11b_i__, E_A11b_T__)\n A11b_sqrt_i__ = tf.matmul(E_A11b__ * tf.sqrt(S_A11b_i__), E_A11b_T__)\n S_A22b__, E_A22b__ = tf.py_func(np.linalg.eigh, [(A22b_v__ + tf.transpose(A22b_v__)) / 2.0], [tf.float32] * 2)\n S_A22b_i__ = 1.0 / (S_A22b__ + FLAGS.reg_ratio)\n E_A22b_T__ = tf.transpose(E_A22b__)\n A22b_i__ = tf.matmul(E_A22b__ * S_A22b_i__, E_A22b_T__)\n A22b_sqrt_i__ = tf.matmul(E_A22b__ * tf.sqrt(S_A22b_i__), E_A22b_T__)\n grad_mat_original3__ = tf.concat([(q_mu__ - q_z3__) / (q_sigma__ ** 2),\\\n (1.0 / q_sigma__ - ((q_mu__ - q_z3__) ** 2) / (q_sigma__ ** 3)) * tf.nn.sigmoid(q_sigma_raw__)], 2)\n grad_mat_original2__ = tf.reshape(tf.matmul(tf.reshape(grad_mat_original3__, [-1, FLAGS.latent_dim * 2]), tf.transpose(W2bi__[:-1])),\n [-1, FLAGS.batch_size, FLAGS.hidden_size]) * tf.cast(h2i__ > 0, tf.float32)\n grad_mat_original1__ = tf.reshape(tf.matmul(tf.reshape(grad_mat_original2__, [-1, FLAGS.hidden_size]), tf.transpose(W1bi__[:-1])),\n [-1, FLAGS.batch_size, FLAGS.hidden_size]) * tf.cast(h1i__ > 0, tf.float32)\n grad_mat_original3_f__ = tf.reshape(grad_mat_original3__, [-1, FLAGS.latent_dim * 2])\n grad_mat_original2_f__ = tf.reshape(grad_mat_original2__, [-1, FLAGS.hidden_size])\n grad_mat_original1_f__ = tf.reshape(grad_mat_original1__, [-1, FLAGS.hidden_size])\n grad_mat_original3_ft__ = tf.transpose(grad_mat_original3_f__)\n grad_mat_original2_ft__ = tf.transpose(grad_mat_original2_f__)\n grad_mat_original1_ft__ = tf.transpose(grad_mat_original1_f__)\n G11_new__ = tf.matmul(grad_mat_original1_ft__, grad_mat_original1_f__) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G12_new__ = tf.matmul(grad_mat_original1_ft__, grad_mat_original2_f__) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G22_new__ = tf.matmul(grad_mat_original2_ft__, grad_mat_original2_f__) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G23_new__ = tf.matmul(grad_mat_original2_ft__, grad_mat_original3_f__) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G33_diag_new__ = tf.reduce_mean(tf.concat([1.0 / (q_sigma__ ** 2), 2.0 * ((tf.nn.sigmoid(q_sigma_raw__) / q_sigma__) ** 2)], 1), 0)\n S_G11__, E_G11__ = tf.py_func(np.linalg.eigh, [(G11_v__ + tf.transpose(G11_v__)) / 2.0], [tf.float32] * 2)\n S_G11_i__ = 1.0 / (S_G11__ + FLAGS.reg_ratio)\n E_G11_T__ = tf.transpose(E_G11__)\n G11_i__ = tf.matmul(E_G11__ * S_G11_i__, E_G11_T__)\n G11_sqrt_i__ = tf.matmul(E_G11__ * tf.sqrt(S_G11_i__), E_G11_T__)\n S_G22__, E_G22__ = tf.py_func(np.linalg.eigh, [(G22_v__ + tf.transpose(G22_v__)) / 2.0], [tf.float32] * 2)\n S_G22_i__ = 1.0 / (S_G22__ + FLAGS.reg_ratio)\n E_G22_T__ = tf.transpose(E_G22__)\n G22_i__ = tf.matmul(E_G22__ * S_G22_i__, E_G22_T__)\n G22_sqrt_i__ = tf.matmul(E_G22__ * tf.sqrt(S_G22_i__), E_G22_T__)\n G33_i_diag__ = 1.0 / (G33_diag_v__ + FLAGS.reg_ratio)\n psi_Ab_01__ = tf.matmul(A01b_v__, A11b_i__)\n psi_Ab_12__ = tf.matmul(A12b_v__, A22b_i__)\n psi_G_12__ = tf.matmul(G12_v__, G22_i__)\n psi_G_23__ = G23_v__ * G33_i_diag__\n V1__ = tf.transpose(grad_W0bi__)\n V2__ = tf.transpose(grad_W1bi__)\n V3__ = tf.transpose(grad_W2bi__)\n V1__ = V1__ - tf.matmul(psi_G_12__, tf.matmul(V2__, tf.transpose(psi_Ab_01__)))\n V2__ = V2__ - tf.matmul(psi_G_23__, tf.matmul(V3__, tf.transpose(psi_Ab_12__)))\n C01__ = tf.matmul(psi_Ab_01__, tf.transpose(A01b_v__))\n C12__ = tf.matmul(psi_Ab_12__, tf.transpose(A12b_v__))\n D12__ = tf.matmul(psi_G_12__, tf.transpose(G12_v__))\n D23__ = tf.matmul(psi_G_23__, tf.transpose(G23_v__))\n V1__ = kronecker_prod_sum_matrix_solve_v3(A00b_sqrt_i__, G11_sqrt_i__, C01__, D12__, V1__, True)\n V2__ = kronecker_prod_sum_matrix_solve_v3(A11b_sqrt_i__, G22_sqrt_i__, C12__, D23__, V2__)\n V3__ = tf.reshape(G33_i_diag__, [-1, 1]) * tf.matmul(V3__, A22b_i__)\n V3__ = V3__ - tf.matmul(tf.transpose(psi_G_23__), tf.matmul(V2__, psi_Ab_12__))\n V2__ = V2__ - tf.matmul(tf.transpose(psi_G_12__), tf.matmul(V1__, psi_Ab_01__))\n ema_assign_op__ = [tf.assign(A00b__, A00b_new__), tf.assign(A01b__, A01b_new__), tf.assign(A11b__, A11b_new__), tf.assign(A12b__, A12b_new__),\\\n tf.assign(A22b__, A22b_new__), tf.assign(G11__, G11_new__), tf.assign(G12__, G12_new__), tf.assign(G22__, G22_new__),\\\n tf.assign(G23__, G23_new__), tf.assign(G33_diag__, G33_diag_new__)]\n train_op__ = optimizer__.apply_gradients([(tf.transpose(V1__), W0bi__), (tf.transpose(V2__), W1bi__), (tf.transpose(V3__), W2bi__),\\\n (grad_W0bg__, W0bg__), (grad_W1bg__, W1bg__), (grad_W2bg__, W2bg__)])\n\n\n (grad_W0bi, grad_W1bi, grad_W2bi, grad_W0bg, grad_W1bg, grad_W2bg) = tf.gradients(-elbo, [W0bi, W1bi, W2bi, W0bg, W1bg, W2bg])\n p_x_given_z_logits3v = tf.reshape(p_x_given_z_logits3, [FLAGS.batch_size, -1])\n p_x_given_z3 = distributions.Bernoulli(logits=p_x_given_z_logits3v)\n p_x_given_z3_samples = p_x_given_z3.sample(FLAGS.n_samples_fisher)\n p_x_given_z3v_1 = tf.nn.sigmoid(p_x_given_z_logits3v)\n p_x_given_z3v_prob = (1.0 - p_x_given_z3v_1) * p_x_given_z3v_1\n h0bi_t = tf.transpose(h0bi)\n h1bi_t = tf.transpose(h1bi)\n h2bi_t = tf.transpose(h2bi)\n h0bg_t = tf.transpose(h0bg)\n h1bg_t = tf.transpose(h1bg)\n h2bg_t = tf.transpose(h2bg)\n ema = tf.train.ExponentialMovingAverage(decay=FLAGS.ema_decay, num_updates=iter_num)\n with tf.variable_scope('average_r'): \n A00b = tf.get_variable('A00b', shape=[FLAGS.figure_size * FLAGS.figure_size + 1, FLAGS.figure_size * FLAGS.figure_size + 1], initializer=tf.zeros_initializer())\n A01b = tf.get_variable('A01b', shape=[FLAGS.figure_size * FLAGS.figure_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A11b = tf.get_variable('A11b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A12b = tf.get_variable('A12b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A22b = tf.get_variable('A22b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A23b = tf.get_variable('A23b', shape=[FLAGS.hidden_size + 1, FLAGS.latent_dim + 1], initializer=tf.zeros_initializer())\n A33b = tf.get_variable('A33b', shape=[FLAGS.latent_dim + 1, FLAGS.latent_dim + 1], initializer=tf.zeros_initializer())\n A34b = tf.get_variable('A34b', shape=[FLAGS.latent_dim + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A44b = tf.get_variable('A44b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A45b = tf.get_variable('A45b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n A55b = tf.get_variable('A55b', shape=[FLAGS.hidden_size + 1, FLAGS.hidden_size + 1], initializer=tf.zeros_initializer())\n G11 = tf.get_variable('G11', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G12 = tf.get_variable('G12', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G22 = tf.get_variable('G22', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G23 = tf.get_variable('G23', shape=[FLAGS.hidden_size, FLAGS.latent_dim * 2], initializer=tf.zeros_initializer())\n G33 = tf.get_variable('G33', shape=[FLAGS.latent_dim * 2, FLAGS.latent_dim * 2], initializer=tf.zeros_initializer())\n G34 = tf.get_variable('G34', shape=[FLAGS.latent_dim * 2, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G44 = tf.get_variable('G44', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G45 = tf.get_variable('G45', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G55 = tf.get_variable('G55', shape=[FLAGS.hidden_size, FLAGS.hidden_size], initializer=tf.zeros_initializer())\n G56 = tf.get_variable('G56', shape=[FLAGS.hidden_size, FLAGS.figure_size * FLAGS.figure_size], initializer=tf.zeros_initializer())\n G66_diag = tf.get_variable('G66_diag', shape=[FLAGS.figure_size * FLAGS.figure_size], initializer=tf.zeros_initializer())\n ema_apply_op = ema.apply([A00b, A01b, A11b, A12b, A22b, A23b, A33b, A34b, A44b, A45b, A55b, G11, G12, G22, G23, G33, G34, G44, G45, G55, G56, G66_diag])\n A00b_v = ema.average(A00b)\n A01b_v = ema.average(A01b)\n A11b_v = ema.average(A11b)\n A12b_v = ema.average(A12b)\n A22b_v = ema.average(A22b)\n A23b_v = ema.average(A23b)\n A33b_v = ema.average(A33b)\n A34b_v = ema.average(A34b)\n A44b_v = ema.average(A44b)\n A45b_v = ema.average(A45b)\n A55b_v = ema.average(A55b)\n G11_v = ema.average(G11)\n G12_v = ema.average(G12)\n G22_v = ema.average(G22)\n G23_v = ema.average(G23)\n G33_v = ema.average(G33)\n G34_v = ema.average(G34)\n G44_v = ema.average(G44)\n G45_v = ema.average(G45)\n G55_v = ema.average(G55)\n G56_v = ema.average(G56)\n G66_diag_v = ema.average(G66_diag)\n\n A00b_new = tf.matmul(h0bi_t, h0bi) / FLAGS.batch_size\n A01b_new = tf.matmul(h0bi_t, h1bi) / FLAGS.batch_size\n A11b_new = tf.matmul(h1bi_t, h1bi) / FLAGS.batch_size\n A12b_new = tf.matmul(h1bi_t, h2bi) / FLAGS.batch_size\n A22b_new = tf.matmul(h2bi_t, h2bi) / FLAGS.batch_size\n A23b_new = tf.matmul(h2bi_t, h0bg) / FLAGS.batch_size\n A33b_new = tf.matmul(h0bg_t, h0bg) / FLAGS.batch_size\n A34b_new = tf.matmul(h0bg_t, h1bg) / FLAGS.batch_size\n A44b_new = tf.matmul(h1bg_t, h1bg) / FLAGS.batch_size\n A45b_new = tf.matmul(h1bg_t, h2bg) / FLAGS.batch_size\n A55b_new = tf.matmul(h2bg_t, h2bg) / FLAGS.batch_size\n\n S_A00b, E_A00b = tf.py_func(my_eigsh_v2, [(A00b_v + tf.transpose(A00b_v)) / 2.0], [tf.float32] * 2)\n S_A00b_i = 1.0 / (S_A00b + FLAGS.reg_ratio)\n E_A00b_T = tf.transpose(E_A00b)\n A00b_i = tf.matmul(E_A00b * S_A00b_i, E_A00b_T)\n A00b_sqrt_i = tf.matmul(E_A00b * tf.sqrt(S_A00b_i), E_A00b_T)\n S_A11b, E_A11b = tf.py_func(np.linalg.eigh, [(A11b_v + tf.transpose(A11b_v)) / 2.0], [tf.float32] * 2)\n S_A11b_i = 1.0 / (S_A11b + FLAGS.reg_ratio)\n E_A11b_T = tf.transpose(E_A11b)\n A11b_i = tf.matmul(E_A11b * S_A11b_i, E_A11b_T)\n A11b_sqrt_i = tf.matmul(E_A11b * tf.sqrt(S_A11b_i), E_A11b_T)\n S_A22b, E_A22b = tf.py_func(np.linalg.eigh, [(A22b_v + tf.transpose(A22b_v)) / 2.0], [tf.float32] * 2)\n S_A22b_i = 1.0 / (S_A22b + FLAGS.reg_ratio)\n E_A22b_T = tf.transpose(E_A22b)\n A22b_i = tf.matmul(E_A22b * S_A22b_i, E_A22b_T)\n A22b_sqrt_i = tf.matmul(E_A22b * tf.sqrt(S_A22b_i), E_A22b_T)\n S_A33b, E_A33b = tf.py_func(np.linalg.eigh, [(A33b_v + tf.transpose(A33b_v)) / 2.0], [tf.float32] * 2)\n S_A33b_i = 1.0 / (S_A33b + FLAGS.reg_ratio)\n E_A33b_T = tf.transpose(E_A33b)\n A33b_i = tf.matmul(E_A33b * S_A33b_i, E_A33b_T)\n A33b_sqrt_i = tf.matmul(E_A33b * tf.sqrt(S_A33b_i), E_A33b_T)\n S_A44b, E_A44b = tf.py_func(np.linalg.eigh, [(A44b_v + tf.transpose(A44b_v)) / 2.0], [tf.float32] * 2)\n S_A44b_i = 1.0 / (S_A44b + FLAGS.reg_ratio)\n E_A44b_T = tf.transpose(E_A44b)\n A44b_i = tf.matmul(E_A44b * S_A44b_i, E_A44b_T)\n A44b_sqrt_i = tf.matmul(E_A44b * tf.sqrt(S_A44b_i), E_A44b_T)\n S_A55b, E_A55b = tf.py_func(np.linalg.eigh, [(A55b_v + tf.transpose(A55b_v)) / 2.0], [tf.float32] * 2)\n S_A55b_i = 1.0 / (S_A55b + FLAGS.reg_ratio)\n E_A55b_T = tf.transpose(E_A55b)\n A55b_i = tf.matmul(E_A55b * S_A55b_i, E_A55b_T)\n A55b_sqrt_i = tf.matmul(E_A55b * tf.sqrt(S_A55b_i), E_A55b_T)\n grad_mat_original6 = tf.cast(p_x_given_z3_samples, tf.float32) - p_x_given_z3v_1\n grad_mat_original5 = tf.reshape(tf.matmul(tf.reshape(grad_mat_original6, [-1, FLAGS.figure_size * FLAGS.figure_size]), tf.transpose(W2bg[:-1])),\n [-1, FLAGS.batch_size, FLAGS.hidden_size]) * tf.cast(h2g > 0, tf.float32)\n grad_mat_original4 = tf.reshape(tf.matmul(tf.reshape(grad_mat_original5, [-1, FLAGS.hidden_size]), tf.transpose(W1bg[:-1])),\n [-1, FLAGS.batch_size, FLAGS.hidden_size]) * tf.cast(h1g > 0, tf.float32)\n grad_mat_original3 = tf.reshape(tf.matmul(tf.reshape(grad_mat_original4, [-1, FLAGS.hidden_size]), tf.transpose(W0bg[:-1])),\n [-1, FLAGS.batch_size, FLAGS.latent_dim])\n grad_mat_original3 = tf.concat([grad_mat_original3, grad_mat_original3 * ((q_z3 - q_mu) / q_sigma) * tf.nn.sigmoid(q_sigma_raw)], 2)\n grad_mat_original2 = tf.reshape(tf.matmul(tf.reshape(grad_mat_original3, [-1, FLAGS.latent_dim * 2]), tf.transpose(W2bi[:-1])),\n [-1, FLAGS.batch_size, FLAGS.hidden_size]) * tf.cast(h2i > 0, tf.float32)\n grad_mat_original1 = tf.reshape(tf.matmul(tf.reshape(grad_mat_original2, [-1, FLAGS.hidden_size]), tf.transpose(W1bi[:-1])),\n [-1, FLAGS.batch_size, FLAGS.hidden_size]) * tf.cast(h1i > 0, tf.float32)\n grad_mat_original6_f = tf.reshape(grad_mat_original6, [-1, FLAGS.figure_size * FLAGS.figure_size])\n grad_mat_original5_f = tf.reshape(grad_mat_original5, [-1, FLAGS.hidden_size])\n grad_mat_original4_f = tf.reshape(grad_mat_original4, [-1, FLAGS.hidden_size])\n grad_mat_original3_f = tf.reshape(grad_mat_original3, [-1, FLAGS.latent_dim * 2])\n grad_mat_original2_f = tf.reshape(grad_mat_original2, [-1, FLAGS.hidden_size])\n grad_mat_original1_f = tf.reshape(grad_mat_original1, [-1, FLAGS.hidden_size])\n grad_mat_original6_ft = tf.transpose(grad_mat_original6_f)\n grad_mat_original5_ft = tf.transpose(grad_mat_original5_f)\n grad_mat_original4_ft = tf.transpose(grad_mat_original4_f)\n grad_mat_original3_ft = tf.transpose(grad_mat_original3_f)\n grad_mat_original2_ft = tf.transpose(grad_mat_original2_f)\n grad_mat_original1_ft = tf.transpose(grad_mat_original1_f)\n G11_new = tf.matmul(grad_mat_original1_ft, grad_mat_original1_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G12_new = tf.matmul(grad_mat_original1_ft, grad_mat_original2_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G22_new = tf.matmul(grad_mat_original2_ft, grad_mat_original2_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G23_new = tf.matmul(grad_mat_original2_ft, grad_mat_original3_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G33_new = tf.matmul(grad_mat_original3_ft, grad_mat_original3_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G34_new = tf.matmul(grad_mat_original3_ft, grad_mat_original4_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G44_new = tf.matmul(grad_mat_original4_ft, grad_mat_original4_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G45_new = tf.matmul(grad_mat_original4_ft, grad_mat_original5_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G55_new = tf.matmul(grad_mat_original5_ft, grad_mat_original5_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G56_new = tf.matmul(grad_mat_original5_ft, grad_mat_original6_f) / (FLAGS.n_samples_fisher * FLAGS.batch_size)\n G66_diag_new = tf.reduce_mean(p_x_given_z3v_prob, 0)\n\n S_G11, E_G11 = tf.py_func(np.linalg.eigh, [(G11_v + tf.transpose(G11_v)) / 2.0], [tf.float32] * 2)\n S_G11_i = 1.0 / (S_G11 + FLAGS.reg_ratio)\n E_G11_T = tf.transpose(E_G11)\n G11_i = tf.matmul(E_G11 * S_G11_i, E_G11_T)\n G11_sqrt_i = tf.matmul(E_G11 * tf.sqrt(S_G11_i), E_G11_T)\n S_G22, E_G22 = tf.py_func(np.linalg.eigh, [(G22_v + tf.transpose(G22_v)) / 2.0], [tf.float32] * 2)\n S_G22_i = 1.0 / (S_G22 + FLAGS.reg_ratio)\n E_G22_T = tf.transpose(E_G22)\n G22_i = tf.matmul(E_G22 * S_G22_i, E_G22_T)\n G22_sqrt_i = tf.matmul(E_G22 * tf.sqrt(S_G22_i), E_G22_T)\n S_G33, E_G33 = tf.py_func(np.linalg.eigh, [(G33_v + tf.transpose(G33_v)) / 2.0], [tf.float32] * 2)\n S_G33_i = 1.0 / (S_G33 + FLAGS.reg_ratio)\n E_G33_T = tf.transpose(E_G33)\n G33_i = tf.matmul(E_G33 * S_G33_i, E_G33_T)\n G33_sqrt_i = tf.matmul(E_G33 * tf.sqrt(S_G33_i), E_G33_T)\n S_G44, E_G44 = tf.py_func(np.linalg.eigh, [(G44_v + tf.transpose(G44_v)) / 2.0], [tf.float32] * 2)\n S_G44_i = 1.0 / (S_G44 + FLAGS.reg_ratio)\n E_G44_T = tf.transpose(E_G44)\n G44_i = tf.matmul(E_G44 * S_G44_i, E_G44_T)\n G44_sqrt_i = tf.matmul(E_G44 * tf.sqrt(S_G44_i), E_G44_T)\n S_G55, E_G55 = tf.py_func(np.linalg.eigh, [(G55_v + tf.transpose(G55_v)) / 2.0], [tf.float32] * 2)\n S_G55_i = 1.0 / (S_G55 + FLAGS.reg_ratio)\n E_G55_T = tf.transpose(E_G55)\n G55_i = tf.matmul(E_G55 * S_G55_i, E_G55_T)\n G55_sqrt_i = tf.matmul(E_G55 * tf.sqrt(S_G55_i), E_G55_T)\n G66_i_diag = 1.0 / (G66_diag_v + FLAGS.reg_ratio)\n psi_Ab_01 = tf.matmul(A01b_v, A11b_i)\n psi_Ab_12 = tf.matmul(A12b_v, A22b_i)\n psi_Ab_23 = tf.matmul(A23b_v, A33b_i)\n psi_Ab_34 = tf.matmul(A34b_v, A44b_i)\n psi_Ab_45 = tf.matmul(A45b_v, A55b_i)\n psi_G_12 = tf.matmul(G12_v, G22_i)\n psi_G_23 = tf.matmul(G23_v, G33_i)\n psi_G_34 = tf.matmul(G34_v, G44_i)\n psi_G_45 = tf.matmul(G45_v, G55_i)\n psi_G_56 = G56_v * G66_i_diag\n V1 = tf.transpose(grad_W0bi)\n V2 = tf.transpose(grad_W1bi)\n V3 = tf.transpose(grad_W2bi)\n V4 = tf.transpose(grad_W0bg)\n V5 = tf.transpose(grad_W1bg)\n V6 = tf.transpose(grad_W2bg)\n V1 = V1 - tf.matmul(psi_G_12, tf.matmul(V2, tf.transpose(psi_Ab_01)))\n V2 = V2 - tf.matmul(psi_G_23, tf.matmul(V3, tf.transpose(psi_Ab_12)))\n V3 = V3 - tf.matmul(psi_G_34, tf.matmul(V4, tf.transpose(psi_Ab_23)))\n V4 = V4 - tf.matmul(psi_G_45, tf.matmul(V5, tf.transpose(psi_Ab_34))) \n V5 = V5 - tf.matmul(psi_G_56, tf.matmul(V6, tf.transpose(psi_Ab_45)))\n C01 = tf.matmul(psi_Ab_01, tf.transpose(A01b_v))\n C12 = tf.matmul(psi_Ab_12, tf.transpose(A12b_v))\n C23 = tf.matmul(psi_Ab_23, tf.transpose(A23b_v))\n C34 = tf.matmul(psi_Ab_34, tf.transpose(A34b_v))\n C45 = tf.matmul(psi_Ab_45, tf.transpose(A45b_v))\n D12 = tf.matmul(psi_G_12, tf.transpose(G12_v))\n D23 = tf.matmul(psi_G_23, tf.transpose(G23_v))\n D34 = tf.matmul(psi_G_34, tf.transpose(G34_v))\n D45 = tf.matmul(psi_G_45, tf.transpose(G45_v))\n D56 = tf.matmul(psi_G_56, tf.transpose(G56_v))\n V1 = kronecker_prod_sum_matrix_solve_v3(A00b_sqrt_i, G11_sqrt_i, C01, D12, V1, True)\n V2 = kronecker_prod_sum_matrix_solve_v3(A11b_sqrt_i, G22_sqrt_i, C12, D23, V2)\n V3 = kronecker_prod_sum_matrix_solve_v3(A22b_sqrt_i, G33_sqrt_i, C23, D34, V3)\n V4 = kronecker_prod_sum_matrix_solve_v3(A33b_sqrt_i, G44_sqrt_i, C34, D45, V4)\n V5 = kronecker_prod_sum_matrix_solve_v3(A44b_sqrt_i, G55_sqrt_i, C45, D56, V5)\n V6 = tf.reshape(G66_i_diag, [-1, 1]) * tf.matmul(V6, A55b_i)\n V6 = V6 - tf.matmul(tf.transpose(psi_G_56), tf.matmul(V5, psi_Ab_45))\n V5 = V5 - tf.matmul(tf.transpose(psi_G_45), tf.matmul(V4, psi_Ab_34))\n V4 = V4 - tf.matmul(tf.transpose(psi_G_34), tf.matmul(V3, psi_Ab_23))\n V3 = V3 - tf.matmul(tf.transpose(psi_G_23), tf.matmul(V2, psi_Ab_12))\n V2 = V2 - tf.matmul(tf.transpose(psi_G_12), tf.matmul(V1, psi_Ab_01))\n ema_assign_op = [tf.assign(A00b, A00b_new), tf.assign(A01b, A01b_new), tf.assign(A11b, A11b_new), tf.assign(A12b, A12b_new),\\\n tf.assign(A22b, A22b_new), tf.assign(A23b, A23b_new), tf.assign(A33b, A33b_new), tf.assign(A34b, A34b_new),\\\n tf.assign(A44b, A44b_new), tf.assign(A45b, A45b_new), tf.assign(A55b, A55b_new),\\\n tf.assign(G11, G11_new), tf.assign(G12, G12_new), tf.assign(G22, G22_new), tf.assign(G23, G23_new), tf.assign(G33, G33_new),\\\n tf.assign(G34, G34_new), tf.assign(G44, G44_new), tf.assign(G45, G45_new), tf.assign(G55, G55_new), tf.assign(G56, G56_new), tf.assign(G66_diag, G66_diag_new)]\n train_op = optimizer.apply_gradients([(tf.transpose(V1), W0bi), (tf.transpose(V2), W1bi), (tf.transpose(V3), W2bi),\\\n (tf.transpose(V4), W0bg), (tf.transpose(V5), W1bg), (tf.transpose(V6), W2bg)])\n \n \n\n\n np_x_original = tf.placeholder(tf.float32, [None, 28, 28, 1])\n np_x_subsample = tf.nn.avg_pool(np_x_original, ksize=[1, FLAGS.strides, FLAGS.strides, 1], strides=[1, FLAGS.strides, FLAGS.strides, 1], padding='SAME')\n\n init_op = tf.global_variables_initializer()\n\n sess = tf.InteractiveSession()\n sess.run(init_op)\n\n mnist = read_data_sets(FLAGS.data_dir, one_hot=True, validation_size=FLAGS.validation_size)\n\n total_time_ = 0.0\n if FLAGS.output_file_name_normal != None:\n ostream_ = file(FLAGS.output_file_name_normal, 'w')\n else:\n ostream_ = None\n\n total_time__ = 0.0\n if FLAGS.output_file_name_q_fisher != None:\n ostream__ = file(FLAGS.output_file_name_q_fisher, 'w')\n else:\n ostream__ = None\n\n total_time = 0.0\n if FLAGS.output_file_name_r_fisher != None:\n ostream = file(FLAGS.output_file_name_r_fisher, 'w')\n else:\n ostream = None\n\n np_x_data = mnist.train.images\n np_x_ori = np_x_data.reshape(-1, 28, 28, 1)\n np_x_subsamples = sess.run(np_x_subsample, {np_x_original: np_x_ori})\n np_x_train = (np_x_subsamples > 0.5).astype(np.float32)\n np.random.shuffle(np_x_train)\n np_x_train_fixed = np_x_train[:FLAGS.train_subset_size]\n\n np_x_data = mnist.test.images\n np_x_ori = np_x_data.reshape(-1, 28, 28, 1)\n np_x_subsamples = sess.run(np_x_subsample, {np_x_original: np_x_ori})\n np_x_test = (np_x_subsamples > 0.5).astype(np.float32)\n\n if FLAGS.profile:\n options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n\n total_time_t_0 = time.time()\n for i in range(max((FLAGS.n_iterations_normal, FLAGS.n_iterations_q_fisher, FLAGS.n_iterations_r_fisher))):\n np_x_data, _ = mnist.train.next_batch(FLAGS.batch_size)\n np_x_ori = np_x_data.reshape(FLAGS.batch_size, 28, 28, 1)\n np_x_subsamples = sess.run(np_x_subsample, {np_x_original: np_x_ori})\n np_x = (np_x_subsamples > 0.5).astype(np.float32)\n \n if i < FLAGS.n_iterations_normal:\n if FLAGS.profile and (i + 1) % FLAGS.print_every == 0:\n time_start = time.time()\n sess.run(train_op_, feed_dict={x: np_x}, options=options, run_metadata=run_metadata)\n total_time_ += time.time() - time_start\n fetched_timeline = timeline.Timeline(run_metadata.step_stats)\n chrome_trace = fetched_timeline.generate_chrome_trace_format()\n with open('timeline_step_normal_%d.json' % (i + 1), 'w') as timeline_ostream:\n timeline_ostream.write(chrome_trace)\n else:\n time_start = time.time()\n sess.run(train_op_, {x: np_x})\n total_time_ += time.time() - time_start\n\n if i < FLAGS.n_iterations_q_fisher:\n if FLAGS.profile and (i + 1) % FLAGS.print_every == 0:\n time_start = time.time()\n sess.run(ema_assign_op__, feed_dict={x: np_x}, options=options, run_metadata=run_metadata)\n sess.run(ema_apply_op__, feed_dict={x: np_x, iter_num: i}, options=options, run_metadata=run_metadata)\n sess.run(train_op__, feed_dict={x: np_x}, options=options, run_metadata=run_metadata)\n total_time__ += time.time() - time_start\n fetched_timeline = timeline.Timeline(run_metadata.step_stats)\n chrome_trace = fetched_timeline.generate_chrome_trace_format()\n with open('timeline_step_fisher_%d.json' % (i + 1), 'w') as timeline_ostream:\n timeline_ostream.write(chrome_trace)\n else:\n time_start = time.time()\n sess.run(ema_assign_op__, feed_dict={x: np_x})\n sess.run(ema_apply_op__, feed_dict={x: np_x, iter_num: i})\n sess.run(train_op__, feed_dict={x: np_x})\n total_time__ += time.time() - time_start\n \n if i < FLAGS.n_iterations_r_fisher:\n if FLAGS.profile and (i + 1) % FLAGS.print_every == 0:\n time_start = time.time()\n sess.run(ema_assign_op, feed_dict={x: np_x}, options=options, run_metadata=run_metadata)\n sess.run(ema_apply_op, feed_dict={x: np_x, iter_num: i}, options=options, run_metadata=run_metadata)\n sess.run(train_op, feed_dict={x: np_x}, options=options, run_metadata=run_metadata)\n total_time += time.time() - time_start\n fetched_timeline = timeline.Timeline(run_metadata.step_stats)\n chrome_trace = fetched_timeline.generate_chrome_trace_format()\n with open('timeline_step_fisher_%d.json' % (i + 1), 'w') as timeline_ostream:\n timeline_ostream.write(chrome_trace)\n else:\n time_start = time.time()\n sess.run(ema_assign_op, feed_dict={x: np_x})\n sess.run(ema_apply_op, feed_dict={x: np_x, iter_num: i})\n sess.run(train_op, feed_dict={x: np_x})\n total_time += time.time() - time_start\n \n if (i + 1) % FLAGS.print_every == 0:\n if i < FLAGS.n_iterations_normal:\n np_batch_elbo_ = sess.run(elbo_, {x: np_x})\n np_train_elbo_ = sess.run(elbo_, {x: np_x_train_fixed})\n np_test_elbo_ = sess.run(elbo_, {x: np_x_test})\n to_print_ = 'Iteration: {0:d} Batch NELBO: {1:.3f} Train NELBO: {3:.3f} Test NELBO: {4:.3f} Time elapsed: {2:.2f}'.format(\n i + 1,\n -np_batch_elbo_,\n total_time_,\n -np_train_elbo_,\n -np_test_elbo_)\n if ostream_ == None:\n print to_print_\n else:\n print >> ostream_, to_print_\n ostream_.flush()\n if i < FLAGS.n_iterations_q_fisher:\n np_batch_elbo__ = sess.run(elbo__, {x: np_x})\n np_train_elbo__ = sess.run(elbo__, {x: np_x_train_fixed})\n np_test_elbo__ = sess.run(elbo__, {x: np_x_test})\n to_print__ = 'Iteration: {0:d} Batch NELBO: {1:.3f} Train NELBO: {3:.3f} Test NELBO: {4:.3f} Time elapsed: {2:.2f}'.format(\n i + 1,\n -np_batch_elbo__,\n total_time__,\n -np_train_elbo__,\n -np_test_elbo__)\n if ostream__ == None:\n print to_print__\n else:\n print >> ostream__, to_print__\n ostream__.flush()\n if i < FLAGS.n_iterations_r_fisher:\n np_batch_elbo = sess.run(elbo, {x: np_x})\n np_train_elbo = sess.run(elbo, {x: np_x_train_fixed})\n np_test_elbo = sess.run(elbo, {x: np_x_test})\n to_print = 'Iteration: {0:d} Batch NELBO: {1:.3f} Train NELBO: {3:.3f} Test NELBO: {4:.3f} Time elapsed: {2:.2f}'.format(\n i + 1,\n -np_batch_elbo,\n total_time,\n -np_train_elbo,\n -np_test_elbo)\n if ostream == None:\n print to_print\n else:\n print >> ostream, to_print\n ostream.flush()\n to_print_t = 'Iteration: {0:d} Total elapsed time: {1:.2f}'.format(i + 1, time.time() - total_time_t_0)\n print to_print_t\n\n if ostream_ != None:\n ostream_.close()\n\n if ostream__ != None:\n ostream__.close()\n\n if ostream != None:\n ostream.close()\n\ndef main(_):\n if tf.gfile.Exists(FLAGS.logdir):\n tf.gfile.DeleteRecursively(FLAGS.logdir)\n tf.gfile.MakeDirs(FLAGS.logdir)\n train()\n\nif __name__ == '__main__':\n tf.app.run()\n" } ]
2
Abit25/ProjectBlog
https://github.com/Abit25/ProjectBlog
c6880a30ee92d0a978f35f1166ab73ec0aeb0fa8
0ac0e25103ae2687aef3ff82dc03a25f2ee773b1
bb248124abd1ef4ea3e729f230d2fe4144c26192
refs/heads/master
2020-06-12T05:43:04.994668
2019-06-28T05:26:50
2019-06-28T05:26:50
194,211,316
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6511111259460449, "alphanum_fraction": 0.6555555462837219, "avg_line_length": 31.926828384399414, "blob_id": "188a601f0ebf7c84895378ffb26eec190eb07afc", "content_id": "1c80197daa59c9961d4d796958f4893bb7592209", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2700, "license_type": "no_license", "max_line_length": 146, "num_lines": 82, "path": "/src/blog/views.py", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,get_object_or_404\nfrom .models import Post,Comment\nfrom .forms import SharePostForm,NewCommentForm,SearchPostForm\nfrom django.urls import reverse\nfrom django.core.mail import send_mail\nfrom taggit.models import Tag\nfrom django.contrib.postgres.search import SearchVector\n\n\n\n# Create your views here.\n\ndef post_list(request,tag_slug=None):\n posts=Post.objects.all()\n tags=Post.tag.all()\n tag=None\n if tag_slug:\n tag=get_object_or_404(Tag,slug=tag_slug)\n posts=Post.objects.filter(tag=tag)\n print(posts)\n\n\n\n return render(request,'blog/list.html',{'posts':posts,'tags':tags,'tag':tag})\n\ndef post_details(request,year,month,day,post):\n post=get_object_or_404(Post,slug=post,publish__year=year,publish__month=month,publish__day=day)\n comments=Comment.objects.filter(post=post)\n similar_posts=post.tag.similar_objects()\n print(similar_posts)\n if request.method=='POST':\n form=NewCommentForm(request.POST)\n if form.is_valid:\n print(form)\n\n new_comment=form.save(commit=False)\n new_comment.post=post\n new_comment.save()\n else:\n form=NewCommentForm()\n return render(request,'blog/detail.html',{'post':post,'form':form,'comments':comments,'similar_posts':similar_posts})\n\ndef post_share(request,post_id):\n sent=False\n post=get_object_or_404(Post,id=post_id)\n if(request.method =='POST'):\n form=SharePostForm(request.POST)\n if(form.is_valid()):\n cd=form.cleaned_data\n post_url=request.build_absolute_uri(post.get_absolute_url())\n subject = \"{} recommends you to read {} by {}\".format(cd['name'],post.title,post.author)\n message=\"{} is an excellent read.Please make sure to go through it once.Here is the link to the post : {}\".format(post.title,post_url)\n sent =True\n send_mail(subject,message,'[email protected]',[cd['to']])\n # print(request.build_absolute_uri(post.get_absolute_url()))\n else:\n form=SharePostForm()\n\n return render(request,\"blog/share.html\",{'form':form,'sent':sent})\n\n\ndef home(request):\n return render(request,'base.html')\n\n\ndef post_search(request):\n\n form=SearchPostForm()\n keyword=None\n posts=[]\n if('keyword' in request.GET):\n\n form=SearchPostForm(request.GET)\n if form.is_valid():\n cd=form.cleaned_data\n keyword=cd['keyword']\n posts=Post.objects.annotate(search=SearchVector('title','body')).filter(search=keyword)\n #\n # else:\n # form=SearchPostForm()\n\n return render(request,'blog/search.html',{'form':form,'posts':posts,'keyword':keyword})\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.782608687877655, "avg_line_length": 22, "blob_id": "6a6623da4879bfc86d0eb4397f4e546d2d37ea8c", "content_id": "7674980849cc895456706acaf8b54efb6027c12a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 46, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/README.md", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "# ProjectBlog\nA Blog created using Django 2.0\n" }, { "alpha_fraction": 0.7099798917770386, "alphanum_fraction": 0.7180173993110657, "avg_line_length": 37.28205108642578, "blob_id": "20e6de4934f02e86a872889640d915463d5b37aa", "content_id": "9f0a147c1cbce551f5c5754f24b8729eb64da288", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1493, "license_type": "no_license", "max_line_length": 114, "num_lines": 39, "path": "/src/blog/models.py", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.urls import reverse\nfrom taggit.managers import TaggableManager\n\n# Create your models here.\nclass Post(models.Model):\n STATUS_CHOICES=[['draft','Draft'],['published','Published']]\n title = models.CharField(max_length=75)\n author = models.ForeignKey(User,on_delete=models.CASCADE)\n body = models.TextField()\n created = models.DateField(auto_now_add=True)\n updated = models.DateField(auto_now=True)\n publish = models.DateField(default=timezone.now)\n slug = models.SlugField(max_length=250,unique_for_date='publish')\n status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='Draft')\n tag=TaggableManager()\n\n def __str__(self):\n return self.title\n\n def get_absolute_url(self):\n return reverse('blog:post_details',args=[self.publish.year,self.publish.month,self.publish.day,self.slug])\n\n # def total_absolute_url(self):\n # url=build_absolute_uri(self.get_absolute_url)\n # return url\n\nclass Comment(models.Model):\n created=models.DateTimeField(auto_now_add=True)\n post=models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE)\n body=models.CharField(max_length=120)\n email=models.EmailField()\n active=models.BooleanField(default=True)\n name=models.CharField(max_length=80)\n\n def __str__(self):\n return \"Comment by {} at {}\".format(self.name,self.created)\n" }, { "alpha_fraction": 0.7390761375427246, "alphanum_fraction": 0.7415730357170105, "avg_line_length": 28.518518447875977, "blob_id": "3b76a9b2829b09c4cf05e6b1c658c16884c6b2c5", "content_id": "bd47cf6762df4cdb4da6e574b8323140f5cca7e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 801, "license_type": "no_license", "max_line_length": 122, "num_lines": 27, "path": "/src/blog/templatetags/blog_tags.py", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "from django import template\nfrom ..models import Post\nfrom django.db.models import Count\nfrom django.utils.safestring import mark_safe\nimport markdown\n\nregister=template.Library()\n\[email protected]_tag\ndef total_posts():\n return Post.objects.all().count()\n\[email protected]_tag('latest_posts.html')\ndef latest_posts(count=3):\n posts=Post.objects.all().order_by('-publish')[:count]\n return {'latest_posts':posts}\n\[email protected]_tag\ndef most_commented(count=5):\n most_commented_posts=Post.objects.all().annotate(total_comments=Count('comments')).order_by('-total_comments')[:count]\n print(\"Here are the required posts\")\n print(most_commented_posts)\n return most_commented_posts\n\[email protected]()\ndef markdown_convert(text):\n return mark_safe(markdown.markdown(text)) \n" }, { "alpha_fraction": 0.682539701461792, "alphanum_fraction": 0.6904761791229248, "avg_line_length": 20, "blob_id": "7d541fde3cc747480ea00bc2848d033b14cbf2c5", "content_id": "e6c44ea5805e4ae90621158d9fd2d94185e06d3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 43, "num_lines": 12, "path": "/src/blog/sitemaps.py", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "from django.contrib.sitemaps import Sitemap\nfrom .models import Post\n\nclass PostSiteMap(Sitemap):\n changefreq='weekly'\n priority=0.9\n\n def items(self):\n return Post.objects.all()\n\n def lastmod(self,item):\n return item.updated\n" }, { "alpha_fraction": 0.5382631421089172, "alphanum_fraction": 0.5520206093788147, "avg_line_length": 26.690475463867188, "blob_id": "1c0969e4afe3a2e9a85b3282f1fc50cfc96bfa1a", "content_id": "5293b4bab219efd990b2164a60b4969216b87fd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1163, "license_type": "no_license", "max_line_length": 149, "num_lines": 42, "path": "/src/templates/base.html", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "{% load static %}\n{% load blog_tags %}\n<!DOCTYPE html>\n<html lang=\"en\" dir=\"ltr\">\n <head>\n <meta charset=\"utf-8\">\n <title>Custom Template Tags</title>\n <link rel=\"stylesheet\" href=\"{% static \"/blog/css/main.css\" %}\">\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n </head>\n <body>\n <div class='sidebar'>\n <h3 style=\"text-align:center\"><u>Latest Posts</u></h3>\n <br>\n {% latest_posts %}\n <hr>\n <h4 style=\"text-align:center\"><u>Most commented posts</u></h4>\n <br>\n {% most_commented as most_commented_posts %}\n {% for post in most_commented_posts %}\n <ul>\n\n <li><p><a href=\"{{post.get_absolute_url}}\">{{post.title}}</a></p></li>\n\n </ul>\n {% endfor %}\n </div>\n <div class=\"content\">\n\n\n <h2 style=\"text-align:center\">Welcome to my blog</h2>\n <hr>\n <h3>It has {% total_posts %} posts</h3>\n <hr>\n <h2>Here are some links for you :</h2>\n <br>\n <h3><a href=\"{% url 'blog:post_list' %}\">List of all Posts</a></h3>\n </div>\n\n\n </body>\n</html>\n" }, { "alpha_fraction": 0.522162139415741, "alphanum_fraction": 0.5416216254234314, "avg_line_length": 23.972972869873047, "blob_id": "7170ad26ed057423e03cdb1da1e8a85eaf4d8da0", "content_id": "c21a0b77538671729ff0705ea9a27f491d169b06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 925, "license_type": "no_license", "max_line_length": 149, "num_lines": 37, "path": "/src/blog/templates/blog/list.html", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "\n<!DOCTYPE html>\n<html lang=\"en\" dir=\"ltr\">\n <head>\n <meta charset=\"utf-8\">\n <title>List-Page</title>\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n </head>\n <body>\n\n<div class=\"ever\" style=\"margin-left:12px\">\n\n {% if tag %}\n <h2 style=\"margin-top:15px\">List of all posts with {{tag.name}} tag</h2>\n <hr>\n {% for post in posts %}\n <a href=\"{{post.get_absolute_url}}\" style=\"font-size:25px\">-> {{post.title}}</a>\n <br>\n {% endfor %}\n\n {% else %}\n <h2>List of all Posts</h2>\n <hr>\n {% for post in posts %}\n <a href=\"{{post.get_absolute_url}}\"><h3>{{post.title}}</h3></a>\n <p>{{post.body}}</p>\n\n {% endfor %}\n <hr>\n <h2>List of all tags</h2>\n {% for tag in tags %}\n <a href=\"\">{{tag.name}}</a>\n {% endfor %}\n {% endif %}\n </div>\n\n </body>\n</html>\n" }, { "alpha_fraction": 0.7050997614860535, "alphanum_fraction": 0.7139689326286316, "avg_line_length": 25.058822631835938, "blob_id": "d960db274a8571b5ce12b939b49d6d7b35bfcb03", "content_id": "a190274bea90b2ec8dbe927abde84d78e8137824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 66, "num_lines": 17, "path": "/src/blog/forms.py", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Comment\n\n\nclass SharePostForm(forms.Form):\n name=forms.CharField(max_length=50)\n fro=forms.EmailField()\n to=forms.EmailField()\n comments=forms.CharField(widget=forms.Textarea,required=False)\n\nclass NewCommentForm(forms.ModelForm):\n class Meta:\n model=Comment\n fields=['name','email','body']\n\nclass SearchPostForm(forms.Form):\n keyword=forms.CharField(max_length=50) \n" }, { "alpha_fraction": 0.6584022045135498, "alphanum_fraction": 0.6611570119857788, "avg_line_length": 20.352941513061523, "blob_id": "b214d12ee2e592c3806498dc183501af3983eb86", "content_id": "73b30d4de6a4f1cbfd857c508b5ed471230acd7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "no_license", "max_line_length": 49, "num_lines": 17, "path": "/src/blog/feeds.py", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "from django.contrib.syndication.views import Feed\nfrom .models import Post\n\nclass LatestPostFeed(Feed):\n title='My Blog'\n link='/blog/'\n description='New Posts of my Blog'\n\n def items(self):\n return Post.objects.all()[:5]\n\n def item_title(self,item):\n return item.title\n\n\n def item_description(self,item):\n return item.body\n" }, { "alpha_fraction": 0.6945898532867432, "alphanum_fraction": 0.6945898532867432, "avg_line_length": 37.20000076293945, "blob_id": "8fe9febe4555077b98de6eaa8136d786a40a7dbb", "content_id": "4fe6c871f214b64c8c5db0fdc653666f78fcb1b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 91, "num_lines": 15, "path": "/src/blog/urls.py", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path\nfrom .views import post_list,post_details,post_share,post_search\nfrom .feeds import LatestPostFeed\n\napp_name='blog'\n\nurlpatterns = [\n path('list/',post_list,name='post_list'),\n path('<int:year>/<int:month>/<int:day>/<slug:post>/',post_details,name='post_details'),\n path('share/<int:post_id>',post_share,name='post_share'),\n path('list/<slug:tag_slug>',post_list,name='post_list_with_tags'),\n path('feed/',LatestPostFeed(),name='post_feed'),\n path('search/',post_search,name='post_search'),\n]\n" }, { "alpha_fraction": 0.7046154141426086, "alphanum_fraction": 0.7046154141426086, "avg_line_length": 28.545454025268555, "blob_id": "938811f62f3d9fd5f614edc057efc43dd6e88e04", "content_id": "7dcf45372ded068831603b316f4b8bb8da0278f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 53, "num_lines": 11, "path": "/src/blog/admin.py", "repo_name": "Abit25/ProjectBlog", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Post,Comment\n\n# Register your models here.\[email protected](Post)\nclass PostAdminChange(admin.ModelAdmin):\n list_display = ['title','slug','author','status']\n prepopulated_fields = { 'slug' : ('title',) }\n raw_id_fields = ('author',)\n\nadmin.site.register(Comment)\n" } ]
11
NirupamReddy2/Hawkeye
https://github.com/NirupamReddy2/Hawkeye
9d140b642a9c30d146e1848445ae4659ee7efcbb
f003d5527d4a97c4026764f65f060fa73a2f3d79
3588c4100aecca4256a76339bd2c9929a7e619b9
refs/heads/master
2023-07-22T09:15:17.697301
2021-08-23T17:43:27
2021-08-23T17:43:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7903226017951965, "alphanum_fraction": 0.7903226017951965, "avg_line_length": 30, "blob_id": "79e1c176a459bbf9e35fdb224b7ac59752b3864a", "content_id": "112f4548c08717223ac20e942793a930d0769bc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "no_license", "max_line_length": 51, "num_lines": 2, "path": "/README.md", "repo_name": "NirupamReddy2/Hawkeye", "src_encoding": "UTF-8", "text": "# Hawkeye\nEnigma's own moderation bot for it's Discord server\n" }, { "alpha_fraction": 0.6364119052886963, "alphanum_fraction": 0.6411889791488647, "avg_line_length": 31.491378784179688, "blob_id": "87209ce12186b85a06791aa316ef8605dfba1857", "content_id": "db142c55fc7953d6ff1aed931906f465e11750b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3780, "license_type": "no_license", "max_line_length": 206, "num_lines": 116, "path": "/cogs/admin/admin_misc.py", "repo_name": "NirupamReddy2/Hawkeye", "src_encoding": "UTF-8", "text": "from asyncio.tasks import ensure_future\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import has_permissions\nimport json\nimport uuid\nimport datetime\nimport asyncio\nimport os\nimport os.path\nfrom os import path\n\nclass admin_misc(commands.Cog):\n\t\n\tdef __init__(self,bot):\n\t\tself.bot = bot\n\t\tself.tasks = []\n\n\[email protected]()\n\tasync def on_ready(self):\n\t\tawait self.bot.wait_until_ready()\n\t\ttry:\n\t\t\twith open(\"res/events.json\", \"rt\") as file:\n\t\t\t\tdata = json.load(file)\n\t\t\t\tfor guild in self.bot.guilds:\n\t\t\t\t\tfor channel in guild.text_channels:\n\t\t\t\t\t\tif channel.name == \"announcements\":\n\t\t\t\t\t\t\tfor i in data:\n\t\t\t\t\t\t\t\tawait self.schedule_events(channel, i, data[i][\"date\"], data[i][\"time\"], data[i][\"topic\"])\n\t\t\t\t\t\t\tbreak\n\t\texcept:\n\t\t\tdata = {}\n\t\t\tfor guild in self.bot.guilds:\n\t\t\t\tfor channel in guild.text_channels:\n\t\t\t\t\tif channel.name == \"announcements\":\n\t\t\t\t\t\tfor i in data:\n\t\t\t\t\t\t\tawait self.schedule_events(channel, i, data[i][\"date\"], data[i][\"time\"], data[i][\"topic\"])\n\t\t\t\t\t\tbreak\n\n\[email protected](help = \"Sends message anonymously | sudo echo YourMessage \")\n\t@has_permissions(administrator=True)\n\tasync def echo(self, ctx, *message):\n\t\tawait ctx.message.delete()\n\t\tmessage = list(message)\n\t\tif message[0] == \"--raw\" or message[0] == \"-r\":\n\t\t\tawait ctx.channel.send(\" \".join(message[1:]))\n\t\t\treturn\n\t\tmessage = \" \".join(message)\n\t\tembed = discord.Embed(description=f\"{message}\",colour=discord.Colour.orange())\n\t\tawait ctx.channel.send(embed = embed)\n\n\[email protected]\n\tasync def echo_error(self,ctx, error):\n\t\tif isinstance(error, commands.MissingPermissions):\n\t\t\tpass\n\t\telse:\n\t\t\tembed = discord.Embed(description=f\"○ No message entered.\\n○ Try typing something after echo -> `sudo echo YourMessage`.\\n○ Type `sudo help` to know more about each command.\",colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\n\[email protected](help = \"SUPERPINGS PEOPLE! VERY RISKY\")\n\t@has_permissions(administrator=True)\n\tasync def superping(self,ctx,*arg):\n\t\tif str(arg) == '()' or (len(arg) == 1 and arg[0].isdigit()) :\n\t\t\tembed = discord.Embed(description=f\"○ A parameter is missing.\\n○ Try mentioning the user -> `sudo superping @User`.\\n○ Type `sudo help` to know about each command.\",colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\treturn\n\t\textra_Users = arg\n\t\tindex = 0\n\t\tfor i in range(len(extra_Users)):\n\t\t\tid = extra_Users[i]\n\t\t\tindex = i\n\t\t\tflag = False\n\t\t\tuser_ID = id.replace(\"<@\", \"\")\n\t\t\tuser_ID = user_ID.replace(\">\", \"\")\n\t\t\ttry:\n\t\t\t\tif arg[len(arg)-1].isdigit():\n\t\t\t\t\tnum = int(arg[len(arg) - 1])\n\t\t\t\t\tflag = True\n\t\t\t\tmember = await ctx.guild.fetch_member(int(str(user_ID.replace(\"!\", \"\"))))\n\t\t\t\tuser_id = id\n\t\t\t\tnum = 2\n\t\t\t\tif len(arg) == 1:\n\t\t\t\t\tfor i in range(2):\n\t\t\t\t\t\tawait ctx.channel.send('%s' % user_id)\n\t\t\t\telse:\n\t\t\t\t\tif arg[len(arg)-1].isdigit():\n\t\t\t\t\t\tnum = int(arg[len(arg) - 1])\n\t\t\t\t\t\tflag = True\n\t\t\t\t\tif int(num) != 69:\n\t\t\t\t\t\tif int(num) > 9:\n\t\t\t\t\t\t\tnum = 9\n\t\t\t\t\t\tif str(num).isdigit():\n\t\t\t\t\t\t\tfor i in range(int(num)):\n\t\t\t\t\t\t\t\tawait ctx.channel.send('%s' % user_id)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tawait ctx.channel.send(\"Give me a number.\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tawait ctx.channel.send('%s' % user_id)\n\t\t\t\t\t\temb = discord.Embed(title = \"NICE!\")\n\t\t\t\t\t\tawait ctx.channel.send(embed = emb)\n\t\t\texcept Exception as e:\n\t\t\t\ttry:\n\t\t\t\t\tuser = await self.bot.fetch_user(user_ID)\n\t\t\t\t\tembed = discord.Embed(description=f\"{user} is not in the server.\", colour=discord.Colour.red())\n\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\texcept:\n\t\t\t\t\t\n\t\t\t\t\tif id.isdigit() and index == len(arg) - 1:\n\t\t\t\t\t\tpass\n\t\t\t\t\telse:\n\t\t\t\t\t\tembed = discord.Embed(description=f\"Invalid user input.\", colour=discord.Colour.red())\n\t\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\n\ndef setup(bot):\n\tbot.add_cog(admin_misc(bot))" }, { "alpha_fraction": 0.6741347908973694, "alphanum_fraction": 0.6765413880348206, "avg_line_length": 41.055419921875, "blob_id": "77f3f37904bbb02b48081527bc8b07a23e9406df", "content_id": "119286ea525e694e0f039d5a1ab7e78c507aa470", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17496, "license_type": "no_license", "max_line_length": 258, "num_lines": 415, "path": "/cogs/admin/mod.py", "repo_name": "NirupamReddy2/Hawkeye", "src_encoding": "UTF-8", "text": "import discord\nfrom discord.ext import commands\nfrom discord.member import Member\nfrom discord.ext.commands import has_permissions\nimport json\n\n\nclass Mod(commands.Cog):\n\t\n\tdef __init__(self,bot):\n\t\tself.bot = bot\n\n\[email protected](help = \"Kicks the specified user | sudo kick @user\", aliases = (\"apt_remove\",\"remove\"))\n\t@has_permissions(administrator=True)\n\tasync def kick(self,ctx, *, reason = None):\n\t\tif reason == None:\n\t\t\tembed = discord.Embed(description=f\"○ A parameter is missing.\\n○ Try mentioning the user -> `sudo kick @User`.\\n○ Type `sudo help` to know about each command.\",colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\treturn\n\t\tasync def kick_user(self,ctx,member:discord.Member, reason):\n\t\t\tif member == self.bot.user:\n\t\t\t\tawait ctx.channel.send(\"Nice Try!\")\n\t\t\telse:\n\t\t\t\tif member == None or member == ctx.message.author:\n\t\t\t\t\tawait ctx.channel.send(\"You cannot kick yourself.\")\n\t\t\t\t\treturn\n\t\t\t\t# administrator exception\n\t\t\t\tif member.guild_permissions.administrator:\n\t\t\t\t\tif not member.bot:\n\t\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=\"Administrator\", description=f\"{member} is an administrator and is not allowed to be kicked.\")\n\t\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\t\telse:\n\t\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=\"Administrator\", description=f\"{member} is an admin bot and is not allowed to be kicked.\")\n\t\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\telse:\n\t\t\t\t\tif reason == None:\n\t\t\t\t\t\treason = \"-\"\n\t\t\t\t\t\tmessage = f\"You have been kicked from {ctx.guild.name}\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tmessage = f\"You have been kicked from {ctx.guild.name} {reason}\"\n\t\t\t\t\tawait member.send(message)\n\t\t\t\t\tawait member.kick(reason = reason)\n\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=f\"{member} was kicked\", description=f\"Reason: {reason}\")\n\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\n\t\t# iterating through the USER_ID list\n\t\textra_Users = reason.split(\">\")\n\t\textra_Users = [x.replace(\"<@!\", \"\") for x in extra_Users]\n\t\tif \">\" not in extra_Users[len(extra_Users)-1]:\n\t\t\treason = str(extra_Users[len(extra_Users)-1])\n\t\t\textra_Users.pop(len(extra_Users)-1)\n\t\telse:\n\t\t\treason = \"-\"\n\t\textra_Users = [x.replace(\">\",\"\") for x in extra_Users]\n\t\tif extra_Users[0] == \"\":\n\t\t\textra_Users.pop(0)\n\t\tfor user_ID in extra_Users:\n\t\t\ttry:\n\t\t\t\tmember = await ctx.guild.fetch_member(int(str(user_ID)))\n\t\t\t\tawait kick_user(self,ctx,member,reason)\n\t\t\texcept Exception as e:\n\t\t\t\tuser = await self.bot.fetch_user(user_ID)\n\t\t\t\tembed = discord.Embed(description=f\"{user} is not in the server.\",colour=discord.Colour.red())\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\n\n\[email protected](help = \"Bans the specified user | sudo ban @User\")\n\t@has_permissions(administrator=True)\n\tasync def ban(self,ctx, *, reason = None):\n\t\tif reason == None:\n\t\t\tembed = discord.Embed(description=f\"○ A parameter is missing.\\n○ Try mentioning the user -> `sudo ban @user`.\\n○ Type `sudo help` to know about each command.\",colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\treturn\n\t\tasync def ban_user(self, ctx, member: discord.Member, reason):\n\t\t\tif member == self.bot.user:\n\t\t\t\tawait ctx.channel.send(\"Nice Try!\")\n\t\t\telse:\n\t\t\t\tif member == None or member == ctx.message.author:\n\t\t\t\t\tawait ctx.channel.send(\"You cannot ban yourself.\")\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tif member.guild_permissions.administrator:\n\t\t\t\t\t\tif not member.bot:\n\t\t\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=\"Administrator\", description=f\"{member} is an administrator and is not allowed to be banned.\")\n\t\t\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=\"Administrator\", description=f\"{member} is an admin bot and is not allowed to be banned.\")\n\t\t\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif member == None or member == ctx.message.author:\n\t\t\t\t\t\t\tawait ctx.channel.send(\"You cannot ban yourself.\")\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tif reason == None:\n\t\t\t\t\t\t\treason = \"-\"\n\t\t\t\t\t\t\tmessage = f\"You have been banned from {ctx.guild.name}.\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmessage = f\"You have been banned from {ctx.guild.name} {reason}.\"\n\t\t\t\t\t\tif not member.bot:\n\t\t\t\t\t\t\tawait member.send(message)\n\t\t\t\t\t\tif reason == None:\n\t\t\t\t\t\t\treason = \"-\"\n\t\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=f\"{member} was banned\", description=f\"Reason: {reason}\")\n\t\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\t\t\tawait member.ban(reason = reason)\n\t\t# iterating through the USER_ID list\n\t\t\n\t\textra_Users = reason.split(\">\")\n\t\textra_Users = [x.replace(\"<@!\", \"\") for x in extra_Users]\n\t\tif \">\" not in extra_Users[len(extra_Users)-1]:\n\t\t\treason = str(extra_Users[len(extra_Users)-1])\n\t\t\textra_Users.pop(len(extra_Users)-1)\n\t\telse:\n\t\t\treason = \"-\"\n\t\textra_Users = [x.replace(\">\",\"\") for x in extra_Users]\n\t\tif extra_Users[0] == \"\":\n\t\t\textra_Users.pop(0)\n\t\tfor user_ID in extra_Users:\n\t\t\ttry:\n\t\t\t\tmember = await ctx.guild.fetch_member(int(str(user_ID)))\n\t\t\t\tawait ban_user(self,ctx,member,reason)\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\t\t\t\tuser = await self.bot.fetch_user(user_ID)\n\t\t\t\tembed = discord.Embed(description=f\"{user} is not in the server.\",colour=discord.Colour.red())\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\n\[email protected](help = f\"Unbans the specified user | sudo unban Hawkeye#1180\")\n\t@has_permissions(administrator = True)\n\tasync def unban(self,ctx, *, arg = None):\n\t\tif arg == None:\n\t\t\tembed = discord.Embed(description=f\"○ A parameter is missing.\\n○ Try mentioning the user -> `sudo unban Hawkeye#1180`.\\n○ Type `sudo help` to know about each command.\",colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\treturn\n\t\tusers = arg.split()\n\t\tfor member in users:\n\t\t\tbanned_users = await ctx.guild.bans()\n\t\t\tmember_name, member_discriminator = member.split('#')\n\t\t\twas_banned = False\n\t\t\tfor ban_entry in banned_users:\n\t\t\t\tuser = ban_entry.user\n\t\t\t\tif (user.name, user.discriminator) == (member_name, member_discriminator):\n\t\t\t\t\twas_banned = True\n\t\t\t\t\tawait ctx.guild.unban(user)\n\t\t\t\t\tembed = discord.Embed(description=f\" Unbanned-{user.mention}\",colour=discord.Colour.red())\n\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t# if the user had not been banned\n\t\t\tif not was_banned:\n\t\t\t\tembed = discord.Embed(description=f\"{member} had not been banned in the first place.\",colour=discord.Colour.red())\n\t\t\t\tawait ctx.channel.send(embed=embed)\n\t\n\[email protected](pass_context = True,help=\"Mutes the specified user | sudo mute @user\")\n\t@has_permissions(administrator = True)\n\tasync def mute(self,ctx, *, reason=None):\n\t\tif reason == None:\n\t\t\tembed = discord.Embed(description=f\"○ A parameter is missing.\\n○ Try mentioning the user -> `sudo mute @User`.\\n○ Type `sudo help` to know about each command.\",colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\treturn\n\n\t\tasync def mute_user(self, ctx, member: Member, reason):\n\t\t\tif member == self.bot.user:\n\t\t\t\tawait ctx.channel.send(\"Nice Try!\")\n\t\t\telse:\n\t\t\t\tif member == None or member == ctx.message.author:\n\t\t\t\t\tawait ctx.channel.send(\"You cannot mute yourself.\")\n\t\t\t\t\treturn\n\t\t\t\tif member.guild_permissions.administrator:\n\t\t\t\t\tif not member.bot:\n\t\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=\"Administrator\", description=f\"{member} is an administrator and is not allowed to be muted.\")\n\t\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\t\telse:\n\t\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=\"Administrator\", description=f\"{member} is an admin bot and is not allowed to be muted.\")\n\t\t\t\t\t\tawait ctx.channel.send(embed = embed)\n\n\t\t\t\telse:\n\t\t\t\t\tguild = ctx.guild\n\t\t\t\t\tmutedRole = discord.utils.get(guild.roles, name=\"Muted\")\n\t\t\t\t\tif not mutedRole:\n\t\t\t\t\t\tmutedRole = await guild.create_role(name=\"Muted\")\n\n\t\t\t\t\t\tfor channel in guild.channels:\n\t\t\t\t\t\t\tawait channel.set_permissions(mutedRole, speak=True, send_messages=False, read_message_history=True, read_messages=True)\n\t\t\t\t\tif mutedRole in member.roles:\n\t\t\t\t\t\tembed = discord.Embed(description=f\"{member} has already been muted.\",colour=discord.Colour.red())\n\t\t\t\t\t\tawait ctx.channel.send(embed=embed)\n\t\t\t\t\telse:\n\t\t\t\t\t\tawait member.add_roles(mutedRole, reason=reason)\n\t\t\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=f\"{member} was muted\", description=f\"Reason: {reason}\")\n\t\t\t\t\t\tawait ctx.channel.send(embed=embed)\n\n\t\t# iterating through the USER_ID list \n\t\t\n\t\textra_Users = reason.split(\">\")\n\t\textra_Users = [x.replace(\"<@!\", \"\") for x in extra_Users]\n\t\tif \">\" not in extra_Users[len(extra_Users)-1]:\n\t\t\treason = str(extra_Users[len(extra_Users)-1])\n\n\t\t\textra_Users.pop(len(extra_Users)-1)\n\t\telse:\n\t\t\treason = \"-\"\n\t\textra_Users = [x.replace(\">\",\"\") for x in extra_Users]\n\t\tif extra_Users[0] == \"\":\n\t\t\textra_Users.pop(0)\n\t\tfor user_ID in extra_Users:\n\t\t\ttry:\n\t\t\t\tmember = await ctx.guild.fetch_member(int(str(user_ID)))\n\t\t\t\tawait mute_user(self,ctx,member,reason)\n\t\t\texcept Exception:\n\t\t\t\tuser = await self.bot.fetch_user(user_ID)\n\t\t\t\tembed = discord.Embed(description=f\"{user} is not in the server.\",colour=discord.Colour.red())\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\n\[email protected](help=\"Unmutes the specified user | sudo unmute @user\")\n\t@has_permissions(manage_messages=True)\n\tasync def unmute(self,ctx,*, reason = None):\n\t\tif reason == None:\n\t\t\tembed = discord.Embed(description=f\"○ A parameter is missing.\\n○ Try mentioning the user -> `sudo unmute @User`.\\n○ Type `sudo help` to know about each command.\",colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\treturn\n\t\tasync def unmute_user(self,ctx,member: discord.Member, reason):\n\t\t\tmutedRole = discord.utils.get(ctx.guild.roles, name=\"Muted\")\n\t\t\tif mutedRole in member.roles:\n\t\t\t\tawait member.remove_roles(mutedRole)\n\t\t\t\tif not member.bot:\n\t\t\t\t\tawait member.send(f\" You have unmuted from: - {ctx.guild.name}.\")\n\t\t\t\tembed = discord.Embed(description=f\"Unmuted-{member.mention}\",colour=discord.Colour.red())\n\t\t\t\tawait ctx.channel.send(embed=embed)\n\t\t\telse:\n\t\t\t\tembed = discord.Embed(description=f\"{member} had not been muted in the first place.\",colour=discord.Colour.red())\n\t\t\t\tawait ctx.channel.send(embed=embed)\n\n\t\t# iterating through the USER_ID list\n\n\t\textra_Users = reason.split(\">\")\n\t\textra_Users = [x.replace(\"<@!\", \"\") for x in extra_Users]\n\t\tif \">\" not in extra_Users[len(extra_Users)-1]:\n\t\t\treason = str(extra_Users[len(extra_Users)-1])\n\t\t\textra_Users.pop(len(extra_Users)-1)\n\t\telse:\n\t\t\treason = \"-\"\n\t\textra_Users = [x.replace(\">\",\"\") for x in extra_Users]\n\t\tif extra_Users[0] == \"\":\n\t\t\textra_Users.pop(0)\n\t\tfor user_ID in extra_Users:\n\t\t\ttry:\n\t\t\t\tmember = await ctx.guild.fetch_member(int(str(user_ID)))\n\t\t\t\tawait unmute_user(self,ctx,member,reason)\n\t\t\texcept Exception:\n\t\t\t\tuser = await self.bot.fetch_user(user_ID)\n\t\t\t\tembed = discord.Embed(description=f\"{user} is not in the server.\",colour=discord.Colour.red())\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\n\n\[email protected](help = f\"Warns the specified user | sudo warn @user\")\n\t@has_permissions(administrator = True)\n\tasync def warn(self,ctx, member:discord.Member, *, reason = \"\"):\n\t\tif member.guild_permissions.administrator:\n\t\t\tif not member.bot:\n\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=\"Administrator\", description=f\"{member} is an administrator and hence cannot be warned.\")\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tembed=discord.Embed(color=discord.Colour.red(), title=\"Administrator\", description=f\"{member} is an admin bot and hence cannot be warned.\")\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\treturn\n\t\ttry:\n\t\t\twith open(\"res/data.json\", \"rt\") as file:\n\t\t\t\tdata = json.load(file)\n\t\texcept:\n\t\t\tdata = {}\n\t\tid = str(member.id)\n\t\tif not \"warn\" in data:\n\t\t\tdata[\"warn\"] = {}\n\t\tif id in data[\"warn\"].keys():\n\t\t\tdata[\"warn\"][id][\"warn_count\"] += 1\n\t\t\tdata[\"warn\"][id][\"reason\"].append(reason)\n\t\telse:\n\t\t\tdata[\"warn\"][id] = {\n\t\t\t\t\"warn_count\": 1,\n\t\t\t\t\"reason\": [reason]\n\t\t\t}\n\t\twith open(\"res/data.json\", \"wt\") as file:\n\t\t\tif reason == \"\":\n\t\t\t\tembed = discord.Embed(description = f\"{member.mention} has been warned.\", colour = discord.Colour.dark_red())\n\t\t\telse:\n\t\t\t\tembed = discord.Embed(description = f\"{member.mention} has been warned.\\nReason : {reason}\", colour = discord.Colour.dark_red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\tif data[\"warn\"][id][\"warn_count\"] >= 4:\n\t\t\t\tmessage = f\"You have been banned from {ctx.guild.name} {reason}.\"\n\t\t\t\tif not member.bot:\n\t\t\t\t\tawait member.send(message)\n\t\t\t\tawait member.ban(reason = reason)\n\t\t\t\tembed = discord.Embed(description = f\"{member} has been banned from the server {reason}.\", colour=discord.Colour.dark_red())\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\tdel data[\"warn\"][id]\n\t\t\tjson.dump(data, file)\n\n\[email protected]\n\tasync def warn_error(self, ctx, error):\n\t\tawait ctx.channel.send(error)\n\n\[email protected](help = f\"Revokes one warning of the specified user | sudo revoke_warn @user\")\n\t@has_permissions(administrator = True)\n\tasync def remove_warn(self,ctx, member:discord.Member):\n\t\ttry:\n\t\t\twith open(\"res/data.json\", \"rt\") as file:\n\t\t\t\tdata = json.load(file)\n\t\texcept:\n\t\t\tdata = {}\n\t\tid = str(member.id)\n\t\tif not \"warn\" in data:\n\t\t\tdata[\"warn\"] = {}\n\t\tif id in data[\"warn\"]:\n\t\t\tif data[\"warn\"][id][\"warn_count\"] <= 0:\n\t\t\t\tembed = discord.Embed(description = \"Member has not been warned at least once.\", colour=discord.Colour.light_gray())\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\treturn\n\t\t\tdata[\"warn\"][id][\"warn_count\"] -= 1\n\t\t\tdata[\"warn\"][id][\"reason\"].pop()\n\t\t\t#await ctx.channel.send(f\"Cleared a warning for {member.name}.\")\n\t\t\tembed = discord.Embed(description = f\"Cleared a warning for {member}.\", colour=discord.Colour.light_gray())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\telse:\n\t\t\tembed = discord.Embed(description = \"Member has not been warned at least once.\", colour=discord.Colour.light_gray())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\treturn\n\t\twith open(\"res/data.json\", \"wt\") as file:\n\t\t\tjson.dump(data, file)\n\n\n\[email protected](help = f\"Shows the warning of the specified user | sudo show_warning @user\")\n\t@has_permissions(administrator = True)\n\tasync def show_warning(self,ctx, member:discord.Member):\n\t\ttry:\n\t\t\twith open(\"res/data.json\", \"rt\") as file:\n\t\t\t\tdata = json.load(file)\n\t\texcept:\n\t\t\tdata = {}\n\t\tid = str(member.id)\n\t\tif not \"warn\" in data:\n\t\t\tdata[\"warn\"] = {}\n\t\tif id in data[\"warn\"] and data[\"warn\"][id][\"warn_count\"]>0:\n\t\t\tif data[\"warn\"][id][\"warn_count\"] > 1:\n\t\t\t\tembed = discord.Embed(title = f\"{member.name} has been warned {data['warn'][id]['warn_count']} times.\")\n\t\t\telse:\n\t\t\t\tembed = discord.Embed(title = f\"{member.name} has been warned {data['warn'][id]['warn_count']} time.\")\n\t\t\tcount = 1\n\t\t\ttext = \"\"\n\t\t\tfor reason in data[\"warn\"][id][\"reason\"]:\n\t\t\t\ttext += f\"\\n{count}) {reason}\"\n\t\t\t\t#await ctx.channel.send(reason)\n\t\t\t\tcount+=1\n\t\t\tembed.add_field(name = \"Reasons :\", value = text, inline = False)\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\telse:\n\t\t\tembed = discord.Embed(description = \"Member has not been warned at least once.\", colour=discord.Colour.light_gray())\n\t\t\tawait ctx.channel.send(embed = embed)\n\n\t@show_warning.error\n\tasync def show_warning_error(self, ctx, error):\n\t\tawait ctx.channel.send(error)\n\n\n\[email protected](pass_context = True ,help = \"Purge messages | sudo purge AnInteger\", aliases = (\"clear\", \"cls\"))\n\t@has_permissions(administrator=True)\n\tasync def purge(self, ctx, limit: int):\n\t\tawait ctx.channel.purge(limit = limit+1)\n\n\[email protected]\n\tasync def purge_error(self,ctx, error):\n\t\tif isinstance(error, commands.MissingPermissions):\n\t\t\treturn\n\t\tcount = 0\n\t\ttry:\n\t\t\tid = int(ctx.message.reference.message_id)\n\t\t\tmsg = await ctx.fetch_message(id)\n\t\t\tif id is not None and msg is not None:\n\t\t\t\tasync for m in ctx.channel.history(limit = None, oldest_first = False):\n\t\t\t\t\tif m.id == id:\n\t\t\t\t\t\tcount+=1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tcount+=1\n\t\t\t\tawait ctx.channel.purge(limit = count)\n\t\t\telse:\n\t\t\t\tembed = discord.Embed(description=\"Hey! something went wrong\",colour=discord.Colour.red())\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\texcept:\n\t\t\tembed = discord.Embed(description=f\"○ A parameter is missing.\\n○ Try mentioning one integer -> `sudo purge Number`.\\n○ Or else reply to a message and type -> `sudo purge` .\\n○ Type `sudo help` to know more about each command.\",colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\n\[email protected](pass_context = True ,help = \"Purge messages of @user | sudo purge_user @mention AnInteger\", aliases = (\"clear_user\", \"cls_user\"))\n\t@has_permissions(administrator=True)\n\tasync def purge_user(self, ctx, member:discord.Member, limit: int):\n\t\tdef is_member(m):\n\t\t\treturn m.author == member\n\n\t\tawait ctx.channel.purge(limit = limit+1, check = is_member)\n\t\tawait ctx.channel.send(member.mention+\", Your messages have been deleted\")\n\n\t@purge_user.error\n\tasync def purge_user_error(self,ctx, error):\n\t\tif isinstance(error, commands.MissingPermissions):\n\t\t\treturn\n\n\t\tembed = discord.Embed(description=f\"○ Missing Parameter(s).\\n○ Try mentioning user and provide an integer -> `sudo purge_user @user Number`.\\n○ Type `sudo help` to know more about each command.\",colour=discord.Colour.red())\n\t\tawait ctx.channel.send(embed = embed)\n\n\[email protected](help = \"Logs the bot out.\", aliases = (\"stopbot\", \"quit\", \"disconnect\"))\n\t@has_permissions(administrator = True)\n\tasync def logout(self,ctx):\n\t\tawait ctx.channel.send(f\"Hey {ctx.author.mention}, I am now logging out :wave:, Good Bye.\")\n\t\tawait self.bot.logout()\n\ndef setup(bot):\n\tbot.add_cog(Mod(bot))" }, { "alpha_fraction": 0.6699453592300415, "alphanum_fraction": 0.6699453592300415, "avg_line_length": 21.899999618530273, "blob_id": "e509580fd229d764a8dea02a3945a69c5b9c3e5a", "content_id": "e1a378ad20d22bb23dce058d8a18cd822654356a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 919, "license_type": "no_license", "max_line_length": 133, "num_lines": 40, "path": "/Hawkeye.py", "repo_name": "NirupamReddy2/Hawkeye", "src_encoding": "UTF-8", "text": "import discord\nfrom discord.ext import commands\nfrom pathlib import Path\n\n\nintents = discord.Intents.default()\nintents.members = True\n\nBOT_PREFIX = ('sudo ')\nbot = commands.Bot(command_prefix=BOT_PREFIX, intents = intents)\n\[email protected]\nasync def on_ready():\n\tprint (f\"\\nLogged in as:\\t {str(bot.user)}\")\n\tprint (\"-----------------\")\n\[email protected]\nasync def on_command_error(ctx, error):\n\tif isinstance(error, commands.CommandNotFound):\n\t\tembed = discord.Embed(description=f\"○ Invalid command\\n○ Type `sudo help` to know about each command.\",colour=discord.Colour.red())\n\t\tawait ctx.send(embed = embed)\n\t\treturn\n\nif __name__ == '__main__':\n\tres = Path(\"res\")\n\n\twith open(res / \"TOKEN\", 'r') as TokenObj:\n\t\tTOKEN = TokenObj.read()\n\n\tcogs = [\n\t\t'cogs.admin.mod',\n\t\t'cogs.admin.admin_misc',\n\t\t'cogs.admin.announcement'\n\t]\n\n\tfor cog in cogs:\n\t\tprint (\"Loading Cog:\\t\", cog, \"...\")\n\t\tbot.load_extension(cog)\n\n\tbot.run(TOKEN)" }, { "alpha_fraction": 0.6620128154754639, "alphanum_fraction": 0.665357768535614, "avg_line_length": 35.97311782836914, "blob_id": "b647c57985b719e0cc807456d7d5d24cdcb7712b", "content_id": "55da14ae0a549547adad2a04e4f10217673ae616", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6882, "license_type": "no_license", "max_line_length": 234, "num_lines": 186, "path": "/cogs/admin/announcement.py", "repo_name": "NirupamReddy2/Hawkeye", "src_encoding": "UTF-8", "text": "from asyncio.tasks import ensure_future\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import has_permissions\nimport json\nimport uuid\nimport datetime\nimport asyncio\nimport os\n\n\n\nclass announcement(commands.Cog):\n\t\n\tdef __init__(self,bot):\n\t\tself.bot = bot\n\t\tself.tasks = []\n\n\[email protected]()\n\tasync def on_ready(self):\n\t\tawait self.bot.wait_until_ready()\n\t\ttry:\n\t\t\twith open(\"res/data.json\", \"rt\") as file:\n\t\t\t\tdata = json.load(file)\n\t\t\t\tfor guild in self.bot.guilds:\n\t\t\t\t\tfor channel in guild.text_channels:\n\t\t\t\t\t\tif channel.name == \"announcements\":\n\t\t\t\t\t\t\tfor i in data:\n\t\t\t\t\t\t\t\tawait self.schedule_events(channel, i, data['events'][i][\"date\"], data['events'][i][\"time\"], data['events'][i][\"topic\"])\n\t\t\t\t\t\t\tbreak\n\t\texcept:\n\t\t\tdata = {}\n\t\t\tfor guild in self.bot.guilds:\n\t\t\t\tfor channel in guild.text_channels:\n\t\t\t\t\tif channel.name == \"announcements\":\n\t\t\t\t\t\tfor i in data:\n\t\t\t\t\t\t\tawait self.schedule_events(channel, i, data['events'][i][\"date\"], data['events'][i][\"time\"], data['events'][i][\"topic\"])\n\t\t\t\t\t\tbreak\n\n\[email protected](pass_context = True ,help = \" Adds Event | sudo add_event dd-mm-yyyy hh:mm Topic\", aliases = [\"add-event\", \"event\", \"announce\"])\n\t@has_permissions(administrator=True)\n\tasync def add_event(self, ctx, date: str, time: str,*, topic):\n\t\tif len(topic) > 2000:\n\t\t\tawait ctx.channel.send(\"I don't have Nitro unfortunately. Please type a message of length less than 2000 characters.\")\n\t\tdd , mm, yyyy = date.split('-')\n\t\thh , minute = time.split(':')\n\t\ttry:\n\t\t\twith open(\"res/data.json\", \"rt\") as file:\n\t\t\t\tdata = json.load(file)\n\t\texcept:\n\t\t\tdata = {}\n\n\t\ttarget_time = datetime.datetime.strptime(date, \"%d-%m-%Y\").replace(hour = int(hh), minute = int(minute))\n\t\tcurrent_time = datetime.datetime.utcnow() + datetime.timedelta(hours = 5 , minutes = 30)\n\n\t\tif(target_time < current_time):\n\t\t\tawait ctx.channel.send(\"Time has already passed, I don't have a time machine unfortunately.\")\n\t\t\treturn\n\n\t\tid = uuid.uuid1().hex\n\t\tif not 'events' in data:\n\t\t\tdata[\"events\"] = {}\n\t\tdata[\"events\"][id] = {\n\t\t\t\"author\" : str(ctx.message.author),\n\t\t\t\"topic\" : topic,\n\t\t\t\"date\" : date,\n\t\t\t\"time\" : time\n\t\t}\n\t\twith open(\"res/data.json\", \"wt\") as file:\n\t\t\tjson.dump(data, file)\n\t\t\tembed = discord.Embed(description = \"An Event has been added.\", colour=discord.Colour.light_gray())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\n\n\t\tawait self.schedule_events(discord.utils.get(ctx.guild.text_channels, name = \"announcements\"), id, date, time, topic)\n\n\t@add_event.error\n\tasync def add_event_error(self, ctx, error):\n\t\tembed = discord.Embed(description=f\"○ Invalid Parameter(s).\\n○ Try sticking to this format -> `sudo add_event dd-mm-yyyy hh:mm`.\\n○ Type `sudo help` to know more about each command.\",colour=discord.Colour.red())\n\t\tawait ctx.channel.send(error, embed = embed)\n\n\tasync def schedule_events(self, channel, id, date, time, topic):\n\t\thh , minute = time.split(':')\n\t\thh = int(hh)\n\t\tminute = int(minute)\n\t\ttarget_time = datetime.datetime.strptime(date, \"%d-%m-%Y\").replace(hour = hh, minute = minute)\n\t\tcurrent_time = datetime.datetime.utcnow() + datetime.timedelta(hours = 5 , minutes = 30)\n\t\tdelta = (target_time - current_time).total_seconds()\n\t\tasyncio.create_task(self.send_message_scheduler(channel, id, delta, topic))\n\n\n\tasync def send_message_scheduler(self, channel, id, delta , topic):\n\t\tif channel:\n\t\t\ttask = asyncio.create_task(asyncio.sleep(delta))\n\t\t\tself.tasks.append([task, id])\n\t\t\ttry:\n\t\t\t\tawait task\n\t\t\t\tself.tasks.remove([task, id])\n\t\t\t\tif delta >= 0:\n\t\t\t\t\tawait channel.send(topic)\n\t\t\t\ttry:\n\t\t\t\t\twith open(\"res/data.json\", \"rt\") as file:\n\t\t\t\t\t\tdata = json.load(file)\n\t\t\t\t\t\tdel data[\"events\"][id]\n\t\t\t\texcept:\n\t\t\t\t\tdata = {}\n\n\t\t\t\twith open(\"res/data.json\", \"wt\") as file:\n\t\t\t\t\tjson.dump(data, file)\n\t\t\texcept asyncio.CancelledError:\n\t\t\t\tpass\n\t\telse:\n\t\t\tprint(\"announcements channel not found!\")\n\t\t\t\n\n\[email protected](pass_context = True ,help = \" Shows All Announcements Scheduled | sudo show_events\", aliases = [\"events-ls\", \"events\", \"announcements\"])\n\t@has_permissions(administrator=True)\n\tasync def show_events(self, ctx):\n\t\t\n\t\twith open(\"res/data.json\", \"rt\") as file:\n\t\t\tdata = json.load(file)\n\t\t\tif not \"events\" in data:\n\t\t\t\tdata[\"events\"] = {}\n\t\t\tif len(data[\"events\"]) == 0:\n\t\t\t\tembed = discord.Embed(description=\"There are no announcements scheduled, `sudo add_event` to add events.\", colour=discord.Colour.light_gray())\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tif len(data[\"events\"]) > 1:\n\t\t\t\t\tembed = discord.Embed(title = f\"There are {len(data['events'])} announcements scheduled.\", colour = discord.Colour.gold())\n\t\t\t\telse:\n\t\t\t\t\tembed = discord.Embed(title = f\"There is {len(data['events'])} announcement scheduled.\", colour = discord.Colour.gold())\n\t\t\t\tcount = 1\n\t\t\t\tfor i in data[\"events\"]:\n\t\t\t\t\tembed.add_field(name = f\"{count}) {str(data['events'][i]['date'])}\", value = f\"Event : {data['events'][i]['topic']}\\nAuthor : {data['events'][i]['author']}\\nTime : {str(data['events'][i]['time'])}\\nID : {str(i)}\", inline = False)\n\t\t\t\t\tcount+=1\n\t\t\t\tawait ctx.channel.send(embed = embed)\n\n\t@show_events.error\n\tasync def show_events_error(self, ctx, error):\n\t\tembed = discord.Embed(description=\"There are no announcements scheduled, sudo add_event to add an event.\", colour=discord.Colour.light_gray())\n\t\tawait ctx.channel.send(embed = embed)\n\n\n\n\[email protected](pass_context = True ,help = \" Adds Event | sudo delete_event id\")\n\t@has_permissions(administrator=True)\n\tasync def delete_event(self, ctx, id:str):\n\t\tid = id.strip()\n\t\ttry:\n\t\t\twith open(\"res/data.json\", \"rt\") as file:\n\t\t\t\tdata = json.load(file)\n\t\texcept:\n\t\t\tdata = {}\n\t\ttry:\n\t\t\tfor task in self.tasks:\n\t\t\t\tif task[1] == id:\n\t\t\t\t\tself.tasks.remove(task)\n\t\t\t\t\ttask[0].cancel()\n\n\t\t\tdel data[\"events\"][id]\n\t\t\twith open(\"res/data.json\", \"wt\") as file:\n\t\t\t\tjson.dump(data, file)\n\t\t\tembed=discord.Embed(color=discord.Colour.dark_red(), title=\"Event Deleted\", description = f\"The announcement with ID: {id} has been removed.\")\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\texcept:\n\t\t\tembed = discord.Embed(description=f\"Invalid Event ID! Try Again.\", colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\n\[email protected](pass_context = True ,help = \" Delete All Events | sudo delete_all_events\")\n\t@has_permissions(administrator=True)\n\tasync def delete_all_events(self, ctx):\n\t\ttry:\n\t\t\tos.remove(\"res/data.json\")\n\t\t\tfor task in self.tasks:\n\t\t\t\tself.tasks.remove(task)\n\t\t\t\ttask[0].cancel()\n\t\t\tawait ctx.channel.send()\n\t\t\tembed = discord.Embed(description = f\"All the events have been cleared.\", colour=discord.Colour.dark_red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\t\texcept: \n\t\t\tembed = discord.Embed(description = \"Something went wrong while removing events.\", colour=discord.Colour.red())\n\t\t\tawait ctx.channel.send(embed = embed)\n\ndef setup(bot):\n\tbot.add_cog(announcement(bot))" } ]
5
anirudh9784/Face-Mask-detection
https://github.com/anirudh9784/Face-Mask-detection
3ebea7db76319b8d4e1010c37d87d13dc5c1ea79
1930349a392fc759f5e69cebcac86e063915d510
c15dd36126d1dfefe079b17f7a93a92caff13cf1
refs/heads/master
2022-06-12T04:05:15.479570
2020-05-07T17:05:43
2020-05-07T17:05:43
261,551,062
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5419847369194031, "alphanum_fraction": 0.5742539763450623, "avg_line_length": 32.511627197265625, "blob_id": "c03c9c4639cd1774ac496ea3cd957adb1f6768db", "content_id": "33807611c45e6d8bf950de67ea9f8bebf97e7388", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5764, "license_type": "no_license", "max_line_length": 123, "num_lines": 172, "path": "/trainm.py", "repo_name": "anirudh9784/Face-Mask-detection", "src_encoding": "UTF-8", "text": "import cv2 \nimport matplotlib.pyplot as plt \t\nimport torchvision.models as models\nimport torch.nn as nn\nimport torch\nimport os\nimport numpy as np\nfrom torchvision import datasets\nfrom torchvision import transforms\nimport torch.optim as optim\nfrom glob import glob\nfrom PIL import Image\ntrain_data_path = 'Data/'\nval_data_path = 'Data/'\n\ntrain_transform = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.RandomRotation(10),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])\n ])\n\nval_transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])\n ])\n\ntrain_data = datasets.ImageFolder(train_data_path, transform=train_transform)\nval_data = datasets.ImageFolder(val_data_path, transform=val_transform)\n\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=True)\nval_loader = torch.utils.data.DataLoader(val_data, batch_size=32)\n\n\nloaders_transfer = {'train': train_loader, 'valid': val_loader}\nsoftmax = nn.Softmax(dim=1)\n#model_transfer = models.resnet50(pretrained=True)\n#model_transfer.fc = nn.Linear(2048, 2)\nuse_cuda = torch.cuda.is_available()\n#if use_cuda:\n# model_transfer = model_transfer.cuda()\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nsoftmax = nn.Softmax(dim=1)\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n ## Define layers of a CNN\n self.conv1 = nn.Conv2d(3, 32, kernel_size=7, padding = 3)\n self.conv1_bn = nn.BatchNorm2d(32)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=5, padding = 2)\n self.conv2_bn = nn.BatchNorm2d(64)\n self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding = 1)\n self.conv3_bn = nn.BatchNorm2d(128)\n self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n \n self.fc1 = nn.Linear(28*28*128, 256)\n self.fc2 = nn.Linear(256 ,128)\n self.output = nn.Linear(128,2)\n \n self.drop = nn.Dropout(0.3)\n \n def forward(self, x):\n ## Define forward behavior\n x = self.pool(F.relu(self.conv1_bn(self.conv1(x))))\n x = self.pool(F.relu(self.conv2_bn(self.conv2(x))))\n x = self.pool(F.relu(self.conv3_bn(self.conv3(x))))\n x = x.view(-1, 14*14*256)\n x = F.relu(self.fc1(self.drop(x)))\n x = F.relu(self.fc2(self.drop(x)))\n x =(self.output(self.drop(x)))\n \n return x\n\nmodel_transfer = Net()\n\nif use_cuda:\n model_transfer.cuda()\n\ncriterion_transfer = nn.CrossEntropyLoss()\noptimizer_transfer = optim.Adam(model_transfer.parameters(),lr=0.003)\n\nlosses = {'train':[], 'validation':[]}\nlosses = {'train':[], 'validation':[]}\n\nprint('training to be strted' , use_cuda)\ndef train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):\n valid_loss_min = np.Inf \n \n for epoch in range(1, n_epochs+1):\n train_loss = 0.0\n valid_loss = 0.0\n \n \n print('training started..............')\n model.train()\n for batch_idx, (data, target) in enumerate(loaders['train']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n optimizer.zero_grad()\n \n pred = model(data)\n loss = criterion(pred, target)\n \n train_loss += ((1 / (batch_idx + 1)) * (loss.data - train_loss))\n \n loss.backward()\n optimizer.step()\n model.eval()\n \n for batch_idx, (data, target) in enumerate(loaders['valid']):\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n val_pred = model(data)\n val_loss = criterion(val_pred, target)\n \n valid_loss += ((1 / (batch_idx + 1)) * (val_loss.data - valid_loss))\n print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n epoch, \n train_loss,\n valid_loss\n ))\n \n \n if (valid_loss < valid_loss_min):\n print(\"Saving model. Validation loss:... {} --> {}\".format(valid_loss_min, valid_loss.item()))\n valid_loss_min = valid_loss\n torch.save(model.state_dict(), save_path)\n print()\n \n losses['train'].append(train_loss)\n losses['validation'].append(valid_loss)\n \n \n return model\n\ndef test(loaders, model, criterion, use_cuda):\n\n test_loss = 0.\n correct = 0.\n total = 0.\n \n model.eval()\n for batch_idx, (data, target) in enumerate(loaders['train']):\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n output = model(data)\n loss = criterion(output, target)\n test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))\n pred = output.data.max(1, keepdim=True)[1]\n correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())\n total += data.size(0)\n \n print('Test Loss: {:.6f}\\n'.format(test_loss))\n\n print('\\nTest Accuracy: %2d%% (%2d/%2d)' % (\n 100. * correct / total, correct, total))\n\n\n\n\n\n#model_transfer = train(20, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model.pt')\n#model_transfer.load_state_dict(torch.load('model.pt'))\n#test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)\n" }, { "alpha_fraction": 0.7816954255104065, "alphanum_fraction": 0.7861965298652649, "avg_line_length": 69.10526275634766, "blob_id": "49610d1cee3de71b4a89b077d3ca5a534b0d6cc3", "content_id": "66c1eaf0eae6dc7dba16a42baa112501286357a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 287, "num_lines": 19, "path": "/README.md", "repo_name": "anirudh9784/Face-Mask-detection", "src_encoding": "UTF-8", "text": "# Face-Mask-detection\nOpen run.py to start Detection<br>\ntrainm.py is CNN model trained from Scratch<br>\nThis Repo is Demonstration of how we can use some Computer Vision with Deep Learning to make a Face Mask Detection which can be used on Entry Gates of Companies or Public Transport or Simply used to Provide some services only to those wearing mask like Ticket Vending Machine, ATM, Etc. \n\n# Face Detection\nUsing OpenCv Haar Cascade Face detection to detect a face then the image is cropped and fed into the Classifier\n\n# Model\nSince we are classifying video feed in 3 Categories:<br>\n 1. Wear Mask<br>\n 2. Wear Mask Properly<br>\n 3. Thank you for wearing Mask<br><br>\nFirstly we used a CNN model made from Scratch on out custom made dataset. Since Dataset is very less so Model was finding it dificult to do feature extraction Succesfully.<br>\nSo we used a Pretrained model like (VGG16 , ResNet, etc) which gave us satisfactory Result\n# Data\nMade a Custom Data in various Lighting Conditions and angles. To make Model more robust more data of different persons are needed.<br>\n# Note\n[Since Dataset was not available so dataset includes my faces wearing mask in different Position and Lightining Conditions and may need a little Callibration ( an automatic cllibration wont work unless we have good amount of data ) ]\n\n" }, { "alpha_fraction": 0.6206790208816528, "alphanum_fraction": 0.6669753193855286, "avg_line_length": 36.117645263671875, "blob_id": "ffa9f33efe2e6ce2808e5211b18b9d9915b8722f", "content_id": "bc7b829a25b74ca4911a31e1447a438b1adb2bf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3240, "license_type": "no_license", "max_line_length": 150, "num_lines": 85, "path": "/run.py", "repo_name": "anirudh9784/Face-Mask-detection", "src_encoding": "UTF-8", "text": "from torch.autograd import Variable\r\nimport cv2 \r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import cm\r\nimport torchvision.models as models\r\nimport torch.nn as nn\r\nimport torch\r\nimport os\r\nimport numpy as np\r\nfrom torchvision import datasets\r\nfrom torchvision import transforms\r\nimport torch.optim as optim\r\nfrom glob import glob\r\nfrom trainm import Net\r\nfrom PIL import Image, ImageEnhance\r\nimport tensorflow.keras\r\nfrom PIL import Image, ImageOps\r\nimport numpy as np\r\n\r\ndef softmax(x):\r\n e_x = np.exp(x - np.max(x))\r\n return e_x / e_x.sum()\r\ndef detect_faces(cascade, test_image, scaleFactor = 1.1):\r\n\timage_copy = test_image.copy()\r\n\tfaces_rect = cascade.detectMultiScale(image_copy[:,:,2], scaleFactor=scaleFactor, minNeighbors=5 ,\tminSize = (30,30))\r\n\tflag = 0\r\n\tfor (x, y, w, h) in faces_rect:\r\n\t\t#print(\"Hello wait untill Machine detects Mask\")\r\n\t\tcrop_img = image_copy[y:y+h, x:x+w]\t\r\n\t\tflag = 1\r\n\t\tflag , val = Classify(crop_img)\r\n\r\n\t\tif flag == 0:\r\n\t\t\tcrop_img = cv2.putText(image_copy, f'Thank you!{max(val*100)}', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX , 0.5 ,(0,255, 0) ,2 , cv2.LINE_AA) \r\n\t\t\tcv2.rectangle(image_copy, (x, y), (x+w, y+h), (0, 255, 0), 1)\r\n\r\n\t\telif flag == 1:\r\n\t\t\tcrop_img = cv2.putText(image_copy, f'Wear Mask{max(val*100)}', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX , 0.5 ,(255, 0,0) ,2 , cv2.LINE_AA) \r\n\t\t\tcv2.rectangle(image_copy, (x, y), (x+w, y+h), (255, 0, 0), 5)\r\n\r\n\t\telse:\r\n\t\t\tcrop_img = cv2.putText(image_copy, f'Wear Mask Properly{max(val*100)}', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX , 0.5 ,(0, 0 , 255) ,2 , cv2.LINE_AA) \r\n\t\t\tcv2.rectangle(image_copy, (x, y), (x+w, y+h), (0,0, 255), 5)\r\n\r\n\treturn image_copy\r\n\r\ndef Classify(image):\r\n\tdata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\r\n\timage = Image.open('asd.jpg')\r\n\tsize = (224, 224)\r\n\timage = ImageOps.fit(image, size, Image.ANTIALIAS)\r\n\timage_array = np.asarray(image)\r\n\tnormalized_image_array = (image_array.astype(np.float32) / 127.0) - 1\r\n\tdata[0] = normalized_image_array\r\n\tprediction = model.predict(data)\r\n\tprint(softmax(prediction))\r\n\r\n\tif prediction[0][1] > prediction[0][0] and prediction[0][1] > prediction[0][2]:\r\n\t\treturn 0 , max(softmax(prediction))\r\n\telif prediction[0][0] > prediction[0][1] and prediction[0][0] > prediction[0][2]:\r\n\t\treturn 1 , max(softmax(prediction))\r\n\telse:\r\n\t\treturn 2 , max(softmax(prediction))\r\n\r\nif __name__ == '__main__':\r\n\tcascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\t#videofile = 'Clip1.wmv'\r\n\tout = cv2.VideoWriter('outpy_intern_mirasys.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 20, (256,256))\r\n\tcap = cv2.VideoCapture(0)\r\n\t#This Net model is Made from Scratch but due to complexity of detection (As we need higher accuracy) we used pretrained Models\r\n\tmodel_transfer = Net()\r\n\t#Three Class Classification : wear mask : wear mask properly : thank you for wearing mask\r\n\tmodel = tensorflow.keras.models.load_model('Trained_mask.h5')\r\n\twhile(True):\r\n\t\tret, frame = cap.read()\r\n\t\tcv2.imwrite('asd.jpg' , frame)\r\n\t\tgray = detect_faces(cascade,frame)\r\n\t\tcv2.imshow('frame',gray)\r\n\t\tout.write(frame)\r\n\t\tcv2.waitKey(500)\r\n\t\tif cv2.waitKey(1) & 0xFF == ord('q'):\r\n\t\t\tbreak\r\n\tcap.release()\r\n\tcv2.destroyAllWindows()\r\nnp.set_printoptions(suppress=True)\r\n" }, { "alpha_fraction": 0.6420890688896179, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 30.987340927124023, "blob_id": "2f52710449047f3eeaeb34530c1d8a17e96b68b8", "content_id": "9c6327a17fb06f9a5681d3d76ae29127a40577ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2604, "license_type": "no_license", "max_line_length": 98, "num_lines": 79, "path": "/face.py", "repo_name": "anirudh9784/Face-Mask-detection", "src_encoding": "UTF-8", "text": "from torch.autograd import Variable\r\nimport cv2 \r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import cm\r\nimport torchvision.models as models\r\nimport torch.nn as nn\r\nimport torch\r\nimport os\r\nimport numpy as np\r\nfrom torchvision import datasets\r\nfrom torchvision import transforms\r\nimport torch.optim as optim\r\nfrom glob import glob\r\nfrom train import Net\r\nfrom PIL import Image\r\ndef predict_breed_transfer(img):\r\n\t# load the image and return the predicted breed\r\n\timg = Image.fromarray(img.astype(np.uint8))\r\n\ttransform = transforms.Compose([\r\n\t\t\ttransforms.Resize(256),\r\n\t\t\ttransforms.CenterCrop(224),\r\n\t\t\ttransforms.ToTensor(),\r\n\t\t\ttransforms.Normalize([0.485, 0.456, 0.406], \r\n [0.229, 0.224, 0.225])\r\n\t\t\t])\r\n\timg_tensor = transform(img)\r\n \r\n\t# reshaping to include batch size\r\n\timg_tensor = img_tensor.view(1, img_tensor.shape[0], img_tensor.shape[1], img_tensor.shape[2])\r\n\t\r\n\tprediction = model_transfer(img_tensor)\r\n\t\r\n\tclass_idx = torch.argmax(prediction).item()\r\n\tprint(prediction , class_idx)\r\n\treturn class_idx\r\ndef detect_faces(cascade, test_image, scaleFactor = 1.1):\r\n\t# create a copy of the image to prevent any changes to the original one.\r\n\timage_copy = test_image.copy()\r\n\t#convert the test image to gray scale as opencv face detector expects gray images\r\n\t#gray_image = cv2.cvtColor(image_copy, cv2.COLOR_BGR2GRAY)\r\n\r\n\t# Applying the haar classifier to detect faces\r\n\tfaces_rect = cascade.detectMultiScale(image_copy[:,:,1], scaleFactor=scaleFactor, minNeighbors=5)\r\n\tflag = 0\r\n\tfor (x, y, w, h) in faces_rect:\r\n\t\t#cv2.rectangle(image_copy, (x, y), (x+w, y+h), (0, 255, 0), 15)\r\n\t\tcrop_img = image_copy[y:y+h, x:x+w]\r\n\t\tflag = 1\r\n\tif flag:\r\n\t\tif predict_breed_transfer(crop_img):\r\n\t\t\tcv2.rectangle(image_copy, (x, y), (x+w, y+h), (0, 255, 0), 15)\r\n\t\t\tprint('Mask')\r\n\t\telse:\r\n\t\t\tcv2.rectangle(image_copy, (x, y), (x+w, y+h), (255,0, 0), 15)\r\n\t\t\tprint('No Mask')\r\n\t\treturn image_copy\r\n\telse:\r\n\t\treturn image_copy\r\n\r\nif __name__ == '__main__':\r\n\tcascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\t#videofile = 'Clip1.wmv'\r\n\tcap = cv2.VideoCapture('WIN_20200505_23_44_58_Pro.mp4')\r\n\tmodel_transfer = Net()\r\n\tmodel_transfer.load_state_dict(torch.load('model.pt') )\r\n\twhile(True):\r\n\t\t# Capture frame-by-frame\r\n\t\tret, frame = cap.read()\r\n\r\n\t\t# Our operations on the frame come here\r\n\t\tgray = detect_faces(cascade,frame)\r\n\t\t# Display the resulting frame\r\n\t\tcv2.imshow('frame',gray)\r\n\t\tif cv2.waitKey(1) & 0xFF == ord('q'):\r\n\t\t\tbreak\r\n\r\n\t# When everything done, release the capture\r\n\tcap.release()\r\n\tcv2.destroyAllWindows()" } ]
4
ulima-is2/tarea-2-r-chavez-m-marroquin
https://github.com/ulima-is2/tarea-2-r-chavez-m-marroquin
d71d7b9c1b89091f423cad05b67d656928e76176
d1e3f23eecef72ef67fa9318ab6c519e50323d9d
e055fa855a78acb83ca415989492713b6d9146d8
refs/heads/master
2021-07-07T02:26:45.775509
2017-10-02T23:18:45
2017-10-02T23:18:45
105,084,430
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.743139386177063, "alphanum_fraction": 0.7442371249198914, "avg_line_length": 48.55555725097656, "blob_id": "4e200dc70aca6c60af838554cfc23f3bd906d177", "content_id": "56b110850dc1c5cc1ca31b7c77f8cccb0b9deab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 911, "license_type": "no_license", "max_line_length": 411, "num_lines": 18, "path": "/Pregunta 1.md", "repo_name": "ulima-is2/tarea-2-r-chavez-m-marroquin", "src_encoding": "UTF-8", "text": "# Pregunta 1\r\n\r\n### Single Responsibility\r\n\r\nCada modulo debe enfocarse en un solo objetivo y esto no se cumple especialmente en el ``` main() ``` el cual se encarga de mostrar informacion, la logica para mostrarla y ademas realiza la funcion de guardar la informacion.\r\n\r\n***\r\n\r\n### Open Close\r\n\r\nEn las clases ``` CinePlaneta ```y ```CineStark```al ser iguales cuando se desee ingresar un nuevo campo para un cine, se debera modificar a ambos cines por separado, o en caso se tenga que crear otro cine, se debera copiar toda la informacion cuando estas deberian tener un padre. De esta manera pueden extenderse en caso se tengan ```funciones``` distintas para cada cine pero esten cerradas para modificarse.\r\n\r\n\r\n***\r\n\r\n### Interface Segregation\r\n\r\nEste principio esta muy relacionado al de **Single Responsibility** por lo que no se cumple en el ```guardar entradas``` ya que realmente no depende del cine \r\n" }, { "alpha_fraction": 0.7265625, "alphanum_fraction": 0.7265625, "avg_line_length": 23.53333282470703, "blob_id": "a40c9ec4696895ee01afecd7aff9577831dd7077", "content_id": "f3bfd517453e6f788066a29b9d5ff6a5dff6d12b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 386, "license_type": "no_license", "max_line_length": 135, "num_lines": 15, "path": "/Sustento pregunta2.md", "repo_name": "ulima-is2/tarea-2-r-chavez-m-marroquin", "src_encoding": "UTF-8", "text": "### Factory\r\n\r\nSe implemento el diseño de factory para los cines ya que distintos cines pueden depender de un padre ya que poseen las mismas funciones\r\n\r\n***\r\n\r\n### Composite\r\n\r\nSe utilizo este diseño ya que las clases tienen estructura de arbol:\r\nCine->Pelicula->Funciones\r\n\r\n***\r\n\r\n### Adapter\r\nYa que en base a la opcion que se escoja, se va a realizar un procedimiento distinto \r\n" }, { "alpha_fraction": 0.5345006585121155, "alphanum_fraction": 0.5452659130096436, "avg_line_length": 30.669490814208984, "blob_id": "65d8f33cdbddbc05dd33def1824bca05d21d6a00", "content_id": "4af4a28fff3f349b0b9bf87b8780be6cb9740ec4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7716, "license_type": "no_license", "max_line_length": 191, "num_lines": 236, "path": "/pregunta2.py", "repo_name": "ulima-is2/tarea-2-r-chavez-m-marroquin", "src_encoding": "UTF-8", "text": "import sqlite3\r\n\r\nconn = sqlite3.connect('Taller2.db')\r\ncur = conn.cursor()\r\n\r\nclass Entrada:\r\n def __init__(self, pelicula_id, funcion, cantidad):\r\n self.pelicula_id = pelicula_id\r\n self.funcion = funcion\r\n self.cantidad = cantidad\r\n\r\n\r\nclass Pelicula:\r\n def __init__(self, nombre):\r\n self.nombre = nombre\r\n\r\n\r\nclass Cine:\r\n def __init__(self, nombre):\r\n self.id = None\r\n self.idP = 1\r\n self.nombre = nombre\r\n self.lista_peliculas = []\r\n self.entradas = []\r\n\r\n def addPelicula(self, pelicula):\r\n\r\n if self.nombre=='CineStark':\r\n\r\n if pelicula.nombre=='Desaparecido':\r\n pelicula.funciones =['21:00', '23:00']\r\n elif pelicula.nombre=='Deep El Pulpo':\r\n pelicula.funciones = ['16:00', '20:00']\r\n pelicula.id=self.idP\r\n self.lista_peliculas.append(pelicula)\r\n self.idP += 1\r\n elif self.nombre=='CinePlaneta':\r\n\r\n if pelicula.nombre=='Desaparecido':\r\n pelicula.funciones = ['20:00', '23:00']\r\n elif pelicula.nombre=='Deep El Pulpo':\r\n pelicula.funciones = ['16:00']\r\n elif pelicula.nombre == 'IT':\r\n pelicula.funciones = ['19:00', '20:30', '22:00']\r\n elif pelicula.nombre == 'La Hora Final':\r\n pelicula.funciones = ['21:00']\r\n pelicula.id = self.idP\r\n self.lista_peliculas.append(pelicula)\r\n self.idP += 1\r\n\r\n\r\n def listar_peliculas(self):\r\n print('********************')\r\n for pelicula in self.lista_peliculas:\r\n print(\"{}. {}\".format(pelicula.id, pelicula.nombre))\r\n print('********************')\r\n\r\n return input('Elija pelicula:')\r\n\r\n def listar_funciones(self, pelicula_id):\r\n print('Ahora elija la función (debe ingresar el formato hh:mm): ')\r\n for funcion in self.lista_peliculas[int(pelicula_id) - 1].funciones:\r\n print('Función: {}'.format(funcion))\r\n\r\n rsltdo1 = input('Funcion:')\r\n rsltdo2 = input('Ingrese cantidad de entradas: ')\r\n\r\n return [rsltdo1,rsltdo2]\r\n\r\n def guardar_entrada(self, id_pelicula_elegida, funcion_elegida, cantidad):\r\n self.entradas.append(Entrada(id_pelicula_elegida, funcion_elegida, cantidad))\r\n return len(self.entradas)\r\n\r\n\r\nclass GrupoCines:\r\n def __init__(self):\r\n self.idCine=1\r\n self.Cines = []\r\n\r\n def getCine(self, idC):\r\n return self.Cines[idC]\r\n\r\n def addCine(self,cine):\r\n cine.id = self.idCine\r\n self.Cines.append(cine)\r\n self.idCine+=1\r\n\r\n def listarCines(self):\r\n print('********************')\r\n print('Lista de cines')\r\n for cine in self.Cines:\r\n print(\"{}: {}\".format(cine.id, cine.nombre))\r\n print('********************')\r\n\r\n def listarCinesInput(self):\r\n print('********************')\r\n print('Lista de cines')\r\n idCine = 0\r\n for cine in self.Cines:\r\n idCine += 1\r\n print(\"{}: {}\".format(idCine, cine.nombre))\r\n print('********************')\r\n return input('Primero elija un cine:')\r\n\r\n\r\ndef Menu():\r\n print('Ingrese la opción que desea realizar')\r\n print('(1) Listar cines')\r\n print('(2) Listar cartelera')\r\n print('(3) Comprar entrada')\r\n print('(4) Ver entradas')\r\n print('(5) LimpiarBD')\r\n print('(0) Salir')\r\n return input('Opción: ')\r\n\r\n\r\ndef sql():\r\n\r\n cur.execute('''CREATE TABLE IF NOT EXISTS Cines\r\n (idCine integer, NombreCine text)''')\r\n\r\n cur.execute('''CREATE TABLE IF NOT EXISTS Peliculas_X_Cine\r\n (idCine integer, NombreCine text, idPelicula integer, NombrePelicula text)''')\r\n\r\n cur.execute('''CREATE TABLE IF NOT EXISTS Entradas_X_Func\r\n (idCine integer, idPelicula integer, Funcion text, Entradas text)''')\r\n conn.commit()\r\n\r\ndef limpiarBD():\r\n cur.execute('''DROP TABLE IF EXISTS Cines''')\r\n cur.execute('''DROP TABLE IF EXISTS Peliculas_X_Cine''')\r\n cur.execute('''DROP TABLE IF EXISTS Entradas_X_Func''')\r\n\r\ndef insertarCine(cine):\r\n\r\n cur.execute(\"INSERT INTO Cines (idCine, NombreCine) VALUES (?,?)\", (cine.id, cine.nombre ))\r\n\r\n conn.commit()\r\n\r\n # Insertar Peliculas\r\n\r\n for pelicula in cine.lista_peliculas:\r\n cur.execute(\"INSERT INTO Peliculas_X_Cine (idCine , NombreCine , idPelicula , NombrePelicula )\"\r\n \" VALUES (?,?,?,?)\", (cine.id, cine.nombre, pelicula.id , pelicula.nombre))\r\n\r\n conn.commit()\r\n\r\ndef insertarFuncionEntrada(idCine, idPelicula, horarioFuncion, cantidadEntradas):\r\n cur.execute(\"INSERT INTO Entradas_X_Func (idCine, idPelicula , Funcion , Entradas )\"\r\n \" VALUES (?, ?,?,?)\", (idCine, idPelicula, horarioFuncion, cantidadEntradas))\r\n\r\n conn.commit()\r\n\r\ndef main():\r\n terminado = False\r\n while not terminado:\r\n \r\n # CineStark\r\n cineStark = Cine(\"CineStark\")\r\n cineStark.addPelicula(Pelicula('Desaparecido'))\r\n cineStark.addPelicula(Pelicula('Deep El Pulpo'))\r\n\r\n # CinePlaneta\r\n cinePlaneta = Cine(\"CinePlaneta\")\r\n cinePlaneta.addPelicula(Pelicula('IT'))\r\n cinePlaneta.addPelicula(Pelicula('La Hora Final'))\r\n cinePlaneta.addPelicula( Pelicula('Desaparecido'))\r\n cinePlaneta.addPelicula(Pelicula('Deep El Pulpo'))\r\n\r\n Cines = GrupoCines()\r\n Cines.addCine(cineStark)\r\n Cines.addCine(cinePlaneta)\r\n\r\n cur.execute('SELECT * FROM Cines where NombreCine=?',(\"CineStark\",))\r\n if cur.fetchone() is None:\r\n insertarCine(cineStark)\r\n\r\n cur.execute('SELECT * FROM Cines where NombreCine=?', (\"CinePlaneta\",))\r\n if cur.fetchone() is None:\r\n insertarCine(cinePlaneta)\r\n\r\n\r\n opcion = Menu()\r\n\r\n if opcion == '1':\r\n Cines.listarCines()\r\n elif opcion == '2':\r\n cine = Cines.listarCinesInput()\r\n if cine == '1':\r\n cine = Cines.getCine(0)\r\n elif cine == '2':\r\n cine = Cines.getCine(1)\r\n else:\r\n print(\"Se ingreso un valor no valido\")\r\n break\r\n\r\n cine.listar_peliculas()\r\n\r\n elif opcion == '3':\r\n print('********************')\r\n print('COMPRAR ENTRADA')\r\n\r\n cine = Cines.listarCinesInput()\r\n if cine == '1':\r\n cine = Cines.getCine(0)\r\n elif cine == '2':\r\n cine = Cines.getCine(1)\r\n else:\r\n print(\"Se ingreso un valor no valido\")\r\n break\r\n\r\n pelicula_elegida = cine.listar_peliculas()\r\n\r\n resultadosFuncion = cine.listar_funciones(pelicula_elegida)\r\n \r\n\r\n codigo_entrada = cine.guardar_entrada(pelicula_elegida, resultadosFuncion[0], resultadosFuncion[0])\r\n insertarFuncionEntrada(cine.id ,pelicula_elegida,resultadosFuncion[0], resultadosFuncion[1])\r\n print('Se realizó la compra de la entrada. Código es {}'.format(codigo_entrada))\r\n elif opcion == '4':\r\n print(\"******Cine Pelicula Funcion Entradas******\")\r\n cur.execute('SELECT B.NombreCine, B.NombrePelicula, A.Funcion, A.Entradas FROM Entradas_X_Func A LEFT JOIN Peliculas_X_Cine B ON A.idCine=B.idCine AND A.idPelicula=B.idPelicula ')\r\n for row in cur:\r\n print(row)\r\n elif opcion == '5':\r\n limpiarBD()\r\n sql()\r\n elif opcion == '0':\r\n terminado = True\r\n else:\r\n print(opcion)\r\n\r\n\r\nif __name__ == '__main__':\r\n sql()\r\n main()\r\n" }, { "alpha_fraction": 0.4588235318660736, "alphanum_fraction": 0.5588235259056091, "avg_line_length": 17.77777862548828, "blob_id": "fb847962e5ab987adbe466014b7efd29c319c17d", "content_id": "be52f84983f207af7112304fb05e60ed6bdc0378", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 170, "license_type": "no_license", "max_line_length": 45, "num_lines": 9, "path": "/ReadMe.md", "repo_name": "ulima-is2/tarea-2-r-chavez-m-marroquin", "src_encoding": "UTF-8", "text": "\n## Tarea 2\n\n### Alumnos\n\n<table>\n <tr><th>Nombre</th><th>Codigo</th></tr><tr>\n<td>Hector Mauricio Marroquin Valcarcel</td><td>20110736</td> </tr>\n<tr><td>Renato Chavez Martinez</td><td>20151536</td></tr>\n</table>\n" } ]
4
sagorchandrapaul/corona
https://github.com/sagorchandrapaul/corona
6c0a684a64030cc396d0d0e025cadc98eba1debf
07aefe6026740135e13db2a8f2d1e959fe8f2b8b
c5a9ad6c7dc898d5e4afcd76c9ac7a19874ffec7
refs/heads/master
2022-12-12T10:55:43.212836
2020-09-09T19:47:36
2020-09-09T19:47:36
293,879,058
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5616147518157959, "alphanum_fraction": 0.5786119103431702, "avg_line_length": 49.42856979370117, "blob_id": "6abe3863edad73806d817b7e90e48d3dff5d72b4", "content_id": "38851598ca71f1795cbcabf18bc9dcd3bfc350c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1412, "license_type": "no_license", "max_line_length": 391, "num_lines": 28, "path": "/core/migrations/0001_initial.py", "repo_name": "sagorchandrapaul/corona", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1 on 2020-08-22 12:00\n\nfrom django.db import migrations, models\nimport multiselectfield.db.fields\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Patient',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('age', models.IntegerField()),\n ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=10)),\n ('pub_date', models.DateField(auto_now_add=True)),\n ('temperature', models.DecimalField(decimal_places=2, max_digits=5)),\n ('symptoms', multiselectfield.db.fields.MultiSelectField(choices=[('DC', 'Dry Cough'), ('ST', 'Sore throat'), ('W', 'Weakness'), ('RN', 'Runny nose')], max_length=255)),\n ('additionalInformation', multiselectfield.db.fields.MultiSelectField(choices=[('AP', 'Abdominal pain'), ('V', 'Vomiting'), ('D', 'Diarrhea'), ('CP', 'Chest pain'), ('P', 'pressure'), ('MP', 'Muscle pain'), ('LTS', 'Loss of taste or smell'), ('RS', 'Rash on the skin'), ('DF', 'discoloration of fingers'), ('T', 'toes'), ('LSM', 'Loss of speech movement')], max_length=255)),\n ('score', models.IntegerField(blank=True, null=True)),\n ],\n ),\n ]\n" } ]
1
ShawnM10/Python-Final-Project
https://github.com/ShawnM10/Python-Final-Project
45a9a7e9d3956c601ec7bf154cf3729a038a9f60
ba7e19f3144fee5b2b91e139885366d9e47c6202
f0df479be78b1b93ee30030c9f1f70092c5926df
refs/heads/master
2021-03-12T20:46:18.112898
2014-07-31T20:35:50
2014-07-31T20:35:50
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4655914008617401, "alphanum_fraction": 0.490680992603302, "avg_line_length": 30.704545974731445, "blob_id": "39702cc3114a9ea096a716d540d324c68d13cdb9", "content_id": "085099372e1fad65f16aec7de486fb19fdc499d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2790, "license_type": "no_license", "max_line_length": 79, "num_lines": 88, "path": "/Shawn_Musengo_final_project.py", "repo_name": "ShawnM10/Python-Final-Project", "src_encoding": "UTF-8", "text": "import random\n\ndef drawboard():\n print\n print \" %s| %s| %s\" % (board[0],board[1],board[2])\n print \"__|__|__\"\n print \" %s| %s| %s\" % (board[3],board[4],board[5])\n print \"__|__|__\"\n print \" %s| %s| %s\" % (board[6],board[7],board[8])\n print\n return\n \n\ndef iswinner(test):\n if board[0] == test and board[1] == test and board[2] == test:\n return True\n if board[3] == test and board[4] == test and board[5] == test:\n return True\n if board[6] == test and board[7] == test and board[8] == test:\n return True\n if board[0] == test and board[3] == test and board[6] == test:\n return True\n if board[1] == test and board[4] == test and board[7] == test:\n return True\n if board[2] == test and board[5] == test and board[8] == test:\n return True\n if board[0] == test and board[4] == test and board[8] == test:\n return True\n if board[6] == test and board[4] == test and board[2] == test:\n return True\n return False\n\n\n\ngame = 0\nrandom.seed()\nwhile (game == 0):\n\n board = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n print \"Welcome to Tic Tac Toe\"\n print\n player1 = raw_input(\"Player ones name? \")\n player2 = raw_input(\"player two's name? (type 'python' for computer) \")\n movesplayed = 0\n playersturn = 1\n gamewon = False\n while (movesplayed < 9):\n drawboard()\n if playersturn == 1:\n nextmove = raw_input(\"Your Move %s ? \" % (player1))\n if board[(int(nextmove)-1)] == nextmove:\n board[(int(nextmove)-1)] = \"X\"\n if iswinner(\"X\"):\n gamewon = True\n winner = player1\n break\n playersturn = 0\n movesplayed = movesplayed+1\n else:\n print \"the space has been taken\"\n else:\n if player2.lower() == \"python\":\n nextmove = str(random.randrange(1,9))\n print \"Pythons move was %s \" % (nextmove)\n else:\n nextmove = raw_input(\"Your Move %s ? \" % (player2))\n if board[(int(nextmove)-1)] == nextmove:\n board[(int(nextmove)-1)] = \"0\"\n if iswinner(\"0\"):\n gamewon = True\n winner = player2\n break\n playersturn = 1\n movesplayed = movesplayed+1\n else:\n print \"the space has been taken\"\n if gamewon:\n print \"congratulatisions %s you won this game\" % winner\n print\n else:\n print \"Oh well %s the game with %s was a draw.....\" % (player1,player2)\n print\n print\n \n if raw_input(\"Play again? ( Y or N) \").lower() == 'n':\n game = 1\n \nprint \"Good bye!\"\n" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 18, "blob_id": "ea955bca9864c43685e1c0cc4b701aec001c3bbc", "content_id": "01ab7afc642fa1719e4155769ed2fce7fed0efad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/README.md", "repo_name": "ShawnM10/Python-Final-Project", "src_encoding": "UTF-8", "text": "Python-Final-Project\n====================\n\nThis is my final Python project.\n" }, { "alpha_fraction": 0.4326621890068054, "alphanum_fraction": 0.4595078229904175, "avg_line_length": 25.506023406982422, "blob_id": "5efc6e8eced85caa5d4bab3f91551a375ed7c620", "content_id": "f03a217baf4207508ac52bbd50645c47a225031a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2235, "license_type": "no_license", "max_line_length": 71, "num_lines": 83, "path": "/final_project_version2.py", "repo_name": "ShawnM10/Python-Final-Project", "src_encoding": "UTF-8", "text": "grid = [[0,0,0],[0,0,0],[0,0,0]]\n\ndef get_state(grid, row, col):\n occupant = grid[col-1] ###This is because a list has a o index\n if occupant == 1:\n return 'X'\n if occupant == 2:\n return '0'\n return ' '\n\ndef set_state(grid, row, col, player):\n if player == 'X':\n occupant = 1\n else:\n occupant = 2\n grid[col-1][row-1] = occupant\n\ndef is_winner(grid):\n if grid[1][1] != 0:\n if grid[0][0] == grid[1][1]: ##Top left to bottowm right\n if grid[2][2] == grid[1][1]:\n return True\n if grid[2][0] == grid[1][1]: ##Top right to bottom left\n if grid[0][2] == grid[1][1]:\n return True\n for i in xrange(0, 3):\n if grid[0][i] != 0:\n if grid[0][i] == grid[1][i]: ##Top left with middle\n if grid[0][i] == grid[2][i]: \n return True\n\n if grid[i][0] != 0: ###Top left to bottom\n if grid[i][0] == [i][1]: ###Center down\n if grid[i][0] == grid[i][2]: ###Right down\n return True\n return False\n\ndef print_grid(grid):\n print_row(grid, 1)\n print '-----'\n print_row(grid, 2)\n print '-----'\n print_row(grid, 3)\n\n\n\ndef print_row(grid, row):\n output = get_state(grid, row, 1)\n output += '|' + get_state(grid, row, 2)\n output += '|' + get_state(grid, row, 3)\n print output\n\nongoing = True\ncurrent_player = 'X'\nspaces = 9\n\nwhile ongoing:\n print_grid(grid)\n print current_player + \"'s turn\"\n print \"Column?\"\n col = int(raw_input())\n print \"Row?\"\n row = int(raw_input())\n current = get_state(grid, row, col)\n if current != ' ':\n print \"That space is occupied!\"\n else:\n set_state(grid, row, col, current_player)\n spaces -= 1\n\n \n if is_winner(grid):\n print current_player + \"Wins!\"\n ongoing = False\n else:\n if current_player == 'X':\n current_player = '0'\n else:\n current_player = 'X'\n\n if spaces == 0:\n print \"Stalemate!\"\n ongoing = False\n \n \n \n" } ]
3
TohsakaHus/alphacoders-wallpaper-downloader
https://github.com/TohsakaHus/alphacoders-wallpaper-downloader
42991cbc27ea36bb0085d3043ab8d9d86f4910da
54b9ca948620a1304056c53102b8e90078d5ec3c
a0b01369fc0feec0d0c60cc0d92f4983e677e1b2
refs/heads/master
2020-08-02T18:06:00.816252
2019-09-28T07:31:27
2019-09-28T07:31:27
211,458,691
0
0
WTFPL
2019-09-28T07:00:32
2019-08-14T13:46:39
2019-08-14T13:46:38
null
[ { "alpha_fraction": 0.538223147392273, "alphanum_fraction": 0.5433884263038635, "avg_line_length": 27.25, "blob_id": "a1267508cf85544d2a33404ac211befe38e51765", "content_id": "1f22602ae1a0e0699ed97ef3897e0816a772edb0", "detected_licenses": [ "WTFPL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1994, "license_type": "permissive", "max_line_length": 116, "num_lines": 68, "path": "/main.py", "repo_name": "TohsakaHus/alphacoders-wallpaper-downloader", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport requests\nfrom pyquery import PyQuery as pq\n\ndef fetch(api_key, tag_id, min_width, i):\n info = requests.get('https://wall.alphacoders.com/api2.0/get.php?auth=%s&method=tag&id=%s&page=%d&sort=views' % \n (api_key, tag_id, i))\n info = json.loads(info.text)\n\n if info['success']:\n if len(info['wallpapers']) == 0:\n print('已无更多图片')\n return False\n\n for j in range(len(info['wallpapers'])):\n pic_info = info['wallpapers'][j]\n\n # 若当前图片小于设定的min_width,则直接下一张\n if int(pic_info['width']) < min_width:\n continue\n\n file_name = pic_info['id'] + '.' + pic_info['file_type']\n if os.path.exists(file_name):\n continue\n\n pic = requests.get(pic_info['url_image'])\n with open(file_name, 'wb') as file_obj:\n file_obj.write(pic.content)\n\n print('第 %d 页下载完成' % i)\n return True\n\n# Read Config\nwith open('config.json', 'r') as file_obj:\n config = file_obj.read()\n config = json.loads(config)\n tag_id = str(config['tag_id'])\n api_key = str(config['api_key'])\n try:\n max_page = int(config['max_page'])\n except:\n max_page = 0\n try:\n min_width = int(config['min_width'])\n except:\n min_width = 0\n# Main\nurl = 'https://wall.alphacoders.com/tags.php?tid=' + str(tag_id)\nhtml = pq(url=url)\ndir_name = html('span.breadcrumb-element').text()\ndir_name = \"\".join(i for i in dir_name if i.isalnum())\nif not os.path.isdir(dir_name):\n os.mkdir(dir_name)\nos.chdir(dir_name)\n\nif max_page != 0:\n for i in range(1, max_page + 1):\n status = fetch(api_key, tag_id, min_width, i)\n if status == False:\n break\nelse:\n i = 1\n while True:\n status = fetch(api_key, tag_id, min_width, i)\n if status == False:\n break\n i += 1\n \n \n\n" } ]
1
jjh42/jjhsnip
https://github.com/jjh42/jjhsnip
24c06a448d982af5ff84d2c13e62fb42bc55e709
18865213158f928b49bf031579d3f2230458ccd5
95b1da25ff884c10f8b5251efaa6f3f01e2a6c57
refs/heads/master
2021-01-23T21:28:34.042191
2007-01-26T00:29:21
2007-01-26T00:29:21
32,288,853
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6288659572601318, "alphanum_fraction": 0.6330660581588745, "avg_line_length": 24.940593719482422, "blob_id": "a278cc3347d828a0da60298ae2c7bb813aedc1f0", "content_id": "5a0232e4c308280147e2769d8c5d2b6958688555", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2619, "license_type": "no_license", "max_line_length": 101, "num_lines": 101, "path": "/pythonsnips/parse_ods.py", "repo_name": "jjh42/jjhsnip", "src_encoding": "UTF-8", "text": "import zipfile;\nimport copy;\nfrom xml.dom.minidom import parse, parseString;\n\n\nclass Spreadsheet:\n\tdef __init__(self, filename=None):\n\t\t# Load the spreadsheet and parse the filename if given\n\t\tif (filename != None):\n\t\t\tself.filename= filename;\n\t\t\tself.parse();\n\n\n\tdef parse(self):\n\t\t\"\"\"Parse the ODS and load the results into this spreadsheet object.\"\"\"\n\n\t\tz = zipfile.ZipFile(self.filename, 'r');\n\t\tc = z.read('content.xml');\n\n\t\tdom = parseString(c);\n\n\t\tself.parse_dom(dom);\n\n\t\tdom.unlink();\n\n\t\t\n\tdef parse_dom(self, dom):\n\t\t\"\"\"DOM is read. Now load data from DOM.\"\"\"\n\n\t\t# Setup empty key sets\n\t\tself.sheets = {};\n\n\t\tsheets = dom.getElementsByTagName(\"table:table\");\n\t\tfor i in sheets:\n\t\t\tself.parse_sheet(i);\n\n\tdef parse_sheet(self, table):\n\t\t\"\"\"Hand a sheet - read it.\"\"\"\n\t\t\n\t\t# First find the name of the sheet\n\t\tname = table.getAttribute('table:name');\n\n\t\t# Now load the table\n\t\t#columns = table.getElementsByTagName(\"table:table-column\");\n\t\t#ncolsstr = columns[0].getAttribute(\"table:number-columns-repeated\");\n\t\t#ncols = 1;\n\t\t#if ncolsstr != \"\":\n\t\t#\tncols = int(str(ncolsstr));\n\t\t\n\t\tsheet = [];\n\t\t#for i in range(ncols):\t# Make enough empty columns\n\t\t#\tsheet.append([]);\n\t\t\n\t\t# Now for each row in the sheet\n\t\trows = table.getElementsByTagName(\"table:table-row\");\n\t\tfor r in rows:\n\t\t\tcells = r.getElementsByTagName(\"table:table-cell\");\n\t\t\tnumnew = 0;\n\t\t\tfor c in cells:\n\t\t\t\tn = 1;\n\t\t\t\tif c.hasAttribute(\"table:number-columns-repeated\"):\n\t\t\t\t\tn = int(c.getAttribute(\"table:number-columns-repeated\"));\n\t\t\t\tnumnew += n;\n\n\t\t\t# Check we have enough columns for this row\n\t\t\tnumnew = numnew - len(sheet);\n\t\t\tif numnew > 0:\n\t\t\t\temptycol = [];\n\t\t\t\tif(len(sheet)):\t# We have already started another column so need to make this column up to length\n\t\t\t\t\tfor i in sheet[0]:\n\t\t\t\t\t\temptycol.append('');\n\t\t\t\tfor i in range(numnew):\n\t\t\t\t\tsheet.append(copy.copy(emptycol));\n\n\t\t\tinspos = 0;\n\t\t\tfor i in range(len(cells)):\n\t\t\t\tc = cells[i];\n\t\t\t\t# Check what type of cell this is\n\t\t\t\tval = \"\";\n\t\t\t\tif c.hasAttribute(\"office:value\"):\n\t\t\t\t\tval = c.getAttribute(\"office:value\");\n\t\t\t\t\tif c.getAttribute(\"office:value-type\") == \"float\":\n\t\t\t\t\t\tval = float(val);\n\t\t\t\telse:\n\t\t\t\t\t# Try reading any text it might contain\n\t\t\t\t\tt = c.getElementsByTagName(\"text:p\");\n\t\t\t\t\tif(len(t)):\n\t\t\t\t\t\tcn = t[0].childNodes;\n\t\t\t\t\t\tif(len(cn)):\n\t\t\t\t\t\t\tval = cn[0].data;\n\t\t\t\n\t\t\t\t# There may be a repeated value\n\t\t\t\tntimes = 1;\n\t\t\t\tif c.hasAttribute(\"table:number-columns-repeated\"):\n\t\t\t\t\tntimes = int(c.getAttribute(\"table:number-columns-repeated\"));\n\t\t\t\tfor l in range(ntimes):\n\t\t\t\t\tsheet[inspos].append(val);\n\t\t\t\t\tinspos+=1;\n\t\t\t\t\n\n\t\tself.sheets[name] = sheet;" }, { "alpha_fraction": 0.5476821064949036, "alphanum_fraction": 0.556291401386261, "avg_line_length": 31.826086044311523, "blob_id": "c7b8aea890e1ac929feaf80642d74d3988e275e0", "content_id": "b484bb48753dee452a7de48ff651c428b0cd11e0", "detected_licenses": [ "MIT", "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1510, "license_type": "permissive", "max_line_length": 90, "num_lines": 46, "path": "/phpsnip/googleblogger.inc", "repo_name": "jjh42/jjhsnip", "src_encoding": "UTF-8", "text": "<?php\nrequire_once(\"HTTP/Request.php\");\n\n\nfunction publish_to_blog($head, $content, $labels, $blogid, $gauth, $name, $email)\n// Publish the post with heading, content and labels to Blogger (Beta).\n{ \n\n $xml = \"<entry xmlns=\\\"http://www.w3.org/2005/Atom\\\">\n <category scheme=\\\"http://www.blogger.com/atom/ns#\\\" term=\\\"\" . $labels . \"\\\" />\n <title type=\\\"text\\\">\" . $head . \"</title>\n <content type=\\\"xhtml\\\">\n <div xmlns=\\\"http://www.w3.org/1999/xhtml\\\">\" . $content . \"</div>\n </content> \n <author>\n <name>\".$name .\"</name>\n <email>\".$email.\"</email>\n </author>\n </entry>\";\n\n $url = \"http://www.blogger.com/feeds/\".$blogid.\"/posts/default\";\n\n // Allow for redirects\n // Okay now build the post\n $req = & new HTTP_Request($url, array('allowRedirects' => true));\n $req->addHeader(\"Authorization\", \"GoogleLogin Auth=\" . $gauth);\n $req->addHeader(\"Content-Type\", \"application/atom+xml\");\n $req->setMethod(HTTP_REQUEST_METHOD_POST);\n $req->addRawPostData($xml, true);\n\n $reqstr = $req->_buildRequest();\n $resp = $req->sendRequest();\n if (PEAR::isError($resp)) {\n die(\"Error logging into google - error \" . $req->getResponseCode());\n }\n \t\n // Need to read the google response\n if ($req->getResponseCode() != 201) {\n\techo \"Error publishing\\n<br>\";\n echo \"Code was \". $req->getResponseCode();\n\techo $req->getResponseBody();\n }\n\n}\n\n?>\n" }, { "alpha_fraction": 0.6046720743179321, "alphanum_fraction": 0.6118598580360413, "avg_line_length": 27.538461685180664, "blob_id": "017e6b7e548fa5301eea9904442189fd40b4420c", "content_id": "ddfa16b41904f7f9b584518925ea3303d205bdfb", "detected_licenses": [ "MIT", "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1113, "license_type": "permissive", "max_line_length": 81, "num_lines": 39, "path": "/phpsnip/gauth.inc", "repo_name": "jjh42/jjhsnip", "src_encoding": "UTF-8", "text": "<?php\nrequire_once \"HTTP/Request.php\";\n\nfunction get_google_login($emailad, $passwd, $service) {\n $gloginurl=\"https://www.google.com/accounts/ClientLogin\";\n\n $req = & new HTTP_Request($gloginurl);\n $req->addHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n $req->setMethod(HTTP_REQUEST_METHOD_POST);\n $req->addPostData(\"Email\", $emailad);\n $req->addPostData(\"Passwd\", $passwd);\n $req->addPostData(\"service\", $service);\n $req->addPostData(\"source\", \"quarks-mybooks-0.1\");\n $req->addPostData(\"accountType\", \"GOOGLE\");\n\n if (PEAR::isError($req->sendRequest())) {\n\tdie(\"Error logging into google with error \" . $req->getResposneCode() . \"<br>\");\n }\n \t\n // Need to read the google response\n if ($req->getResponseCode() != 200) {\n\techo \"Error authenticating\\n<br>\";\n\techo $req->getResponseBody();\n }\n \n // Now we need to extrac the auth key\n $body = $req->getResponseBody();\n $sres = preg_match(\"/Auth=(.*)/\", $body, $matches);\n\n if($sres == 0) {\n die(\"Error logging into google 2.\");\n }\n $key = $matches[1];\n\n return $key;\n}\n\n\n?>\n" } ]
3
sagnik10/PragatishilCGECians
https://github.com/sagnik10/PragatishilCGECians
65d275f284a48b687ed298451e94bcbf17035832
e6f55eb92c1b871c6909715e1614fa67ea8ad0f3
15ee170083caf333146fece5178217c5c534ce81
refs/heads/main
2023-05-08T01:44:16.090195
2021-05-28T07:36:21
2021-05-28T07:36:21
371,619,844
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.542553186416626, "alphanum_fraction": 0.5829787254333496, "avg_line_length": 21.380952835083008, "blob_id": "909572e3babf1e861f456521a5a0a523de300ee4", "content_id": "69cb6a8e8a726941840dbf0c0bf551210d6bed92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 49, "num_lines": 21, "path": "/PragatishilCGECians/Literarry_CLub/migrations/0007_auto_20210408_1258.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-04-08 07:28\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Literarry_CLub', '0006_peptalksusers'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='PepTalksUsers',\n new_name='PepTalksUserModel',\n ),\n migrations.RenameModel(\n old_name='SignUpModel',\n new_name='PragatishilModel',\n ),\n ]\n" }, { "alpha_fraction": 0.7075180411338806, "alphanum_fraction": 0.7075180411338806, "avg_line_length": 41.21739196777344, "blob_id": "49d454a1c7be56de065cac15312fef27a2e17ac2", "content_id": "4c985aafc6c2f154a79f321a69eae647011f96de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 971, "license_type": "no_license", "max_line_length": 63, "num_lines": 23, "path": "/PragatishilCGECians/Literarry_CLub/urls.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home),\n path('main_page/', views.main_page),\n path('register/', views.register),\n path('peptalks/',views.peptalks),\n path('peptalksregister/',views.peptalksregister),\n path('Arietta_Home_Page/',views.Arietta_Home_Page),\n path('Arietta_Register/',views.Arietta_Register),\n path('Debate_Home_Page/',views.Debate_Home_Page),\n path('Debate_Register/',views.Debate_Register),\n path('Literarry_Home_Page/',views.Literarry_Home_Page),\n path('Literarry_Register/',views.Literarry_Register),\n path('Pratibimba_Home_Page/',views.Pratibimba_Home_Page),\n path('Pratibimba_Register/',views.Pratibimba_Register),\n path('Rongmilanti_Home_Page/',views.Rongmilanti_Home_Page),\n path('Rongmilanti_Register/',views.Rongmilanti_Register),\n path('Techonics_Home_Page/',views.Techonics_Home_Page),\n path('Techonics_Register/',views.Techonics_Register),\n \n]\n" }, { "alpha_fraction": 0.6496670842170715, "alphanum_fraction": 0.6694958806037903, "avg_line_length": 66.33004760742188, "blob_id": "2c5837d383c126f5d3f349431ba2755b1f4922aa", "content_id": "b54e5a32fba9c3d10a3605962ae9a2469b5a7aa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13667, "license_type": "no_license", "max_line_length": 690, "num_lines": 203, "path": "/PragatishilCGECians/Literarry_CLub/views.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .forms import PragatishilModelForm,PepTalksUserModelForm,AriettaUserModelForm,DebateUserModelForm,LiterarryUserModelForm,PratibimbaUserModelForm,RongmilantiUserModelForm,TechonicsUserModelForm\nfrom django.conf import settings\nfrom .models import PragatishilModel,PepTalksUserModel,AriettaUserModel,DebateUserModel,LiterarryUserModel,PratibimbaUserModel,RongmilantiUserModel,TechonicsUserModel\nfrom django.core.mail import EmailMultiAlternatives\n\ndef home(request):\n return render(request, 'welcome_page_pragatishils.html')\n\n\ndef main_page(request):\n return render(request, 'PragatishilCGECians_Home_Page.html')\n\n\ndef register(request):\n if request.method == 'POST':\n form = PragatishilModelForm(request.POST)\n if form.is_valid(): \n name = form.cleaned_data.get('name')\n email = form.cleaned_data.get('email')\n user = PragatishilModel(name = name, email = email)\n subject = 'welcome to PragatishilCGECians'\n message = f'Hi {user.name}'\n html_content='<br><div><img src=\"https://drive.google.com/uc?export=download&id=14q6aQNKwqqBiQdavOlasY3gczm40y_R_\" style=\"width:100%; height: 700px; position: relative;\"></div><br> thank you for registering in PragatishilCGECians. Its glad to hear from you and thanks for asking to be a part of us. Your credentials are with us and we will mail you if you are considered to be a part of us.for more details you can contact with<br><br><div><img src=\"https://drive.google.com/uc?export=download&id=17OPSdMsQ8k0-b1Fa8Z-ONIIZ0ARhkOEe\" style=\"width:100%; height: 700px; position: relative;\"></div><br><br> <b>Tapasree Kait</b>, contact number- 8420913317. <br>Thank You.'\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [user.email]\n msg=EmailMultiAlternatives( subject, message, email_from, recipient_list)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n form.save() \n return render(request, 'PragatishilCGECians_Home_Page.html')\n else:\n form = PragatishilModelForm()\n return render(request, 'pragatishil_register.html', {'form': form})\n\ndef peptalks(request):\n return render(request,'PEP-TALKS.html')\n\ndef peptalksregister(request):\n if request.method == 'POST':\n form = PepTalksUserModelForm(request.POST)\n if form.is_valid(): \n name = form.cleaned_data.get('name')\n email = form.cleaned_data.get('email')\n user = PepTalksUserModel(name = name, email = email)\n subject = 'welcome to PepTalks CGEC'\n message = f'Hi {user.name}'\n html_content='<br><div><img src=\"https://drive.google.com/uc?export=download&id=14qd7cYWZG3TgV-IkS8Vj8uO8DwrzzugW\" style=\"width:100%; height: 700px; position: relative;\"></div><br> thank you for registering in PepTalks CGEC. Its glad to hear from you and thanks for asking to be a part of us. Your credentials are with us and we will mail you if you are considered to be a part of us.for more details you can contact with<br><br><div><img src=\"https://drive.google.com/uc?id=1sVDI--4tLutfDvEut4jH1dZxDyH9S1Ju\" style=\"width:100%; height: 700px; position: relative;\"></div><br><br> <b>Sagnik Sen</b>, contact number- 6295862826. <br>Thank You.'\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [user.email]\n msg=EmailMultiAlternatives( subject, message, email_from, recipient_list)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n form.save() \n return render(request, 'PEP-TALKS.html')\n else:\n form = PepTalksUserModelForm()\n return render(request, 'peptalksregister.html', {'form': form})\n\ndef Arietta_Home_Page(request):\n return render(request,'Arietta_Home_Page.html')\n\ndef Arietta_Register(request):\n if request.method == 'POST':\n form = AriettaUserModelForm(request.POST)\n if form.is_valid(): \n name = form.cleaned_data.get('name')\n email = form.cleaned_data.get('email')\n user = AriettaUserModel(name = name, email = email)\n subject = 'welcome to Arietta Music Club CGEC'\n message = f'Hi {user.name}'\n html_content='<br><div><img src=\" https://drive.google.com/uc?export=download&id=1N-x1v8KBl-rQ8m-ND1YHIuvnUJJuQibS\" style=\"width:100%; height: 700px; position: relative;\"></div><br> thank you for registering in Arietta Music Club CGEC. Its glad to hear from you and thanks for asking to be a part of us. Your credentials are with us and we will mail you if you are considered to be a part of us.for more details you can contact with<br><br><div><img src=\"https://drive.google.com/uc?export=download&id=1uiRO28NRqwGstYgmiLuwzU4dopNJbXQW\" style=\"width:100%; height: 700px; position: relative;\"></div><br><br> <b>Ayan Chakrabarty</b>, contact number- 7477868319. <br>Thank You.'\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [user.email]\n msg=EmailMultiAlternatives( subject, message, email_from, recipient_list)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n form.save() \n return render(request, 'Arietta_Home_Page.html')\n else:\n form = AriettaUserModelForm()\n return render(request, 'Arietta_Register.html', {'form': form})\n\n\ndef Debate_Home_Page(request):\n return render(request,'Debate_Home_Page.html')\n\ndef Debate_Register(request):\n if request.method == 'POST':\n form = DebateUserModelForm(request.POST)\n if form.is_valid(): \n name = form.cleaned_data.get('name')\n email = form.cleaned_data.get('email')\n user = DebateUserModel(name = name, email = email)\n subject = 'welcome to Debate Club CGEC'\n message = f'Hi {user.name}'\n html_content='<br><div><img src=\" https://drive.google.com/uc?export=download&id=1xgL1gRbgHZhfU4IR1GJX225hKoM6kAp1\" style=\"width:100%; height: 700px; position: relative;\"></div><br> thank you for registering in Debate Club CGEC. Its glad to hear from you and thanks for asking to be a part of us. Your credentials are with us and we will mail you if you are considered to be a part of us.for more details you can contact with<br><br><div><img src=\"https://drive.google.com/uc?id=1Nxkm9eVUWObTi5S9sJWI3P13KgD9ReB1\" style=\"width:100%; height: 700px; position: relative;\"></div><br><br> <b>Sahasrak Bhattacharya</b>, contact number- 9064309163. <br>Thank You.'\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [user.email]\n msg=EmailMultiAlternatives( subject, message, email_from, recipient_list)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n form.save() \n return render(request, 'Debate_Home_Page.html')\n else:\n form = DebateUserModelForm()\n return render(request, 'Debate_Register.html', {'form': form})\n\ndef Literarry_Home_Page(request):\n return render (request,'Literarry_Club_Home_Page.html')\n\ndef Literarry_Register(request):\n if request.method == 'POST':\n form = LiterarryUserModelForm(request.POST)\n if form.is_valid(): \n name = form.cleaned_data.get('name')\n email = form.cleaned_data.get('email')\n user = LiterarryUserModel(name = name, email = email)\n subject = 'welcome to Creative Pens CGEC'\n message = f'Hi {user.name}'\n html_content='<br><div><img src=\" https://drive.google.com/uc?export=download&id=1-3xNdQV0tGBdb5l4iERE5EfnE3rmlFRq\" style=\"width:100%; height: 700px; position: relative;\"></div><br> thank you for registering iat Creative Pens CGEC. Its glad to hear from you and thanks for asking to be a part of us. Your credentials are with us and we will mail you if you are considered to be a part of us.for more details you can contact with<br><br><div><img src=\"https://drive.google.com/uc?id=1QP87qNH5x3_HhhruatzaYvx49mhJvETM\" style=\"width:100%; height: 700px; position: relative;\"></div><br><br> <b>Swatilekha Roy</b>, contact number- 8637813901. <br>Thank You.'\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [user.email]\n msg=EmailMultiAlternatives( subject, message, email_from, recipient_list)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n form.save() \n return render(request, 'Literarry_Club_Home_Page.html')\n else:\n form = LiterarryUserModelForm()\n return render(request, 'Literarry_Register.html', {'form': form})\n\ndef Pratibimba_Home_Page(request):\n return render (request,'Pratibimba_Home_Page.html')\n\ndef Pratibimba_Register(request):\n if request.method == 'POST':\n form = PratibimbaUserModelForm(request.POST)\n if form.is_valid(): \n name = form.cleaned_data.get('name')\n email = form.cleaned_data.get('email')\n user = PratibimbaUserModel(name = name, email = email)\n subject = 'welcome to Pratibimba Theatre Group CGEC'\n message = f'Hi {user.name}'\n html_content='<br><div><img src=\"https://drive.google.com/uc?export=download&id=1jOPUT_1tSHjtbKsIWLtN6HetRTpC-FRW\" style=\"width:100%; height: 700px; position: relative;\"></div><br> thank you for registering iat Pratibimba Theatre Group CGEC. Its glad to hear from you and thanks for asking to be a part of us. Your credentials are with us and we will mail you if you are considered to be a part of us.for more details you can contact with<br><br><div><img src=\"https://drive.google.com/uc?export=download&id=17OPSdMsQ8k0-b1Fa8Z-ONIIZ0ARhkOEe\" style=\"width:100%; height: 700px; position: relative;\"></div><br><br> <b>Tapasree Kait</b>, contact number- 8420913317. <br>Thank You.'\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [user.email]\n msg=EmailMultiAlternatives( subject, message, email_from, recipient_list)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n form.save() \n return render(request, 'Pratibimba_Home_Page.html')\n else:\n form = PratibimbaUserModelForm()\n return render(request, 'Pratibimba_Register.html', {'form': form})\n\ndef Rongmilanti_Home_Page(request):\n return render (request,'Rongmilanti_Home_Page.html')\n\ndef Rongmilanti_Register(request):\n if request.method == 'POST':\n form = RongmilantiUserModelForm(request.POST)\n if form.is_valid(): \n name = form.cleaned_data.get('name')\n email = form.cleaned_data.get('email')\n user = RongmilantiUserModel(name = name, email = email)\n subject = 'welcome to Rongmilanti CGEC'\n message = f'Hi {user.name}'\n html_content='<br><div><img src=\"https://drive.google.com/uc?export=download&id=1-aAsW0RqfYv1sDzpUb2uM_Z5yB_Ogxun\" style=\"width:100%; height: 700px; position: relative;\"></div><br> thank you for registering at Rongmilanti CGEC. Its glad to hear from you and thanks for asking to be a part of us. Your credentials are with us and we will mail you if you are considered to be a part of us.for more details you can contact with<br><br><div><img src=\"https://drive.google.com/uc?id=1MMqxwF_GbY3XelpJom5gvxvQAOkNP7Yb\" style=\"width:100%; height: 700px; position: relative;\"></div><br><br> <b>Soumyajeet Sinha</b>, contact number- 7872403006. <br>Thank You.'\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [user.email]\n msg=EmailMultiAlternatives( subject, message, email_from, recipient_list)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n form.save() \n return render(request, 'Rongmilanti_Home_Page.html')\n else:\n form = RongmilantiUserModelForm()\n return render(request, 'Rongmilanti_Register.html', {'form': form})\n\ndef Techonics_Home_Page(request):\n return render (request,'Techonics_Home_Page.html')\n\ndef Techonics_Register(request):\n if request.method == 'POST':\n form = TechonicsUserModelForm(request.POST)\n if form.is_valid(): \n name = form.cleaned_data.get('name')\n email = form.cleaned_data.get('email')\n user = TechonicsUserModel(name = name, email = email)\n subject = 'welcome to Techonics CGEC'\n message = f'Hi {user.name}'\n html_content='<br><div><img src=\"https://drive.google.com/uc?export=download&id=1g-v_SftT_duePEbmIEuTaOxewoniLG5w\" style=\"width:100%; height: 700px; position: relative;\"></div><br> thank you for registering at Techonics CGEC. Its glad to hear from you and thanks for asking to be a part of us. Your credentials are with us and we will mail you if you are considered to be a part of us.for more details you can contact with<br><br><div><img src=\"https://drive.google.com/uc?id=19NioX3rpmxUfF612GtOEcAYRlwd0mfms\" style=\"width:100%; height: 700px; position: relative;\"></div><br><br> <b>Ayush Gupta</b>, contact number- 8927246040. <br>Thank You.'\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [user.email]\n msg=EmailMultiAlternatives( subject, message, email_from, recipient_list)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n form.save() \n return render(request, 'Techonics_Home_Page.html')\n else:\n form = TechonicsUserModelForm()\n return render(request, 'Techonics_Register.html', {'form': form})" }, { "alpha_fraction": 0.563076913356781, "alphanum_fraction": 0.6215384602546692, "avg_line_length": 19.3125, "blob_id": "142c0f34ea61232d39cebde81478f479d50c2f41", "content_id": "d91e4ed9d4e65efbb854df433497b2ec649b5132", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/PragatishilCGECians/Literarry_CLub/migrations/0003_delete_customuserform.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.6 on 2021-02-08 11:23\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Literarry_CLub', '0002_remove_customuserform_why_join_us'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='CustomUserForm',\n ),\n ]\n" }, { "alpha_fraction": 0.6912000179290771, "alphanum_fraction": 0.6912000179290771, "avg_line_length": 26.799999237060547, "blob_id": "57bc1d7a14f1d0684977b2ff8527733a47f24a23", "content_id": "45d4c6b28a51c2829ad0aca2a35cc70b5af92675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1250, "license_type": "no_license", "max_line_length": 166, "num_lines": 45, "path": "/PragatishilCGECians/Literarry_CLub/forms.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import PragatishilModel,PepTalksUserModel,AriettaUserModel,DebateUserModel,LiterarryUserModel,PratibimbaUserModel,TechonicsUserModel,RongmilantiUserModel\n\n\n# create a ModelForm\nclass PragatishilModelForm(forms.ModelForm):\n # specify the name of model to use\n class Meta:\n model = PragatishilModel\n fields = \"__all__\"\n\nclass PepTalksUserModelForm(forms.ModelForm):\n class Meta:\n model = PepTalksUserModel\n fields = \"__all__\"\n\nclass AriettaUserModelForm(forms.ModelForm):\n class Meta:\n model = AriettaUserModel\n fields = \"__all__\"\n\nclass DebateUserModelForm(forms.ModelForm):\n class Meta:\n model = DebateUserModel\n fields = \"__all__\"\n\nclass LiterarryUserModelForm(forms.ModelForm):\n class Meta:\n model = LiterarryUserModel\n fields = \"__all__\"\n\nclass PratibimbaUserModelForm(forms.ModelForm):\n class Meta:\n model = PratibimbaUserModel\n fields = \"__all__\"\n\nclass RongmilantiUserModelForm(forms.ModelForm):\n class Meta:\n model = RongmilantiUserModel\n fields = \"__all__\"\n\nclass TechonicsUserModelForm(forms.ModelForm):\n class Meta:\n model = TechonicsUserModel\n fields = \"__all__\"" }, { "alpha_fraction": 0.5311572551727295, "alphanum_fraction": 0.5875371098518372, "avg_line_length": 18.823530197143555, "blob_id": "e28d4cf5d6c19ca47507e4f18bcd9e476744548b", "content_id": "ce5f0735d9f547f822ddd339fd89506acc1a22fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 337, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/PragatishilCGECians/Literarry_CLub/migrations/0002_remove_customuserform_why_join_us.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.6 on 2021-02-08 10:58\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Literarry_CLub', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='customuserform',\n name='why_join_us',\n ),\n ]\n" }, { "alpha_fraction": 0.6825745701789856, "alphanum_fraction": 0.720251202583313, "avg_line_length": 28.5, "blob_id": "10882eea1d68adb3b1ee0ff11dab0b82fcb1e9f8", "content_id": "9d8c3d3e02f4a8a7f3032376a28c53239cb3664e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3185, "license_type": "no_license", "max_line_length": 51, "num_lines": 108, "path": "/PragatishilCGECians/Literarry_CLub/models.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\n# declare a new model with a name \"GeeksModel\"\nclass PragatishilModel(models.Model):\n # fields of the model\n name = models.CharField(max_length=200)\n email=models.EmailField(max_length=200)\n admission_year=models.CharField(max_length=30)\n your_department=models.CharField(max_length=50)\n contact_number=models.CharField(max_length=13)\n description = models.CharField(max_length=200)\n\n\n def __str__(self):\n return self.name\n\n\nclass PepTalksUserModel(models.Model):\n\n name = models.CharField(max_length=200)\n email=models.EmailField(max_length=200)\n admission_year=models.CharField(max_length=30)\n your_department=models.CharField(max_length=50)\n contact_number=models.CharField(max_length=13)\n description = models.CharField(max_length=200)\n\n\n def __str__(self):\n return self.name\n\nclass AriettaUserModel(models.Model):\n\n name = models.CharField(max_length=200)\n email=models.EmailField(max_length=200)\n admission_year=models.CharField(max_length=30)\n your_department=models.CharField(max_length=50)\n contact_number=models.CharField(max_length=13)\n description = models.CharField(max_length=200)\n\n\n def __str__(self):\n return self.name\n\nclass DebateUserModel(models.Model):\n\n name = models.CharField(max_length=200)\n email=models.EmailField(max_length=200)\n admission_year=models.CharField(max_length=30)\n your_department=models.CharField(max_length=50)\n contact_number=models.CharField(max_length=13)\n description = models.CharField(max_length=200)\n\n\n def __str__(self):\n return self.name\n\nclass LiterarryUserModel(models.Model):\n\n name = models.CharField(max_length=200)\n email=models.EmailField(max_length=200)\n admission_year=models.CharField(max_length=30)\n your_department=models.CharField(max_length=50)\n contact_number=models.CharField(max_length=13)\n description = models.CharField(max_length=200)\n\n\n def __str__(self):\n return self.name\n\nclass RongmilantiUserModel(models.Model):\n\n name = models.CharField(max_length=200)\n email=models.EmailField(max_length=200)\n admission_year=models.CharField(max_length=30)\n your_department=models.CharField(max_length=50)\n contact_number=models.CharField(max_length=13)\n description = models.CharField(max_length=200)\n\n\n def __str__(self):\n return self.name\n \nclass PratibimbaUserModel(models.Model):\n\n name = models.CharField(max_length=200)\n email=models.EmailField(max_length=200)\n admission_year=models.CharField(max_length=30)\n your_department=models.CharField(max_length=50)\n contact_number=models.CharField(max_length=13)\n description = models.CharField(max_length=200)\n\n\n def __str__(self):\n return self.name\n\nclass TechonicsUserModel(models.Model):\n\n name = models.CharField(max_length=200)\n email=models.EmailField(max_length=200)\n admission_year=models.CharField(max_length=30)\n your_department=models.CharField(max_length=50)\n contact_number=models.CharField(max_length=13)\n description = models.CharField(max_length=200)\n\n\n def __str__(self):\n return self.name" }, { "alpha_fraction": 0.7745097875595093, "alphanum_fraction": 0.7745097875595093, "avg_line_length": 19.399999618530273, "blob_id": "d93a99c8e0d98a47cb7ebf930717dc959737384d", "content_id": "f208e07c7fd307ae6121d4044fdda984e186bdfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 37, "num_lines": 5, "path": "/PragatishilCGECians/Literarry_CLub/apps.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass LiterarryClubConfig(AppConfig):\n name = 'Literarry_CLub'\n" }, { "alpha_fraction": 0.7867902517318726, "alphanum_fraction": 0.7867902517318726, "avg_line_length": 49.79411697387695, "blob_id": "9cfe51821f78adb7b0d2cb55cd923af3c434b3ac", "content_id": "bc14b6c44cff816973bacd704df88c480c7d2dfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1726, "license_type": "no_license", "max_line_length": 166, "num_lines": 34, "path": "/PragatishilCGECians/Literarry_CLub/admin.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import PragatishilModel,PepTalksUserModel,AriettaUserModel,DebateUserModel,LiterarryUserModel,PratibimbaUserModel,RongmilantiUserModel,TechonicsUserModel\n\nclass PragatishilAdmin(admin.ModelAdmin):\n fields = ('name','email','admission_year','your_department','contact_number','description')\nadmin.site.register(PragatishilModel, PragatishilAdmin)\n\nclass PEPAdmin(admin.ModelAdmin):\n fields = ('name','email','admission_year','your_department','contact_number','description')\nadmin.site.register(PepTalksUserModel, PEPAdmin)\n\nclass AriettaAdmin(admin.ModelAdmin):\n fields = ('name','email','admission_year','your_department','contact_number','description')\nadmin.site.register(AriettaUserModel, AriettaAdmin)\n\nclass DebateAdmin(admin.ModelAdmin):\n fields = ('name','email','admission_year','your_department','contact_number','description')\nadmin.site.register(DebateUserModel, DebateAdmin)\n\nclass LiterarryAdmin(admin.ModelAdmin):\n fields = ('name','email','admission_year','your_department','contact_number','description')\nadmin.site.register(LiterarryUserModel, LiterarryAdmin)\n\nclass PratibimbaAdmin(admin.ModelAdmin):\n fields = ('name','email','admission_year','your_department','contact_number','description')\nadmin.site.register(PratibimbaUserModel, PratibimbaAdmin)\n\nclass RongmilantiAdmin(admin.ModelAdmin):\n fields = ('name','email','admission_year','your_department','contact_number','description')\nadmin.site.register(RongmilantiUserModel, RongmilantiAdmin)\n\nclass TechonicsAdmin(admin.ModelAdmin):\n fields = ('name','email','admission_year','your_department','contact_number','description')\nadmin.site.register(TechonicsUserModel, TechonicsAdmin)" }, { "alpha_fraction": 0.5189148783683777, "alphanum_fraction": 0.5490293502807617, "avg_line_length": 46.27058792114258, "blob_id": "14a0232f8566bdcc89a738b76c53995a3de9fc05", "content_id": "ded0282ff112365e75ea6e504e6473ed801f8fb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4018, "license_type": "no_license", "max_line_length": 114, "num_lines": 85, "path": "/PragatishilCGECians/Literarry_CLub/migrations/0008_ariettausermodel_debateusermodel_literarryusermodel_pratibimbausermodel_rongmilantiusermodel_techoni.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-04-11 08:26\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Literarry_CLub', '0007_auto_20210408_1258'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AriettaUserModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('email', models.EmailField(max_length=200)),\n ('admission_year', models.CharField(max_length=30)),\n ('your_department', models.CharField(max_length=50)),\n ('contact_number', models.CharField(max_length=13)),\n ('description', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='DebateUserModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('email', models.EmailField(max_length=200)),\n ('admission_year', models.CharField(max_length=30)),\n ('your_department', models.CharField(max_length=50)),\n ('contact_number', models.CharField(max_length=13)),\n ('description', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='LiterarryUserModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('email', models.EmailField(max_length=200)),\n ('admission_year', models.CharField(max_length=30)),\n ('your_department', models.CharField(max_length=50)),\n ('contact_number', models.CharField(max_length=13)),\n ('description', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='PratibimbaUserModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('email', models.EmailField(max_length=200)),\n ('admission_year', models.CharField(max_length=30)),\n ('your_department', models.CharField(max_length=50)),\n ('contact_number', models.CharField(max_length=13)),\n ('description', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='RongmilantiUserModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('email', models.EmailField(max_length=200)),\n ('admission_year', models.CharField(max_length=30)),\n ('your_department', models.CharField(max_length=50)),\n ('contact_number', models.CharField(max_length=13)),\n ('description', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='TechonicsUserModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('email', models.EmailField(max_length=200)),\n ('admission_year', models.CharField(max_length=30)),\n ('your_department', models.CharField(max_length=50)),\n ('contact_number', models.CharField(max_length=13)),\n ('description', models.CharField(max_length=200)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5214152932167053, "alphanum_fraction": 0.5623835921287537, "avg_line_length": 22.34782600402832, "blob_id": "3ba97b4520846ee7b4c3221e6333526bb6223795", "content_id": "d9741725d40e82e175412c6c5f0a3bd99e9d386c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 537, "license_type": "no_license", "max_line_length": 51, "num_lines": 23, "path": "/PragatishilCGECians/Literarry_CLub/migrations/0005_auto_20210329_1548.py", "repo_name": "sagnik10/PragatishilCGECians", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-29 10:18\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Literarry_CLub', '0004_signupmodel'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='signupmodel',\n old_name='title',\n new_name='name',\n ),\n migrations.AlterField(\n model_name='signupmodel',\n name='description',\n field=models.CharField(max_length=200),\n ),\n ]\n" } ]
11
jairmj/complejidad-alg
https://github.com/jairmj/complejidad-alg
9a4743bfe7efdf0ae5fd9b45fbbf47749a397699
a3f6bdc5cf0ee644c4de797d72b55a042c6caca1
077a0e3986ad623a09ffb33104e4137a90de6a10
refs/heads/main
2023-04-22T11:50:36.281488
2021-04-26T17:27:34
2021-04-26T17:27:34
352,712,967
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47983014583587646, "alphanum_fraction": 0.4851379990577698, "avg_line_length": 21.452381134033203, "blob_id": "a2820dc1b32c117b303256c63d7422b414e10d07", "content_id": "a10657af6b7daf76786eba41d3c604bc23c76ad5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 55, "num_lines": 42, "path": "/Grafos/RecorridoGrafos.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "import graphstuff as gs\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = nx.read_adjlist('grafo2.txt')\nnx.draw(G, with_labels = True)\nplt.show()\n\n\ndef bfs(G, s):\n n = G.order()\n visited = [False]*n\n path = [None]*n\n queue = [s]\n visited[s] = True\n while len(queue) > 0:\n u = int(queue[0])\n queue.pop(0)\n for v in G.neighbors(str(u)):\n v = int(v)\n if not visited[v]:\n visited[v] = True\n path[v] = u\n queue.append(v)\n return visited, path\n\n\ndef dfs(G, s, b = True, visited = [], path = []):\n if b:\n n = G.order()\n visited = [False]*n\n path = [None]*n\n visited[s] = True\n for v in G.neighbors(str(s)):\n v = int(v)\n if not visited[v]:\n path[v] = s\n path = dfs(G, int(v), False, visited, path)\n return path\n\npath = dfs(G, 3)\nprint(path)" }, { "alpha_fraction": 0.5014164447784424, "alphanum_fraction": 0.5070821642875671, "avg_line_length": 27.648649215698242, "blob_id": "804a50324d3b7fa4d424438b3cbe6e8741b7d48f", "content_id": "ea3fb7cbc3657a057b9e25f88fc96157604ab65a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1059, "license_type": "no_license", "max_line_length": 54, "num_lines": 37, "path": "/Grafos/Dijkstra.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "import graphstuff as gs\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport math\nimport heapq as hq\n\nG = nx.read_adjlist('grafo2.txt')\nnx.draw(G, with_labels = True)\nplt.show()\n\n\ndef ucs(G, s):\n for u in G.nodes:\n G.nodes[u]['visited'] = False\n G.nodes[u]['path'] = -1\n G.nodes[u]['cost'] = math.inf\n\n G.node[s]['cost'] = 0\n queue = []\n hq.heappush(queue, (0, s)) # Cola pero ordenada :O\n\n while queue: #Mientras haya algo en la cola\n g, u = hp.heappop(queue)\n if G.nodes[u]['visited']: continue\n G.nodes[u]['visited'] = True\n for v in G.neighbors(str(u)):\n if not G.nodes[v]['visited']:\n w = G.edge[(u, v)]['weight']\n f = g + w\n if f < G.nodes[v]['cost']:\n G.nodes[v]['cost'] = f\n G.nodes[v]['path'] = u\n hq.heappush(queue, (f, v))\n wPath = [(0, 0)]*G.number_of_nodes()\n for v, info in G.nodes.data():\n wPath[v] = (info['path'], info['cost'])\n return wPath" }, { "alpha_fraction": 0.6600331664085388, "alphanum_fraction": 0.6699833869934082, "avg_line_length": 32.55555725097656, "blob_id": "363b0c7d2c61464c9fa8753dbfa47187f80d46ed", "content_id": "9fe1d8824da69f051b23cff6591722dab46d2916", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 603, "license_type": "no_license", "max_line_length": 83, "num_lines": 18, "path": "/Algoritmos/Divide_and_c/Contador_palabras.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "def wc(lines, i, j):\n if i == j:\n return len(lines[i].strip().split(\" \"))\n med = (i + j) // 2\n return wc(lines, i, med) + wc(lines, med + 1, j)\n\ndef wordCount(text):\n lines = text.strip().split(\"\\n\")\n return wc(lines, 0, len(lines) - 1)\n#45 palabras\ntexto = \"\"\" \nAt quaeque adversarium ius, sed at integre persius verterem.\nSit summo tibique at, eam et fugit complectitur, vis te natum vivendum mandamus.\nIudico quodsi cum ad, dicit everti sensibus in sea, ea eius paulo deterruisset pri.\nPro id aliquam hendrerit definitiones. Per et legimus delectus.\n\"\"\"\n\nprint(wordCount(texto))" }, { "alpha_fraction": 0.3670412003993988, "alphanum_fraction": 0.43820226192474365, "avg_line_length": 16.866666793823242, "blob_id": "6ad7bedf145cdf1375e68e4e1e8683a8434b785b", "content_id": "a7219c4f171042ba2b250552b8e1573d3d604bc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 267, "license_type": "no_license", "max_line_length": 37, "num_lines": 15, "path": "/Algoritmos/Divide_and_c/max_ar.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "def max(a, i, j):\n if i == j:\n return a[i]\n\n med = (i+j)//2\n maxI = max(a, i, med)\n maxD = max(a, med +1 , j)\n if maxI > maxD:\n return maxI\n else:\n return maxD\n\na = [23, 42, 12, 4, 9, 13, 53, 23, 1]\n\nprint(max(a, 0, len(a) - 1))" }, { "alpha_fraction": 0.3702564239501953, "alphanum_fraction": 0.4287179410457611, "avg_line_length": 24.0256404876709, "blob_id": "187aa6b11911fcdc3f27c0fb228a6d75bed60a1c", "content_id": "64ea96fae4d2ac28c52ae03de6d471fcee747c7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 975, "license_type": "no_license", "max_line_length": 83, "num_lines": 39, "path": "/Algoritmos/Divide_and_c/Siluetas.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "import pdb #Debug\n\ndef add(res, tupla):\n if len(res) > 0:\n if res[-1][1] == tupla[1]:\n return\n if res[-1][0] == tupla[0]:\n res[-1] = (res[-1][0], max(res[-1][1], tupla[1]))\n return\n res.append(tupla)\n\ndef mergePL(a, b):\n res = []\n i, j = 0, 0\n Na, Nb = len(a), len(b)\n yleft, yright = 0, 0\n while i < Na or j < Nb:\n if j >= Nb or i < Na and a[i][0] < b[j][0]:\n x, yleft = a[i]\n i += 1\n else:\n x, yright = b[j]\n j += 1\n ymax = max(yleft, yright)\n add(res, (x, ymax))\n return res\n\ndef skyline(rects: list, i, f):\n if i == f:\n g, h, d = rects[i]\n return [(g, h), (d,0)]\n mid = (i + f) // 2\n pl1 = skyline(rects, i, mid)\n pl2 = skyline(rects, mid + 1, f)\n return mergePL(pl1, pl2)\n\nrects = [(3, 13, 9), (1, 11, 5), (19, 18, 22), (3, 6, 7), (16, 3, 25), (12, 7, 16)]\n\nprint(skyline(rects, 0, len(rects) - 1))" }, { "alpha_fraction": 0.5403226017951965, "alphanum_fraction": 0.5540322661399841, "avg_line_length": 23.81999969482422, "blob_id": "3460af6b8a1dd1b92b3c15a19e747d5bbf41b37c", "content_id": "5141de75c63da516f3457207e13cb0c33f00b535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1240, "license_type": "no_license", "max_line_length": 80, "num_lines": 50, "path": "/Grafos/GrafoAleatorio.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "# Generar una matriz aleatoria de adyacencia para G\n# Generar una lista aleatoria de adyacencia para G\nimport numpy as np\nimport random\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n#Matriz de adyacencia\ndef Matriz_adyacencia():\n n = 10\n G = np.random.randint(2, size = (n, n))\n print(G)\n\n G2 = [[random.randint(0,1) for _ in range(n)] for _ in range (n)]\n print(G2)\n\n G = nx.from_numpy_matrix(G)\n nx.draw(G, with_labels = True, node_color = \"black\", font_color = \"White\")\n plt.show()\n\n#Lista de adyacencia\ndef ListaAdyacencia():\n n, m = 10, 20\n\n lst = [[]for _ in range(n)]\n\n for _ in range(m):\n u = random.randint(0, n-1)\n while True:\n v = random.randint(0, n-1)\n if not v in lst[u] and v != u: \n break \n lst[u].append(v)\n\n f = open(\"1.txt\", \"w\")\n\n for u in range(n):\n print(u, *lst[u])\n ap = \"{}\".format(u)\n for i in lst[u]:\n ap = \"{} {}\".format(ap, i)\n ap = \"{}\\n\".format(ap)\n f.write(ap)\n\n f.close()\n \n Gra = nx.read_adjlist(\"1.txt\", create_using = nx.DiGraph)\n nx.draw(Gra, with_labels = True, node_color = \"black\", font_color = \"White\")\n plt.show()\nListaAdyacencia()" }, { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 23, "blob_id": "48a0b1f3176d91ea34036e8191923d183d6f0f9f", "content_id": "de3ae1cb4607d7c13631f0d1cf6370e26c927e49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/Algoritmos/Fuerza_bruta/ConectarCiudades.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "#pendiente para clase 4" }, { "alpha_fraction": 0.503496527671814, "alphanum_fraction": 0.5328671336174011, "avg_line_length": 22.09677505493164, "blob_id": "2825d032ae44871ed736cb8fead48b76fe02ed50", "content_id": "db99d9986724ba9b492770ea107e85f1c0dc78a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 715, "license_type": "no_license", "max_line_length": 67, "num_lines": 31, "path": "/Algoritmos/Backtracking/nQueens.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\ndef dibujar(t):\n n = len(t)\n tablero = np.zeros((n, n, 3))\n tablero += 0.8\n tablero[::2, ::2] = 1\n tablero[1::2, 1::2] = 1\n\n fig, ax = plt.subplots()\n ax.imshow(tablero, interpolation='nearest')\n\n for y, x in enumerate(t):\n ax.text(x, y, u'\\u2655', size=30, ha='center', va='center')\n\n ax.set(xticks=[], yticks = [])\n ax.axis('image')\n\n plt.show()\n \ndibujar([0, 2, -1, -1])\n\ndef isLegal(board, row, column):\n n = len(board)\n for i in range(row):\n if board[i] == column:\n return False\n dif = row - i\n if board[i] + diff == column or board[i] - dif == column:\n return False" }, { "alpha_fraction": 0.4921259880065918, "alphanum_fraction": 0.5433070659637451, "avg_line_length": 18.615385055541992, "blob_id": "e9ca613246057a0cbffb6512217b107b6396020d", "content_id": "23e4c1f78238f367d98ebd58e3ccf51bbc2b5d63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "no_license", "max_line_length": 46, "num_lines": 13, "path": "/Ejercicio2.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "#Se sobreentiende que tenemos los coeficientes\n\na = [10, 20, 0, 1, 23, 4]\n\ndef p(x, coefs):\n sum = 0.0\n #coefs.reverse()\n #n=len(a)\n for i, ai in enumerate(reversed(coefs)):\n sum += ai * x **i\n #n-=1\n return sum\nprint(p(2,a))" }, { "alpha_fraction": 0.42561984062194824, "alphanum_fraction": 0.45179063081741333, "avg_line_length": 22.45161247253418, "blob_id": "c40e200f5ee6d2ca4f427b220e39a0959eedebcc", "content_id": "606d02c8051766c8b93ad075d78cfad385b8edb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 726, "license_type": "no_license", "max_line_length": 53, "num_lines": 31, "path": "/Algoritmos/Fuerza_bruta/Ordenamiento.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "def selectionSort(A):\n n = len(A)\n for i in range(n-1):\n min_pos = i\n for j in range(i+1, n):\n if A[j] < A[min_pos]:\n min_pos = j\n if min_pos != i:\n A[min_pos], A[i] = A[i], A[min_pos] #swap\n\ndef bubbleSort(A):\n n = len(A)\n for i in range(n - 1):\n for j in range(n - 1 - i):\n if A[j] > A[j + 1]:\n A[j], A[j + 1] = A[j + 1], A[j]\n\ndef stringMatching(p, t):\n l = len(p)\n n = len(t)\n resultados = []\n for i in range(n - l):\n if p == t[i:i+l]:\n resultados.append(i)\n return resultados\n\n\nX = [3, 1, 5, 7, 2, 9, 10, 12, 11]\nprint(stringMatching('rac', 'abracadabracamal'))\nbubbleSort(X)\nprint(X)" }, { "alpha_fraction": 0.4677419364452362, "alphanum_fraction": 0.5219941139221191, "avg_line_length": 30.022727966308594, "blob_id": "2cfd10adaed50d0f993a03e6fd5607e17c74fb12", "content_id": "5d8112979dd589707e3315953826a9b72631a1ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1364, "license_type": "no_license", "max_line_length": 119, "num_lines": 44, "path": "/Grafos/Orden.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "import graphstuff as gs\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport math\nimport heapq as hq\n\ncolors = ['#37AB65', '#3DF735', '#AD6D70', '#EC2504', '#8C0B90', '#C0E4FF', '#27B502', '#7C60A8', '#CF95D7', '#145JKH']\n\nG = nx.DiGraph()\nG.add_node(0, label = \"undies\", color = colors[0])\nG.add_node(1, label = \"pants\", color = colors[1])\nG.add_node(2, label = \"belt\", color = colors[2])\nG.add_node(3, label = \"shirt\", color = colors[3])\nG.add_node(4, label = \"tie\", color = colors[4])\nG.add_node(5, label = \"jacket\", color = colors[5])\nG.add_node(6, label = \"socks\", color = colors[6])\nG.add_node(7, label = \"shoes\", color = colors[7])\nG.add_node(8, label = \"watch\", color = colors[8])\n\nG.add_edges_from([(0, 1), (0, 7),\n (1, 2), (1, 7),\n (2,5),\n (3, 2), (3, 4),\n (4, 5),\n (6, 7)])\n\ngs.nx2gv(G, nodeinfo = True).render(\"test.gv\", view = True)\n\ndef _dfs(G, u, ts):\n if not G.nodes[u][\"visited\"]:\n G.nodes[u][\"visited\"] = True\n for v in G.neighbors(u):\n if not G.nodes[v][\"visited\"]:\n _dfs(G, v, ts)\n ts.insert(0, G.nodes[u][\"label\"])\ndef toposort(G):\n for u in G.nodes():\n G.nodes[u][\"visited\"] = False\n ts = []\n for u in G.nodes():\n _dfs(G, u, ts)\n return ts\n\nprint(toposort(G))" }, { "alpha_fraction": 0.5092059969902039, "alphanum_fraction": 0.5212888121604919, "avg_line_length": 26.125, "blob_id": "8c07ced6216962f656c4602c5fa1f4bee86a0660", "content_id": "740984d9ee1a171f35b6badc843449f3fefe50fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1739, "license_type": "no_license", "max_line_length": 112, "num_lines": 64, "path": "/Grafos/DLS-ICS.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "import graphstuff as gs\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport math\nimport heapq as hq\n\nG = nx.read_adjlist('grafo3.txt', create_using = nx.DiGraph, nodetype = int)\nv = gs.nx2gv(G)\n#v.render('test.gv', view = True)\n\n\ndef _dls(G, u, limit):\n if limit > 0:\n if not G.nodes[u]['visited']:\n print(\"Nodo visitado: {}\".format(u))\n G.nodes[u]['visited'] = True\n for v in G.neighbors(u):\n if not G.nodes[v]['visited']:\n G.nodes[v]['reached'] = True\n G.nodes[v]['path'] = u\n _dls(G, v, limit - 1)\n\ndef dls(G, s, limit):\n for u in G.nodes:\n G.nodes[u]['visited'] = False\n G.nodes[u]['path'] = -1\n\n _dls(G, s, limit)\n\n path = [0]*G.number_of_nodes()\n for v, info in G.nodes.data():\n path[v] = info['path']\n return path\n\ndef ids(G, s, t):\n for u in G.nodes:\n G.nodes[u]['visited'] = False\n G.nodes[u]['reached'] = False\n G.nodes[u]['path'] = -1\n\n limit = 0\n while not G.nodes[t]['reached']:\n _dls(G, s, limit)\n limit += 1\n if not G.nodes[t]['reached']: #Si no lo encuentra reseteo para volver a hacer la llamada con otro límite\n for u in G.nodes:\n G.nodes[u]['visited'] = False\n G.nodes[u]['reached'] = False\n G.nodes[u]['path'] = -1\n\n\n path = [0]*G.number_of_nodes()\n for v, info in G.nodes.data():\n path[v] = info['path']\n return path\n\n\n# path = dls(G, 3, 400)\n# print(path)\n# gs.path2gv(path).render('test.gv', view = True)\n\npath = ids(G, 3, 12)\nprint(path)\ngs.path2gv(path, params = {'rankdir' : 'LR', 'size' : '5'}).render('test.gv', view = True)\n\n\n" }, { "alpha_fraction": 0.4208333194255829, "alphanum_fraction": 0.47083333134651184, "avg_line_length": 27.016666412353516, "blob_id": "b6cc74d14aa06715632b55b8b44b8822c520395a", "content_id": "3e5560f19d1824b7003663d62b3ac54a632a125d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1680, "license_type": "no_license", "max_line_length": 88, "num_lines": 60, "path": "/Algoritmos/Backtracking/Maze/mazeBuilder.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "import random\nimport numpy as np\n\nclass DisjointSet:\n def __init__(self, n):\n self.s = [-1]*n\n\n def find(self, a):\n if self.s[a] < 0:\n return a\n parent = self.find(self.s[a])\n self.s[a] = parent\n return parent\n\n def sameset(self, a, b):\n return self.find(a) == self.find(b)\n\n def union(self, a, b):\n if self.sameset(a, b):\n return\n a = self.find(a)\n b = self.find(b)\n if -self.s[a] > -self.s[b]:\n self.s[a] += self.s[b]\n self.s[b] = a\n else:\n self.s[b] += self.s[a]\n self.s[a] = b\n\ndef makeMaze(rows, cols: int):\n maze = np.zeros((rows*2 + 1, cols*2+1))\n maze[1::2, 1::2] = 1\n maze[ 1][ 0] = 3\n maze[-2][-1] = 3\n\n walls = []\n walls.extend((i*cols+j, i*cols+j+1) for j in range(cols-1) for i in range(rows-1))\n walls.extend((i*cols+j, (i+1)*cols+j) for j in range(cols-1) for i in range(rows-1))\n walls.extend((i*cols+cols-1,(i+1)*cols+cols-1) for i in range(rows-1))\n walls.extend(((rows-1)*cols+j, (rows-1)*cols+j+1) for j in range(cols-1))\n\n s = DisjointSet(len(walls))\n random.shuffle(walls)\n while len(walls) > 0:\n e1, e2 = walls.pop()\n r1, c1 = e1 // cols, e1 % cols\n r2, c2 = e2 // cols, e2 % cols\n if not s.sameset(e1, e2):\n if r1 == r2 and c1 < c2:\n maze[r1*2+1][c1*2+2] = 1\n elif r1 == r2:\n maze[r1*2+1][c2*2+2] = 1\n elif c1 == c2 and r1 < r2:\n maze[r1*2+2][c1*2+1] = 1\n else:\n maze[r2*2+2][c1*2+1] = 1\n\n s.union(e1, e2)\n\n return maze" }, { "alpha_fraction": 0.3811802268028259, "alphanum_fraction": 0.4066985547542572, "avg_line_length": 21.81818199157715, "blob_id": "a9acd28546b6816529679f56803e41ffa2b39542", "content_id": "066fd6d56054a584adb5fc65b59d66055ba861c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1254, "license_type": "no_license", "max_line_length": 99, "num_lines": 55, "path": "/Algoritmos/Fuerza_bruta/SEND.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "def replace(a, equivalence):\n s = 0\n for c in a:\n s = s * 10 + equivalence[c]\n return s\n\ndef validate(a, b, c, equivalence):\n na = replace(a, equivalence)\n nb = replace(b, equivalence)\n nc = replace(c, equivalence)\n return na + nb == nc\n \n\nequivalence = {\n 's' : 0,\n 'n' : 1,\n 'd' : 2,\n 'y' : 3,\n 'e' : 4,\n 'm' : 5,\n 'r' : 6,\n 'o' : 7\n}\n\ndef makeEquivalence(dic, s, n, d, y, e, m, r, o):\n dic['s'] = s\n dic['n'] = n\n dic['d'] = d\n dic['y'] = y\n dic['e'] = e\n dic['m'] = m\n dic['r'] = r\n dic['o'] = o\n\n\n\nequivalence1 = {}\nsolutions = 0\n\nfor s in range(10):\n for n in range(10):\n for d in range(10):\n for y in range(10):\n for e in range(10):\n for m in range(10):\n for r in range(10):\n for o in range(10):\n makeEquivalence(equivalence1, s, n, d, y, e, m, r, o)\n if validate(\"send\", \"more\", \"money\", equivalence1):\n print(\"{} + {} = {}\".format([s,e,n,d], [m,o,r,e], [m,o,n,e,y]))\n solutions+=1\n\n\n\nprint(\"Soluciones: {}\".format(solutions))" }, { "alpha_fraction": 0.49501660466194153, "alphanum_fraction": 0.5049833655357361, "avg_line_length": 28.129032135009766, "blob_id": "a9b37b760d34b85486d6ac2e8156ba74662c4c61", "content_id": "ff10bc9e3e7ff38adcd1ea0bcbfcd728d2ad1c1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 903, "license_type": "no_license", "max_line_length": 88, "num_lines": 31, "path": "/Algoritmos/Backtracking/SEND.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "\ndef replace(a, equivalence):\n s = 0\n for c in a:\n s = s * 10 + equivalence[c]\n return s\n\ndef validate(a, b, c, codex, chars):\n for i in range(len(codex)):\n a = a.replace(chars[i], str(codex[i]))\n b = b.replace(chars[i], str(codex[i]))\n c = c.replace(chars[i], str(codex[i]))\n if int(a) + int(b) == int(c):\n print(a,b,c)\n\ndef combinations(digits, n, w, chars, codex, a, b, c):\n if w == n:\n validate(a, b, c, codex, chars)\n else:\n for i in range(len(digits)):\n e = digits[i]\n print(digits[:i], digits[i+1:])\n print(e, i)\n combinations(digits[:i] + digits[i+1:], n, w + 1, chars, codex+[e], a, b, c)\n\ndef solve(a, b, c):\n chars = list(set(a + b + c))\n digits = [i for i in range(10)]\n n = len(chars)\n combinations(digits, n, 0, chars, [], a, b, c)\n\nsolve(\"SEND\", \"MORE\", \"MONEY\")" }, { "alpha_fraction": 0.5734042525291443, "alphanum_fraction": 0.5978723168373108, "avg_line_length": 31.413793563842773, "blob_id": "1a339a8c2d097f3a66e04168e1a79ce60ebac060", "content_id": "bb28961b89741a8bbccd360b16493a4f7402c482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 128, "num_lines": 29, "path": "/Algoritmos/Backtracking/Maze/mazeSolver.py", "repo_name": "jairmj/complejidad-alg", "src_encoding": "UTF-8", "text": "from mazeBuilder import makeMaze\nimport matplotlib.pyplot as plt\nimport time\ndef drawMaze(maze):\n fig, ax = plt.subplots(figsize=(18, 18))\n ax.imshow(maze, cmap='viridis') # \n ax.axis('off')\n\ndef mazeSolve(maze, row, col, rowF, colF):\n maze[row][col] = 3 # camino correcto (amarillito)\n time.sleep(0.1)\n drawMaze(maze)\n plt.show()\n if row == rowF and col == colF: #Si es la salida\n return True\n \n for r, c in [(row-1, col), (row, col+1), (row+1, col), (row, col-1)]: #rc se vuelve en la priemra tupla, luego la sig, y así\n if maze[r][c] == 1 and mazeSolve(maze, r, c, rowF, colF):\n return True\n\n maze[row][col] = 2 # camino sin salida (verde)\n time.sleep(0.1)\n drawMaze(maze)\n plt.show()\n return False\n\nmaze = makeMaze(5, 10)\nrows, cols = maze.shape # matriz de numpy, sino, sería len(maze), len(maze[0])\nmazeSolve(maze, 1, 1, rows - 2, cols -2 )\n" } ]
16
ituis18/a2-KillerJacKTM05
https://github.com/ituis18/a2-KillerJacKTM05
2a2a0bc86df15b4dc93105be7f91cf0750ec9044
146d0708f9e6bd938889bb08debfe2fef71b3d6b
84cac0657c39bc7b24de4ac1a8148c1458c5de15
refs/heads/master
2020-04-13T11:11:34.295006
2018-12-30T19:22:06
2018-12-30T19:22:06
163,166,536
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5313441157341003, "alphanum_fraction": 0.5368190407752991, "avg_line_length": 34.28985595703125, "blob_id": "3ac300b065c6f2cd04dff752dec35d126c54620c", "content_id": "25b64eb54b3bda675faedda0c593eacebdba7a7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7306, "license_type": "no_license", "max_line_length": 165, "num_lines": 207, "path": "/bottle_app.py", "repo_name": "ituis18/a2-KillerJacKTM05", "src_encoding": "UTF-8", "text": "\n#####################################################################\n### Assignment skeleton\n### You can alter the below code to make your own dynamic website.\n### The landing page for assignment 3 should be at /\n#####################################################################\n\n\nfrom bottle import route, run, default_app, debug, template, static_file, request, Request\nfrom hashlib import sha256\nimport bottle\n\n# importing static file which contains html, audio, image files.\n\n\ndef static_file_callback(filename):\n return static_file(filename, root='./static')\n\n\ndef htmlify(title, text):\n page = \"\"\"\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>%s</title>\n </head>\n <body>\n %s <br>\n </body>\n </html>\n\n \"\"\" % (title, text)\n return page\n\n# main page html block\n\n\ndef htmlify_index(title, text):\n pageindex = \"\"\"\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>%s</title>\n <style>\n h1{\n font-size: 20px;\n color: grey;\n }\n a {\n font-family: Verdana;\n color: purple;\n }\n </style>\n </head>\n <body>\n %s <br>\n </body>\n </html>\n\n \"\"\" % (title, text)\n return pageindex\n\n# This is the intro page of the application. User will see this page first.\n\n\ndef index():\n return htmlify_index(\"Studio 146\", \"\"\" \n <h1>Studio 146's web page. </h1> \n <ul>\n <li> <a href=\"./static/index.html\">Home</a> </li>\n <li> <a href=\"./static/OurTeam.html\">Our Team</a> </li>\n <li> <a href=\"./static/Contact.html\">Contact</a> </li>\n <li> <a href=\"./static/Valhalla.html\">Projects</a> </li>\n <li class=\"comment_class\"><a href=\"../../add_comments/\">Leave comment</a></li>\n </ul> <br>\n <p title = \"About us\"> Hello everyone! We are 146Studios! <br> We are the <em> Voluntariness - Based </em> game developer squad for developing 3D RPG games.<br>\n\nWe are all university student and we are also 5 people. We started to develop games with joining the school - club named \"ITU OTG\". <br> After that, \n\nwe took courses from different parts of developing industry. Then, we decided to start our project. This project's every single word was come from our \n\ndesign. We are still working on this project. <br> We are using Blender3D for 3D modeling, Substance Painter for texturing, Photoshop for concept art \n\npaper and pencil for game design :) <br> </p>\n <img src=\"./static/146_logo.jpg\" alt= \"our logo\" style= \"width:640px;\" \"height:640px;\" image-position=center;> <br>\n \"\"\")\n\n# the code contained below is about writing comments and taking user account texts.\n\n\nroute(\"/static/<filename:path>\", \"GET\", static_file_callback)\nroute('/', 'GET', index)\n\n\ndef create_hash(password):\n pw_bytestring = password.encode()\n return sha256(pw_bytestring).hexdigest()\n\n\ndef htmlify_comment(title, text):\n pagecomment = \"\"\"\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>%s</title>\n <style>\n a {\n font-family: Verdana;\n color: purple;\n }\n </style>\n </head>\n <body>\n %s <br>\n </body>\n </html>\n\n \"\"\" % (title, text)\n return pagecomment\n\n# This is comment page which users can enter their names,surnames and favorite game genres\n\n\ndef page_of_comment():\n return htmlify_comment(\"Leave us a comment\", \"\"\"\n <ul>\n <li> <a href=\"./static/index.html\">Home</a> </li>\n <li> <a href=\"./static/OurTeam.html\">Our Team</a> </li>\n <li> <a href=\"./static/Contact.html\">Contact</a> </li>\n <li> <a href=\"./static/Valhalla.html\">Projects</a> </li> \n </ul> <br> <br> <br>\n <form action = \"../comments/\" method = \"get\">\n <fieldset>\n <legend> Personal Information: </legend>\n Name: <br>\n <input type = \"text\" name=\"Name\" value=\"Name\">\n <br>\n Surname:<br>\n <input type = \"text\" name=\"SurName\" value=\"Surname\">\n <br>\n Nickname: <br>\n <input type = \"text\" name=\"Nickname\" value=\"Example146\" required>\n <br>\n Email: <br>\n <input type = \"text\" name=\"Mail\" value =\"[email protected]\" required>\n <br>\n Password: <br>\n <input type = \"text\" name=\"Password\" value= \"*******\" required>\n <br>\n </fieldset>\n <fieldset>\n <legend> Personal Interests: </legend>\n What kind of games do you like to play?:<br>\n <em> Please select the most attractive game type of your likes. This will be your \"title\" in website.</em> <br>\n <input type= \"radio\" name = \"game\" value = \"RPG's\"> RPG's <br>\n <input type = \"radio\" name = \"game\" value = \"Moba's\"> Moba's <br>\n <input type = \"radio\" name = \"game\" value = \"Visual Novels's\"> Visual Novel's <br>\n <input type = \"radio\" name = \"game\" value = \"Shooter\"> Shooter's <br>\n <input type = \"radio\" name = \"game\" value = \"Puzzle\"> Puzzle's <br>\n <input type = \"radio\" name = \"game\" value = \"Strategy\"> Strategies <br>\n </fieldset>\n <fieldset>\n <p>What do you think about our website?</p>\n <input type= \"radio\" name = \"satisfy\" value = \"Good-Condition\"> Wonderful! <br>\n <input type= \"radio\" name = \"satisfy\" value = \"Avg-Condition\"> Average <br>\n <input type= \"radio\" name = \"satisfy\" value = \"Bad-Condition\"> Terrible <br>\n </fieldset>\n <input type=\"submit\" value=\"submit\"> \n </form> <br> <br>\n \"\"\")\n\n# This function takes the inputs come from the user, after that it reads them, finally it prepares an output.\n\n\ndef reply_of_comment():\n name_value = request.GET[\"Name\"]\n surname_value = request.GET[\"SurName\"]\n condition_value = request.GET[\"satisfy\"]\n if condition_value == \"Good-Condition\":\n feedback = \"<p>We are happy for your good feedback :) .</p>\"\n elif condition_value == \"Avg-Condition\":\n feedback = \"<p>We are okay for your feedback.</p>\"\n else:\n feedback = \"<p>We are sad for your bad feedback :( .</p>\"\n\n main_value = \"Hello! \" + name_value + \" \" + surname_value + \" \" + feedback\n return htmlify_comment(\"Thanks for your writings!\", main_value)\n\n\nroute('/add_comments/', 'GET', page_of_comment)\nroute('/comments/', 'GET', reply_of_comment)\n\n#####################################################################\n### Don't alter the below code.\n### It allows this website to be hosted on Heroku\n### OR run on your computer.\n#####################################################################\n\n# This line makes bottle give nicer error messages\ndebug(True)\n# This line is necessary for running on Heroku\napp = default_app()\n# The below code is necessary for running this bottle app standalone on your computer.\nif __name__ == \"__main__\":\n run()\n" } ]
1
Tugceekaynak/python
https://github.com/Tugceekaynak/python
4167796e5636430c2d7cea380da0abf00053c323
03d055ee54008d9f64f3e100686b84bc6c5fd26a
a208962b3683093fc517e22d7e48a3cd60562683
refs/heads/master
2020-03-23T16:24:17.904489
2018-07-21T17:00:05
2018-07-21T17:00:05
141,807,711
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5923076868057251, "alphanum_fraction": 0.6448717713356018, "avg_line_length": 11.396825790405273, "blob_id": "c72565f30338011217cf99b300f95e8ee2bf846b", "content_id": "3d140cf472ad5cb34317647712790ec0b03b6d6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 780, "license_type": "no_license", "max_line_length": 37, "num_lines": 63, "path": "/integer.py", "repo_name": "Tugceekaynak/python", "src_encoding": "UTF-8", "text": "from typing import List, Union\n\nx=\"5\"\ny=\"10\"\n#print(type(x+y))\n#print(x+y)\n\nx=5\ny=10\n#print(type(x*y))\n#print(x*y)\n\nx=5\ny=10\nz=x/y\n\n#print(z)\n#print(type(z))\n\n###################type change\n\n#print(str(z))\n\n###################bool\n\ndogru = True\nYanlis = False\n\n#print(dogru == False)\n\n\nliste =[ x, y, \"elma\",dogru,z,\"yeni\"]\n\nliste.append(\"armut\")\nliste.insert(0,\"yeni\")\n#print(liste)\n\ncikarilan=liste.remove(liste[4])\n#print(cikarilan)\n\nliste2=[5,4,3,2,1]\n\nliste.append(liste2)\n#print(liste)\n#print(liste2)\n#print(liste[liste.index(liste2)])\n\nliste.extend(liste2)\n#print(liste)\n\n\nliste3=sorted(liste2)\n#print(liste2)\n#print(liste3)\n\nliste4=[2,6,1,9,10,2,1]\nliste4.sort(reverse=True)\n#print(liste4)\n\n#print(liste4.count(1))\n#print(len(liste4))\nprint(max(liste4))\nprint(min(liste4))" }, { "alpha_fraction": 0.6224783658981323, "alphanum_fraction": 0.651296854019165, "avg_line_length": 12.920000076293945, "blob_id": "4b85852f227578d7919b9cc4cccd5db456e143f2", "content_id": "ac8fac22e7d283b1f90ab93f967c44852087bdb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 347, "license_type": "no_license", "max_line_length": 39, "num_lines": 25, "path": "/sözlük.py", "repo_name": "Tugceekaynak/python", "src_encoding": "UTF-8", "text": "sozluk = {'one' : '1','two':[2,10,3,1]}\n\n#print(sozluk.get('two'))\n\nsozluk['one']=1\n#print(sozluk)\n\nsozluk.update({'two':2})\n#print(sozluk)\n\nsozluk.update({1:'one'})\nsozluk['four']=4\n#print(sozluk)\n\ndel sozluk['one']\n\n#print(sozluk)\n\nsozluk.pop('two')\n#print(sozluk)\n\nprint(sozluk.items())\nprint(sozluk)\nprint(sozluk.keys())\nprint(sozluk.values())" }, { "alpha_fraction": 0.4703925549983978, "alphanum_fraction": 0.5276114344596863, "avg_line_length": 32.42222213745117, "blob_id": "ef35ffe0cd906b8e1ac0f00ac1406ea5f621725d", "content_id": "ec1d0b62591ac6c65e62e4fe9e4aa993c3e3096f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1511, "license_type": "no_license", "max_line_length": 77, "num_lines": 45, "path": "/if-else.py", "repo_name": "Tugceekaynak/python", "src_encoding": "UTF-8", "text": "#0-40 dc\n#41-60 cb\n#61-80 bb\n#80-100 aa\n\nkul_vize = int(input(\"vize Notunuzu girin: \"))\nkul_final = int(input(\"final Notunuzu girin: \"))\n\nif type(kul_vize) == \"int\" and type(kul_final) == \"int\":\n if 0 < kul_vize < 100 and 0 < kul_final < 100:\n kul_not= ((kul_vize*40/100)+(kul_final*60/100))\n if 0 < kul_not <= 40:\n print(\"notunuz dc\")\n elif 40 < kul_not <=60:\n print(\"notunuz cb\")\n elif 60 < kul_not <=80:\n print(\"notunuz bb\")\n elif 80 < kul_not <=100:\n print(\"notunuz aa\")\n else:\n print(\"tanımsız\")\nelse:\n print(\"lütfen sayı girin\")\n\ndef ortalama_hesapla (gecici_vize, gecici_final):\n print(gecici_vize, type(gecici_vize))\n print(gecici_final, type(gecici_final))\n if type(gecici_vize_vize) == \"int\" and type(gecici_final_final) == \"int\":\n if 0 < gecici_vize < 100 and 0 < gecici_final < 100:\n kul_not = ((gecici_vize * 40 / 100) + (gecici_final * 60 / 100))\n if 0 < kul_not <= 40:\n print(\"notunuz dc\")\n elif 40 < kul_not <= 60:\n print(\"notunuz cb\")\n elif 60 < kul_not <= 80:\n print(\"notunuz bb\")\n elif 80 < kul_not <= 100:\n print(\"notunuz aa\")\n else:\n print(\"tanımsız\")\n else:\n print(\"lütfen sayı girin\")\n\nogr_1_vize = int (input(\"ilk ogrencinin vizesini giriniz\"))\nogr_1_final = int (input(\"ilk ogrencinin finalini giriniz\"))" }, { "alpha_fraction": 0.6333333253860474, "alphanum_fraction": 0.6333333253860474, "avg_line_length": 28.66666603088379, "blob_id": "15e1abd6db530bbf1f6d44a7aafc2ce4bf2dc92b", "content_id": "2231f19e09fda1058666cd590e42a087f9191c55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 35, "num_lines": 3, "path": "/test.py", "repo_name": "Tugceekaynak/python", "src_encoding": "UTF-8", "text": "isim = input(\"ismin nedir ?\")\nprint(\"hoşgeldin {}\" .format(isim))\nprint(\"hoşgeldin \" +isim)\n\n" }, { "alpha_fraction": 0.4838709533214569, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 15, "blob_id": "a2d8b9f8609f6439c35e8c6de5b1cec5e4559810", "content_id": "a890186e7769a400fbee175501d51c78af13b795", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/demetler.py", "repo_name": "Tugceekaynak/python", "src_encoding": "UTF-8", "text": "demet = (1,5,1,20)\nprint(demet)" }, { "alpha_fraction": 0.7703348994255066, "alphanum_fraction": 0.7703348994255066, "avg_line_length": 33.91666793823242, "blob_id": "8d5384ad8cada82fd3b7dd5fc743c5dcdc73bd23", "content_id": "2b36d465f6307ba9612b0737093e8cecfc94c6b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 422, "license_type": "no_license", "max_line_length": 47, "num_lines": 12, "path": "/string.py", "repo_name": "Tugceekaynak/python", "src_encoding": "UTF-8", "text": "test_degiskeni= \"bu bir test değişkenidir\"\nprint(test_degiskeni.lower())\nprint(test_degiskeni.capitalize())\nprint(test_degiskeni.upper())\nprint(test_degiskeni.strip())\nprint(test_degiskeni.lstrip().upper())\ntest_degiskeni= \"\\r\\n bu bir test değişkenidir\"\nprint(test_degiskeni.lower())\nprint(test_degiskeni.capitalize())\nprint(test_degiskeni.upper())\nprint(test_degiskeni.strip())\nprint(test_degiskeni.lstrip().upper())" } ]
6
lbianculli/replay_analysis
https://github.com/lbianculli/replay_analysis
f6c98204584a8429225872dee5cdc8bf86a9bd97
062bda6258fb9ac0e32de20d80eaace005bc29d8
b8af6ddd9f79413fb40636cbbed4aba7e34da448
refs/heads/master
2020-07-23T03:12:30.467107
2019-09-13T15:26:13
2019-09-13T15:26:13
207,430,323
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5473842620849609, "alphanum_fraction": 0.553735613822937, "avg_line_length": 36.15528106689453, "blob_id": "58b985bef6f9e2956f6c34933b7a83cd8e554096", "content_id": "f5fed1b9dc9fa6a90478f3d445392a6ae0025efe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5983, "license_type": "no_license", "max_line_length": 115, "num_lines": 161, "path": "/wrappers.py", "repo_name": "lbianculli/replay_analysis", "src_encoding": "UTF-8", "text": "from spec import Spec, Space\nfrom base_env import Env\nfrom utils.logger import base_logger\nfrom pysc2.lib import features\n\n\nlogger = base_logger(\"./wrapper_testing_log.txt\")\n\nclass ObservationWrapper:\n\n def __init__(self, _features=None, action_ids=None):\n self.spec = None\n self.features = _features\n self.action_ids = action_ids\n\n screen_feature_to_idx = {feat: idx for idx, feat in enumerate(features.SCREEN_FEATURES._fields)}\n minimap_feature_to_idx = {feat: idx for idx, feat in enumerate(features.MINIMAP_FEATURES._fields)}\n\n self.feature_masks = {\n 'screen': [screen_feature_to_idx[f] for f in _features['screen']],\n 'minimap': [minimap_feature_to_idx[f] for f in _features['minimap']]\n }\n # logger.info(self.feature_masks)\n\n def __call__(self, timestep):\n \"\"\" Takes features and action_ids, masks incoming observations, and returns wrapped obs, reward and done\"\"\"\n ts = timestep\n obs, reward, done = ts.observation, ts.reward, ts.step_type == StepType.LAST\n\n obs_wrapped = [\n obs['feature_screen'][self.feature_masks['screen']],\n obs['feature_minimap'][self.feature_masks['minimap']]\n ]\n for feat_name in self.features['non-spatial']:\n if feat_name == 'available_actions':\n fn_ids_idxs = [i for i, fn_id in enumerate(self.action_ids) if fn_id in obs[feat_name]]\n mask = np.zeros((len(self.action_ids),), dtype=np.int32)\n mask[fn_ids_idxs] = 1\n obs[feat_name] = mask\n obs_wrapped.append(obs[feat_name])\n\n return obs_wrapped, reward, done\n\n def make_spec(self, spec):\n \"\"\" creates spec given mock env observation_spec() \"\"\"\n spec = spec[0]\n\n default_dims = {\n 'available_actions': (len(self.action_ids))\n }\n\n screen_shape = (len(self.features['screen']), *spec['feature_screen'][1:])\n minimap_shape = (len(self.features['minimap']), *spec['feature_minimap'][1:])\n screen_dims = get_spatial_dims(self.features['screen'], features.SCREEN_FEATURES)\n minimap_dims = get_spatial_dims(self.features['minimap'], features.MINIMAP_FEATURES)\n\n spaces = [\n SC2Space(screen_shape, 'screen', self.features['screen'], screen_dims),\n SC2Space(minimap_shape, 'minimap', self.features['minimap'], minimap_dims),\n ]\n\n for feat in self.features['non-spatial']:\n if 0 in spec[feat]:\n spec[feat] = default_dims[feat]\n spaces.append(Space(spec[feat], name=feat))\n\n self.spec = Spec(spaces, 'Observation')\n\n\nclass ActionWrapper:\n \"\"\" \"\"\"\n def __init__(self, spatial_dim, action_ids, args=None):\n self.spec = None\n if not args:\n args = [\n 'screen',\n 'minimap',\n 'screen2',\n 'queued',\n 'control_group_act',\n 'control_group_id',\n 'select_add', # 6\n 'select_point_act', # 7\n 'select_unit_act',\n # 'select_unit_id'\n 'select_worker',\n 'build_queue_id',\n # 'unload_id'\n ]\n self.func_ids = action_ids\n self.args, self.spatial_dim = args, spatial_dim\n\n def __call__(self, action):\n defaults = {\n 'control_group_act': 0,\n 'control_group_id': 0,\n 'select_point_act': 0,\n 'select_unit_act': 0,\n 'select_unit_id': 0,\n 'build_queue_id': 0,\n 'unload_id': 0,\n }\n fn_id_idx, args = action.pop(0), []\n fn_id = self.func_ids[fn_id_idx]\n for arg_type in actions.FUNCTIONS[fn_id].args:\n arg_name = arg_type.name\n if arg_name in self.args:\n arg = action[self.args.index(arg_name)]\n # pysc2 expects all args in their separate lists\n if type(arg) not in [list, tuple]:\n arg = [arg]\n # pysc2 expects spatial coords, but we have flattened => attempt to fix\n if len(arg_type.sizes) > 1 and len(arg) == 1:\n arg = [arg[0] % self.spatial_dim, arg[0] // self.spatial_dim]\n args.append(arg)\n else:\n args.append([defaults[arg_name]])\n\n return [actions.FunctionCall(fn_id, args)]\n\n def make_spec(self, spec):\n \"\"\" creates spec given mock env action_spec() \"\"\"\n spec = spec[0]\n\n spaces = [SC2FuncIdSpace(self.func_ids, self.args)]\n for arg_name in self.args:\n arg = getattr(spec.types, arg_name)\n if len(arg.sizes) > 1:\n spaces.append(Space(domain=(0, arg.sizes), categorical=True, name=arg_name))\n else:\n spaces.append(Space(domain=(0, arg.sizes[0]), categorical=True, name=arg_name))\n\n self.spec = Spec(spaces, \"Action\")\n\n\nclass SC2Space(Space):\n def __init__(self, shape, name, spatial_feats=None, spatial_dims=None):\n if spatial_feats:\n name += \"{%s}\" % \", \".join(spatial_feats)\n self.spatial_feats, self.spatial_dims = spatial_feats, spatial_dims\n\n super().__init__(shape, name=name)\n\n\nclass SC2FuncIdSpace(Space):\n def __init__(self, func_ids, args):\n super().__init__(domain=(0, len(func_ids)), categorical=True, name=\"function_id\")\n self.args_mask = []\n for fn_id in func_ids:\n fn_id_args = [arg_type.name for arg_type in actions.FUNCTIONS[fn_id].args]\n self.args_mask.append([arg in fn_id_args for arg in args])\n\n\ndef get_spatial_dims(feat_names, feats):\n feats_dims = []\n for feat_name in feat_names:\n feat = getattr(feats, feat_name)\n feats_dims.append(1)\n if feat.type == features.FeatureType.CATEGORICAL:\n feats_dims[-1] = feat.scale\n return feats_dims\n\n" }, { "alpha_fraction": 0.7111716866493225, "alphanum_fraction": 0.7111716866493225, "avg_line_length": 29.66666603088379, "blob_id": "170b7dcc782d5bc97726783ee628a3398defc2e3", "content_id": "a08ce666e1875c89ef65fdffb6c84ecb9eeb2bf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/utils/logger.py", "repo_name": "lbianculli/replay_analysis", "src_encoding": "UTF-8", "text": "import logging\n\ndef base_logger(dir):\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n file_handler = logging.FileHandler(dir, mode='w')\n file_handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n\n return logger" }, { "alpha_fraction": 0.5165073871612549, "alphanum_fraction": 0.5208514332771301, "avg_line_length": 28.89610481262207, "blob_id": "ab0d9f6ca5ec1e20500414f37e450adb2c1b46a3", "content_id": "26988650b41552a9f6629824585eafc3a26b865b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2302, "license_type": "no_license", "max_line_length": 114, "num_lines": 77, "path": "/main.py", "repo_name": "lbianculli/replay_analysis", "src_encoding": "UTF-8", "text": "import os\nimport multiprocessing\nimport tensorflow as tf\nimport math\n\nfrom tqdm import tqdm # tqdm just progress bar decorator\nfrom absl import app, flags\nfrom test_env import ControllerEnv\n# ** do i want two funcs/cls or is it clean enough in main?\n\nclass MultiprocEnv:\n \"\"\" I still feel like theres a way to make this flow easier \"\"\"\n def __init__(\n self,\n replay_path=\"C:/Program Files (x86)/StarCraft II/Replays/\",\n processes=8,\n batch_size=16):\n\n if processes == -1:\n processes = multiprocessing.cpu_count()\n\n self.processes = processes\n self.batch_size = batch_size\n self.replays = [replay_path+f for f in os.listdir(replay_path)]\n\n assert len(self.replays) > 0\n\n def run(self):\n try:\n for i in tqdm(range(math.ceil(len(self.replays)/self.processes/self.batch_size))):\n procs = []\n x = i * self.processes * self.batch_size\n if x < 0:\n continue\n\n for p in range(self.processes):\n batch_start = x + p * self.batch_size\n batch_end = batch_start + self.batch_size\n batch_end = min(batch_end, len(self.replays))\n p = multiprocessing.Process(target=self._run, args=([self.replays[batch_start: batch_end]])) \n p.start()\n procs.append(p)\n if batch_end == len(self.replays):\n break\n for p in procs:\n p.join()\n\n except Exception as e:\n print(\"******\", e, \"******\")\n\n def _run(self, replay_batch):\n for replay in replay_batch:\n try:\n env = ControllerEnv(replay)\n env.start()\n env.run()\n\n except KeyboardInterrupt:\n env.controller.quit()\n except Exception as e:\n print(e)\n\n\ndef main(argv):\n \"\"\"\n for replay in os.listdir(replay_path):\n env = ControllerEnv(replay)\n env.start()\n env.run()...\n \"\"\"\n os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n env = MultiprocEnv()\n env.run()\n\nif __name__ == '__main__':\n app.run(main)\n" }, { "alpha_fraction": 0.6462882161140442, "alphanum_fraction": 0.6462882161140442, "avg_line_length": 31.85714340209961, "blob_id": "869bfdce1806a0adf6c20cd1965e9424d85e6fac", "content_id": "3772c2d3339c644bb15b9977055d2b0ac8791731", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 229, "license_type": "no_license", "max_line_length": 83, "num_lines": 7, "path": "/utils/exceptions.py", "repo_name": "lbianculli/replay_analysis", "src_encoding": "UTF-8", "text": "class Error(Exception):\n \"\"\" Base class for exceptions in this module \"\"\"\n pass\n\nclass ReplayError(Error):\n def __init__(self, message):\n super().__init__(message) # previously had the two params. is it the same?" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 19.16666603088379, "blob_id": "0e41b52730bad83dd9404f6cf1f82dccc03f6497", "content_id": "f80113e737cdd30431ff491bdd45bd19bd01a45e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/utils/types.py", "repo_name": "lbianculli/replay_analysis", "src_encoding": "UTF-8", "text": "from typing import Callable, List, Tuple, Any, Type\n\nDone = bool\nReward = int\nAction = List[Any]\nObservation = List[Any]" }, { "alpha_fraction": 0.626055896282196, "alphanum_fraction": 0.6330409646034241, "avg_line_length": 35.64881134033203, "blob_id": "c2b10ec23f8f85ebb2ab14f49dc37009d9cd1eb8", "content_id": "588c4e8030f14a6387b3ca05890463797fd03520", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6156, "license_type": "no_license", "max_line_length": 124, "num_lines": 168, "path": "/env.py", "repo_name": "lbianculli/replay_analysis", "src_encoding": "UTF-8", "text": "import pickle\nimport logging\nimport random\nimport numpy as np\nimport os\nimport sys\n\nfrom wrappers import ObsWrapper, ActWrapper\nfrom spec import Spec\nfrom base_env import Env\nfrom exceptions import ReplayError\nfrom pysc2.env.environment import StepType\nfrom pysc2.lib import features, point, actions, protocol # obj for coordinates\nfrom pysc2.env.environment import TimeStep, StepType\nfrom pysc2 import run_configs\nfrom s2clientprotocol import sc2api_pb2 as sc_pb\nfrom s2clientprotocol import common_pb2 as sc_common\n\n\ndef _assert_compat_version(replay_path):\n raise ReplayError(f\"Version is incompatible: {replay_path+'.SC2Replay'}\")\n\ndef _assert_not_corrupt(replay_path):\n raise ReplayError(f\"Replay may be corrupt: {replay_path+'.SC2Replay'}\")\n\ndef _assert_useful(replay_path):\n raise ReplayError(f\"Replay not useful for learning purposes. Could be too short or low MMR: {replay_path+'.SC2Replay'}\")\n\ndef _assert_misc_error(replay_path):\n raise ReplayError(f\"Replay could not be loaded: {replay_path+'.SC2Replay'}\")\n\n\nclass ControllerEnv(Env):\n def __init__(\n self,\n replay_file_path, # path from which replay is gathered\n base_path=\"C:/Users/lbianculli/replay_analysis/replay_saves/\",\n player_id=1,\n render=False,\n reset_done=True,\n max_ep_len=None,\n spatial_dim=32,\n step_mul=8,\n obs_features=None,\n frames_per_game=1,\n ):\n super().__init__(render, reset_done, max_ep_len) # why super here, not in agents?\n\n self.run_config = run_configs.get()\n self.sc2_proc = self.run_config.start()\n self.controller = self.sc2_proc.controller\n self.player_id = player_id\n self.replay_file_name = replay_file_path.split(\"/\")[-1].split(\".\")[0]\n\n self.frames_per_game = frames_per_game\n self.step_mul = step_mul\n self.spatial_dim = spatial_dim\n self.map_size = (spatial_dim, spatial_dim)\n self._env = None\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n self.save_path = base_path+self.replay_file_name+\".p\" # i feel like the root is available implicitly\n\n\n self.episode_states = []\n\n action_ids = [f.id for f in actions.FUNCTIONS]\n\n if not obs_features:\n obs_features = {\n 'screen': ['player_relative', 'selected', 'visibility_map', 'unit_hit_points_ratio', 'unit_density'],\n 'minimap': ['player_relative', 'selected', 'visibility_map', 'camera'],\n # available actions should always be present and in first position\n 'non-spatial': ['available_actions', 'player']}\n\n self.act_wrapper = ActWrapper(spatial_dim, action_ids)\n self.obs_wrapper = ObsWrapper(obs_features, action_ids)\n\n self.aif = features.AgentInterfaceFormat(\n feature_dimensions=features.Dimensions(screen=spatial_dim, minimap=spatial_dim),\n use_feature_units=True)\n\n self.replay_data = self.run_config.replay_data(self.replay_file_name + '.SC2Replay')\n ping = self.controller.ping()\n self.info = self.controller.replay_info(self.replay_data)\n\n if self._valid_replay(self.info, ping) == \"version\":\n self.sc2_proc.close()\n _assert_compat_version(self.replay_file_name)\n if self._valid_replay(self.info, ping) == \"corrupt\":\n self.sc2_proc.close()\n _assert_not_corrupt(self.replay_file_name)\n if self._valid_replay(self.info, ping) == \"not_useful\":\n self.sc2_proc.close()\n _assert_useful(self.replay_file_name)\n\n # do i need this block?\n screen_size_px = point.Point(*self.map_size)\n minimap_size_px = point.Point(*self.map_size)\n self.interface = sc_pb.InterfaceOptions(\n raw=False, score=True,\n feature_layer=sc_pb.SpatialCameraSetup(width=self.spatial_dim))\n screen_size_px.assign_to(self.interface.feature_layer.resolution)\n minimap_size_px.assign_to(self.interface.feature_layer.minimap_resolution) # this is working\n\n self.map_data = None\n if self.info.local_map_path:\n self.map_data = self.run_config.map_data(self.info.local_map_path)\n\n self._episode_length = self.info.game_duration_loops\n self._episode_steps = 0\n\n\n def start(self):\n \"\"\" get features and begin \"\"\"\n self.controller.start_replay(sc_pb.RequestStartReplay(\n replay_data=self.replay_data,\n map_data=self.map_data,\n options=self.interface,\n observed_player_id=self.player_id))\n\n self._state = StepType.FIRST\n\n def step(self): \n\n\n def obs_spec(self):\n if not self.obs_wrapper.spec:\n self.make_specs()\n return self.obs_wrapper.spec\n\n def act_spec(self):\n if not self.act_wrapper.spec:\n self.make_specs()\n return self.act_wrapper.spec\n\n def make_specs(self):\n # importing here to lazy-load\n from pysc2.env import mock_sc2_env\n mock_env = mock_sc2_env.SC2TestEnv(map_name=self.id, agent_interface_format=[ # will this throw an error?\n features.parse_agent_interface_format(feature_screen=self.spatial_dim, feature_minimap=self.spatial_dim)])\n self.act_wrapper.make_spec(mock_env.action_spec())\n self.obs_wrapper.make_spec(mock_env.observation_spec())\n mock_env.close()\n\n\n @staticmethod\n def _valid_replay(info, ping):\n \"\"\"\n Make sure the replay isn't corrupt, and is worth looking at.\n Could I use the below logic to raise varying exceptions?\n \"\"\"\n if info.HasField(\"error\"):\n return \"corrupt\"\n if info.base_build != ping.base_build:\n return \"version\"\n if info.game_duration_loops < 1000 or len(info.player_info) != 2:\n return \"not_useful\"\n for p in info.player_info:\n if p.player_apm < 60 or (p.player_mmr != 0 and p.player_mmr < 2000):\n return \"not_useful\"\n\n def flush(self):\n self.episode_states = []\n\n\n def reset(self):\n self.controller.restart()" } ]
6
mjnrt/charity_app
https://github.com/mjnrt/charity_app
b18e67df314fb26efed256893abf341f385c6a71
48ecdb5af468113e1e1a76388bf4f6751bfd8126
6855205d2726fe4ca8a7ec991d7b57583c43f4a4
refs/heads/main
2023-06-15T14:23:07.134974
2021-07-08T16:46:13
2021-07-08T16:46:13
382,623,811
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6898574829101562, "alphanum_fraction": 0.7066219449043274, "avg_line_length": 33.08571243286133, "blob_id": "05d19a08e2c1edc368a33148693de1e01edb6143", "content_id": "bbd113b05a157ecbf8b7cc1f32043bba721369bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1197, "license_type": "no_license", "max_line_length": 84, "num_lines": 35, "path": "/charity/models.py", "repo_name": "mjnrt/charity_app", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=64)\n\n def __str__(self):\n return self.name\n\n\nclass Institution(models.Model):\n TYPE_CHOICES = (\n (\"fundacja\", \"fundacja\"),\n (\"organizacja pozarządowa\", \"organizacja pozarządowa\"),\n (\"zbiórka lokalna\", \"zbiórka lokalna\")\n )\n name = models.CharField(max_length=64)\n description = models.CharField(max_length=128)\n type = models.CharField(max_length=64, choices=TYPE_CHOICES, default=\"fundacja\")\n categories = models.ManyToManyField(Category)\n\n\nclass Donation(models.Model):\n quantity = models.IntegerField()\n categories = models.ManyToManyField(Category)\n institution = models.ManyToManyField(Institution)\n address = models.CharField(max_length=64)\n phone_number = models.CharField(max_length=20)\n city = models.CharField(max_length=64)\n zip_code = models.CharField(max_length=20)\n pickup_date = models.DateField()\n pickup_time = models.TimeField()\n pickup_comment = models.TextField(max_length=240)\n user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n" }, { "alpha_fraction": 0.6654275059700012, "alphanum_fraction": 0.6654275059700012, "avg_line_length": 26.58974266052246, "blob_id": "16a4447844557471d97f1db2e427c6000bdd7ffb", "content_id": "e6a785037d5a77057d459d23dcabeb04c2233a4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1076, "license_type": "no_license", "max_line_length": 60, "num_lines": 39, "path": "/charity/views.py", "repo_name": "mjnrt/charity_app", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views import View\nfrom .models import Donation, Institution\n\n\nclass LandingPage(View):\n template_name = \"charity/index.html\"\n\n def get(self, request):\n bags_quantity = []\n for x in Donation.objects.all():\n bags_quantity.append(x.quantity)\n institutions_counter = Institution.objects.count()\n institutions = Institution.objects.all()\n ctx = {'bags_counter': sum(bags_quantity),\n 'institutions_counter': institutions_counter,\n 'institutions': institutions}\n return render(request, self.template_name, ctx)\n\n\nclass AddDonation(View):\n template_name = \"charity/form.html\"\n\n def get(self, request):\n return render(request, self.template_name)\n\n\nclass Login(View):\n template_name = \"charity/login.html\"\n\n def get(self, request):\n return render(request, self.template_name)\n\n\nclass Register(View):\n template_name = \"charity/register.html\"\n\n def get(self, request):\n return render(request, self.template_name)\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5925925970077515, "avg_line_length": 36.565216064453125, "blob_id": "4605d6e3d8bd7ab4c29608d476d17711c846fbf6", "content_id": "9c5fa884d736dc8b3c44583e91369024d4681819", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 210, "num_lines": 23, "path": "/charity/migrations/0002_institution.py", "repo_name": "mjnrt/charity_app", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.8 on 2021-07-03 21:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('charity', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Institution',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=64)),\n ('description', models.CharField(max_length=128)),\n ('type', models.CharField(choices=[('fundacja', 'fundacja'), ('organizacja pozarządowa', 'organizacja pozarządowa'), ('zbiórka lokalna', 'zbiórka lokalna')], default='fundacja', max_length=64)),\n ('categories', models.ManyToManyField(to='charity.Category')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7981651425361633, "alphanum_fraction": 0.7981651425361633, "avg_line_length": 53.5, "blob_id": "434b6604a1b50b3fe7910b763cd65d6c6e3a1e26", "content_id": "8066d184147b25683ead89b00db3a3ea172e6ba8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 109, "license_type": "no_license", "max_line_length": 94, "num_lines": 2, "path": "/README.md", "repo_name": "mjnrt/charity_app", "src_encoding": "UTF-8", "text": "# charity_app\nThe purpose of application is to create a place where people can give items to others for free\n" } ]
4
fabiocasolari/rpi-examples
https://github.com/fabiocasolari/rpi-examples
7b13b1938b6279028dbed9d2372e092d46b971f9
ff08e27d463a9871f067f0df4c248a268840432f
3b78237c78381c0cdf2e4498700f02025c388186
refs/heads/master
2023-06-24T22:40:17.236444
2022-08-20T17:00:12
2022-08-20T17:00:12
159,086,811
0
0
MIT
2018-11-26T00:05:21
2018-11-25T22:48:34
2017-11-28T23:44:42
null
[ { "alpha_fraction": 0.6558441519737244, "alphanum_fraction": 0.6720778942108154, "avg_line_length": 16.11111068725586, "blob_id": "b5c7a6d3df2c62b7d127edef386c9359c759aed8", "content_id": "5861ef97fa45b96e0d22ec0d889eb56eaf400573", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 308, "license_type": "permissive", "max_line_length": 40, "num_lines": 18, "path": "/PIR-sensor/python/motion.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "from gpiozero import MotionSensor\nimport time\nimport signal\nimport sys\n\ndef close(signal, frame):\n sys.exit(0)\n\nsignal.signal(signal.SIGINT, close)\n\npir = MotionSensor(4)\ncount = 0;\n\nwhile True:\n if pir.motion_detected:\n count += 1\n print \"Motion detected: \", count\n time.sleep(1)\n" }, { "alpha_fraction": 0.508474588394165, "alphanum_fraction": 0.5593220591545105, "avg_line_length": 13.6875, "blob_id": "be57d8471c16eb83972a97a3ec78d455c36b2cd3", "content_id": "da65e739f083c1f3eb0e17e5235870c5487d6339", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 236, "license_type": "permissive", "max_line_length": 39, "num_lines": 16, "path": "/BMP180/c/Makefile", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS=-I.\nDEPS = \nOBJ = smbus.o BMP180.o BMP180_test.o\nEXTRA_LIBS=-lm\n\n%.o: %.c $(DEPS)\n\t$(CC) -c -o $@ $< $(CFLAGS)\n\nBMP180_test: $(OBJ)\n\t$(CC) -o $@ $^ $(CFLAGS) $(EXTRA_LIBS)\n\n.PHONY: clean\n\nclean:\n\trm -f BMP180_test $(OBJ) \n" }, { "alpha_fraction": 0.6854663491249084, "alphanum_fraction": 0.7375271320343018, "avg_line_length": 37.41666793823242, "blob_id": "781c8ace906e82873ad1661aabb4052c10c831ba", "content_id": "f116081a5b9d368abe6d23cbbf609fc4be124180", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 461, "license_type": "permissive", "max_line_length": 78, "num_lines": 12, "path": "/BMP280/python/BMP280_test.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# Depends on Adafruit Python BMP from Bastien Wirtz:\n# https://github.com/bastienwirtz/Adafruit_Python_BMP\n\nimport Adafruit_BMP.BMP280 as BMP280\n\nsensor = BMP280.BMP280()\n\nprint 'Temperature: {0:0.2f} *C'.format(sensor.read_temperature())\nprint 'Barometric Pressure: {0:0.2f} Pa'.format(sensor.read_pressure())\nprint 'Altitude: {0:0.2f} m'.format(sensor.read_altitude())\nprint 'Sealevel Pressure: {0:0.2f} Pa'.format(sensor.read_sealevel_pressure())\n" }, { "alpha_fraction": 0.48458150029182434, "alphanum_fraction": 0.5638766288757324, "avg_line_length": 13.125, "blob_id": "67974b7969e00b6a2f06392a587f26c4951d3c3f", "content_id": "f0fc07125cb19a4202a862d4007602ce957a2ee7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 227, "license_type": "permissive", "max_line_length": 39, "num_lines": 16, "path": "/DC-motor-SN754410/c/Makefile", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS=-I.\nDEPS = \nOBJ = sn754410.o\nEXTRA_LIBS=-lwiringPi -lpthread\n\n%.o: %.c $(DEPS)\n\t$(CC) -c -o $@ $< $(CFLAGS)\n\nsn754410: $(OBJ)\n\t$(CC) -o $@ $^ $(CFLAGS) $(EXTRA_LIBS)\n\n.PHONY: clean\n\nclean:\n\trm -f sn754410 $(OBJ) \n" }, { "alpha_fraction": 0.594936728477478, "alphanum_fraction": 0.7405063509941101, "avg_line_length": 13.363636016845703, "blob_id": "383ee270247e1acba06ab39306da229023411acf", "content_id": "187e86bf946ec1380679a2070e8493602d0b3a46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 158, "license_type": "permissive", "max_line_length": 27, "num_lines": 11, "path": "/MAX44009/c/MAX44009.h", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#ifndef _MAX44009_H_\n#define _MAX44009_H_\n\n#define MAX44009_ADDR 0x4A\n\n#define lux_h_register 0x03\n#define lux_l_register 0x04\n\nfloat getLux(int fd);\n\n#endif\n" }, { "alpha_fraction": 0.6009975075721741, "alphanum_fraction": 0.6733167171478271, "avg_line_length": 22.58823585510254, "blob_id": "0f234340706243c1fddd67b84f03aa7c0f22db77", "content_id": "58b8051913c3e714dabcb5b4dc3e939aee2a2ae8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 802, "license_type": "permissive", "max_line_length": 58, "num_lines": 34, "path": "/HTU21D/c/HTU21D.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <unistd.h>\n\n#include \"wiringPi.h\"\n#include \"wiringPiI2C.h\"\n\n#include \"HTU21D.h\"\n\n// Get temperature\ndouble getTemperature(int fd)\n{\n\tunsigned char buf [4];\n\twiringPiI2CWrite(fd, HTU21D_TEMP);\n\tdelay(100);\n\tread(fd, buf, 3);\n\tunsigned int temp = (buf [0] << 8 | buf [1]) & 0xFFFC;\n\t// Convert sensor reading into temperature.\n\t// See page 14 of the datasheet\n\tdouble tSensorTemp = temp / 65536.0;\n\treturn -46.85 + (175.72 * tSensorTemp);\n}\n\n// Get humidity\ndouble getHumidity(int fd)\n{\n\tunsigned char buf [4];\n\twiringPiI2CWrite(fd, HTU21D_HUMID);\n\tdelay(100);\n\tread(fd, buf, 3);\n \tunsigned int humid = (buf [0] << 8 | buf [1]) & 0xFFFC;\n\t// Convert sensor reading into humidity.\n\t// See page 15 of the datasheet\n\tdouble tSensorHumid = humid / 65536.0;\n\treturn -6.0 + (125.0 * tSensorHumid);\n}\n" }, { "alpha_fraction": 0.46521738171577454, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 24.61111068725586, "blob_id": "876ac8b980f509b5b6d88ba3c1d29da343e60de5", "content_id": "c2cdcea44a74070245b66d5be43068852d915634", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "permissive", "max_line_length": 49, "num_lines": 18, "path": "/pico/micropython/mini-oled-i2c-ssd1306-draw/main.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "from machine import Pin, I2C\nimport ssd1306\n\n# using default address 0x3C\nsda=machine.Pin(4)\nscl=machine.Pin(5)\ni2c = I2C(0,sda=sda, scl=scl, freq=400000)\ndisplay = ssd1306.SSD1306_I2C(128, 64, i2c)\ndisplay.rect(0, 0, 128, 16, 1)\ndisplay.fill_rect(0, 0, 100, 16, 1)\nfor row in range(1, 4):\n for n in range(4):\n if row % 2:\n pos = 32*n\n else:\n pos = 16+32*n\n display.fill_rect(pos, row*16, 16, 16, 1)\ndisplay.show()" }, { "alpha_fraction": 0.6286919713020325, "alphanum_fraction": 0.7046413421630859, "avg_line_length": 14.800000190734863, "blob_id": "7d135b66fd78a21c632f60f5e3de9804c4dba264", "content_id": "f6d5d174e2ca5769096323eab88705189fc5f417", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 237, "license_type": "permissive", "max_line_length": 30, "num_lines": 15, "path": "/HTU21D/c/HTU21D.h", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#ifndef _HTU21D_H_\n#define _HTU21D_H_\n\n#define HTU21D_I2C_ADDR 0x40\n\n#define HTU21D_TEMP 0xF3\n#define HTU21D_HUMID 0xF5\n\n// Get temperature\ndouble getTemperature(int fd);\n\n// Get humidity\ndouble getHumidity(int fd);\n\n#endif\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.7207977175712585, "avg_line_length": 20.489795684814453, "blob_id": "7aaaddbfa3eed9d959bf746a7be4c88f4e5efd08", "content_id": "a9f54cab4039141f6e1c0a15dd497f76197c5c80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1053, "license_type": "permissive", "max_line_length": 58, "num_lines": 49, "path": "/HC-SR04/python/distance.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\nimport signal\nimport sys\n\n# use Raspberry Pi board pin numbers\nGPIO.setmode(GPIO.BCM)\n\n# set GPIO Pins\npinTrigger = 18\npinEcho = 24\n\ndef close(signal, frame):\n\tprint(\"\\nTurning off ultrasonic distance detection...\\n\")\n\tGPIO.cleanup() \n\tsys.exit(0)\n\nsignal.signal(signal.SIGINT, close)\n\n# set GPIO input and output channels\nGPIO.setup(pinTrigger, GPIO.OUT)\nGPIO.setup(pinEcho, GPIO.IN)\n\nwhile True:\n\t# set Trigger to HIGH\n\tGPIO.output(pinTrigger, True)\n\t# set Trigger after 0.01ms to LOW\n\ttime.sleep(0.00001)\n\tGPIO.output(pinTrigger, False)\n\n\tstartTime = time.time()\n\tstopTime = time.time()\n\n\t# save start time\n\twhile 0 == GPIO.input(pinEcho):\n\t\tstartTime = time.time()\n\n\t# save time of arrival\n\twhile 1 == GPIO.input(pinEcho):\n\t\tstopTime = time.time()\n\n\t# time difference between start and arrival\n\tTimeElapsed = stopTime - startTime\n\t# multiply with the sonic speed (34300 cm/s)\n\t# and divide by 2, because there and back\n\tdistance = (TimeElapsed * 34300) / 2\n\n\tprint (\"Distance: %.1f cm\" % distance)\n\ttime.sleep(1)\n" }, { "alpha_fraction": 0.49561402201652527, "alphanum_fraction": 0.5657894611358643, "avg_line_length": 13.25, "blob_id": "4518edc83ec5c4a3365649f3308ffc62d44b22ac", "content_id": "b0677810afe1b95db8a18c6216fe07005e5cff85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 228, "license_type": "permissive", "max_line_length": 39, "num_lines": 16, "path": "/BH1750/c/Makefile", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS=-I.\nDEPS =\nOBJ = BH1750.o BH1750_test.o\nEXTRA_LIBS=-lwiringPi\n\n%.o: %.c $(DEPS)\n\t$(CC) -c -o $@ $< $(CFLAGS)\n\nBH1750_test: $(OBJ)\n\t$(CC) -o $@ $^ $(CFLAGS) $(EXTRA_LIBS)\n\n.PHONY: clean\n\nclean:\n\trm -f BH1750 $(OBJ)\n" }, { "alpha_fraction": 0.5919975638389587, "alphanum_fraction": 0.634434700012207, "avg_line_length": 29.831775665283203, "blob_id": "8820e7abba59dd8c7491d4ca73c3769ee6d172bc", "content_id": "7ec99b647d2966f251860db72a8524283bcbe8d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3299, "license_type": "permissive", "max_line_length": 79, "num_lines": 107, "path": "/PN532/python/rfid-save.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "# Requires Adafruit_Python_PN532\n\nimport binascii\nimport sys\nimport struct\n\nimport Adafruit_PN532 as PN532\n\n# Hack to make code compatible with both Python 2 and 3 (since 3 moved\n# raw_input from a builtin to a different function, ugh).\ntry:\n input = raw_input\nexcept NameError:\n pass\n\n# PN532 configuration for a Raspberry Pi GPIO:\n\n# GPIO 18, pin 12\nCS = 18\n# GPIO 23, pin 16\nMOSI = 23\n# GPIO 24, pin 18\nMISO = 24\n# GPIO 25, pin 22\nSCLK = 25\n\n# Configure the key to use for writing to the MiFare card. You probably don't\n# need to change this from the default below unless you know your card has a\n# different key associated with it.\nCARD_KEY = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]\n\n# Prefix, aka header from the card\nHEADER = b'BG'\n\n# Create and initialize an instance of the PN532 class.\npn532 = PN532.PN532(cs=CS, sclk=SCLK, mosi=MOSI, miso=MISO)\npn532.begin()\npn532.SAM_configuration()\n\n# Step 1, wait for card to be present.\nprint('PN532 NFC Module Writer')\nprint('')\nprint('== STEP 1 =========================')\nprint('Place the card to be written on the PN532...')\nuid = pn532.read_passive_target()\nwhile uid is None:\n uid = pn532.read_passive_target()\nprint('')\nprint('Found card with UID: 0x{0}'.format(binascii.hexlify(uid)))\nprint('')\nprint('==============================================================')\nprint('WARNING: DO NOT REMOVE CARD FROM PN532 UNTIL FINISHED WRITING!')\nprint('==============================================================')\nprint('')\n\n# Step 2, pick a block type.\nprint('== STEP 2 =========================')\nblock_choice = None\nwhile block_choice is None:\n print('')\n block_choice = input('Enter user ID: ')\n try:\n block_choice = int(block_choice)\n except ValueError:\n print('Error! Unrecognized option.')\n continue\n # Decimal value not greater than hex number with 6 digits\n if not (0 <= block_choice < 16777215):\n print('Error! User ID must be within 0 to 4294967295.')\n continue\n print('')\nprint('You chose the block type: {0}'.format(block_choice))\nprint('')\n\n# Confirm writing the block type.\nprint('== STEP 3 =========================')\nprint('Confirm you are ready to write to the card:')\nprint('User ID: {0}'.format(block_choice))\nchoice = input('Confirm card write (Y or N)? ')\nif choice.lower() != 'y' and choice.lower() != 'yes':\n print('Aborted!')\n sys.exit(0)\nprint('Writing card (DO NOT REMOVE CARD FROM PN532)...')\n\n# Write the card!\n# First authenticate block 4.\nif not pn532.mifare_classic_authenticate_block(uid, 4, PN532.MIFARE_CMD_AUTH_B,\n CARD_KEY):\n print('Error! Failed to authenticate block 4 with the card.')\n sys.exit(-1)\n# Next build the data to write to the card.\n# Format is as follows:\n# - 2 bytes 0-1 store a header with ASCII value, for example 'BG'\n# - 6 bytes 2-7 store the user data, for example user ID\ndata = bytearray(16)\n# Add header\ndata[0:2] = HEADER\n# Convert int to hex string with up to 6 digits\nvalue = format(block_choice, 'x')\nwhile (6 > len(value)):\n value = '0' + value\ndata[2:8] = value\n# Finally write the card.\nif not pn532.mifare_classic_write_block(4, data):\n print('Error! Failed to write to the card.')\n sys.exit(-1)\nprint('Wrote card successfully! You may now remove the card from the PN532.')\n" }, { "alpha_fraction": 0.650943398475647, "alphanum_fraction": 0.6792452931404114, "avg_line_length": 16.66666603088379, "blob_id": "a55e135c27faea8d90581386576f880ddef611c4", "content_id": "ee87e9217fbe346ee09ee8c546312524a80edace", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "permissive", "max_line_length": 23, "num_lines": 6, "path": "/pico/micropython/blink/main.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "import time\nfrom machine import Pin\nled = Pin(25, Pin.OUT)\nwhile True:\n led.toggle()\n time.sleep(1) " }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 9.55555534362793, "blob_id": "121b54e1a029b8dfd4580aa2b431ba78eb2b8a53", "content_id": "946e30fa8c90e5f65ed7b95997a254defc7ab37d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 95, "license_type": "permissive", "max_line_length": 25, "num_lines": 9, "path": "/LED/bash/led.sh", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ \"$1\" == \"on\" ]; then\n\tled=1\nelse\n\tled=0\nfi\ngpio mode 0 out\ngpio write 0 $led\n" }, { "alpha_fraction": 0.5244544744491577, "alphanum_fraction": 0.6392024159431458, "avg_line_length": 44.050846099853516, "blob_id": "4e9d524e593ddefd25102df3916643e15b1cd946", "content_id": "026f36ebdaffd38751b3e0c16ed4b83b6aa60a03", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2658, "license_type": "permissive", "max_line_length": 106, "num_lines": 59, "path": "/TSL2561/c/example-wiringpi/TSL2561.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <inttypes.h>\n#include <wiringPi.h>\n#include <wiringPiI2C.h>\n#include <errno.h>\n\n// ALL COMMAND TSL2561\n// Default I2C RPI address in (0x39) = FLOAT ADDR (Slave) Other [(0x49) = VCC ADDR / (0x29) = GROUND ADDR]\n#define TSL2561_ADDR_LOW (0x29)\n#define TSL2561_ADDR_FLOAT (0x39)\n#define TSL2561_ADDR_HIGH (0x49)\n#define TSL2561_CONTROL_POWERON (0x03)\n#define TSL2561_CONTROL_POWEROFF (0x00)\n#define TSL2561_GAIN_0X (0x00) //No gain\n#define TSL2561_GAIN_AUTO (0x01)\n#define TSL2561_GAIN_1X (0x02)\n#define TSL2561_GAIN_16X (0x12) // (0x10)\n#define TSL2561_INTEGRATIONTIME_13MS (0x00) // 13.7ms\n#define TSL2561_INTEGRATIONTIME_101MS (0x01) // 101ms\n#define TSL2561_INTEGRATIONTIME_402MS (0x02) // 402ms\n#define TSL2561_READBIT (0x01)\n#define TSL2561_COMMAND_BIT (0x80) //Must be 1\n#define TSL2561_CLEAR_BIT (0x40) //Clears any pending interrupt (write 1 to clear)\n#define TSL2561_WORD_BIT (0x20) // 1 = read/write word (rather than byte)\n#define TSL2561_BLOCK_BIT (0x10) // 1 = using block read/write\n#define TSL2561_REGISTER_CONTROL (0x00)\n#define TSL2561_REGISTER_TIMING (0x81)\n#define TSL2561_REGISTER_THRESHHOLDL_LOW (0x02)\n#define TSL2561_REGISTER_THRESHHOLDL_HIGH (0x03)\n#define TSL2561_REGISTER_THRESHHOLDH_LOW (0x04)\n#define TSL2561_REGISTER_THRESHHOLDH_HIGH (0x05)\n#define TSL2561_REGISTER_INTERRUPT (0x06)\n#define TSL2561_REGISTER_CRC (0x08)\n#define TSL2561_REGISTER_ID (0x0A)\n#define TSL2561_REGISTER_CHAN0_LOW (0x8C)\n#define TSL2561_REGISTER_CHAN0_HIGH (0x8D)\n#define TSL2561_REGISTER_CHAN1_LOW (0x8E)\n#define TSL2561_REGISTER_CHAN1_HIGH (0x8F)\n//Delay getLux function\n#define LUXDELAY 500\n\nint getLux(int fd){\n // Enable the device\n wiringPiI2CWriteReg8(fd, TSL2561_COMMAND_BIT, TSL2561_CONTROL_POWERON);\n // Set timing (101 mSec)\n wiringPiI2CWriteReg8(fd, TSL2561_REGISTER_TIMING, TSL2561_GAIN_AUTO);\n //Wait for the conversion to complete\n delay(LUXDELAY);\n //Reads visible + IR diode from the I2C device auto\n uint16_t visible_and_ir = wiringPiI2CReadReg16(fd, TSL2561_REGISTER_CHAN0_LOW);\n // Disable the device\n wiringPiI2CWriteReg8(fd, TSL2561_COMMAND_BIT, TSL2561_CONTROL_POWEROFF);\n return visible_and_ir * 2;\n}\n\nvoid main(){\n int fd = wiringPiI2CSetup(TSL2561_ADDR_FLOAT);\n printf(\"Lux: %d\\n\", getLux(fd));\n}\n" }, { "alpha_fraction": 0.4976303279399872, "alphanum_fraction": 0.5402843356132507, "avg_line_length": 12.125, "blob_id": "98220a15999e12415d1cc396b8cd23e3fb989d74", "content_id": "9a1b03da99b129268074b11a5203fda4370261d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 211, "license_type": "permissive", "max_line_length": 39, "num_lines": 16, "path": "/BMP280/c/Makefile", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS=-I.\nDEPS = \nOBJ = BMP280.o\nEXTRA_LIBS=-lwiringPi\n\n%.o: %.c $(DEPS)\n\t$(CC) -c -o $@ $< $(CFLAGS)\n\nBMP280: $(OBJ)\n\t$(CC) -o $@ $^ $(CFLAGS) $(EXTRA_LIBS)\n\n.PHONY: clean\n\nclean:\n\trm -f BMP280 $(OBJ) \n" }, { "alpha_fraction": 0.5436893105506897, "alphanum_fraction": 0.6019417643547058, "avg_line_length": 10.44444465637207, "blob_id": "67fbb28360561a1847def3d613cf82a44039ad73", "content_id": "c0f537ea576426b13f985a883f47bbae4a43c93c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 103, "license_type": "permissive", "max_line_length": 33, "num_lines": 9, "path": "/LED/bash/switch.sh", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ `gpio read 0` == \"1\" ]; then\n\tled=0\nelse\n\tled=1\nfi\ngpio mode 0 out\ngpio write 0 $led\n" }, { "alpha_fraction": 0.5327102541923523, "alphanum_fraction": 0.5327102541923523, "avg_line_length": 12.3125, "blob_id": "fc9744fa264302ce36b8d06bd65273d192bda9f4", "content_id": "72b1d3d6f97fcf2f49ec31a9c15536c49360885c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 214, "license_type": "permissive", "max_line_length": 39, "num_lines": 16, "path": "/LED-RGB/c/Makefile", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS=-I.\nDEPS = \nOBJ = led-rgb.o\nEXTRA_LIBS=-lwiringPi\n\n%.o: %.c $(DEPS)\n\t$(CC) -c -o $@ $< $(CFLAGS)\n\nled-rgb: $(OBJ)\n\t$(CC) -o $@ $^ $(CFLAGS) $(EXTRA_LIBS)\n\n.PHONY: clean\n\nclean:\n\trm -f led-rgb $(OBJ) \n" }, { "alpha_fraction": 0.5545171499252319, "alphanum_fraction": 0.5950155854225159, "avg_line_length": 21.928571701049805, "blob_id": "85669c72a61e20a56591883c5e05e6685c5e4bb1", "content_id": "6308573ccf2f6e9fd71d619cf6ffefc2068536f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 321, "license_type": "permissive", "max_line_length": 67, "num_lines": 14, "path": "/BMP180/c/BMP180_test.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n#include \"BMP180.h\"\n\nint main(int argc, char **argv)\n{\n calibration();\n\n printf(\"Temperature\\t%0.1f C\\n\", getTemperature());\n printf(\"Pressure\\t%0.2f hPa\\n\", (double)getPressure()/100);\n printf(\"Altitude\\t%0.2f m\\n\", getAltitude());\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5871720314025879, "alphanum_fraction": 0.6244897842407227, "avg_line_length": 25.384614944458008, "blob_id": "f9e34773155925ae270f54a5fafce3e5215c2415", "content_id": "bc6ced1578b4555270a4ca15ccd544e0da6fefea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1715, "license_type": "permissive", "max_line_length": 138, "num_lines": 65, "path": "/MCP3002/python/adc.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n# Tested on Raspberry Pi OS. Requirements: enable SPI, for example\n# from raspi-config. The example is based on a SparkFun tutorial:\n# https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-3-spi-and-analog-input\n\nimport signal\nimport sys\nimport time\nimport spidev\nimport RPi.GPIO as GPIO\n\nspi_ch = 0\n\n# Enable SPI\nspi = spidev.SpiDev(0, spi_ch)\nspi.max_speed_hz = 1200000\n\ndef close(signal, frame):\n sys.exit(0)\n\nsignal.signal(signal.SIGINT, close)\n\ndef get_adc(channel):\n\n # Make sure ADC channel is 0 or 1\n if channel != 0:\n channel = 1\n\n # Construct SPI message\n # First bit (Start): Logic high (1)\n # Second bit (SGL/DIFF): 1 to select single mode\n # Third bit (ODD/SIGN): Select channel (0 or 1)\n # Fourth bit (MSFB): 0 for LSB first\n # Next 12 bits: 0 (don't care)\n msg = 0b11\n msg = ((msg << 1) + channel) << 5\n msg = [msg, 0b00000000]\n reply = spi.xfer2(msg)\n\n # Construct single integer out of the reply (2 bytes)\n adc = 0\n for n in reply:\n adc = (adc << 8) + n\n\n # Last bit (0) is not part of ADC value, shift to remove it\n adc = adc >> 1\n\n # Calculate voltage form ADC value\n # considering the soil moisture sensor is working at 5V\n voltage = (5 * adc) / 1024\n\n return voltage\n\nif __name__ == '__main__':\n # Report the channel 0 and channel 1 voltages to the terminal\n try:\n while True:\n adc_0 = get_adc(0)\n adc_1 = get_adc(1)\n print(\"ADC Channel 0:\", round(adc_0, 2), \"V ADC Channel 1:\", round(adc_1, 2), \"V\")\n time.sleep(0.2)\n\n except KeyboardInterrupt:\n GPIO.cleanup()\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.6319444179534912, "avg_line_length": 15, "blob_id": "78c94673f0166f9a4155002d1b7c5bc1bdb35483", "content_id": "49d3040f779e9d3c39bb4fda3655fcec96612561", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 144, "license_type": "permissive", "max_line_length": 41, "num_lines": 9, "path": "/BH1750/c/BH1750_test.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"BH1750.h\"\n\nint main()\n{\n\tint fd = wiringPiI2CSetup(BH1750_ADDR) ;\n\tprintf(\"Lux: %d \\n\", getLux(fd));\n\treturn 0 ;\n}\n" }, { "alpha_fraction": 0.5757575631141663, "alphanum_fraction": 0.6126482486724854, "avg_line_length": 16.25, "blob_id": "cf578a121419a569c72aac24c2317c238f23409d", "content_id": "069a775579391076a89abddaf8a2fb89de87a5b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 759, "license_type": "permissive", "max_line_length": 56, "num_lines": 44, "path": "/LED-RGB/c/led-rgb.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <wiringPi.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n// Red: GPIO 7, aka pin 7\nconst int pinRed = 7;\n// Green: GPIO 0, aka pin 11\nconst int pinGreen = 0;\n// Blue: GPIO 2, aka pin 13\nconst int pinBlue = 2;\n\nvoid color(int colorRed, int colorGreen, int colorBlue) \n{\n digitalWrite(pinRed, colorRed);\n digitalWrite(pinGreen, colorGreen);\n digitalWrite(pinBlue, colorBlue);\n //Wait for 1 second\n delay(1000);\n}\n\nint main()\n{\n if (-1 == wiringPiSetup())\n {\n printf(\"setup wiringPi failed!\\n\");\n return 1;\n }\n\n // Set pin mode\n pinMode(pinRed, OUTPUT);\n pinMode(pinGreen, OUTPUT);\n pinMode(pinBlue, OUTPUT);\n\n for(;;) \n {\n // Red\n color(1, 0, 0);\n // Green\n color(0, 1, 0);\n //Blue\n color(0, 0, 1);\t\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.6373477578163147, "alphanum_fraction": 0.6962110996246338, "avg_line_length": 22.229507446289062, "blob_id": "810d31bf0ec54741d041eb0483a7f7b3a8c74f96", "content_id": "df9874475288c7692f3dadc9a6502bc6c028127b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1478, "license_type": "permissive", "max_line_length": 84, "num_lines": 61, "path": "/BMP180/c/BMP180.h", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "/*\r\nRaspberry Pi Bosch BMP0180/BMP085 communication code.\r\n\r\nThis is a derivative work based on:\r\n\tJohn Burns (www.john.geek.nz)\r\n\tSource: https://www.john.geek.nz/2013/02/update-bosch-bmp085-source-raspberry-pi/ \r\n\tBMP085 Extended Example Code\r\n\tby: Jim Lindblom\r\n\tSparkFun Electronics\r\n\tdate: 1/18/11\r\n\tlicense: CC BY-SA v3.0 - http://creativecommons.org/licenses/by-sa/3.0/\r\n\tSource: http://www.sparkfun.com/tutorial/Barometric/BMP085_Example_Code.pde\r\n\r\nCircuit detail:\r\n\tUsing BMP180 Board Module\r\n\r\n\tVIN - \t3.3V (Raspberry Pi pin 1)\r\n\tGND\t-\tGND (Raspberry Pi pin 14)\r\n\tSCL \t-\tSCL (Raspberry Pi pin 5)\r\n\tSDA - \tSDA (Raspberry Pi pin 3)\r\n\t\r\n\tNote: Make sure BMP180/085 is connected to 3.3V NOT the 5V pin!\r\n\r\n\tNote: Change /dev/i2c-1 to /dev/i2c-0 if you are using the very first Raspberry Pi.\r\n*/\r\n\r\n#ifndef _BMP180_H_\r\n#define _BMP180_H_\r\n\r\n#define BMP180_I2C_ADDRESS 0x77\r\n\r\n// Set default calibration values from values in the datasheet example\r\n// After that exact values will be read from BMP180/BMP085 sensor\r\n\r\nstruct calibrate {\r\n\tshort int ac1;\r\n\tshort int ac2;\r\n\tshort int ac3;\r\n\tunsigned short int ac4;\r\n\tunsigned short int ac5;\r\n\tunsigned short int ac6;\r\n\tshort int b1;\r\n\tshort int b2;\r\n\tshort int mb;\r\n\tshort int mc;\r\n\tshort int md;\r\n} cal;\r\n\r\n// Calibrate BMP180/BMP085\r\nvoid calibration();\r\n\r\n// Calculate pressure in Pa\r\nint getPressure();\r\n\r\n// Calculate temperature in Celsius\r\ndouble getTemperature();\r\n\r\n// Calculate \r\ndouble getAltitude();\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.5663082599639893, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 22.33333396911621, "blob_id": "96f5ed0285decbc396fb201ea85caefd50725391", "content_id": "3d7e7480bbd3d71fb89b32c45c15e5e94a14984e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "permissive", "max_line_length": 43, "num_lines": 12, "path": "/pico/micropython/mini-oled-i2c-ssd1306-hello/main.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "from machine import Pin, I2C\nimport ssd1306\n\n# using default address 0x3C\nsda=machine.Pin(4)\nscl=machine.Pin(5)\ni2c = I2C(0,sda=sda, scl=scl, freq=400000)\ndisplay = ssd1306.SSD1306_I2C(128, 64, i2c)\n\ndisplay.text('Hello,', 0, 8, 1)\ndisplay.text('World!', 0, 16, 1)\ndisplay.show()" }, { "alpha_fraction": 0.4958333373069763, "alphanum_fraction": 0.5791666507720947, "avg_line_length": 14, "blob_id": "5f29d7c39cdaeda959b94ea03c8035b7d9d6512b", "content_id": "46c2fa97500922878b1938fb74b924c09d2af574", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 240, "license_type": "permissive", "max_line_length": 39, "num_lines": 16, "path": "/MAX44009/c/Makefile", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS=-I. -lm\nDEPS =\nOBJ = MAX44009.o MAX44009_test.o\nEXTRA_LIBS=-lwiringPi\n\n%.o: %.c $(DEPS)\n\t$(CC) -c -o $@ $< $(CFLAGS)\n\nMAX44009_test: $(OBJ)\n\t$(CC) -o $@ $^ $(CFLAGS) $(EXTRA_LIBS)\n\n.PHONY: clean\n\nclean:\n\trm -f MAX44009 $(OBJ)\n" }, { "alpha_fraction": 0.5533333420753479, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 15.666666984558105, "blob_id": "bc0871bf811630fd91d067bb54d24a99136276d2", "content_id": "075aa421e9b2b82dc0ee78b0b2f9a3c2d1177eb8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 150, "license_type": "permissive", "max_line_length": 43, "num_lines": 9, "path": "/MAX44009/c/MAX44009_test.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"MAX44009.h\"\n\nint main()\n{\n\tint fd = wiringPiI2CSetup(MAX44009_ADDR) ;\n\tprintf(\"Lux: %.3f \\n\", getLux(fd));\n\treturn 0 ;\n}\n" }, { "alpha_fraction": 0.46226415038108826, "alphanum_fraction": 0.5566037893295288, "avg_line_length": 13.066666603088379, "blob_id": "fe75d1e5510aa83c31384392500094e748cab131", "content_id": "c60b167f072f2641e170a7aa9ac10ac666e3732c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 212, "license_type": "permissive", "max_line_length": 30, "num_lines": 15, "path": "/TSL2561/c/example/Makefile", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS=-I.\nDEPS = TSL2561.h\nOBJ = TSL2561.o TSL2561_test.o\n\n%.o: %.c $(DEPS)\n\t$(CC) -c -o $@ $< $(CFLAGS)\n\nTSL2561_test: $(OBJ)\n\t$(CC) -o $@ $^ $(CFLAGS)\n\n.PHONY: clean\n\nclean:\n\trm -f TSL2561_test $(OBJ) \n" }, { "alpha_fraction": 0.6038960814476013, "alphanum_fraction": 0.6298701167106628, "avg_line_length": 15.5, "blob_id": "eba54f5ce86c7da8bfdb831baf210d0289b10c75", "content_id": "59003ae304920cf048a976a84c2e45581a458939", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 462, "license_type": "permissive", "max_line_length": 70, "num_lines": 28, "path": "/buzzer/c/beep.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <wiringPi.h>\n#include <stdio.h>\n\n//Pin 11 on Raspberry Pi corresponds to BCM GPIO 17 and wiringPi pin 0\n#define BeepPin 0\n\nint main(void)\n{\n if(-1 == wiringPiSetup())\n {\n printf(\"setup wiringPi failed!\");\n return 1;\n }\n\n //Set GPIO pin\n pinMode(BeepPin, OUTPUT);\n\n //Play a sound until the user closes the app\n while(1)\n {\n digitalWrite(BeepPin, LOW);\n delay(2);\n digitalWrite(BeepPin, HIGH);\n delay(2);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5401661992073059, "alphanum_fraction": 0.5844875574111938, "avg_line_length": 16.190475463867188, "blob_id": "8fbe4e84a9ec02f21e00b5cd037937998514bb50", "content_id": "a085cd1d2e0a858f5c9c930f701f364bd8608c9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 361, "license_type": "permissive", "max_line_length": 40, "num_lines": 21, "path": "/LED-SMD3528/c/Makefile", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS=-I.\nDEPS = \nOBJ1 = led-strip-smd3528.o\nOBJ2 = led-strip-smd3528-pwm.o\nEXTRA_LIBS=-lwiringPi -lpthread\nCFLAGS=-std=c99\n\n%.o: %.c $(DEPS)\n\t$(CC) -c -o $@ $< $(CFLAGS)\n\nled-blink: $(OBJ1)\n\t$(CC) -o $@ $^ $(CFLAGS) $(EXTRA_LIBS)\n\nled-pwm: $(OBJ2)\n\t$(CC) -o $@ $^ $(CFLAGS) $(EXTRA_LIBS)\n\n.PHONY: clean\n\nclean:\n\trm -f led-blink led-pwm $(OBJ1) $(OBJ2)\n" }, { "alpha_fraction": 0.5978260636329651, "alphanum_fraction": 0.654891312122345, "avg_line_length": 23.53333282470703, "blob_id": "40eb8377c7dc86eff1e51c0f5fe5cf9622053c13", "content_id": "ac929efd837a0bc820a087e09c2297fb2dc10b5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 368, "license_type": "permissive", "max_line_length": 70, "num_lines": 15, "path": "/MAX44009/c/MAX44009.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <wiringPiI2C.h>\n#include <math.h>\n#include \"MAX44009.h\"\n\nfloat getLux(int fd)\n{\n\tint vhigh = wiringPiI2CReadReg8(fd, lux_h_register);\n\tint vlow = wiringPiI2CReadReg8(fd, lux_l_register);\n\t\n\tint exponent=( vhigh & 0xF0 ) >> 4;\n\tint mantisa= ( vhigh & 0x0F ) << 4 | vlow;\n\t\n\tfloat lux= ( ( pow(2,(double)exponent) ) * (double)mantisa ) * 0.045;\n\treturn lux;\n}\n" }, { "alpha_fraction": 0.5976095795631409, "alphanum_fraction": 0.6374502182006836, "avg_line_length": 12.94444465637207, "blob_id": "d89974e0bec1c9b272c77f636d9e369111631995", "content_id": "70c4d477b41bbb460753a8832da08ab190033893", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 502, "license_type": "permissive", "max_line_length": 57, "num_lines": 36, "path": "/LED-SMD3528/c/led-strip-smd3528.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <wiringPi.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <signal.h>\n\n// Pin for controlling the LED strip: GPIO 11, aka pin 11\nconst int pinCtrl = 0;\n\nvoid close()\n{\n\tdigitalWrite(pinCtrl, 0);\n\texit(0);\n}\n\nint main()\n{\n\tsignal(SIGINT, close);\n\n\tif (-1 == wiringPiSetup())\n\t{\n\t\tprintf(\"setup wiringPi failed!\\n\");\n\t\treturn 1;\n\t}\n\n\t// Set pin mode\n\tpinMode(pinCtrl, OUTPUT);\n\n\tfor(;;) \n\t{\n\t\tdigitalWrite(pinCtrl, 1);\n\t\tdelay(1000);\n\t\tdigitalWrite(pinCtrl, 0);\n\t\tdelay(1000);\n\t}\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5560117363929749, "alphanum_fraction": 0.5950146913528442, "avg_line_length": 17.042327880859375, "blob_id": "234a31bea01dc708d4585ab3cffaf63916d859f4", "content_id": "578033da217cc112612af91e140463947499b23d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3410, "license_type": "permissive", "max_line_length": 109, "num_lines": 189, "path": "/SN754410/c/motor.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <wiringPi.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <signal.h>\n#include <softPwm.h>\n#include <ctype.h>\n#include <getopt.h>\n\nconst int speedMax = 200;\n\n// Motor 1 1st: GPIO 0, aka pin 11\nconst int motor1pin1 = 22;\n// Motor 1 2nd: GPIO 1, aka pin 12\nconst int motor1pin2 = 23;\n\n// Motor 2 1st: GPIO 3, aka pin 15\nconst int motor2pin1 = 24;\n// Motor 2 2nd: GPIO 4, aka pin 16\nconst int motor2pin2 = 25;\n\nvoid motor1(int pin1, int pin2)\n{\n digitalWrite(motor1pin1, pin1);\n digitalWrite(motor1pin2, pin2);\n}\n\nvoid motor2(int pin1, int pin2)\n{\n digitalWrite(motor2pin1, pin1);\n digitalWrite(motor2pin2, pin2);\n}\n\nvoid brake()\n{\n softPwmWrite(motor1pin1, 0);\n softPwmWrite(motor1pin2, 0);\n softPwmWrite(motor2pin1, 0);\n softPwmWrite(motor2pin2, 0);\n motor1(LOW, LOW);\n motor2(LOW, LOW);\n}\n\nvoid enablePWM(pin, speed)\n{\n if (0 != softPwmCreate(pin, 0, speed))\n {\n printf(\"ERROR: Cannot enable software PWM for pin %d\", pin);\n }\n}\n\nint init()\n{\n if (-1 == wiringPiSetup())\n {\n printf(\"setup wiringPi failed!\\n\");\n return 1;\n }\n\n signal(SIGINT, brake);\n\n // Set pin mode\n pinMode(motor1pin1, OUTPUT);\n pinMode(motor1pin2, OUTPUT);\n pinMode(motor2pin1, OUTPUT);\n pinMode(motor2pin2, OUTPUT);\n\n //Software PWM\n enablePWM(motor1pin1, speedMax);\n enablePWM(motor1pin2, speedMax);\n enablePWM(motor2pin1, speedMax);\n enablePWM(motor2pin2, speedMax);\n\n brake();\n return 0;\n}\n\nvoid forward(int speed)\n{\n softPwmWrite(motor1pin1, speed);\n softPwmWrite(motor2pin1, speed);\n\n motor1(HIGH, LOW);\n motor2(HIGH, LOW);\n}\n\nvoid back(int speed)\n{\n softPwmWrite(motor1pin2, speed);\n softPwmWrite(motor2pin2, speed);\n\n motor1(LOW, HIGH);\n motor2(LOW, HIGH);\n}\n\nright(int speed)\n{\n softPwmWrite(motor1pin2, speed);\n softPwmWrite(motor2pin2, 0);\n\n motor1(LOW, HIGH);\n motor2(LOW, LOW);\n}\n\nleft(int speed)\n{\n softPwmWrite(motor1pin2, 0);\n softPwmWrite(motor2pin2, speed);\n\n motor1(LOW, LOW);\n motor2(LOW, HIGH);\n}\n\nint main(int argc, char **argv)\n{\n char *direction = \"\";\n opterr = 0;\n int argument = 0;\n int speed = 80;\n while ((argument = getopt (argc, argv, \"d:s:\")) != -1)\n {\n switch (argument)\n {\n case 'd':\n direction = optarg;\n break;\n\n case 's':\n speed = atoi(optarg);\n break;\n\n case '?':\n if (optopt == 'd')\n {\n fprintf (stderr, \"Option -%c requires an argument: forward, back, stop, left or right.\\n\", optopt);\n }\n else if (isprint (optopt))\n {\n fprintf (stderr, \"Unknown option `-%c'.\\n\", optopt);\n }\n else\n {\n fprintf (stderr,\n \"Unknown option character `\\\\x%x'.\\n\",\n optopt);\n }\n return 1;\n\n default:\n abort();\n }\n }\n\n printf(\"Direction: %s Speed: %d\\n\", direction, speed);\n\n if (0 < init())\n {\n return 1;\n }\n\n if (0 == strcmp(direction, \"forward\"))\n {\n printf(\"Moving forward...\\n\");\n forward(speed);\n }\n else if (0 == strcmp(direction, \"back\"))\n {\n printf(\"Moving backward...\\n\");\n back(speed);\n }\n else if (0 == strcmp(direction, \"left\"))\n {\n printf(\"Turning left...\\n\");\n left(speed);\n }\n else if (0 == strcmp(direction, \"right\"))\n {\n printf(\"Turning right...\\n\");\n right(speed);\n }\n else\n {\n printf(\"Unknown direction. Stopping...\\n\");\n brake();\n return 3;\n }\n sleep(1);\n brake();\n return 0;\n}\n" }, { "alpha_fraction": 0.6211603879928589, "alphanum_fraction": 0.6825938820838928, "avg_line_length": 24.478260040283203, "blob_id": "60a7cb9ffbe8a615c689299dd0c43c25afd65350", "content_id": "bbe4cf00b53eced34d9459a9405a183b7455811d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 586, "license_type": "permissive", "max_line_length": 52, "num_lines": 23, "path": "/LM75A/python/LM75A.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n# Raspberry Pi LM75A I2C temperature sample code.\n# Author: Leon Anavi <[email protected]>\n\nimport sys\nimport smbus\n\n# By default the address of LM75A is set to 0x48\n# aka A0, A1, and A2 are set to GND (0v).\naddress = 0x48\n\n# Check if another address has been specified\nif 1 < len(sys.argv):\n\taddress = int(sys.argv[1], 16)\n\n# Read I2C data and calculate temperature\nbus = smbus.SMBus(1)\nraw = bus.read_word_data(address, 0) & 0xFFFF\nraw = ((raw << 8) & 0xFF00) + (raw >> 8)\ntemperature = (raw / 32.0) / 8.0\n# Print temperature\nprint 'Temperature: {0:0.2f} *C'.format(temperature)\n" }, { "alpha_fraction": 0.6053897738456726, "alphanum_fraction": 0.6419634222984314, "avg_line_length": 16.913793563842773, "blob_id": "2b134f2426033a830c6480228fcefe75aeb5fd3a", "content_id": "838b7df1b9831299093fe3b15f9d9dd298ad41c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1039, "license_type": "permissive", "max_line_length": 64, "num_lines": 58, "path": "/LED-SMD3528/c/led-strip-smd3528-pwm.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <wiringPi.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <signal.h>\n#include <softPwm.h>\n\n// Pin for controlling the LED strip: GPIO 11, aka pin 11\nconst int pinCtrl = 0;\n\nvoid close()\n{\n\tsoftPwmWrite(pinCtrl, 0);\n\texit(0);\n}\n\nvoid enablePWM(int pin, int speed)\n{\n\tif (0 != softPwmCreate(pin, 0, speed))\n\t{\n\t\tprintf(\"ERROR: Cannot enable software PWM for pin %d\\n\", pin);\n\t}\n}\n\nint main()\n{\n\t// Process Ctrl+C to terminate the application\n\tsignal(SIGINT, close);\n\n\tif (-1 == wiringPiSetup())\n\t{\n\t\tprintf(\"setup wiringPi failed!\\n\");\n\t\treturn 1;\n\t}\n\n\t// Enable PWM and set max value\n\tenablePWM(pinCtrl, 5);\n\n\t// Infinite loop\n\tfor(;;) \n\t{\n\t\t// Increase brightness from 20% to 100%\n\t\tfor (int fadeIn=1; fadeIn<6;fadeIn++)\n\t\t{\n\t\t\tprintf(\"Brightness: %d%\\n\", fadeIn*20);\n\t\t\tsoftPwmWrite(pinCtrl, fadeIn);\n\t\t\tdelay(3000);\n\t\t}\n\n\t\t// Decrease brightness from 80% to 40%\n\t\tfor (int fadeOut=4; fadeOut>1; fadeOut--)\n\t\t{\n\t\t\tprintf(\"Brightness: %d%\\n\", fadeOut*20);\n\t\t\tsoftPwmWrite(pinCtrl, fadeOut);\n\t\t\tdelay(3000);\n\t\t}\n\t}\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5445701479911804, "alphanum_fraction": 0.6194570064544678, "avg_line_length": 21.76344108581543, "blob_id": "150f49d7cd89e8a6ea6f92ba2bfec91afecf9c08", "content_id": "1b7f9d8edb4229ba6f80f09a87edc5c3dd75f79d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4420, "license_type": "permissive", "max_line_length": 150, "num_lines": 186, "path": "/BMP180/c/BMP180.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#include <fcntl.h>\r\n#include <stdlib.h>\r\n#include <linux/i2c-dev.h>\r\n#include <linux/i2c.h>\r\n#include <sys/ioctl.h>\r\n#include <math.h>\r\n\r\n#include \"BMP180.h\"\r\n#include \"smbus.h\"\r\n\r\nconst unsigned char BMP085_OVERSAMPLING_SETTING = 3;\r\n\r\n// Open a connection to the bmp085\r\n// Returns a file id\r\nint begin()\r\n{\r\n\tint fd = 0;\r\n\tchar *fileName = \"/dev/i2c-1\";\r\n\t\r\n\t// Open port for reading and writing\r\n\tif ((fd = open(fileName, O_RDWR)) < 0)\r\n\t{\r\n\t\texit(1);\r\n\t}\r\n\t\r\n\t// Set the port options and set the address of the device\r\n\tif (ioctl(fd, I2C_SLAVE, BMP180_I2C_ADDRESS) < 0) \r\n\t{\t\t\t\t\t\r\n\t\tclose(fd);\r\n\t\texit(1);\r\n\t}\r\n\r\n\treturn fd;\r\n}\r\n\r\n// Read two words from the BMP085 and supply it as a 16 bit integer\r\n__s32 i2cReadInt(int fd, __u8 address)\r\n{\r\n\t__s32 res = i2c_smbus_read_word_data(fd, address);\r\n\tif (0 > res) \r\n\t{\r\n\t\tclose(fd);\r\n\t\texit(1);\r\n\t}\r\n\r\n\t// Convert result to 16 bits and swap bytes\r\n\tres = ((res<<8) & 0xFF00) | ((res>>8) & 0xFF);\r\n\r\n\treturn res;\r\n}\r\n\r\n//Write a byte to the BMP085\r\nvoid i2cWriteByteData(int fd, __u8 address, __u8 value)\r\n{\r\n\tif (0 > i2c_smbus_write_byte_data(fd, address, value)) \r\n\t{\r\n\t\tclose(fd);\r\n\t\texit(1);\r\n\t}\r\n}\r\n\r\n// Read a block of data BMP085\r\nvoid i2cReadBlockData(int fd, __u8 address, __u8 length, __u8 *values)\r\n{\r\n\tif (0 > i2c_smbus_read_i2c_block_data(fd, address,length,values)) \r\n\t{\r\n\t\tclose(fd);\r\n\t\texit(1);\r\n\t}\r\n}\r\n\r\n\r\nvoid calibration()\r\n{\r\n\tint fd = begin();\r\n\tcal.ac1 = i2cReadInt(fd,0xAA);\r\n\tcal.ac2 = i2cReadInt(fd,0xAC);\r\n\tcal.ac3 = i2cReadInt(fd,0xAE);\r\n\tcal.ac4 = i2cReadInt(fd,0xB0);\r\n\tcal.ac5 = i2cReadInt(fd,0xB2);\r\n\tcal.ac6 = i2cReadInt(fd,0xB4);\r\n\tcal.b1 = i2cReadInt(fd,0xB6);\r\n\tcal.b2 = i2cReadInt(fd,0xB8);\r\n\tcal.mb = i2cReadInt(fd,0xBA);\r\n\tcal.mc = i2cReadInt(fd,0xBC);\r\n\tcal.md = i2cReadInt(fd,0xBE);\r\n\tclose(fd);\r\n}\r\n\r\n// Read the uncompensated temperature value\r\nunsigned int readRawTemperature()\r\n{\r\n\tint fd = begin();\r\n\r\n\t// Write 0x2E into Register 0xF4\r\n\t// This requests a temperature reading\r\n\ti2cWriteByteData(fd,0xF4,0x2E);\r\n\t\r\n\t// Wait at least 4.5ms\r\n\tusleep(5000);\r\n\r\n\t// Read the two byte result from address 0xF6\r\n\tunsigned int ut = i2cReadInt(fd,0xF6);\r\n\r\n\t// Close the i2c file\r\n\tclose (fd);\r\n\t\r\n\treturn ut;\r\n}\r\n\r\n// Read the uncompensated pressure value\r\nunsigned int readRawPressure()\r\n{\r\n\tint fd = begin();\r\n\r\n\t// Write 0x34+(BMP085_OVERSAMPLING_SETTING<<6) into register 0xF4\r\n\t// Request a pressure reading w/ oversampling setting\r\n\ti2cWriteByteData(fd,0xF4,0x34 + (BMP085_OVERSAMPLING_SETTING<<6));\r\n\r\n\t// Wait for conversion, delay time dependent on oversampling setting\r\n\tusleep((2 + (3<<BMP085_OVERSAMPLING_SETTING)) * 1000);\r\n\r\n\t// Read the three byte result from 0xF6\r\n\t// 0xF6 = MSB, 0xF7 = LSB and 0xF8 = XLSB\r\n\t__u8 values[3];\r\n\ti2cReadBlockData(fd, 0xF6, 3, values);\r\n\r\n\tunsigned int up = (((unsigned int) values[0] << 16) | ((unsigned int) values[1] << 8) | (unsigned int) values[2]) >> (8-BMP085_OVERSAMPLING_SETTING);\r\n\r\n\t// Close the i2c file\r\n\tclose (fd);\r\n\t\r\n\treturn up;\r\n}\r\n\r\nint compensateTemperature()\r\n{\r\n\tunsigned int ut = readRawTemperature();\r\n\tint x1 = (((int)ut - (int)cal.ac6)*(int)cal.ac5) >> 15;\r\n \tint x2 = ((int)cal.mc << 11)/(x1 + cal.md);\r\n\treturn x1 + x2;\r\n}\r\n\r\n// Calculate pressure given uncalibrated pressure\r\n// Value returned will be in units of Pa\r\nint getPressure()\r\n{\r\n\tunsigned int up = readRawPressure();\r\n\r\n\tint b6 = compensateTemperature() - 4000;\r\n\t// Calculate B3\r\n\tint x1 = (cal.b2 * (b6 * b6)>>12)>>11;\r\n\tint x2 = (cal.ac2 * b6)>>11;\r\n\tint x3 = x1 + x2;\r\n\tint b3 = (((((int) cal.ac1)*4 + x3)<<BMP085_OVERSAMPLING_SETTING) + 2)>>2;\r\n \r\n\t// Calculate B4\r\n\tx1 = (cal.ac3 * b6)>>13;\r\n\tx2 = (cal.b1 * ((b6 * b6)>>12))>>16;\r\n\tx3 = ((x1 + x2) + 2)>>2;\r\n\tunsigned int b4 = (cal.ac4 * (unsigned int)(x3 + 32768))>>15;\r\n \r\n\tunsigned int b7 = ((unsigned int)(up - b3) * (50000>>BMP085_OVERSAMPLING_SETTING));\r\n\tint p = (b7 < 0x80000000) ? (b7<<1)/b4 : (b7/b4)<<1;\r\n\tx1 = (p>>8) * (p>>8);\r\n\tx1 = (x1 * 3038)>>16;\r\n\tx2 = (-7357 * p)>>16;\r\n\tp += (x1 + x2 + 3791)>>4;\r\n \r\n\treturn p;\r\n}\r\n\r\n// Calculate temperature given uncalibrated temperature\r\ndouble getTemperature()\r\n{\r\n\t// Retrieve temperature in units of 0.1 deg C\r\n\tint rawTemperature = ((compensateTemperature() + 8)>>4); \r\n\treturn ((double)rawTemperature)/10;\r\n}\r\n\r\ndouble getAltitude()\r\n{\r\n\tdouble pressure = getPressure();\r\n\t// Sea level pressure: 101325.0\r\n\treturn 44330.0 * (1.0 - pow(pressure / 101325.0, (1.0/5.255)));\r\n}\r\n" }, { "alpha_fraction": 0.6643757224082947, "alphanum_fraction": 0.7136311531066895, "avg_line_length": 33.91999816894531, "blob_id": "2e8d95b2bc09c3678f428d66f8756379487872b4", "content_id": "0fcb8dffb0a0e542aac6aefc3d4bb50661f25060", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 873, "license_type": "permissive", "max_line_length": 94, "num_lines": 25, "path": "/SSD1306/ssd1306-demo.py", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "# Install with:\n# sudo apt-get install -y python3-dev python3-pip libfreetype6-dev libjpeg-dev build-essential\n# sudo -H pip3 install --upgrade luma.oled\n# \n# Run with:\n# \n\nfrom luma.core.interface.serial import i2c\nfrom luma.core.render import canvas\nfrom luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\nimport time\nfrom PIL import ImageFont, ImageDraw\n\nserial = i2c(port=1, address=0x3C)\ndevice = ssd1306(serial, rotate=0)\n\n# Box and text rendered in portrait mode\nwith canvas(device) as draw:\n draw.rectangle(device.bounding_box, outline=\"white\", fill=\"black\")\n font = ImageFont.load_default()\n draw.text((10, 5), \"Example\", fill=\"white\", font=font)\n draw.text((15, 25), \"Hello\", fill=\"white\", font=font)\n font = ImageFont.truetype('./FreePixel.ttf', 20)\n draw.text((15, 35), \"World\", fill=\"white\", font=font)\ninput(\"Press Enter to exit...\")\n" }, { "alpha_fraction": 0.5446428656578064, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 22.578947067260742, "blob_id": "8eb363cb2ca058419a57c54104747ddbfebc842e", "content_id": "8a6a786bd98adf7ab6c2e77c19bf92bf5f9232b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 448, "license_type": "permissive", "max_line_length": 50, "num_lines": 19, "path": "/LM75A/bash/lm75a.sh", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Raspberry Pi LM75A I2C temperature sample code.\n# Author: Leon Anavi <[email protected]>\n\n# By default the address of LM75A is set to 0x48\n# aka A0, A1, and A2 are set to GND (0v).\naddress=0x48\n\n# Check if another address has been specified\nif [ ! -z \"$1\" ]; then\n\taddress=$1\nfi\n\n# Read from I2C and print temperature \ni2cget -y 1 $address 0x00 w |\nawk '{printf(\"%.2f\\n\", (a=( \\\n((\"0x\"substr($1,5,2)substr($1,3,1))*0.0625)+0.1) \\\n)>128?a-256:a)}'\n" }, { "alpha_fraction": 0.6162420511245728, "alphanum_fraction": 0.6703821420669556, "avg_line_length": 24.632652282714844, "blob_id": "994c0eaf6d58d6fd565bfebb6b3295f31ec6aca2", "content_id": "905fa8c0bb5d7fb1d1fe96dea6a7f09b06cd5bd1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1256, "license_type": "permissive", "max_line_length": 73, "num_lines": 49, "path": "/LM75A/c/LM75A.c", "repo_name": "fabiocasolari/rpi-examples", "src_encoding": "UTF-8", "text": "/*\nRaspberry Pi LM75A IC2 temperature sample code.\n\nAuthor: Leon Anavi <[email protected]>\n\nFor more information and other samples for Raspberry Pi visit:\nhttps://github.com/leon-anavi/rpi-examples\n\nCircuit detail:\n\tUsing CJMCU-75 (LM75A) Board Module\n\tVIN - \t3.3V (Raspberry Pi pin 1)\n\tGND\t-\tGND (Raspberry Pi pin 14)\n SDA - SDA (Raspberry Pi pin 3)\n\tSCL \t-\tSCL (Raspberry Pi pin 5)\n\t\n\tNote: Make sure LM75A is connected to 3.3V NOT the 5V pin!\n\nSlave address:\n\tBy default the application uses I2C address 0x48.\n\tSolder pins A0, A1 and A2 of LM75A to ground to use the default address.\n\n\tOtherwise, you can specify another address as a command line argument,\n\tfor example: ./LM75A 0x4c\n*/\n#include <stdio.h>\n#include <wiringPiI2C.h>\n\nfloat getTemperature(int fd)\n{\n\tint raw = wiringPiI2CReadReg16(fd, 0x00);\n\traw = ((raw << 8) & 0xFF00) + (raw >> 8);\n\treturn (float)((raw / 32.0) / 8.0);\n}\n \nint main(int argc, char *argv[]) \n{\n\t/* By default the address of LM75A is set to 0x48\n\t aka A0, A1, and A2 are set to GND (0v). */\n\tint address = 0x48;\n\tif (1 < argc)\n\t{\n\t\taddress = (int)strtol(argv[1], NULL, 0);\n\t}\n\n\t/* Read from I2C and print temperature */\n\tint fd = wiringPiI2CSetup(address);\n\tprintf(\"%.2f\\n\", getTemperature(fd) );\n\treturn 0;\n}\n" } ]
37
H3adcra5h/rhasspy-hermes-app
https://github.com/H3adcra5h/rhasspy-hermes-app
934106719ec170acafc284ad65c3d05e92a954fa
6c646b9430ac3ce152a33fc36b2617c1911e352f
6d0b197d5638cd6386e3fbb3b9a4e0437e5417bc
refs/heads/master
2023-02-27T10:36:43.072825
2021-02-02T11:28:34
2021-02-02T11:28:34
269,100,923
0
0
MIT
2020-06-03T13:51:08
2021-02-02T10:48:11
2021-02-02T11:28:34
Python
[ { "alpha_fraction": 0.7492446899414062, "alphanum_fraction": 0.7492446899414062, "avg_line_length": 30.03125, "blob_id": "796b124dd51bd2a60ca21cfefa7679efa353dd2f", "content_id": "0121c11dc4b06ee52aa43615e704543a78958f46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 993, "license_type": "permissive", "max_line_length": 82, "num_lines": 32, "path": "/tests/test_nlu.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Tests for rhasspyhermes_app NLU.\"\"\"\n# pylint: disable=protected-access,too-many-function-args\nimport asyncio\n\nimport pytest\nfrom rhasspyhermes.nlu import NluIntentNotRecognized\n\nfrom rhasspyhermes_app import HermesApp\n\nINR_TOPIC = \"hermes/nlu/intentNotRecognized\"\nINR = NluIntentNotRecognized(input=\"covfefe\")\n\n_LOOP = asyncio.get_event_loop()\n\n\[email protected]\nasync def test_callbacks_intent_not_recognized(mocker):\n \"\"\"Test intent not recognized callbacks.\"\"\"\n app = HermesApp(\"Test intentNotRecognized\", mqtt_client=mocker.MagicMock())\n\n # Mock callback and apply on_intent_not_recognized decorator.\n inr = mocker.MagicMock()\n app.on_intent_not_recognized(inr)\n\n # Simulate app.run() without the MQTT client.\n app._subscribe_callbacks()\n\n # Simulate intent not recognized message.\n await app.on_raw_message(INR_TOPIC, INR.to_json())\n\n # Check whether callback has been called with the right Rhasspy Hermes object.\n inr.assert_called_once_with(INR)\n" }, { "alpha_fraction": 0.7171491980552673, "alphanum_fraction": 0.7249442934989929, "avg_line_length": 41.761905670166016, "blob_id": "e7979f0b40fb3f31fa8e8532a1e4578dbf28f705", "content_id": "421166275fe029678b34d9743f3d9f93ccaa7965", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1796, "license_type": "permissive", "max_line_length": 235, "num_lines": 42, "path": "/docs/development.rst", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "###########\nDevelopment\n###########\n\nYou can find the code of Rhasspy Hermes App `on GitHub`_.\n\n.. _`on GitHub`: https://github.com/rhasspy/rhasspy-hermes-app\n\nRhasspy Hermes App is actively seeking contributions. If you want to start developing, have a look at the `Contributing <https://rhasspy.readthedocs.io/en/latest/contributing/>`_ page of the Rhasspy project for some general guidelines.\n\nThe project's documentation is generated with:\n\n.. code-block:: shell\n\n make docs\n\nThis also checks all references in the documentation and the docstrings in the code. The generated documentation can be previewed in ``docs/build``.\n\n*****************\nThings to work on\n*****************\n\nIf you want to help, have a look at the issues in the `issue tracker`_, especially the following categories:\n\n- `help wanted`_: Issues that could use some extra help.\n- `good first issue`_: Issues that are good for newcomers to the project.\n\n.. _`help wanted`: https://github.com/rhasspy/rhasspy-hermes-app/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22\n\n.. _`good first issue`: https://github.com/rhasspy/rhasspy-hermes-app/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22\n\nBefore starting significant work, please discuss it first on the issue tracker. If there's no issue yet about the work you want to start, feel free to open a new issue.\n\n.. _`issue tracker`: https://github.com/rhasspy/rhasspy-hermes-app/issues\n\n************************\nLicense of contributions\n************************\n\nBy submitting patches to this project, you agree to allow them to be redistributed under the project's :doc:`license` according to the normal forms and usages of the open-source community.\n\nIt is your responsibility to make sure you have all the necessary rights to contribute to the project.\n" }, { "alpha_fraction": 0.5142857432365417, "alphanum_fraction": 0.7035714387893677, "avg_line_length": 16.5, "blob_id": "dc3869ef03d8edfbfe329c8e172f11d777c50791", "content_id": "aa97b0bb719842f023e669dc73af91ae8cb0d73f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 280, "license_type": "permissive", "max_line_length": 33, "num_lines": 16, "path": "/requirements_dev.txt", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "Sphinx==3.4.3\nblack==20.8b1\ncoverage==5.4\nflake8==3.8.4\nlxml==4.6.2\nmypy==0.800\npylint==2.6.0\npytest==6.2.2\npytest-asyncio==0.12.0\npytest-cov==2.11.1\npytest-mock==3.5.1\npytest-sugar==0.9.4\nrstcheck==3.3.1\nsphinx_rtd_theme==0.5.1\nsphinxcontrib-programoutput==0.16\nyamllint==1.26.0\n" }, { "alpha_fraction": 0.6654719114303589, "alphanum_fraction": 0.6678614020347595, "avg_line_length": 30, "blob_id": "23a012f680946f703cddad9f45da51021aa4dc0b", "content_id": "b5080f245a11ef2e018b1837e247bb3cc1c08062", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 837, "license_type": "permissive", "max_line_length": 85, "num_lines": 27, "path": "/examples/raw_topic_list_app.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Example app using topic lists for receiving raw MQTT messages.\"\"\"\nimport logging\n\nfrom rhasspyhermes_app import HermesApp, TopicData\n\n_LOGGER = logging.getLogger(\"RawTopicApp\")\n\napp = HermesApp(\"RawTopicApp\")\n\n\[email protected]_topic(\n \"hermes/dialogueManager/sessionStarted\",\n \"hermes/hotword/{hotword}/detected\",\n \"hermes/tts/+\",\n \"hermes/+/{site_id}/playBytes/#\",\n)\nasync def test_topic1(data: TopicData, payload: bytes):\n \"\"\"Receive MQTT messages for the subscribed topics.\"\"\"\n if \"hotword\" in data.topic:\n _LOGGER.debug(\"topic: %s, hotword: %s\", data.topic, data.data.get(\"hotword\"))\n elif \"playBytes\" in data.topic:\n _LOGGER.debug(\"topic: %s, site_id: %s\", data.topic, data.data.get(\"site_id\"))\n else:\n _LOGGER.debug(\"topic: %s, payload: %s\", data.topic, payload.decode(\"utf-8\"))\n\n\napp.run()\n" }, { "alpha_fraction": 0.6517857313156128, "alphanum_fraction": 0.6517857313156128, "avg_line_length": 15, "blob_id": "65c394fd161313b68885a72bdbbb8efc77d0bcc8", "content_id": "756294c6f88b7b358114784227c75c9169454f4f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 112, "license_type": "permissive", "max_line_length": 61, "num_lines": 7, "path": "/docs/license.rst", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "#######\nLicense\n#######\n\nRhasspy Hermes App is distributed with the following license:\n\n.. include:: ../LICENSE\n" }, { "alpha_fraction": 0.6760797500610352, "alphanum_fraction": 0.6760797500610352, "avg_line_length": 24.08333396911621, "blob_id": "265f5c8819485b864de619f01adbef567b4fb2c2", "content_id": "4aea15aee2bc4e56ac3eb3751d12bd564c215c4f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1204, "license_type": "permissive", "max_line_length": 84, "num_lines": 48, "path": "/examples/continue_session.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Example app that shows how to continue a session.\"\"\"\nimport logging\n\nfrom rhasspyhermes.nlu import NluIntent\n\nfrom rhasspyhermes_app import ContinueSession, EndSession, HermesApp\n\n_LOGGER = logging.getLogger(\"ContinueApp\")\n\napp = HermesApp(\"ContinueApp\")\n\n\[email protected]_intent(\"Yes\")\nasync def yes(intent: NluIntent):\n \"\"\"The user confirms.\"\"\"\n if intent.custom_data == \"TurnOffLight\":\n response = \"OK, turning off the light\"\n elif intent.custom_data == \"TurnOnLight\":\n response = \"OK, turning on the light\"\n else:\n response = \"We can!\"\n\n return EndSession(response)\n\n\[email protected]_intent(\"No\")\nasync def no(intent: NluIntent):\n \"\"\"The user says no.\"\"\"\n return EndSession()\n\n\[email protected]_intent(\"TurnOffLight\")\nasync def turn_off_light(intent: NluIntent):\n \"\"\"The user asks to turn off the light.\"\"\"\n return ContinueSession(\n text=\"Do you really want to turn off the light?\", custom_data=\"TurnOffLight\"\n )\n\n\[email protected]_intent(\"TurnOnLight\")\nasync def turn_on_light(intent: NluIntent):\n \"\"\"The user asks to turn on the light.\"\"\"\n return ContinueSession(\n text=\"Do you really want to turn on the light?\", custom_data=\"TurnOnLight\"\n )\n\n\napp.run()\n" }, { "alpha_fraction": 0.6896825432777405, "alphanum_fraction": 0.6920635104179382, "avg_line_length": 30.5, "blob_id": "cee1fea3d503d7b06d9cec289024b49f48ad15fc", "content_id": "963e7469b81cd4c18f15576a162f363e9b34f363", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1260, "license_type": "permissive", "max_line_length": 100, "num_lines": 40, "path": "/examples/async_advice_app.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Example app to react to an intent to tell you the time.\"\"\"\nimport json\nimport logging\n\nimport aiohttp # pylint: disable=import-error\nfrom rhasspyhermes.nlu import NluIntent\n\nfrom rhasspyhermes_app import EndSession, HermesApp\n\n_LOGGER = logging.getLogger(\"AdviceApp\")\n\napp = HermesApp(\"AdviceApp\")\n\n\"\"\"\nThis is JUST an example!\nNone of the authors, contributors, administrators, or anyone else connected with Rhasspy_Hermes_App,\nin any way whatsoever, can be responsible for your use of the api endpoint.\n\"\"\"\nURL = \"https://api.adviceslip.com/advice\"\n\n\[email protected]_intent(\"GetAdvice\")\nasync def get_advice(intent: NluIntent):\n \"\"\"Giving life advice.\"\"\"\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(URL) as response:\n data = await response.read()\n message = json.loads(data)\n return EndSession(str(message[\"slip\"][\"advice\"]))\n except aiohttp.ClientConnectionError:\n _LOGGER.exception(\"No Connection could be established.\")\n except: # noqa: E722 pylint: disable=bare-except\n _LOGGER.exception(\"An Exception occured\")\n return EndSession(\n \"Sadly i cannot connect to my spring my whisdom. Maybe try later again.\"\n )\n\n\napp.run()\n" }, { "alpha_fraction": 0.5795918107032776, "alphanum_fraction": 0.5795918107032776, "avg_line_length": 19.41666603088379, "blob_id": "ca924078d0f36f217e6b329f045fc29833c51f33", "content_id": "1d59d34f65eb4bcc02758acf06cc7b959834e43f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 245, "license_type": "permissive", "max_line_length": 98, "num_lines": 12, "path": "/docs/api.rst", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "#############\nAPI reference\n#############\n\nThis is the API documentation of the Rhasspy Hermes App package, covering all modules and classes.\n\n*****************\nrhasspyhermes_app\n*****************\n\n.. automodule:: rhasspyhermes_app\n :members:\n" }, { "alpha_fraction": 0.7369242906570435, "alphanum_fraction": 0.7423887848854065, "avg_line_length": 30.2439022064209, "blob_id": "98f2c34b0226f618eb28207c3232b6db5ab6724c", "content_id": "86f80de03f0c6f2db8c4b5e88f6912b7c2acf387", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1281, "license_type": "permissive", "max_line_length": 82, "num_lines": 41, "path": "/tests/test_hotword.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Tests for rhasspyhermes_app hotword.\"\"\"\n# pylint: disable=protected-access,too-many-function-args\nimport asyncio\n\nimport pytest\nfrom rhasspyhermes.wake import HotwordDetected\n\nfrom rhasspyhermes_app import HermesApp\n\nHOTWORD_TOPIC = \"hermes/hotword/test/detected\"\nHOTWORD = HotwordDetected(\"test_model\")\nHOTWORD_TOPIC2 = \"hermes/hotword/test2/detected\"\nHOTWORD2 = HotwordDetected(\"test_model2\")\n\n_LOOP = asyncio.get_event_loop()\n\n\[email protected]\nasync def test_callbacks_hotword(mocker):\n \"\"\"Test hotword callbacks.\"\"\"\n app = HermesApp(\"Test HotwordDetected\", mqtt_client=mocker.MagicMock())\n\n # Mock wake callback and apply on_hotword decorator.\n wake = mocker.MagicMock()\n app.on_hotword(wake)\n\n # Simulate app.run() without the MQTT client.\n app._subscribe_callbacks()\n\n # Simulate detected hotword.\n await app.on_raw_message(HOTWORD_TOPIC, HOTWORD.to_json())\n\n # Check whether callback has been called with the right Rhasspy Hermes object.\n wake.assert_called_once_with(HOTWORD)\n\n # Simulate another detected hotword.\n wake.reset_mock()\n await app.on_raw_message(HOTWORD_TOPIC2, HOTWORD2.to_json())\n\n # Check whether callback has been called with the right Rhasspy Hermes object.\n wake.assert_called_once_with(HOTWORD2)\n" }, { "alpha_fraction": 0.7734219431877136, "alphanum_fraction": 0.7734219431877136, "avg_line_length": 74.25, "blob_id": "08530f66bb8396bf1dbb8c3458f0bc8b221065db", "content_id": "80a1e17f99cac18a3ebc3572c4607acf87aa350a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1505, "license_type": "permissive", "max_line_length": 355, "num_lines": 20, "path": "/docs/rationale.rst", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "Rationale\n=========\n\n`Rhasspy Hermes`_ is an extensive library implementing Hermes protocol support in Rhasspy. It implements a lot of the low-level details such as MQTT communication and converting JSON payloads and binary payloads to more usable Python classes. Thanks to the HermesClient_ class and the cli_ module, you can easily implement a Rhasspy 'app'.\n\n.. _`Rhasspy Hermes`: https://github.com/rhasspy/rhasspy-hermes/\n\n.. _HermesClient: https://github.com/rhasspy/rhasspy-hermes/blob/master/rhasspyhermes/client.py\n\n.. _cli: https://github.com/rhasspy/rhasspy-hermes/blob/master/rhasspyhermes/cli.py\n\nHowever, the result `still needs a lot of lines of code`_. If you want to have control over the finer details of the Rhasspy Hermes library, this is fine. But if you just want to create a simple voice app that tells you the time, it should be easier. This is where the Rhasspy Hermes App library comes in. Its lets you write code such as `the following`_:\n\n.. _`still needs a lot of lines of code`: https://github.com/rhasspy/rhasspy-hermes-app/blob/master/examples/time_app_direct.py\n\n.. _`the following`: https://github.com/rhasspy/rhasspy-hermes-app/blob/master/examples/time_app.py\n\n.. literalinclude:: ../examples/time_app.py\n\nIn fact, the code using Rhasspy Hermes directly and the one using Rhasspy Hermes App are doing exactly the same. Thanks to the extra abstraction layer of the Rhasspy Hermes App library, a few lines of code are enough to start a whole machinery behind the scenes.\n" }, { "alpha_fraction": 0.5717461109161377, "alphanum_fraction": 0.5826129913330078, "avg_line_length": 28.992591857910156, "blob_id": "e875033dcec2370b6d18340e06e30229376e7f65", "content_id": "0f2d3515fedddf75e55e21775a6a2b7c9d473610", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4049, "license_type": "permissive", "max_line_length": 98, "num_lines": 135, "path": "/tests/test_arguments.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Tests for HermesApp arguments.\"\"\"\n# pylint: disable=no-member\nimport argparse\n\nfrom rhasspyhermes_app import HermesApp\n\n\ndef test_default_arguments(mocker):\n \"\"\"Test whether default arguments are set up correctly in a HermesApp object.\"\"\"\n app = HermesApp(\"Test default arguments\", mqtt_client=mocker.MagicMock())\n\n assert app.args.host == \"localhost\"\n assert app.args.port == 1883\n assert app.args.tls is False\n assert app.args.username is None\n assert app.args.password is None\n\n\ndef test_arguments_from_cli(mocker):\n \"\"\"Test whether arguments from the command line are set up correctly in a HermesApp object.\"\"\"\n mocker.patch(\n \"sys.argv\",\n [\n \"rhasspy-hermes-app-test\",\n \"--host\",\n \"rhasspy.home\",\n \"--port\",\n \"8883\",\n \"--tls\",\n \"--username\",\n \"rhasspy-hermes-app\",\n \"--password\",\n \"test\",\n ],\n )\n app = HermesApp(\"Test arguments in init\", mqtt_client=mocker.MagicMock())\n\n assert app.args.host == \"rhasspy.home\"\n assert app.args.port == 8883\n assert app.args.tls is True\n assert app.args.username == \"rhasspy-hermes-app\"\n assert app.args.password == \"test\"\n\n\ndef test_arguments_in_init(mocker):\n \"\"\"Test whether arguments are set up correctly while initializing a HermesApp object.\"\"\"\n app = HermesApp(\n \"Test arguments in init\",\n mqtt_client=mocker.MagicMock(),\n host=\"rhasspy.home\",\n port=8883,\n tls=True,\n username=\"rhasspy-hermes-app\",\n password=\"test\",\n )\n\n assert app.args.host == \"rhasspy.home\"\n assert app.args.port == 8883\n assert app.args.tls is True\n assert app.args.username == \"rhasspy-hermes-app\"\n assert app.args.password == \"test\"\n\n\ndef test_if_cli_arguments_overwrite_init_arguments(mocker):\n \"\"\"Test whether arguments from the command line overwrite arguments to a HermesApp object.\"\"\"\n mocker.patch(\n \"sys.argv\",\n [\n \"rhasspy-hermes-app-test\",\n \"--host\",\n \"rhasspy.home\",\n \"--port\",\n \"1883\",\n \"--username\",\n \"rhasspy-hermes-app\",\n \"--password\",\n \"test\",\n ],\n )\n app = HermesApp(\n \"Test arguments in init\",\n mqtt_client=mocker.MagicMock(),\n host=\"rhasspy.local\",\n port=8883,\n username=\"rhasspy-hermes-app-test\",\n password=\"covfefe\",\n )\n\n assert app.args.host == \"rhasspy.home\"\n assert app.args.port == 1883\n assert app.args.username == \"rhasspy-hermes-app\"\n assert app.args.password == \"test\"\n\n\ndef test_if_cli_arguments_overwrite_init_arguments_with_argument_parser(mocker):\n \"\"\"Test whether arguments from the command line overwrite arguments to a HermesApp object\n if the user supplies their own ArgumentParser object.\"\"\"\n mocker.patch(\n \"sys.argv\",\n [\n \"rhasspy-hermes-app-test\",\n \"--host\",\n \"rhasspy.home\",\n \"--port\",\n \"1883\",\n \"--username\",\n \"rhasspy-hermes-app\",\n \"--password\",\n \"test\",\n \"--test-argument\",\n \"foobar\",\n \"--test-flag\",\n ],\n )\n parser = argparse.ArgumentParser(prog=\"rhasspy-hermes-app-test\")\n parser.add_argument(\"--test-argument\", default=\"foo\")\n parser.add_argument(\"--test-flag\", action=\"store_true\")\n\n app = HermesApp(\n \"Test arguments in init\",\n parser=parser,\n mqtt_client=mocker.MagicMock(),\n host=\"rhasspy.local\",\n port=8883,\n username=\"rhasspy-hermes-app-test\",\n password=\"covfefe\",\n test_argument=\"bar\",\n )\n\n assert app.args.host == \"rhasspy.home\"\n assert app.args.port == 1883\n assert app.args.username == \"rhasspy-hermes-app\"\n assert app.args.password == \"test\"\n assert app.args.test_argument == \"foobar\"\n assert app.args.test_flag is True\n" }, { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 21, "blob_id": "6e4ade759a330a8b1ebd04ac1f5f7696aae23514", "content_id": "186b570f7638c3a4d08a081109f1449bf9d6dc64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 22, "license_type": "permissive", "max_line_length": 21, "num_lines": 1, "path": "/requirements.txt", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "rhasspy-hermes==0.5.0\n" }, { "alpha_fraction": 0.6608623266220093, "alphanum_fraction": 0.6699833869934082, "avg_line_length": 29.149999618530273, "blob_id": "e5a98c649b1bef6f5e3716349004e4754a9d3fe4", "content_id": "5dced64b78d452a92a058ef541676679fc11c484", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1206, "license_type": "permissive", "max_line_length": 82, "num_lines": 40, "path": "/examples/raw_topic_app.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Example app using topic for receiving raw MQTT messages.\"\"\"\nimport logging\n\nfrom rhasspyhermes_app import HermesApp, TopicData\n\n_LOGGER = logging.getLogger(\"RawTopicApp\")\n\napp = HermesApp(\"RawTopicApp\")\n\n\[email protected]_topic(\"hermes/hotword/{hotword}/detected\")\nasync def test_topic1(data: TopicData, payload: bytes):\n \"\"\"Receive topic with template.\"\"\"\n _LOGGER.debug(\n \"topic1: %s, hotword: %s, payload: %s\",\n data.topic,\n data.data.get(\"hotword\"),\n payload.decode(\"utf-8\"),\n )\n\n\[email protected]_topic(\"hermes/dialogueManager/sessionStarted\")\nasync def test_topic2(data: TopicData, payload: bytes):\n \"\"\"Receive verbatim topic.\"\"\"\n _LOGGER.debug(\"topic2: %s, payload: %s\", data.topic, payload.decode(\"utf-8\"))\n\n\[email protected]_topic(\"hermes/tts/+\")\nasync def test_topic3(data: TopicData, payload: bytes):\n \"\"\"Receive topic with wildcard.\"\"\"\n _LOGGER.debug(\"topic3: %s, payload: %s\", data.topic, payload.decode(\"utf-8\"))\n\n\[email protected]_topic(\"hermes/+/{site_id}/playBytes/#\")\nasync def test_topic4(data: TopicData, payload: bytes):\n \"\"\"Receive topic with wildcards and template.\"\"\"\n _LOGGER.debug(\"topic4: %s, site_id: %s\", data.topic, data.data.get(\"site_id\"))\n\n\napp.run()\n" }, { "alpha_fraction": 0.7231712937355042, "alphanum_fraction": 0.739378035068512, "avg_line_length": 34.671875, "blob_id": "9795b7a48333d21795aa776f465dfb49ed60b75f", "content_id": "eebeaaec297d21b38a1daa4882ee906b073aee59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2283, "license_type": "permissive", "max_line_length": 89, "num_lines": 64, "path": "/tests/test_intent.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Tests for rhasspyhermes_app intent.\"\"\"\n# pylint: disable=protected-access,too-many-function-args\nimport asyncio\n\nimport pytest\nfrom rhasspyhermes.intent import Intent\nfrom rhasspyhermes.nlu import NluIntent\n\nfrom rhasspyhermes_app import HermesApp\n\nINTENT_NAME = \"GetTime\"\nINTENT_TOPIC = f\"hermes/intent/{INTENT_NAME}\"\nINTENT = Intent(INTENT_NAME, 1.0)\nNLU_INTENT = NluIntent(\"what time is it\", INTENT)\n\nINTENT_NAME2 = \"GetTemperature\"\nINTENT_TOPIC2 = f\"hermes/intent/{INTENT_NAME2}\"\nINTENT2 = Intent(INTENT_NAME2, 1.0)\nNLU_INTENT2 = NluIntent(\"what's the temperature\", INTENT2)\n\nINTENT_NAME3 = \"GetWeather\"\nINTENT_TOPIC3 = f\"hermes/intent/{INTENT_NAME3}\"\nINTENT3 = Intent(INTENT_NAME3, 1.0)\nNLU_INTENT3 = NluIntent(\"how's the weather\", INTENT3)\n\n_LOOP = asyncio.get_event_loop()\n\n\[email protected]\nasync def test_callbacks_intent(mocker):\n \"\"\"Test intent callbacks.\"\"\"\n app = HermesApp(\"Test NluIntent\", mqtt_client=mocker.MagicMock())\n\n # Mock intent callback and apply on_intent decorator.\n intent_handler = mocker.MagicMock()\n app.on_intent(INTENT_NAME)(intent_handler)\n\n intent_handler2 = mocker.MagicMock()\n app.on_intent(INTENT_NAME2, INTENT_NAME3)(intent_handler2)\n\n # Simulate app.run() without the MQTT client.\n app._subscribe_callbacks()\n\n # Simulate detected intent GetTime.\n await app.on_raw_message(INTENT_TOPIC, NLU_INTENT.to_json())\n # Check whether intent_handler has been called with the right Rhasspy Hermes object.\n intent_handler.assert_called_once_with(NLU_INTENT)\n intent_handler2.assert_not_called()\n\n # Simulate intent GetTemperature.\n intent_handler.reset_mock()\n intent_handler2.reset_mock()\n await app.on_raw_message(INTENT_TOPIC2, NLU_INTENT2.to_json())\n # Check whether intent_handler2 has been called with the right Rhasspy Hermes object.\n intent_handler2.assert_called_once_with(NLU_INTENT2)\n intent_handler.assert_not_called()\n\n # Simulate intent GetWeather.\n intent_handler.reset_mock()\n intent_handler2.reset_mock()\n # Check whether intent_handler2 has been called with the right Rhasspy Hermes object.\n await app.on_raw_message(INTENT_TOPIC3, NLU_INTENT3.to_json())\n intent_handler2.assert_called_once_with(NLU_INTENT3)\n intent_handler.assert_not_called()\n" }, { "alpha_fraction": 0.6285623908042908, "alphanum_fraction": 0.6627612709999084, "avg_line_length": 30.26732635498047, "blob_id": "5360b2e738fef50ecea7841ba733b11840742543", "content_id": "af0cee07669e35598cfa0677cf5b49da560261c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3158, "license_type": "permissive", "max_line_length": 379, "num_lines": 101, "path": "/docs/changelog.rst", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "#########\nChangelog\n#########\n\nAll notable changes to the Rhasspy Hermes App project are documented in this file.\n\nThe format is based on `Keep a Changelog`_, and this project adheres to the `Semantic Versioning`_ specification with major, minor and patch version.\n\nGiven a version number major.minor.patch this project increments the:\n\n- major version when incompatible API changes are made;\n- minor version when functionality is added in a backwards-compatible manner;\n- patch version when backwards-compatible bug fixes are made.\n\n.. _`Keep a Changelog`: https://keepachangelog.com/en/1.0.0/\n\n.. _`Semantic Versioning`: https://semver.org\n\n**********\nUnreleased\n**********\n\nCommits `since last release`_:\n\n.. _`since last release`: https://github.com/rhasspy/rhasspy-hermes-app/compare/v1.1.1...HEAD\n\nAdded\n=====\n\nChanged\n=======\n\nDeprecated\n==========\n\nRemoved\n=======\n\nFixed\n=====\n\nSecurity\n========\n\n*********************\n`1.1.1`_ - 2021-01-13\n*********************\n\n.. _`1.1.1`: https://github.com/rhasspy/rhasspy-hermes-app/releases/tag/v1.1.1\n\nChanged\n=======\n\n- Updated dependencies. The most important one is the upgrade to rhasspy-hermes 0.5.0.\n\n*********************\n`1.1.0`_ - 2020-08-28\n*********************\n\n.. _`1.1.0`: https://github.com/rhasspy/rhasspy-hermes-app/releases/tag/v1.1.0\n\nChanged\n=======\n\n- Command-line arguments can now also be passed as keyword arguments to the constructor of a :class:`rhasspyhermes_app.HermesApp` object. Note that arguments on the command line have precedence. Pull request `#37 <https://github.com/rhasspy/rhasspy-hermes-app/pull/37>`_ by `@JonahKr <https://github.com/JonahKr>`_ with help from `@maxbachmann <https://github.com/maxbachmann>`_.\n\n*********************\n`1.0.0`_ - 2020-07-26\n*********************\n\n.. _`1.0.0`: https://github.com/rhasspy/rhasspy-hermes-app/releases/tag/v1.0.0\n\nChanged\n=======\n\n- All decorators of this library now only work with ``async`` functions. Pull request `#16 <https://github.com/rhasspy/rhasspy-hermes-app/pull/16>`_ by `@JonahKr <https://github.com/JonahKr>`_. Existing code should only add the ``async`` keyword before the function definition to keep the code valid. See :doc:`usage` for some examples.\n\n*********************\n`0.2.0`_ - 2020-07-19\n*********************\n\n.. _`0.2.0`: https://github.com/rhasspy/rhasspy-hermes-app/releases/tag/v0.2.0\n\nAdded\n=====\n\n- Method :meth:`rhasspyhermes_app.HermesApp.notify` to send a dialogue notification. See `#10 <https://github.com/rhasspy/rhasspy-hermes-app/issues/10>`_.\n- Decorator :meth:`rhasspyhermes_app.HermesApp.on_dialogue_intent_not_recognized` to act when the dialogue manager failed to recognize an intent. See `#9 <https://github.com/rhasspy/rhasspy-hermes-app/issues/9>`_.\n\n*********************\n`0.1.0`_ - 2020-06-14\n*********************\n\n.. _`0.1.0`: https://github.com/rhasspy/rhasspy-hermes-app/releases/tag/v0.1.0\n\nAdded\n=====\n\n- This is the first released version with decorators :meth:`rhasspyhermes_app.HermesApp.on_hotword`,\n :meth:`rhasspyhermes_app.HermesApp.on_intent`, :meth:`rhasspyhermes_app.HermesApp.on_intent_not_recognized`\n and :meth:`rhasspyhermes_app.HermesApp.on_topic`.\n" }, { "alpha_fraction": 0.6175675392150879, "alphanum_fraction": 0.6189188957214355, "avg_line_length": 19, "blob_id": "79438f4a4aad1d6f23b0a456b485e6d26684d1d2", "content_id": "e66e6d0f0a6f1cbdf225777f313c124d185c5fc6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 740, "license_type": "permissive", "max_line_length": 133, "num_lines": 37, "path": "/docs/index.rst", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": ".. include:: ../README.rst\n :end-before: end-of-inclusion-in-index-rst\n\n**************\nGitHub project\n**************\n\nDevelopment of Rhasspy Hermes App is done in the GitHub project `rhasspy-hermes-app`_. You can find the latest code there.\n\n.. _`rhasspy-hermes-app`: https://github.com/rhasspy/rhasspy-hermes-app\n\n*******\nLicense\n*******\n\nThis project is provided by `Koen Vervloesem`_ as open source software with the MIT license. See the :doc:`license` file for more information.\n\n.. _`Koen Vervloesem`: mailto:[email protected]\n\n.. toctree::\n :maxdepth: 2\n :caption: Contents:\n\n rationale\n usage\n api\n changelog\n development\n license\n\n******************\nIndices and tables\n******************\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n" }, { "alpha_fraction": 0.7198989391326904, "alphanum_fraction": 0.7257928848266602, "avg_line_length": 38.588890075683594, "blob_id": "8ba1ae0335c845a83b3944af027a6287e6631c32", "content_id": "09f9570943c6e3dc7252c7ff952c85ad62a91158", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3565, "license_type": "permissive", "max_line_length": 227, "num_lines": 90, "path": "/docs/usage.rst", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "#####\nUsage\n#####\n\nThe design philosophy of Rhasspy Hermes App is:\n\n- It should be easy to create a Rhasspy app with minimal boilerplate code.\n- All Rhasspy Hermes App code should behave by default in a sensible way.\n\n*********************\nReacting to an intent\n*********************\n\nThis example app reacts to the default \"GetTime\" intent that comes with Rhasspy's installation by telling you the current time:\n\n.. literalinclude:: ../examples/time_app.py\n\nIgnoring the import lines and the logger, what this code does is:\n\n* creating a :class:`rhasspyhermes_app.HermesApp` object;\n* defining an async function ``get_time`` that ends a session by telling the time;\n* running the app.\n\nBy applying the app's :meth:`rhasspyhermes_app.HermesApp.on_intent` decorator to the function, this function will be called whenever the app receives an intent with the name \"GetTime\".\n\nTry the example app `time_app.py`_ with the ``--help`` flag to see what settings you can use to start the app (mostly connection settings for the MQTT broker):\n\n.. command-output:: PYTHONPATH=. python3 examples/time_app.py --help\n :shell:\n :cwd: ..\n\n.. _`time_app.py`: https://github.com/rhasspy/rhasspy-hermes-app/blob/master/examples/time_app.py\n\nYou can pass all the settings as keyword arguments inside the constructor as well:\n``rhasspyhermes_app.HermesApp(\"ExampleApp\", host=\"192.168.178.123\", port=12183)``. Note that arguments passed on the\ncommand line have precedence over arguments passed to the constructor.\n\n*******\nAsyncio\n*******\n\nEvery function that you decorate with Rhasspy Hermes App should be defined with the ``async`` keyword. However, you don't have to use the async functionality.\n\nFor apps which are time intensive by e.g. using database queries or API calls, we recommend the use of asynchronous functions.\nThese allow your code to handle multiple requests at the same time and therefore cutting down on precious runtime.\n\nTry the example app `async_advice_app.py`_.\n\n.. _`async_advice_app.py`: https://github.com/rhasspy/rhasspy-hermes-app/blob/master/examples/async_advice_app.py\n\n\n******************\nOther example apps\n******************\n\nThe GitHub repository has a couple of other example apps showing the library's functionality:\n\n- `raw_topic_app.py`_\n- `raw_topic_list_app.py`_\n\n.. _`raw_topic_app.py`: https://github.com/rhasspy/rhasspy-hermes-app/blob/master/examples/raw_topic_app.py\n.. _`raw_topic_list_app.py`: https://github.com/rhasspy/rhasspy-hermes-app/blob/master/examples/raw_topic_list_app.py\n\n*******************************\nBuilding an app on this library\n*******************************\n\nIf the API of this library changes, your app possibly stops working when it updates to the newest release of Rhasspy Hermes App. Therefore, it’s best to define a specific version in your ``requirements.txt`` file, for instance:\n\n.. code-block::\n\n rhasspy-hermes-app==1.0.0\n\nThis way your app keeps working when the Rhasspy Hermes App adds incompatible changes in a new version.\n\nThe project adheres to the `Semantic Versioning`_ specification with major, minor and patch version.\n\nGiven a version number major.minor.patch, this project increments the:\n\n- major version when incompatible API changes are made;\n- minor version when functionality is added in a backwards-compatible manner;\n- patch version when backwards-compatible bug fixes are made.\n\n.. _`Semantic Versioning`: https://semver.org\n\n****************\nMore information\n****************\n\nMore information about the usage of the Rhasspy Hermes App library can be found in the :doc:`api`.\n" }, { "alpha_fraction": 0.5499782562255859, "alphanum_fraction": 0.5505720376968384, "avg_line_length": 39.03327941894531, "blob_id": "0a3730297c75d5876fef8e565120069430ae93a1", "content_id": "1f3cb0acc17eb646a994ba1f7bacf7c792703c46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25261, "license_type": "permissive", "max_line_length": 119, "num_lines": 631, "path": "/rhasspyhermes_app/__init__.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Helper library to create voice apps for Rhasspy using the Hermes protocol.\"\"\"\nimport argparse\nimport asyncio\nimport logging\nimport re\nfrom copy import deepcopy\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Dict, List, Optional, Union\n\nimport paho.mqtt.client as mqtt\nimport rhasspyhermes.cli as hermes_cli\nfrom rhasspyhermes.client import HermesClient\nfrom rhasspyhermes.dialogue import (\n DialogueContinueSession,\n DialogueEndSession,\n DialogueIntentNotRecognized,\n DialogueNotification,\n DialogueStartSession,\n)\nfrom rhasspyhermes.nlu import NluIntent, NluIntentNotRecognized\nfrom rhasspyhermes.wake import HotwordDetected\n\n_LOGGER = logging.getLogger(\"HermesApp\")\n\n\n@dataclass\nclass ContinueSession:\n \"\"\"Helper class to continue the current session.\n\n Attributes:\n text: The text the TTS should say to start this additional request of the session.\n intent_filter: A list of intents names to restrict the NLU resolution on the\n answer of this query.\n custom_data: An update to the session's custom data. If not provided, the custom data\n will stay the same.\n send_intent_not_recognized: Indicates whether the dialogue manager should handle non recognized\n intents by itself or send them for the client to handle.\n \"\"\"\n\n custom_data: Optional[str] = None\n text: Optional[str] = None\n intent_filter: Optional[List[str]] = None\n send_intent_not_recognized: bool = False\n\n\n@dataclass\nclass EndSession:\n \"\"\"Helper class to end the current session.\n\n Attributes:\n text: The text the TTS should say to end the session.\n custom_data: An update to the session's custom data. If not provided, the custom data\n will stay the same.\n \"\"\"\n\n text: Optional[str] = None\n custom_data: Optional[str] = None\n\n\n@dataclass\nclass TopicData:\n \"\"\"Helper class for topic subscription.\n\n Attributes:\n topic: The MQTT topic.\n data: A dictionary holding extracted data for the given placeholder.\n \"\"\"\n\n topic: str\n data: Dict[str, str]\n\n\nclass HermesApp(HermesClient):\n \"\"\"A Rhasspy app using the Hermes protocol.\n\n Attributes:\n args: Command-line arguments for the Hermes app.\n\n Example:\n\n .. literalinclude:: ../examples/time_app.py\n \"\"\"\n\n def __init__(\n self,\n name: str,\n parser: Optional[argparse.ArgumentParser] = None,\n mqtt_client: Optional[mqtt.Client] = None,\n **kwargs\n ):\n \"\"\"Initialize the Rhasspy Hermes app.\n\n Arguments:\n name: The name of this object.\n\n parser: An argument parser.\n If the argument is not specified, the object creates an\n argument parser itself.\n\n mqtt_client: An MQTT client. If the argument\n is not specified, the object creates an MQTT client itself.\n\n **kwargs: Other arguments. This supports the same arguments as the command-line\n arguments, such has ``host`` and ``port``. Arguments specified by the user\n on the command line have precedence over arguments passed as ``**kwargs``.\n \"\"\"\n if parser is None:\n parser = argparse.ArgumentParser(prog=name)\n # Add default arguments\n hermes_cli.add_hermes_args(parser)\n\n # overwrite argument defaults inside parser with argparse.SUPPRESS\n # so arguments that are not provided get ignored\n suppress_parser = deepcopy(parser)\n for action in suppress_parser._actions:\n action.default = argparse.SUPPRESS\n\n supplied_args = vars(suppress_parser.parse_args())\n default_args = vars(parser.parse_args([]))\n\n # Command-line arguments take precedence over the arguments of the HermesApp.__init__\n args = {**default_args, **kwargs, **supplied_args}\n self.args = argparse.Namespace(**args)\n\n # Set up logging\n hermes_cli.setup_logging(self.args)\n _LOGGER.debug(self.args)\n\n # Create MQTT client\n if mqtt_client is None:\n mqtt_client = mqtt.Client()\n\n # Initialize HermesClient\n # pylint: disable=no-member\n super().__init__(name, mqtt_client, site_ids=self.args.site_id)\n\n self._callbacks_hotword: List[Callable[[HotwordDetected], Awaitable[None]]] = []\n\n self._callbacks_intent: Dict[\n str,\n List[Callable[[NluIntent], Awaitable[None]]],\n ] = {}\n\n self._callbacks_intent_not_recognized: List[\n Callable[[NluIntentNotRecognized], Awaitable[None]]\n ] = []\n\n self._callbacks_dialogue_intent_not_recognized: List[\n Callable[[DialogueIntentNotRecognized], Awaitable[None]]\n ] = []\n\n self._callbacks_topic: Dict[\n str, List[Callable[[TopicData, bytes], Awaitable[None]]]\n ] = {}\n\n self._callbacks_topic_regex: List[\n Callable[[TopicData, bytes], Awaitable[None]]\n ] = []\n\n self._additional_topic: List[str] = []\n\n def _subscribe_callbacks(self) -> None:\n # Remove duplicate intent names\n intent_names: List[str] = list(set(self._callbacks_intent.keys()))\n topics: List[str] = [\n NluIntent.topic(intent_name=intent_name) for intent_name in intent_names\n ]\n\n if self._callbacks_hotword:\n topics.append(HotwordDetected.topic())\n\n if self._callbacks_intent_not_recognized:\n topics.append(NluIntentNotRecognized.topic())\n\n if self._callbacks_dialogue_intent_not_recognized:\n topics.append(DialogueIntentNotRecognized.topic())\n\n topic_names: List[str] = list(set(self._callbacks_topic.keys()))\n topics.extend(topic_names)\n topics.extend(self._additional_topic)\n\n self.subscribe_topics(*topics)\n\n async def on_raw_message(self, topic: str, payload: bytes):\n \"\"\"This method handles messages from the MQTT broker.\n\n Arguments:\n topic: The topic of the received MQTT message.\n\n payload: The payload of the received MQTT message.\n\n .. warning:: Don't override this method in your app. This is where all the magic happens in Rhasspy Hermes App.\n \"\"\"\n try:\n if HotwordDetected.is_topic(topic):\n # hermes/hotword/<wakeword_id>/detected\n try:\n hotword_detected = HotwordDetected.from_json(payload)\n for function_h in self._callbacks_hotword:\n await function_h(hotword_detected)\n except KeyError as key:\n _LOGGER.error(\n \"Missing key %s in JSON payload for %s: %s\", key, topic, payload\n )\n elif NluIntent.is_topic(topic):\n # hermes/intent/<intent_name>\n try:\n nlu_intent = NluIntent.from_json(payload)\n intent_name = nlu_intent.intent.intent_name\n if intent_name in self._callbacks_intent:\n for function_i in self._callbacks_intent[intent_name]:\n await function_i(nlu_intent)\n except KeyError as key:\n _LOGGER.error(\n \"Missing key %s in JSON payload for %s: %s\", key, topic, payload\n )\n elif NluIntentNotRecognized.is_topic(topic):\n # hermes/nlu/intentNotRecognized\n try:\n nlu_intent_not_recognized = NluIntentNotRecognized.from_json(\n payload\n )\n for function_inr in self._callbacks_intent_not_recognized:\n await function_inr(nlu_intent_not_recognized)\n except KeyError as key:\n _LOGGER.error(\n \"Missing key %s in JSON payload for %s: %s\", key, topic, payload\n )\n elif DialogueIntentNotRecognized.is_topic(topic):\n # hermes/dialogueManager/intentNotRecognized\n try:\n dialogue_intent_not_recognized = (\n DialogueIntentNotRecognized.from_json(payload)\n )\n for function_dinr in self._callbacks_dialogue_intent_not_recognized:\n await function_dinr(dialogue_intent_not_recognized)\n except KeyError as key:\n _LOGGER.error(\n \"Missing key %s in JSON payload for %s: %s\", key, topic, payload\n )\n else:\n unexpected_topic = True\n if topic in self._callbacks_topic:\n for function_1 in self._callbacks_topic[topic]:\n await function_1(TopicData(topic, {}), payload)\n unexpected_topic = False\n else:\n for function_2 in self._callbacks_topic_regex:\n if hasattr(function_2, \"topic_extras\"):\n topic_extras = getattr(function_2, \"topic_extras\")\n for pattern, named_positions in topic_extras:\n if re.match(pattern, topic) is not None:\n data = TopicData(topic, {})\n parts = topic.split(sep=\"/\")\n if named_positions is not None:\n for name, position in named_positions.items():\n data.data[name] = parts[position]\n\n await function_2(data, payload)\n unexpected_topic = False\n\n if unexpected_topic:\n _LOGGER.warning(\"Unexpected topic: %s\", topic)\n\n except Exception:\n _LOGGER.exception(\"on_raw_message\")\n\n def on_hotword(\n self, function: Callable[[HotwordDetected], Awaitable[None]]\n ) -> Callable[[HotwordDetected], Awaitable[None]]:\n \"\"\"Apply this decorator to a function that you want to act on a detected hotword.\n\n The decorated function has a :class:`rhasspyhermes.wake.HotwordDetected` object as an argument\n and doesn't have a return value.\n\n Example:\n\n .. code-block:: python\n\n @app.on_hotword\n async def wake(hotword: HotwordDetected):\n print(f\"Hotword {hotword.model_id} detected on site {hotword.site_id}\")\n\n If a hotword has been detected, the ``wake`` function is called with the ``hotword`` argument.\n This object holds information about the detected hotword.\n \"\"\"\n\n self._callbacks_hotword.append(function)\n\n return function\n\n def on_intent(\n self, *intent_names: str\n ) -> Callable[\n [\n Callable[\n [NluIntent], Union[Awaitable[ContinueSession], Awaitable[EndSession]]\n ]\n ],\n Callable[[NluIntent], Awaitable[None]],\n ]:\n \"\"\"Apply this decorator to a function that you want to act on a received intent.\n\n Arguments:\n intent_names: Names of the intents you want the function to act on.\n\n The decorated function has a :class:`rhasspyhermes.nlu.NluIntent` object as an argument\n and needs to return a :class:`ContinueSession` or :class:`EndSession` object.\n\n If the function returns a :class:`ContinueSession` object, the intent's session is continued after\n saying the supplied text. If the function returns a a :class:`EndSession` object, the intent's session\n is ended after saying the supplied text, or immediately when no text is supplied.\n\n Example:\n\n .. code-block:: python\n\n @app.on_intent(\"GetTime\")\n async def get_time(intent: NluIntent):\n return EndSession(\"It's too late.\")\n\n If the intent with name GetTime has been detected, the ``get_time`` function is called\n with the ``intent`` argument. This object holds information about the detected intent.\n \"\"\"\n\n def wrapper(\n function: Callable[\n [NluIntent], Union[Awaitable[ContinueSession], Awaitable[EndSession]]\n ]\n ) -> Callable[[NluIntent], Awaitable[None]]:\n async def wrapped(intent: NluIntent) -> None:\n message = await function(intent)\n if isinstance(message, EndSession):\n if intent.session_id is not None:\n self.publish(\n DialogueEndSession(\n session_id=intent.session_id,\n text=message.text,\n custom_data=message.custom_data,\n )\n )\n else:\n _LOGGER.error(\n \"Cannot end session of intent without session ID.\"\n )\n elif isinstance(message, ContinueSession):\n if intent.session_id is not None:\n self.publish(\n DialogueContinueSession(\n session_id=intent.session_id,\n text=message.text,\n intent_filter=message.intent_filter,\n custom_data=message.custom_data,\n send_intent_not_recognized=message.send_intent_not_recognized,\n )\n )\n else:\n _LOGGER.error(\n \"Cannot continue session of intent without session ID.\"\n )\n\n for intent_name in intent_names:\n try:\n self._callbacks_intent[intent_name].append(wrapped)\n except KeyError:\n self._callbacks_intent[intent_name] = [wrapped]\n\n return wrapped\n\n return wrapper\n\n def on_intent_not_recognized(\n self,\n function: Callable[\n [NluIntentNotRecognized],\n Union[Awaitable[ContinueSession], Awaitable[EndSession], Awaitable[None]],\n ],\n ) -> Callable[[NluIntentNotRecognized], Awaitable[None]]:\n \"\"\"Apply this decorator to a function that you want to act when the NLU system\n hasn't recognized an intent.\n\n The decorated function has a :class:`rhasspyhermes.nlu.NluIntentNotRecognized` object as an argument\n and can return a :class:`ContinueSession` or :class:`EndSession` object or have no return value.\n\n If the function returns a :class:`ContinueSession` object, the current session is continued after\n saying the supplied text. If the function returns a a :class:`EndSession` object, the current session\n is ended after saying the supplied text, or immediately when no text is supplied. If the function doesn't\n have a return value, nothing is changed to the session.\n\n Example:\n\n .. code-block:: python\n\n @app.on_intent_not_recognized\n async def not_understood(intent_not_recognized: NluIntentNotRecognized):\n print(f\"Didn't understand \\\"{intent_not_recognized.input}\\\" on site {intent_not_recognized.site_id}\")\n\n If an intent hasn't been recognized, the ``not_understood`` function is called\n with the ``intent_not_recognized`` argument. This object holds information about the not recognized intent.\n \"\"\"\n\n async def wrapped(inr: NluIntentNotRecognized) -> None:\n message = await function(inr)\n if isinstance(message, EndSession):\n if inr.session_id is not None:\n self.publish(\n DialogueEndSession(\n session_id=inr.session_id,\n text=message.text,\n custom_data=message.custom_data,\n )\n )\n else:\n _LOGGER.error(\n \"Cannot end session of NLU intent not recognized message without session ID.\"\n )\n elif isinstance(message, ContinueSession):\n if inr.session_id is not None:\n self.publish(\n DialogueContinueSession(\n session_id=inr.session_id,\n text=message.text,\n intent_filter=message.intent_filter,\n custom_data=message.custom_data,\n send_intent_not_recognized=message.send_intent_not_recognized,\n )\n )\n else:\n _LOGGER.error(\n \"Cannot continue session of NLU intent not recognized message without session ID.\"\n )\n\n self._callbacks_intent_not_recognized.append(wrapped)\n\n return wrapped\n\n def on_dialogue_intent_not_recognized(\n self,\n function: Callable[\n [DialogueIntentNotRecognized],\n Union[Awaitable[ContinueSession], Awaitable[EndSession], Awaitable[None]],\n ],\n ) -> Callable[[DialogueIntentNotRecognized], Awaitable[None]]:\n \"\"\"Apply this decorator to a function that you want to act when the dialogue manager\n failed to recognize an intent and you requested to notify you of this event with the\n `sendIntentNotRecognized` flag.\n\n The decorated function has a :class:`rhasspyhermes.dialogue.DialogueIntentNotRecognized` object as an argument\n and can return a :class:`ContinueSession` or :class:`EndSession` object or have no return value.\n\n If the function returns a :class:`ContinueSession` object, the current session is continued after\n saying the supplied text. If the function returns a a :class:`EndSession` object, the current session\n is ended after saying the supplied text, or immediately when no text is supplied. If the function doesn't\n have a return value, nothing is changed to the session.\n\n Example:\n\n .. code-block:: python\n\n @app.on_dialogue_intent_not_recognized\n async def not_understood(intent_not_recognized: DialogueIntentNotRecognized):\n print(f\"Didn't understand \\\"{intent_not_recognized.input}\\\" on site {intent_not_recognized.site_id}\")\n\n If an intent hasn't been recognized, the ``not_understood`` function is called\n with the ``intent_not_recognized`` argument. This object holds information about the not recognized intent.\n \"\"\"\n\n async def wrapped(inr: DialogueIntentNotRecognized) -> None:\n message = await function(inr)\n if isinstance(message, EndSession):\n if inr.session_id is not None:\n self.publish(\n DialogueEndSession(\n session_id=inr.session_id,\n text=message.text,\n custom_data=message.custom_data,\n )\n )\n else:\n _LOGGER.error(\n \"Cannot end session of dialogue intent not recognized message without session ID.\"\n )\n elif isinstance(message, ContinueSession):\n if inr.session_id is not None:\n self.publish(\n DialogueContinueSession(\n session_id=inr.session_id,\n text=message.text,\n intent_filter=message.intent_filter,\n custom_data=message.custom_data,\n send_intent_not_recognized=message.send_intent_not_recognized,\n )\n )\n else:\n _LOGGER.error(\n \"Cannot continue session of dialogue intent not recognized message without session ID.\"\n )\n\n self._callbacks_dialogue_intent_not_recognized.append(wrapped)\n\n return wrapped\n\n def on_topic(self, *topic_names: str):\n \"\"\"Apply this decorator to a function that you want to act on a received raw MQTT message.\n\n Arguments:\n topic_names: The MQTT topics you want the function to act on.\n\n The decorated function has a :class:`TopicData` and a :class:`bytes` object as its arguments.\n The former holds data about the topic and the latter about the payload of the MQTT message.\n\n Example:\n\n .. code-block:: python\n\n @app.on_topic(\"hermes/+/{site_id}/playBytes/#\")\n async def test_topic1(data: TopicData, payload: bytes):\n _LOGGER.debug(\"topic: %s, site_id: %s\", data.topic, data.data.get(\"site_id\"))\n\n .. note:: The topic names can contain MQTT wildcards (`+` and `#`) or templates (`{foobar}`).\n In the latter case, the value of the named template is available in the decorated function\n as part of the :class:`TopicData` argument.\n \"\"\"\n\n def wrapper(function):\n async def wrapped(data: TopicData, payload: bytes):\n await function(data, payload)\n\n replaced_topic_names = []\n\n for topic_name in topic_names:\n named_positions = {}\n parts = topic_name.split(sep=\"/\")\n length = len(parts) - 1\n\n def placeholder_mapper(part):\n i, token = tuple(part)\n if token.startswith(\"{\") and token.endswith(\"}\"):\n named_positions[token[1:-1]] = i\n return \"+\"\n\n return token\n\n parts = list(map(placeholder_mapper, enumerate(parts)))\n replaced_topic_name = \"/\".join(parts)\n\n def regex_mapper(part):\n i, token = tuple(part)\n value = token\n if i == 0:\n value = (\n \"^[^+#/]\"\n if token == \"+\"\n else \"[^/]+\"\n if length == 0 and token == \"#\"\n else \"^\" + token\n )\n elif i < length:\n value = \"[^/]+\" if token == \"+\" else token\n elif i == length:\n value = (\n \"[^/]+\"\n if token == \"#\"\n else \"[^/]+$\"\n if token == \"+\"\n else token + \"$\"\n )\n\n return value\n\n pattern = \"/\".join(map(regex_mapper, enumerate(parts)))\n\n if topic_name == pattern[1:-1]:\n try:\n self._callbacks_topic[topic_name].append(wrapped)\n except KeyError:\n self._callbacks_topic[topic_name] = [wrapped]\n else:\n replaced_topic_names.append(replaced_topic_name)\n if not hasattr(wrapped, \"topic_extras\"):\n wrapped.topic_extras = []\n wrapped.topic_extras.append(\n (\n re.compile(pattern),\n named_positions if len(named_positions) > 0 else None,\n )\n )\n\n if hasattr(wrapped, \"topic_extras\"):\n self._callbacks_topic_regex.append(wrapped)\n self._additional_topic.extend(replaced_topic_names)\n\n return wrapped\n\n return wrapper\n\n def run(self):\n \"\"\"Run the app. This method:\n\n - subscribes to all MQTT topics for the functions you decorated;\n - connects to the MQTT broker;\n - starts the MQTT event loop and reacts to received MQTT messages.\n \"\"\"\n # Subscribe to callbacks\n self._subscribe_callbacks()\n\n # Try to connect\n # pylint: disable=no-member\n _LOGGER.debug(\"Connecting to %s:%s\", self.args.host, self.args.port)\n hermes_cli.connect(self.mqtt_client, self.args)\n self.mqtt_client.loop_start()\n\n try:\n # Run main loop\n asyncio.run(self.handle_messages_async())\n except KeyboardInterrupt:\n pass\n finally:\n self.mqtt_client.loop_stop()\n\n def notify(self, text: str, site_id: str = \"default\"):\n \"\"\"Send a dialogue notification.\n\n Use this to inform the user of something without expecting a response.\n\n Arguments:\n text: The text to say.\n site_id: The ID of the site where the text should be said.\n \"\"\"\n notification = DialogueNotification(text)\n self.publish(DialogueStartSession(init=notification, site_id=site_id))\n" }, { "alpha_fraction": 0.7108168005943298, "alphanum_fraction": 0.7108168005943298, "avg_line_length": 20.571428298950195, "blob_id": "8ed3117ef060847f4c939be9c004a7b065090c6f", "content_id": "6cf8fa87b0c4febd1a1fe0055aa15e9a62239682", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "permissive", "max_line_length": 61, "num_lines": 21, "path": "/examples/time_app.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Example app to react to an intent to tell you the time.\"\"\"\nimport logging\nfrom datetime import datetime\n\nfrom rhasspyhermes.nlu import NluIntent\n\nfrom rhasspyhermes_app import EndSession, HermesApp\n\n_LOGGER = logging.getLogger(\"TimeApp\")\n\napp = HermesApp(\"TimeApp\")\n\n\[email protected]_intent(\"GetTime\")\nasync def get_time(intent: NluIntent):\n \"\"\"Tell the time.\"\"\"\n now = datetime.now().strftime(\"%H %M\")\n return EndSession(f\"It's {now}\")\n\n\napp.run()\n" }, { "alpha_fraction": 0.5796812772750854, "alphanum_fraction": 0.5796812772750854, "avg_line_length": 29.240962982177734, "blob_id": "e0a50bea3e3ae5dc8b5f47d55b43ad0de629712d", "content_id": "6c744c1e480dcc7ad409484253ce6d973782da4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2510, "license_type": "permissive", "max_line_length": 88, "num_lines": 83, "path": "/examples/time_app_direct.py", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "\"\"\"Example app using Rhasspy Hermes directly.\"\"\"\nimport argparse\nimport asyncio\nimport logging\nimport typing\nfrom datetime import datetime\n\nimport paho.mqtt.client as mqtt\nimport rhasspyhermes.cli as hermes_cli\nfrom rhasspyhermes.client import HermesClient\nfrom rhasspyhermes.dialogue import DialogueEndSession\nfrom rhasspyhermes.nlu import NluIntent\n\n_LOGGER = logging.getLogger(\"TimeApp\")\n\n\nclass TimeApp(HermesClient):\n \"\"\"Tells the time.\"\"\"\n\n def __init__(self, mqtt_client, site_ids: typing.Optional[typing.List[str]] = None):\n super().__init__(\"TimeApp\", mqtt_client, site_ids=site_ids)\n\n self.subscribe_topics(NluIntent.topic(intent_name=\"GetTime\"))\n\n async def on_raw_message(self, topic: str, payload: bytes):\n \"\"\"Received message from MQTT broker.\"\"\"\n\n try:\n if NluIntent.is_topic(topic):\n # hermes/intent/<intent_name>\n nlu_intent = NluIntent.from_json(payload)\n if nlu_intent.intent.intent_name == \"GetTime\":\n now = datetime.now().strftime(\"%H %M\")\n if nlu_intent.session_id is not None:\n self.publish(\n DialogueEndSession(\n session_id=nlu_intent.session_id,\n text=f\"It's {now}\",\n )\n )\n else:\n _LOGGER.error(\n \"Cannot end session of intent without session ID.\"\n )\n else:\n _LOGGER.warning(\"Unexpected topic: %s\", topic)\n\n except Exception:\n _LOGGER.exception(\"on_raw_message\")\n\n\ndef main():\n \"\"\"Main entry point.\"\"\"\n # Parse command-line arguments\n parser = argparse.ArgumentParser(prog=\"TimeApp\")\n hermes_cli.add_hermes_args(parser)\n\n args = parser.parse_args()\n\n # Add default MQTT arguments\n hermes_cli.setup_logging(args)\n _LOGGER.debug(args)\n\n # Create MQTT client\n mqtt_client = mqtt.Client()\n hermes_client = TimeApp(mqtt_client, site_ids=args.site_id)\n\n # Try to connect\n _LOGGER.debug(\"Connecting to %s:%s\", args.host, args.port)\n hermes_cli.connect(mqtt_client, args)\n mqtt_client.loop_start()\n\n try:\n # Run main loop\n asyncio.run(hermes_client.handle_messages_async())\n except KeyboardInterrupt:\n pass\n finally:\n mqtt_client.loop_stop()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6951537132263184, "alphanum_fraction": 0.6977592706680298, "avg_line_length": 27.22058868408203, "blob_id": "fbd13bb3f9ee46f7eafcdc1a6b8e789aec7b1d16", "content_id": "73c3738f2d640bda4bf3d032c2c833ce12a77c49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1919, "license_type": "permissive", "max_line_length": 132, "num_lines": 68, "path": "/README.rst", "repo_name": "H3adcra5h/rhasspy-hermes-app", "src_encoding": "UTF-8", "text": "##################\nRhasspy Hermes App\n##################\n\n.. image:: https://github.com/rhasspy/rhasspy-hermes-app/workflows/Tests/badge.svg\n :target: https://github.com/rhasspy/rhasspy-hermes-app/actions\n :alt: Continuous integration\n\n.. image:: https://readthedocs.org/projects/rhasspy-hermes-app/badge/?version=latest\n :target: https://rhasspy-hermes-app.readthedocs.io/en/latest/?badge=latest\n :alt: Documentation status\n\n.. image:: https://img.shields.io/pypi/v/rhasspy-hermes-app.svg\n :target: https://pypi.org/project/rhasspy-hermes-app\n :alt: PyPI package version\n\n.. image:: https://img.shields.io/pypi/pyversions/rhasspy-hermes-app.svg\n :target: https://www.python.org\n :alt: Supported Python versions\n\n.. image:: https://img.shields.io/github/license/rhasspy/rhasspy-hermes-app.svg\n :target: https://github.com/rhasspy/rhasspy-hermes-app/blob/master/LICENSE\n :alt: License\n\nRhasspy Hermes App is a helper library to create voice apps for Rhasspy_ in Python using the `Hermes protocol`_\n\n.. _Rhasspy: https://rhasspy.readthedocs.io/en/latest/\n\n.. _`Hermes protocol`: https://docs.snips.ai/reference/hermes\n\n************\nRequirements\n************\n\nRhasspy Hermes App requires:\n\n* Python 3.7\n* Rhasspy 2.5\n\n************\nInstallation\n************\n\nA package can be installed from PyPI:\n\n.. code-block:: shell\n\n pip3 install rhasspy-hermes-app\n\n.. end-of-inclusion-in-index-rst\n\n*************\nDocumentation\n*************\n\nRead the online documentation_ for more information about using the library, including the full API documentation with example code.\n\n.. _documentation: https://rhasspy-hermes-app.readthedocs.io/en/latest/\n\n*******\nLicense\n*******\n\nThis project is provided by `Koen Vervloesem`_ as open source software with the MIT license. See the LICENSE_ file for more information.\n\n.. _`Koen Vervloesem`: mailto:[email protected]\n\n.. _LICENSE: https://github.com/rhasspy/rhasspy-hermes-app/blob/master/LICENSE\n" } ]
21
nsmith-/DiBosonTP
https://github.com/nsmith-/DiBosonTP
fbf3506f4923d2f02f06a3dd223336b94700662a
1b86fc1d37f4466b4946b37cce2a345732218d46
8a46c4f4046dfc9c133553f60209429f0462e6f0
refs/heads/master
2021-01-10T05:44:43.183386
2016-09-13T12:08:58
2016-09-13T12:08:58
44,267,654
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.5936599373817444, "alphanum_fraction": 0.6171950101852417, "avg_line_length": 32.57258224487305, "blob_id": "feb66c922e43089878313b6da602e617de951393", "content_id": "6726b6fb061ecdfccd09fa2a19d69bb634811042", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4164, "license_type": "no_license", "max_line_length": 105, "num_lines": 124, "path": "/muons/plot.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nROOT.gROOT.SetBatch(True)\nROOT.PyConfig.IgnoreCommandLineOptions = True\nimport array\nimport sys\nimport subprocess\n__gitversion__ = subprocess.check_output([\"git\", \"describe\", \"--always\"]).strip()\n\n#idName = 'ZZLoose'\n#idNameNice = 'ZZ Loose ID'\nidName = sys.argv[1]\nidNameNice = sys.argv[2]\n\nptbins = [5.,10.,20.,30.,40.,50.,80.]\netabins = [0.,0.9,1.2,2.1,2.4]\ncolors = [ROOT.kRed, ROOT.kGreen, ROOT.kBlue, ROOT.kBlack]\n\nROOT.gROOT.ProcessLine('.L plots/{id}/{id}.C+'.format(id=idName))\n\nvariations = [\n ROOT.STAT_UP,\n ROOT.STAT_DOWN,\n ROOT.SYST_ALT_TEMPL,\n ROOT.SYST_TAG_PT30,\n ROOT.SYST_CMSSHAPE\n ]\n\nif 'wrt' in idName :\n eff = lambda pt, eta, var : getattr(ROOT, idName)(pt, eta, True, True, var)\nelse :\n eff = lambda pt, eta, var : getattr(ROOT, idName)(pt, eta, True, var)\n\neffCentral = lambda pt, eta : eff(pt, eta, ROOT.CENTRAL)\neffMax = lambda pt, eta : max(map(lambda v : eff(pt,eta,v), variations))-effCentral(pt,eta)\neffMin = lambda pt, eta : effCentral(pt,eta)-min(map(lambda v : eff(pt,eta,v), variations))\n\n\nxbins = array.array('d', [0.5*sum(ptbins[i:i+2]) for i in range(len(ptbins)-1)])\nxlo = lambda bins: array.array('d', map(lambda (a,b): a-b, zip(bins, ptbins)))\nxhi = lambda bins: array.array('d', map(lambda (a,b): a-b, zip(ptbins[1:], bins)))\n\ndef y(eta) : return array.array('d', map(lambda pt : effCentral(pt, eta), xbins))\ndef eyl(eta) : return array.array('d', map(lambda pt : effMin(pt, eta), xbins))\ndef eyh(eta) : return array.array('d', map(lambda pt : effMax(pt, eta), xbins))\n\ncanvas = ROOT.TCanvas()\nmg = ROOT.TMultiGraph('alletaBins', ';Probe p_{T};Scale Factor')\n\nfor i in range(len(etabins)-1) :\n eta = .5*sum(etabins[i:i+2])\n bins2 = array.array('d', [b-1.5+i for b in xbins])\n graph = ROOT.TGraphAsymmErrors(len(xbins), bins2, y(eta), xlo(bins2), xhi(bins2), eyl(eta), eyh(eta))\n graph.SetName('eff_etaBin%d'%i)\n graph.SetTitle('%.1f #leq |#eta| #leq %.1f' % tuple(etabins[i:i+2]))\n graph.SetMarkerColor(colors[i])\n graph.SetLineColor(colors[i])\n mg.Add(graph, 'p')\n\nmg.SetMinimum(0.9)\nmg.SetMaximum(1.05)\nmg.Draw('a')\nleg = canvas.BuildLegend(.5,.2,.9,.4)\nfor entry in leg.GetListOfPrimitives() :\n entry.SetOption('lp')\nleg.SetHeader(idNameNice)\n\ncanvas.Print('plots/%s/scaleFactor_vs_pt.png'%idName)\ncanvas.Print('plots/%s/scaleFactor_vs_pt.root'%idName)\n\n# ------- Latex\ndef formatValue(var, varerr, etabin, ptbin) :\n eta = etabins[etabin-1]+.001\n pt = ptbins[ptbin-1]+.001\n value = eff(pt, eta, var)\n if var is ROOT.CENTRAL :\n return '$%1.4f^{+%1.4f}_{-%1.4f}$' % (value, effMax(pt,eta), effMin(pt,eta))\n else :\n err = eff(ptbins[ptbin-1]+.001, etabins[etabin-1]+.001, varerr)\n return '$%1.4f \\\\pm %1.4f$' % (value, err)\n\noutput = ''\n\nneta = len(etabins)-1\noutput += '''\\\\begin{table}[htbp]\n\\\\centering\n\\\\begin{tabular}{%s}\n\\hline\n''' % 'c'.join(['|']*(neta+3))\n\netaLabels = ['$p_T$', '-']\nfor etabin in xrange(1, neta+1) :\n etalo = etabins[etabin-1]\n etahi = etabins[etabin]\n etaLabels.append('$%1.1f < |\\\\eta| < %1.1f$' % (etalo, etahi))\n\noutput += ' ' + ' & '.join(etaLabels) + '\\\\\\\\ \\hline\\n'\n\nnpt = len(ptbins)-1\nfor ptbin in xrange(1, npt+1) :\n ptlo = ptbins[ptbin-1]\n pthi = ptbins[ptbin]\n ptLabel = '$%3.0f - %3.0f$' % (ptlo, pthi)\n\n output += ' \\\\multirow{3}{*}{%s} \\n' % ptLabel\n\n dataLine, mcLine, ratioLine = [['', name] for name in ['Data', 'MC', 'Ratio']]\n for etabin in xrange(1, neta+1) :\n dataLine.append(formatValue(ROOT.EFF_DATA, ROOT.EFF_DATA_ERRSYM, etabin, ptbin))\n mcLine.append(formatValue(ROOT.EFF_MC, ROOT.EFF_MC_ERRSYM, etabin, ptbin))\n ratioLine.append(formatValue(ROOT.CENTRAL, None, etabin, ptbin))\n\n\n output += ' %s \\\\\\\\ \\n' % ' & '.join(dataLine)\n output += ' %s \\\\\\\\ \\n' % ' & '.join(mcLine)\n output += ' %s \\\\\\\\ \\\\hline\\n' % ' & '.join(ratioLine)\n\noutput += ''' \\\\end{tabular}\n\\\\caption{Efficiency table for %s}\n\\\\end{table}\n%% Generated with DiBosonTP version %s\n''' % (idName, __gitversion__)\nwith open('plots/%s/table.tex'%idName, 'w') as fout :\n fout.write(output)\n\n" }, { "alpha_fraction": 0.7414236664772034, "alphanum_fraction": 0.7731561064720154, "avg_line_length": 57.29999923706055, "blob_id": "9fec4b27b5cb1aded55a2d2c018282b1e8833007", "content_id": "595e3a6312e5ce266b367d4d104a322b6b00bc9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4664, "license_type": "no_license", "max_line_length": 209, "num_lines": 80, "path": "/muons/runFits.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\ncmsenv\n\nif [[ $1 == 'doMC' ]]; then\n # MC ID/Iso\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIDZZLoose 2>&1 > /dev/null &\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIDZZTight 2>&1 > /dev/null &\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIsoZZ conditions=passingIDZZLoose outputFileName=passingIDZZLoose 2>&1 > /dev/null &\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIsoZZ conditions=passingIDZZTight outputFileName=passingIDZZTight 2>&1 > /dev/null &\n\n # MC Triggers\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingMu17 2>&1 > /dev/null &\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingMu17L1Match 2>&1 > /dev/null &\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingMu8 2>&1 > /dev/null &\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingTkMu8 2>&1 > /dev/null &\n\n # DZ\n #cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTreeDZ_mc.root idName=passingDZ dirName=globalMuonDZTree outputFileName=globalMuon 2>&1 > /dev/null\n #cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTreeDZ_mc.root idName=passingDZ dirName=trackerMuonDZTree outputFileName=trackerMuon 2>&1 > /dev/null\nfi\n\n# Make MC templates for data fit\ncommonTemplateFlags=\"-d muonEffs --var2Name=probe_pt --var1Name=probe_abseta --var2Bins=5,10,20,30,40,50,100,1000 --var1Bins=0,1.5,2.5 --weightVarName=totWeight\"\ndataFitSeq() {\n idName=$1\n shift\n conditions=$1\n\n if [[ $conditions ]]; then\n condFileSafe=$(echo ${conditions}|tr ',' '_')\n if [[ ! -f mcTemplates-${idName}-${condFileSafe}.root ]]; then\n getTemplatesFromMC.py ${commonTemplateFlags} -i TnPTree_mc.root -o mcTemplates-${idName}-${condFileSafe}.root --idprobe=${idName} --conditions=\"${conditions}\"\n fi\n cmsRun fitter.py isMC=0 inputFileName=TnPTree_data.root idName=${idName} conditions=${conditions} outputFileName=${condFileSafe} mcTemplateFile=mcTemplates-${idName}-${condFileSafe}.root 2>&1 > /dev/null &\n else\n if [[ ! -f mcTemplates-${idName}.root ]]; then\n getTemplatesFromMC.py ${commonTemplateFlags} -i TnPTree_mc.root -o mcTemplates-${idName}.root --idprobe=${idName}\n fi\n cmsRun fitter.py isMC=0 inputFileName=TnPTree_data.root idName=${idName} mcTemplateFile=mcTemplates-${idName}.root 2>&1 > /dev/null &\n fi\n}\n\n# rm -rf mcTemplates-*.root\n\n# Data ID/Iso\ndataFitSeq passingIDZZLoose\ndataFitSeq passingIDZZTight\ndataFitSeq passingIsoZZ passingIDZZLoose\ndataFitSeq passingIsoZZ passingIDZZTight\n\n# Data Triggers\ndataFitSeq passingMu17\ndataFitSeq passingMu17L1Match\ndataFitSeq passingMu8\ndataFitSeq passingTkMu8\n\n# DZ filters\n#getTemplatesFromMC.py -i TnPTreeDZ_mc.root -o mcTemplates-globalMuonPassingDZ.root --idprobe=passingDZ \\\n# -d globalMuonDZTree --var2Name=probe_pt --var1Name=probe_abseta --var2Bins=10,20,30,40,50,100,1000 --var1Bins=0,1.5,2.5 --weightVarName=totWeight\n#cmsRun fitter.py isMC=0 inputFileName=TnPTreeDZ_data.root idName=passingDZ dirName=globalMuonDZTree outputFileName=globalMuon mcTemplateFile=mcTemplates-globalMuonPassingDZ.root 2>&1 > /dev/null &\n#\n#getTemplatesFromMC.py -i TnPTreeDZ_mc.root -o mcTemplates-trackerMuonPassingDZ.root --idprobe=passingDZ \\\n# -d trackerMuonDZTree --var2Name=probe_pt --var1Name=probe_abseta --var2Bins=10,20,30,40,50,100,1000 --var1Bins=0,1.5,2.5 --weightVarName=totWeight\n#cmsRun fitter.py isMC=0 inputFileName=TnPTreeDZ_data.root idName=passingDZ dirName=trackerMuonDZTree outputFileName=trackerMuon mcTemplateFile=mcTemplates-trackerMuonPassingDZ.root 2>&1 > /dev/null &\n\nwait\n\nhadd -f efficiency-mc.root efficiency-mc-*.root\nhadd -f efficiency-data.root efficiency-data-*.root\n\noutDir=~/www/TagProbePlots/$(git describe)\n\ndumpTagProbeTreeHTML.py --mc efficiency-mc.root --data efficiency-data.root -i muonEffs -o ${outDir}/muons\ndumpTagProbeLatex.py --mc efficiency-mc.root --data efficiency-data.root -i muonEffs -o ${outDir}/muons --count\n\n#dumpTagProbeTreeHTML.py --mc efficiency-mc.root --data efficiency-data.root -i globalMuonDZTree -o ${outDir}/globalMuonDZ\n#dumpTagProbeLatex.py --mc efficiency-mc.root --data efficiency-data.root -i globalMuonDZTree -o ${outDir}/globalMuonDZ --count\n\n#dumpTagProbeTreeHTML.py --mc efficiency-mc.root --data efficiency-data.root -i trackerMuonDZTree -o ~/www/TagProbePlots/trackerMuonDZ\n#dumpTagProbeLatex.py --mc efficiency-mc.root --data efficiency-data.root -i trackerMuonDZTree -o ~/www/TagProbePlots/trackerMuonDZ --count\n" }, { "alpha_fraction": 0.596738338470459, "alphanum_fraction": 0.608320951461792, "avg_line_length": 31.90243911743164, "blob_id": "06c8b78b4f285689e86c63ebf5691ad95491a467", "content_id": "6a6ceba1bf1bc2b2ba4f8aeb7e377033fa7b5bab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10792, "license_type": "no_license", "max_line_length": 159, "num_lines": 328, "path": "/scripts/dumpTagProbeTreeHTML.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nROOT.gROOT.SetBatch(True)\nROOT.PyConfig.IgnoreCommandLineOptions = True\nimport argparse, json, pickle, os, re, subprocess\n\n__gitversion__ = subprocess.check_output([\"git\", \"describe\", \"--always\"]).strip()\n\n# mkdir -p \ndef mkdirP(dirname) :\n import errno\n try:\n os.mkdir(dirname)\n except OSError, e:\n if e.errno != errno.EEXIST:\n raise e\n pass\n\ndef rootFileType(string) :\n file = ROOT.TFile.Open(string)\n if not file :\n raise argparse.ArgumentTypeError(string+' could not be opened!')\n return file\n\ndef get2DPlot(effDir) :\n canvas = None\n plotsDir = effDir.Get('fit_eff_plots')\n if not plotsDir :\n return\n for key in plotsDir.GetListOfKeys() :\n if re.match('probe_.*abseta.*_probe_.*_PLOT.*', key.GetName()) :\n canvas = key.ReadObj()\n break\n\n if not canvas :\n raise Exception('No canvas found in %s' % effDir.GetName())\n \n # Stylize?\n canvas.SetLogy(True)\n plot = canvas.GetPrimitive(canvas.GetName())\n\n ROOT.SetOwnership(canvas, False)\n return canvas\n\ndef parseFitTree(baseDirectory, outputDirectory) :\n '''\n Generates HTML files in outputDirectory\n '''\n\n mkdirP(outputDirectory)\n with open(os.path.join(outputDirectory, 'index.html'), 'w') as index :\n index.write(HTML.header.format(\n rootFile=baseDirectory.GetFile().GetName(),\n baseDirectory=baseDirectory.GetName()\n ))\n\n for effDir in subDirs(baseDirectory) :\n effName = effDir.GetName()\n\n effoutDir = os.path.join(outputDirectory, effName)\n mkdirP(effoutDir)\n\n parseEfficiencyDir(effDir, effoutDir, index)\n \n index.write(HTML.footer.format(\n version=__gitversion__\n ))\n\ndef parseEfficiencyDir(effDir, outputDirectory, index) :\n effName = effDir.GetName()\n rows = ''\n codeRows = []\n\n for effBinDir in fitSubDirs(effDir) :\n binName = effBinDir.GetName()\n\n if not effBinDir.Get('fitresults') :\n continue\n\n (row, code) = parseEfficiencyBin(effBinDir, outputDirectory)\n codeRows.append(code)\n rows += row\n\n plot = get2DPlot(effDir)\n plotName = 'efficiency2DPtEta.png'\n if plot :\n plot.Print(os.path.join(outputDirectory, plotName))\n\n macroVariables = effDir.Get('variables').GetTitle()\n with open(os.path.join(outputDirectory, effName+'.C'), 'w') as fout :\n fout.write(\"// Made with love by DiBosonTP version: %s\\n\" % __gitversion__)\n fout.write(\"\"\"\nenum Variation {\n CENTRAL,\n STAT_UP,\n STAT_DOWN,\n SYST_ALT_TEMPL,\n SYST_TAG_PT30,\n SYST_CMSSHAPE,\n EFF_DATA,\n EFF_DATA_ERRSYM,\n EFF_MC,\n EFF_MC_ERRSYM,\n EFF_CUTCOUNT,\n EFF_CUTCOUNT_UP,\n EFF_CUTCOUNT_DOWN,\n EFF_FIT,\n EFF_FIT_UP,\n EFF_FIT_DOWN,\n};\n\"\"\")\n fout.write(\"float %s(%s, Variation variation) {\\n\" % (effName, macroVariables))\n for row in codeRows :\n fout.write(row+\"\\n\")\n fout.write(\" return 1.; // Default\\n\")\n fout.write(\"}\\n\")\n\n index.write(HTML.effDirItem.format(\n effName=effName,\n eff2DPtEtaImage=os.path.join(effName, plotName),\n tableRows=rows\n ))\n\ndef makeChi2(rooPad, nFitParam) :\n # This is so fucking stupid\n data = rooPad.FindObject('h_data_binned')\n model = rooPad.FindObject('pdfPass_Norm[mass]')\n chi2 = 0.\n for i in range(data.GetN()) :\n x = ROOT.Double()\n y = ROOT.Double()\n data.GetPoint(i, x, y)\n yerr = data.GetErrorY(i)\n ypred = model.interpolate(x)\n if y > 0 :\n chi2 += (y-ypred)**2 / yerr**2\n return (chi2, data.GetN()-nFitParam)\n\ndef makeChi2_roofit(rooPad, nFitParam) :\n data = rooPad.FindObject('h_data_binned')\n model = rooPad.FindObject('pdfPass_Norm[mass]')\n Redchi2 = model.chiSquare(data, nFitParam)\n dof = data.GetN() - nFitParam\n return (Redchi2*dof, dof)\n\ndef parseEfficiencyBin(effBinDir, outputDirectory) :\n fitResults = effBinDir.Get('fitresults')\n # https://root.cern.ch/root/html/tutorials/roofit/rf607_fitresult.C.html\n effValue = fitResults.floatParsFinal().find('efficiency')\n dataEff = effValue.getVal()\n dataEffErrHi = effValue.getErrorHi()\n dataEffErrLo = effValue.getErrorLo()\n\n if effValue.getVal()+effValue.getErrorHi() > 1. :\n print \"Found one! :\"\n effValue.Print()\n\n canvas = effBinDir.Get('fit_canvas')\n passing = canvas.FindObject('fit_canvas_1')\n firstPlot = passing.GetListOfPrimitives()[0]\n firstPlot.SetTitle('Passing '+effBinDir.GetName())\n fullPlot = os.path.join(outputDirectory, effBinDir.GetName()+'.png')\n canvas.Print(fullPlot)\n smallPlot = fullPlot.replace('.png','_small.png')\n subprocess.call(['convert', '-gravity', 'north', '-crop', '100%x50%', fullPlot, smallPlot])\n\n cHist = fitResults.correlationHist()\n cHist.SetTitle('')\n cHist.SetContour(256)\n canvasCorr = ROOT.TCanvas('correlation', '', 800,600)\n canvasCorr.SetMargin(.2,.12,.1,.01)\n cHist.Draw('colz')\n canvasCorr.Print(fullPlot.replace('.png','_correlation.png'))\n cHist.SetDirectory(0)\n del cHist\n\n nll = fitResults.minNll()\n\n mcHist = effBinDir.Get('mc_cutCount')\n mcPass = mcHist.GetBinContent(1)\n mcTotal= mcHist.GetBinContent(2)\n mcEff = mcPass/mcTotal\n mcEffLo = ROOT.TEfficiency.ClopperPearson(int(mcTotal), int(mcPass), 0.68, False)\n mcEffHi = ROOT.TEfficiency.ClopperPearson(int(mcTotal), int(mcPass), 0.68, True)\n\n scaleFactor = dataEff / mcEff\n maxSf = (dataEff+dataEffErrHi)/mcEffLo\n scaleFactorErrHi = maxSf-scaleFactor\n minSf = (dataEff+dataEffErrLo)/mcEffHi\n scaleFactorErrLo = minSf-scaleFactor\n\n with open(os.path.join(outputDirectory, effBinDir.GetName()+'.parameters.txt'), 'w') as paramOut :\n #paramOut.write(\"# Fit chi2/dof: %f / %d\\n\" % (chi2, dof))\n params = fitResults.floatParsFinal()\n for p in xrange(params.getSize()):\n myPar = params.at(p)\n paramOut.write(\"%s[%.3f,%.3f,%.3f]\\n\"%(myPar.GetName(), myPar.getVal(), myPar.getMin(), myPar.getMax()))\n\n colors = ['#79ff00', '#ffff00', '#ff7700', '#ff0000']\n thresholds = [1., 5., 10., 100.]\n fitStatusColor = '#00ff00' \n for i in range(4) :\n if nll > thresholds[i] :\n fitStatusColor = colors[i]\n\n binName = effBinDir.GetName()\n\n row = HTML.effTableRow.format(\n fitStatusColor=fitStatusColor,\n efficiencyNice='%.4f +%.4f %.4f' % (dataEff, dataEffErrHi, dataEffErrLo),\n mcEfficiency='%.4f (%d/%d)' % (mcEff, mcPass, mcTotal),\n scaleFactor='%.4f +%.4f %.4f' % (scaleFactor, scaleFactorErrHi, scaleFactorErrLo),\n effName=effBinDir.GetDirectory('..').GetName(),\n binName=binName,\n binNameNice=re.sub('__pdfSignal.*', '', binName),\n numSignalAll=fitResults.floatParsFinal().find('numSignalAll').getVal(),\n nll=nll,\n fitStatus=':'.join(['%d' % fitResults.statusCodeHistory(i) for i in range(fitResults.numStatusHistory())]),\n )\n row += '''<tr><td colspan=\"7\" style=\"text-align: center;\"><img src=\"{effName}/{binName}_small.png\"></td></tr>'''.format(\n effName=effBinDir.GetDirectory('..').GetName(),\n binName=binName,\n )\n\n codeRow = effBinDir.Get('cutString').GetTitle()\n\n return (row, codeRow)\n\ndef subDirs(dir) :\n for key in dir.GetListOfKeys() :\n if key.IsFolder() :\n yield key.ReadObj()\n\ndef fitSubDirs(dir) :\n for key in dir.GetListOfKeys() :\n if key.IsFolder() :\n yield key.ReadObj()\n\n# HTML Templates\nclass HTML :\n header = '''<html>\n<head>\n <title>Efficiency summary for {rootFile}/{baseDirectory}</title>\n <style type=\"text/css\">\n div.effResult {{\n margin: auto;\n width: 80%;\n border: 2px solid #888888;\n }}\n\n table {{\n width: 100%;\n }}\n </style>\n</head>\n<body>\n<h2>Efficiency summary for {rootFile}/{baseDirectory}</h2>\n'''\n\n effDirItem = '''<div class=\"effResult\">\n <h3>Efficiency results for {effName}</h3><br />\n Function: <a href=\"{effName}/{effName}.C\">{effName}.C</a><br />\n Latex: <a href=\"{effName}/table.tex\">table.tex</a><br />\n <div style=\"text-align: center;\"><b>Summary Plot</b><br /><img src=\"{effName}/scaleFactor_vs_pt.png\" /></div>\n <table>\n <tr style=\"background: #cccccc\">\n <td>Bin name</td>\n <td>Data Efficiency</td>\n <td>MC Cut&Count</td>\n <td>Scale Factor</td>\n <td>Fit status <a href=\"https://root.cern.ch/root/htmldoc/ROOT__Minuit2__Minuit2Minimizer.html#ROOT__Minuit2__Minuit2Minimizer:Minimize\">?</a></td>\n <td>Fit signal yield</td>\n <td>Extras</td>\n </tr>\n {tableRows}\n </table>\n</div>'''\n\n effTableRow = '''\n <tr style=\"background: {fitStatusColor}\">\n <td><a href=\"{effName}/{binName}.png\">{binNameNice}</a></td>\n <td>{efficiencyNice}</td>\n <td>{mcEfficiency}</td>\n <td>{scaleFactor}</td>\n <td>{fitStatus}</td>\n <td>{numSignalAll:.0f}</td>\n <td><a href=\"{effName}/{binName}.parameters.txt\">Params</a> <a href=\"{effName}/{binName}_correlation.png\">Corr.</a> NLL: {nll:.0f}</td>\n </tr>'''\n\n\n footer = '''</table>\nGenerated using DiBosonTP version {version}<br />\n</body>\n</html>\n'''\n\ndef setPalette() :\n import array\n def readColors(fileName) :\n with open(fileName) as palette :\n for i, line in enumerate(palette) :\n (r,g,b) = map(float, line.strip().split(','))\n c = ROOT.TColor(r,g,b)\n ROOT.SetOwnership(c, False)\n yield c.GetNumber()\n\n # http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html\n colors = array.array('i', readColors('../data/diverging_bwr_55-98_c37_n256.csv'))\n ROOT.TColor.SetPalette(len(colors), colors)\n ROOT.gStyle.SetNumberContours(len(colors))\n\ndef main() :\n parser = argparse.ArgumentParser(description='Dumps fit info generated by TagProbeFitTreeAnalyzer into HTML summary')\n parser.add_argument('--data', help='Data fit tree name', type=rootFileType)\n parser.add_argument('--output', '-o', help='Directory name for output', required=True)\n parser.add_argument('--input', '-i', help='Directory name in root files to load', default='muonEffs')\n args = parser.parse_args()\n \n ROOT.gStyle.SetPaintTextFormat('0.4f')\n ROOT.gStyle.SetOptTitle(True)\n setPalette()\n\n mkdirP(args.output)\n\n parseFitTree(args.data.Get(args.input), args.output)\n\nif __name__ == '__main__' :\n main()\n" }, { "alpha_fraction": 0.558413028717041, "alphanum_fraction": 0.5818355679512024, "avg_line_length": 41.86475372314453, "blob_id": "ae14fa7d1d53be41938e6825aace68a6ee6014c9", "content_id": "3167163cc3af0627979a7e28e3380fdd91dbc61b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10460, "license_type": "no_license", "max_line_length": 170, "num_lines": 244, "path": "/muonJPsi/fitter.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import FWCore.ParameterSet.Config as cms\nfrom FWCore.ParameterSet.VarParsing import VarParsing\nimport sys\n\noptions = VarParsing('analysis')\n\noptions.register(\n \"isMC\",\n True,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"Compute MC efficiencies\"\n )\n\noptions.register(\n \"inputFileName\",\n \"TnPTree_mc.root\",\n VarParsing.multiplicity.singleton,\n VarParsing.varType.string,\n \"Input filename\"\n )\n\noptions.register(\n \"outputFileName\",\n \"\",\n VarParsing.multiplicity.singleton,\n VarParsing.varType.string,\n \"Output filename\"\n )\n\noptions.register(\n \"conditions\",\n \"\",\n VarParsing.multiplicity.list,\n VarParsing.varType.string,\n \"Additional binned categories (set true)\"\n )\n\noptions.register(\n \"idName\",\n \"passingTight\",\n VarParsing.multiplicity.singleton,\n VarParsing.varType.string,\n \"ID variable name as in the fitter_tree\"\n )\n\noptions.register(\n \"dirName\",\n \"muonEffs\",\n VarParsing.multiplicity.singleton,\n VarParsing.varType.string,\n \"Folder name containing the fitter_tree\"\n )\n\noptions.register(\n \"mcTemplateFile\",\n \"\",\n VarParsing.multiplicity.singleton,\n VarParsing.varType.string,\n \"MC Templates for fit\"\n )\n\noptions.register(\n \"doCutAndCount\",\n False,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"Perform cut and count efficiency measurement\"\n )\n\noptions.register(\n \"startEfficiency\",\n 0.9,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.float,\n \"Adjust default efficiency used to seed the start of fit\"\n )\n\noptions.parseArguments()\n\n\nprocess = cms.Process(\"TagProbe\")\nprocess.source = cms.Source(\"EmptySource\")\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) )\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.destinations = ['cout', 'cerr']\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\n\n################################################\n\nInputFileName = options.inputFileName\nOutputFile = \"efficiency-mc-\"+options.idName\nif (not options.isMC):\n OutputFile = \"efficiency-data-\"+options.idName\n\nif (options.outputFileName != \"\"):\n OutputFile = OutputFile+\"-\"+options.outputFileName+\".root\"\nelse:\n OutputFile = OutputFile+\".root\"\n\n################################################\n\nEfficiencyBins = cms.PSet(\n probe_pt = cms.vdouble( 5, 10, 20, 30 ),\n probe_abseta = cms.vdouble( 0.0, 1.5, 2.5), \n )\n\nEfficiencyBinningSpecification = cms.PSet(\n UnbinnedVariables = cms.vstring(\"mass\", \"totWeight\"),\n BinnedVariables = cms.PSet(EfficiencyBins),\n BinToPDFmap = cms.vstring(\"pdfSignalPlusBackground\") \n )\n\nif options.mcTemplateFile :\n for absetabin in range(len(EfficiencyBins.probe_abseta)-1) :\n for ptbin in range(len(EfficiencyBins.probe_pt)-1) :\n EfficiencyBinningSpecification.BinToPDFmap += [\n \"*probe_abseta_bin%d*probe_pt_bin%d*\" % (absetabin, ptbin),\n \"pdfSignal_probe_abseta_bin%d__probe_pt_bin%d\" % (absetabin, ptbin)\n ]\n\nif len(options.conditions) > 0 :\n for condition in options.conditions :\n setattr(EfficiencyBinningSpecification.BinnedVariables, condition, cms.vstring(\"true\"))\n\nif options.isMC :\n setattr(EfficiencyBinningSpecification.BinnedVariables, 'mcTrue', cms.vstring(\"true\"))\n\n############################################################################################\n\nprocess.TnPMeasurement = cms.EDAnalyzer(\"TagProbeFitTreeAnalyzer\",\n InputFileNames = cms.vstring(InputFileName),\n InputDirectoryName = cms.string(options.dirName),\n InputTreeName = cms.string(\"fitter_tree\"), \n OutputFileName = cms.string(OutputFile),\n NumCPU = cms.uint32(1),\n SaveWorkspace = cms.bool(False), #VERY TIME CONSUMING FOR MC\n doCutAndCount = cms.bool(options.doCutAndCount),\n floatShapeParameters = cms.bool(True),\n binnedFit = cms.bool(True),\n binsForFit = cms.uint32(60),\n #fixVars = cms.vstring(\"meanP\", \"meanF\", \"sigmaP\", \"sigmaF\", \"sigmaP_2\", \"sigmaF_2\"),\n \n # defines all the real variables of the probes available in the input tree and intended for use in the efficiencies\n Variables = cms.PSet(mass = cms.vstring(\"Tag-Probe Mass\", \"2.5\", \"3.5\", \"GeV/c^{2}\"),\n probe_pt = cms.vstring(\"Probe p_{T}\", \"0\", \"100\", \"GeV/c\"),\n probe_abseta = cms.vstring(\"Probe |#eta|\", \"0\", \"2.5\", \"\"), \n totWeight = cms.vstring(\"totWeight\", \"-100000000\", \"1000000000\", \"\"),\n ),\n \n # defines all the discrete variables of the probes available in the input tree and intended for use in the efficiency calculations\n Categories = cms.PSet(),\n \n # defines all the PDFs that will be available for the efficiency calculations; \n # uses RooFit's \"factory\" syntax;\n # each pdf needs to define \"signal\", \"backgroundPass\", \"backgroundFail\" pdfs, \"efficiency[0.9,0,1]\" \n # and \"signalFractionInPassing[0.9]\" are used for initial values \n PDFs = cms.PSet(\n pdfSignalPlusBackground = cms.vstring(\n #\"ZGeneratorLineShape::signalPhy(mass, \\\"../data/ZmmGenLevel.root\\\")\", \n \"RooBreitWigner::signalPhy(mass,jpsiMass[3.097],jpsiW[0.0001])\", # ~100keV total width\n \"Gaussian::signalRes(mass, meanSmear[0,-0.2,0.2], widthSmear[0.05,0.01,0.1])\",\n \"RooCMSShape::backgroundPass(mass, alphaPass[0.1], betaPass[0.02, 0.,0.1], gammaPass[0.1, 0, 1], peakPass[4.0])\",\n \"RooCMSShape::backgroundFail(mass, alphaFail[0.1], betaFail[0.02, 0.,0.1], gammaFail[0.1, 0, 1], peakFail[4.0])\",\n \"FCONV::signalPass(mass, signalPhy, signalRes)\",\n \"FCONV::signalFail(mass, signalPhy, signalRes)\", \n \"efficiency[0.9,0,1]\",\n \"signalFractionInPassing[1.0]\" \n ),\n ),\n )\n\n# Set categories\nsetattr(process.TnPMeasurement.Categories, options.idName, cms.vstring(options.idName, \"dummy[pass=1,fail=0]\"))\nsetattr(process.TnPMeasurement.Categories, \"mcTrue\", cms.vstring(\"MC true\", \"dummy[true=1,false=0]\"))\nif len(options.conditions) > 0 :\n for condition in options.conditions :\n setattr(process.TnPMeasurement.Categories, condition, cms.vstring(condition, \"dummy[true=1,false=0]\"))\n\n# Actual efficiency pset\neffName = options.idName\nif options.isMC :\n effName += '_mcTrue'\nif len(options.conditions) > 0 :\n for condition in options.conditions :\n effName += '_'+condition\n\nprocess.TnPMeasurement.Efficiencies = cms.PSet()\nsetattr(process.TnPMeasurement.Efficiencies, effName, cms.PSet(\n EfficiencyBinningSpecification,\n EfficiencyCategoryAndState = cms.vstring(options.idName, \"pass\")\n )\n )\n\n# MC weight\n#if options.isMC :\n# setattr(process.TnPMeasurement, 'WeightVariable', cms.string(\"totWeight\"))\n\n# Templates\npdfDef = cms.vstring(\n #\"Gaussian::signalResPass(mass,meanPSmearing[0.0,-0.200,0.200],sigmaPSmearing[0.05,0.01,0.100])\",\n #\"Gaussian::signalResFail(mass,meanFSmearing[0.0,-0.200,0.200],sigmaFSmearing[0.05,0.01,0.100])\",\n \"Gaussian::signalRes(mass,meanSmearing[0.0,-0.200,0.200],sigmaSmearing[0.05,0.01,0.100])\",\n \"RooCMSShape::backgroundPass(mass, alphaPass[0.1], betaPass[0.02, 0.,0.1], gammaPass[0.1, 0, 1], peakPass[4.0])\",\n \"RooCMSShape::backgroundFail(mass, alphaFail[0.1], betaFail[0.02, 0.,0.1], gammaFail[0.1, 0, 1], peakFail[4.0])\",\n \"FCONV::signalPass(mass, signalPhyPass, signalRes)\",\n \"FCONV::signalFail(mass, signalPhyFail, signalRes)\", \n \"efficiency[%f,0,1]\" % options.startEfficiency,\n \"signalFractionInPassing[1.0]\" \n )\nif options.mcTemplateFile :\n for absetabin in range(len(EfficiencyBins.probe_abseta)-1) :\n for ptbin in range(len(EfficiencyBins.probe_pt)-1) :\n pdfName = \"probe_abseta_bin%d__probe_pt_bin%d\" % (absetabin, ptbin)\n thisDef = cms.vstring(\n 'ZGeneratorLineShape::signalPhyPass(mass, \"%s\", \"%s\")' % (options.mcTemplateFile, 'hMass_%s_Pass' % pdfName),\n 'ZGeneratorLineShape::signalPhyFail(mass, \"%s\", \"%s\")' % (options.mcTemplateFile, 'hMass_%s_Fail' % pdfName)\n )\n setattr(process.TnPMeasurement.PDFs, 'pdfSignal_'+pdfName, thisDef+pdfDef)\n\n# switch pdf settings\nif (not options.isMC):\n for pdf in process.TnPMeasurement.PDFs.__dict__:\n param = process.TnPMeasurement.PDFs.getParameter(pdf)\n if (type(param) is not cms.vstring):\n continue\n for i, l in enumerate(getattr(process.TnPMeasurement.PDFs, pdf)):\n if l.find(\"signalFractionInPassing\") != -1:\n getattr(process.TnPMeasurement.PDFs, pdf)[i] = l.replace(\"[1.0]\",\"[0.5,0.,1.]\")\nelse:\n for pdf in process.TnPMeasurement.PDFs.__dict__:\n param = process.TnPMeasurement.PDFs.getParameter(pdf)\n if (type(param) is not cms.vstring):\n continue\n for i, l in enumerate(getattr(process.TnPMeasurement.PDFs, pdf)):\n if l.find(\"backgroundPass\") != -1:\n getattr(process.TnPMeasurement.PDFs, pdf)[i] = \"RooPolynomial::backgroundPass(mass, a[0.0])\"\n if l.find(\"backgroundFail\") != -1:\n getattr(process.TnPMeasurement.PDFs, pdf)[i] = \"RooPolynomial::backgroundFail(mass, a[0.0])\"\n\nprocess.fit = cms.Path(\n process.TnPMeasurement \n )\n\n" }, { "alpha_fraction": 0.7626112699508667, "alphanum_fraction": 0.7626112699508667, "avg_line_length": 32.70000076293945, "blob_id": "04ae35e3ad109af03e3194dca6cfa98d180ac7c5", "content_id": "f90b6f4fd021e51291d5f5315b7460666c512cff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 337, "license_type": "no_license", "max_line_length": 65, "num_lines": 10, "path": "/electrons/runNewFits.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\nrm -rf plots/*\n./newfitter.py\nmkdir -p plots/badFits\nmv badFit_* plots/badFits\ndumpTagProbeTreeHTML.py --data fits.root -i electronFits -o plots\n./plot.py ZZLoose \"Electron Loose ID\"\n./plot.py ZZTight \"Electron Tight ID\"\n./plot.py ZZIso_wrtLoose \"Electron Loose Isolation\"\n./plot.py ZZIso_wrtTight \"Electron Tight Isolation\"\n" }, { "alpha_fraction": 0.7028868794441223, "alphanum_fraction": 0.7075488567352295, "avg_line_length": 26.885000228881836, "blob_id": "a1903796d5b80395a0fa73d259db576d6b9e214d", "content_id": "1b25a38fdfd8c1d67eae91e20c855f9346fab186", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5577, "license_type": "no_license", "max_line_length": 109, "num_lines": 200, "path": "/plugins/OneStopMuonShop.cc", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "// -*- C++ -*-\n//\n// Package: Analysis/OneStopMuonShop\n// Class: OneStopMuonShop\n// \n/**\\class OneStopMuonShop OneStopMuonShop.cc Analysis/OneStopMuonShop/plugins/OneStopMuonShop.cc\n\n Description: [one line class summary]\n\n Implementation:\n [Notes on implementation]\n*/\n//\n// Original Author: Nicholas Charles Smith\n// Created: Recently?\n//\n//\n\n\n// system include files\n#include <memory>\n\n// user include files\n#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/Framework/interface/stream/EDProducer.h\"\n\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n#include \"FWCore/Utilities/interface/StreamID.h\"\n\n#include \"DataFormats/PatCandidates/interface/Muon.h\"\n#include \"DataFormats/TrackReco/interface/TrackFwd.h\"\n#include \"DataFormats/VertexReco/interface/VertexFwd.h\"\n#include \"DataFormats/VertexReco/interface/Vertex.h\"\n\n#include \"RecoMuon/MuonIdentification/plugins/MuonIdProducer.h\"\n\nclass OneStopMuonShop : public edm::stream::EDProducer<> {\n public:\n explicit OneStopMuonShop(const edm::ParameterSet&);\n ~OneStopMuonShop();\n\n static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);\n\n private:\n virtual void beginStream(edm::StreamID) override;\n virtual void produce(edm::Event&, const edm::EventSetup&) override;\n virtual void endStream() override;\n\n //virtual void beginRun(edm::Run const&, edm::EventSetup const&) override;\n //virtual void endRun(edm::Run const&, edm::EventSetup const&) override;\n //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override;\n //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override;\n\n edm::EDGetTokenT<reco::TrackRefVector> srcTrackRefToken_;\n edm::EDGetTokenT<reco::MuonCollection> srcRecoToken_;\n edm::EDGetTokenT<pat::MuonCollection> srcPatToken_;\n\n edm::EDGetTokenT<reco::VertexCollection> vertexToken_;\n};\n\nOneStopMuonShop::OneStopMuonShop(const edm::ParameterSet& iConfig) :\n srcTrackRefToken_(consumes<reco::TrackRefVector>(iConfig.getParameter<edm::InputTag>(\"tracks\"))),\n srcRecoToken_(consumes<reco::MuonCollection>(iConfig.getParameter<edm::InputTag>(\"recoMuons\"))),\n srcPatToken_(consumes<pat::MuonCollection>(iConfig.getParameter<edm::InputTag>(\"patMuons\"))),\n vertexToken_(consumes<reco::VertexCollection>(iConfig.getParameter<edm::InputTag>(\"vertices\")))\n{\n produces<pat::MuonCollection>();\n}\n\n\nOneStopMuonShop::~OneStopMuonShop()\n{\n}\n\nvoid\nOneStopMuonShop::produce(edm::Event& iEvent, const edm::EventSetup& iSetup)\n{\n using namespace edm;\n\n std::unique_ptr<pat::MuonCollection> output(new pat::MuonCollection());\n\n Handle<reco::TrackRefVector> trackRefsH;\n iEvent.getByToken(srcTrackRefToken_, trackRefsH);\n\n Handle<reco::MuonCollection> muonsH;\n iEvent.getByToken(srcRecoToken_, muonsH);\n\n Handle<pat::MuonCollection> patMuonsH;\n iEvent.getByToken(srcPatToken_, patMuonsH);\n\n bool usePat{false};\n if ( patMuonsH.isValid() ) usePat = true;\n\n Handle<reco::VertexCollection> vtx;\n iEvent.getByToken(vertexToken_, vtx);\n const auto& pv = vtx->at(0);\n\n for(const reco::TrackRef& track : *trackRefsH) {\n const pat::Muon * matchedMuon{nullptr};\n if ( usePat ) {\n for(const auto& patMuon : *patMuonsH) {\n if ( patMuon.innerTrack() == track ) {\n matchedMuon = &patMuon;\n break;\n }\n }\n } else {\n for(const auto& muon : *muonsH) {\n if ( muon.innerTrack() == track ) {\n matchedMuon = new pat::Muon(muon);\n break;\n }\n }\n }\n\n if ( matchedMuon != nullptr ) {\n output->push_back(*matchedMuon);\n if ( ! usePat ) delete matchedMuon;\n } else {\n // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_2/doc/html/df/d17/MuonIdProducer_8cc_source.html#l01166\n const double energy = hypot(track->p(), 0.105658369);\n const math::XYZTLorentzVector p4(track->px(), track->py(), track->pz(), energy);\n pat::Muon newMuon(reco::Muon(track->charge(), p4, track->vertex()));\n newMuon.setMuonTrack(reco::Muon::InnerTrack, track);\n newMuon.setBestTrack(reco::Muon::InnerTrack);\n newMuon.setTunePBestTrack(reco::Muon::InnerTrack);\n output->push_back(newMuon);\n }\n\n auto& muon = output->back();\n if ( matchedMuon != nullptr && muon.isTightMuon(pv) ) {\n muon.addUserInt(\"isTightMuon\", 1);\n } else {\n muon.addUserInt(\"isTightMuon\", 0);\n }\n muon.addUserFloat(\"dxyToPV\", muon.muonBestTrack()->dxy(pv.position()));\n muon.addUserFloat(\"dzToPV\", muon.muonBestTrack()->dz(pv.position()));\n }\n\n iEvent.put(std::move(output));\n}\n\n\nvoid\nOneStopMuonShop::beginStream(edm::StreamID)\n{\n}\n\n\nvoid\nOneStopMuonShop::endStream() {\n}\n\n\n/*\nvoid\nOneStopMuonShop::beginRun(edm::Run const&, edm::EventSetup const&)\n{\n}\n*/\n \n\n/*\nvoid\nOneStopMuonShop::endRun(edm::Run const&, edm::EventSetup const&)\n{\n}\n*/\n \n\n/*\nvoid\nOneStopMuonShop::beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&)\n{\n}\n*/\n \n\n/*\nvoid\nOneStopMuonShop::endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&)\n{\n}\n*/\n \n\nvoid\nOneStopMuonShop::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {\n //The following says we do not know what parameters are allowed so do no validation\n // Please change this to state exactly what you do use, even if it is no parameters\n edm::ParameterSetDescription desc;\n desc.setUnknown();\n descriptions.addDefault(desc);\n}\n\n\nDEFINE_FWK_MODULE(OneStopMuonShop);\n" }, { "alpha_fraction": 0.7106130719184875, "alphanum_fraction": 0.7758734226226807, "avg_line_length": 41.13888931274414, "blob_id": "d4a60e64b33680cd8b71d68ce8b1897df746c109", "content_id": "be1e5bff8686e8edfed4d2843533cb81c27d0e0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1517, "license_type": "no_license", "max_line_length": 175, "num_lines": 36, "path": "/electrons/submit.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\n\nsubmit() {\n jobName=$1\n shift\n pythonFile=$1\n shift\n dataset=$1\n shift\n cachefile=$1\n shift\n flags=$@\n\n if [ ! -f $cachefile ]\n then\n das_client.py --query=\"file dataset=${dataset}\" --format plain --limit 0 > $cachefile\n fi\n\n farmoutAnalysisJobs $jobName \\\n --infer-cmssw-path \\\n --input-file-list=${cachefile} \\\n --input-dir=root://cmsxrootd.hep.wisc.edu/ \\\n --assume-input-files-exist \\\n --input-files-per-job=10 \\\n ${pythonFile} \\\n 'inputFiles=$inputFileNames' 'outputFile=$outputFileName' ${flags}\n}\n\nsubmit electronTP makeTree.py /DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1/MINIAODSIM DYJetsMC.txt isMC=1\nsubmit electronTPLO makeTree.py /DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1/MINIAODSIM DYJetsMC_LO.txt isMC=1\nsubmit electronTPData makeTree.py /SingleElectron/Run2015D-05Oct2015-v1/MINIAOD SingleElectron.txt isMC=0\nsubmit electronTPDataPrompt makeTree.py /SingleElectron/Run2015D-PromptReco-v4/MINIAOD SingleElectronPrompt.txt isMC=0\nsubmit electronTPDataC makeTree.py /SingleElectron/Run2015C_25ns-05Oct2015-v1/MINIAOD SingleElectronC.txt isMC=0\n\n#submit electronTPMC makeDZTree.py /DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1/MINIAODSIM DYJetsMC.txt isMC=1\n#submit electronTPData makeDZTree.py /DoubleEG/Run2015D-05Oct2015-v1/MINIAOD DoubleElectron.txt isMC=0\n" }, { "alpha_fraction": 0.6473512649536133, "alphanum_fraction": 0.6687811017036438, "avg_line_length": 36.15286636352539, "blob_id": "fe6cf238c640077bbe4602e32828ca693633af4d", "content_id": "edd4169d530264297c788d3c78fc0804f45e83cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5833, "license_type": "no_license", "max_line_length": 138, "num_lines": 157, "path": "/plugins/zzElectronIdIsoProducer.cc", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "// Original Author: Nicholas Charles Smith\n// Created: Tue, 16 Jun 2015 08:49:00 GMT\n\n// system include files\n#include <memory>\n\n// user include files\n#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/Framework/interface/EDProducer.h\"\n\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n\n#include \"DataFormats/Common/interface/RefVector.h\"\n#include \"DataFormats/EgammaCandidates/interface/GsfElectron.h\"\n#include \"DataFormats/PatCandidates/interface/Electron.h\"\n#include \"DataFormats/VertexReco/interface/VertexFwd.h\"\n#include \"DataFormats/VertexReco/interface/Vertex.h\"\n\nclass zzElectronIdIsoProducer : public edm::EDProducer {\n public:\n explicit zzElectronIdIsoProducer(const edm::ParameterSet&);\n ~zzElectronIdIsoProducer();\n\n static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);\n\n private:\n virtual void beginJob() override;\n virtual void produce(edm::Event&, const edm::EventSetup&) override;\n virtual void endJob() override;\n\n edm::EDGetTokenT<edm::View<reco::GsfElectron>> electronsToken_;\n edm::EDGetTokenT<edm::ValueMap<float>> mvaIdValueMapToken_;\n edm::EDGetTokenT<reco::VertexCollection> vertexToken_;\n edm::EDGetTokenT<double> rhoToken_;\n};\n\nzzElectronIdIsoProducer::zzElectronIdIsoProducer(const edm::ParameterSet& iConfig) :\n electronsToken_(consumes<edm::View<reco::GsfElectron>>(iConfig.getParameter<edm::InputTag>(\"electrons\"))),\n mvaIdValueMapToken_(consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>(\"mvaIdValueMap\"))),\n vertexToken_(consumes<reco::VertexCollection>(iConfig.getParameter<edm::InputTag>(\"primaryVertices\"))),\n rhoToken_(consumes<double>(iConfig.getParameter<edm::InputTag>(\"rho\")))\n{\n produces<edm::ValueMap<bool>>(\"electronZZIDLoose\");\n produces<edm::ValueMap<bool>>(\"electronZZIDTight\");\n produces<edm::ValueMap<bool>>(\"electronZZIso\");\n}\n\n\nzzElectronIdIsoProducer::~zzElectronIdIsoProducer()\n{\n}\n\nvoid\nzzElectronIdIsoProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup)\n{\n using namespace edm;\n\n Handle<View<reco::GsfElectron>> electrons;\n iEvent.getByToken(electronsToken_, electrons);\n\n Handle<ValueMap<float>> mvaValues;\n iEvent.getByToken(mvaIdValueMapToken_, mvaValues);\n\n Handle<reco::VertexCollection> vertices;\n iEvent.getByToken(vertexToken_, vertices);\n const auto& primaryVertex = vertices->at(0);\n\n Handle<double> rhoPtr;\n iEvent.getByToken(rhoToken_, rhoPtr);\n const double rho = *rhoPtr;\n\n std::vector<bool> idLooseValues(electrons->size());\n std::vector<bool> idTightValues(electrons->size());\n std::vector<bool> isoValues(electrons->size());\n\n for ( size_t i=0; i<electrons->size(); ++i ) {\n auto l = dynamic_cast<const pat::Electron *>(&electrons->at(i));\n if ( l == nullptr )\n throw cms::Exception(\"Could not upcast to pat::Electron\");\n\n float BDT = (*mvaValues)[electrons->ptrAt(i)];\n // https://twiki.cern.ch/twiki/bin/viewauth/CMS/HiggsZZ4l2015#Electrons\n float pt = l->pt();\n float eta = fabs(l->eta());\n float dxy = l->gsfTrack()->dxy(primaryVertex.position());\n float dz = l->gsfTrack()->dz(primaryVertex.position());\n float fSCeta = fabs(l->superCluster()->eta());\n\n bool idL = (pt>10.) && (fabs(eta)<2.5) && fabs(dxy)<0.5 && fabs(dz)<1.;\n\n bool isBDT = (pt<=10 && ((fSCeta<0.8 && BDT > -0.265) ||\n (fSCeta>=0.8 && fSCeta<1.479 && BDT > -0.556) ||\n (fSCeta>=1.479 && BDT > -0.551))) \n || (pt>10 && ((fSCeta<0.8 && BDT > -0.072) ||\n (fSCeta>=0.8 && fSCeta<1.479 && BDT > -0.286) || \n (fSCeta>=1.479 && BDT > -0.267)));\n\n float EffectiveArea = 0.;\n if (eta >= 0.0 && eta < 0.8 ) EffectiveArea = 0.1830;\n if (eta >= 0.8 && eta < 1.3 ) EffectiveArea = 0.1734;\n if (eta >= 1.3 && eta < 2.0 ) EffectiveArea = 0.1077;\n if (eta >= 2.0 && eta < 2.2 ) EffectiveArea = 0.1565;\n if (eta >= 2.2) EffectiveArea = 0.2680;\n\n float pfRelCombIso = (l->chargedHadronIso() + std::max(0., l->neutralHadronIso() + l->photonIso() - EffectiveArea * rho)) / l->pt();\n\n idLooseValues[i] = idL;\n idTightValues[i] = idL && isBDT;\n isoValues[i] = pfRelCombIso < 0.5;\n }\n\n // All this just to fill some value maps?!\n\n std::unique_ptr<ValueMap<bool>> idLoose{new ValueMap<bool>};\n std::unique_ptr<ValueMap<bool>> idTight{new ValueMap<bool>};\n std::unique_ptr<ValueMap<bool>> iso{new ValueMap<bool>};\n\n ValueMap<bool>::Filler idLooseFill(*idLoose);\n ValueMap<bool>::Filler idTightFill(*idTight);\n ValueMap<bool>::Filler isoFill(*iso);\n\n idLooseFill.insert(electrons, idLooseValues.begin(), idLooseValues.end());\n idTightFill.insert(electrons, idTightValues.begin(), idTightValues.end());\n isoFill.insert(electrons, isoValues.begin(), isoValues.end());\n\n idLooseFill.fill();\n idTightFill.fill();\n isoFill.fill();\n\n iEvent.put(std::move(idLoose), \"electronZZIDLoose\");\n iEvent.put(std::move(idTight), \"electronZZIDTight\");\n iEvent.put(std::move(iso), \"electronZZIso\");\n}\n\nvoid \nzzElectronIdIsoProducer::beginJob()\n{\n}\n\nvoid \nzzElectronIdIsoProducer::endJob() {\n}\n\nvoid\nzzElectronIdIsoProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {\n //The following says we do not know what parameters are allowed so do no validation\n // Please change this to state exactly what you do use, even if it is no parameters\n edm::ParameterSetDescription desc;\n desc.setUnknown();\n descriptions.addDefault(desc);\n}\n\n//define this as a plug-in\nDEFINE_FWK_MODULE(zzElectronIdIsoProducer);\n" }, { "alpha_fraction": 0.6651884913444519, "alphanum_fraction": 0.6962305903434753, "avg_line_length": 33.69230651855469, "blob_id": "f3b135a4a5e1ff869a8ffcee095e3728259e76b4", "content_id": "984de373e75078667e57991b6eed6878fd91aba6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 451, "license_type": "no_license", "max_line_length": 61, "num_lines": 13, "path": "/phase2muons/runNewFits.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\nrm -rf plots/*\n./newfitter.py $1\npuVal=${1%.root}\nmkdir -p plots/badFits\nmv badFit_* plots/badFits\ndumpTagProbeTreeHTML.py --data fits.root -i muonFits -o plots\n./plot.py WZLoose \"WZ Loose ID @${puVal}\"\n./plot.py Tight \"Tight ID @${puVal}\"\n./plot.py RelIso0p4 \"PF Rel. Iso<0.4 @${puVal}\"\n./plot.py RelIso0p12 \"PF Rel. Iso<0.12 @${puVal}\"\nrm -rf ~/www/TagProbePlots/Phase2Muons/${puVal}\ncp -r plots ~/www/TagProbePlots/Phase2Muons/${puVal}\n" }, { "alpha_fraction": 0.7218788862228394, "alphanum_fraction": 0.7255871295928955, "avg_line_length": 31.360000610351562, "blob_id": "8eb98637a8e54851d0ec24ab0c408f9330e03a12", "content_id": "12c433c07f0350182c55906b7d99f33705e9ceb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3236, "license_type": "no_license", "max_line_length": 119, "num_lines": 100, "path": "/plugins/triggerObjectUnpacker.cc", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "// Original Author: Nicholas Charles Smith\n// Created: Tue, 16 Jun 2015 08:49:00 GMT\n\n// system include files\n#include <memory>\n\n// user include files\n#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/Framework/interface/EDProducer.h\"\n\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n\n#include \"FWCore/Common/interface/TriggerNames.h\"\n#include \"DataFormats/Common/interface/TriggerResults.h\"\n#include \"DataFormats/PatCandidates/interface/TriggerObjectStandAlone.h\"\n#include \"DataFormats/PatCandidates/interface/PackedTriggerPrescales.h\"\n\nclass triggerObjectUnpacker : public edm::EDProducer {\n public:\n explicit triggerObjectUnpacker(const edm::ParameterSet&);\n ~triggerObjectUnpacker();\n\n static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);\n\n private:\n virtual void beginJob() override;\n virtual void produce(edm::Event&, const edm::EventSetup&) override;\n virtual void endJob() override;\n\n edm::EDGetTokenT<edm::TriggerResults> triggerBits_;\n edm::EDGetTokenT<pat::TriggerObjectStandAloneCollection> triggerObjects_;\n};\n\ntriggerObjectUnpacker::triggerObjectUnpacker(const edm::ParameterSet& iConfig) :\n triggerBits_(consumes<edm::TriggerResults>(iConfig.getParameter<edm::InputTag>(\"bits\"))),\n triggerObjects_(consumes<pat::TriggerObjectStandAloneCollection>(iConfig.getParameter<edm::InputTag>(\"objects\")))\n{\n produces<pat::TriggerObjectStandAloneCollection>();\n\n}\n\n\ntriggerObjectUnpacker::~triggerObjectUnpacker()\n{\n}\n\nvoid\ntriggerObjectUnpacker::produce(edm::Event& iEvent, const edm::EventSetup& iSetup)\n{\n using namespace edm;\n\n edm::Handle<edm::TriggerResults> triggerBits;\n edm::Handle<pat::TriggerObjectStandAloneCollection> triggerObjects;\n\n iEvent.getByToken(triggerBits_, triggerBits);\n iEvent.getByToken(triggerObjects_, triggerObjects);\n\n const edm::TriggerNames &names = iEvent.triggerNames(*triggerBits);\n\n std::unique_ptr<pat::TriggerObjectStandAloneCollection> unpackedObjects{new pat::TriggerObjectStandAloneCollection};\n\n for ( auto object : *triggerObjects ) {\n object.unpackPathNames(names);\n unpackedObjects->push_back(object);\n // if ( object.type(trigger::TriggerPhoton) ) {\n // std::cout << \"New electron----------------------------------------\" << std::endl;\n // for( auto name : object.pathNames() )\n // std::cout << \"Path name: \" << name << std::endl;\n // for( auto name : object.filterLabels() )\n // std::cout << \"Filter label: \" << name << std::endl;\n // }\n \n }\n\n iEvent.put(std::move(unpackedObjects));\n}\n\nvoid \ntriggerObjectUnpacker::beginJob()\n{\n}\n\nvoid \ntriggerObjectUnpacker::endJob() {\n}\n\nvoid\ntriggerObjectUnpacker::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {\n //The following says we do not know what parameters are allowed so do no validation\n // Please change this to state exactly what you do use, even if it is no parameters\n edm::ParameterSetDescription desc;\n desc.setUnknown();\n descriptions.addDefault(desc);\n}\n\n//define this as a plug-in\nDEFINE_FWK_MODULE(triggerObjectUnpacker);\n" }, { "alpha_fraction": 0.5889674425125122, "alphanum_fraction": 0.6108911037445068, "avg_line_length": 43.74683380126953, "blob_id": "d44fb4a8ece5ea8e31bda391ff44c81956814618", "content_id": "9deab97899fe2cae450003cd2f2622c8ae7209b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7070, "license_type": "no_license", "max_line_length": 135, "num_lines": 158, "path": "/muons/newfitter.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nROOT.gROOT.SetBatch(True)\nROOT.PyConfig.IgnoreCommandLineOptions = True\nfrom Analysis.DiBosonTP.PassFailSimulFitter import PassFailSimulFitter\n\ndef main() :\n fitVariable = ROOT.RooRealVar('mass', 'TP Pair Mass', 60, 120, 'GeV')\n fitVariable.setBins(60)\n\n ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.ERROR)\n ROOT.Math.MinimizerOptions.SetDefaultTolerance(1.e-2) # default is 1.e-2\n\n fmc = ROOT.TFile.Open('TnPTree_mc.root')\n tmc = fmc.Get('muonEffs/fitter_tree')\n\n fmcAlt = ROOT.TFile.Open('TnPTree_mcLO.root')\n tmcAlt = fmcAlt.Get('muonEffs/fitter_tree')\n\n fdata = ROOT.TFile.Open('TnPTree_data.root')\n tdata = fdata.Get('muonEffs/fitter_tree')\n\n mcTruthCondition = ['mcTrue', 'mc_probe_isPromptFinalState']\n\n pdfDefinition = []\n with open('pdfDefinition.txt') as defFile :\n for line in defFile :\n line = line.strip()\n if len(line) == 0 or line[0] is '#' :\n continue\n pdfDefinition.append(line)\n\n\n def statusInfo(fitResults) :\n fitStatus=':'.join(['% d' % fitResults.statusCodeHistory(i) for i in range(fitResults.numStatusHistory())]),\n return fitStatus\n\n def fitBin(name, allProbeCondition, passingProbeCondition) :\n ROOT.gDirectory.mkdir(name).cd()\n fitter = PassFailSimulFitter(name, fitVariable)\n fitter.addDataFromTree(tmc, 'mcData', allProbeCondition+mcTruthCondition, passingProbeCondition, separatePassFail = True)\n fitter.addDataFromTree(tmcAlt, 'mcAltData', allProbeCondition+mcTruthCondition, passingProbeCondition, separatePassFail = True)\n nMCPass = fitter.workspace.data('mcDataPass').sumEntries()\n nMCFail = fitter.workspace.data('mcDataFail').sumEntries()\n mcEff = nMCPass/(nMCPass+nMCFail)\n mcEffLo = ROOT.TEfficiency.ClopperPearson(int(nMCPass+nMCFail), int(nMCPass), 0.68, False)\n mcEffHi = ROOT.TEfficiency.ClopperPearson(int(nMCPass+nMCFail), int(nMCPass), 0.68, True)\n h=ROOT.TH1F('mc_cutCount', 'Cut & Count', 2, 0, 2)\n h.SetBinContent(1, nMCPass)\n h.SetBinContent(2, nMCPass+nMCFail)\n\n # All MC templates must be set up by now\n fitter.setPdf(pdfDefinition)\n\n print '-'*40, 'Central value fit'\n fitter.addDataFromTree(tdata, 'data', allProbeCondition, passingProbeCondition)\n res = fitter.fit('simPdf', 'data')\n effValue = res.floatParsFinal().find('efficiency')\n dataEff = effValue.getVal()\n dataEffErrHi = effValue.getErrorHi()\n dataEffErrLo = effValue.getErrorLo()\n scaleFactor = dataEff / mcEff\n maxSf = (dataEff+dataEffErrHi)/mcEffLo\n minSf = (dataEff+dataEffErrLo)/mcEffHi\n res.SetName('fitresults')\n c = fitter.drawFitCanvas(res)\n c.Write()\n h.Write()\n res.Write()\n\n print '-'*40, 'Fit with alternate MC template'\n resAlt = fitter.fit('simAltPdf', 'data')\n dataAltEff = resAlt.floatParsFinal().find('efficiency').getVal()\n resAlt.SetName('fitresults_systAltTemplate')\n resAlt.Write()\n\n print '-'*40, 'Fit with tag pt > 30 (vs. 25)'\n fitter.addDataFromTree(tdata, 'dataTagPt30', allProbeCondition+['tag_tag_pt>30'], passingProbeCondition)\n resTagPt30 = fitter.fit('simPdf', 'dataTagPt30')\n dataTagPt30Eff = resTagPt30.floatParsFinal().find('efficiency').getVal()\n resTagPt30.Write()\n\n print '-'*40, 'Fit with CMSShape background (vs. Bernstein)'\n resCMSBkg = fitter.fit('simCMSBkgPdf', 'data')\n dataCMSBkgEff = resCMSBkg.floatParsFinal().find('efficiency').getVal()\n resCMSBkg.Write()\n\n fitter.workspace.Write()\n print name, ': Data=%.2f, MC=%.2f, Ratio=%.2f' % (dataEff, mcEff, dataEff/mcEff)\n condition = ' && '.join(allProbeCondition+[passingProbeCondition])\n variations = {\n 'CENTRAL' : (scaleFactor, res),\n 'STAT_UP' : (maxSf, res),\n 'STAT_DOWN': (minSf, res),\n 'SYST_ALT_TEMPL' : (dataAltEff / mcEff, resAlt),\n 'SYST_TAG_PT30' : (dataTagPt30Eff / mcEff, resTagPt30),\n 'SYST_CMSSHAPE' : (dataCMSBkgEff / mcEff, resCMSBkg),\n 'EFF_DATA' : (dataEff, res),\n 'EFF_DATA_ERRSYM' : ((dataEffErrHi-dataEffErrLo)/2, res),\n 'EFF_MC' : (mcEff, res),\n 'EFF_MC_ERRSYM' : ((mcEffHi-mcEffLo)/2, res),\n }\n cutString = ''\n for varName, value in variations.items() :\n (value, fitResult) = value\n cutString += ' if ( variation == Variation::%s && (%s) ) return %f;\\n' % (varName, condition, value)\n print ' Variation {:>15s} : {:.4f}, edm={:f}, status={:s}'.format(varName, value, fitResult.edm(), statusInfo(fitResult))\n if 'STAT' not in varName and fitResult.statusCodeHistory(0) < 0 :\n cBad = fitter.drawFitCanvas(fitResult)\n cBad.Print('badFit_%s_%s.png' %(name, varName))\n\n ROOT.TNamed('cutString', cutString).Write()\n print\n ROOT.gDirectory.cd('..')\n\n def fit(name, allProbeCondition, passingProbeCondition, binningMap, macroVariables) :\n ROOT.gDirectory.mkdir(name).cd()\n ROOT.TNamed('variables', ', '.join(macroVariables)).Write()\n for binName, cut in sorted(binningMap.items()) :\n fitBin(name+'_'+binName, allProbeCondition+cut, passingProbeCondition)\n ROOT.gDirectory.cd('..')\n\n ptBinning = {\n 'pt05to10' : ['probe_pt>5 && probe_pt<10'],\n 'pt10to20' : ['probe_pt>10 && probe_pt<20'],\n 'pt20to30' : ['probe_pt>20 && probe_pt<30'],\n 'pt30to40' : ['probe_pt>30 && probe_pt<40'],\n 'pt40to50' : ['probe_pt>40 && probe_pt<50'],\n 'pt50toInf' : ['probe_pt>50'],\n }\n\n etaBinning = {\n 'abseta0p0to0p9' : ['probe_abseta < 0.9'],\n 'abseta0p9to1p2' : ['probe_abseta > 0.9 && probe_abseta < 1.2'],\n 'abseta1p2to2p1' : ['probe_abseta > 1.2 && probe_abseta < 2.1'],\n 'abseta2p1to2p4' : ['probe_abseta > 2.1 && probe_abseta < 2.4'],\n }\n \n binning = {}\n for name1, cut1 in ptBinning.items() :\n if name1 is 'pt05to10' :\n binning[name1] = cut1\n continue\n for name2, cut2 in etaBinning.items() :\n binning[name1+'_'+name2] = cut1+cut2\n\n commonVars = ['float probe_pt', 'float probe_abseta']\n\n fout = ROOT.TFile('fits.root', 'recreate')\n fout.mkdir('muonFits').cd()\n\n fit('ZZLoose', [], 'passingIDZZLoose', binning, commonVars+['bool passingIDZZLoose'])\n fit('ZZTight', [], 'passingIDZZTight', binning, commonVars+['bool passingIDZZTight'])\n fit('ZZIso_wrtLoose', ['passingIDZZLoose'], 'passingIsoZZ', binning, commonVars+['bool passingIDZZLoose','bool passingIsoZZ'])\n fit('ZZIso_wrtTight', ['passingIDZZTight'], 'passingIsoZZ', binning, commonVars+['bool passingIDZZTight','bool passingIsoZZ'])\n\nif __name__ == '__main__' :\n main()\n" }, { "alpha_fraction": 0.7571614384651184, "alphanum_fraction": 0.7886284589767456, "avg_line_length": 58.07692337036133, "blob_id": "773d5bfd2ead8b7366e934f783809135f529e2ed", "content_id": "ab287a7ec4403e8ea79f6115f3b5c4184691be38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4608, "license_type": "no_license", "max_line_length": 228, "num_lines": 78, "path": "/electrons/runFits.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\ncmsenv\n\nif [[ $1 == 'doMC' ]]; then\n # MC ID/Iso\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingLoose 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingMedium 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingTight 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingVeto 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingZZLoose 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingZZTight 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingZZIso conditions=passingZZLoose outputFileName=passingZZLoose 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingZZIso conditions=passingZZTight outputFileName=passingZZTight 2>&1 > /dev/null\n\n # MC Triggers\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root dirName=GsfElectronToTrigger idName=passingHLTEle17Ele12Leg1 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root dirName=GsfElectronToTrigger idName=passingHLTEle17Ele12Leg1L1Match 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root dirName=GsfElectronToTrigger idName=passingHLTEle17Ele12Leg2 2>&1 > /dev/null\n\n # DZ\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTreeDZ_mc.root idName=passingHLTDZFilter dirName=GsfElectronToTrigger 2>&1 > /dev/null\nfi\n\n# Make MC templates for data fit\ncommonTemplateFlags=\"-d GsfElectronToRECO --var2Name=probe_Ele_pt --var1Name=probe_Ele_abseta --var2Bins=10,20,30,40,50,100,1000 --var1Bins=0,1.5,2.5 --weightVarName=totWeight\"\ndataFitSeq() {\n dirName=$1\n shift\n idName=$1\n shift\n conditions=$1\n\n if [[ $conditions ]]; then\n condFileSafe=$(echo ${conditions}|tr ',' '_')\n if [[ ! -f mcTemplates-${idName}-${condFileSafe}.root ]]; then\n getTemplatesFromMC.py ${commonTemplateFlags} -d ${dirName} -i TnPTree_mc.root -o mcTemplates-${idName}-${condFileSafe}.root --idprobe=${idName} --conditions=\"${conditions}\"\n fi\n cmsRun fitter.py isMC=0 inputFileName=TnPTree_data.root dirName=${dirName} idName=${idName} conditions=${conditions} outputFileName=${condFileSafe} mcTemplateFile=mcTemplates-${idName}-${condFileSafe}.root 2>&1 > /dev/null &\n else\n if [[ ! -f mcTemplates-${idName}.root ]]; then\n getTemplatesFromMC.py ${commonTemplateFlags} -d ${dirName} -i TnPTree_mc.root -o mcTemplates-${idName}.root --idprobe=${idName}\n fi\n cmsRun fitter.py isMC=0 inputFileName=TnPTree_data.root dirName=${dirName} idName=${idName} mcTemplateFile=mcTemplates-${idName}.root 2>&1 > /dev/null &\n fi\n}\n\n# rm -rf mcTemplates-*.root\n\n# Data ID/Iso\ndataFitSeq GsfElectronToRECO passingLoose\ndataFitSeq GsfElectronToRECO passingMedium\ndataFitSeq GsfElectronToRECO passingTight\ndataFitSeq GsfElectronToRECO passingVeto\ndataFitSeq GsfElectronToRECO passingZZLoose\ndataFitSeq GsfElectronToRECO passingZZTight\ndataFitSeq GsfElectronToRECO passingZZIso passingZZLoose\ndataFitSeq GsfElectronToRECO passingZZIso passingZZTight\n\n# Data Triggers\ndataFitSeq GsfElectronToTrigger passingHLTEle17Ele12Leg1\ndataFitSeq GsfElectronToTrigger passingHLTEle17Ele12Leg1L1Match\ndataFitSeq GsfElectronToTrigger passingHLTEle17Ele12Leg2\n\n# DZ Filter\ngetTemplatesFromMC.py -i TnPTreeDZ_mc.root -o mcTemplates-passingDZ.root --idprobe=passingHLTDZFilter \\\n -d GsfElectronToTrigger --var2Name=probe_Ele_pt --var1Name=probe_Ele_abseta --var2Bins=10,20,30,40,50,100,1000 --var1Bins=0,1.5,2.5 --weightVarName=totWeight\ncmsRun fitter.py isMC=0 inputFileName=TnPTreeDZ_data.root idName=passingHLTDZFilter dirName=GsfElectronToTrigger mcTemplateFile=mcTemplates-passingDZ.root 2>&1 > /dev/null &\n\nwait\n\nhadd -f efficiency-mc.root efficiency-mc-*.root\nhadd -f efficiency-data.root efficiency-data-*.root\n\ndumpTagProbeTreeHTML.py --mc efficiency-mc.root --data efficiency-data.root -i GsfElectronToRECO -o ~/www/TagProbePlots/electrons\ndumpTagProbeLatex.py --mc efficiency-mc.root --data efficiency-data.root -i GsfElectronToRECO -o ~/www/TagProbePlots/electrons --count\n\ndumpTagProbeTreeHTML.py --mc efficiency-mc.root --data efficiency-data.root -i GsfElectronToTrigger -o ~/www/TagProbePlots/electronTrigger\ndumpTagProbeLatex.py --mc efficiency-mc.root --data efficiency-data.root -i GsfElectronToTrigger -o ~/www/TagProbePlots/electronTrigger --count\n" }, { "alpha_fraction": 0.7188575267791748, "alphanum_fraction": 0.724363386631012, "avg_line_length": 28.353534698486328, "blob_id": "83f0c7c9c3680463bc82a70238056f54582742a8", "content_id": "3fb0e6f23e1f975dedc8e0ce3ea18f4972dabcd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2906, "license_type": "no_license", "max_line_length": 89, "num_lines": 99, "path": "/plugins/stupidTightMuonProducer.cc", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "// Original Author: Nicholas Charles Smith\n// Created: Tue, 16 Jun 2015 08:49:00 GMT\n\n// system include files\n#include <memory>\n\n// user include files\n#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/Framework/interface/EDProducer.h\"\n\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n\n#include \"DataFormats/Common/interface/RefVector.h\"\n#include \"DataFormats/PatCandidates/interface/Muon.h\"\n#include \"DataFormats/VertexReco/interface/VertexFwd.h\"\n#include \"DataFormats/VertexReco/interface/Vertex.h\"\n\nclass stupidTightMuonProducer : public edm::EDProducer {\n public:\n explicit stupidTightMuonProducer(const edm::ParameterSet&);\n ~stupidTightMuonProducer();\n\n static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);\n\n private:\n virtual void beginJob() override;\n virtual void produce(edm::Event&, const edm::EventSetup&) override;\n virtual void endJob() override;\n\n edm::EDGetTokenT<pat::MuonCollection> srcTag_;\n edm::EDGetTokenT<reco::VertexCollection> vtxTag_;\n};\n\nstupidTightMuonProducer::stupidTightMuonProducer(const edm::ParameterSet& iConfig) :\n srcTag_(consumes<pat::MuonCollection>(iConfig.getParameter<edm::InputTag>(\"src\"))),\n vtxTag_(consumes<reco::VertexCollection>(iConfig.getParameter<edm::InputTag>(\"vtx\")))\n{\n produces<pat::MuonCollection>();\n\n}\n\n\nstupidTightMuonProducer::~stupidTightMuonProducer()\n{\n}\n\nvoid\nstupidTightMuonProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup)\n{\n using namespace edm;\n\n Handle<pat::MuonCollection> muons;\n iEvent.getByToken(srcTag_, muons);\n\n Handle<reco::VertexCollection> vtx;\n iEvent.getByToken(vtxTag_, vtx);\n const auto& pv = vtx->at(0);\n\n std::unique_ptr<pat::MuonCollection> tightMuons{new pat::MuonCollection};\n\n for ( size_t i=0; i<muons->size(); ++i ) {\n pat::Muon muon = muons->at(i);\n if ( muon.isTightMuon(pv) ) {\n muon.addUserInt(\"isTightMuon\", 1);\n } else {\n muon.addUserInt(\"isTightMuon\", 0);\n }\n // Some vertex info\n muon.addUserFloat(\"dxyToPV\", muon.muonBestTrack()->dxy(pv.position()));\n muon.addUserFloat(\"dzToPV\", muon.muonBestTrack()->dz(pv.position()));\n tightMuons->push_back(muon);\n }\n\n iEvent.put(std::move(tightMuons));\n}\n\nvoid \nstupidTightMuonProducer::beginJob()\n{\n}\n\nvoid \nstupidTightMuonProducer::endJob() {\n}\n\nvoid\nstupidTightMuonProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {\n //The following says we do not know what parameters are allowed so do no validation\n // Please change this to state exactly what you do use, even if it is no parameters\n edm::ParameterSetDescription desc;\n desc.setUnknown();\n descriptions.addDefault(desc);\n}\n\n//define this as a plug-in\nDEFINE_FWK_MODULE(stupidTightMuonProducer);\n" }, { "alpha_fraction": 0.6802388429641724, "alphanum_fraction": 0.686753511428833, "avg_line_length": 33.42990493774414, "blob_id": "d2df0ed7dcbf50718df6e6b8f96f805f196254cb", "content_id": "cbcbe784b27009c03af109c2150ec704a14c680e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3684, "license_type": "no_license", "max_line_length": 116, "num_lines": 107, "path": "/plugins/TriggerObjectDump.cc", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "// Original Author: Nicholas Charles Smith\n// Created: Tue, 16 Jun 2015 08:49:00 GMT\n\n// system include files\n#include <memory>\n\n// user include files\n#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/Framework/interface/EDFilter.h\"\n\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n\n#include \"FWCore/Common/interface/TriggerNames.h\"\n#include \"DataFormats/Common/interface/TriggerResults.h\"\n#include \"DataFormats/PatCandidates/interface/TriggerObjectStandAlone.h\"\n#include \"DataFormats/PatCandidates/interface/PackedTriggerPrescales.h\"\n#include \"DataFormats/PatCandidates/interface/Muon.h\"\n\nclass TriggerObjectDump : public edm::EDFilter {\n public:\n explicit TriggerObjectDump(const edm::ParameterSet&);\n ~TriggerObjectDump();\n\n static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);\n\n private:\n virtual void beginJob();\n virtual bool filter(edm::Event&, const edm::EventSetup&);\n virtual void endJob();\n\n edm::EDGetTokenT<edm::View<reco::Candidate>> candidates_;\n};\n\nTriggerObjectDump::TriggerObjectDump(const edm::ParameterSet& iConfig) :\n candidates_(consumes<edm::View<reco::Candidate>>(iConfig.getParameter<edm::InputTag>(\"candidates\")))\n{\n\n}\n\n\nTriggerObjectDump::~TriggerObjectDump()\n{\n}\n\nbool\nTriggerObjectDump::filter(edm::Event& iEvent, const edm::EventSetup& iSetup)\n{\n edm::Handle<edm::View<reco::Candidate>> candidateCollection;\n\n iEvent.getByToken(candidates_, candidateCollection);\n\n if ( candidateCollection->size() == 0 ) return false;\n\n edm::LogVerbatim(\"triggers\") << \"New event\" << std::endl;\n edm::LogVerbatim(\"triggers\") << \"==============================\" << std::endl;\n\n for ( auto& candidate : *candidateCollection ) {\n edm::LogVerbatim(\"triggers\") << \"New candidate mass = \" << candidate.mass() << std::endl;\n\n auto tagCand = dynamic_cast<const reco::CompositeCandidate*>(&candidate)->daughter(0);\n auto tagMuon = tagCand->masterClone().castTo<pat::MuonRef>();\n auto tagTriggerObject = tagMuon->triggerObjectMatchByPath(\"HLT_IsoMu20_eta2p1_v*\");\n\n auto probeCand = dynamic_cast<const reco::CompositeCandidate*>(&candidate)->daughter(1);\n auto probeMuon = probeCand->masterClone().castTo<pat::MuonRef>();\n\n for ( auto object : probeMuon->triggerObjectMatches() ) {\n edm::LogVerbatim(\"triggers\") << \" Probe muon trigger match dR = \" << reco::deltaR(object, *probeMuon) << \n \", dR to tag trigger object = \" << reco::deltaR(object, *tagTriggerObject) << std::endl;\n if ( object.p4() == tagTriggerObject->p4() ) {\n edm::LogError(\"triggers\") << \" \\e[31mREUSED TAG TRIGGER OBJECT FOR PROBE!!!\\e[0m\" << std::endl;\n return false;\n }\n for( auto name : object.pathNames() )\n edm::LogVerbatim(\"triggers\") << \" Path name: \" << name << std::endl;\n for( auto name : object.filterLabels() )\n edm::LogVerbatim(\"triggers\") << \" Filter label: \" << name << std::endl;\n }\n }\n\n edm::LogVerbatim(\"triggers\") << std::endl;\n return true;\n}\n\nvoid \nTriggerObjectDump::beginJob()\n{\n}\n\nvoid \nTriggerObjectDump::endJob() {\n}\n\nvoid\nTriggerObjectDump::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {\n //The following says we do not know what parameters are allowed so do no validation\n // Please change this to state exactly what you do use, even if it is no parameters\n edm::ParameterSetDescription desc;\n desc.setUnknown();\n descriptions.addDefault(desc);\n}\n\n//define this as a plug-in\nDEFINE_FWK_MODULE(TriggerObjectDump);\n" }, { "alpha_fraction": 0.6817656755447388, "alphanum_fraction": 0.6988675594329834, "avg_line_length": 37.98198318481445, "blob_id": "b469ca7e78b523f0aabfdcfeabd4f1e82e65597c", "content_id": "a4a4d27a0351b8ec1058e5e94c425bb05f8581be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4327, "license_type": "no_license", "max_line_length": 114, "num_lines": 111, "path": "/python/ZZIDIsoEmbedding_cff.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import FWCore.ParameterSet.Config as cms\n\n# Make FSR photon collection, give them isolation and cut on it\n# might be able to just use packedPFCands selected for pdgID and use\n# standard isolation; I haven't checked\nfrom FinalStateAnalysis.PatTools.miniAOD_fsrPhotons_cff import *\n\ndretPhotonSelection = cms.EDFilter(\n \"CandPtrSelector\",\n src = cms.InputTag('boostedFsrPhotons'),\n cut = cms.string('pt > 2 && abs(eta) < 2.4 && '\n '((userFloat(\"fsrPhotonPFIsoChHadPUNoPU03pt02\") + '\n 'userFloat(\"fsrPhotonPFIsoNHadPhoton03\")) / pt < 1.8)'),\n )\nmakeFSRPhotons = cms.Sequence(fsrPhotonSequence *\n dretPhotonSelection)\n\n# ZZ Loose ID decision will be embedded as userFloat(\"HZZIDPass\"),\n# tight ID as userFloat(\"HZZIDPassTight\")\nzzIDLabel = 'HZZIDPass'\n\n# Embed HZZ ID decisions because we need to know them for FSR recovery\nelectronZZIDEmbedding = cms.EDProducer(\n \"MiniAODElectronHZZIDDecider\",\n src = cms.InputTag(\"slimmedElectrons\"),\n idLabel = cms.string(zzIDLabel), # boolean stored as userFloat with this name\n vtxSrc = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n bdtLabel = cms.string(\"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Values\"),\n idCutLowPtLowEta = cms.double(-.265),\n idCutLowPtMedEta = cms.double(-.556),\n idCutLowPtHighEta = cms.double(-.551),\n idCutHighPtLowEta = cms.double(-.072),\n idCutHighPtMedEta = cms.double(-.286),\n idCutHighPtHighEta = cms.double(-.267),\n missingHitsCut = cms.int32(999),\n ptCut = cms.double(7.), \n )\nmuonZZIDEmbedding = cms.EDProducer(\n \"MiniAODMuonHZZIDDecider\",\n src = cms.InputTag(\"slimmedMuons\"),\n idLabel = cms.string(zzIDLabel), # boolean will be stored as userFloat with this name\n vtxSrc = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n # Defaults are correct as of 6 January 2016, overwrite later if needed\n ptCut = cms.double(5.), \n )\n\nzzIDDecisions = cms.Sequence(\n electronZZIDEmbedding +\n muonZZIDEmbedding\n )\n\n# FSR will be embedded as userCand(\"fsrCand\") if any is found\nfsrLabel = \"fsrCand\"\n\n# Embed fsr as userCands\nleptonDRETFSREmbedding = cms.EDProducer(\n \"MiniAODLeptonDRETFSREmbedder\",\n muSrc = cms.InputTag(\"muonZZIDEmbedding\"),\n eSrc = cms.InputTag(\"electronZZIDEmbedding\"),\n phoSrc = cms.InputTag(\"dretPhotonSelection\"),\n phoSelection = cms.string(\"\"),\n eSelection = cms.string('userFloat(\"%s\") > 0.5'%zzIDLabel),\n muSelection = cms.string('userFloat(\"%s\") > 0.5'%zzIDLabel),\n fsrLabel = cms.string(fsrLabel),\n etPower = cms.double(2.),\n maxDR = cms.double(0.5),\n )\n\neaFile = 'RecoEgamma/ElectronIdentification/data/Spring15/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_25ns.txt'\neffectiveAreaEmbedding = cms.EDProducer(\n \"MiniAODElectronEffectiveAreaEmbedder\",\n src = cms.InputTag(\"leptonDRETFSREmbedding\"),\n label = cms.string(\"EffectiveArea\"), # embeds a user float with this name\n configFile = cms.FileInPath(eaFile), # the effective areas file\n )\n\n# isolation decisions embedded as userFloat(\"HZZIsoPass\")\nzzIsoLabel = \"HZZIsoPass\"\n# actual rel iso value embedded as userFloat(\"HZZIsoVal\")\nzzIsoValueLabel = zzIsoLabel.replace(\"Pass\", \"Val\")\n\n# embed isolation decisions\nleptonZZIsoEmbedding = cms.EDProducer(\n \"MiniAODLeptonHZZIsoDecider\",\n srcE = cms.InputTag(\"effectiveAreaEmbedding\"),\n srcMu = cms.InputTag(\"leptonDRETFSREmbedding\"),\n isoDecisionLabel = cms.string(zzIsoLabel),\n isoValueLabel = cms.string(zzIsoValueLabel),\n fsrLabel = cms.string(fsrLabel),\n fsrElecSelection = cms.string('userFloat(\"%s\") > 0.5'%zzIDLabel),\n fsrMuonSelection = cms.string('userFloat(\"%s\") > 0.5'%zzIDLabel),\n eaLabel = cms.string('EffectiveArea'),\n isoConeDRMaxE = cms.double(0.3),\n isoConeDRMaxMu = cms.double(0.3),\n isoCutE = cms.double(0.35),\n isoCutMu = cms.double(0.35),\n )\n\nzzIsoDecisions = cms.Sequence(\n effectiveAreaEmbedding\n + leptonZZIsoEmbedding\n )\n\n# electrons and muons in event as 'leptonZZIsoEmbedding:electrons' \n# and 'leptonZZIsoEmbedding:muons'\n\nzzEmbedding = cms.Sequence(makeFSRPhotons\n + zzIDDecisions\n + leptonDRETFSREmbedding\n + zzIsoDecisions\n )\n" }, { "alpha_fraction": 0.6888889074325562, "alphanum_fraction": 0.7602339386940002, "avg_line_length": 44, "blob_id": "ce9a7b5f44dc4a1a6be25540a80dbbbb7c790be5", "content_id": "4576ae8467b39a261bc32148b8422f4382f57ded", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1710, "license_type": "no_license", "max_line_length": 168, "num_lines": 38, "path": "/muons/submit.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\n\nsubmit() {\n jobName=$1\n shift\n pythonFile=$1\n shift\n dataset=$1\n shift\n cachefile=$1\n shift\n flags=$@\n\n if [ ! -f $cachefile ]\n then\n das_client.py --query=\"file dataset=${dataset}\" --format plain --limit 0 > $cachefile\n fi\n\n farmoutAnalysisJobs $jobName \\\n --infer-cmssw-path \\\n --input-file-list=${cachefile} \\\n --input-dir=root://cmsxrootd.hep.wisc.edu/ \\\n --assume-input-files-exist \\\n --input-files-per-job=10 \\\n ${pythonFile} \\\n 'inputFiles=$inputFileNames' 'outputFile=$outputFileName' ${flags}\n}\n\nsubmit muonTP makeTree.py /DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1/MINIAODSIM DYJetsMC.txt isMC=1\nsubmit muonTPLO makeTree.py /DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1/MINIAODSIM DYJetsMC_LO.txt isMC=1\nsubmit muonTPData makeTree.py /SingleMuon/Run2015D-05Oct2015-v1/MINIAOD SingleMuon.txt isMC=0\nsubmit muonTPDataPrompt makeTree.py /SingleMuon/Run2015D-PromptReco-v4/MINIAOD SingleMuonPrompt.txt isMC=0\nsubmit muonTPDataC makeTree.py /SingleMuon/Run2015C_25ns-05Oct2015-v1/MINIAOD SingleMuonC.txt isMC=0\n\nsubmit muonTPMC makeDZTree.py /DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v3/MINIAODSIM DYJetsMC.txt isMC=1\nsubmit muonTPData makeDZTree.py /DoubleMuon/Run2015D-05Oct2015-v1/MINIAOD DoubleMuon.txt isMC=0\nsubmit muonTPDataPrompt makeDZTree.py /DoubleMuon/Run2015D-PromptReco-v4/MINIAOD DoubleMuonPrompt.txt isMC=0\nsubmit muonTPDataC makeDZTree.py /DoubleMuon/Run2015C_25ns-05Oct2015-v1/MINIAOD DoubleMuonC.txt isMC=0\n" }, { "alpha_fraction": 0.701042890548706, "alphanum_fraction": 0.7230591177940369, "avg_line_length": 25.15151596069336, "blob_id": "42b1644ff66dcae9b548a3f43829eb23bae001fd", "content_id": "d6099b59a2a32a132e2ff5bfde1c44c9e6db0232", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "no_license", "max_line_length": 72, "num_lines": 33, "path": "/data/makePUhists.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import ROOT\n\n# DZ has more stuff\ndata = ROOT.TFile('../muons/TnPTreeDZ_data.root')\nmc = ROOT.TFile('../muons/TnPTreeDZ_mc.root')\n\ndatatree = data.Get('trackerMuonDZTree/fitter_tree')\nmctree = mc.Get('trackerMuonDZTree/fitter_tree')\n\ndatatree.Draw('event_nPV >> hdata(60, 0, 60)')\n#mctree.Draw('event_nPV >> hmc(60, 0, 60)', 'totWeight')\nmctree.Draw('event_nPV >> hmcunweight(60, 0, 60)', 'weight/abs(weight)')\n\nhdata = ROOT.gDirectory.Get('hdata')\nhmcunweight = ROOT.gDirectory.Get('hmcunweight')\n\nhdata.SetNormFactor(1.)\nhmcunweight.SetNormFactor(1.)\n\n#hdata.Draw('ex0hist')\n#hmcunweight.Draw('ex0histsame')\n\ndataFile = ROOT.TFile('puWeightData.root', 'recreate')\ndataFile.cd()\nhdata.SetName('pileup')\nhdata.Write()\ndataFile.Close()\n\nmcFile = ROOT.TFile('puWeightMC.root', 'recreate')\nmcFile.cd()\nhmcunweight.SetName('pileup')\nhmcunweight.Write()\nmcFile.Close()\n" }, { "alpha_fraction": 0.6482887268066406, "alphanum_fraction": 0.6714609265327454, "avg_line_length": 36.919193267822266, "blob_id": "df42ef8bff5707202b4bce7b8f675b4d03419a47", "content_id": "c80c2ecaed209bb00ed2218aee9393989e9402e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7509, "license_type": "no_license", "max_line_length": 160, "num_lines": 198, "path": "/phase2muons/makeTree.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import FWCore.ParameterSet.Config as cms\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\nprocess = cms.Process(\"TNP\")\noptions = VarParsing('analysis')\noptions.register(\n \"debug\",\n False,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"EDM File output\"\n )\noptions.parseArguments()\n\ninputFiles = [\n '/store/relval/CMSSW_8_1_0_pre9/RelValZMM_13/GEN-SIM-RECO/81X_mcRun2_asymptotic_v2_2023GReco-v1/10000/9041DC3E-5954-E611-8DB7-0025905B8566.root',\n]\n\nif len(options.inputFiles) is 0:\n options.inputFiles = inputFiles\n\nif len(options.outputFile) is 0:\n options.outputFile = 'TnPTree.root'\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(options.inputFiles),\n )\n\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents) )\n\nprocess.tracksSelection = cms.EDFilter(\"TrackRefSelector\",\n src = cms.InputTag(\"generalTracks\"),\n cut = cms.string(\"pt>10\"),\n filter = cms.bool(True),\n)\n\nprocess.makeMuonsFromTracks = cms.EDProducer(\"OneStopMuonShop\",\n tracks = cms.InputTag(\"tracksSelection\"),\n recoMuons = cms.InputTag(\"muons\"),\n patMuons = cms.InputTag(\"slimmedMuons\"),\n vertices = cms.InputTag(\"offlinePrimaryVertices\")\n)\n\nisolationDef = \"(pfIsolationR04().sumChargedHadronPt+max(pfIsolationR04().sumPhotonEt+pfIsolationR04().sumNeutralHadronEt-0.5*pfIsolationR04().sumPUPt,0.0))/pt\"\nprocess.tagMuons = cms.EDFilter(\"PATMuonRefSelector\",\n src = cms.InputTag(\"makeMuonsFromTracks\"),\n cut = cms.string(\"userInt('isTightMuon')==1 && pt > 25 && abs(eta) < 2.1 && \"+isolationDef+\" < 0.2\"),\n filter = cms.bool(True),\n)\n\nprocess.probeMuons = cms.EDFilter(\"PATMuonRefSelector\",\n src = cms.InputTag(\"makeMuonsFromTracks\"),\n cut = cms.string(\"pt>10\"), \n filter = cms.bool(True),\n)\n\nprocess.tpPairs = cms.EDProducer(\"CandViewShallowCloneCombiner\",\n decay = cms.string(\"tagMuons@+ probeMuons@-\"), # charge coniugate states are implied\n cut = cms.string(\"60 < mass < 120\")\n)\n\nprocess.tpPairsMCEmbedded = cms.EDProducer(\"pairMCInfoEmbedder\",\n input = cms.InputTag(\"tpPairs\"),\n leg1Matches = cms.InputTag(\"tagMatch\"),\n leg2Matches = cms.InputTag(\"probeMatch\")\n)\n\nprocess.tagMatch = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n pdgId = cms.vint32(13),\n src = cms.InputTag(\"tagMuons\"),\n distMin = cms.double(0.3),\n matched = cms.InputTag(\"genParticles\"),\n checkCharge = cms.bool(True)\n)\n\nprocess.probeMatch = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n pdgId = cms.vint32(13),\n src = cms.InputTag(\"probeMuons\"),\n distMin = cms.double(0.3),\n matched = cms.InputTag(\"genParticles\"),\n checkCharge = cms.bool(True)\n)\n\n#process.pileupReweightingProducer = cms.EDProducer(\"PileupWeightProducer\",\n# hardcodedWeights = cms.untracked.bool(False),\n# PileupMCFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightMC.root'),\n# PileupDataFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightData.root'),\n# )\n\nZVariablesToStore = cms.PSet(\n eta = cms.string(\"eta\"),\n abseta = cms.string(\"abs(eta)\"),\n pt = cms.string(\"pt\"),\n mass = cms.string(\"mass\"),\n ) \n\nProbeVariablesToStore = cms.PSet(\n probe_eta = cms.string(\"eta\"),\n probe_abseta = cms.string(\"abs(eta)\"),\n probe_pt = cms.string(\"pt\"),\n probe_et = cms.string(\"et\"),\n probe_e = cms.string(\"energy\"),\n probe_q = cms.string(\"charge\"),\n probe_chargedHadronIsoR04 = cms.string(\"pfIsolationR04().sumChargedHadronPt\"),\n probe_neutralHadronIsoR04 = cms.string(\"pfIsolationR04().sumNeutralHadronEt\"),\n probe_photonIsoR04 = cms.string(\"pfIsolationR04().sumPhotonEt\"),\n probe_pileupIsoR04 = cms.string(\"pfIsolationR04().sumPUPt\"),\n )\n\nTagVariablesToStore = cms.PSet(\n tag_eta = cms.string(\"eta\"),\n tag_abseta = cms.string(\"abs(eta)\"),\n tag_pt = cms.string(\"pt\"),\n tag_et = cms.string(\"et\"),\n tag_e = cms.string(\"energy\"),\n tag_q = cms.string(\"charge\"),\n tag_chargedHadronIsoR04 = cms.string(\"pfIsolationR04().sumChargedHadronPt\"),\n tag_neutralHadronIsoR04 = cms.string(\"pfIsolationR04().sumNeutralHadronEt\"),\n tag_photonIsoR04 = cms.string(\"pfIsolationR04().sumPhotonEt\"),\n tag_pileupIsoR04 = cms.string(\"pfIsolationR04().sumPUPt\"),\n )\n\nCommonStuffForMuonProbe = cms.PSet(\n variables = cms.PSet(ProbeVariablesToStore),\n ignoreExceptions = cms.bool (False),\n addRunLumiInfo = cms.bool (True),\n\n addEventVariablesInfo = cms.bool(True),\n vertexCollection = cms.InputTag(\"offlinePrimaryVertices\"),\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n\n pairVariables = cms.PSet(ZVariablesToStore),\n pairFlags = cms.PSet(\n mass60to120 = cms.string(\"60 < mass < 120\")\n ),\n tagVariables = cms.PSet(TagVariablesToStore),\n tagFlags = cms.PSet(), \n )\n\nmcTruthCommonStuff = cms.PSet(\n isMC = cms.bool(True),\n eventWeight = cms.double(1.),\n tagMatches = cms.InputTag(\"tagMatch\"),\n probeMatches = cms.InputTag(\"probeMatch\"),\n motherPdgId = cms.vint32(22,23),\n #motherPdgId = cms.vint32(443), # JPsi\n #motherPdgId = cms.vint32(553), # Yupsilon\n makeMCUnbiasTree = cms.bool(False),\n checkMotherInUnbiasEff = cms.bool(False),\n mcVariables = cms.PSet(\n probe_eta = cms.string(\"eta\"),\n probe_abseta = cms.string(\"abs(eta)\"),\n probe_et = cms.string(\"et\"),\n probe_e = cms.string(\"energy\"),\n ),\n mcFlags = cms.PSet(\n probe_isPromptFinalState = cms.string(\"isPromptFinalState\")\n ), \n )\n\nprocess.muonEffs = cms.EDAnalyzer(\"TagProbeFitTreeProducer\",\n CommonStuffForMuonProbe, mcTruthCommonStuff,\n tagProbePairs = cms.InputTag(\"tpPairsMCEmbedded\"),\n arbitration = cms.string(\"Random2\"),\n flags = cms.PSet(\n passingIDWZLoose = cms.string(\"isMediumMuon && trackIso()/pt()<0.25 && abs(userFloat('dxyToPV')) < 0.02 && abs(userFloat('dzToPV')) < 0.1\"), \n passingIDWZLooseNoTrackIso = cms.string(\"isMediumMuon && abs(userFloat('dxyToPV')) < 0.02 && abs(userFloat('dzToPV')) < 0.1\"), \n passingTightID = cms.string(\"userInt('isTightMuon')==1\"), \n passingIsoWZLoose = cms.string(isolationDef+\" < 0.4\"),\n passingIsoWZTight = cms.string(isolationDef+\" < 0.12\"),\n ),\n allProbes = cms.InputTag(\"probeMuons\"),\n )\n\n# (if isMC)\nsetattr(process.muonEffs.pairVariables, 'mc_mass', cms.string(\"userFloat('mc_mass')\"))\nprocess.muonEffs.tagProbePairs = cms.InputTag(\"tpPairsMCEmbedded\")\n\nprocess.p = cms.Path(\n process.tracksSelection *\n (process.makeMuonsFromTracks + process.tagMuons + process.probeMuons) *\n (process.tpPairs + process.tagMatch + process.probeMatch + process.tpPairsMCEmbedded) *\n process.muonEffs\n )\n\nif options.debug:\n process.out = cms.OutputModule(\"PoolOutputModule\", \n fileName = cms.untracked.string('debug.root'),\n SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(\"p\")),\n outputCommands = cms.untracked.vstring(\"drop *\", \"keep *_*_*_TNP\"),\n )\n process.outpath = cms.EndPath(process.out)\n\nprocess.TFileService = cms.Service(\"TFileService\", fileName = cms.string(options.outputFile))\n\n" }, { "alpha_fraction": 0.7202876806259155, "alphanum_fraction": 0.7380772233009338, "avg_line_length": 29.022727966308594, "blob_id": "29d0809f58b71aefed58660c72cb2947e48e0dde", "content_id": "24f4056158b65df07b0f3e1b19b81096952d0b03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2642, "license_type": "no_license", "max_line_length": 147, "num_lines": 88, "path": "/plugins/L1MuonMatcher.cc", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n#include \"FWCore/Framework/interface/EDProducer.h\"\n\n#include \"DataFormats/L1Trigger/interface/L1MuonParticle.h\"\n#include \"DataFormats/L1Trigger/interface/L1MuonParticleFwd.h\"\n\n#include \"DataFormats/PatCandidates/interface/Muon.h\"\n\n#include <DataFormats/Math/interface/deltaR.h>\n\n#include \"FWCore/MessageLogger/interface/MessageLogger.h\"\n\n#include <string>\n#include <vector>\n\nclass L1MuonMatcher : public edm::EDProducer {\n public:\n L1MuonMatcher(const edm::ParameterSet&);\n ~L1MuonMatcher();\n\n bool l1OfflineMatching(const l1extra::L1MuonParticleCollection& triggerObjects, \n\t\t\t math::XYZTLorentzVector refP4, float dRmin, int& index);\n\n private:\n virtual void produce(edm::Event&, const edm::EventSetup&) override;\n \n edm::EDGetTokenT<pat::MuonRefVector> inputs_;\n edm::EDGetTokenT<l1extra::L1MuonParticleCollection> l1muonObjectsToken_;\n float minET_;\n float dRMatch_;\n};\n\nL1MuonMatcher::L1MuonMatcher(const edm::ParameterSet& iConfig ) :\n inputs_(consumes<pat::MuonRefVector>(iConfig.getParameter<edm::InputTag>(\"inputs\"))),\n l1muonObjectsToken_(consumes<l1extra::L1MuonParticleCollection>(iConfig.getParameter<edm::InputTag>(\"l1extraMuons\"))),\n minET_(iConfig.getParameter<double>(\"minET\")),\n dRMatch_(iConfig.getParameter<double>(\"dRmatch\")) {\n\n produces<pat::MuonRefVector>();\n}\n\nL1MuonMatcher::~L1MuonMatcher()\n{}\n\nvoid L1MuonMatcher::produce(edm::Event &iEvent, const edm::EventSetup &eventSetup) {\n\n edm::Handle<l1extra::L1MuonParticleCollection> l1muonsHandle;\n edm::Handle<pat::MuonRefVector> inputs;\n\n iEvent.getByToken(l1muonObjectsToken_, l1muonsHandle);\n iEvent.getByToken(inputs_, inputs);\n\n // Create the output collection\n std::auto_ptr<pat::MuonRefVector> outColRef(new pat::MuonRefVector);\n\n for (size_t i=0; i<inputs->size(); i++) {\n auto ref = (*inputs)[i];\n int index = -1;\n\n if (l1OfflineMatching(*l1muonsHandle, ref->p4(), dRMatch_, index)) {\n outColRef->push_back(ref);\n }\n }\n\n iEvent.put(outColRef);\n}\n\nbool L1MuonMatcher::l1OfflineMatching(const l1extra::L1MuonParticleCollection& l1Objects, math::XYZTLorentzVector refP4, float dRmin, int& index) {\n\n index = 0;\n for (l1extra::L1MuonParticleCollection::const_iterator it=l1Objects.begin(); it != l1Objects.end(); it++) {\n if (it->et() < minET_)\n continue;\n\n float dR = deltaR(refP4, it->p4());\n if (dR < dRmin)\n return true;\n\n index++;\n }\n\n return false;\n}\n\n#include \"FWCore/Framework/interface/MakerMacros.h\"\nDEFINE_FWK_MODULE(L1MuonMatcher);\n" }, { "alpha_fraction": 0.6313363909721375, "alphanum_fraction": 0.6605222821235657, "avg_line_length": 21.44827651977539, "blob_id": "a2b5b6d73991e5ab7b6f58408bc11123a8ee6f11", "content_id": "5a8266ce38735a4b1f7ddda460949c9566484c45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 651, "license_type": "no_license", "max_line_length": 97, "num_lines": 29, "path": "/muonJPsi/submit.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\n\nsubmit() {\n jobName=$1\n shift\n pythonFile=$1\n shift\n dataset=$1\n shift\n cachefile=$1\n shift\n flags=$@\n\n if [ ! -f $cachefile ]\n then\n das_client.py --query=\"file dataset=${dataset}\" --format plain --limit 0 > $cachefile\n fi\n\n farmoutAnalysisJobs $jobName \\\n --infer-cmssw-path \\\n --input-file-list=${cachefile} \\\n --input-dir=root://cmsxrootd.fnal.gov/ \\\n --assume-input-files-exist \\\n --input-files-per-job=10 \\\n ${pythonFile} \\\n 'inputFiles=$inputFileNames' 'outputFile=$outputFileName' ${flags}\n}\n\nsubmit muonJPsiTPData makeTree.py /SingleMuon/Run2015D-05Oct2015-v1/MINIAOD SingleMuon.txt isMC=0\n" }, { "alpha_fraction": 0.5339503884315491, "alphanum_fraction": 0.5676416158676147, "avg_line_length": 47.06049728393555, "blob_id": "06e66b133c4e035099c4370773e663f3f7d90945", "content_id": "61c024f2db964b2f7dabc5dea74c72bec1e1a3ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13505, "license_type": "no_license", "max_line_length": 219, "num_lines": 281, "path": "/electrons/makeDZTree.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import FWCore.ParameterSet.Config as cms\nfrom FWCore.ParameterSet.VarParsing import VarParsing\nimport sys\n\nprocess = cms.Process(\"tnp\")\n\noptions = VarParsing('analysis')\noptions.register(\n \"isMC\",\n True,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"Compute MC efficiencies\"\n )\n\noptions.parseArguments()\n\njsonFile = 'Cert_246908-258714_13TeV_PromptReco_Collisions15_25ns_JSON.txt'\n\n# file dataset=/DoubleEG/Run2015D-05Oct2015-v1/MINIAOD\n# https://cmsweb.cern.ch/das/request?view=plain&limit=50&instance=prod%2Fglobal&input=file+dataset%3D%2FDoubleEG%2FRun2015D-05Oct2015-v1%2FMINIAOD\ninputFilesData = [\n '/store/data/Run2015D/DoubleEG/MINIAOD/05Oct2015-v1/50000/0014E86F-656F-E511-9D3F-002618943831.root',\n '/store/data/Run2015D/DoubleEG/MINIAOD/05Oct2015-v1/50000/008CB82F-5D6F-E511-8510-0025905A6090.root',\n '/store/data/Run2015D/DoubleEG/MINIAOD/05Oct2015-v1/50000/00916A9B-586F-E511-A8F3-002618943800.root',\n]\n\n# file dataset=/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v3/MINIAODSIM\n# https://cmsweb.cern.ch/das/request?view=plain&limit=50&instance=prod%2Fglobal&input=file+dataset%3D%2FDYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8%2FRunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v3%2FMINIAODSIM\ninputFilesMC = [\n '/store/mc/RunIISpring15DR74/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/Asympt25ns_MCRUN2_74_V9-v3/10000/009D49A5-7314-E511-84EF-0025905A605E.root',\n '/store/mc/RunIISpring15DR74/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/Asympt25ns_MCRUN2_74_V9-v3/10000/00C0BECF-6F14-E511-96F8-0025904B739A.root',\n '/store/mc/RunIISpring15DR74/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/Asympt25ns_MCRUN2_74_V9-v3/10000/0260F225-7614-E511-A79F-00A0D1EE8EB4.root',\n]\n\nif len(options.inputFiles) is 0 :\n if options.isMC :\n options.inputFiles = inputFilesMC\n else :\n options.inputFiles = inputFilesData\n\nif len(options.outputFile) is 0 :\n if options.isMC :\n options.outputFile = 'TnPTreeDZ_mc.root'\n else :\n options.outputFile = 'TnPTreeDZ_data.root'\n\nfrom HLTrigger.HLTfilters.hltHighLevel_cfi import hltHighLevel\nprocess.hltFilter = hltHighLevel.clone()\nprocess.hltFilter.throw = cms.bool(True)\nprocess.hltFilter.HLTPaths = cms.vstring('HLT_Ele17_Ele12_CaloIdL_TrackIdL_IsoVL_v*')\n\nprocess.goodElectrons = cms.EDFilter(\"PATElectronRefSelector\",\n src = cms.InputTag(\"slimmedElectrons\"),\n cut = cms.string(\"abs(eta)<2.5 && pt > 10\"),\n filter = cms.bool(True)\n )\n\nprocess.eleVarHelper = cms.EDProducer(\"ElectronVariableHelper\",\n probes = cms.InputTag(\"slimmedElectrons\"),\n vertexCollection = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n )\n\nprocess.goodElectronsTagEle17 = cms.EDProducer(\"PatElectronTriggerCandProducer\",\n filterNames = cms.vstring(\"hltEle17Ele12CaloIdLTrackIdLIsoVLTrackIsoLeg1Filter\"),\n inputs = cms.InputTag(\"goodElectrons\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.3),\n isAND = cms.bool(True)\n )\n\nprocess.goodElectronsProbeEle12 = cms.EDProducer(\"PatElectronTriggerCandProducer\",\n filterNames = cms.vstring(\"hltEle17Ele12CaloIdLTrackIdLIsoVLTrackIsoLeg2Filter\"),\n inputs = cms.InputTag(\"goodElectrons\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.3),\n isAND = cms.bool(True)\n )\n\nprocess.goodElectronsMeasureDZ = cms.EDProducer(\"PatElectronTriggerCandProducer\",\n filterNames = cms.vstring(\"hltEle17Ele12CaloIdLTrackIdLIsoVLDZFilter\"),\n inputs = cms.InputTag(\"goodElectronsProbeEle12\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.3),\n isAND = cms.bool(True)\n )\n\n###################################################################\n## TnP PAIRS\n###################################################################\n \nprocess.tagTightHLT = cms.EDProducer(\"CandViewShallowCloneCombiner\",\n decay = cms.string(\"goodElectronsTagEle17@+ goodElectronsProbeEle12@-\"), \n checkCharge = cms.bool(True),\n cut = cms.string(\"40<mass<1000\"),\n )\n\n##########################################################################\n## TREE CONTENT\n#########################################################################\n \nZVariablesToStore = cms.PSet(\n eta = cms.string(\"eta\"),\n abseta = cms.string(\"abs(eta)\"),\n pt = cms.string(\"pt\"),\n mass = cms.string(\"mass\"),\n ) \n\nProbeVariablesToStore = cms.PSet(\n probe_Ele_eta = cms.string(\"eta\"),\n probe_Ele_abseta = cms.string(\"abs(eta)\"),\n probe_Ele_pt = cms.string(\"pt\"),\n probe_Ele_et = cms.string(\"et\"),\n probe_Ele_e = cms.string(\"energy\"),\n probe_Ele_q = cms.string(\"charge\"),\n \n ## super cluster quantities\n probe_sc_energy = cms.string(\"superCluster.energy\"),\n probe_sc_et = cms.string(\"superCluster.energy*sin(superClusterPosition.theta)\"), \n probe_sc_eta = cms.string(\"superCluster.eta\"),\n probe_sc_abseta = cms.string(\"abs(superCluster.eta)\"),\n \n #id based\n probe_Ele_dEtaIn = cms.string(\"deltaEtaSuperClusterTrackAtVtx\"),\n probe_Ele_dPhiIn = cms.string(\"deltaPhiSuperClusterTrackAtVtx\"),\n probe_Ele_sigmaIEtaIEta = cms.string(\"sigmaIetaIeta\"),\n probe_Ele_hoe = cms.string(\"hadronicOverEm\"),\n probe_Ele_ooemoop = cms.string(\"(1.0/ecalEnergy - eSuperClusterOverP/ecalEnergy)\"),\n probe_Ele_mHits = cms.InputTag(\"eleVarHelper:missinghits\"),\n probe_Ele_dz = cms.InputTag(\"eleVarHelper:dz\"),\n probe_Ele_dxy = cms.InputTag(\"eleVarHelper:dxy\"),\n \n #isolation\n probe_Ele_chIso = cms.string(\"pfIsolationVariables().sumChargedHadronPt\"),\n probe_Ele_phoIso = cms.string(\"pfIsolationVariables().sumPhotonEt\"),\n probe_Ele_neuIso = cms.string(\"pfIsolationVariables().sumNeutralHadronEt\"),\n )\n\nTagVariablesToStore = cms.PSet(\n Ele_eta = cms.string(\"eta\"),\n Ele_abseta = cms.string(\"abs(eta)\"),\n Ele_pt = cms.string(\"pt\"),\n Ele_et = cms.string(\"et\"),\n Ele_e = cms.string(\"energy\"),\n Ele_q = cms.string(\"charge\"),\n \n ## super cluster quantities\n sc_energy = cms.string(\"superCluster.energy\"),\n sc_et = cms.string(\"superCluster.energy*sin(superClusterPosition.theta)\"), \n sc_eta = cms.string(\"superCluster.eta\"),\n sc_abseta = cms.string(\"abs(superCluster.eta)\"),\n )\n\nCommonStuffForGsfElectronProbe = cms.PSet(\n variables = cms.PSet(ProbeVariablesToStore),\n ignoreExceptions = cms.bool (False),\n addRunLumiInfo = cms.bool (True),\n addEventVariablesInfo = cms.bool(True),\n vertexCollection = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n #pfMet = cms.InputTag(\"\"),\n pairVariables = cms.PSet(ZVariablesToStore),\n pairFlags = cms.PSet(\n mass60to120 = cms.string(\"60 < mass < 120\")\n ),\n tagVariables = cms.PSet(TagVariablesToStore),\n tagFlags = cms.PSet(), \n )\n\nprocess.load(\"Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff\")\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')\nprocess.GlobalTag.globaltag = 'GR_P_V56'\n\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load(\"SimGeneral.HepPDTESSource.pythiapdt_cfi\")\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.MessageLogger.cerr.threshold = ''\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(options.inputFiles),\n )\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents))\n\nif not options.isMC :\n import FWCore.PythonUtilities.LumiList as LumiList\n process.source.lumisToProcess = LumiList.LumiList(filename = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/'+jsonFile).getVLuminosityBlockRange()\n\n##########################################################################\n## TREE MAKER OPTIONS\n##########################################################################\n\nmcTruthCommonStuff = cms.PSet(\n isMC = cms.bool(True),\n tagMatches = cms.InputTag(\"McMatchHLT\"),\n motherPdgId = cms.vint32(22,23),\n #motherPdgId = cms.vint32(443), # JPsi\n #motherPdgId = cms.vint32(553), # Yupsilon\n makeMCUnbiasTree = cms.bool(False),\n checkMotherInUnbiasEff = cms.bool(False),\n mcVariables = cms.PSet(\n probe_eta = cms.string(\"eta\"),\n probe_abseta = cms.string(\"abs(eta)\"),\n probe_et = cms.string(\"et\"),\n probe_e = cms.string(\"energy\"),\n ),\n mcFlags = cms.PSet(\n probe_flag = cms.string(\"pt>0\")\n ), \n )\n\nif (not options.isMC):\n mcTruthCommonStuff = cms.PSet(\n isMC = cms.bool(False)\n )\n\nprocess.GsfElectronToTrigger = cms.EDAnalyzer(\"TagProbeFitTreeProducer\",\n CommonStuffForGsfElectronProbe, mcTruthCommonStuff,\n tagProbePairs = cms.InputTag(\"tagTightHLT\"),\n arbitration = cms.string(\"BestMass\"),\n massForArbitration = cms.double(91.),\n flags = cms.PSet(\n passingHLTDZFilter = cms.InputTag(\"goodElectronsMeasureDZ\")\n ),\n allProbes = cms.InputTag(\"goodElectronsProbeEle12\"),\n )\n\n##########################################################################\n## MC stuff\n##########################################################################\n\nprocess.McMatchHLT = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n matchPDGId = cms.vint32(11),\n src = cms.InputTag(\"goodElectrons\"),\n distMin = cms.double(0.3),\n matched = cms.InputTag(\"prunedGenParticles\"),\n checkCharge = cms.bool(True)\n )\n\nprocess.pileupReweightingProducer = cms.EDProducer(\"PileupWeightProducer\",\n hardcodedWeights = cms.untracked.bool(False),\n PileupMCFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightMC.root'),\n PileupDataFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightData.root'),\n )\n\nprocess.mc_sequence = cms.Sequence()\nif (options.isMC):\n process.GsfElectronToTrigger.probeMatches = cms.InputTag(\"McMatchHLT\")\n process.GsfElectronToTrigger.eventWeight = cms.InputTag(\"generator\")\n process.GsfElectronToTrigger.PUWeightSrc = cms.InputTag(\"pileupReweightingProducer\",\"pileupWeights\")\n process.mc_sequence *= (process.McMatchHLT+process.pileupReweightingProducer)\n\nprocess.p = cms.Path(\n process.hltFilter +\n process.goodElectrons + \n process.goodElectronsTagEle17 +\n process.goodElectronsProbeEle12 +\n process.goodElectronsMeasureDZ +\n process.tagTightHLT +\n process.eleVarHelper +\n process.mc_sequence +\n process.GsfElectronToTrigger\n )\n\nprocess.TFileService = cms.Service(\n \"TFileService\", \n fileName = cms.string(options.outputFile),\n closeFileFast = cms.untracked.bool(True)\n)\n\nprocess.out = cms.OutputModule(\"PoolOutputModule\", \n fileName = cms.untracked.string('debug.root'),\n SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(\"p\"))\n )\n#process.outpath = cms.EndPath(process.out)\n" }, { "alpha_fraction": 0.6424319744110107, "alphanum_fraction": 0.6611394286155701, "avg_line_length": 33.57352828979492, "blob_id": "e3d246db851eafb448e218e7cfd945196516b503", "content_id": "95c75995c4a28af916759d9be2eaac47a425f528", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2352, "license_type": "no_license", "max_line_length": 105, "num_lines": 68, "path": "/phase2muons/plot.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nROOT.gROOT.SetBatch(True)\nROOT.PyConfig.IgnoreCommandLineOptions = True\nimport array\nimport sys\nimport subprocess\n__gitversion__ = subprocess.check_output([\"git\", \"describe\", \"--always\"]).strip()\n\n#idName = 'ZZLoose'\n#idNameNice = 'ZZ Loose ID'\nidName = sys.argv[1]\nidNameNice = sys.argv[2]\n\nptbins = [10.,30.,50., 80.]\netabins = [0.,1.2,2.4]\ncolors = [ROOT.kRed, ROOT.kGreen, ROOT.kBlue, ROOT.kBlack]\n\nROOT.gROOT.ProcessLine('.L plots/{id}/{id}.C+'.format(id=idName))\n\nvariations = [\n ROOT.EFF_FIT_UP,\n ROOT.EFF_FIT_DOWN,\n ]\n\nif 'Iso' in idName :\n eff = lambda pt, eta, var : getattr(ROOT, idName)(pt, eta, True, var)\nelse :\n eff = lambda pt, eta, var : getattr(ROOT, idName)(pt, eta, var)\n\neffCentral = lambda pt, eta : eff(pt, eta, ROOT.EFF_FIT)\neffMax = lambda pt, eta : max(map(lambda v : eff(pt,eta,v), variations))-effCentral(pt,eta)\neffMin = lambda pt, eta : effCentral(pt,eta)-min(map(lambda v : eff(pt,eta,v), variations))\n\n\nxbins = array.array('d', [0.5*sum(ptbins[i:i+2]) for i in range(len(ptbins)-1)])\nxlo = lambda bins: array.array('d', map(lambda (a,b): a-b, zip(bins, ptbins)))\nxhi = lambda bins: array.array('d', map(lambda (a,b): a-b, zip(ptbins[1:], bins)))\n\ndef y(eta) : return array.array('d', map(lambda pt : effCentral(pt, eta), xbins))\ndef eyl(eta) : return array.array('d', map(lambda pt : effMin(pt, eta), xbins))\ndef eyh(eta) : return array.array('d', map(lambda pt : effMax(pt, eta), xbins))\n\ncanvas = ROOT.TCanvas()\nmg = ROOT.TMultiGraph('alletaBins', ';Probe p_{T};Scale Factor')\n\nminEff = 1.\nfor i in range(len(etabins)-1) :\n eta = .5*sum(etabins[i:i+2])\n bins2 = array.array('d', [b-1.5+i for b in xbins])\n graph = ROOT.TGraphAsymmErrors(len(xbins), bins2, y(eta), xlo(bins2), xhi(bins2), eyl(eta), eyh(eta))\n minEff = min(minEff, min(y(eta)))\n graph.SetName('eff_etaBin%d'%i)\n graph.SetTitle('%.1f #leq |#eta| #leq %.1f' % tuple(etabins[i:i+2]))\n graph.SetMarkerColor(colors[i])\n graph.SetLineColor(colors[i])\n mg.Add(graph, 'p')\n\nmg.SetMinimum(0.1*int(minEff*10))\nmg.SetMaximum(1.05)\nmg.Draw('a')\nleg = canvas.BuildLegend(.5,.2,.9,.4)\nfor entry in leg.GetListOfPrimitives() :\n entry.SetOption('lp')\nleg.SetHeader(idNameNice)\n\ncanvas.Print('plots/%s/scaleFactor_vs_pt.png'%idName)\ncanvas.Print('plots/%s/scaleFactor_vs_pt.root'%idName)\n\n" }, { "alpha_fraction": 0.5254837274551392, "alphanum_fraction": 0.5456444025039673, "avg_line_length": 54.24519348144531, "blob_id": "574a889fa651840e1f25d64f82e819ffd126bc5e", "content_id": "f940fa083eec0430accc1462096e02a4243d6d49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34473, "license_type": "no_license", "max_line_length": 182, "num_lines": 624, "path": "/electrons/makeTree.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import FWCore.ParameterSet.Config as cms\nfrom FWCore.ParameterSet.VarParsing import VarParsing\nimport sys\n\nprocess = cms.Process(\"tnp\")\n\noptions = dict()\nvarOptions = VarParsing('analysis')\nvarOptions.register(\n \"isMC\",\n True,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"Compute MC efficiencies\"\n )\n\nvarOptions.parseArguments()\n\noptions['HLTProcessName'] = \"HLT\"\noptions['ELECTRON_COLL'] = \"leptonZZIsoEmbedding:electrons\"\noptions['ELECTRON_CUTS'] = \"abs(eta)<2.5 && pt > 7\"\noptions['ELECTRON_TAG_CUTS'] = \"(abs(superCluster.eta)<=2.5) && !(1.4442<=abs(superCluster.eta)<=1.566) && pt >= 25.0\"\noptions['SUPERCLUSTER_COLL'] = \"reducedEgamma:reducedSuperClusters\"\noptions['SUPERCLUSTER_CUTS'] = \"abs(eta)<2.5 && !(1.4442< abs(eta) <1.566) && et>10.0\"\noptions['MAXEVENTS'] = cms.untracked.int32(-1) \noptions['useAOD'] = cms.bool(False)\noptions['DOTRIGGER'] = cms.bool(False)\noptions['DORECO'] = cms.bool(False)\noptions['DOID'] = cms.bool(True)\noptions['OUTPUTEDMFILENAME'] = 'edmFile.root'\noptions['DEBUG'] = cms.bool(False)\noptions['json'] = 'Cert_246908-260627_13TeV_PromptReco_Collisions15_25ns_JSON_v2.txt'\n\n# file dataset=/SingleElectron/Run2015D-05Oct2015-v1/MINIAOD\n# https://cmsweb.cern.ch/das/request?view=plain&limit=50&instance=prod%2Fglobal&input=file+dataset%3D%2FSingleElectron%2FRun2015D-05Oct2015-v1%2FMINIAOD\ninputFilesData = [\n '/store/data/Run2015D/SingleElectron/MINIAOD/05Oct2015-v1/10000/00991D45-4E6F-E511-932C-0025905A48F2.root',\n '/store/data/Run2015D/SingleElectron/MINIAOD/05Oct2015-v1/10000/020243DA-326F-E511-8953-0026189438B1.root',\n '/store/data/Run2015D/SingleElectron/MINIAOD/05Oct2015-v1/10000/02D29CFD-2B6F-E511-AD72-00261894385A.root',\n]\n\n# file dataset=/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1/MINIAODSIM\ninputFilesMC = [\n '/store/mc/RunIISpring15MiniAODv2/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v1/50000/00759690-D16E-E511-B29E-00261894382D.root',\n '/store/mc/RunIISpring15MiniAODv2/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v1/50000/00E88378-6F6F-E511-9D54-001E6757EAA4.root',\n '/store/mc/RunIISpring15MiniAODv2/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v1/50000/02CD8A95-736F-E511-B76E-00266CFFBF34.root',\n]\n\nif len(varOptions.inputFiles) is 0 :\n if varOptions.isMC :\n varOptions.inputFiles = inputFilesMC\n else :\n varOptions.inputFiles = inputFilesData\n\nif len(varOptions.outputFile) is 0 :\n if varOptions.isMC :\n varOptions.outputFile = 'TnPTree_mc.root'\n else :\n varOptions.outputFile = 'TnPTree_data.root'\n\nif (varOptions.isMC):\n options['TnPPATHS'] = cms.vstring(\"HLT_Ele22_eta2p1_WP75_Gsf_v*\")\n options['TnPHLTTagFilters'] = cms.vstring(\"hltSingleEle22WP75GsfTrackIsoFilter\")\n options['TnPHLTProbeFilters'] = cms.vstring()\n options['GLOBALTAG'] = 'MCRUN2_74_V9A'\n options['EVENTSToPROCESS'] = cms.untracked.VEventRange()\nelse:\n options['TnPPATHS'] = cms.vstring(\"HLT_Ele22_eta2p1_WPTight_Gsf_v*\")\n options['TnPHLTTagFilters'] = cms.vstring(\"hltSingleEle22WPTightGsfTrackIsoFilter\")\n options['TnPHLTProbeFilters'] = cms.vstring()\n options['GLOBALTAG'] = 'GR_P_V56'\n options['EVENTSToPROCESS'] = cms.untracked.VEventRange()\n\n###################################################################\n\nprocess.load('Analysis.DiBosonTP.ZZIDIsoEmbedding_cff')\n\nprocess.sampleInfo = cms.EDAnalyzer(\"tnp::SampleInfoTree\",\n vertexCollection = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n genInfo = cms.InputTag(\"generator\")\n )\n\nprocess.eleVarHelper = cms.EDProducer(\"ElectronVariableHelper\",\n probes = cms.InputTag(options['ELECTRON_COLL']),\n vertexCollection = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n )\n\nfrom HLTrigger.HLTfilters.hltHighLevel_cfi import hltHighLevel\nprocess.hltFilter = hltHighLevel.clone()\nprocess.hltFilter.throw = cms.bool(True)\nprocess.hltFilter.HLTPaths = options['TnPPATHS']\n\nprocess.pileupReweightingProducer = cms.EDProducer(\"PileupWeightProducer\",\n hardcodedWeights = cms.untracked.bool(False),\n PileupMCFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightMC.root'),\n PileupDataFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightData.root'),\n )\n\nprocess.GsfDRToNearestTauProbe = cms.EDProducer(\"DeltaRNearestGenPComputer\",\n probes = cms.InputTag(options['ELECTRON_COLL']),\n objects = cms.InputTag('prunedGenParticles'),\n objectSelection = cms.string(\"abs(pdgId)==15\"),\n )\n\nprocess.GsfDRToNearestTauSC = cms.EDProducer(\"DeltaRNearestGenPComputer\",\n probes = cms.InputTag(\"superClusterCands\"),\n objects = cms.InputTag('prunedGenParticles'),\n objectSelection = cms.string(\"abs(pdgId)==15\"),\n )\n\nprocess.GsfDRToNearestTauTag = cms.EDProducer(\"DeltaRNearestGenPComputer\",\n probes = cms.InputTag(options['ELECTRON_COLL']),\n objects = cms.InputTag('prunedGenParticles'),\n objectSelection = cms.string(\"abs(pdgId)==15\"),\n )\n\n################################################################### \n## ELECTRON MODULES \n################################################################### \n \nprocess.goodElectrons = cms.EDFilter(\"PATElectronRefSelector\",\n src = cms.InputTag(options['ELECTRON_COLL']),\n cut = cms.string(options['ELECTRON_CUTS']),\n filter = cms.bool(True)\n )\n\n################################################################### \n## SUPERCLUSTER MODULES \n################################################################### \n \nprocess.superClusterCands = cms.EDProducer(\"ConcreteEcalCandidateProducer\",\n src = cms.InputTag(options['SUPERCLUSTER_COLL']),\n particleType = cms.int32(11),\n )\n\nprocess.goodSuperClusters = cms.EDFilter(\"RecoEcalCandidateRefSelector\",\n src = cms.InputTag(\"superClusterCands\"),\n cut = cms.string(options['SUPERCLUSTER_CUTS']),\n filter = cms.bool(True)\n )\n\nprocess.GsfMatchedSuperClusterCands = cms.EDProducer(\"ElectronMatchedCandidateProducer\",\n src = cms.InputTag(\"superClusterCands\"),\n ReferenceElectronCollection = cms.untracked.InputTag(\"goodElectrons\"),\n cut = cms.string(options['SUPERCLUSTER_CUTS'])\n )\n\n###################################################################\n## TRIGGER MATCHING\n###################################################################\n\nprocess.goodElectronsTagHLT = cms.EDProducer(\"PatElectronTriggerCandProducer\",\n filterNames = cms.vstring(options['TnPHLTTagFilters']),\n inputs = cms.InputTag(\"goodElectronsTAGCutBasedTight\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.3),\n isAND = cms.bool(True)\n )\n\nprocess.goodElectronsProbeHLT = cms.EDProducer(\"PatElectronTriggerCandProducer\",\n filterNames = cms.vstring(options['TnPHLTProbeFilters']),\n inputs = cms.InputTag(\"goodElectrons\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.3),\n isAND = cms.bool(True)\n )\n\nprocess.goodElectronsProbeMeasureHLT = cms.EDProducer(\"PatElectronTriggerCandProducer\",\n filterNames = cms.vstring(options['TnPHLTProbeFilters']),\n inputs = cms.InputTag(\"goodElectrons\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.3),\n isAND = cms.bool(True)\n )\nprocess.goodElectronsMeasureHLT = cms.Sequence()\n\nprocess.goodElectronsMeasureHLTEle23 = cms.EDProducer(\"PatElectronTriggerCandProducer\",\n filterNames = cms.vstring(\"hltEle23CaloIdLTrackIdLIsoVLTrackIsoFilter\"),\n inputs = cms.InputTag(\"goodElectronsProbeMeasureHLT\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.3),\n isAND = cms.bool(False)\n )\nprocess.goodElectronsMeasureHLT += process.goodElectronsMeasureHLTEle23\n\nprocess.goodElectronsMeasureHLTEle17 = process.goodElectronsMeasureHLTEle23.clone()\nprocess.goodElectronsMeasureHLTEle17.filterNames = cms.vstring(\"hltEle17CaloIdLTrackIdLIsoVLTrackIsoFilter\")\nprocess.goodElectronsMeasureHLT += process.goodElectronsMeasureHLTEle17\n\nprocess.goodElectronsMeasureHLTEle12 = process.goodElectronsMeasureHLTEle23.clone()\nprocess.goodElectronsMeasureHLTEle12.filterNames = cms.vstring(\"hltEle12CaloIdLTrackIdLIsoVLTrackIsoFilter\")\nprocess.goodElectronsMeasureHLT += process.goodElectronsMeasureHLTEle12\n\nprocess.goodElectronsMeasureHLTEle17Ele12Leg1 = process.goodElectronsMeasureHLTEle23.clone()\nprocess.goodElectronsMeasureHLTEle17Ele12Leg1.filterNames = cms.vstring(\"hltEle17Ele12CaloIdLTrackIdLIsoVLTrackIsoLeg1Filter\")\nprocess.goodElectronsMeasureHLT += process.goodElectronsMeasureHLTEle17Ele12Leg1\n\nprocess.goodElectronsMeasureHLTEle17Ele12Leg1L1EG15 = cms.EDProducer(\"PatElectronL1CandProducer\",\n inputs = cms.InputTag(\"goodElectronsMeasureHLTEle17Ele12Leg1\"),\n isoObjects = cms.InputTag(\"l1extraParticles:Isolated\"),\n nonIsoObjects = cms.InputTag(\"l1extraParticles:NonIsolated\"),\n minET = cms.double(15.),\n dRmatch = cms.double(.5)\n )\nprocess.goodElectronsMeasureHLT += process.goodElectronsMeasureHLTEle17Ele12Leg1L1EG15\n\nprocess.goodElectronsMeasureHLTEle17Ele12Leg2 = process.goodElectronsMeasureHLTEle23.clone()\nprocess.goodElectronsMeasureHLTEle17Ele12Leg2.filterNames = cms.vstring(\"hltEle17Ele12CaloIdLTrackIdLIsoVLTrackIsoLeg2Filter\")\nprocess.goodElectronsMeasureHLT += process.goodElectronsMeasureHLTEle17Ele12Leg2\n\nprocess.goodElectronsMeasureHLTMu17Ele12ELeg = process.goodElectronsMeasureHLTEle23.clone()\nprocess.goodElectronsMeasureHLTMu17Ele12ELeg.filterNames = cms.vstring(\"hltMu17TrkIsoVVLEle12CaloIdLTrackIdLIsoVLElectronlegTrackIsoFilter\")\nprocess.goodElectronsMeasureHLT += process.goodElectronsMeasureHLTMu17Ele12ELeg\n\nprocess.goodSuperClustersHLT = cms.EDProducer(\"RecoEcalCandidateTriggerCandProducer\",\n filterNames = cms.vstring(options['TnPHLTProbeFilters']),\n inputs = cms.InputTag(\"goodSuperClusters\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.3),\n isAND = cms.bool(True)\n )\n\n###################################################################\n## MC MATCHES\n###################################################################\n \nprocess.McMatchHLT = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n matchPDGId = cms.vint32(11),\n src = cms.InputTag(\"goodElectrons\"),\n distMin = cms.double(0.3),\n matched = cms.InputTag(\"prunedGenParticles\"),\n checkCharge = cms.bool(True)\n )\n\nprocess.McMatchSC = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n matchPDGId = cms.vint32(11),\n src = cms.InputTag(\"goodSuperClusters\"),\n distMin = cms.double(0.3),\n matched = cms.InputTag(\"prunedGenParticles\"),\n checkCharge = cms.bool(False)\n )\n\nprocess.McMatchTag = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n matchPDGId = cms.vint32(11),\n src = cms.InputTag(\"goodElectronsTAGCutBasedTight\"),\n distMin = cms.double(0.2),\n matched = cms.InputTag(\"prunedGenParticles\"),\n checkCharge = cms.bool(True)\n )\n\nprocess.McMatchRECO = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n matchPDGId = cms.vint32(11),\n src = cms.InputTag(\"goodElectrons\"),\n distMin = cms.double(0.2),\n matched = cms.InputTag(\"prunedGenParticles\"),\n checkCharge = cms.bool(True)\n )\n \n###################################################################\n## TnP PAIRS\n###################################################################\n \nprocess.tagTightHLT = cms.EDProducer(\"CandViewShallowCloneCombiner\",\n decay = cms.string(\"goodElectronsTagHLT@+ goodElectronsProbeMeasureHLT@-\"), \n checkCharge = cms.bool(True),\n cut = cms.string(\"40<mass<1000\"),\n )\n\nprocess.tagTightSC = cms.EDProducer(\"CandViewShallowCloneCombiner\",\n decay = cms.string(\"goodElectronsTagHLT goodSuperClustersHLT\"), \n checkCharge = cms.bool(False),\n cut = cms.string(\"40<mass<1000\"),\n )\n\nprocess.tagTightRECO = cms.EDProducer(\"CandViewShallowCloneCombiner\",\n decay = cms.string(\"goodElectronsTagHLT@+ goodElectronsProbeHLT@-\"), \n checkCharge = cms.bool(True),\n cut = cms.string(\"40<mass<1000\"),\n )\n\n##########################################################################\n## TREE CONTENT\n#########################################################################\n \nZVariablesToStore = cms.PSet(\n eta = cms.string(\"eta\"),\n abseta = cms.string(\"abs(eta)\"),\n pt = cms.string(\"pt\"),\n mass = cms.string(\"mass\"),\n ) \n\nSCProbeVariablesToStore = cms.PSet(\n probe_sc_eta = cms.string(\"eta\"),\n probe_sc_abseta = cms.string(\"abs(eta)\"),\n probe_sc_pt = cms.string(\"pt\"),\n probe_sc_et = cms.string(\"et\"),\n probe_sc_e = cms.string(\"energy\"),\n )\n\nProbeVariablesToStore = cms.PSet(\n probe_Ele_eta = cms.string(\"eta\"),\n probe_Ele_abseta = cms.string(\"abs(eta)\"),\n probe_Ele_pt = cms.string(\"pt\"),\n probe_Ele_et = cms.string(\"et\"),\n probe_Ele_e = cms.string(\"energy\"),\n probe_Ele_q = cms.string(\"charge\"),\n \n ## super cluster quantities\n probe_sc_energy = cms.string(\"superCluster.energy\"),\n probe_sc_et = cms.string(\"superCluster.energy*sin(superClusterPosition.theta)\"), \n probe_sc_eta = cms.string(\"superCluster.eta\"),\n probe_sc_abseta = cms.string(\"abs(superCluster.eta)\"),\n \n #id based\n probe_Ele_dEtaIn = cms.string(\"deltaEtaSuperClusterTrackAtVtx\"),\n probe_Ele_dPhiIn = cms.string(\"deltaPhiSuperClusterTrackAtVtx\"),\n probe_Ele_sigmaIEtaIEta = cms.string(\"sigmaIetaIeta\"),\n probe_Ele_hoe = cms.string(\"hadronicOverEm\"),\n probe_Ele_ooemoop = cms.string(\"(1.0/ecalEnergy - eSuperClusterOverP/ecalEnergy)\"),\n probe_Ele_mHits = cms.InputTag(\"eleVarHelper:missinghits\"),\n probe_Ele_dz = cms.InputTag(\"eleVarHelper:dz\"),\n probe_Ele_dxy = cms.InputTag(\"eleVarHelper:dxy\"),\n probe_Ele_mva = cms.InputTag(\"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Values\"),\n \n #isolation\n probe_Ele_chIso = cms.string(\"pfIsolationVariables().sumChargedHadronPt\"),\n probe_Ele_phoIso = cms.string(\"pfIsolationVariables().sumPhotonEt\"),\n probe_Ele_neuIso = cms.string(\"pfIsolationVariables().sumNeutralHadronEt\"),\n )\n\nTagVariablesToStore = cms.PSet(\n Ele_eta = cms.string(\"eta\"),\n Ele_abseta = cms.string(\"abs(eta)\"),\n Ele_pt = cms.string(\"pt\"),\n Ele_et = cms.string(\"et\"),\n Ele_e = cms.string(\"energy\"),\n Ele_q = cms.string(\"charge\"),\n \n ## super cluster quantities\n sc_energy = cms.string(\"superCluster.energy\"),\n sc_et = cms.string(\"superCluster.energy*sin(superClusterPosition.theta)\"), \n sc_eta = cms.string(\"superCluster.eta\"),\n sc_abseta = cms.string(\"abs(superCluster.eta)\"),\n )\n\nCommonStuffForGsfElectronProbe = cms.PSet(\n variables = cms.PSet(ProbeVariablesToStore),\n ignoreExceptions = cms.bool (True),\n addRunLumiInfo = cms.bool (True),\n addEventVariablesInfo = cms.bool(True),\n vertexCollection = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n #pfMet = cms.InputTag(\"\"),\n pairVariables = cms.PSet(ZVariablesToStore),\n pairFlags = cms.PSet(\n mass60to120 = cms.string(\"60 < mass < 120\")\n ),\n tagVariables = cms.PSet(TagVariablesToStore),\n tagFlags = cms.PSet(), \n )\n\nCommonStuffForSuperClusterProbe = CommonStuffForGsfElectronProbe.clone()\nCommonStuffForSuperClusterProbe.variables = cms.PSet(SCProbeVariablesToStore)\n\nmcTruthCommonStuff = cms.PSet(\n isMC = cms.bool(True),\n tagMatches = cms.InputTag(\"McMatchTag\"),\n motherPdgId = cms.vint32(22,23),\n #motherPdgId = cms.vint32(443), # JPsi\n #motherPdgId = cms.vint32(553), # Yupsilon\n makeMCUnbiasTree = cms.bool(False),\n checkMotherInUnbiasEff = cms.bool(False),\n mcVariables = cms.PSet(\n probe_eta = cms.string(\"eta\"),\n probe_abseta = cms.string(\"abs(eta)\"),\n probe_et = cms.string(\"et\"),\n probe_e = cms.string(\"energy\"),\n ),\n mcFlags = cms.PSet(\n probe_flag = cms.string(\"pt>0\")\n ), \n )\n\nprocess.load(\"Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff\")\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')\nprocess.GlobalTag.globaltag = options['GLOBALTAG']\n\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load(\"SimGeneral.HepPDTESSource.pythiapdt_cfi\")\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(False) )\n\nprocess.MessageLogger.cerr.threshold = ''\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(varOptions.inputFiles),\n eventsToProcess = options['EVENTSToPROCESS']\n )\n\nprocess.maxEvents = cms.untracked.PSet( input = options['MAXEVENTS'])\n\nif not varOptions.isMC :\n import FWCore.PythonUtilities.LumiList as LumiList\n process.source.lumisToProcess = LumiList.LumiList(filename = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/'+options['json']).getVLuminosityBlockRange()\n\n###################################################################\n## ID\n###################################################################\n\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import *\ndataFormat = DataFormat.MiniAOD\nif (options['useAOD']):\n dataFormat = DataFormat.AOD\n \nswitchOnVIDElectronIdProducer(process, dataFormat)\n \n# define which IDs we want to produce\nmy_id_modules = ['RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Spring15_25ns_V1_cff']\n \nfor idmod in my_id_modules:\n setupAllVIDIdsInModule(process, idmod, setupVIDElectronSelection)\n\nprocess.goodElectronsPROBECutBasedVeto = cms.EDProducer(\"PatElectronSelectorByValueMap\",\n input = cms.InputTag(\"goodElectrons\"),\n cut = cms.string(options['ELECTRON_CUTS']),\n selection = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-veto\"),\n id_cut = cms.bool(True)\n )\n\nprocess.goodElectronsPROBECutBasedLoose = process.goodElectronsPROBECutBasedVeto.clone()\nprocess.goodElectronsPROBECutBasedLoose.selection = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-loose\")\nprocess.goodElectronsPROBECutBasedMedium = process.goodElectronsPROBECutBasedVeto.clone()\nprocess.goodElectronsPROBECutBasedMedium.selection = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-medium\")\nprocess.goodElectronsPROBECutBasedTight = process.goodElectronsPROBECutBasedVeto.clone()\nprocess.goodElectronsPROBECutBasedTight.selection = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-tight\")\n\nprocess.goodElectronsTAGCutBasedVeto = cms.EDProducer(\"PatElectronSelectorByValueMap\",\n input = cms.InputTag(\"goodElectrons\"),\n cut = cms.string(options['ELECTRON_TAG_CUTS']),\n selection = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-veto\"),\n id_cut = cms.bool(True)\n )\n\nprocess.goodElectronsTAGCutBasedLoose = process.goodElectronsTAGCutBasedVeto.clone()\nprocess.goodElectronsTAGCutBasedLoose.selection = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-loose\")\nprocess.goodElectronsTAGCutBasedMedium = process.goodElectronsTAGCutBasedVeto.clone()\nprocess.goodElectronsTAGCutBasedMedium.selection = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-medium\")\nprocess.goodElectronsTAGCutBasedTight = process.goodElectronsTAGCutBasedVeto.clone()\nprocess.goodElectronsTAGCutBasedTight.selection = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-tight\")\n\n###################################################################\n## SEQUENCES\n###################################################################\n\nprocess.egmGsfElectronIDs.physicsObjectSrc = cms.InputTag(options['ELECTRON_COLL'])\nprocess.ele_sequence = cms.Sequence(\n process.zzEmbedding +\n process.goodElectrons +\n process.egmGsfElectronIDSequence +\n process.goodElectronsPROBECutBasedVeto +\n process.goodElectronsPROBECutBasedLoose +\n process.goodElectronsPROBECutBasedMedium +\n process.goodElectronsPROBECutBasedTight +\n process.goodElectronsTAGCutBasedVeto +\n process.goodElectronsTAGCutBasedLoose +\n process.goodElectronsTAGCutBasedMedium +\n process.goodElectronsTAGCutBasedTight +\n process.goodElectronsTagHLT +\n process.goodElectronsProbeHLT +\n process.goodElectronsProbeMeasureHLT +\n process.goodElectronsMeasureHLT\n )\n\nprocess.sc_sequence = cms.Sequence(process.superClusterCands +\n process.goodSuperClusters +\n process.goodSuperClustersHLT +\n process.GsfMatchedSuperClusterCands\n )\n\n###################################################################\n## TnP PAIRS\n###################################################################\n\nprocess.allTagsAndProbes = cms.Sequence()\n\nif (options['DOTRIGGER']):\n process.allTagsAndProbes *= process.tagTightHLT\n\nif (options['DORECO']):\n process.allTagsAndProbes *= process.tagTightSC\n\nif (options['DOID']):\n process.allTagsAndProbes *= process.tagTightRECO\n\nprocess.mc_sequence = cms.Sequence()\n\nif (varOptions.isMC):\n process.mc_sequence *= (process.McMatchHLT + process.McMatchTag + process.McMatchRECO)\n\n##########################################################################\n## TREE MAKER OPTIONS\n##########################################################################\nif (not varOptions.isMC):\n mcTruthCommonStuff = cms.PSet(\n isMC = cms.bool(False)\n )\n\nprocess.GsfElectronToTrigger = cms.EDAnalyzer(\"TagProbeFitTreeProducer\",\n CommonStuffForGsfElectronProbe, mcTruthCommonStuff,\n tagProbePairs = cms.InputTag(\"tagTightHLT\"),\n arbitration = cms.string(\"Random2\"),\n flags = cms.PSet(\n ),\n allProbes = cms.InputTag(\"goodElectronsProbeMeasureHLT\"),\n )\n\nif (varOptions.isMC):\n process.GsfElectronToTrigger.probeMatches = cms.InputTag(\"McMatchHLT\")\n process.GsfElectronToTrigger.eventWeight = cms.InputTag(\"generator\")\n process.GsfElectronToTrigger.PUWeightSrc = cms.InputTag(\"pileupReweightingProducer\",\"pileupWeights\")\n process.GsfElectronToTrigger.variables.probe_dRTau = cms.InputTag(\"GsfDRToNearestTauSC\")\n process.GsfElectronToTrigger.tagVariables.Ele_dRTau = cms.InputTag(\"GsfDRToNearestTauTag\")\n\nprocess.GsfElectronToSC = cms.EDAnalyzer(\"TagProbeFitTreeProducer\",\n CommonStuffForSuperClusterProbe, mcTruthCommonStuff,\n tagProbePairs = cms.InputTag(\"tagTightSC\"),\n arbitration = cms.string(\"Random2\"),\n flags = cms.PSet(passingRECO = cms.InputTag(\"GsfMatchedSuperClusterCands\", \"superclusters\"), \n ), \n allProbes = cms.InputTag(\"goodSuperClustersHLT\"),\n )\n\nif (varOptions.isMC):\n process.GsfElectronToSC.probeMatches = cms.InputTag(\"McMatchSC\")\n process.GsfElectronToSC.eventWeight = cms.InputTag(\"generator\")\n process.GsfElectronToSC.PUWeightSrc = cms.InputTag(\"pileupReweightingProducer\",\"pileupWeights\")\n process.GsfElectronToSC.variables.probe_dRTau = cms.InputTag(\"GsfDRToNearestTauSC\")\n process.GsfElectronToSC.tagVariables.Ele_dRTau = cms.InputTag(\"GsfDRToNearestTauTag\")\n\nprocess.GsfElectronToRECO = cms.EDAnalyzer(\"TagProbeFitTreeProducer\",\n mcTruthCommonStuff, CommonStuffForGsfElectronProbe,\n tagProbePairs = cms.InputTag(\"tagTightRECO\"),\n arbitration = cms.string(\"Random2\"),\n flags = cms.PSet(passingVeto = cms.InputTag(\"goodElectronsPROBECutBasedVeto\"),\n passingLoose = cms.InputTag(\"goodElectronsPROBECutBasedLoose\"),\n passingMedium = cms.InputTag(\"goodElectronsPROBECutBasedMedium\"),\n passingTight = cms.InputTag(\"goodElectronsPROBECutBasedTight\"),\n passingZZLoose =cms.string(\"userFloat('HZZIDPass')\"), \n passingZZTight =cms.string(\"userFloat('HZZIDPassTight')\"), \n passingZZIso = cms.string(\"userFloat('HZZIsoPass')\"), \n passingHLTEle23 = cms.InputTag(\"goodElectronsMeasureHLTEle23\"),\n passingHLTEle17 = cms.InputTag(\"goodElectronsMeasureHLTEle17\"),\n passingHLTEle12 = cms.InputTag(\"goodElectronsMeasureHLTEle12\"),\n passingHLTEle17Ele12Leg1 = cms.InputTag(\"goodElectronsMeasureHLTEle17Ele12Leg1\"),\n passingHLTEle17Ele12Leg1L1Match = cms.InputTag(\"goodElectronsMeasureHLTEle17Ele12Leg1L1EG15\"),\n passingHLTEle17Ele12Leg2 = cms.InputTag(\"goodElectronsMeasureHLTEle17Ele12Leg2\"),\n passingHLTMu17Ele12ELeg = cms.InputTag(\"goodElectronsMeasureHLTMu17Ele12ELeg\"),\n ), \n allProbes = cms.InputTag(\"goodElectronsProbeHLT\"),\n )\n\nif (varOptions.isMC):\n process.GsfElectronToRECO.probeMatches = cms.InputTag(\"McMatchRECO\")\n process.GsfElectronToRECO.eventWeight = cms.InputTag(\"generator\")\n process.GsfElectronToRECO.PUWeightSrc = cms.InputTag(\"pileupReweightingProducer\",\"pileupWeights\")\n process.GsfElectronToRECO.variables.probe_dRTau = cms.InputTag(\"GsfDRToNearestTauProbe\")\n process.GsfElectronToRECO.tagVariables.Ele_dRTau = cms.InputTag(\"GsfDRToNearestTauTag\")\n\nprocess.tree_sequence = cms.Sequence()\nif (options['DOTRIGGER']):\n process.tree_sequence *= process.GsfElectronToTrigger\n\nif (options['DORECO']):\n process.tree_sequence *= process.GsfElectronToSC\n\nif (options['DOID']):\n process.tree_sequence *= process.GsfElectronToRECO\n\n##########################################################################\n## PATHS\n##########################################################################\n\nprocess.out = cms.OutputModule(\"PoolOutputModule\", \n fileName = cms.untracked.string(options['OUTPUTEDMFILENAME']),\n SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(\"p\"))\n )\nprocess.outpath = cms.EndPath(process.out)\nif (not options['DEBUG']):\n process.outpath.remove(process.out)\n\nif (varOptions.isMC):\n process.p = cms.Path(\n process.sampleInfo +\n process.hltFilter +\n process.ele_sequence + \n process.allTagsAndProbes +\n process.pileupReweightingProducer +\n process.mc_sequence +\n process.eleVarHelper +\n process.GsfDRToNearestTauProbe + \n process.GsfDRToNearestTauTag + \n process.tree_sequence\n )\nelse:\n process.p = cms.Path(\n process.sampleInfo +\n process.hltFilter +\n process.ele_sequence + \n process.allTagsAndProbes +\n process.mc_sequence +\n process.eleVarHelper +\n process.tree_sequence\n )\n\nprocess.TFileService = cms.Service(\n \"TFileService\", fileName = cms.string(varOptions.outputFile),\n closeFileFast = cms.untracked.bool(True)\n )\n" }, { "alpha_fraction": 0.7528906464576721, "alphanum_fraction": 0.773042619228363, "avg_line_length": 52.105262756347656, "blob_id": "87ffb3285d3cab0df5b3e998aabc727f7ad46e05", "content_id": "fc38b5abef4fc2a861a3fa1ddc9db2ddeaf39c51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3027, "license_type": "no_license", "max_line_length": 209, "num_lines": 57, "path": "/muonJPsi/runFits.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\ncmsenv\n\nif [[ $1 == 'doMC' ]]; then\n # MC ID/Iso\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIDZZLoose 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIDZZTight 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIsoZZ conditions=passingIDZZLoose outputFileName=passingIDZZLoose 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIsoZZ conditions=passingIDZZTight outputFileName=passingIDZZTight 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIDWZLoose 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIDWZTight 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIsoWZLoose conditions=passingIDWZLoose outputFileName=fromWZLoose 2>&1 > /dev/null\n cmsRun fitter.py isMC=1 doCutAndCount=1 inputFileName=TnPTree_mc.root idName=passingIsoWZTight conditions=passingIDWZTight outputFileName=fromWZTight 2>&1 > /dev/null\n\nfi\n\n# Make MC templates for data fit\ncommonTemplateFlags=\"-d muonEffs --var2Name=probe_pt --var1Name=probe_abseta --var2Bins=5,10,20,30 --var1Bins=0,1.5,2.5 --weightVarName=totWeight --massWindow=2.5,3.5\"\ndataFitSeq() {\n idName=$1\n shift\n conditions=$1\n\n if [[ $conditions ]]; then\n condFileSafe=$(echo ${conditions}|tr ',' '_')\n if [[ ! -f mcTemplates-${idName}-${condFileSafe}.root ]]; then\n getTemplatesFromMC.py ${commonTemplateFlags} -i TnPTree_mc.root -o mcTemplates-${idName}-${condFileSafe}.root --idprobe=${idName} --conditions=\"${conditions}\"\n fi\n cmsRun fitter.py isMC=0 inputFileName=TnPTree_data.root idName=${idName} conditions=${conditions} outputFileName=${condFileSafe} mcTemplateFile=mcTemplates-${idName}-${condFileSafe}.root 2>&1 > /dev/null &\n else\n if [[ ! -f mcTemplates-${idName}.root ]]; then\n getTemplatesFromMC.py ${commonTemplateFlags} -i TnPTree_mc.root -o mcTemplates-${idName}.root --idprobe=${idName}\n fi\n cmsRun fitter.py isMC=0 inputFileName=TnPTree_data.root idName=${idName} mcTemplateFile=mcTemplates-${idName}.root 2>&1 > /dev/null &\n fi\n}\n\n# rm -rf mcTemplates-*.root\n\n# Data ID/Iso\ndataFitSeq passingIDZZLoose\ndataFitSeq passingIDZZTight\ndataFitSeq passingIsoZZ passingIDZZLoose\ndataFitSeq passingIsoZZ passingIDZZTight\ndataFitSeq passingIDWZLoose\ndataFitSeq passingIDWZTight\ndataFitSeq passingIsoWZLoose passingIDWZLoose\ndataFitSeq passingIsoWZTight passingIDWZTight\n\nwait\n\nhadd -f efficiency-mc.root efficiency-mc-*.root\nhadd -f efficiency-data.root efficiency-data-*.root\n\nmkdir -p ~/www/TagProbePlots/muonJPsi\ndumpTagProbeTreeHTML.py --mc efficiency-mc.root --data efficiency-data.root -i muonEffs -o ~/www/TagProbePlots/muonJPsi\ndumpTagProbeLatex.py --mc efficiency-mc.root --data efficiency-data.root -i muonEffs -o ~/www/TagProbePlots/muonJPsi --count\n" }, { "alpha_fraction": 0.6347711682319641, "alphanum_fraction": 0.6837446093559265, "avg_line_length": 40.47265625, "blob_id": "2d13f7b1f735f60e58d01e3d7314c106e6c3fb4e", "content_id": "724b1352761bb937247dbc774b1b84fc5238a68f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10618, "license_type": "no_license", "max_line_length": 181, "num_lines": 256, "path": "/muonJPsi/makeTree.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import FWCore.ParameterSet.Config as cms\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\nprocess = cms.Process(\"tnp\")\noptions = VarParsing('analysis')\noptions.register(\n \"isMC\",\n True,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"Compute MC efficiencies\"\n )\noptions.parseArguments()\n\nisolationDef = \"(chargedHadronIso+max(photonIso+neutralHadronIso-0.5*puChargedHadronIso,0.0))/pt\"\nconfig = {}\nconfig['MUON_COLL'] = \"slimmedMuons\"\nconfig['MUON_CUTS'] = \"(isTrackerMuon || isGlobalMuon) && abs(eta)<2.5 && pt > 5\"\nconfig['MUON_TAG_CUTS'] = \"userInt('isTightMuon')==1 && pt > 22 && abs(eta) < 2.1 && \"+isolationDef+\" < 0.2\"\nconfig['MUON_TAG_TRIGGER'] = \"hltL3crIsoL1sMu16L1f0L2f10QL3f20QL3trkIsoFiltered0p09\"\nconfig['DEBUG'] = cms.bool(False)\nconfig['json'] = 'Cert_246908-260627_13TeV_PromptReco_Collisions15_25ns_JSON_v2.txt'\n\n# file dataset=/SingleMuon/Run2015D-05Oct2015-v1/MINIAOD\n# https://cmsweb.cern.ch/das/request?view=plain&limit=50&instance=prod%2Fglobal&input=file+dataset%3D%2FSingleMuon%2FRun2015D-05Oct2015-v1%2FMINIAOD\ninputFilesData = [\n '/store/data/Run2015D/SingleMuon/MINIAOD/05Oct2015-v1/30000/DAF6F553-986F-E511-AB07-002618943982.root',\n '/store/data/Run2015D/SingleMuon/MINIAOD/05Oct2015-v1/30000/DC242338-986F-E511-9196-00261894394B.root',\n '/store/data/Run2015D/SingleMuon/MINIAOD/05Oct2015-v1/30000/DC4D3D93-906F-E511-BEAD-0026189438F9.root',\n]\n\n# file dataset=/JPsiToMuMu_Pt20to100-pythia8-gun/RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v2/MINIAODSIM\ninputFilesMC = [\n '/store/mc/RunIISpring15MiniAODv2/JPsiToMuMu_Pt20to100-pythia8-gun/MINIAODSIM/74X_mcRun2_asymptotic_v2-v2/30000/085258CF-CA76-E511-AF11-00237DF20360.root',\n '/store/mc/RunIISpring15MiniAODv2/JPsiToMuMu_Pt20to100-pythia8-gun/MINIAODSIM/74X_mcRun2_asymptotic_v2-v2/30000/2C190717-CB76-E511-911C-00237DF25430.root',\n '/store/mc/RunIISpring15MiniAODv2/JPsiToMuMu_Pt20to100-pythia8-gun/MINIAODSIM/74X_mcRun2_asymptotic_v2-v2/30000/48EAA0D6-CA76-E511-82F0-00237DF25430.root',\n]\n\nif len(options.inputFiles) is 0 :\n if options.isMC :\n options.inputFiles = inputFilesMC\n else :\n options.inputFiles = inputFilesData\n\nif len(options.outputFile) is 0 :\n if options.isMC :\n options.outputFile = 'TnPTree_mc.root'\n else :\n options.outputFile = 'TnPTree_data.root'\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(options.inputFiles),\n )\n\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\nprocess.tightMuons = cms.EDProducer(\"stupidTightMuonProducer\",\n src = cms.InputTag(\"slimmedMuons\"),\n vtx = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n)\n\nprocess.tagMuons = cms.EDFilter(\"PATMuonRefSelector\",\n src = cms.InputTag(\"tightMuons\"),\n cut = cms.string(config['MUON_TAG_CUTS']),\n filter = cms.bool(True)\n)\n\nprocess.tagMuonsTriggerMatched = cms.EDProducer(\"PatMuonTriggerCandProducer\",\n filterNames = cms.vstring(config['MUON_TAG_TRIGGER']),\n inputs = cms.InputTag(\"tagMuons\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.4),\n isAND = cms.bool(True)\n )\n\nprocess.probeMuons = cms.EDFilter(\"PATMuonRefSelector\",\n src = cms.InputTag(\"tightMuons\"),\n cut = cms.string(config['MUON_CUTS']), \n)\n\n########### Probe Triggers ###############\n\nprocess.probeTriggerSeq = cms.Sequence()\n\nprocess.probeTriggersMu17Leg = cms.EDProducer(\"PatMuonTriggerCandProducer\",\n filterNames = cms.vstring(\"hltDiMuonGlb17Glb8RelTrkIsoFiltered0p4\", \"hltL3fL1sDoubleMu103p5L1f0L2f10OneMuL3Filtered17\"),\n inputs = cms.InputTag(\"probeMuons\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.5),\n isAND = cms.bool(True)\n )\nprocess.probeTriggerSeq += process.probeTriggersMu17Leg\n\nprocess.probeTriggersMu17LegL1Mu12 = cms.EDProducer(\"L1MuonMatcher\",\n inputs = cms.InputTag(\"probeTriggersMu17Leg\"),\n l1extraMuons = cms.InputTag(\"l1extraParticles\"),\n minET = cms.double(12.),\n dRmatch = cms.double(.5)\n )\nprocess.probeTriggerSeq += process.probeTriggersMu17LegL1Mu12\n\nprocess.probeTriggersMu8Leg = process.probeTriggersMu17Leg.clone()\nprocess.probeTriggersMu8Leg.filterNames = cms.vstring(\"hltDiMuonGlb17Glb8RelTrkIsoFiltered0p4\", \"hltL3pfL1sDoubleMu103p5L1f0L2pf0L3PreFiltered8\")\nprocess.probeTriggerSeq += process.probeTriggersMu8Leg\n\nprocess.probeTriggersTkMu8Leg = process.probeTriggersMu17Leg.clone()\nprocess.probeTriggersTkMu8Leg.filterNames = cms.vstring(\"hltDiMuonGlb17Trk8RelTrkIsoFiltered0p4\", \"hltDiMuonGlbFiltered17TrkFiltered8\")\nprocess.probeTriggerSeq += process.probeTriggersTkMu8Leg\n\nprocess.tpPairs = cms.EDProducer(\"CandViewShallowCloneCombiner\",\n decay = cms.string(\"tagMuonsTriggerMatched@+ probeMuons@-\"), # charge coniugate states are implied\n cut = cms.string(\"2.5 < mass < 3.5\")\n)\n\nprocess.muMcMatch = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n pdgId = cms.vint32(13),\n src = cms.InputTag(\"tightMuons\"),\n distMin = cms.double(0.3),\n matched = cms.InputTag(\"prunedGenParticles\"),\n checkCharge = cms.bool(True)\n)\n\nprocess.pileupReweightingProducer = cms.EDProducer(\"PileupWeightProducer\",\n hardcodedWeights = cms.untracked.bool(False),\n PileupMCFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightMC.root'),\n PileupDataFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightData.root'),\n )\n\nZVariablesToStore = cms.PSet(\n eta = cms.string(\"eta\"),\n abseta = cms.string(\"abs(eta)\"),\n pt = cms.string(\"pt\"),\n mass = cms.string(\"mass\"),\n deltaR = cms.string(\"deltaR(daughter(0).eta, daughter(0).phi, daughter(1).eta, daughter(1).phi)\"),\n ) \n\nProbeVariablesToStore = cms.PSet(\n probe_eta = cms.string(\"eta\"),\n probe_abseta = cms.string(\"abs(eta)\"),\n probe_pt = cms.string(\"pt\"),\n probe_et = cms.string(\"et\"),\n probe_e = cms.string(\"energy\"),\n probe_q = cms.string(\"charge\"),\n )\n\nTagVariablesToStore = cms.PSet(\n tag_eta = cms.string(\"eta\"),\n tag_abseta = cms.string(\"abs(eta)\"),\n tag_pt = cms.string(\"pt\"),\n tag_et = cms.string(\"et\"),\n tag_e = cms.string(\"energy\"),\n tag_q = cms.string(\"charge\"),\n )\n\nCommonStuffForMuonProbe = cms.PSet(\n variables = cms.PSet(ProbeVariablesToStore),\n ignoreExceptions = cms.bool (True),\n addRunLumiInfo = cms.bool (True),\n addEventVariablesInfo = cms.bool(True),\n vertexCollection = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n #pfMet = cms.InputTag(\"\"),\n pairVariables = cms.PSet(ZVariablesToStore),\n pairFlags = cms.PSet(\n mass60to120 = cms.string(\"60 < mass < 120\"),\n pt_lower_100 = cms.string(\"pt<100\"),\n ),\n tagVariables = cms.PSet(TagVariablesToStore),\n tagFlags = cms.PSet(), \n )\n\nmcTruthCommonStuff = cms.PSet(\n isMC = cms.bool(False),\n tagMatches = cms.InputTag(\"muMcMatch\"),\n probeMatches = cms.InputTag(\"muMcMatch\"),\n #motherPdgId = cms.vint32(22,23),\n motherPdgId = cms.vint32(443), # JPsi\n #motherPdgId = cms.vint32(553), # Yupsilon\n makeMCUnbiasTree = cms.bool(False),\n checkMotherInUnbiasEff = cms.bool(False),\n mcVariables = cms.PSet(\n probe_eta = cms.string(\"eta\"),\n probe_abseta = cms.string(\"abs(eta)\"),\n probe_et = cms.string(\"et\"),\n probe_e = cms.string(\"energy\"),\n ),\n mcFlags = cms.PSet(\n probe_flag = cms.string(\"pt>0\")\n ), \n )\n\nprocess.muonEffs = cms.EDAnalyzer(\"TagProbeFitTreeProducer\",\n CommonStuffForMuonProbe, mcTruthCommonStuff,\n tagProbePairs = cms.InputTag(\"tpPairs\"),\n arbitration = cms.string(\"Random2\"),\n flags = cms.PSet(\n passingIDZZLoose = cms.string(\n \"pt > 5. && abs(eta) < 2.4 && (isGlobalMuon || (isTrackerMuon && numberOfMatches > 0)) && muonBestTrackType != 2 \"\n \"&& abs(userFloat('dxyToPV')) < 0.5 && abs(userFloat('dzToPV')) < 1.\"\n ),\n passingIDZZTight = cms.string(\n \"pt > 5. && abs(eta) < 2.4 && (isGlobalMuon || (isTrackerMuon && numberOfMatches > 0)) && muonBestTrackType != 2 \"\n \"&& abs(userFloat('dxyToPV')) < 0.5 && abs(userFloat('dzToPV')) < 1. && isPFMuon\"\n ),\n passingIsoZZ = cms.string(isolationDef+\" < 0.4\"),\n\n passingIDWZLoose = cms.string(\"isLooseMuon\"), \n passingIDWZTight = cms.string(\"userInt('isTightMuon')==1\"), \n passingIsoWZLoose = cms.string(isolationDef+\" < 0.2\"),\n passingIsoWZTight = cms.string(isolationDef+\" < 0.12\"),\n\n passingMu17 = cms.InputTag(\"probeTriggersMu17Leg\"),\n passingMu17L1Match = cms.InputTag(\"probeTriggersMu17LegL1Mu12\"),\n passingMu8= cms.InputTag(\"probeTriggersMu8Leg\"),\n passingTkMu8 = cms.InputTag(\"probeTriggersTkMu8Leg\"),\n ),\n allProbes = cms.InputTag(\"probeMuons\"),\n )\n\nprocess.tpPairSeq = cms.Sequence(\n process.tpPairs\n)\n\nif options.isMC :\n process.tpPairSeq += process.muMcMatch \n process.muonEffs.isMC = cms.bool(True)\n process.muonEffs.eventWeight = cms.InputTag(\"generator\")\n process.muonEffs.PUWeightSrc = cms.InputTag(\"pileupReweightingProducer\",\"pileupWeights\")\n process.tpPairSeq += process.pileupReweightingProducer\n\nif not options.isMC :\n import FWCore.PythonUtilities.LumiList as LumiList\n process.source.lumisToProcess = LumiList.LumiList(filename = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/'+config['json']).getVLuminosityBlockRange()\n\nprocess.p = cms.Path(\n process.tightMuons *\n (process.tagMuons + process.probeMuons) *\n (process.tagMuonsTriggerMatched + process.probeTriggerSeq) *\n process.tpPairSeq *\n process.muonEffs\n )\n\nprocess.out = cms.OutputModule(\"PoolOutputModule\", \n fileName = cms.untracked.string('debug.root'),\n SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(\"p\"))\n )\nif config['DEBUG'] :\n process.outpath = cms.EndPath(process.out)\n\nprocess.TFileService = cms.Service(\"TFileService\", fileName = cms.string(options.outputFile))\n\n" }, { "alpha_fraction": 0.7355102300643921, "alphanum_fraction": 0.7428571581840515, "avg_line_length": 34, "blob_id": "40e02218386bf462eb0ff12dc79360b2440cfead", "content_id": "86294a829f3f4559a2259d5c030ea3f3d7376831", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3675, "license_type": "no_license", "max_line_length": 142, "num_lines": 105, "path": "/plugins/pairMCInfoEmbedder.cc", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "// Original Author: Nicholas Charles Smith\n\n// system include files\n#include <memory>\n\n// user include files\n#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/Framework/interface/EDProducer.h\"\n\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n\n#include \"DataFormats/Candidate/interface/CandidateFwd.h\"\n#include \"DataFormats/Candidate/interface/Candidate.h\"\n#include \"DataFormats/PatCandidates/interface/CompositeCandidate.h\"\n\n#include \"DataFormats/Common/interface/Association.h\"\n#include \"DataFormats/HepMCCandidate/interface/GenParticle.h\"\n\nclass pairMCInfoEmbedder : public edm::EDProducer {\n public:\n explicit pairMCInfoEmbedder(const edm::ParameterSet&);\n ~pairMCInfoEmbedder();\n\n static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);\n\n private:\n virtual void beginJob() override;\n virtual void produce(edm::Event&, const edm::EventSetup&) override;\n virtual void endJob() override;\n\n edm::EDGetTokenT<reco::CandidateView> srcToken_;\n edm::EDGetTokenT<edm::Association<reco::GenParticleCollection>> leg1MatchesToken_, leg2MatchesToken_;\n};\n\npairMCInfoEmbedder::pairMCInfoEmbedder(const edm::ParameterSet& iConfig) :\n srcToken_(consumes<reco::CandidateView>(iConfig.getParameter<edm::InputTag>(\"input\"))),\n leg1MatchesToken_(consumes<edm::Association<reco::GenParticleCollection>>(iConfig.getParameter<edm::InputTag>(\"leg1Matches\"))),\n leg2MatchesToken_(consumes<edm::Association<reco::GenParticleCollection>>(iConfig.getParameter<edm::InputTag>(\"leg2Matches\")))\n{\n produces<pat::CompositeCandidateCollection>();\n}\n\n\npairMCInfoEmbedder::~pairMCInfoEmbedder()\n{\n}\n\nvoid\npairMCInfoEmbedder::produce(edm::Event& iEvent, const edm::EventSetup& iSetup)\n{\n using namespace edm;\n\n Handle<reco::CandidateView> src;\n iEvent.getByToken(srcToken_, src);\n \n Handle<edm::Association<reco::GenParticleCollection>> leg1Matches;\n iEvent.getByToken(leg1MatchesToken_, leg1Matches);\n \n Handle<edm::Association<reco::GenParticleCollection>> leg2Matches;\n iEvent.getByToken(leg2MatchesToken_, leg2Matches);\n \n std::unique_ptr<pat::CompositeCandidateCollection> pairsEmbedded{new pat::CompositeCandidateCollection};\n\n for ( const auto& mother : *src ) {\n if (mother.numberOfDaughters() != 2) throw cms::Exception(\"CorruptData\") << \"Pair with \" << mother.numberOfDaughters() << \" daughters\\n\";\n pat::CompositeCandidate motherEmbedded((reco::CompositeCandidate) mother);\n reco::GenParticleRef leg1 = (*leg1Matches)[mother.daughter(0)->masterClone()];\n reco::GenParticleRef leg2 = (*leg2Matches)[mother.daughter(1)->masterClone()];\n if ( !leg1.isNull() && !leg2.isNull() ) {\n auto mcVector = leg1->p4() + leg2->p4();\n motherEmbedded.addUserFloat(\"mc_mass\", mcVector.mass());\n motherEmbedded.addUserFloat(\"mc_pt\", mcVector.pt());\n } else {\n motherEmbedded.addUserFloat(\"mc_mass\", 0.);\n motherEmbedded.addUserFloat(\"mc_pt\", 0.);\n }\n pairsEmbedded->push_back(motherEmbedded);\n }\n\n iEvent.put(std::move(pairsEmbedded));\n}\n\nvoid \npairMCInfoEmbedder::beginJob()\n{\n}\n\nvoid \npairMCInfoEmbedder::endJob() {\n}\n\nvoid\npairMCInfoEmbedder::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {\n //The following says we do not know what parameters are allowed so do no validation\n // Please change this to state exactly what you do use, even if it is no parameters\n edm::ParameterSetDescription desc;\n desc.setUnknown();\n descriptions.addDefault(desc);\n}\n\n//define this as a plug-in\nDEFINE_FWK_MODULE(pairMCInfoEmbedder);\n" }, { "alpha_fraction": 0.7476340532302856, "alphanum_fraction": 0.7476340532302856, "avg_line_length": 30.700000762939453, "blob_id": "4bcebcee924bd9cfc0dbd1e188e0c40fb79f021a", "content_id": "219bb3504dd695a02249a2068a4436c3ebda9582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 317, "license_type": "no_license", "max_line_length": 61, "num_lines": 10, "path": "/muons/runNewFits.sh", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "# source me\nrm -rf plots/*\n./newfitter.py\nmkdir -p plots/badFits\nmv badFit_* plots/badFits\ndumpTagProbeTreeHTML.py --data fits.root -i muonFits -o plots\n./plot.py ZZLoose \"Muon Loose ID\"\n./plot.py ZZTight \"Muon Tight ID\"\n./plot.py ZZIso_wrtLoose \"Muon Loose Isolation\"\n./plot.py ZZIso_wrtTight \"Muon Tight Isolation\"\n" }, { "alpha_fraction": 0.5745459794998169, "alphanum_fraction": 0.5831868648529053, "avg_line_length": 34.015384674072266, "blob_id": "78a7e50e9fc2a44379bd9b1c12bb955b6acfad78", "content_id": "58a06c1d79b909c63e15674a691cfb2af52ab691", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6828, "license_type": "no_license", "max_line_length": 144, "num_lines": 195, "path": "/scripts/dumpTagProbeLatex.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nROOT.gROOT.SetBatch(True)\nROOT.PyConfig.IgnoreCommandLineOptions = True\nimport argparse, json, pickle, os, re\n\n# mkdir -p \ndef mkdirP(dirname) :\n import errno\n try:\n os.mkdir(dirname)\n except OSError, e:\n if e.errno != errno.EEXIST:\n raise e\n pass\n\ndef rootFileType(string) :\n file = ROOT.TFile.Open(string)\n if not file :\n raise argparse.ArgumentTypeError(string+' could not be opened!')\n return file\n\ndef subDirs(dir) :\n for key in dir.GetListOfKeys() :\n if key.IsFolder() :\n yield key.ReadObj()\n\ndef get2DPlot(effDir, isMC=False) :\n canvas = None\n plotsDir = None\n if isMC :\n plotsDir = effDir.Get('cnt_eff_plots')\n else :\n plotsDir = effDir.Get('fit_eff_plots')\n\n for key in plotsDir.GetListOfKeys() :\n if re.match('probe_.*abseta.*_probe_.*_PLOT.*', key.GetName()) :\n canvas = key.ReadObj()\n break\n\n if not canvas :\n raise Exception('No canvas found in %s' % effDir.GetName())\n \n plot = canvas.GetPrimitive(canvas.GetName())\n plot.SetName(effDir.GetName())\n ROOT.SetOwnership(canvas, False)\n return plot\n\ndef formatValue(hist, etabin, ptbin) :\n value = hist.GetBinContent(etabin, ptbin)\n err = hist.GetBinError(etabin, ptbin)\n return '$%1.4f \\\\pm %1.4f$' % (value, err)\n\ndef makeLatex(data, mc, ratio) :\n output = ''\n\n neta = data.GetNbinsX()\n output += '''\\\\begin{table}[htbp]\n \\\\centering\n \\\\begin{tabular}{%s}\n \\hline\n''' % 'c'.join(['|']*(neta+3))\n\n etaLabels = ['$p_T$', '-']\n for etabin in xrange(1, neta+1) :\n etalo = data.GetXaxis().GetBinLowEdge(etabin)\n etahi = data.GetXaxis().GetBinLowEdge(etabin+1)\n etaLabels.append('$%1.1f < |\\\\eta| < %1.1f$' % (etalo, etahi))\n\n output += ' ' + ' & '.join(etaLabels) + '\\\\\\\\ \\hline\\n'\n\n npt = data.GetNbinsY()\n for ptbin in xrange(1, npt+1) :\n ptlo = data.GetYaxis().GetBinLowEdge(ptbin)\n pthi = data.GetYaxis().GetBinLowEdge(ptbin+1)\n ptLabel = '$%3.0f - %3.0f$' % (ptlo, pthi)\n\n output += ' \\\\multirow{3}{*}{%s} \\n' % ptLabel\n\n dataLine, mcLine, ratioLine = [['', name] for name in ['Data', 'MC', 'Ratio']]\n for etabin in xrange(1, neta+1) :\n dataLine.append(formatValue(data, etabin, ptbin))\n mcLine.append(formatValue(mc, etabin, ptbin))\n ratioLine.append(formatValue(ratio, etabin, ptbin))\n\n\n output += ' %s \\\\\\\\ \\n' % ' & '.join(dataLine)\n output += ' %s \\\\\\\\ \\n' % ' & '.join(mcLine)\n output += ' %s \\\\\\\\ \\\\hline\\n' % ' & '.join(ratioLine)\n\n output += ''' \\\\end{tabular}\n \\\\caption{Efficiency table for %s}\n\\\\end{table}\n''' % data.GetName().replace('_','\\\\_')\n return output\n\ndef makeJson(data, mc, ratio) :\n output = []\n\n neta = data.GetNbinsX()\n npt = data.GetNbinsY()\n for ptbin in xrange(1, npt+1) :\n ptlo = data.GetYaxis().GetBinLowEdge(ptbin)\n pthi = data.GetYaxis().GetBinLowEdge(ptbin+1)\n\n for etabin in xrange(1, neta+1) :\n etalo = data.GetXaxis().GetBinLowEdge(etabin)\n etahi = data.GetXaxis().GetBinLowEdge(etabin+1)\n data_value = data.GetBinContent(etabin, ptbin)\n data_err = data.GetBinError(etabin, ptbin)\n mc_value = mc.GetBinContent(etabin, ptbin)\n mc_err = mc.GetBinError(etabin, ptbin)\n ratio_value = ratio.GetBinContent(etabin, ptbin)\n ratio_err = ratio.GetBinError(etabin, ptbin)\n output.append({\n 'pt_lo' : ptlo,\n 'pt_hi' : pthi,\n 'abseta_lo' : etalo,\n 'abseta_hi' : etahi,\n 'data' : data_value,\n 'data_err' : data_err,\n 'mc' : mc_value,\n 'mc_err' : mc_err,\n 'ratio' : ratio_value,\n 'ratio_err' : ratio_err\n })\n return output\n\ndef main() :\n parser = argparse.ArgumentParser(description='Dumps fit info generated by TagProbeFitTreeAnalyzer into HTML summary')\n parser.add_argument('--mc', help='MC fit tree name', type=rootFileType, required=True)\n parser.add_argument('--data', help='Data fit tree name', type=rootFileType, required=True)\n parser.add_argument('--output', '-o', help='Directory name for output', required=True)\n parser.add_argument('--input', '-i', help='Directory name in root files to load', default='muonEffs')\n parser.add_argument('--count', '-c', help='Use count efficiency for MC', action='store_true')\n args = parser.parse_args()\n\n latexOutput = open(os.path.join(args.output, 'tables.tex.txt'), 'w')\n\n mcPlots = [get2DPlot(effDir, args.count) for effDir in subDirs(args.mc.Get(args.input))]\n dataPlots = [get2DPlot(effDir) for effDir in subDirs(args.data.Get(args.input))]\n\n def makeFromDivide(num, denom) :\n new = ROOT.TH2F(num)\n new.Divide(denom)\n return new\n\n ratioPlots = ( (p1, p2, makeFromDivide(p1, p2)) for p1 in dataPlots for p2 in mcPlots if p1.GetName() == p2.GetName().replace('_mcTrue',''))\n\n ROOT.gStyle.SetOptDate(0)\n ROOT.gStyle.SetHistLineWidth(2)\n\n table_json = {}\n for (data,mc,ratio) in ratioPlots :\n latexOutput.write(makeLatex(data, mc, ratio))\n table_json[data.GetName()] = makeJson(data, mc, ratio)\n canvas = ROOT.TCanvas(data.GetName()+\"_canvas\", \"\")\n canvas.SetLogx(True)\n\n dataproj = data.ProjectionY(\"Data\", 0, -1, \"e\")\n dataproj.Scale(1./data.GetXaxis().GetNbins())\n dataproj.SetLineColor(ROOT.kRed)\n dataproj.SetTitle('Data')\n\n mcproj = mc.ProjectionY(\"MC\", 0, -1, \"e\")\n mcproj.Scale(1./data.GetXaxis().GetNbins())\n mcproj.SetLineColor(ROOT.kGreen)\n mcproj.SetTitle('MC')\n\n ratioproj = ratio.ProjectionY(\"Ratio\", 0, -1, \"e\")\n ratioproj.Scale(1./data.GetXaxis().GetNbins())\n ratioproj.SetLineColor(ROOT.kBlue)\n ratioproj.SetTitle('Ratio')\n\n stack = ROOT.THStack(\"stack\", \"stack;p_{T};Efficiency\")\n stack.Add(dataproj, 'ep')\n stack.Add(mcproj, 'ep')\n stack.Add(ratioproj, 'ep')\n stack.SetMinimum(0)\n stack.SetMaximum(1.2)\n stack.Draw('nostack')\n leg = canvas.BuildLegend(.5,.2,.9,.4)\n leg.SetHeader(data.GetName())\n canvas.Update()\n canvas.Print(os.path.join(args.output, data.GetName()+'.png'))\n canvas.Print(os.path.join(args.output, data.GetName()+'.pdf'))\n\n import subprocess\n table_json['version'] = subprocess.check_output([\"git\", \"describe\", \"--always\"]).strip()\n\n with open(os.path.join(args.output, 'table.json'), 'w') as out :\n json.dump(table_json, out, indent=4)\n\nif __name__ == '__main__' :\n main()\n" }, { "alpha_fraction": 0.6222015023231506, "alphanum_fraction": 0.6464552283287048, "avg_line_length": 25.799999237060547, "blob_id": "d87b2a80bab05962cca35c727e73f6e226f3c55f", "content_id": "f6bd3a2ddecd62ca62f02b3396e6b7afcc8e3a65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1072, "license_type": "no_license", "max_line_length": 77, "num_lines": 40, "path": "/data/makeZmmGenShape.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nROOT.gROOT.SetBatch(True)\n\nROOT.gSystem.Load(\"libFWCoreFWLite.so\");\nROOT.gSystem.Load(\"libDataFormatsFWLite.so\");\nROOT.AutoLibraryLoader.enable()\n\nfrom DataFormats.FWLite import Handle, Events\n\ngenParticles = Handle(\"std::vector<reco::GenParticle>\")\ngenWeights = Handle(\"GenEventInfoProduct\")\n\nevents = Events(sys.argv[1])\n\noutFile = ROOT.TFile(sys.argv[2], 'recreate')\nhGen = ROOT.TH1F('Mass', 'Z#rightarrow #mu#mu Gen-level Mass', 2000, 0, 200.)\n\nfor iev,event in enumerate(events):\n if iev%1000 == 0 :\n print \"Done with %d events\" % iev\n event.getByLabel('prunedGenParticles', genParticles)\n event.getByLabel('generator', genWeights)\n zmms = []\n for p in genParticles.product() :\n if not p.mother() :\n continue\n if abs(p.pdgId()) == 13 and p.isPromptFinalState() :\n zmms.append(p)\n\n w = -1.\n if genWeights.product().weight() > 0 :\n w = 1.\n\n if len(zmms) == 2 :\n hGen.Fill((zmms[0].p4()+zmms[1].p4()).mass(), w)\n\noutFile.cd()\nhGen.Write()\noutFile.Close()\n" }, { "alpha_fraction": 0.6268656849861145, "alphanum_fraction": 0.7149964570999146, "avg_line_length": 38.08333206176758, "blob_id": "e73b70f1a5a3d060fa5c618dea99f2ca1214ccbf", "content_id": "fc750dd66824b0efdbe0ae648047acc19ab0afc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1407, "license_type": "no_license", "max_line_length": 156, "num_lines": 36, "path": "/phase2muons/drawstuff.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import ROOT\nimport glob\nf0 = ROOT.TFile('pu0.root')\nf35 = ROOT.TFile('pu35.root')\nf140 = ROOT.TFile('pu140.root')\nf200 = ROOT.TFile('pu200.root')\n\nt0 = f0.Get('muonEffs/fitter_tree')\nt35 = f35.Get('muonEffs/fitter_tree')\nt140 = f140.Get('muonEffs/fitter_tree')\nt200 = f200.Get('muonEffs/fitter_tree')\n\ntrees = [t0, t35, t140, t200]\nmap(lambda t: t.SetLineWidth(2), trees)\nt0.SetLineColor(ROOT.kRed)\nt35.SetLineColor(ROOT.kGreen)\nt140.SetLineColor(ROOT.kBlue)\nt200.SetLineColor(ROOT.kBlack)\n\npfRelIso = \"(probe_chargedHadronIsoR04 + max(0, probe_neutralHadronIsoR04 + probe_photonIsoR04 - 0.5*probe_pileupIsoR04))/probe_pt >> hRelIsoPu%d(50, 0, 1)\"\nmaxPart = \"(probe_neutralHadronIsoR04 + probe_photonIsoR04 - 0.5*probe_pileupIsoR04)/probe_pt >> hRelIsoPu%d(50, -2, 2)\"\n\ndrawStr = pfRelIso\n#title = \"(#Sum E_{h^0} + E_{#gamma} - 0.5*E_{PU}) / p_{T,#mu}\"\ntitle = \"PF Relative Isolation R<0.4 w/#Delta#beta\"\n\nt0.Draw(drawStr % 0, \"mcTrue&&mc_probe_isPromptFinalState\")\nt0.GetHistogram().SetTitle(\"<PU>=0\")\nt0.GetHistogram().GetXaxis().SetTitle(title)\nt35.Draw(drawStr % 35, \"mcTrue&&mc_probe_isPromptFinalState\", \"same\")\nt35.GetHistogram().SetTitle(\"<PU>=35\")\nt140.Draw(drawStr % 140, \"mcTrue&&mc_probe_isPromptFinalState\", \"same\")\nt140.GetHistogram().SetTitle(\"<PU>=140\")\nt200.Draw(drawStr % 200, \"mcTrue&&mc_probe_isPromptFinalState\", \"same\")\nt200.GetHistogram().SetTitle(\"<PU>=200\")\nROOT.gPad.BuildLegend()\n" }, { "alpha_fraction": 0.5920111536979675, "alphanum_fraction": 0.6085055470466614, "avg_line_length": 40.93333435058594, "blob_id": "647d85de0f49bb2c89192f28ed62680003f3ea01", "content_id": "7727fcdd550ee26e945a04f21f6c4114f1c9ea6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5032, "license_type": "no_license", "max_line_length": 154, "num_lines": 120, "path": "/phase2muons/newfitter.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nROOT.gROOT.SetBatch(True)\nROOT.PyConfig.IgnoreCommandLineOptions = True\nfrom Analysis.DiBosonTP.PassFailSimulFitter import PassFailSimulFitter\nimport sys\n\ndef main() :\n fitVariable = ROOT.RooRealVar('mass', 'TP Pair Mass', 60, 120, 'GeV')\n fitVariable.setBins(60)\n\n ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.ERROR)\n ROOT.Math.MinimizerOptions.SetDefaultTolerance(1.e-2) # default is 1.e-2\n\n fmc = ROOT.TFile.Open(sys.argv[-1])\n tmc = fmc.Get('muonEffs/fitter_tree')\n\n mcTruthCondition = ['mcTrue', 'mc_probe_isPromptFinalState']\n\n pdfDefinition = []\n with open('pdfDefinition.txt') as defFile :\n for line in defFile :\n line = line.strip()\n if len(line) == 0 or line[0] is '#' :\n continue\n pdfDefinition.append(line)\n\n\n def statusInfo(fitResults) :\n fitStatus=':'.join(['% d' % fitResults.statusCodeHistory(i) for i in range(fitResults.numStatusHistory())]),\n return fitStatus\n\n def fitBin(name, allProbeCondition, passingProbeCondition) :\n ROOT.gDirectory.mkdir(name).cd()\n fitter = PassFailSimulFitter(name, fitVariable)\n fitter.addDataFromTree(tmc, 'mcData', allProbeCondition+mcTruthCondition, passingProbeCondition, separatePassFail = True, weightVariable='weight')\n nMCPass = fitter.workspace.data('mcDataPass').sumEntries()\n nMCFail = fitter.workspace.data('mcDataFail').sumEntries()\n mcEff = nMCPass/(nMCPass+nMCFail)\n mcEffLo = ROOT.TEfficiency.ClopperPearson(int(nMCPass+nMCFail), int(nMCPass), 0.68, False)\n mcEffHi = ROOT.TEfficiency.ClopperPearson(int(nMCPass+nMCFail), int(nMCPass), 0.68, True)\n h=ROOT.TH1F('mc_cutCount', 'Cut & Count', 2, 0, 2)\n h.SetBinContent(1, nMCPass)\n h.SetBinContent(2, nMCPass+nMCFail)\n\n # All MC templates must be set up by now\n fitter.setPdf(pdfDefinition)\n\n print '-'*40, 'Central value fit'\n fitter.addDataFromTree(tmc, 'data', allProbeCondition, passingProbeCondition, weightVariable='weight')\n res = fitter.fit('simPdf', 'data')\n effValue = res.floatParsFinal().find('efficiency')\n dataEff = effValue.getVal()\n dataEffErrHi = effValue.getErrorHi()\n dataEffErrLo = effValue.getErrorLo()\n res.SetName('fitresults')\n c = fitter.drawFitCanvas(res)\n c.Write()\n h.Write()\n res.Write()\n\n fitter.workspace.Write()\n print name, ': Data=%.2f, MC=%.2f, Ratio=%.2f' % (dataEff, mcEff, dataEff/mcEff)\n condition = ' && '.join(allProbeCondition)\n variations = {\n 'EFF_CUTCOUNT' : (mcEff, res),\n 'EFF_CUTCOUNT_UP' : (mcEffHi, res),\n 'EFF_CUTCOUNT_DOWN' : (mcEffLo, res),\n 'EFF_FIT' : (mcEff, res),\n 'EFF_FIT_UP' : (mcEffHi, res),\n 'EFF_FIT_DOWN' : (mcEffLo, res),\n }\n cutString = ''\n for varName, value in variations.items() :\n (value, fitResult) = value\n cutString += ' if ( variation == Variation::%s && (%s) ) return %f;\\n' % (varName, condition, value)\n print ' Variation {:>15s} : {:.4f}, edm={:f}, status={:s}'.format(varName, value, fitResult.edm(), statusInfo(fitResult))\n if 'EFF_FIT' == varName and fitResult.statusCodeHistory(0) < 0 :\n cBad = fitter.drawFitCanvas(fitResult)\n cBad.Print('badFit_%s_%s.png' %(name, varName))\n\n ROOT.TNamed('cutString', cutString).Write()\n print\n ROOT.gDirectory.cd('..')\n\n def fit(name, allProbeCondition, passingProbeCondition, binningMap, macroVariables) :\n ROOT.gDirectory.mkdir(name).cd()\n ROOT.TNamed('variables', ', '.join(macroVariables)).Write()\n for binName, cut in sorted(binningMap.items()) :\n fitBin(name+'_'+binName, allProbeCondition+cut, passingProbeCondition)\n ROOT.gDirectory.cd('..')\n\n ptBinning = {\n 'pt10to30' : ['probe_pt>10 && probe_pt<30'],\n 'pt30to50' : ['probe_pt>30 && probe_pt<50'],\n 'pt50toInf' : ['probe_pt>50'],\n }\n\n etaBinning = {\n 'abseta0p0to1p2' : ['probe_abseta < 1.2'],\n 'abseta1p2to2p4' : ['probe_abseta >= 1.2 && probe_abseta < 2.4'],\n }\n \n binning = {}\n for name1, cut1 in ptBinning.items() :\n for name2, cut2 in etaBinning.items() :\n binning[name1+'_'+name2] = cut1+cut2\n\n commonVars = ['float probe_pt', 'float probe_abseta']\n\n fout = ROOT.TFile('fits.root', 'recreate')\n fout.mkdir('muonFits').cd()\n\n fit('WZLoose', [], 'passingIDWZLoose', binning, commonVars)\n fit('Tight', [], 'passingTightID', binning, commonVars)\n fit('RelIso0p4', ['passingTightID'], 'passingIsoWZLoose', binning, commonVars+['bool passingTightID'])\n fit('RelIso0p12', ['passingTightID'], 'passingIsoWZTight', binning, commonVars+['bool passingTightID'])\n\nif __name__ == '__main__' :\n main()\n" }, { "alpha_fraction": 0.672510027885437, "alphanum_fraction": 0.7214768528938293, "avg_line_length": 42.080169677734375, "blob_id": "a79757a6edad0919769887efe944a206baec81f6", "content_id": "e7be7817e0d31c70f8bb827f5d3bb4bf78496042", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10211, "license_type": "no_license", "max_line_length": 200, "num_lines": 237, "path": "/muons/makeDZTree.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "import FWCore.ParameterSet.Config as cms\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\nprocess = cms.Process(\"tnp\")\noptions = VarParsing('analysis')\noptions.register(\n \"isMC\",\n True,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"Compute MC efficiencies\"\n )\noptions.parseArguments()\n\nisolationDef = \"(chargedHadronIso+max(photonIso+neutralHadronIso-0.5*puChargedHadronIso,0.0))/pt\"\nconfig = {}\nconfig['MUON_COLL'] = \"slimmedMuons\"\nconfig['MUON_CUTS'] = \"(isTrackerMuon || isGlobalMuon) && abs(eta)<2.5 && pt > 5\"\nconfig['DEBUG'] = cms.bool(False)\nconfig['json'] = 'Cert_246908-260627_13TeV_PromptReco_Collisions15_25ns_JSON_v2.txt'\n\n# file dataset=/DoubleMuon/Run2015D-05Oct2015-v1/MINIAOD\n# https://cmsweb.cern.ch/das/request?view=plain&limit=50&instance=prod%2Fglobal&input=file+dataset%3D%2FDoubleMuon%2FRun2015D-05Oct2015-v1%2FMINIAOD\ninputFilesData = [\n '/store/data/Run2015D/DoubleMuon/MINIAOD/05Oct2015-v1/40000/529E5F9F-5F6F-E511-83C6-0026189438F4.root',\n '/store/data/Run2015D/DoubleMuon/MINIAOD/05Oct2015-v1/40000/52A8BE9F-5F6F-E511-86A9-0025905AA9CC.root',\n '/store/data/Run2015D/DoubleMuon/MINIAOD/05Oct2015-v1/40000/56CC0262-5E6F-E511-B9BD-0025905A613C.root',\n]\n\n# file dataset=/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15MiniAODv2-74X_mcRun2_asymptotic_v2-v1/MINIAODSIM\ninputFilesMC = [\n '/store/mc/RunIISpring15MiniAODv2/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v1/50000/00759690-D16E-E511-B29E-00261894382D.root',\n '/store/mc/RunIISpring15MiniAODv2/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v1/50000/00E88378-6F6F-E511-9D54-001E6757EAA4.root',\n '/store/mc/RunIISpring15MiniAODv2/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v1/50000/02CD8A95-736F-E511-B76E-00266CFFBF34.root',\n]\n\nif len(options.inputFiles) is 0 :\n if options.isMC :\n options.inputFiles = inputFilesMC\n else :\n options.inputFiles = inputFilesData\n\nif len(options.outputFile) is 0 :\n if options.isMC :\n options.outputFile = 'TnPTreeDZ_mc.root'\n else :\n options.outputFile = 'TnPTreeDZ_data.root'\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(options.inputFiles),\n )\n\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\nfrom HLTrigger.HLTfilters.hltHighLevel_cfi import hltHighLevel\nprocess.hltFilter = hltHighLevel.clone()\nprocess.hltFilter.throw = cms.bool(True)\nprocess.hltFilter.HLTPaths = cms.vstring('HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_v*', 'HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_v*')\n\nprocess.goodMuons = cms.EDFilter(\"PATMuonRefSelector\",\n src = cms.InputTag(config['MUON_COLL']),\n cut = cms.string(config['MUON_CUTS']),\n filter = cms.bool(True)\n)\n\nprocess.triggerMatchingSequence = cms.Sequence()\n\nprocess.muonTriggerUpperLeg = cms.EDProducer(\"PatMuonTriggerCandProducer\",\n filterNames = cms.vstring(\"hltDiMuonGlb17Glb8RelTrkIsoFiltered0p4\", \"hltL3fL1sDoubleMu103p5L1f0L2f10OneMuL3Filtered17\"),\n inputs = cms.InputTag(\"goodMuons\"),\n bits = cms.InputTag('TriggerResults::HLT'),\n objects = cms.InputTag('selectedPatTrigger'),\n dR = cms.double(0.5),\n isAND = cms.bool(True)\n )\nprocess.triggerMatchingSequence += process.muonTriggerUpperLeg\n\nprocess.muonTriggerMu8Leg = process.muonTriggerUpperLeg.clone()\nprocess.muonTriggerMu8Leg.filterNames = cms.vstring(\"hltDiMuonGlb17Glb8RelTrkIsoFiltered0p4\", \"hltL3pfL1sDoubleMu103p5L1f0L2pf0L3PreFiltered8\")\nprocess.triggerMatchingSequence += process.muonTriggerMu8Leg\n\nprocess.muonTriggerTkMu8Leg = process.muonTriggerUpperLeg.clone()\nprocess.muonTriggerTkMu8Leg.filterNames = cms.vstring(\"hltDiMuonGlb17Trk8RelTrkIsoFiltered0p4\", \"hltDiMuonGlbFiltered17TrkFiltered8\")\nprocess.triggerMatchingSequence += process.muonTriggerTkMu8Leg\n\nprocess.muonDZTriggerMu8Leg = process.muonTriggerUpperLeg.clone()\nprocess.muonDZTriggerMu8Leg.filterNames = cms.vstring(\"hltDiMuonGlb17Glb8RelTrkIsoFiltered0p4\", \"hltL3pfL1sDoubleMu103p5L1f0L2pf0L3PreFiltered8\", \"hltDiMuonGlb17Glb8RelTrkIsoFiltered0p4DzFiltered0p2\")\nprocess.triggerMatchingSequence += process.muonDZTriggerMu8Leg\n\nprocess.muonDZTriggerTkMu8Leg = process.muonTriggerUpperLeg.clone()\nprocess.muonDZTriggerTkMu8Leg.filterNames = cms.vstring(\"hltDiMuonGlb17Trk8RelTrkIsoFiltered0p4\", \"hltDiMuonGlbFiltered17TrkFiltered8\", \"hltDiMuonGlb17Trk8RelTrkIsoFiltered0p4DzFiltered0p2\")\nprocess.triggerMatchingSequence += process.muonDZTriggerTkMu8Leg\n\nprocess.tpPairsMu17Mu8 = cms.EDProducer(\"CandViewShallowCloneCombiner\",\n decay = cms.string(\"muonTriggerUpperLeg@+ muonTriggerMu8Leg@-\"), # charge coniugate states are implied\n cut = cms.string(\"40 < mass < 200\")\n)\n\nprocess.tpPairsMu17TkMu8 = cms.EDProducer(\"CandViewShallowCloneCombiner\",\n decay = cms.string(\"muonTriggerUpperLeg@+ muonTriggerTkMu8Leg@-\"), # charge coniugate states are implied\n cut = cms.string(\"40 < mass < 200\")\n)\n\nprocess.muMcMatch = cms.EDProducer(\"MCTruthDeltaRMatcherNew\",\n pdgId = cms.vint32(13),\n src = cms.InputTag(config['MUON_COLL']),\n distMin = cms.double(0.3),\n matched = cms.InputTag(\"prunedGenParticles\"),\n checkCharge = cms.bool(True)\n)\n\nprocess.pileupReweightingProducer = cms.EDProducer(\"PileupWeightProducer\",\n hardcodedWeights = cms.untracked.bool(False),\n PileupMCFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightMC.root'),\n PileupDataFile = cms.string('$CMSSW_BASE/src/Analysis/DiBosonTP/data/puWeightData.root'),\n )\n\nZVariablesToStore = cms.PSet(\n eta = cms.string(\"eta\"),\n abseta = cms.string(\"abs(eta)\"),\n pt = cms.string(\"pt\"),\n mass = cms.string(\"mass\"),\n ) \n\nProbeVariablesToStore = cms.PSet(\n probe_eta = cms.string(\"eta\"),\n probe_abseta = cms.string(\"abs(eta)\"),\n probe_pt = cms.string(\"pt\"),\n probe_et = cms.string(\"et\"),\n probe_e = cms.string(\"energy\"),\n probe_q = cms.string(\"charge\"),\n )\n\nTagVariablesToStore = cms.PSet(\n tag_eta = cms.string(\"eta\"),\n tag_abseta = cms.string(\"abs(eta)\"),\n tag_pt = cms.string(\"pt\"),\n tag_et = cms.string(\"et\"),\n tag_e = cms.string(\"energy\"),\n tag_q = cms.string(\"charge\"),\n )\n\nCommonStuffForMuonProbe = cms.PSet(\n variables = cms.PSet(ProbeVariablesToStore),\n ignoreExceptions = cms.bool (True),\n addRunLumiInfo = cms.bool (True),\n addEventVariablesInfo = cms.bool(True),\n vertexCollection = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n #pfMet = cms.InputTag(\"\"),\n pairVariables = cms.PSet(ZVariablesToStore),\n pairFlags = cms.PSet(\n mass60to120 = cms.string(\"60 < mass < 120\")\n ),\n tagVariables = cms.PSet(TagVariablesToStore),\n tagFlags = cms.PSet(), \n )\n\nmcTruthCommonStuff = cms.PSet(\n isMC = cms.bool(False),\n tagMatches = cms.InputTag(\"muMcMatch\"),\n probeMatches = cms.InputTag(\"muMcMatch\"),\n motherPdgId = cms.vint32(22,23),\n #motherPdgId = cms.vint32(443), # JPsi\n #motherPdgId = cms.vint32(553), # Yupsilon\n makeMCUnbiasTree = cms.bool(False),\n checkMotherInUnbiasEff = cms.bool(False),\n mcVariables = cms.PSet(\n probe_eta = cms.string(\"eta\"),\n probe_abseta = cms.string(\"abs(eta)\"),\n probe_et = cms.string(\"et\"),\n probe_e = cms.string(\"energy\"),\n ),\n mcFlags = cms.PSet(\n probe_flag = cms.string(\"pt>0\")\n ), \n )\n\nprocess.globalMuonDZTree = cms.EDAnalyzer(\"TagProbeFitTreeProducer\",\n CommonStuffForMuonProbe, mcTruthCommonStuff,\n tagProbePairs = cms.InputTag(\"tpPairsMu17Mu8\"),\n arbitration = cms.string(\"BestMass\"),\n massForArbitration = cms.double(91.),\n flags = cms.PSet(\n passingDZ = cms.InputTag(\"muonDZTriggerMu8Leg\"),\n ),\n allProbes = cms.InputTag(\"muonTriggerMu8Leg\"),\n )\n\nprocess.trackerMuonDZTree = cms.EDAnalyzer(\"TagProbeFitTreeProducer\",\n CommonStuffForMuonProbe, mcTruthCommonStuff,\n tagProbePairs = cms.InputTag(\"tpPairsMu17TkMu8\"),\n arbitration = cms.string(\"BestMass\"),\n massForArbitration = cms.double(91.),\n flags = cms.PSet(\n passingDZ = cms.InputTag(\"muonDZTriggerTkMu8Leg\"),\n ),\n allProbes = cms.InputTag(\"muonTriggerTkMu8Leg\"),\n )\n\nprocess.tpPairSeq = cms.Sequence(\n process.tpPairsMu17Mu8 + process.tpPairsMu17TkMu8\n)\n\nif options.isMC :\n process.tpPairSeq += process.muMcMatch \n process.tpPairSeq += process.pileupReweightingProducer\n process.globalMuonDZTree.isMC = cms.bool(True)\n process.globalMuonDZTree.eventWeight = cms.InputTag(\"generator\")\n process.globalMuonDZTree.PUWeightSrc = cms.InputTag(\"pileupReweightingProducer\",\"pileupWeights\")\n process.trackerMuonDZTree.isMC = cms.bool(True)\n process.trackerMuonDZTree.eventWeight = cms.InputTag(\"generator\")\n process.trackerMuonDZTree.PUWeightSrc = cms.InputTag(\"pileupReweightingProducer\",\"pileupWeights\")\n\nif not options.isMC :\n import FWCore.PythonUtilities.LumiList as LumiList\n process.source.lumisToProcess = LumiList.LumiList(filename = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/'+config['json']).getVLuminosityBlockRange()\n\nprocess.p = cms.Path(\n process.goodMuons *\n process.triggerMatchingSequence *\n process.tpPairSeq *\n (process.globalMuonDZTree + process.trackerMuonDZTree)\n )\n\nprocess.out = cms.OutputModule(\"PoolOutputModule\", \n fileName = cms.untracked.string('debug.root'),\n SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(\"p\"))\n )\nif config['DEBUG'] :\n process.outpath = cms.EndPath(process.out)\n\nprocess.TFileService = cms.Service(\"TFileService\", fileName = cms.string(options.outputFile))\n\n" }, { "alpha_fraction": 0.5675603747367859, "alphanum_fraction": 0.5919830203056335, "avg_line_length": 43.31764602661133, "blob_id": "f84d4c7a4bf795a663e2e50b1898772d16280c1f", "content_id": "c4aab74de6658a4e22f37f23455fd7d8b20ee26d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3767, "license_type": "no_license", "max_line_length": 232, "num_lines": 85, "path": "/scripts/getTemplatesFromMC.py", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nfrom optparse import OptionParser\n\ndef findBins(array, var):\n size = len(array)\n bin = \"dump\";\n for i in xrange(size-1):\n low = array[i]\n hi = array[i+1]\n if (low <= var and hi > var):\n bin = str(low)+\"To\"+str(hi)\n \n return bin;\n\ndef main(options):\n \n var1s = []\n for v in options.var1Bins.split(\",\"):\n var1s.append(float(v))\n var2s = []\n for v in options.var2Bins.split(\",\"):\n var2s.append(float(v))\n\n inFile = ROOT.TFile(options.input)\n inFile.cd(options.directory)\n fDir = inFile.Get(options.directory)\n fChain = fDir.Get(\"fitter_tree\")\n\n histos = dict()\n\n def fixForPDFusage(hist) :\n # Remove any negative-weighted bins, and\n # apply a small value uniformly to gurantee no zero bins\n for b in range(hist.GetNbinsX()+1) :\n if ( hist.GetBinContent(b) <= 0. ) :\n hist.SetBinContent(b, 0.0001)\n\n for binVar1 in xrange(len(var1s)-1):\n for binVar2 in xrange(len(var2s)-1):\n histNameSt = \"hMass_%s_bin%d__%s_bin%d\" % (options.var1Name, binVar1, options.var2Name, binVar2)\n hp = histNameSt+\"_Pass\"\n hf = histNameSt+\"_Fail\"\n (minMass, maxMass) = map(float, options.massWindow.split(\",\"))\n histos[hp] = ROOT.TH1D(hp, hp, 120, minMass, maxMass)\n histos[hf] = ROOT.TH1D(hf, hf, 120, minMass, maxMass)\n \n binning = \"mcTrue == 1 && \"+options.var1Name +\">\"+str(var1s[binVar1])+\" && \"+options.var1Name +\"<\"+str(var1s[binVar1+1])+\" && \"+options.var2Name +\">\"+str(var2s[binVar2])+\" && \"+options.var2Name +\"<\"+str(var2s[binVar2+1])\n if options.conditions :\n for condition in options.conditions.split(',') :\n binning += \" && %s==1\" % condition\n cuts = \"(\" + binning + \" && \"+options.idprobe+\"==1\"+\")*\"+options.weightVarName\n fChain.Draw(\"mass>>\"+histos[hp].GetName(), cuts, \"goff\")\n cuts = \"(\" + binning + \" && \"+options.idprobe+\"==0\"+\")*\"+options.weightVarName\n fChain.Draw(\"mass>>\"+histos[hf].GetName(), cuts, \"goff\")\n\n fixForPDFusage(histos[hp])\n fixForPDFusage(histos[hf])\n #hpassInt = histos[hp].Integral()\n #hfailInt = histos[hf].Integral()\n #print hpassInt, hfailInt, hpassInt/(hpassInt+hfailInt)\n \n outFile = ROOT.TFile(options.output, \"RECREATE\")\n for k in histos:\n histos[k].Write()\n outFile.Close()\n\n\nif __name__ == \"__main__\": \n parser = OptionParser()\n parser.add_option(\"-i\", \"--input\", default=\"../TnPTree_mc.root\", help=\"Input filename\")\n parser.add_option(\"-o\", \"--output\", default=\"mc_templates.root\", help=\"Output filename\")\n parser.add_option(\"-d\", \"--directory\", default=\"GsfElectronToRECO\", help=\"Directory with fitter_tree\")\n parser.add_option(\"\", \"--idprobe\", default=\"passingMedium\", help=\"String identifying ID WP to measure\")\n parser.add_option(\"\", \"--conditions\", default=\"\", help=\"String identifying conditions on Tag and Probe\")\n parser.add_option(\"\", \"--var1Bins\", default=\"20,30,40,50,200\", help=\"Binning to use in var1\")\n parser.add_option(\"\", \"--var2Bins\", default=\"0.0,1.0,1.4442,1.566,2.0,2.5\", help=\"Binning to use in var2\")\n parser.add_option(\"\", \"--var1Name\", default=\"probe_sc_eta\", help=\"Variable1 branch name\")\n parser.add_option(\"\", \"--var2Name\", default=\"probe_sc_et\", help=\"Variable2 branch name\")\n parser.add_option(\"\", \"--weightVarName\", default=\"totWeight\", help=\"Weight variable branch name\")\n parser.add_option(\"\", \"--massWindow\", default=\"60,120\", help=\"Mass window to generate template for\")\n\n (options, arg) = parser.parse_args()\n \n main(options)\n" }, { "alpha_fraction": 0.6951871514320374, "alphanum_fraction": 0.7165775299072266, "avg_line_length": 16, "blob_id": "efb5228c72eebcdd781177cba2f1cd84f0722c6c", "content_id": "42f376cc39ffba90cb46b9223c164f6f61b5fd32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 187, "license_type": "no_license", "max_line_length": 50, "num_lines": 11, "path": "/README.md", "repo_name": "nsmith-/DiBosonTP", "src_encoding": "UTF-8", "text": "Installation:\n\nStart with new CMSSW 7_4_X, X >= 14\n```\ngit cms-merge-topic nsmith-:egm_tnp\nmkdir Analysis\ncd Analysis\ngit clone https://github.com/nsmith-/DiBosonTP.git\ncd ..\nscram b\n```\n" } ]
34
ricco386/zaciname-s-djangom
https://github.com/ricco386/zaciname-s-djangom
96eed7f5147599afba2b28fff5a9245c0bd0a54a
988a9132f9bd17d17cade86fd8fcdd1335c25595
8a641ccb45f9109dd2d135073ddbe969823eb79d
refs/heads/master
2021-01-18T20:19:59.984346
2019-02-27T13:36:05
2019-02-27T13:36:05
31,981,950
6
2
null
null
null
null
null
[ { "alpha_fraction": 0.6731707453727722, "alphanum_fraction": 0.6780487895011902, "avg_line_length": 24.625, "blob_id": "d79e2a111982b724f401c1cca0bddf3b26f4f241", "content_id": "4bc374a5e1a0b83b72b45294f80a6de03ae71c8a", "detected_licenses": [ "CC-BY-4.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 205, "license_type": "permissive", "max_line_length": 41, "num_lines": 8, "path": "/konferencia/mailinglist/forms.py", "repo_name": "ricco386/zaciname-s-djangom", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.forms import ModelForm\nfrom mailinglist.models import Subscriber\n\nclass SubscribeForm(ModelForm):\n class Meta:\n model = Subscriber\n fields = ('email',)\n" }, { "alpha_fraction": 0.8084291219711304, "alphanum_fraction": 0.8084291219711304, "avg_line_length": 31.625, "blob_id": "2dabd00228ba3a3ea67a7329df8a70030c16bda8", "content_id": "599d7bcdba1101a72b46bd5ad00bc3f6aed4f9ec", "detected_licenses": [ "CC-BY-4.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "permissive", "max_line_length": 54, "num_lines": 8, "path": "/konferencia/mailinglist/admin.py", "repo_name": "ricco386/zaciname-s-djangom", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom mailinglist.models import Subscriber, MailingList\n\nclass SubscriberAdmin(admin.ModelAdmin):\n list_display = ('email', 'subscribed_date')\n\nadmin.site.register(Subscriber, SubscriberAdmin)\nadmin.site.register(MailingList)\n" }, { "alpha_fraction": 0.6290322542190552, "alphanum_fraction": 0.6413662433624268, "avg_line_length": 26.736841201782227, "blob_id": "a84fd4932a06519edf9e5f7b6397df3d0eb156e9", "content_id": "f3daf7709d207faa22af382fe706781f188979b3", "detected_licenses": [ "CC-BY-4.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1055, "license_type": "permissive", "max_line_length": 64, "num_lines": 38, "path": "/konferencia/mailinglist/views.py", "repo_name": "ricco386/zaciname-s-djangom", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django.http import HttpResponse, Http404\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom mailinglist.models import MailingList\nfrom mailinglist.forms import SubscribeForm\n\n\ndef index(request):\n return HttpResponse('Ahoj Svet.\\\n Práve ste v mailinglistovom indexe.')\n\n\ndef mlist(request, list_id):\n try:\n ml = MailingList.objects.get(pk=list_id)\n except MailingList.DoesNotExist:\n raise Http404('Mailinglist neexistuje!!!')\n\n return render(request, 'mailinglist/mlist.html', {'ml': ml})\n\n\ndef subscribe(request, list_id):\n ml = get_object_or_404(MailingList, pk=list_id)\n\n if request.method == \"POST\":\n form = SubscribeForm(request.POST)\n\n if form.is_valid():\n subscriber = form.save()\n ml.subscriber.add(subscriber)\n\n return redirect('mlist', list_id=list_id)\n else:\n form = SubscribeForm()\n\n return render(request, 'mailinglist/subscribe.html',\n {'ml': ml, 'form': form})\n" }, { "alpha_fraction": 0.6701030731201172, "alphanum_fraction": 0.6845360994338989, "avg_line_length": 27.52941131591797, "blob_id": "0e82a422787aef797d29aacb2befd543e3654fab", "content_id": "758a510c81b6a9b1ec90ba4ded68cd091665d30b", "detected_licenses": [ "CC-BY-4.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "permissive", "max_line_length": 92, "num_lines": 17, "path": "/konferencia/mailinglist/models.py", "repo_name": "ricco386/zaciname-s-djangom", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Subscriber(models.Model):\n email = models.EmailField(max_length=255)\n subscribed_date = models.DateTimeField('Date subscribed', auto_now_add=True, blank=True)\n\n def __str__(self): # __unicode__ on Python 2\n return self.email\n\n\nclass MailingList(models.Model):\n name = models.CharField(max_length=50)\n subscriber = models.ManyToManyField(Subscriber)\n\n def __str__(self): # __unicode__ on Python 2\n return self.name\n" }, { "alpha_fraction": 0.7617886066436768, "alphanum_fraction": 0.7894309163093567, "avg_line_length": 60.5, "blob_id": "7da3b42a8b29d4d4705935a38b211dc3e53981df", "content_id": "cffdce83c4f06267072f4ede836bf61cc18322fe", "detected_licenses": [ "CC-BY-4.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2582, "license_type": "permissive", "max_line_length": 450, "num_lines": 40, "path": "/README.md", "repo_name": "ricco386/zaciname-s-djangom", "src_encoding": "UTF-8", "text": "# ZAČÍNAME S DJANGOM\n\nÚvod do web programovania s [Django frameworkom](https://www.djangoproject.com/).\n\nProjekt bol vytvorený ako [prezentácia](https://ricco386.github.io/zaciname-s-djangom/) na Bratislavský [OSS víkend 2015](http://ossden.soit.sk/index.php/ossvikendmenu), updatnutý a prezentovaný na [Trinástom Bratislavskom Python Meetupe](https://2016.pycon.sk/sk/ba-13-meetup.html), [Kôlničke](https://www.facebook.com/events/1783622468543805/) a [Web UP #22](https://www.facebook.com/events/332957283982272/) v Žiline.\n\nPrednáška je určená pre ľudí, ktorí by chceli začať programovať v Djangu. Ale tiež pre ľudí, ktorí už programujú v iných jazykoch a radi by sa pozreli ako sa pracuje s jedným z najrozšírenejších Pythonových frameworkov.\n\n### Abstrakt\n\nPovieme si ako nainštalovať Django. Spravíme si jednoduchú aplikáciu, na ktorej si ukážeme dobré vlastnosti Djanga:\n\n* inštalácia v Linuxe\n* vytvorenie projektu a aplikácie\n* vytvorenie databázového modelu\n* vytvorenie admin rozhrania\n* vytvorenie views a templateov\n* vytvorenie formulára\n\nV čase poslednej prednášky bola aktuálna verzia Djanga 2.1.7, pričom na verziu 2.1 sa odkazujú linky v materiáli a na tejto verzii aj bol prezentovaný zdrojový kód v príkladoch. Prvá prezentácia bol na verzii Djanga 1.8\n\n### Ako ďalej?\n\nPrednáška iba načrtla možnosti, ktoré Django ponúka. Ak Vás zaujala a radi by ste sa venovali programovaniu s Django frameworkom ďalej, odporúčam sa pozrieť na [oficálnu dokumentáciu](https://docs.djangoproject.com/en/2.1/). Súčasťou dokumentácie je aj [návod](https://docs.djangoproject.com/en/2.1/intro/tutorial01/), pomocou ktorého môžete nadviazať na prednášku a podrobnejšie si prečítať o jednotlivých častiach, ktoré boli aj súčasťou prednášky.\n\n### Licencia\n\nZdrojové kódy k prednáške sú zverejnené pod 3-klauzulovou BSD Licenciou a prezentácia je zverejnená ako Creative Commons Attribution 4.0\n\n### Podpora\n\nPrednáška a vedomosti sú zadarmo (viď Licencia). Ak ma chcete podporiť pri tvorbe podobných prednášok, môžete ma pozvať na pivo (alebo kávu ;)\n\n[![Donate PayPal](https://img.shields.io/badge/Donate-PayPal-blue.svg)](https://paypal.me/ricco386)\n\n[![Donate Bitcoin](https://img.shields.io/badge/Donate-bitcoin-blue.svg)](https://tallyco.in/RicCo386/)\n\nPre pravidelnú podporu mojich aktivít v Open Source (hlavne Python) komunite: \n\n[![Recurring Donation](http://img.shields.io/liberapay/goal/RicCo.svg?logo=liberapay)](https://liberapay.com/RicCo/donate)\n" }, { "alpha_fraction": 0.5809859037399292, "alphanum_fraction": 0.5809859037399292, "avg_line_length": 30.66666603088379, "blob_id": "b10bd0a0e57fd966ad931d225e435182bf3fe792", "content_id": "e36ab1537cd9ae7cb59c77d92c0fcfab5fe1ba67", "detected_licenses": [ "CC-BY-4.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "permissive", "max_line_length": 56, "num_lines": 9, "path": "/konferencia/mailinglist/urls.py", "repo_name": "ricco386/zaciname-s-djangom", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom mailinglist import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('<int:list_id>/', views.mlist, name='mlist'),\n path('<int:list_id>/subscribe/', views.subscribe,\n name='subscribe'),\n]" } ]
6
duanrui1234/my
https://github.com/duanrui1234/my
3c220933dfe4088e4d966b8f72cfda4033a034bb
f0f55059523fed267be1f4ce8e70036e23475afb
e9149b5f549e38029b132e90f2745ae13a56193c
refs/heads/master
2021-06-27T09:16:41.743389
2021-02-22T06:18:45
2021-02-22T06:18:45
210,283,260
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.502212405204773, "alphanum_fraction": 0.5641592741012573, "avg_line_length": 42.774192810058594, "blob_id": "478cecebd78d5f8f141b5afdeb9015bfbd5359de", "content_id": "6b24f478e20b38dbc2260640cda75f690388860b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 434, "num_lines": 31, "path": "/spring-cloud-config.py", "repo_name": "duanrui1234/my", "src_encoding": "UTF-8", "text": "import requests\nimport os\nimport sys\n\nfile = str(sys.argv[1])\nwrite = sys.argv[2]\nreadfile = open(file , 'r' , encoding='UTF-8')\nwritefile = open(write , 'a')\nff = readfile.readlines()\n\ndef webhttp():\n for line in ff:\n try:\n line = line.rstrip(\"\\n\")\n payload = \"/..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252Fetc%252Fpasswd%23foo/development\"\n headers = {\"Upgrade-Insecure-Requests\": \"1\", \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\", \"Accept-Encoding\": \"gzip, deflate\", \"Accept-Language\": \"zh-CN,zh;q=0.9\", \"Connection\": \"close\"}\n url = line + payload\n print(url)\n req = requests.get(url,headers=headers, verify=False, timeout=5)\n status = req.status_code\n print(req.text)\n if 'root:x' in req.text and status == 200:\n print(url+\" -------------存在漏洞-------------\")\n writefile.write(url)\n writefile.write('\\n')\n else :\n print(url+\" 不存在漏洞\")\n pass\n except OSError:\n pass\nwebhttp()" }, { "alpha_fraction": 0.3636363744735718, "alphanum_fraction": 0.3636363744735718, "avg_line_length": 4.5, "blob_id": "e28ee9a73d49ed063ec9c6236881ccc971e43829", "content_id": "9eb8e88d3b9304103099e5ab0f3bc3104f4329c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 22, "license_type": "no_license", "max_line_length": 7, "num_lines": 4, "path": "/README.md", "repo_name": "duanrui1234/my", "src_encoding": "UTF-8", "text": "# my\n##my\n**aaa**\n*a*\n" } ]
2
heyunyan19930924/RPCA
https://github.com/heyunyan19930924/RPCA
766d4695a4ead91e1b2897ec8a06d590eb905fea
4625fee39fcae7644cd056835c305894a1c11aac
7c21084b74008f91ca1e5055767a31c886497cae
refs/heads/master
2020-07-01T19:49:31.592822
2019-08-08T15:05:21
2019-08-08T15:05:21
201,279,395
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6458333134651184, "alphanum_fraction": 0.647988498210907, "avg_line_length": 80.88235473632812, "blob_id": "42813a17305d7c9a133cc358503a90bd3560855f", "content_id": "ec5435d362f32d5c22583fcf7183eabe7fba9a89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1392, "license_type": "no_license", "max_line_length": 287, "num_lines": 17, "path": "/README.md", "repo_name": "heyunyan19930924/RPCA", "src_encoding": "UTF-8", "text": "# RPCA\nRPCA image processing\nRobust Principal Component Analysis (RPCA) is a modification of classical PCA that enhances the robustness against corrupted observations.\nRPCA decomposes data matrix M into two parts, M = L + S, where L usually has a lower rank, and S is sparse and contains noise and outliers.\nWhile the low rank matrix L helps learning the data property and can be used for dimension reduction, the sparse matrix S provides information about anomalies\n\nThis work contains image processing pipeline that does image foreground extraction and defect detection using RPCA on CAS server. \n\nPipeline: \n1. Read in image data (LOADIMAGES) -> process images (PROCESSIMAGES) -> convert images into one table (FLATTENIMAGETABLE).\n\n2. Apply RPCA on table. Foreground information contained in S matrix. CAS memory issue may occur if image table is too large. Solution: Resize images/ train on one part, score on the other.\n\n3. Convert table back to a list of images (CONDENSEIMAGES) -> Export images (SAVEIMAGES)\n\nRequirements: \nNeed to connect to cas server and is able to get access to actionsets including 'images', 'robustPCA', etc.\n" }, { "alpha_fraction": 0.655811607837677, "alphanum_fraction": 0.6758517026901245, "avg_line_length": 36.42307662963867, "blob_id": "e3f03c4b591cf5642e3cce2de34c6e9751543191", "content_id": "049cf5ef2c7d122d3fe241db4d639c810e334a09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1996, "license_type": "no_license", "max_line_length": 157, "num_lines": 52, "path": "/uploadArrayAsCastable.py", "repo_name": "heyunyan19930924/RPCA", "src_encoding": "UTF-8", "text": "'''\r\nManipulate downloaded castable locally and upload to castable again.\r\n'''\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport swat.cas.datamsghandlers as dmh\r\n\r\n# Before uploading, Make sure the numeric data are in correct format, for example float, int etc., not 'object' \r\n\r\n# Function that converts columns into numeric datatype.\r\n# Convert column by column. Inefficient when column number is huge.\r\ndef coerce_df_columns_to_numeric(df, column_list):\r\n df[column_list] = df[column_list].apply(pd.to_numeric, errors='ignore')\r\n\r\n# Function that upload dataframe to CAS server as CAStable.\r\ndef convert_dataframe_to_castable(df, output):\r\n handler = dmh.PandasDataFrame(df)\r\n myCAS.addtable(table=output, replace = True, **handler.args.addtable)\r\n \r\n# Did some modification to numerical data\r\ntarget_dataframe = lowrank\r\nmapped = target_dataframe.values[:,1:]\r\nmapped = mapped.astype(np.float)\r\n#mapped[:,:-1] = np.clip(mapped[:,:-1], 0, 255)\r\nmapped += np.min(mapped)\r\n\r\n# Initialize column list as input when initializing dataframe.\r\ncol_name = ['c'+str(x) for x in range(1, image_width*image_height+2)]\r\ncol_name[-1] = '_outlier_detection_score_'\r\ndf = pd.DataFrame(mapped, columns = col_name)\r\ndf['_path_'] = lowrank['_path_']\r\nconvert_dataframe_to_castable(df, 'score_lowrank_mapped')\r\nmapped_castable = myCAS.fetch(table={\"name\":\"mat_score_lowrank_mapped\"})['Fetch']\r\n\r\n# Plot mapped image\r\nmyCAS.condenseImages(\r\n casout={\"name\":\"scored_images\", \"replace\":True},\r\n width = image_width,\r\n\t\theight = image_height,\r\n #copyvars = {\"_path_\"},\r\n numberOfChannels='GRAY_SCALE_IMAGE',\r\n table = {\"name\" : \"score_lowrank_mapped\", \"where\" :'_path_=\\\"/u/yunhe/GSK_data/HubAngle_for_RPCA/5015#087967904_S207_HubAngle.20170901-000004.jpg\\\"'}\r\n )\r\n\r\nmyCAS.saveImages(\r\n caslib = \"CASUSER\",\r\n subDirectory = 'GSK_data/background',\r\n\t\timages={\"table\":\"scored_images\"},\r\n type = 'jpg',\r\n\t\tprefix = 'mapped_add_all'\r\n )" }, { "alpha_fraction": 0.49982741475105286, "alphanum_fraction": 0.6199516654014587, "avg_line_length": 50.6363639831543, "blob_id": "03403d77a149ec16f917c715c8646843c3526380", "content_id": "d15cd7c529b1665a00b1b5c4644f2a0a841906f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2897, "license_type": "no_license", "max_line_length": 175, "num_lines": 55, "path": "/precision.py", "repo_name": "heyunyan19930924/RPCA", "src_encoding": "UTF-8", "text": "'''\r\nFunction that calculates accuracy, precision, recall from comparing scoring output with hand labeled negatives\r\nEnter negatives in <defects>\r\n'''\r\n\r\nimport numpy as np\r\n# Input index of defects\r\ndefects = set()\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017443052_S207_HubAngle.20170901-005747.jpg')\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017445399_S207_HubAngle.20170901-015203.jpg')\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017445887_S207_HubAngle.20170901-020239.jpg')\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017446005_S207_HubAngle.20170901-020455.jpg')\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017455497_S207_HubAngle.20170901-053954.jpg')\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017457231_S207_HubAngle.20170901-081732.jpg')\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017458092_S207_HubAngle.20170901-084024.jpg')\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017459688_S207_HubAngle.20170901-101026.jpg')\r\ndefects.add('/u/yunhe/GSK_data/scoring/5026#017454100_S207_HubAngle.20170901-050721.jpg')\r\n \r\n# Output is a 5*5 table with row: para1 and col: para2 and entries of triples. First element shows number of anomalies. Second: precision (TP/ALL P). Third: recall (TP/ALL T).\r\n# TFmatrix stores TP, TN, FP, FN\r\n# accuracy stores accuracy and F1-measure\r\nnum_para1, num_para2 = len(parameter_list_1), len(parameter_list_2)\r\nnum_total_sample = len(outlier_result_store[0][0])\r\nt = len(defects)\r\nADmatrix = np.zeros((num_para1, num_para2,3))\r\nTFmatrix = np.zeros((num_para1, num_para2,4)) \r\naccuracy = np.zeros((num_para1, num_para2,2)) \r\nfor i in range(num_para1):\r\n for j in range(num_para2):\r\n num_TP,num_FP,num_TN,num_FN = 0, 0, 0, 0\r\n if (type(outlier_result_store[i][j][0,1]) == float):\r\n ADmatrix[i,j,0] = np.count_nonzero(outlier_result_store[i][j][:,1])\r\n num_TP = 0\r\n for p in outlier_result_store[i][j]:\r\n if ((p[0] in defects) & (p[1] == 1.0)):\r\n num_TP += 1\r\n ADmatrix[i,j,1] = num_TP*1.0/(ADmatrix[i,j,0]*1.0)\r\n ADmatrix[i,j,2] = num_TP*1.0/(t*1.0)\r\n else:\r\n ADmatrix[i,j,0] = np.count_nonzero(outlier_result_store[i][j][:,0])\r\n num_TP = 0\r\n for p in outlier_result_store[i][j]:\r\n if ((p[1] in defects) & (p[0] == 1.0)):\r\n num_TP += 1\r\n ADmatrix[i,j,1] = num_TP*1.0/(ADmatrix[i,j,0]*1.0)\r\n ADmatrix[i,j,2] = num_TP*1.0/(t*1.0)\r\n num_FP = ADmatrix[i,j,0] - num_TP\r\n num_TN = t - num_TP\r\n num_FN = num_total_sample - num_TP - num_FP - num_TN\r\n TFmatrix[i,j,0] = num_TP\r\n TFmatrix[i,j,1] = num_FP\r\n TFmatrix[i,j,2] = num_TN\r\n TFmatrix[i,j,3] = num_FN\r\n accuracy[i,j,0] = (num_TP + num_FN) / num_total_sample\r\n accuracy[i,j,1] = 2/(1/ADmatrix[i,j,1] + 1/ADmatrix[i,j,2])\r\n\r\n" }, { "alpha_fraction": 0.5749926567077637, "alphanum_fraction": 0.5859994292259216, "avg_line_length": 32.25125503540039, "blob_id": "c4ab2694728ba1276d919dea3df72b56e08784d1", "content_id": "d95ea630122d798cddd1889e2ab2e9006138143f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6814, "license_type": "no_license", "max_line_length": 196, "num_lines": 199, "path": "/processImageData.py", "repo_name": "heyunyan19930924/RPCA", "src_encoding": "UTF-8", "text": "'''\r\nPython pipeline to Process image data and generate foreground/background images. \r\n'''\r\n\r\nmyCAS.loadactionset(actionset=\"robustPca\")\r\nmyCAS.loadactionset(actionset=\"dataStep\")\r\nmyCAS.loadactionset(actionset=\"image\")\r\nmyCAS.loadactionset(actionset=\"astore\")\r\nimport pandas as pd\r\n\r\nimage_path = 'path_training_images'\r\nscoring_image_path = 'path_scoring_images'\r\n# Enter resolution information of images. orig_image: original image resolution. cropped_: cropping coordinate info. image_: final resolution after resizing. \r\norig_image_width, orig_image_height = 720, 1280\r\ncropped_width = 440\r\ncropped_height = 1280\r\nimage_width = 220\r\nimage_height = 640\r\n\r\n# Reading pictures from image_path and load to CAS server.\r\nmyCAS.loadImages(\r\n path= image_path,\r\n casOut={\"name\":\"gray_table_s\", \"replace\":True},\r\n decode=False,\r\n recurse=False\r\n )\r\n\r\n# Changing color images to gray scale.\r\nmyCAS.processImages(\r\n casout={\"name\":'gray_table_s', \"replace\":True}, \r\n \timagefunctions=[#{\"functionOptions\":{\"functiontype\":\"CONVERT_COLOR\", \"type\": \"COLOR2GRAY\"}},\r\n {\"functionOptions\":{\"functiontype\":\"GET_PATCH\", \"width\": cropped_width, \"height\": cropped_height, \"x\": orig_image_width-cropped_width, \"y\": orig_image_height-cropped_height}},\r\n {\"functionOptions\":{\"functiontype\":\"RESIZE\", \"width\": image_width, \"height\": image_height}},],\r\n \tdecode = True,\r\n \ttable={\"name\":\"gray_table_s\"}\r\n )\r\n\r\n# Make flat table (number_of_obs, number_of_pixels)\r\nmyCAS.flattenImageTable(\r\n casout={\"name\":'gray_table_s', \"replace\":True},\r\n \ttable={\"name\":'gray_table_s'},\r\n \twidth = image_width,\r\n\t\theight = image_height\r\n )\r\n\r\n# Run this line of code if image dimension changed.\r\n# We don't run this! Just change the RPCA working columns.\r\n'''\r\nmyCAS.runCode(\r\n code=\"\"\"data working_table; \r\n set gray_table_t; \r\n keep _path_ c1-c1536304; \r\n run;\r\n \"\"\"\r\n )\r\n'''\r\n\r\n# Image has already been converted to working table. Now let's do RPCA!\r\ntable_name = 'gray_table_s'\r\n# Create working column name list\r\ncol_name = ['c'+str(x) for x in range(1, image_width*image_height+1)]\r\n_lambdaWeight=1\r\n_cumEigPctTol=1\r\nmyCAS.loadactionset(actionset=\"robustPca\")\r\nRPCAresult = myCAS.robustPca(\r\n table={\"name\" : table_name},\r\n id={\"_path_\"},\r\n method=\"ALM\",\r\n decomp=\"svd\", \r\n scale=False, \r\n center=True,\r\n #inputs=col_name,\r\n cumEigPctTol=_cumEigPctTol,\r\n lambdaWeight=_lambdaWeight,\r\n #svdMethod=\"RANDOM\",\r\n saveState={\"name\":\"store\", \"replace\":True}, \r\n outmat={\"sparseMat\":{\"name\":\"gray_table_s\", \"replace\":True}},\r\n #\"lowrankMat\":{\"name\":\"lowrankmat\", \"replace\":True}, \r\n anomalyDetection=True,\r\n anomalyDetectionMethod=0, # 0 : SIGVAR method; 1: R4S methods\r\n sigmaCoef=1, # Threshold to identify an observation to be outlier\r\n numSigVars=1, # SIGVAR ONLY: Number of outliers for data to be identified as anomaly\r\n useMatrix=False # False: Use standard deviation of original data True: Use standard deviation of sparse data \r\n)\r\nrank = RPCAresult['Summary']['Value'][1]\r\n#sparsemat = myCAS.fetch(table={\"name\":\"sparsemat\"}, to=100000, maxrows = 100000)['Fetch']\r\n#sparsemat.to_csv(\"sparse_mat_lambdaweight_0.5_rank_253.csv\", index=False)\r\n\r\n###################################### Output processed images #####################################################\r\n'''\r\nmyCAS.runCode(\r\n code=\"\"\"data scoredw;\r\n\t\t\t \tset scored;\r\n\t\t\t\tname_mod = cats(_name_,'.jpg');\r\n\t\t\t\tlength 'nm'n varchar(25) ;\r\n format 'nm'n $CHAR25. ;\r\n 'nm'n= PUT('name_mod'n,$CHAR25.);\r\n\t\t\t\trun ;\r\n\t\t\t\t\"\"\"\r\n )\r\n'''\r\n\r\n# Generating image table for output.\r\n# foreground\r\n# Extract file name as row index. Concatenate from the full path.\r\nmyCAS.dataStep.runCode(\r\n code=\"\"\"data sparsemat_new; \r\n set gray_table_s;\r\n name = substr(_path_,length(_path_)-13, 14);\r\n run ;\"\"\"\r\n )\r\n\r\nmyCAS.condenseImages(\r\n casout={\"name\":\"sparsemat_new\", \"replace\":True},\r\n width = image_width,\r\n\t\theight = image_height,\r\n copyvars = {\"name\"},\r\n numberOfChannels='COLOR_IMAGE',\r\n table = {\"name\" : \"sparsemat_new\"}\r\n )\r\n\r\nmyCAS.saveImages(\r\n caslib = \"CASUSER\",\r\n subDirectory = 'bees/colored_rank'+str(rank),\r\n\t\timages={\"table\":\"sparsemat_new\", \"path\":\"name\"},\r\n type = 'jpg',\r\n\t\tprefix = ''\r\n )\r\n\r\n################################### Scoring ###################################################\r\nmyCAS.loadImages(\r\n path= scoring_image_path,\r\n casOut={\"name\":\"gray_table_s\", \"replace\":True},\r\n decode=False,\r\n recurse=False\r\n )\r\n\r\n# Changing color images to gray scale.\r\nmyCAS.processImages(\r\n casout={\"name\":'gray_table_s', \"replace\":True}, \r\n \timagefunctions=[#{\"functionOptions\":{\"functiontype\":\"CONVERT_COLOR\", \"type\": \"COLOR2GRAY\"}},\r\n {\"functionOptions\":{\"functiontype\":\"GET_PATCH\", \"width\": cropped_width, \"height\": cropped_height, \"x\": orig_image_width-cropped_width, \"y\": orig_image_height-cropped_height}},\r\n {\"functionOptions\":{\"functiontype\":\"RESIZE\", \"width\": image_width, \"height\": image_height}},],\r\n \tdecode = True,\r\n \ttable={\"name\":\"images_s\"}\r\n )\r\n\r\n# Make flat table (number_of_obs, number_of_pixels)\r\nmyCAS.flattenImageTable(\r\n casout={\"name\":'gray_table_s', \"replace\":True},\r\n \ttable={\"name\":'gray_table_s'},\r\n \twidth = image_width,\r\n\t\theight = image_height\r\n )\r\n\r\nscoring_table_name = 'gray_table_s'\r\n\r\n# Score on the store file from training.\r\n# Projection type 1: background. 2: foreground\r\nSCOREresult = myCAS.score(\r\n table={\"name\" : scoring_table_name},\r\n options=[{\"name\":\"RPCA_PROJECTION_TYPE\",\"value\":2}],\r\n rstore={\"name\":\"store\"}, \r\n out={\"name\":\"gray_table_s\",\"replace\":True}\r\n )\r\n\r\n# Remove anomaly detection results column\r\nmyCAS.runCode(\r\n code=\"\"\"data gray_table_s (drop = _outlier_detection_score_); \r\n set gray_table_s; \r\n run;\r\n \"\"\"\r\n )\r\n\r\nmyCAS.runCode(\r\n code=\"\"\"\r\n data working_table; \r\n set gray_table_s;\r\n name = substr(_path_,length(_path_)-13, 14);\r\n run;\r\n \"\"\"\r\n )\r\n\r\nmyCAS.condenseImages(\r\n casout={\"name\":\"working_table\", \"replace\":True},\r\n width = image_width,\r\n\t\theight = image_height,\r\n copyvars = {\"name\"},\r\n numberOfChannels='COLOR_IMAGE',\r\n table = {\"name\" : \"working_table\"}\r\n )\r\n\r\nmyCAS.saveImages(\r\n caslib = \"CASUSER\",\r\n subDirectory = 'bees/colored_rank'+str(rank),\r\n\t\timages={\"table\":\"working_table\", \"path\":\"name\"},\r\n type = 'jpg',\r\n\t\tprefix = ''\r\n )" }, { "alpha_fraction": 0.591936469078064, "alphanum_fraction": 0.5949908494949341, "avg_line_length": 32.87234115600586, "blob_id": "96f78a22c6fbad294a3e57d61d1309d7f3647704", "content_id": "8306a51f8043a921910c5cb5f8706851174b6ba6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1637, "license_type": "no_license", "max_line_length": 135, "num_lines": 47, "path": "/image_table_convert.py", "repo_name": "heyunyan19930924/RPCA", "src_encoding": "UTF-8", "text": "'''\r\nPython pipeline to import images to cas and convert images into table. \r\n'''\r\nmyCAS.loadactionset(actionset=\"image\")\r\n\r\ndef convert_image_to_table(image_path, image_height, image_weight, table_name):\r\n myCAS.loadImages(\r\n path= image_path,\r\n casOut={\"name\":\"images_t\", \"replace\":True},\r\n decode=False,\r\n recurse=False\r\n )\r\n\r\n# Changing color images to gray scale.\r\n myCAS.processImages(\r\n casout={\"name\":table_name, \"replace\":True}, \r\n \timagefunctions=[{\"functionOptions\":{\"functiontype\":\"CONVERT_COLOR\", \"type\": \"COLOR2GRAY\"}},\r\n {\"functionOptions\":{\"functiontype\":\"GET_PATCH\", \"width\": image_width, \"height\": image_height, \"x\": 0, \"y\": 290}}],\r\n \tdecode = True,\r\n \ttable={\"name\":\"images_t\"}\r\n )\r\n\r\n# Make flat table (number_of_obs, number_of_pixels)\r\n myCAS.flattenImageTable(\r\n casout={\"name\":'gray_table_t', \"replace\":True },\r\n \ttable={\"name\":'gray_images_t'},\r\n \twidth = image_width,\r\n\t\theight = image_height\r\n )\r\n \r\ndef convert_table_to_image(table_name, image_label, output_dir, output_name, output_format, image_height, image_width):\r\n myCAS.condenseImages(\r\n casout={\"name\":\"scored_images\", \"replace\":True},\r\n width = image_width,\r\n\t\theight = image_height,\r\n #copyvars = {\"_path_\"},\r\n numberOfChannels='GRAY_SCALE_IMAGE',\r\n table = {\"name\" : table_name, \"where\" :image_label}\r\n )\r\n\r\nmyCAS.saveImages(\r\n caslib = \"CASUSER\",\r\n subDirectory = output_dir,\r\n\t\timages={\"table\":\"scored_images\"},\r\n type = output_format,\r\n\t\tprefix = output_name\r\n )" }, { "alpha_fraction": 0.5816636085510254, "alphanum_fraction": 0.5980570912361145, "avg_line_length": 38.85123825073242, "blob_id": "95926ff1e2ccbeb0bbda357dc03895347828b30e", "content_id": "265b8866e8685c05fed5e6e7460bb325e2bcbd2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4941, "license_type": "no_license", "max_line_length": 161, "num_lines": 121, "path": "/coord_formated.py", "repo_name": "heyunyan19930924/RPCA", "src_encoding": "UTF-8", "text": "'''\r\nRead image table. Save bees coordinate output into format for Brad to feed into ESP.\r\nThe format is:\r\n Each row represents each observation. Column labels: opcode\tflags(ESP settings) _id_(image id) _image_(image 64bit code)\t_nObjects_(number of objects)\r\n\t_Object0_(object id) P_Object0_(probability) _Object0_x\t_Object0_y(object left lower coordinate) _Object0_width\t_Object0_height(object width and height)\r\n Then other objects. Repeat the columns for objects\r\n'''\r\n\r\nmyCAS.loadactionset(actionset=\"image\")\r\nimport pandas as pd\r\nimport shutil\r\nimport numpy as np\r\nnp.set_printoptions(threshold=sys.maxsize)\r\nimport base64\r\n\r\ndef detect_bee_boundingbox(image, size_threshold):\r\n def dfs(image, row, col):\r\n nonlocal size, output_coord, visited, n\r\n global direction\r\n index = row*n + col\r\n if index not in visited and image[row][col] > 0:\r\n visited.add(index)\r\n size += 1\r\n output_coord[0] = min(output_coord[0], row)\r\n output_coord[1] = min(output_coord[1], col)\r\n output_coord[2] = max(output_coord[2], row)\r\n output_coord[3] = max(output_coord[3], col)\r\n for i in range(len(direction)):\r\n cur_row = row + direction[i][0]\r\n cur_col = col + direction[i][1]\r\n if cur_row < 0 or cur_row >= m or cur_col < 0 or cur_col >= n:\r\n continue;\r\n dfs(image, cur_row, cur_col)\r\n \r\n m,n = image.shape\r\n visited = set([])\r\n output = []\r\n # entry at (i,j) is represented by index i*n+j\r\n for i in range(m):\r\n for j in range(n):\r\n index = i*n+j\r\n if (index in visited or image[i][j] == 0):\r\n continue\r\n size = 0\r\n output_coord = [i,j,i,j]\r\n dfs(image, i, j)\r\n if (size >= size_threshold):\r\n to_add = set([x*n+y for x in range(output_coord[0], output_coord[2]+1) for y in range(output_coord[1], output_coord[3]+1)])\r\n visited |= to_add\r\n output.append(output_coord) # Track the output by array of form lrow, lcol, rrow, rcol \r\n return output\r\n\r\ndef generate_search_list(dim):\r\n toReturn = []\r\n for i in range(1,dim+1):\r\n for j in range(i+1):\r\n toReturn.append([j, i])\r\n for j in range(-i, i):\r\n toReturn.append([i, j])\r\n return toReturn\r\n\r\n# Convert original format [x_upperleft, y_upperleft, x_lowerright, y_lowerright] to Brad's format [ObjectID, P_Object, x_lowerleft, y_lowerleft, width, height]. \r\ndef convert_format(coord):\r\n output = []\r\n for bee_coords in coord:\r\n bee_formated = ['bee',1,bee_coords[2], bee_coords[1], bee_coords[3]-bee_coords[1], bee_coords[2]-bee_coords[0]]\r\n output.extend(bee_formated)\r\n return output\r\n\r\nimage_width = 220\r\nimage_height = 640\r\n# Read image table\r\nimages = pd.read_csv(\"data_matrix.csv\")\r\nimages.pop('Unnamed: 0')\r\n\r\n# Parameters to be tweaked.\r\ncolor_threshold = 25\r\nsize_threshold = 30\r\nsearch_dim = 3\r\ndirection = generate_search_list(search_dim)\r\n\r\n# Output original format.\r\noutput = []\r\nfor i in range(len(images)):\r\n if (i%100 == 0):\r\n print('working on image '+str(i))\r\n image_data = images.iloc[i,1:].values\r\n image_data = image_data.reshape(image_height, image_width)\r\n image_data[image_data < color_threshold] = 0\r\n image_name = images['_path_'][i][-14:]\r\n current_output = (image_name,detect_bee_boundingbox(image_data, size_threshold))\r\n output.append(current_output)\r\n\r\n# Convert original output format to Brad's format row by row.\r\nimage_file_path = 'cropped/foreground_rank823/'\r\nnum_rows = len(output)\r\nmax_num_object = 0\r\nformated = []\r\nfor i in range(6, num_rows - 6):\r\n _id_ = np.int64(i)\r\n filename = output[i][0]\r\n with open(image_file_path + filename, \"rb\") as image_file:\r\n _image_ = base64.b64encode(image_file.read()).decode('utf8')\r\n _nObjects_ = len(output[i][1])\r\n formated_coord = convert_format(output[i][1])\r\n # If number of bees exceeds df column numbers, we need to expand df variable names\r\n max_num_object = max(max_num_object, len(output[i][1]))\r\n to_append = [_id_, _image_, _nObjects_]\r\n to_append.extend(formated_coord)\r\n formated.append(to_append)\r\n \r\n# Create column names\r\ncol_names = ['_id_','_image_','_nObjects_']\r\nfor i in range(max_num_object):\r\n col_names.extend(['_Object'+str(i)+'_', 'P_Object'+str(i)+'_', '_Object'+str(i)+'_x',\r\n '_Object'+str(i)+'_y', '_Object'+str(i)+'_width', '_Object'+str(i)+'_height'])\r\ndf = pd.DataFrame(formated, columns = col_names)\r\ndf.insert(loc = 0, column = 'opcode', value = 'I')\r\ndf.insert(loc = 1, column = 'flags', value = 'N')\r\n# Save to .csv file\r\ndf.to_csv('bee_position_color_'+str(color_threshold)+'_size_'+str(size_threshold)+'searchdim_' + str(search_dim)+'.csv', index = False)" }, { "alpha_fraction": 0.543788492679596, "alphanum_fraction": 0.5577784180641174, "avg_line_length": 39.569766998291016, "blob_id": "a1ece163a8a74030702600bd3fc3f78a0d32cf4f", "content_id": "d644cd080ac1fcddaa2e1f481d084d35e9828b55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7148, "license_type": "no_license", "max_line_length": 177, "num_lines": 172, "path": "/beeLocation.py", "repo_name": "heyunyan19930924/RPCA", "src_encoding": "UTF-8", "text": "'''\r\nDetect bee coordinate box by detecting bright clusters. \r\nThe idea was first filter out all dim pixels, then count connected bright components. Drop all components which have less area than size_threshold. It is not a learning process.\r\n'''\r\n\r\n# After promoting the table in SAS\r\nmyCAS.loadactionset(actionset=\"image\")\r\nimport pandas as pd\r\nimport shutil\r\nimport numpy as np\r\nnp.set_printoptions(threshold=sys.maxsize)\r\n\r\nimage_width = 220\r\nimage_height = 640\r\nimage_path = 'bees/foreground_rank823'\r\n\r\n# Reading pictures from image_path and load to CAS server.\r\nmyCAS.loadImages(\r\n path= image_path,\r\n casOut={\"name\":\"images_s\", \"replace\":True},\r\n decode=False,\r\n recurse=False\r\n )\r\n\r\n# Changing color images to gray scale.\r\nmyCAS.processImages(\r\n casout={\"name\":'gray_images_s', \"replace\":True}, \r\n \timagefunctions=[{\"functionOptions\":{\"functiontype\":\"CONVERT_COLOR\", \"type\": \"COLOR2GRAY\"}}],\r\n #{\"functionOptions\":{\"functiontype\":\"MUTATIONS\", \"type\": \"LIGHTEN\"}},\r\n #{\"functionOptions\":{\"functiontype\":\"RESIZE\", \"width\": image_width, \"height\": image_height}},],\r\n \tdecode = True,\r\n \ttable={\"name\":\"images_s\"}\r\n )\r\n\r\nmyCAS.flattenImageTable(\r\n casout={\"name\":'gray_table_s', \"replace\":True},\r\n \ttable={\"name\":'gray_images_s'},\r\n \twidth = image_width,\r\n\t\theight = image_height\r\n )\r\n\r\n###################################### Main function to detect bees by detecting bright clusters ############################################\r\n# New version that detects multiple adjacent pixels. Number of pixels are to be specified in the global variable \"direction\"\r\ndef detect_bee_boundingbox(image, size_threshold):\r\n # DFS for each bright cluster until all its bright neighbors are traversed.\r\n def dfs(image, row, col):\r\n nonlocal size, output_coord, visited, n\r\n global direction\r\n index = row*n + col\r\n if index not in visited and image[row][col] > 0:\r\n visited.add(index)\r\n size += 1\r\n output_coord[0] = min(output_coord[0], row)\r\n output_coord[1] = min(output_coord[1], col)\r\n output_coord[2] = max(output_coord[2], row)\r\n output_coord[3] = max(output_coord[3], col)\r\n for i in range(len(direction)):\r\n cur_row = row + direction[i][0]\r\n cur_col = col + direction[i][1]\r\n if cur_row < 0 or cur_row >= m or cur_col < 0 or cur_col >= n:\r\n continue;\r\n dfs(image, cur_row, cur_col)\r\n \r\n m,n = image.shape\r\n visited = set([])\r\n output = []\r\n # entry at (i,j) is represented by index i*n+j\r\n for i in range(m):\r\n for j in range(n):\r\n index = i*n+j\r\n if (index in visited or image[i][j] == 0):\r\n continue\r\n size = 0\r\n output_coord = [i,j,i,j]\r\n dfs(image, i, j)\r\n # If cluster size smaller than size_threshold, ignore the threshold. Or add bounding box to output and add all pixels in bounding box to \"visited\" \r\n if (size >= size_threshold):\r\n # Set all pixels in the bounding box to \"visited\"\r\n to_add = set([x*n+y for x in range(output_coord[0], output_coord[2]+1) for y in range(output_coord[1], output_coord[3]+1)])\r\n visited |= to_add\r\n output.append(output_coord) # Track the output by array of form lrow, lcol, rrow, rcol \r\n return output\r\n\r\ndef detect_bee_boundingbox_V2(image, size_threshold):\r\n def dfs(image, row, col):\r\n nonlocal size, output_coord, visited, n\r\n global direction\r\n index = row*n + col\r\n if index not in visited and image[row][col] > 0:\r\n visited.add(index)\r\n size += 1\r\n output_coord[0] = min(output_coord[0], row)\r\n output_coord[1] = min(output_coord[1], col)\r\n output_coord[2] = max(output_coord[2], row)\r\n output_coord[3] = max(output_coord[3], col)\r\n for i in range(len(direction)):\r\n cur_row = row + direction[i][0]\r\n cur_col = col + direction[i][1]\r\n if cur_row < 0 or cur_row >= m or cur_col < 0 or cur_col >= n:\r\n continue;\r\n dfs(image, cur_row, cur_col)\r\n \r\n m,n = image.shape\r\n visited = set([])\r\n output = []\r\n # entry at (i,j) is represented by index i*n+j\r\n for i in range(m):\r\n for j in range(n):\r\n index = i*n+j\r\n if (index in visited or image[i][j] == 0):\r\n continue\r\n size = 0\r\n output_coord = [i,j,i,j]\r\n dfs(image, i, j)\r\n if (size >= size_threshold):\r\n output.append(output_coord) # Track the output by array of form lrow, lcol, rrow, rcol \r\n return output\r\n\r\n# Generate search directions based on how many adjacent pixels to be searched. \r\ndef generate_search_list(dim):\r\n toReturn = []\r\n for i in range(1,dim+1):\r\n for j in range(i+1):\r\n toReturn.append([j, i])\r\n for j in range(-i, i):\r\n toReturn.append([i, j])\r\n return toReturn\r\n\r\n############################## Test ##########################################################################\r\nimages = myCAS.fetch(table={\"name\":\"gray_table_s\"}, to = 10, maxRows = 10)['Fetch']\r\n\r\ncolor_threshold = 15\r\nsize_threshold = 30\r\n\r\nimage_index = 1401\r\n#images = images.iloc[:,0:image_width*image_height+1]\r\nimage_data = images.iloc[image_index,1:].values\r\nimage_name = images['_path_'][image_index][-14:]\r\nimage_data = image_data.reshape(image_height, image_width)\r\nimage_data[image_data < color_threshold] = 0\r\n\r\ndetect_bee_boundingbox(image_data, size_threshold)\r\n\r\n#################################### Full run ##############################################################\r\n\r\ncolor_threshold = 20\r\nsize_threshold = 30\r\nsearch_dim = 3\r\ndirection = generate_search_list(search_dim)\r\ncol_labels = ['c' + str(idx) for idx in range (0, image_width*image_height+1)]\r\ncol_labels[0] = \"_path_\"\r\n\r\nimages = myCAS.fetch(table={\"name\":\"gray_table_s\", \"vars\":col_labels}, to = 100000, maxRows = 100000, sortBy={\"name\":\"_path_\"}, )['Fetch']\r\n# Or read existing data from local\r\nimages = pd.read_csv(\"data_matrix.csv\")\r\nimages.pop('Unnamed: 0')\r\n\r\noutput = []\r\nfor i in range (len(images)):\r\n if (i%100 == 0):\r\n print('working on image '+str(i))\r\n image_data = images.iloc[i,1:].values\r\n image_data = image_data.reshape(image_height, image_width)\r\n # Set all pixels that has lower value than color_threshold to 0.\r\n image_data[image_data < color_threshold] = 0\r\n image_name = images['_path_'][i][-14:]\r\n current_output = (image_name,detect_bee_boundingbox(image_data, size_threshold))\r\n output.append(current_output)\r\n\r\n# Write output into .txt file\r\nwith open('bee_position_color_'+str(color_threshold)+'_size_'+str(size_threshold)+'searchdim_' + str(search_dim)+'.txt', 'w') as fp:\r\n fp.write('\\n'.join('%s : %s' % x for x in output))" }, { "alpha_fraction": 0.6144440174102783, "alphanum_fraction": 0.6308750510215759, "avg_line_length": 36.485294342041016, "blob_id": "780e877d48ade5e2b6d7899537433cb40c9dbe5f", "content_id": "2501a0fcd4a880826281992ceac2d19c3205b0cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2617, "license_type": "no_license", "max_line_length": 131, "num_lines": 68, "path": "/RPCApipeline.py", "repo_name": "heyunyan19930924/RPCA", "src_encoding": "UTF-8", "text": "'''\r\nPython RPCA pipeline \r\n'''\r\n\r\nfrom swat import *\r\nmyCAS = CAS('rdcgrd098', 33836, 'yunhe')\r\nimport swat.datamsghandlers as dmh\r\n\r\ndata_file = '10_Preprocessed' # File name\r\nfull_path = 'U:\\\\weather_data/RaleighAirport_01/'+data_file+'.csv'\r\n\r\n# First need to copy data to U:\\\r\ndef read_file_cvs(data_path):\r\n handler=dmh.CSV(data_path, skipinitialspace=True) \r\n myCAS.addtable(table=data_file, replace=True, **handler.args.addtable)\r\n LoadedTable=myCAS.fetch(table=data_file)\r\n print(LoadedTable)\r\n\r\n# Upload data to CAS for later actions\r\nread_file_cvs(full_path)\r\n# Run RPCA\r\nmyCAS.loadactionset(actionset=\"robustPca\")\r\nresult=myCAS.robustPca(\r\n table={\"name\" : data_file},\r\n id={\"STATION\", \"NAME\", \"DATE\"},\r\n method=\"ALM\",\r\n decomp=\"svd\", \r\n scale=True, \r\n center=True,\r\n #cumEigPctTol=0.99,\r\n lambdaWeight=1.06,\r\n saveState={\"name\":\"store\", \"replace\":True}, \r\n outmat={\"lowrankMat\":{\"name\":\"lowrankmat\", \"replace\":True}, \r\n \"sparseMat\":{\"name\":\"sparsemat\", \"replace\":True}},\r\n outsvd={\"svdleft\":{\"name\":\"svdleft\", \"replace\":True}, \r\n \"svddiag\":{\"name\":\"svddiag\", \"replace\":True},\r\n \"svdright\":{\"name\":\"svdright\", \"replace\":True}},\r\n anomalyDetection=True,\r\n anomalyDetectionMethod=1, # 0 : SIGVAR method; 1: R4S methods\r\n sigmaCoef=1, # Threshold to identify an observation to be outlier\r\n numSigVars=1, # SIGVAR ONLY: Number of outliers for data to be identified as anomaly\r\n useMatrix=False # False: Use standard deviation of original data True: Use standard deviation of sparse data \r\n)\r\n\r\nscore_path = 'U:\\\\weather_data/Greensboro_10/'+data_file+'.csv'\r\n# SCoring and anomaly detection\r\nmyCAS.loadactionset(actionset=\"astore\")\r\nmyCAS.score(\r\n table={\"name\" : data_file},\r\n options=[{\"name\":\"RPCA_PROJECTION_TYPE\",\"value\":2}],\r\n rstore={\"name\":\"store\"}, \r\n out={\"name\":\"scored\",\"replace\":True}\r\n )\r\n# Visualize cas matrices by downloading cas tables to memory. Watch out for large tables! Might take too long if table size is huge\r\noutput_s = myCAS.fetch(table={\"name\":\"scored\"}, to=10000, maxrows = 100000)['Fetch']\r\noutput_value = output_s.values\r\n\r\n###################################################################################################################################\r\n# Some basic manipulation of the table\r\n# Simple analysis\r\nmyCAS.loadactionset(actionset = \"simple\") \r\nout=myCAS.summary(table=data_file)\r\nprint(out)\r\n\r\nprint(result.keys)\r\nr1 = myCAS.fetch(table = {\"name\":\"sparsemat\"}, to = 61)\r\nmyCAS.columnInfo(table = {\"name\":\"sparsemat\"})\r\nr2 = r1.values # nparray data\r\n" } ]
8
lu-chang-axonic/Election_Analysis
https://github.com/lu-chang-axonic/Election_Analysis
44713c68a88c58eb8baeead5aa98d764ae62ec4c
f59a277598d10791c464d3c53e081caf25aa00bc
26eae2eb5a8a9eb009c5f38f5f3c5f4b4b9c987e
refs/heads/main
2023-02-01T15:16:52.593709
2020-12-20T02:20:19
2020-12-20T02:20:19
321,843,934
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5398229956626892, "alphanum_fraction": 0.5995575189590454, "avg_line_length": 20.571428298950195, "blob_id": "d5ba10c032bc1ed3090710197df7634ef339b4f2", "content_id": "e94066ae4485985308e576562d59e7569cb511a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 79, "num_lines": 21, "path": "/practices/Python_Practice2.py", "repo_name": "lu-chang-axonic/Election_Analysis", "src_encoding": "UTF-8", "text": "x = 0\nwhile x <= 5:\n print(x)\n x = x + 1\n\n#numbers = [0, 1, 2, 3, 4]\n#for nu in numbers:\n# print(nu)\n\nfor num in range(5):\n print(num)\n \ncounties = [\"Arapahoe\",\"Denver\",\"Jefferson\"]\nfor i in range(len(counties)):\n print(counties[i])\n\n counties_dict = {\"Arapahoe\": 422829, \"Denver\": 463353, \"Jefferson\": 432438}\n for county in counties_dict:\n print(county)\n for countykey in counties_dict.keys():\n print(countykey)" }, { "alpha_fraction": 0.608364999294281, "alphanum_fraction": 0.6102661490440369, "avg_line_length": 22.68181800842285, "blob_id": "1edb9ce01406bda24e46a7586dd0ff6d2c923f68", "content_id": "c714774554dc5667cc0ce2f8e808873de779ce02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 526, "license_type": "no_license", "max_line_length": 61, "num_lines": 22, "path": "/practices/Rock Paper Scissors.py", "repo_name": "lu-chang-axonic/Election_Analysis", "src_encoding": "UTF-8", "text": "###\n#import random\n\n#U_choice = (input(\"What is your choice among r, p, or s? \"))\n#I_choice=random.randrange(\"r\",\"p\",\"s\")\n#if U_choice ==r and I_choice==r:\n # print(\"Its a smashing tie\")\n\n#elif U_choice ==r and I_choice==p:\n# print('I chose p.')\n\nuser_play=\"y\"\n\nstart_number = 0 \n\nwhile user_play ==\"y\":\n number=input(\"What is your number?\")\n x=int(number)\n for x in range(start_number,x+start_number):\n print (x)\n start_number=start_number+x\n user_play=input(\"Do you still want to play?(y/n)\")\n\n\n\n\n\n" }, { "alpha_fraction": 0.6794625520706177, "alphanum_fraction": 0.7197696566581726, "avg_line_length": 53.76315689086914, "blob_id": "3b05a0b1047c6475c0ae0044d17be2274230b953", "content_id": "a4c443d5e310a4ca4e6b981f1c9aa0eeb3e80f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2084, "license_type": "no_license", "max_line_length": 234, "num_lines": 38, "path": "/README.md", "repo_name": "lu-chang-axonic/Election_Analysis", "src_encoding": "UTF-8", "text": "<h1 align=\"center\">Election Analysis</h1>\n\n## Overview of Election Audit\nThe purpose of this project is to summarize the number of votes by county and by candidate, as well as to identify the county with the largest number of votes and the winning candidate.\n\n## Election Audit Results\n\n* There are 369,711 votes that were cast in this congressional election. \n* There are three counties in this election. They are Jefferson with 38,855 votes (10.51%), Denver with 306,055 votes (82.78%), and Arapahoe with 24,801 votes (6.71%).\n* Denver Had the largest number of votes.\n* There are three candidates in the election. They are Charles Casper Stockham with 85,213 votes (23.0%), Diana DeGette with 272,892 votes (73.8%), and Raymon Anthony Doane with 11,606 votes (3.1%).\n* Diana DeGette won the election. She got 272,892 votes, which was 73.8% of the total votes. \n\nThe screenshot below shows the above results as how they printed in the terminal. \n![](https://github.com/lu-chang-axonic/Election_Analysis/blob/main/Results%20Printed%20to%20the%20Terminal.PNG)\n\n## Election Audit Summary\nThis script can be repurposed for other election analysis. Two examples:\n1. For election audit summarize other parameters such as gender, race, or education, etc, the code below can be modified to navigate to the desired parameter (be it a string or a numerical value) to conduct similar summary of results.\n\n for row in reader:\n\n # Add to the total vote count\n total_votes = total_votes + 1\n\n # Get the candidate name from each row.\n candidate_name = row[2]\n \n2. For other analysis, such as finding what % of each candidate's votes was from each county, the code below can be modified by replacing the total number of votes in the denominator to the number of votes in each county.\n\n \n for candidate_name in candidate_votes:\n\n # Retrieve vote count and percentage\n votes = candidate_votes.get(candidate_name)\n vote_percentage = float(votes) / float(total_votes) * 100\n candidate_results = (\n f\"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\\n\\n\")\n\n\n\n" }, { "alpha_fraction": 0.6246368288993835, "alphanum_fraction": 0.6316095590591431, "avg_line_length": 35.446807861328125, "blob_id": "04db484201437925d61acaedde7b1e00efcb8347", "content_id": "5882cfc35f9ff625a770867df1e41599d222ab52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1721, "license_type": "no_license", "max_line_length": 193, "num_lines": 47, "path": "/PyPoll.py", "repo_name": "lu-chang-axonic/Election_Analysis", "src_encoding": "UTF-8", "text": "import os\nimport csv\nfile_to_load = os.path.join(\"Resources\", \"election_results.csv\")\n\n# with open(file_to_load) as election_data:\n \nfile_to_save=os.path.join(\"analysis\",\"election_analysis.txt\")\n \ntotal_votes = 0\n\ncandidate_options=[]\n\ncandidate_votes={}\n\nwinning_canddiate = \"\"\nwinning_count = 0\nwining_percentage = 0\n\nwith open (file_to_load) as election_data:\n file_reader= csv.reader(election_data)\n headers = (next(file_reader))\n for row in file_reader:\n total_votes +=1\n candidate_name = row[2]\n if candidate_name not in candidate_options:\n candidate_options.append(candidate_name)\n candidate_votes[candidate_name]=0\n candidate_votes[candidate_name]+=1\n\nwith open(file_to_save,\"w\") as txt_file:\n election_results=(f\"Election Results\\n-------------------------\\nTotal Votes: {total_votes:,d}\\n-------------------------\\n\\n\")\n print (election_results, end=\"\")\n txt_file.write(election_results)\n \n for candidate_name in candidate_votes:\n #this is just to shortern the votes, which was defined upstairs\n votes=candidate_votes[candidate_name]\n vote_percentage=float(votes)/float(total_votes)*100\n candidate_results=(f\"{candidate_name}: {vote_percentage:.2f}% ({votes:,d})\\n\\n\")\n txt_file.write(candidate_results)\n\n if (votes>winning_count):\n winning_count=votes\n winning_candidate=candidate_name\n winning_percentage=vote_percentage\n winning_result=(f\"-------------------------\\nWinner: {winning_candidate}\\nWinning Vote Count: {winning_count:,d}\\nWinning Percentage: {winning_percentage:.2f}%.\\n-------------------------\")\n txt_file.write(winning_result) \n\n" }, { "alpha_fraction": 0.5903515815734863, "alphanum_fraction": 0.6639411449432373, "avg_line_length": 26.81818199157715, "blob_id": "287a4c7fc738ae02d96c586da31efc6a3c2c3177", "content_id": "06b18f6052f872fac3f3fb222a0012c5886c9473", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1223, "license_type": "no_license", "max_line_length": 197, "num_lines": 44, "path": "/practices/Python_Practice3.py", "repo_name": "lu-chang-axonic/Election_Analysis", "src_encoding": "UTF-8", "text": "'''\ncounties_dict = {\"Arapahoe\": 422829, \"Denver\": 463353, \"Jefferson\": 432438}\n\nfor county in counties_dict:\n print(county)\nfor countykey in counties_dict.keys():\n print(countykey)\nfor countykey in counties_dict.values():\n print(countykey)\nfor county in counties_dict:\n print(counties_dict[county])\n\n\nfor county in counties_dict.values ():\n print(county)\n\nfor county in counties_dict:\n print(counties_dict.get(county))\n\nfor key, value in counties_dict.items():\n print (key,value)\n''' \n\n# Make the dictionary the list\n'''\ncounties_dict = [{\"Arapahoe\": 422829, \"Denver\": 463353, \"Jefferson\": 432438},{\"Arapahoe\": 422829, \"Denver\": 463353, \"Jefferson\": 432438},{\"Arapahoe\": 422829, \"Denver\": 463353, \"Jefferson\": 432438}]\nfor x in counties_dict:\n print (x)\n\nfor i in range(len(counties_dict)):\n print (counties_dict[i])\n\ncounties_dict = [{\"county\":\"Arapahoe\", \"registered_voters\": 422829},\n {\"county\":\"Denver\", \"registered_voters\": 463353},\n {\"county\":\"Jefferson\", \"registered_voters\": 432438}]\nfor x in counties_dict:\n print(x['registered_voters'])\nfor x in counties_dict:\n for value in x.values():\n print(value)\n'''\nimport csv\ndir(csv)\nprint (dir(csv))" }, { "alpha_fraction": 0.6245487332344055, "alphanum_fraction": 0.6664260029792786, "avg_line_length": 29.130434036254883, "blob_id": "8cb0bbebbf2209bf8a0dc9f8d46e5b636283e2dd", "content_id": "919432434bc6309b8250d46b2d184f1b0c73807d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1385, "license_type": "no_license", "max_line_length": 71, "num_lines": 46, "path": "/practices/Python_Practice.py", "repo_name": "lu-chang-axonic/Election_Analysis", "src_encoding": "UTF-8", "text": "voting_data=[]\nvoting_data.append({\"county\":\"Arapahoe\", \"registered_voters\": 422829})\nvoting_data.append({\"county\":\"Denver\", \"registered_voters\": 463353})\nvoting_data.append({\"county\":\"Jefferson\", \"registered_voters\": 432438})\n#print(voting_data)\nvoting_data.insert(1,{\"county\":\"El Paso\",\"registered_voters\":461149})\n\nvoting_data.pop(0)\nvoting_data[2]=({\"county\":\"Denver\", \"registered_voters\": 463353})\nvoting_data[1]=({\"county\":\"Jefferson\", \"registered_voters\": 432438})\nvoting_data.append({\"county\":\"Arapahoe\", \"registered_voters\": 422829})\nprint(voting_data)\ncounties = [\"Arapahoe\",\"Denver\",\"Jefferson\"]\nif counties[1] == 'Denver':\n print(counties[1])\n\n# If Else statements\ntemperature = int(input(\"What is the temperature outside? \"))\n\nif temperature > 80:\n print(\"Turn on the AC.\")\nelse:\n print(\"Open the windows.\")\n # What is the score?\n# score = int(input(\"What is your test score? \"))\n\n# Elif Determine the grade.\nif score >= 90:\n print('Your grade is an A.')\nelif score >= 80:\n print('Your grade is a B.')\nelif score >= 70:\n print('Your grade is a C.')\nelif score >= 60:\n print('Your grade is a D.')\nelse:\n print('Your grade is an F.')\n\n# in and not in\ncounties = [\"Arapahoe\",\"Denver\",\"Jefferson\"]\nif \"El Paso\" in counties:\n print(\"El Paso is in the list of counties.\")\nelse:\n print(\"El Paso is not the list of counties.\")\n\n #if not(x > y):" } ]
6
dburns7/hxx_2a100tev
https://github.com/dburns7/hxx_2a100tev
3e3d62851fa92e1d65d8ba16be5dbbd6c55ed8d9
a710943244a23322e3a38658aabdfefa54de2046
b71ecb34641606d4268b0a92f64d0514456dd5e2
refs/heads/master
2020-12-24T14:56:24.925807
2014-12-15T19:12:34
2014-12-15T19:12:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4367283880710602, "alphanum_fraction": 0.5216049551963806, "avg_line_length": 28.454545974731445, "blob_id": "29cdf5f56f5fcbdc04fd5b71276a4e52de221793", "content_id": "0acbdbaea5ae7bdc2bad50a227921febf5bb64ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 648, "license_type": "no_license", "max_line_length": 177, "num_lines": 22, "path": "/run/scripts/make_100tev_ntuples.sh", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nsource COMPILE\n\nrm ../data/analysis/*.root \n\n# Using lumi in fb, xsec in fb^-1\n# H -> llll ................................. 2.813706\n# ZZ -> llll ................................ 71.637508096\n# ZH, Z -> vv, H -> llll .................... 0.011097\n# ZH, Z -> ll, H -> llvv .................... 0.3139155\n# WH, W -> lv, H -> llll .................... 0.020300112\n\n./bin/MakeHxxTree --maxevent=100 --sample=1 --lumi=20 --xsec=1 ../data/analysis/Higgs_hhxx_combined_1GeV_8TeV_ntuple.root ../data/preprocessed/Higgs_hhxx_combined_1GeV_8TeV.root\n\npushd ../data/analysis/\nif [ -e \"all.root\" ] \nthen \n rm all.root\nfi\nhadd all.root *.root\npopd\n" }, { "alpha_fraction": 0.6898608207702637, "alphanum_fraction": 0.6898608207702637, "avg_line_length": 21.863636016845703, "blob_id": "e98b6245f1745756e936e78274da077fc2dc1708", "content_id": "dc6e285c24f6ddd3b97b8434a0964631584cd900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 503, "license_type": "no_license", "max_line_length": 81, "num_lines": 22, "path": "/include/cutflow_tool.h", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#ifndef CUTFLOW_TOOL_H\n#define CUTFLOW_TOOL_H\n\n#include <vector>\n#include <string>\n\nclass cutflow_tool {\npublic:\n cutflow_tool();\n\n void increment(int stage, int sample, double weight);\n double count(int stage, int sample);\n void print(int stage);\n\n void add_sample_name(int sample, const std::string & sample_name); // optional\nprivate:\n std::vector< std::string > sample_names;\n std::vector< std::vector<double> > evt_counts;\n std::vector< std::vector<double> > wsq_counts;\n};\n\n#endif\n" }, { "alpha_fraction": 0.675159215927124, "alphanum_fraction": 0.6796178221702576, "avg_line_length": 23.920635223388672, "blob_id": "c9ba764cdf531582c198153257814a88a3eaf7a1", "content_id": "1332ad0db87318ad72f95068558f4dacf0bca3bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1570, "license_type": "no_license", "max_line_length": 82, "num_lines": 63, "path": "/include/histogram_manager.h", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#ifndef HISTOGRAM_MANAGER_H\n#define HISTOGRAM_MANAGER_H\n\n#include <vector>\n#include <string>\n\nclass TH1F;\nclass auto_write;\n\nclass histogram_manager {\npublic:\n\n histogram_manager();\n histogram_manager(TH1F * hbase );\n histogram_manager(TH1F * hbase, const histogram_manager & hm);\n histogram_manager(TH1F * hbase, const histogram_manager & hm, auto_write & aw);\n\n // add to an automatic write service:\n void add_auto_write(auto_write & aw);\n\n // set the base histogram, for which each sample will have its own copy:\n void set_base_histogram(TH1F * hbase){ this->hbase = hbase; }\n\n // add a sample and corresponding sample name\n void add_sample (int sample, const std::string & tag);\n\n // copy the samples and names from an already initialized histogram_manager\n void copy_samples_from (const histogram_manager & hm);\n\n // find the index for this sample\n // (issues cout message and exits on no corresponding sample!)\n int index(int sample);\n\n // Fill histogram with this sample id:\n void Fill(int sample, double x);\n void Fill(int sample, double x, double w);\n\n void WriteAll();\n\n // direct access to everything for your enjoyment:\n TH1F * hbase;\n std::vector<int> sample;\n std::vector<std::string> tag;\n std::vector<TH1F *> vhist;\n\nprivate:\n void init(){ hbase = NULL; }\n};\n\n\n// Automatically write to the file list:\nclass auto_write {\npublic:\n auto_write();\n void AutoWrite(histogram_manager & hm);\n void WriteAll();\nprivate:\n std::vector<histogram_manager *> write_list;\n};\n\n\n\n#endif\n" }, { "alpha_fraction": 0.5069520473480225, "alphanum_fraction": 0.5313386917114258, "avg_line_length": 33.86040496826172, "blob_id": "7672947a3e1063f43180e85adb429faf1b54457c", "content_id": "90de914da091f70f353b11fb51a566cdb8cdf5a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13737, "license_type": "no_license", "max_line_length": 117, "num_lines": 394, "path": "/test/MakeHxxTree.cpp", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <utility>\n#include <vector>\n\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TApplication.h\"\n\n#include \"TString.h\"\n\n#include \"TH2.h\"\n#include \"THStack.h\"\n#include \"TLegend.h\"\n#include \"TPaveText.h\"\n#include \"TClonesArray.h\"\n#include \"TLorentzVector.h\"\n#include \"TCanvas.h\"\n#include \"TRandom.h\"\n\n#include \"classes/DelphesClasses.h\"\n\n#include \"ExRootAnalysis/ExRootTreeReader.h\"\n#include \"ExRootAnalysis/ExRootTreeWriter.h\"\n#include \"ExRootAnalysis/ExRootTreeBranch.h\"\n#include \"ExRootAnalysis/ExRootResult.h\"\n#include \"ExRootAnalysis/ExRootUtilities.h\"\n\n\n#include \"koptions.h\"\n#include \"hxx_tree.h\"\n\nusing namespace std;\nusing namespace kutil;\n\nvoid usage(){\n cout << \"usage: MakeHxxTree [OPTIONS] <input_file> <output_file>\\n\";\n cout << \"\\n\";\n cout << \" --seed=<n> (0) set rng seed if non-zero\\n\";\n cout << \" --sample=<n> (0) set sample id to <n>\\n\";\n cout << \" --lumi=<l> (14) set weight for lumi <l> [fb^-1]\\n\";\n cout << \" --xsec=<x> (0) set weight for xsec <x> [fb]\\n\";\n cout << \" --maxevent=<n> (0) if greater than zero, write only <n> events.\\n\";\n cout << \" --mllcut require non-zero mll (saves space).\\n\";\n exit(0);\n}\n\nint compare_part(GenParticle * g1, GenParticle * g2){ return (g1->PT > g2->PT); }\n\nint main(int argc, char *argv[])\n{\n TRandom rng;\n hxx_tree data;\n int seed = 0;\n int sample = 0;\n double lumi = 14.0;\n double xsec = 0.0;\n double weight = 1.0; \n int maxevent = 0;\n\n std::string opt, infile, outfile;\n koptions options(argc, argv);\n \n //check for the --help option:\n int mllcut = options.find(\"--mllcut\"); \n\n if ( options.find(\"--help\") ) { usage(); }\n options.set(\"--seed=\", seed); \n if (seed > 0) rng.SetSeed(seed);\n\n options.set(\"--sample=\", sample); \n options.set(\"--lumi=\", lumi);\n options.set(\"--xsec=\", xsec);\n options.set(\"--maxevent=\", maxevent);\n\n //check for unrecognized options (beginning with -- or -)\n while(options.unrecognized_option(opt)){\n cout << \"WARNING: unrecognized option:\" << opt << \"\\n\";\n usage();\n } \n\n if (options.size() < 2){\n usage();\n }\n\n options.shift_argument(outfile);\n\n cout << \"INFO: sample id is \" << sample << \"\\n\";\n cout << \"INFO: writing analysis tree file: \" << outfile << \"\\n\";\n\n TChain chain(\"Delphes\");\n while(options.shift_argument(infile)){\n cout << \"INFO: adding input file: \" << infile << \"\\n\"; \n chain.Add(infile.c_str());\n }\n\n ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);\n Long64_t numberOfEntries = treeReader->GetEntries();\n if (numberOfEntries == 0) { cout << \"Zero entries...\\n\"; return 0; }\n if ((maxevent > 0) && (maxevent < numberOfEntries)) numberOfEntries = maxevent;\n double Ngen = numberOfEntries;\n\n // Get pointers to branches used in this analysis\n TClonesArray *branchJet = treeReader->UseBranch(\"Jet\");\n TClonesArray *branchElec = treeReader->UseBranch(\"Electron\");\n TClonesArray *branchMuon = treeReader->UseBranch(\"Muon\");\n TClonesArray *branchMET = treeReader->UseBranch(\"MissingET\"); \n TClonesArray *branchHt = treeReader->UseBranch(\"ScalarHT\"); \n TClonesArray *branchGen = treeReader->UseBranch(\"Particle\"); \n\n // calculate appropriate weight:\n if (xsec > 0.0){\n double Lgen = Ngen / xsec;\n weight = lumi * xsec / Ngen;\n cout << \"INFO: calculating event weights:\\n\";\n cout << \"INFO: Ngen = \" << Ngen << \"\\n\";\n cout << \"INFO: lumi = \" << lumi << \"\\n\";\n cout << \"INFO: xsec = \" << xsec << \"\\n\";\n cout << \"INFO: Lgen = \" << Lgen << \"\\n\";\n cout << \"INFO: weight = \" << weight << \"\\n\";\n cout << \"INFO: Ntot = \" << weight * Ngen << \"\\n\";\n } else {\n cout << \"INFO: no xsec provided, using weight=1\";\n weight = 1;\n }\n\n TFile * file = new TFile(outfile.c_str(), \"RECREATE\");\n TTree * tree = new TTree(\"hxxtree\", \"\");\n data.WriteTree(tree);\n \n double tot_wgt = 0.0;\n int count = 0;\n int nupdate = numberOfEntries / 20;\n if (nupdate < 1) nupdate=1;\n cout << \"PROGRESS: \";\n\n // Loop over all events\n for(Int_t entry = 0; entry < numberOfEntries; ++entry)\n {\n count++;\n if (count % nupdate == 0) { cout << \".\"; cout.flush(); }\n treeReader->ReadEntry(entry);\n \n data.Clear();\n data.testvar = 2;\n data.sample = sample;\n //hs->Draw();\n //hs->Draw();\n data.weight = weight;\n data.weight_met = 0;\n\n data.nelec = branchElec->GetEntries();\n data.nmuon = branchMuon->GetEntries();\n data.njet = branchJet->GetEntries();\n \n if (data.nmuon >= data.nelec) {\n data.lepton_flavor = LFMUMU;\n if (branchMuon->GetEntries() > 0) {\n Muon * mu1 = (Muon*) branchMuon->At(0);\n data.l1_pt = mu1->PT;\n data.l1_eta = mu1->Eta;\n data.l1_phi = mu1->Phi;\n }\n if (branchMuon->GetEntries() > 1) {\n Muon * mu1 = (Muon*) branchMuon->At(0);\n Muon * mu2 = (Muon*) branchMuon->At(1);\n data.l2_pt = mu2->PT;\n data.l2_eta = mu2->Eta;\n data.l2_phi = mu2->Phi;\n data.mll = ((mu1->P4()) + (mu2->P4())).M(); \n }\n } else {\n data.lepton_flavor = LFEMEM;\n if (branchElec->GetEntries() > 0) {\n Electron * elec1 = (Electron*) branchElec->At(0);\n data.l1_pt = elec1->PT;\n data.l1_eta = elec1->Eta;\n data.l1_phi = elec1->Phi;\n }\n if (branchElec->GetEntries() > 1) {\n Electron * elec1 = (Electron*) branchElec->At(0);\n Electron * elec2 = (Electron*) branchElec->At(1);\n data.l2_pt = elec2->PT;\n data.l2_eta = elec2->Eta;\n data.l2_phi = elec2->Phi;\n data.mll = ((elec1->P4()) + (elec2->P4())).M(); \n }\n }\n\n\n if (mllcut && (data.mll <= 0.0)) continue;\n\n int nJet = branchJet->GetEntries();\n for (int i=0; i<nJet; i++){\n Jet * jet = (Jet*) branchJet->At(i);\n data.jet_pt ->push_back(jet->PT);\n data.jet_eta ->push_back(jet->Eta);\n data.jet_phi ->push_back(jet->Phi);\n data.jet_btag ->push_back((int) jet->BTag);\n data.jet_tautag ->push_back((int) jet->TauTag);\n } \n//-------------------------------------------ADDED-----------------------------\n \n Electron *elec1, *elec2, *elec3, *elec4;\n Muon *muon1, *muon2, *muon3, *muon4;\n TLorentzVector dimuonP4, dimuonP4_2, dielecP4, dielecP4_2, totalP4;\n if(data.nelec == 2 && data.nmuon == 2){\n weight *= 0.1*weight;\n elec1 = (Electron *) branchElec->At(0);\n elec2 = (Electron *) branchElec->At(1);\n muon1 = (Muon *) branchMuon->At(0);\n muon2 = (Muon *) branchMuon->At(1);\n dimuonP4 = (muon1->P4())+(muon2->P4());\n dielecP4 = (elec1->P4())+(elec2->P4());\n totalP4 = dimuonP4 + dielecP4;\n data.elec_pt ->push_back(elec1->PT);\n data.elec_eta ->push_back(elec1->Eta);\n data.elec_phi ->push_back(elec1->Phi);\n data.elec_ch ->push_back(elec1->Charge);\n data.elec_pt ->push_back(elec2->PT);\n data.elec_eta ->push_back(elec2->Eta);\n data.elec_phi ->push_back(elec2->Phi);\n data.elec_ch ->push_back(elec2->Charge);\n data.muon_pt ->push_back(muon1->PT);\n data.muon_eta ->push_back(muon1->Eta);\n data.muon_phi ->push_back(muon1->Phi);\n data.muon_ch ->push_back(muon1->Charge);\n data.muon_pt ->push_back(muon2->PT);\n data.muon_eta ->push_back(muon2->Eta);\n data.muon_phi ->push_back(muon2->Phi);\n data.muon_ch ->push_back(muon2->Charge);\n data.dielec_minv ->push_back(dielecP4.M());\n data.dimuon_minv ->push_back(dimuonP4.M());\n if(abs(dielecP4.M()-91.0) < abs(dimuonP4.M()-91.0)){\n data.leadingm = dielecP4.M();\n data.subleadingm = dimuonP4.M();\n }\n else{\n data.leadingm = dimuonP4.M();\n data.subleadingm = dielecP4.M();\n }\n data.total_minv = totalP4.M(); \n }\n if(data.nelec == 4 && data.nmuon == 0){\n weight *= 0.1*weight;\n elec1 = (Electron *) branchElec->At(0);\n elec2 = (Electron *) branchElec->At(1);\n elec3 = (Electron *) branchElec->At(2);\n elec4 = (Electron *) branchElec->At(3);\n dielecP4 = (elec1->P4())+(elec2->P4());\n dielecP4_2 = (elec3->P4())+(elec4->P4());\n totalP4 = dielecP4 + dielecP4_2;\n data.elec_pt ->push_back(elec1->PT);\n data.elec_eta ->push_back(elec1->Eta);\n data.elec_phi ->push_back(elec1->Phi);\n data.elec_ch ->push_back(elec1->Charge);\n data.elec_pt ->push_back(elec2->PT);\n data.elec_eta ->push_back(elec2->Eta);\n data.elec_phi ->push_back(elec2->Phi);\n data.elec_ch ->push_back(elec2->Charge);\n data.elec_pt ->push_back(elec3->PT);\n data.elec_eta ->push_back(elec3->Eta);\n data.elec_phi ->push_back(elec3->Phi);\n data.elec_ch ->push_back(elec3->Charge);\n data.elec_pt ->push_back(elec4->PT);\n data.elec_eta ->push_back(elec4->Eta);\n data.elec_phi ->push_back(elec4->Phi);\n data.elec_ch ->push_back(elec4->Charge);\n data.dielec_minv ->push_back(dielecP4.M());\n data.dielec_minv ->push_back(dielecP4_2.M());\n if(abs(dielecP4.M()-91.0) < abs(dielecP4_2.M()-91.0)){\n data.leadingm = dielecP4.M();\n data.subleadingm = dielecP4_2.M();\n }\n else{\n data.leadingm = dielecP4_2.M();\n data.subleadingm = dielecP4.M();\n }\n data.total_minv = totalP4.M();\n }\n if(data.nelec == 0 && data.nmuon == 4){\n weight *= 0.1*weight;\n muon1 = (Muon *) branchMuon->At(0);\n muon2 = (Muon *) branchMuon->At(1);\n muon3 = (Muon *) branchMuon->At(2);\n muon4 = (Muon *) branchMuon->At(3);\n dimuonP4 = (muon1->P4())+(muon2->P4());\n dimuonP4_2 = (muon3->P4())+(muon4->P4());\n totalP4 = dimuonP4 + dimuonP4_2;\n data.muon_pt ->push_back(muon1->PT);\n data.muon_eta ->push_back(muon1->Eta);\n data.muon_phi ->push_back(muon1->Phi);\n data.muon_ch ->push_back(muon1->Charge);\n data.muon_pt ->push_back(muon2->PT);\n data.muon_eta ->push_back(muon2->Eta);\n data.muon_phi ->push_back(muon2->Phi);\n data.muon_ch ->push_back(muon2->Charge);\n data.muon_pt ->push_back(muon3->PT);\n data.muon_eta ->push_back(muon3->Eta);\n data.muon_phi ->push_back(muon3->Phi);\n data.muon_ch ->push_back(muon3->Charge);\n data.muon_pt ->push_back(muon4->PT);\n data.muon_eta ->push_back(muon4->Eta);\n data.muon_phi ->push_back(muon4->Phi);\n data.muon_ch ->push_back(muon4->Charge);\n data.dimuon_minv ->push_back(dimuonP4.M());\n data.dimuon_minv ->push_back(dimuonP4_2.M());\n if(abs(dimuonP4.M()-91.0) < abs(dimuonP4_2.M()-91.0)){\n data.leadingm = dimuonP4.M();\n data.subleadingm = dimuonP4_2.M();\n }\n else{\n data.leadingm = dimuonP4_2.M();\n data.subleadingm = dimuonP4.M();\n }\n data.total_minv = totalP4.M();\n }\n \n//--------------------------------------------------------------------\n\n if (branchMET->GetEntries() > 0) {\n MissingET * met = (MissingET *) branchMET->At(0);\n data.nopu_met = met->MET;\n data.nopu_met_phi = met->Phi;\n }\n\n if (branchHt->GetEntries() > 0) {\n ScalarHT * ht = (ScalarHT *) branchHt->At(0);\n data.ht = ht->HT;\n }\n\n // Sort Gen Muons and Electrons:\n std::vector<GenParticle *> genLept;\n int npart = branchGen->GetEntries();\n for (int i=0; i<npart; i++){\n\tGenParticle * part = (GenParticle*) branchGen->At(i);\n\tint aPID = abs(part->PID);\n\tif (part->Status!=1) continue;\n\tif (part->PT < 1.0) continue;\n\tif (part->D1 != -1) { cout << \"ERROR DETECTED!\\n\"; }\n\n\tif (aPID == 11){ genLept.push_back(part); } \n\tif (aPID == 13){ genLept.push_back(part); }\n }\n sort(genLept.begin(), genLept.end(), compare_part);\n\n\n if (genLept.size() > 0) {\n\tGenParticle * lept1 = genLept.at(0);\n\tdata.gl1_pt = lept1->PT;\n\tdata.gl1_eta = lept1->Eta;\n\tdata.gl1_phi = lept1->Phi;\n }\n if (genLept.size() > 1) {\n\tGenParticle * lept1 = genLept.at(0);\n\tGenParticle * lept2 = genLept.at(1);\n\tdata.gl2_pt = lept2->PT;\n\tdata.gl2_eta = lept2->Eta;\n\tdata.gl2_phi = lept2->Phi;\n\tdata.gmll = ((lept1->P4()) + (lept2->P4())).M(); \n }\n\n if (0) {\n\tint n = genLept.size();\n\tif (n > 2) n=2;\n\tcout << \"\\n\\nGenerated Leptons:\\n\";\n\tfor (int i=0; i<n; i++) { cout << \"Lept: \" << genLept[i]->PT << \"\\n\"; }\n\tint nmuon = branchMuon->GetEntries();\n\tcout << \"Reco Muon:\\n\";\n\tfor (int i=0; i<nmuon; i++){\n\t Muon * mu = (Muon*) branchMuon->At(i);\n\t cout << \"PT: \" << mu->PT << \"\\n\";\n\t}\n\t\n\tint nelec = branchElec->GetEntries();\n\tcout << \"Reco Electron:\\n\";\n\tfor (int i=0; i<nelec; i++){\n\t Electron * mu = (Electron*) branchElec->At(i);\n\t cout << \"PT: \" << mu->PT << \"\\n\";\n\t}\n }\n\n tot_wgt += data.weight;\n tree->Fill();\n }\n cout << \"\\n\";\n\n cout << \"SUMMARY: wrote \" << tree->GetEntries() << \" to analysis tree from \" << count << \" events considered.\\n\";\n cout << \"SUMMARY: total weight: \" << tot_wgt << \"\\n\";\n file->cd();\n tree->Write();\n file->Close(); \n\n cout << \"SUMMARY: done writing files.\\n\";\n}\n\n\n" }, { "alpha_fraction": 0.623711347579956, "alphanum_fraction": 0.7164948582649231, "avg_line_length": 63.66666793823242, "blob_id": "3526ff4dfb4975c8a5c8d92f746fc1e832969dfa", "content_id": "4c29351651e5de5d6b9b9d74a76ec756bb69cfb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "no_license", "max_line_length": 151, "num_lines": 3, "path": "/Delphes-3.0.10/python/__init__.py", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#Automatically created by SCRAM\nimport os\n__path__.append(os.path.dirname(os.path.abspath(__file__).rsplit('/hxx_4l/Delphes-3.0.10/',1)[0])+'/cfipython/slc5_amd64_gcc462/hxx_4l/Delphes-3.0.10')\n" }, { "alpha_fraction": 0.5093937516212463, "alphanum_fraction": 0.5582278370857239, "avg_line_length": 34.64845657348633, "blob_id": "45b2456a486979322b047cc35b9bab1b540209d0", "content_id": "ef43cfcc1e609f656bd828f3fdc8aa6845d1b655", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15010, "license_type": "no_license", "max_line_length": 105, "num_lines": 421, "path": "/test/AnalyzeHxx.cpp", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <utility>\n#include <vector>\n#include <math.h>\n\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TApplication.h\"\n\n#include \"TFile.h\"\n#include \"TH1F.h\"\n#include \"TTree.h\"\n#include \"TRandom.h\"\n#include \"TLorentzVector.h\"\n\n#include \"koptions.h\"\n#include \"hxx_tree.h\"\n#include \"histogram_manager.h\"\n#include \"cutflow_tool.h\"\n\nusing namespace std;\nusing namespace kutil;\n\nvoid usage(){\n cout << \"usage: AnalyzeHxx [OPTIONS] <input_file> <output_root> <output_dir>\\n\";\n cout << \"\\n\";\n cout << \" --met_smear=<x> : extra amount to smear MET.\\n\";\n cout << \" --num_smear=<n> : number of times to smear MET.\\n\";\n exit(0);\n}\n\nvoid kinematic_vars_2g(hxx_tree &data, double &mgg){\n TLorentzVector vg1, vg2;\n vg1.SetPtEtaPhiM(data.phot_pt->at(0), data.phot_eta->at(0), data.phot_phi->at(0), 0.0);\n vg2.SetPtEtaPhiM(data.phot_pt->at(1), data.phot_eta->at(1), data.phot_phi->at(1), 0.0);\n mgg = (vg1 + vg2).M();\n}\n\ndouble sensitivity(TH1F * hsig, TH1F * hbkg, double sigtot){\n int n = hsig->GetNbinsX() + 2;\n double best_sens = 0.0;\n int ibest = 0;\n for (int i=0; i<n; i++){\n double s = 0;\n double b = 0;\n for (int j=i; j<n; j++){\n //s += hsig->GetBinContent(i);\n s += sigtot * hsig->GetBinContent(i);\n b += hbkg->GetBinContent(i);\n } \n double sens = 0;\n if (b > 0.0) sens = s / sqrt(b);\n if (sens > best_sens) { \n best_sens = sens;\n ibest = i;\n }\n }\n cout << \"Best MET cut at: \" << hsig->GetBinLowEdge(ibest) << \"\\n\";\n return best_sens;\n}\n\nint main(int argc, char *argv[])\n{\n TRandom rng;\n rng.SetSeed(2014);\n hxx_tree data;\n \n std::string opt, infile, outroot, outdir;\n koptions options(argc, argv);\n \n //check for the --help option:\n if ( options.find(\"--help\") ) { usage(); }\n double met_smear = 30.0;\n options.set(\"--met_smear=\", met_smear); \n int num_smear = 1;\n options.set(\"--num_smear=\", num_smear); \n\n //check for unrecognized options (beginning with -- or -)\n while(options.unrecognized_option(opt)){\n cout << \"WARNING: unrecognized option:\" << opt << \"\\n\";\n usage();\n } \n\n if (options.size() != 3){\n usage();\n }\n\n options.shift_argument(infile);\n options.shift_argument(outroot);\n options.shift_argument(outdir);\n\n cout << \"INFO: reading analysis tree file: \" << infile << \"\\n\";\n cout << \"INFO: writing histogram root file: \" << outroot << \"\\n\";\n cout << \"INFO: writing results to directory: \" << outdir << \"\\n\";\n cout << \"INFO: MET smearing amount is \" << met_smear << \"\\n\";\n cout << \"INFO: MET smearing number is \" << num_smear << \"\\n\";\n\n auto_write aw;\n\n cutflow_tool cutflow;\n histogram_manager h0mll(new TH1F(\"h0mll\",\"\",60,60.0,120.0));\n\n/*\n h0mll.add_sample(9000, \"_DAS\");\n h0mll.add_sample(9001, \"_PU\");\n h0mll.add_sample(9002, \"_NO_PU\");\n \n cutflow.add_sample_name(9000, \"DAS\");\n cutflow.add_sample_name(9001, \"PU\");\n cutflow.add_sample_name(9002, \"NO_PU\");\n*/\n h0mll.add_sample(20, \"_hxx_1GeV\");\n h0mll.add_sample(21, \"_hxx_10GeV\");\n h0mll.add_sample(22, \"_hxx_100GeV\");\n h0mll.add_sample(23, \"_hxx_500GeV\");\n h0mll.add_sample(24, \"_hxx_1000GeV\");\n \n cutflow.add_sample_name(20, \"hxx_1GeV\"); \n cutflow.add_sample_name(21, \"hxx_10GeV\"); \n cutflow.add_sample_name(22, \"hxx_100GeV\"); \n cutflow.add_sample_name(23, \"hxx_500GeV\"); \n cutflow.add_sample_name(24, \"hxx_1000GeV\"); \n\n h0mll.add_auto_write(aw);\n\n TH1F hfit_bkg(\"sample_1\",\"\", 100,0.0,300.0);\n TH1F hfit_sig1(\"signal1\",\"\", 100,0.0,300.0);\n TH1F hfit_sig21(\"signal21\",\"\", 100,0.0,300.0);\n TH1F hfit_sig22(\"signal22\",\"\", 100,0.0,300.0);\n TH1F hfit_sig23(\"signal23\",\"\", 100,0.0,300.0);\n TH1F hfit_sig24(\"signal24\",\"\", 100,0.0,300.0);\n\n int nsig = 0;\n double wsig = 0.0;\n hfit_bkg.Sumw2();\n hfit_sig1.Sumw2();\n hfit_sig21.Sumw2();\n hfit_sig22.Sumw2();\n hfit_sig23.Sumw2();\n hfit_sig24.Sumw2();\n\n //histograms at stage 0\n histogram_manager h0ID (new TH1F(\"h0ID\", \"\", 25, 0.0, 25.0), h0mll, aw);\n \n histogram_manager h0ept (new TH1F(\"h0ept\", \"\", 100, 0.0, 250.0), h0mll, aw);\n histogram_manager h0eeta (new TH1F(\"h0eeta\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0ephi (new TH1F(\"h0ephi\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0ech (new TH1F(\"h0ech\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0ecnt (new TH1F(\"h0ecnt\", \"\", 10, 0.0, 10.0), h0mll, aw);\n \n histogram_manager h0mpt (new TH1F(\"h0mpt\", \"\", 100, 0.0, 250.0), h0mll, aw);\n histogram_manager h0meta (new TH1F(\"h0meta\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0mphi (new TH1F(\"h0mphi\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0mch (new TH1F(\"h0mch\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0mcnt (new TH1F(\"h0mcnt\", \"\", 10, 0.0, 10.0), h0mll, aw);\n \n histogram_manager h0l1pt (new TH1F(\"h0l1pt\", \"\", 200, 0.0, 250.0), h0mll, aw);\n histogram_manager h0l2pt (new TH1F(\"h0l2pt\", \"\", 200, 0.0, 250.0), h0mll, aw);\n histogram_manager h0l3pt (new TH1F(\"h0l3pt\", \"\", 200, 0.0, 250.0), h0mll, aw);\n histogram_manager h0l4pt (new TH1F(\"h0l4pt\", \"\", 200, 0.0, 250.0), h0mll, aw);\n \n histogram_manager h0gpt (new TH1F(\"h0gpt\", \"\", 100, 0.0, 250.0), h0mll, aw);\n histogram_manager h0geta (new TH1F(\"h0geta\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0gphi (new TH1F(\"h0gphi\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0gch (new TH1F(\"h0gch\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0gcnt (new TH1F(\"h0gcnt\", \"\", 10, 0.0, 10.0), h0mll, aw);\n \n histogram_manager h0mgg (new TH1F(\"h0mgg\", \"\", 100, 0.0, 250.0), h0mll, aw);\n \n histogram_manager h0met_nopu (new TH1F(\"h0met_nopu\", \"\", 100, 0.0, 250.0), h0mll, aw);\n histogram_manager h0met_pu (new TH1F(\"h0met_pu\", \"\", 100, 0.0, 250.0), h0mll, aw);\n histogram_manager h0met_nopu_phi (new TH1F(\"h0met_nopu_phi\", \"\", 60, -5.0, 5.0), h0mll, aw);\n histogram_manager h0met_pu_phi (new TH1F(\"h0met_pu_phi\", \"\", 60, -5.0, 5.0), h0mll, aw);\n \n //histograms after analysis cuts\n histogram_manager h1met_nopu (new TH1F(\"h1met_nopu\", \"\", 100, 0.0, 250.0), h0mll, aw);\n \n cout << \"INFO: opening file: \" << infile << \"\\n\";\n\n TFile * file = new TFile(infile.c_str());\n TDirectoryFile * dir = (TDirectoryFile*) file->Get(\"demo\");\n TTree * tree = (TTree*) dir->Get(\"hxxtree\");\n\n if (! tree) {\n cout << \"ERROR: could not open tree.\\n\";\n exit(0);\n }\n\n data.ReadTree(tree);\n long int numberOfEntries = tree->GetEntries();\n\n int count = 0;\n int nupdate = numberOfEntries / 20;\n if (nupdate < 1) nupdate=1;\n cout << \"PROGRESS: \";\n\n int prescale = 0; \n int iprescale = 0;\n // Loop over all events\n for(Int_t entry = 0; entry < numberOfEntries; ++entry)\n {\n count++;\n if (count % nupdate == 0) { cout << \".\"; cout.flush(); }\n\n if (iprescale < prescale){\n iprescale++;\n continue;\n } else {\n iprescale = 0;\n }\n \n tree->GetEntry(entry);\n\n h0ID.Fill(data.sample, data.sample);\n\n\n////////////////////////////// 2g preselection cuts ////////////////////////////////////////\n /* \n if (data.nphot != 2) continue;\n bool hasHighPtElecs = false;\n bool hasLowEtaElecs = false;\n for(int i=0; i<data.nelec; i++) {\n if (data.elec_pt->at(i) > 20) hasHighPtElecs = true;\n if (data.elec_eta->at(i) < 2.5) hasLowEtaElecs = true;\n }\n if (hasHighPtElecs) continue;\n if (hasLowEtaElecs) continue;\n bool hasHighPtMuons = false;\n bool hasLowEtaMuons = false;\n for(int i=0; i<data.nmuon; i++) {\n if (data.muon_pt->at(i) > 20) hasHighPtMuons = true;\n if (data.muon_eta->at(i) < 2.5) hasLowEtaMuons = true;\n }\n if (hasHighPtMuons) continue;\n if (hasLowEtaMuons) continue;\n */\n////////////////////////////////////////////////////////////////////////////////////////////\n \n cutflow.increment(0, data.sample, data.weight); \n\n h0mll.Fill(data.sample, data.mll, data.weight);\n \n //Fill single lepton hists at stage 0 \n for(int i=0; i<data.nelec; i++){\n //cout << data.nelec << \" \" << data.elec_pt->size() << \" \" << data.sample << endl;\n h0ept .Fill(data.sample, data.elec_pt->at(i), data.weight);\n h0eeta .Fill(data.sample, data.elec_eta->at(i), data.weight);\n h0ephi .Fill(data.sample, data.elec_phi->at(i), data.weight);\n h0ech .Fill(data.sample, data.elec_ch->at(i), data.weight);\n }\n h0ecnt .Fill(data.sample, data.nelec, data.weight);\n for(int i=0; i<data.nmuon; i++){\n h0mpt .Fill(data.sample, data.muon_pt->at(i), data.weight);\n h0meta .Fill(data.sample, data.muon_eta->at(i), data.weight);\n h0mphi .Fill(data.sample, data.muon_phi->at(i), data.weight);\n h0mch .Fill(data.sample, data.muon_ch->at(i), data.weight);\n }\n h0mcnt .Fill(data.sample, data.nmuon, data.weight);\n\n //Fill single photon hists at stage 0 \n for(int i=0; i<data.nphot; i++){\n h0gpt .Fill(data.sample, data.phot_pt->at(i), data.weight);\n h0geta .Fill(data.sample, data.phot_eta->at(i), data.weight);\n h0gphi .Fill(data.sample, data.phot_phi->at(i), data.weight);\n }\n h0gcnt .Fill(data.sample, data.nphot, data.weight);\n \n //Fill multiparticle hists at stage 0\n double mgg;\n if(data.nphot == 2){\n kinematic_vars_2g(data, mgg);\n\th0mgg .Fill(data.sample, mgg, data.weight);\n }\n\n //Fill other hists at stage 0\n h0met_nopu .Fill(data.sample, data.nopu_met, data.weight);\n h0met_nopu_phi .Fill(data.sample, data.nopu_met_phi, data.weight);\n\n\n/////////////////////////////// 2a Analysis cuts ///////////////////////////////////////////\n\n bool hasHighPtElecs = false;\n bool hasLowEtaElecs = false;\n for(int i=0; i<data.nelec; i++) {\n if (data.elec_pt->at(i) > 20) hasHighPtElecs = true;\n if (data.elec_eta->at(i) < 2.5) hasLowEtaElecs = true;\n }\n bool hasHighPtMuons = false;\n bool hasLowEtaMuons = false;\n for(int i=0; i<data.nmuon; i++) {\n if (data.muon_pt->at(i) > 20) hasHighPtMuons = true;\n if (data.muon_eta->at(i) < 2.5) hasLowEtaMuons = true;\n }\n bool hasLowPtPhots = false;\n bool hasHighEtaPhots = false;\n for(int i=0; i<data.nphot; i++) {\n if (data.phot_pt->at(i) < 20) hasLowPtPhots = true;\n\tif (data.phot_eta->at(i) > 2.5) hasHighEtaPhots = true;\n }\n\n // Single photon cuts\n if (hasLowPtPhots || hasHighEtaPhots) continue;\n cutflow.increment(1, data.sample, data.weight);\n\n // diphoton cut\n if (mgg < 110.0 || mgg > 130.0) continue;\n cutflow.increment(2, data.sample, data.weight);\n\n // Lepton cuts\n if (hasHighPtElecs || hasLowEtaElecs || hasHighPtMuons || hasLowEtaMuons) continue;\n cutflow.increment(3, data.sample, data.weight);\n\n // Met cut\n if (data.nopu_met < 100) continue;\n cutflow.increment(4, data.sample, data.weight);\n\n////////////////////////////////////////////////////////////////////////////////////////////\n\n //Fill histograms after analysis cuts\n h1met_nopu. Fill(data.sample, data.nopu_met, data.weight);\n\n // fill limit setting histograms:\n if (data.sample < 20) hfit_bkg.Fill(data.nopu_met, data.weight);\n if (data.sample == 20) hfit_sig1.Fill(data.nopu_met, data.weight);\n \n \n }\n \n cout << \"\\n\";\n\n cout << \"SUMMARY: read \" << count << \" of \" << tree->GetEntries() << \" events from analysis tree.\\n\";\n \n TFile * foutroot = new TFile(outroot.c_str(), \"RECREATE\");\n foutroot->cd();\n aw.WriteAll();\n foutroot->Close();\n\n cout << \"Cutflow: Stage 0 (gg preselection)\" << endl;\n cutflow.print(0);\n\n cout << \"Cutflow: Stage 1 (after single photon cuts)\" << endl;\n cutflow.print(1);\n\n cout << \"Cutflow: Stage 2 (after diphoton cut)\" << endl;\n cutflow.print(2);\n\n cout << \"Cutflow: Stage 3 (after single lepton cuts)\" << endl;\n cutflow.print(3);\n\n cout << \"Cutflow: Stage 4 (after Met cut)\" << endl;\n cutflow.print(4);\n\n //cout << \"Fit Histogram Summary: \\n\";\n //double SIGTOT = lumi * 149.8;\n //hfit_bkg.Scale(1.0/SIGTOT);\n //hfit_sig1.Scale(1.0/SIGTOT);\n /*hfit_sig21.Scale(1.0/SIGTOT);\n hfit_sig22.Scale(1.0/SIGTOT);\n hfit_sig23.Scale(1.0/SIGTOT);\n hfit_sig24.Scale(1.0/SIGTOT);*/\n //cout << \" -> using total signal events of : \" << SIGTOT << \"\\n\";\n //cout << \" -> background integral (evts): \" << hfit_bkg.GetSumOfWeights() << \"\\n\";\n //cout << \" -> signal 1 integral (eff): \" << hfit_sig1.GetSumOfWeights() << \"\\n\";\n /*cout << \" -> signal 10 integral (eff): \" << hfit_sig21.GetSumOfWeights() << \"\\n\";\n cout << \" -> signal 100 integral (eff): \" << hfit_sig22.GetSumOfWeights() << \"\\n\";\n cout << \" -> signal 500 integral (eff): \" << hfit_sig23.GetSumOfWeights() << \"\\n\";\n cout << \" -> signal 1000 integral (eff): \" << hfit_sig24.GetSumOfWeights() << \"\\n\";*/\n //cout << \" -> local count of signal events: \" << nsig << \"\\n\";\n //cout << \" -> local integral of signal weight: \" << wsig << \"\\n\";\n\n //cout << \" --> signal 1 sensitivity: \" << sensitivity(&hfit_sig1, &hfit_bkg, SIGTOT) << \"\\n\";\n /*cout << \" --> signal 10 sensitivity: \" << sensitivity(&hfit_sig21, &hfit_bkg, SIGTOT) << \"\\n\";\n cout << \" --> signal 100 sensitivity: \" << sensitivity(&hfit_sig22, &hfit_bkg, SIGTOT) << \"\\n\";\n cout << \" --> signal 500 sensitivity: \" << sensitivity(&hfit_sig23, &hfit_bkg, SIGTOT) << \"\\n\";\n cout << \" --> signal 1000 sensitivity: \" << sensitivity(&hfit_sig24, &hfit_bkg, SIGTOT) << \"\\n\";*/\n\n char name[100];\n TFile * f = NULL;\n TH1F * h = NULL;\n\n sprintf(name, \"%s/mchi1.root\", outdir.c_str());\n f = new TFile(name, \"RECREATE\");\n f->cd();\n h = (TH1F *) hfit_sig1.Clone(\"signal\");\n h->Write();\n hfit_bkg.Write();\n f->Close();\n\n sprintf(name, \"%s/mchi10.root\", outdir.c_str());\n f = new TFile(name, \"RECREATE\");\n f->cd();\n h = (TH1F *) hfit_sig21.Clone(\"signal\");\n h->Write();\n hfit_bkg.Write();\n f->Close();\n\n sprintf(name, \"%s/mchi100.root\", outdir.c_str());\n f = new TFile(name, \"RECREATE\");\n f->cd();\n h = (TH1F *) hfit_sig22.Clone(\"signal\");\n h->Write();\n hfit_bkg.Write();\n f->Close();\n\n sprintf(name, \"%s/mchi500.root\", outdir.c_str());\n f = new TFile(name, \"RECREATE\");\n f->cd();\n h = (TH1F *) hfit_sig23.Clone(\"signal\");\n h->Write();\n hfit_bkg.Write();\n f->Close();\n\n sprintf(name, \"%s/mchi1000.root\", outdir.c_str());\n f = new TFile(name, \"RECREATE\");\n f->cd();\n h = (TH1F *) hfit_sig24.Clone(\"signal\");\n h->Write();\n hfit_bkg.Write();\n f->Close();\n\n}\n\n\n" }, { "alpha_fraction": 0.6429378390312195, "alphanum_fraction": 0.7118644118309021, "avg_line_length": 67.07691955566406, "blob_id": "6610de562f2225b467d4f22c65984cf073945112", "content_id": "f16696a267e50087121171228996bb87ea887548", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 885, "license_type": "no_license", "max_line_length": 182, "num_lines": 13, "path": "/run/scripts/fill_100tev_hists.sh", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nsource COMPILE\n\n#./bin/AnalyzeHxx --8tev --fake_rate=1E-5 --num_smear=100 --met_smear=20 ../data/Analysis/CMSSW/DAS/8TeV/all.root ../results/8TeV/latest.root ../results/8TeV/\n\n#./bin/AnalyzeHxx --8tev --fake_rate=1E-5 --num_smear=100 --met_smear=20 ../data/Analysis/CMSSW/DAS_100k/8TeV/all.root ../results/8TeV/latest_100k.root ../results/8TeV/\n\n#./bin/AnalyzeHxx --8tev --fake_rate=1E-5 --num_smear=100 --met_smear=20 ../data/Analysis/CMSSW/DAS_Full/8TeV/all.root ../results/8TeV/latest_Full.root ../results/8TeV/\n\n./bin/AnalyzeHxx --8tev --fake_rate=1E-5 --num_smear=100 --met_smear=20 ../data/Analysis/CMSSW/DAS_Full/8TeV/all.root ../results/8TeV/latest_Full_Combo.root ../results/8TeV/\n\n#./bin/AnalyzeHxx --8tev --fake_rate=1E-5 --num_smear=100 --met_smear=20 ../data/Analysis/CMSSW/MCValidation/all.root ../results/8TeV/latest_MCValidation_4emuta.root ../results/8TeV/\n" }, { "alpha_fraction": 0.49618321657180786, "alphanum_fraction": 0.5453774333000183, "avg_line_length": 34.69696807861328, "blob_id": "4c1d605a030fefbe5de8706095f008a7fbf0efcf", "content_id": "2c93f8612b8f35b44a27dfc057fb7a746dd8de3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1179, "license_type": "no_license", "max_line_length": 147, "num_lines": 33, "path": "/run/scripts/calc_xsections_33tev.py", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n# Branching ratios from PDG and https://twiki.cern.ch/twiki/bin/view/LHCPhysics/CERNYellowReportPageBR2#Higgs_2_gauge_bosons\n# Assumes mH=126 GeV\nBR_H_AA = 2.28E-03\n# Z->v v~ : 20.0% = 0.200\nBR_Z_VV = 0.200\n# W->l v : 10.8 * 2% = 0.216\nBR_W_LV = 0.216\n\n\n# Higgs production cross sections in fb from https://twiki.cern.ch/twiki/bin/view/LHCPhysics/HiggsEuropeanStrategy#SM_Higgs_decay_branching_ratio_M\nPB_TO_FB = 1E3\nSIGMA_H = (178.3 + 16.5) * PB_TO_FB\nSIGMA_WH = 4.71 * PB_TO_FB\nSIGMA_ZH = 2.97 * PB_TO_FB \n\n# Background production cross sections from madgraph\nSIGMA_AA = 1\nSIGMA_ZAA = 1\n\n# Signal cross section is taken to be 100 pb:\nSIGMA_HXX = 100 * PB_TO_FB\n\nprint \"Sigma x BR in fb at 33 TeV\"\nprint \"Backgrounds: \"\nprint \"Zh, Z->vv ........................\", SIGMA_ZH * BR_Z_VV\nprint \"Wh, W->lv ........................\", SIGMA_WH * BR_W_LV\nprint \"h->aa ........................\", SIGMA_H * BR_H_AA\nprint \"aa ........................\", SIGMA_AA\nprint \"Zaa, Z->vv ........................\", SIGMA_ZAA * BR_Z_VV\nprint \"Signal: \"\nprint \"Hxx ........................\", SIGMA_HXX \n" }, { "alpha_fraction": 0.6204894185066223, "alphanum_fraction": 0.6271256804466248, "avg_line_length": 24.09375, "blob_id": "cd904c927f775adaf970330f26a5e0fede0f2a02", "content_id": "0e8ebc53fdc142088dd4934e75be0fbdbd47e0d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2411, "license_type": "no_license", "max_line_length": 119, "num_lines": 96, "path": "/src/histogram_manager.cpp", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <stdlib.h>\n\n#include \"TH1F.h\"\n\n#include \"histogram_manager.h\"\n\nusing namespace std;\n\n\n\nhistogram_manager::histogram_manager(){ init(); }\n \nhistogram_manager::histogram_manager(TH1F * hbase ){ \n init(); set_base_histogram(hbase); \n}\n \nhistogram_manager::histogram_manager(TH1F * hbase, const histogram_manager & hm){ \n init(); set_base_histogram(hbase); copy_samples_from(hm); \n}\n\nhistogram_manager::histogram_manager(TH1F * hbase, const histogram_manager & hm, auto_write & aw){ \n init(); set_base_histogram(hbase); copy_samples_from(hm); add_auto_write(aw);\n}\n\n// add to an automatic write service:\nvoid histogram_manager::add_auto_write(auto_write & aw){ aw.AutoWrite(*this); }\n\n\nvoid histogram_manager::add_sample(int sample, const std::string & tag){\n string hname(hbase->GetName());\n hname += tag;\n \n if (! hbase){cout << \"ERROR: no base histogram defined!\\n\"; exit(0); }\n\n this->sample.push_back (sample);\n this->tag.push_back (tag);\n //cout << \"INFO: adding histogram named \" << hname << \" to managed collection.\\n\";\n TH1F * temp = (TH1F*) hbase->Clone(hname.c_str());\n temp->Sumw2();\n vhist.push_back((TH1F*) temp);\n\n}\n\nvoid histogram_manager::copy_samples_from(const histogram_manager & hm){\n int n = hm.sample.size();\n for (int i=0; i<n; i++){\n add_sample(hm.sample[i], hm.tag[i]);\n }\n}\n\nint histogram_manager::index(int sample){\n int n = this->sample.size();\n for (int i=0; i<n; i++){\n if (sample == this->sample[i]){\n return i;\n }\n }\n if (! hbase) { cout << \"ERROR: no base histogram defined!\\n\"; exit(0); }\n cout << \"ERROR: undefined sample id \" << sample << \" requested for histogram manager \" << hbase->GetName() << \"\\n\";\n exit(0);\n return 0;\n}\n\nvoid histogram_manager::Fill(int sample, double x){\n vhist[index(sample)]->Fill(x);\n}\n\nvoid histogram_manager::Fill(int sample, double x, double w){\n vhist[index(sample)]->Fill(x, w);\n}\n\nvoid histogram_manager::WriteAll(){\n hbase->Write();\n int n = sample.size();\n for (int i=0; i<n; i++){\n vhist[i]->Write();\n }\n}\n\n\nauto_write::auto_write(){\n write_list.clear();\n}\n\n// Automatically write to the file list:\nvoid auto_write::AutoWrite(histogram_manager & hm){ \n write_list.push_back(&hm); \n}\n\nvoid auto_write::WriteAll(){\n int n = write_list.size();\n for (int i=0; i<n; i++){\n write_list[i]->WriteAll();\n }\n}\n\n\n" }, { "alpha_fraction": 0.5218659043312073, "alphanum_fraction": 0.5374149680137634, "avg_line_length": 24.725000381469727, "blob_id": "b271c84700acb3e0c21d166f2c1266d8beae6105", "content_id": "5bae45ae18c4ffe2f8b9724aae94a583f7a11a64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2058, "license_type": "no_license", "max_line_length": 80, "num_lines": 80, "path": "/src/cutflow_tool.cpp", "repo_name": "dburns7/hxx_2a100tev", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include <iostream>\n#include <iomanip>\n\n#include \"cutflow_tool.h\"\n#include \"math.h\"\n\nusing namespace std;\n\ncutflow_tool::cutflow_tool(){\n evt_counts.clear();\n}\n\nvoid cutflow_tool::increment(int stage, int sample, double weight){\n if (stage >= evt_counts.size()) {\n evt_counts.resize(stage+1);\n wsq_counts.resize(stage+1);\n }\n std::vector<double> & x = evt_counts[stage]; \n std::vector<double> & x2 = wsq_counts[stage]; \n if (sample >= x.size()){\n x.resize(sample+1,0);\n x2.resize(sample+1,0);\n }\n x[sample] += weight;\n x2[sample] += weight*weight;\n\n}\n\ndouble cutflow_tool::count(int stage, int sample){\n if (stage >= evt_counts.size()) return 0;\n std::vector<double> & x = evt_counts[stage]; \n if (sample >= x.size()) return 0;\n return x[sample];\n}\n\nvoid cutflow_tool::print(int stage){\n if (stage >= evt_counts.size()) return; \n std::vector<double> & x = evt_counts[stage]; \n std::vector<double> & x2 = wsq_counts[stage]; \n\n for (int i=0; i<x.size(); i++){\n double evts = x[i];\n double devts = sqrt(x2[i]); \n if (evts > 0.0) {\n if ((sample_names.size() > i) && (sample_names[i] != \"\"))\n cout << setw(10) << sample_names[i];\n else \n cout << \"sample \" << setw(3) << i;\n cout << \" events: \" << evts << \" +/-\" << devts << \"\\n\";\n }\n }\n\n double bkg = 0;\n for (int i=0; i<x.size(); i++){\n if (i < 20) bkg+= x[i];\n }\n cout << \"Total Background: \" << bkg << \"\\n\";\n\n if (bkg <= 0.0) return;\n \n for (int i=0; i<x.size(); i++){\n if (i >= 20){\n if ((sample_names.size() > i) && (sample_names[i] != \"\"))\n\t cout << setw(10) << sample_names[i];\n else \n\t cout << \"sample \" << setw(3) << i;\n cout << \" S / sqrt(B) = \" << x[i] / sqrt(bkg) << \"\\n\";\n }\n }\n\n\n\n}\n\nvoid cutflow_tool::add_sample_name(int sample, const std::string & sample_name){\n std::string empty = \"\";\n if (sample >= sample_names.size()) sample_names.resize(sample+1, empty);\n sample_names[sample] = sample_name;\n}\n" } ]
10
silvacms/Products.SilvaNews
https://github.com/silvacms/Products.SilvaNews
d084d3e147143324717423f380a0b79678539059
e14c13fd7a93f63b00980b66e64020c0900e8597
2524eb4ba3ad36a4bfca3841fb442137e26ea426
refs/heads/master
2016-09-02T00:43:05.640411
2013-12-12T15:38:41
2013-12-12T15:38:41
15,139,779
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6821191906929016, "alphanum_fraction": 0.692052960395813, "avg_line_length": 30.241378784179688, "blob_id": "0be9172c8bff71d94c3d26721515b0dae357592d", "content_id": "ce07bf1a0ada60ebf921eeb67755cbad8c6fa380", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "permissive", "max_line_length": 65, "num_lines": 29, "path": "/Products/SilvaNews/testing.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2011-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom Products.Silva.testing import SilvaLayer\nimport Products.SilvaNews\nimport transaction\n\n\nclass SilvaNewsLayer(SilvaLayer):\n default_products = SilvaLayer.default_products + [\n 'SilvaExternalSources',\n 'SilvaDocument',\n ]\n default_packages = SilvaLayer.default_packages + [\n 'silva.app.document',\n 'silva.app.news'\n ]\n\n def _install_application(self, app):\n super(SilvaNewsLayer, self)._install_application(app)\n app.root.service_extensions.install('silva.app.document')\n app.root.service_extensions.install('silva.app.news')\n app.root.service_extensions.install('SilvaDocument')\n app.root.service_extensions.install('SilvaNews')\n transaction.commit()\n\n\nFunctionalLayer = SilvaNewsLayer(Products.SilvaNews)\n" }, { "alpha_fraction": 0.6555540561676025, "alphanum_fraction": 0.6575543284416199, "avg_line_length": 35.93595886230469, "blob_id": "f88bb4b8a0b3ccf74b9d4b403d6f2c0682a4a996", "content_id": "0f246a73467f43b5689c10d432a7e07075ce6837", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7499, "license_type": "permissive", "max_line_length": 78, "num_lines": 203, "path": "/Products/SilvaNews/NewsItem.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2002-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom five import grok\n\n# Zope\nfrom AccessControl import ClassSecurityInfo\nfrom App.class_init import InitializeClass\nfrom DateTime import DateTime\n\n# Silva\nfrom Products.Silva import SilvaPermissions\nfrom Products.SilvaDocument import Document\nfrom Products.SilvaDocument.rendering.xsltrendererbase import XSLTTransformer\nfrom silva.core import conf as silvaconf\nfrom silva.core.interfaces import IRoot\nfrom silva.core.views import views as silvaviews\n\nfrom Products.SilvaNews.NewsCategorization import NewsCategorization\nfrom Products.SilvaNews.interfaces import INewsItem, INewsItemVersion\nfrom silva.app.news.datetimeutils import CalendarDatetime\nfrom silva.app.news.datetimeutils import datetime_to_unixtimestamp\nfrom silva.app.news.interfaces import INewsPublication\n\n\nclass NewsItemVersion(NewsCategorization, Document.DocumentVersion):\n \"\"\"Base class for news item versions.\n \"\"\"\n security = ClassSecurityInfo()\n grok.implements(INewsItemVersion)\n meta_type = \"Obsolete Article Version\"\n _external_url = None # For backward compatibility.\n\n def __init__(self, id):\n super(NewsItemVersion, self).__init__(id)\n self._display_datetime = None\n\n security.declareProtected(SilvaPermissions.ChangeSilvaContent,\n 'set_display_datetime')\n def set_display_datetime(self, ddt):\n \"\"\"set the display datetime\n\n this datetime is used to determine whether an item should be shown\n in the news viewer, and to determine the order in which the items\n are shown\n \"\"\"\n self._display_datetime = DateTime(ddt)\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'get_display_datetime')\n def get_display_datetime(self):\n \"\"\"returns the display datetime\n\n see 'set_display_datetime'\n \"\"\"\n return self._display_datetime\n\n # ACCESSORS\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'get_intro')\n def get_intro(self, max_size=128, request=None):\n \"\"\"Returns first bit of the news item's content\n\n this returns all elements up to and including the first\n paragraph, if it turns out that there are more than max_size\n characters in the data returned it will truncate (per element)\n to minimally 1 element\n \"\"\"\n # XXX fix intro, remove this function.\n return u\"XXX: FIXME\"\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'get_description')\n def get_description(self):\n return self.service_metadata.getMetadataValue(\n self, 'silva-extra', 'content_description')\n\n def _get_source(self):\n c = self.aq_inner.aq_parent\n while True:\n if INewsPublication.providedBy(c):\n return c\n if IRoot.providedBy(c):\n return None\n c = c.aq_parent\n return None\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'source_path')\n def source_path(self):\n \"\"\"Returns the path to the source containing this item\n \"\"\"\n source = self._get_source()\n if not source:\n return None\n return source.getPhysicalPath()\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'is_private')\n def is_private(self):\n \"\"\"Returns whether the object is in a private source\n \"\"\"\n source = self._get_source()\n if not source:\n return False\n return self.service_metadata.getMetadataValue(\n source, 'snn-np-settings', 'is_private')\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'last_author_fullname')\n def last_author_fullname(self):\n \"\"\"Returns the userid of the last author, to be used in\n combination with the ZCatalog. The data this method returns\n can, in opposite to the sec_get_last_author_info data, be\n stored in the ZCatalog without any problems.\n \"\"\"\n return self.sec_get_last_author_info().fullname()\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'fulltext')\n def fulltext(self):\n \"\"\"Returns all data as a flat string for full text-search\n \"\"\"\n keywords = list(self._subjects)\n keywords.extend(self._target_audiences)\n keywords.extend(super(NewsItemVersion, self).fulltext())\n return keywords\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'publication_time')\n def publication_time(self):\n binding = self.service_metadata.getMetadata(self)\n return binding.get('silva-extra', 'publicationtime')\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'sort_index')\n def sort_index(self):\n dt = self.get_display_datetime()\n if dt:\n return datetime_to_unixtimestamp(dt)\n return None\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'get_timestamp_ranges')\n def get_timestamp_ranges(self):\n if self._display_datetime:\n return CalendarDatetime(self._display_datetime, None).\\\n get_unixtimestamp_ranges()\n\n\nInitializeClass(NewsItemVersion)\n\n\nclass NewsItem(Document.Document):\n \"\"\"A News item that appears as an individual page. By adjusting\n settings the Author can determine which subjects, and\n for which audiences the Article should be presented.\n \"\"\"\n grok.implements(INewsItem)\n security = ClassSecurityInfo()\n meta_type = \"Obsolete Article\"\n silvaconf.icon(\"www/news_item.png\")\n silvaconf.priority(3.7)\n silvaconf.version_class(NewsItemVersion)\n\n security.declareProtected(SilvaPermissions.ApproveSilvaContent,\n 'set_next_version_display_datetime')\n def set_next_version_display_datetime(self, dt):\n \"\"\"Set display datetime of next version.\n \"\"\"\n version = getattr(self, self.get_next_version())\n version.set_display_datetime(dt)\n\n security.declareProtected(SilvaPermissions.ChangeSilvaContent,\n 'set_unapproved_version_display_datetime')\n def set_unapproved_version_display_datetime(self, dt):\n \"\"\"Set display datetime for unapproved\n \"\"\"\n version = getattr(self, self.get_unapproved_version())\n version.set_display_datetime(dt)\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'get_unapproved_version_display_datetime')\n def get_unapproved_version_display_datetime(self):\n \"\"\"get display datetime for unapproved\n \"\"\"\n version = getattr(self, self.get_unapproved_version())\n version.get_display_datetime()\n\nInitializeClass(NewsItem)\n\n\nNewsHTML = XSLTTransformer('newsitem.xslt', __file__)\n\n\nclass NewsItemView(silvaviews.View):\n \"\"\" View on a News Item (either Article / Agenda )\n \"\"\"\n grok.context(INewsItem)\n\n def render(self):\n return NewsHTML.transform(self.content, self.request)\n\n" }, { "alpha_fraction": 0.5685279369354248, "alphanum_fraction": 0.5775521993637085, "avg_line_length": 28.065574645996094, "blob_id": "f0068b42732976d576b8ca5be4f94a27122bba8f", "content_id": "ec67c561f473cbb1113b8b4e072f38a2cc225ba6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1773, "license_type": "no_license", "max_line_length": 83, "num_lines": 61, "path": "/setup.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2002-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom setuptools import setup, find_packages\nimport os\n\nversion = '3.0.2dev'\n\ntests_require = [\n 'Products.Silva [test]',\n 'Products.SilvaDocument [test]',\n ]\n\ndef product_readme(filename):\n return open(os.path.join('Products', 'SilvaNews', filename)).read()\n\n\nsetup(name='Products.SilvaNews',\n version=version,\n description=\"News extension for Silva 2\",\n long_description=product_readme(\"README.txt\") + \"\\n\" +\n product_readme(\"HISTORY.txt\"),\n\n classifiers=[\n \"Framework :: Zope2\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords='news silva zope2',\n author='Infrae',\n author_email='[email protected]',\n url='https://github.com/silvacms/Products.SilvaNews',\n license='BSD',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['Products'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'five.grok',\n 'Products.Silva',\n 'Products.SilvaDocument',\n 'python-dateutil',\n 'setuptools',\n 'silva.app.news',\n 'silva.core.conf',\n 'silva.core.interfaces',\n 'silva.core.smi',\n 'silva.core.upgrade',\n 'silva.core.views',\n 'z3locales',\n 'zope.interface',\n ],\n tests_require = tests_require,\n extras_require = {'test': tests_require},\n entry_points = \"\"\"\n [zodbupdate]\n renames = Products.SilvaNews:CLASS_CHANGES\n \"\"\"\n )\n" }, { "alpha_fraction": 0.6845637559890747, "alphanum_fraction": 0.6912751793861389, "avg_line_length": 30.13953399658203, "blob_id": "e19703e2a5da8f5eec366d7db0b1436398bdbc84", "content_id": "9925cd1a8d3f9e946b6f2d9694c2d9aff5f48ce7", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1341, "license_type": "permissive", "max_line_length": 75, "num_lines": 43, "path": "/Products/SilvaNews/NewsCategorization.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2011-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\n# Zope\nfrom AccessControl import ClassSecurityInfo\nfrom App.class_init import InitializeClass\nfrom Products.Silva import SilvaPermissions\n\n\nclass NewsCategorization(object):\n security = ClassSecurityInfo()\n\n def __init__(self, id):\n super(NewsCategorization, self).__init__(id)\n self._subjects = set()\n self._target_audiences = set()\n\n security.declareProtected(\n SilvaPermissions.ChangeSilvaContent, 'set_subjects')\n def set_subjects(self, subjects):\n self._subjects = set(subjects)\n\n security.declareProtected(\n SilvaPermissions.ChangeSilvaContent, 'set_target_audiences')\n def set_target_audiences(self, target_audiences):\n self._target_audiences = set(target_audiences)\n\n security.declareProtected(\n SilvaPermissions.AccessContentsInformation, 'get_subjects')\n def get_subjects(self):\n \"\"\"Returns the subjects\n \"\"\"\n return set(self._subjects or [])\n\n security.declareProtected(\n SilvaPermissions.AccessContentsInformation, 'get_target_audiences')\n def get_target_audiences(self):\n \"\"\"Returns the target audiences\n \"\"\"\n return set(self._target_audiences or [])\n\nInitializeClass(NewsCategorization)\n\n\n" }, { "alpha_fraction": 0.7071428298950195, "alphanum_fraction": 0.7392857074737549, "avg_line_length": 30.11111068725586, "blob_id": "163ea937934f6df6e81f996060e7750c1ffa3bc4", "content_id": "a9a7caad8e0cff9919b418f4a06267f4c8cb8457", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "permissive", "max_line_length": 64, "num_lines": 9, "path": "/Products/SilvaNews/silvaxml/__init__.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n# this is a package\n\nfrom silva.core.xml import registerNamespace\n\nNS_SILVA_NEWS = 'http://infrae.com/namespace/silva-news-network'\nregisterNamespace('silvanews', NS_SILVA_NEWS)\n" }, { "alpha_fraction": 0.6400787830352783, "alphanum_fraction": 0.6445100903511047, "avg_line_length": 23.154762268066406, "blob_id": "43c25873da3b67a33650a49bc072400771f86298", "content_id": "5d40a7cf720f465da5649a299bf35735fad40422", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2031, "license_type": "permissive", "max_line_length": 73, "num_lines": 84, "path": "/Products/SilvaNews/interfaces.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2002-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom zope.interface import Interface\n\nfrom Products.SilvaDocument.interfaces import IDocument, IDocumentVersion\n\n\nclass ISilvaNewsExtension(Interface):\n \"\"\"Marker interface for SNN Extension\"\"\"\n\n\nclass INewsCategorization(Interface):\n \"\"\"Categorize news information by subject and target audience.\n \"\"\"\n\n def get_subjects():\n \"\"\"Returns the list of subjects.\"\"\"\n\n def get_target_audiences():\n \"\"\"Returns the list of target audiences.\"\"\"\n\n def set_subjects(subjects):\n \"\"\"Updates the list of subjects\"\"\"\n\n def set_target_audiences(target_audiences):\n \"\"\"Updates the list of target_audiences\"\"\"\n\n\nclass INewsItem(IDocument):\n \"\"\"Silva News Item interface\n \"\"\"\n\n\nclass INewsItemVersion(IDocumentVersion, INewsCategorization):\n \"\"\"Silva news item version.\n\n This contains the real content for a news item.\n \"\"\"\n\n def source_path():\n \"\"\"Returns the physical path of the versioned content.\"\"\"\n\n def is_private():\n \"\"\"Returns true if the item is private.\n\n Private items are picked up only by news filters in the same\n container as the source.\n \"\"\"\n\n def fulltext():\n \"\"\"Returns a string containing all the words of all content.\n\n For fulltext ZCatalog search.\n XXX This should really be on an interface in the Silva core\"\"\"\n\n\nclass IAgendaItem(INewsItem):\n \"\"\"Silva AgendaItem Version.\n \"\"\"\n\n\nclass IAgendaItemVersion(INewsItemVersion):\n def get_start_datetime():\n \"\"\"Returns start_datetime\n \"\"\"\n\n def get_end_datetime():\n \"\"\"Returns end_datetime\n \"\"\"\n\n def get_location():\n \"\"\"Returns location\n \"\"\"\n\n def set_start_datetime(value):\n \"\"\"Sets the start datetime to value (DateTime)\"\"\"\n\n def set_end_datetime(value):\n \"\"\"Sets the end datetime to value (DateTime)\"\"\"\n\n def set_location(value):\n \"\"\"Sets the location\"\"\"\n\n\n" }, { "alpha_fraction": 0.6307222843170166, "alphanum_fraction": 0.6333672404289246, "avg_line_length": 35.400001525878906, "blob_id": "da014668a7ce9f5c1374f3b842e1009f0818abf1", "content_id": "6316b03a3204f9383e8ced8abd2669a268e9c266", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4915, "license_type": "permissive", "max_line_length": 80, "num_lines": 135, "path": "/Products/SilvaNews/silvaxml/xmlimport.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2002-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom silva.core.xml import handlers\nfrom Products.Silva.silvaxml.xmlimport import NS_SILVA_URI as NS_URI\nfrom Products.Silva import mangle\nfrom silva.core import conf as silvaconf\n\nfrom Products.SilvaNews.silvaxml.xmlexport import NS_SILVA_NEWS\nfrom Products.SilvaNews.silvaxml import helpers\nfrom Products.SilvaNews.NewsItem import (\n NewsItem, NewsItemVersion)\nfrom Products.SilvaNews.AgendaItem import (\n AgendaItem, AgendaItemVersion)\nfrom Products.SilvaDocument.silvaxml.xmlimport import DocXMLHandler\nfrom Products.SilvaDocument.silvaxml import NS_DOCUMENT_URI as NS_SILVA_DOCUMENT\n\nsilvaconf.namespace(NS_SILVA_NEWS)\n\n\nclass SNNHandlerMixin(object):\n \"\"\" mixin class to handle shared attribute setting across\n many of the SNN objects \"\"\"\n\n def set_attrs(self,attrs,obj):\n helpers.set_attribute_as_list(obj, 'target_audiences', attrs)\n helpers.set_attribute_as_list(obj, 'subjects', attrs)\n helpers.set_attribute_as_bool(obj, 'number_is_days', attrs)\n helpers.set_attribute_as_bool(obj, 'show_agenda_items', attrs)\n helpers.set_attribute_as_bool(obj, 'keep_to_path', attrs)\n helpers.set_attribute_as_int(obj, 'number_to_show', attrs)\n helpers.set_attribute_as_int(obj, 'number_to_show_archive', attrs)\n if attrs.has_key((None,'excluded_items')):\n eis = attrs[(None,'excluded_items')]\n for ei in eis.split(','):\n obj.add_excluded_item(ei)\n\n\nclass NewsItemHandler(handlers.SilvaHandler):\n silvaconf.name('plainarticle')\n\n def getOverrides(self):\n return {(NS_URI, 'content'): NewsItemContentHandler}\n\n def startElementNS(self, name, qname, attrs):\n if name == (NS_SILVA_NEWS, 'plainarticle'):\n id = attrs[(None, 'id')].encode('utf-8')\n uid = self.generateOrReplaceId(id)\n object = NewsItem(uid)\n self.parent()._setObject(uid, object)\n self.setResultId(uid)\n\n def endElementNS(self, name, qname):\n if name == (NS_SILVA_NEWS, 'plainarticle'):\n self.notifyImport()\n\n\nclass NewsItemContentHandler(handlers.SilvaVersionHandler):\n silvaconf.baseclass()\n\n def getOverrides(self):\n return{(NS_SILVA_DOCUMENT, 'doc'): DocXMLHandler}\n\n def startElementNS(self, name, qname, attrs):\n if name == (NS_URI, 'content'):\n id = attrs[(None, 'version_id')].encode('utf-8')\n if not mangle.Id(self._parent, id).isValid():\n return\n version = NewsItemVersion(id)\n parent = self.parent()\n parent._setObject(id, version)\n version = version.__of__(parent)\n\n helpers.set_attribute_as_list(version, 'target_audiences', attrs)\n helpers.set_attribute_as_list(version, 'subjects', attrs)\n helpers.set_attribute_as_naive_datetime(\n version, 'display_datetime', attrs)\n\n self.setResultId(id)\n self.updateVersionCount()\n\n def endElementNS(self, name, qname):\n if name == (NS_URI, 'content'):\n self.storeMetadata()\n self.storeWorkflow()\n\n\nclass AgendaItemHandler(handlers.SilvaHandler):\n silvaconf.name('plainagendaitem')\n\n def getOverrides(self):\n return {(NS_URI, 'content'): AgendaItemContentHandler}\n\n def startElementNS(self, name, qname, attrs):\n if name == (NS_SILVA_NEWS, 'plainagendaitem'):\n id = attrs[(None, 'id')].encode('utf-8')\n uid = self.generateOrReplaceId(id)\n object = AgendaItem(uid)\n self.parent()._setObject(uid, object)\n self.setResultId(uid)\n\n def endElementNS(self, name, qname):\n if name == (NS_SILVA_NEWS, 'plainagendaitem'):\n self.notifyImport()\n\n\nclass AgendaItemContentHandler(handlers.SilvaVersionHandler):\n silvaconf.baseclass()\n\n def getOverrides(self):\n return{(NS_SILVA_DOCUMENT, 'doc'): DocXMLHandler}\n\n def startElementNS(self, name, qname, attrs):\n if name == (NS_URI, 'content'):\n id = attrs[(None, 'version_id')].encode('utf-8')\n if not mangle.Id(self._parent, id).isValid():\n return\n version = AgendaItemVersion(id)\n parent = self.parent()\n parent._setObject(id, version)\n version = version.__of__(parent)\n\n helpers.set_attribute_as_list(version, 'target_audiences', attrs)\n helpers.set_attribute_as_list(version, 'subjects', attrs)\n helpers.set_attribute_as_naive_datetime(\n version, 'display_datetime', attrs)\n\n self.setResultId(id)\n self.updateVersionCount()\n\n def endElementNS(self, name, qname):\n if name == (NS_URI, 'content'):\n self.storeMetadata()\n self.storeWorkflow()\n\n" }, { "alpha_fraction": 0.6490157246589661, "alphanum_fraction": 0.6555117964744568, "avg_line_length": 41.68067169189453, "blob_id": "458f8d0d77b5070b50f5d0f0dfbf9df17efb24d3", "content_id": "4cb1043f23c2f328e751d3acdf5fd3e4491af916", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5080, "license_type": "permissive", "max_line_length": 77, "num_lines": 119, "path": "/Products/SilvaNews/tests/test_upgrader.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nimport unittest\n\nfrom Products.Silva.testing import tests\nfrom Products.SilvaNews.testing import FunctionalLayer\nfrom Products.SilvaNews.upgrader.upgrade_220 import publication_upgrader\nfrom Products.SilvaNews.upgrader.upgrade_230 import filter_upgrader\nfrom Products.SilvaNews.upgrader.upgrade_230 import viewer_upgrader\nfrom Products.SilvaNews.upgrader.upgrade_300 import upgrade_agendaviewer\nfrom Products.SilvaMetadata.interfaces import IMetadataService\n\nfrom zope.component import getUtility\nfrom zope.interface.verify import verifyObject\nfrom silva.core.services.interfaces import ICatalogService\nfrom silva.app.news.NewsPublication import NewsPublication\nfrom silva.app.news.filters.NewsFilter import NewsFilter\nfrom silva.app.news.viewers.NewsViewer import NewsViewer\nfrom silva.app.news.viewers.AgendaViewer import AgendaViewer\nfrom silva.app.news.interfaces import INewsFilter, INewsViewer\n\n\nclass UpgraderTestCase(unittest.TestCase):\n layer = FunctionalLayer\n maxDiff = None\n\n def setUp(self):\n self.root = self.layer.get_application()\n self.layer.login('editor')\n\n def test_upgrade_news_viewer(self):\n \"\"\"Test upgrade of a news viewer\n \"\"\"\n self.root._setObject('news', NewsFilter('news'))\n self.root._setObject('events', NewsFilter('events'))\n self.root._setObject('viewer', NewsViewer('viewer'))\n self.assertIn('news', self.root.objectIds())\n self.assertIn('events', self.root.objectIds())\n self.assertIn('viewer', self.root.objectIds())\n self.assertIn('index', self.root.objectIds())\n self.root.viewer._filters = [\n '/root/index',\n '/root/news',\n '/root/lala',\n '/root/@@pouet',\n '/root/events']\n self.assertTrue(viewer_upgrader.validate(self.root.viewer))\n self.assertEqual(\n viewer_upgrader.upgrade(self.root.viewer),\n self.root.viewer)\n self.assertFalse(viewer_upgrader.validate(self.root.viewer))\n tests.assertContentItemsEqual(\n self.root.viewer.get_filters(),\n [self.root.news, self.root.events])\n\n def test_upgrade_news_filter(self):\n \"\"\"Test upgrade of a news filter.\n \"\"\"\n self.root._setObject('news', NewsPublication('news'))\n self.root._setObject('events', NewsPublication('events'))\n self.root._setObject('filter', NewsFilter('filter'))\n self.assertIn('news', self.root.objectIds())\n self.assertIn('events', self.root.objectIds())\n self.assertIn('filter', self.root.objectIds())\n self.assertIn('index', self.root.objectIds())\n self.root.filter._sources = [\n '/root/news',\n '/root/events',\n '/root/index',\n '/root/lala',\n '/root/@@pouet']\n self.assertTrue(filter_upgrader.validate(self.root.filter))\n self.assertEqual(\n filter_upgrader.upgrade(self.root.filter),\n self.root.filter)\n self.assertFalse(filter_upgrader.validate(self.root.filter))\n tests.assertContentItemsEqual(\n self.root.filter.get_sources(),\n [self.root.news, self.root.events])\n\n def test_upgrade_news_publication(self):\n \"\"\"Test upgrade of a news publication.\n \"\"\"\n self.root._setObject('news', NewsPublication('news'))\n self.assertIn('news', self.root.objectIds())\n news = self.root.news\n news._is_private = True\n self.assertItemsEqual(news.objectIds(), [])\n self.assertTrue(publication_upgrader.validate(news))\n self.assertEqual(publication_upgrader.upgrade(news), news)\n self.assertFalse(publication_upgrader.validate(news))\n self.assertItemsEqual(news.objectIds(), ['index', 'filter'])\n metadata = getUtility(IMetadataService)\n self.assertEqual(\n metadata.getMetadataValue(news, 'snn-np-settings', 'is_private'),\n 'yes')\n self.assertTrue(verifyObject(INewsViewer, news._getOb('index')))\n self.assertTrue(verifyObject(INewsFilter, news._getOb('filter')))\n catalog = getUtility(ICatalogService)\n self.assertItemsEqual(\n [b.getPath() for b in catalog(\n {'meta_type': 'Silva News Publication',\n 'snn-np-settingsis_private': 'yes'})],\n ['/root/news'])\n\n def test_upgrade_agenda_viewer(self):\n \"\"\"Test upgrade of agenda viewer\n \"\"\"\n self.root._setObject('test_agenda_viewer',\n AgendaViewer('test_agenda_viewer'))\n viewer = self.root.test_agenda_viewer\n viewer._days_to_show = 42 + 1138\n self.assertTrue(upgrade_agendaviewer.validate(viewer))\n self.assertEqual(upgrade_agendaviewer.upgrade(viewer), viewer)\n self.assertFalse(upgrade_agendaviewer.validate(viewer))\n self.assertEqual(viewer.get_number_to_show(), 1138 + 42)\n self.assertTrue(viewer.get_number_is_days())\n\n" }, { "alpha_fraction": 0.6206472516059875, "alphanum_fraction": 0.6272019743919373, "avg_line_length": 32.21088409423828, "blob_id": "49c0b121889b58cbe50e5a5dc58b5cd4b88f6f74", "content_id": "84db8b0c16c1c7481f026f05732954f215492eec", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4882, "license_type": "permissive", "max_line_length": 75, "num_lines": 147, "path": "/Products/SilvaNews/upgrader/upgrade_230.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nimport logging\n\nfrom silva.app.news.interfaces import INewsPublication, INewsItemFilter\nfrom silva.core.upgrade.upgrade import BaseUpgrader, content_path\nfrom Products.ParsedXML.ParsedXML import ParsedXML\nfrom Products.SilvaNews.interfaces import INewsItem\nfrom Products.SilvaDocument.upgrader.upgrade_230 import DocumentUpgrader\n\nfrom zExceptions import NotFound\n\nlogger = logging.getLogger('silva.core.upgrade')\n\n\nVERSION_B1='2.3b1'\nVERSION_B2='2.3b2'\nVERSION_FINAL='2.3'\n\n\nclass ArticleAttributeUpgrader(BaseUpgrader):\n tags = {'pre',}\n\n def validate(self, doc):\n return INewsItem.providedBy(doc)\n\n def upgrade(self, doc):\n # The 3.0 upgrader only upgrade the published, working and\n # last closed version. Only apply this upgrader on thoses.\n for version_id in [doc.get_public_version(),\n doc.get_unapproved_version(),\n doc.get_last_closed_version()]:\n if version_id is None:\n continue\n version = doc._getOb(version_id, None)\n if version is None:\n continue\n if not isinstance(version.content, ParsedXML):\n logger.info(\n u'Upgrade xmlattribute for %s.', content_path(version))\n parsed_xml = version.content._content\n version.content = parsed_xml\n return doc\n\n\nclass ArticleDocumentUpgrader(DocumentUpgrader):\n # Due to a bug in martian, we need to make a new sub class for\n # this upgrader, in order to see it properly grokked.\n pass\n\n\narticle_upgrader_agenda = ArticleAttributeUpgrader(\n VERSION_B1, ['Obsolete Agenda Item', 'Obsolete Article'], -50)\ndocument_upgrader_agenda = ArticleDocumentUpgrader(\n VERSION_B1, ['Obsolete Agenda Item', 'Obsolete Article'], 50)\n\n\nclass NewsAgendaItemVersionCleanup(BaseUpgrader):\n tags = {'pre',}\n\n def validate(self, content):\n if hasattr(content, '_calendar_date_representation'):\n return True\n return False\n\n def upgrade(self, content):\n del content._calendar_date_representation\n return content\n\n\nclass NewsAgendaItemRecurrenceUpgrade(BaseUpgrader):\n tags = {'pre',}\n\n def validate(self, content):\n return not hasattr(content, '_recurrence')\n\n def upgrade(self, content):\n content._end_recurrence_datetime = None\n content._recurrence = None\n return content\n\n\nagenda_item_upgrader = NewsAgendaItemVersionCleanup(\n VERSION_B2, 'Obsolete Agenda Item Version')\nagenda_item_recurrence_upgrader = NewsAgendaItemRecurrenceUpgrade(\n VERSION_B2, 'Obsolete Agenda Item Version')\n\n\nclass NewsFilterUpgrader(BaseUpgrader):\n\n def validate(self, content):\n return '_sources' in content.__dict__\n\n def upgrade(self, content):\n logger.info(u\"Upgrade News Filter %s.\", content_path(content))\n root = content.get_root()\n for source in content._sources:\n try:\n target = root.unrestrictedTraverse(source)\n except (AttributeError, KeyError, NotFound, TypeError):\n logger.error(\n u'Could not find content %s for News Filter %s.',\n source,\n content_path(content))\n continue\n if INewsPublication.providedBy(target):\n content.add_source(target)\n else:\n logger.error(\n u'Content type %s is not an allowed source for %s.',\n content_path(target), content_path(content))\n del content._sources\n return content\n\n\nclass NewsViewerUpgrader(BaseUpgrader):\n\n def validate(self, content):\n return '_filters' in content.__dict__\n\n def upgrade(self, content):\n logger.info(u\"Upgrade News Viewer %s.\", content_path(content))\n root = content.get_root()\n for flt in content._filters:\n try:\n target = root.unrestrictedTraverse(flt)\n except (AttributeError, KeyError, NotFound, TypeError):\n logger.error(\n u'Could not find content %s for News Viewer %s.',\n flt, content_path(content))\n continue\n if INewsItemFilter.providedBy(target):\n content.add_filter(target)\n else:\n logger.error(\n u'Content type %s is not an allowed filter for %s.',\n content_path(target), content_path(content))\n del content._filters\n return content\n\n\nfilter_upgrader = NewsFilterUpgrader(\n VERSION_FINAL, ['Silva News Filter', 'Silva Agenda Filter'])\nviewer_upgrader = NewsViewerUpgrader(\n VERSION_FINAL, ['Silva News Viewer', 'Silva Agenda Viewer'])\n" }, { "alpha_fraction": 0.7446808218955994, "alphanum_fraction": 0.7474968433380127, "avg_line_length": 41.599998474121094, "blob_id": "354985a7c3870b83273978b5a72f64fd2e8b8eb8", "content_id": "709f724bdea2314cf387f33871cac362e19d0d1d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3196, "license_type": "permissive", "max_line_length": 79, "num_lines": 75, "path": "/Products/SilvaNews/__init__.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2004-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom Products.SilvaNews.installer import install\n\nfrom silva.core import conf as silvaconf\n\nsilvaconf.extension_name(\"SilvaNews\")\nsilvaconf.extension_title(\"Silva Obsolete News Network\")\nsilvaconf.extension_depends([\"Silva\", \"SilvaDocument\", \"SilvaExternalSources\"])\n\n\n# Specify import path for old classes (for upgrade)\nCLASS_CHANGES = {\n 'Products.SilvaNews.silvaxmlattribute SilvaXMLAttribute':\n 'OFS.SimpleItem SimpleItem',\n\n 'Products.SilvaNews.PlainAgendaItem PlainAgendaItem':\n 'Products.SilvaNews.AgendaItem AgendaItem',\n 'Products.SilvaNews.PlainAgendaItem PlainAgendaItemVersion':\n 'Products.SilvaNews.AgendaItem AgendaItemVersion',\n 'Products.SilvaNews.PlainArticle PlainArticle':\n 'Products.SilvaNews.NewsItem NewsItem',\n 'Products.SilvaNews.PlainArticle PlainArticleVersion':\n 'Products.SilvaNews.NewsItem NewsItemVersion',\n\n 'Products.SilvaNews.indexing IntegerRangesIndex':\n 'silva.app.news.indexing IntegerRangesIndex',\n\n 'Products.SilvaNews.InlineViewer InlineViewer':\n 'Products.SilvaExternalSources.CodeSource CodeSource',\n\n 'Products.SilvaNews.AgendaItem AgendaItemOccurrence':\n 'silva.app.news.AgendaItem.content AgendaItemOccurrence',\n\n 'Products.SilvaNews.AgendaViewer AgendaViewer':\n 'silva.app.news.viewers.AgendaViewer AgendaViewer',\n 'Products.SilvaNews.NewsViewer NewsViewer':\n 'silva.app.news.viewers.NewsViewer NewsViewer',\n 'Products.SilvaNews.RSSAggregator RSSAggregator':\n 'silva.app.news.viewers.RSSAggregator RSSAggregator',\n\n 'Products.SilvaNews.viewers.RSSAggregator RSSAggregator':\n 'silva.app.news.viewers.RSSAggregator RSSAggregator',\n 'Products.SilvaNews.viewers.NewsViewer NewsViewer':\n 'silva.app.news.viewers.NewsViewer NewsViewer',\n 'Products.SilvaNews.viewers.AgendaViewer AgendaViewer':\n 'silva.app.news.viewers.AgendaViewer AgendaViewer',\n\n 'Products.SilvaNews.NewsPublication NewsPublication':\n 'silva.app.news.NewsPublication NewsPublication',\n\n 'Products.SilvaNews.ServiceNews ServiceNews':\n 'silva.app.news.ServiceNews ServiceNews',\n 'Products.SilvaNews.interfaces IServiceNews':\n 'silva.app.news.interfaces IServiceNews',\n 'Products.SilvaNews.Tree Root':\n 'silva.app.news.Tree Root',\n 'Products.SilvaNews.Tree Node':\n 'silva.app.news.Tree Node',\n\n 'Products.SilvaNews.AgendaFilter AgendaFilter':\n 'silva.app.news.filters.AgendaFilter AgendaFilter',\n 'Products.SilvaNews.CategoryFilter CategoryFilter':\n 'silva.app.news.filters.CategoryFilter CategoryFilter',\n 'Products.SilvaNews.NewsFilter NewsFilter':\n 'silva.app.news.filters.NewsFilter NewsFilter',\n 'Products.SilvaNews.filters.AgendaFilter AgendaFilter':\n 'silva.app.news.filters.AgendaFilter AgendaFilter',\n 'Products.SilvaNews.filters.NewsFilter NewsFilter':\n 'silva.app.news.filters.NewsFilter NewsFilter',\n 'Products.SilvaNews.filters.CategoryFilter CategoryFilter':\n 'silva.app.news.filters.CategoryFilter CategoryFilter',\n }\n\n" }, { "alpha_fraction": 0.7428571581840515, "alphanum_fraction": 0.7626373767852783, "avg_line_length": 31.5, "blob_id": "305afcaff0e37863f1960cf7c6afed9da375e78a", "content_id": "0827e5e470986239ff4e3ff26b7f93ddd76a5547", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "permissive", "max_line_length": 72, "num_lines": 14, "path": "/Products/SilvaNews/installer.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom silva.core.conf.installer import DefaultInstaller\nfrom Products.SilvaNews.interfaces import ISilvaNewsExtension\n\n\nclass SilvaNewsInstaller(DefaultInstaller):\n \"\"\"Installer for the Silva News Service\n \"\"\"\n not_globally_addables = ['Obsolete Article', 'Obsolete Agenda Item']\n\ninstall = SilvaNewsInstaller(\"SilvaNews\", ISilvaNewsExtension)\n" }, { "alpha_fraction": 0.6194895505905151, "alphanum_fraction": 0.6244614124298096, "avg_line_length": 32.131866455078125, "blob_id": "0dc2d3b175c720ba5becbcdfdcb4b7a05648522f", "content_id": "c8442ff854681a7f6c3409be0f4b35aa1d800831", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3017, "license_type": "permissive", "max_line_length": 79, "num_lines": 91, "path": "/Products/SilvaNews/silvaxml/xmlexport.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2002-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom five import grok\nfrom zope.interface import Interface\n\nfrom Products.SilvaNews import interfaces\nfrom silva.app.news.datetimeutils import utc_datetime\nfrom Products.SilvaDocument.silvaxml.xmlexport import DocumentVersionProducer\nfrom Products.SilvaNews.silvaxml import NS_SILVA_NEWS\nfrom silva.core.xml import producers\n\n\ndef iso_datetime(dt):\n if dt:\n string = utc_datetime(dt).replace(microsecond=0).isoformat()\n if string.endswith('+00:00'):\n string = string[:-6] + 'Z'\n return string\n return ''\n\n\nclass PlainArticleProducer(producers.SilvaVersionedContentProducer):\n \"\"\"Export a PlainArticle object to XML.\n \"\"\"\n grok.adapts(interfaces.INewsItem, Interface)\n\n def sax(self):\n \"\"\"sax\"\"\"\n self.startElementNS(NS_SILVA_NEWS,\n 'plainarticle',\n {'id': self.context.id})\n self.sax_workflow()\n self.sax_versions()\n self.endElementNS(NS_SILVA_NEWS,'plainarticle')\n\n\nclass PlainArticleVersionProducer(DocumentVersionProducer):\n \"\"\"Export a version of a PlainArticle object to XML.\n \"\"\"\n grok.adapts(interfaces.INewsItemVersion, Interface)\n\n def sax(self):\n \"\"\"sax\"\"\"\n self.startElement(\n 'content',\n {'version_id': self.context.id,\n 'subjects': ','.join(self.context.get_subjects()),\n 'target_audiences': ','.join(self.context.get_target_audiences()),\n 'display_datetime': iso_datetime(\n self.context.get_display_datetime())})\n self.sax_metadata()\n node = self.context.content.documentElement.getDOMObj()\n self.sax_node(node)\n self.endElement('content')\n\n\nclass PlainAgendaItemProducer(producers.SilvaVersionedContentProducer):\n \"\"\"Export an AgendaItem object to XML.\n \"\"\"\n grok.adapts(interfaces.IAgendaItem, Interface)\n\n def sax(self):\n \"\"\"sax\"\"\"\n self.startElementNS(NS_SILVA_NEWS,\n 'plainagendaitem',\n {'id': self.context.id})\n self.sax_workflow()\n self.sax_versions()\n self.endElementNS(NS_SILVA_NEWS,'plainagendaitem')\n\n\nclass PlainAgendaItemVersionProducer(DocumentVersionProducer):\n \"\"\"Export a version of an AgendaItem object to XML.\n \"\"\"\n grok.adapts(interfaces.IAgendaItemVersion, Interface)\n\n def sax(self):\n \"\"\"sax\"\"\"\n self.startElement(\n 'content',\n {'version_id': self.context.id,\n 'subjects': ','.join(self.context.get_subjects()),\n 'target_audiences': ','.join(self.context.get_target_audiences()),\n 'display_datetime': iso_datetime(\n self.context.get_display_datetime())})\n self.sax_metadata()\n node = self.context.content.documentElement.getDOMObj()\n self.sax_node(node)\n self.endElement('content')\n\n\n" }, { "alpha_fraction": 0.6152934432029724, "alphanum_fraction": 0.621221125125885, "avg_line_length": 32.70000076293945, "blob_id": "4faa880e5bba96491d489cfeb6d4c4a19d044ade", "content_id": "8a3d4d9181e30b5a93a62587639ca76a1fcf9a06", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1687, "license_type": "permissive", "max_line_length": 79, "num_lines": 50, "path": "/Products/SilvaNews/silvaxml/helpers.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\nfrom dateutil.parser import parse as datetimeparse\nfrom silva.app.news.datetimeutils import local_timezone\n\ndef set_attribute(content, name, attrs, extract=None, ns=None):\n ns_name = (ns, name)\n if attrs.has_key(ns_name):\n if extract is not None:\n value = extract(attrs[ns_name])\n else:\n value = attrs[ns_name]\n setter = getattr(content, \"set_%s\" % name)\n setter(value)\n return value\n\ndef set_attribute_as_list(content, name, attrs, ns=None, sep=\",\"):\n return set_attribute(\n content, name, attrs, ns=ns, extract=lambda x: x.split(sep))\n\ndef set_attribute_as_bool(content, name, attrs, ns=None):\n return set_attribute(\n content, name, attrs, ns=ns, extract=lambda x: x == 'True' or x == '1')\n\ndef set_attribute_as_int(content, name, attrs, ns=None):\n return set_attribute(\n content, name, attrs, ns=ns, extract=lambda x: int(x))\n\ndef set_attribute_as_datetime(content, name, attrs, ns=None, tz=None):\n def extract(value):\n if value == '':\n return None\n dt = datetimeparse(value)\n if tz:\n dt = dt.astimezone(tz)\n return dt\n\n return set_attribute(\n content, name, attrs, ns=ns, extract=extract)\n\ndef set_attribute_as_naive_datetime(content, name, attrs, ns=None):\n def extract(value):\n if value == '':\n return None\n dt = datetimeparse(value).astimezone(\n local_timezone).replace(tzinfo=None)\n return dt\n return set_attribute(\n content, name, attrs, ns=ns, extract=extract)\n\n\n" }, { "alpha_fraction": 0.6487252116203308, "alphanum_fraction": 0.6543909311294556, "avg_line_length": 24.214284896850586, "blob_id": "7f74ac9ed59406c0dae0ec5e59e24d4caf4ddd55", "content_id": "dd99b8a8e0d6816d3dd3fd8828efa7ff61524f4e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 353, "license_type": "permissive", "max_line_length": 69, "num_lines": 14, "path": "/Products/SilvaNews/README.txt", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "==================\nSilva News Network\n==================\n\nThis extension is the equivalent of silva.app.news for `Silva`_ 2 and\nbefore. It is available on Silva 3 only for migration purposes.\n\nCode repository\n===============\n\nYou can find the code of this extension in Git:\nhttps://github.com/silvacms/Products.SilvaNews\n\n.. _Silva: http://silvacms.org\n" }, { "alpha_fraction": 0.539301335811615, "alphanum_fraction": 0.5480349063873291, "avg_line_length": 32.5121955871582, "blob_id": "d983f7b6f970f5ab2e21c3333813cac538882bf3", "content_id": "305d0b034d3c8dcb5922a3708bf71244c23cceca", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "permissive", "max_line_length": 79, "num_lines": 41, "path": "/Products/SilvaNews/upgrader/upgrade_236.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nimport logging\n\nfrom silva.core.upgrade.upgrade import BaseUpgrader, content_path\nfrom silva.app.news.AgendaItem.content import AgendaItemOccurrence\nfrom DateTime import DateTime\n\nlogger = logging.getLogger('silva.core.upgrade')\n\nVERSION_SIX='2.3.6'\n\n\nclass AgendaItemVersionUpgrader(BaseUpgrader):\n tags = {'pre',}\n\n def upgrade(self, item):\n logger.debug(u'Update agenda item %s occurrences.', content_path(item))\n if not item.get_occurrences():\n values = {}\n for name in ['start_datetime',\n 'end_datetime',\n 'location',\n 'recurrence',\n 'all_day',\n 'timezone_name']:\n attr = '_' + name\n if attr in item.__dict__:\n value = item.__dict__[attr]\n if isinstance(value, DateTime):\n value = value.asdatetime()\n if value is not None:\n values[name] = value\n del item.__dict__[attr]\n item.set_occurrences([AgendaItemOccurrence(**values)])\n return item\n\nagenda_upgrader = AgendaItemVersionUpgrader(\n VERSION_SIX, 'Obsolete Agenda Item Version')\n" }, { "alpha_fraction": 0.7030485272407532, "alphanum_fraction": 0.7071885466575623, "avg_line_length": 29.872093200683594, "blob_id": "ba8f3bf2c5c158aef94d231bab22b6e22da01e14", "content_id": "2c4ee283cc6d48ce71717688575abe5e87aeddce", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2657, "license_type": "permissive", "max_line_length": 75, "num_lines": 86, "path": "/Products/SilvaNews/AgendaItem.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2002-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\n# ztk\nfrom five import grok\nfrom zope.interface import implements\n\n# Zope\nfrom AccessControl import ClassSecurityInfo\nfrom App.class_init import InitializeClass\n\n# Silva\nfrom silva.core import conf as silvaconf\nfrom Products.Silva import SilvaPermissions\n\n# SilvaNews\nfrom Products.SilvaNews.interfaces import IAgendaItem, IAgendaItemVersion\nfrom Products.SilvaNews.NewsItem import NewsItem, NewsItemVersion\nfrom silva.app.news.datetimeutils import datetime_to_unixtimestamp\n# This is used by migration code.\nfrom silva.app.news.AgendaItem.content import AgendaItemOccurrence\n\n_marker = object()\n\n\nclass AgendaItemVersion(NewsItemVersion):\n \"\"\"Silva News AgendaItemVersion\n \"\"\"\n grok.implements(IAgendaItemVersion)\n\n security = ClassSecurityInfo()\n meta_type = \"Obsolete Agenda Item Version\"\n\n _occurrences = []\n\n security.declareProtected(\n SilvaPermissions.ChangeSilvaContent, 'set_occurrences')\n def set_occurrences(self, occurrences):\n self._occurrences = occurrences\n\n security.declareProtected(\n SilvaPermissions.AccessContentsInformation, 'get_occurrences')\n def get_occurrences(self):\n # Secuity check in ZODB\n return map(lambda o: o.__of__(self), self._occurrences)\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'fulltext')\n def fulltext(self):\n \"\"\"Deliver the contents as plain text, for full-text search\n \"\"\"\n parenttext = AgendaItemVersion.inheritedAttribute('fulltext')(self)\n return \"%s %s\" % (parenttext, self._location)\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'sort_index')\n def sort_index(self):\n dt = self.get_start_datetime()\n if dt:\n return datetime_to_unixtimestamp(dt)\n return None\n\n security.declareProtected(SilvaPermissions.AccessContentsInformation,\n 'get_timestamp_ranges')\n def get_timestamp_ranges(self):\n return self.get_calendar_datetime().\\\n get_unixtimestamp_ranges()\n\n\nInitializeClass(AgendaItemVersion)\n\n\nclass AgendaItem(NewsItem):\n \"\"\"A News item for events. Includes date and location\n metadata, as well settings for subjects and audiences.\n \"\"\"\n security = ClassSecurityInfo()\n implements(IAgendaItem)\n meta_type = \"Obsolete Agenda Item\"\n silvaconf.icon(\"www/agenda_item.png\")\n silvaconf.priority(3.8)\n silvaconf.versionClass(AgendaItemVersion)\n\n\nInitializeClass(AgendaItem)\n\n\n" }, { "alpha_fraction": 0.6381787657737732, "alphanum_fraction": 0.6424705982208252, "avg_line_length": 33.798702239990234, "blob_id": "fc724a4de4e5632021aa9f0539b2bf535b142eb2", "content_id": "90505764686a2490671b0442d399afa668408bfc", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5359, "license_type": "permissive", "max_line_length": 76, "num_lines": 154, "path": "/Products/SilvaNews/upgrader/upgrade_300.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom silva.app.news.AgendaItem.content import AgendaItemOccurrence\nfrom silva.core.interfaces import IPostUpgrader\nfrom silva.core.upgrade.upgrader.upgrade_300 import VERSION_A1\nfrom silva.core.upgrade.upgrade import BaseUpgrader\nfrom zope.interface import implements\n\nfrom Acquisition import aq_base\nfrom DateTime import DateTime\nfrom Products.SilvaDocument.upgrader.upgrade_300 import DocumentUpgrader\n\n\nclass CatalogUpgrader(BaseUpgrader):\n\n def validate(self, root):\n return bool(root.service_catalog)\n\n def upgrade(self, root):\n catalog = root.service_catalog\n\n columns = ['get_end_datetime','get_start_datetime',\n 'get_location','get_title', 'get_intro']\n\n indexes = ['idx_end_datetime', 'idx_display_datetime',\n 'idx_parent_path', 'idx_start_datetime', 'idx_target_audiences',\n 'idx_timestamp_ranges', 'idx_subjects', 'idx_is_private']\n\n existing_columns = catalog.schema()\n existing_indexes = catalog.indexes()\n\n for column_name in columns:\n if column_name in existing_columns:\n catalog.delColumn(column_name)\n\n for field_name in indexes:\n if field_name in existing_indexes:\n catalog.delIndex(field_name)\n\n return root\n\n\nclass RootUpgrader(BaseUpgrader):\n\n def upgrade(self, root):\n extensions = root.service_extensions\n # If Silva News is installed, we need to refresh it, and\n # install silva.app.news for the migration.\n if (hasattr(aq_base(root), 'service_news') or\n extensions.is_installed('SilvaNews')):\n extensions.refresh('SilvaNews')\n if not extensions.is_installed('silva.app.news'):\n extensions.install('silva.app.news')\n return root\n\n\nclass NewsItemUpgrader(DocumentUpgrader):\n\n def create_document(self, parent, identifier, title):\n factory = parent.manage_addProduct['silva.app.news']\n return factory.manage_addNewsItem(identifier, title)\n\n def copy_version(self, source, target, ensure=False):\n super(NewsItemUpgrader, self).copy_version(source, target, ensure)\n target._subjects = set(source._subjects)\n target._target_audiences = set(source._target_audiences)\n target._display_datetime = source._display_datetime\n target._external_url = source._external_url\n\n\nclass AgendaItemUpgrader(DocumentUpgrader):\n\n def create_document(self, parent, identifier, title):\n factory = parent.manage_addProduct['silva.app.news']\n return factory.manage_addAgendaItem(identifier, title)\n\n def copy_version(self, source, target, ensure=False):\n super(AgendaItemUpgrader, self).copy_version(source, target, ensure)\n target._subjects = source._subjects\n target._target_audiences = source._target_audiences\n target._display_datetime = source._display_datetime\n target._external_url = source._external_url\n\n occurrences = list(source._occurrences)\n if occurrences:\n target._occurrences = occurrences\n else:\n values = {}\n for name in ['start_datetime',\n 'end_datetime',\n 'location',\n 'recurrence',\n 'all_day',\n 'timezone_name']:\n attr = '_' + name\n if attr in source.__dict__:\n value = source.__dict__[attr]\n if isinstance(value, DateTime):\n value = value.asdatetime()\n if value is not None:\n values[name] = value\n if values:\n target._occurrences = [AgendaItemOccurrence(**values)]\n\nclass AgendaViewerUpgrader(BaseUpgrader):\n tags = {'pre',}\n\n def validate(self, context):\n return hasattr(context, '_days_to_show')\n\n def upgrade(self, context):\n context._number_to_show = context._days_to_show\n context._number_is_days = True\n delattr(context, '_days_to_show')\n return context\n\nclass FilterUpgrader(BaseUpgrader):\n\n def available(self, content):\n return isinstance(content._excluded_items, list)\n\n def upgrade(self, content):\n content._excluded_items = set(content._excluded_items)\n return content\n\n\nupgrade_catalog = CatalogUpgrader(\n VERSION_A1, \"Silva Root\")\nupgrade_root = RootUpgrader(\n VERSION_A1, \"Silva Root\")\nupgrade_newsitem = NewsItemUpgrader(\n VERSION_A1, \"Obsolete Article\")\nupgrade_agendaitem = AgendaItemUpgrader(\n VERSION_A1, \"Obsolete Agenda Item\")\nupgrade_filter = FilterUpgrader(\n VERSION_A1, (\"Silva Agenda Filter\", \"Silva News Filter\"))\nupgrade_agendaviewer = AgendaViewerUpgrader(\n VERSION_A1, \"Silva Agenda Viewer\")\n\n\nclass RootPostUpgrader(BaseUpgrader):\n implements(IPostUpgrader)\n\n def upgrade(self, root):\n # We need to install the new SilvaDocument, and Silva Obsolete\n # Document for the document migration.\n extensions = root.service_extensions\n if extensions.is_installed('SilvaNews'):\n extensions.uninstall('SilvaNews')\n return root\n\nroot_post_upgrader = RootPostUpgrader(VERSION_A1, 'Silva Root')\n" }, { "alpha_fraction": 0.6141618490219116, "alphanum_fraction": 0.623795747756958, "avg_line_length": 31.421875, "blob_id": "e211415c7da2b6ad2801d8240e61236a37324a8a", "content_id": "ab8bba5ec94e5fe0e6e96d5c85fc4c4bb79d23ad", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2076, "license_type": "permissive", "max_line_length": 82, "num_lines": 64, "path": "/Products/SilvaNews/upgrader/upgrade_220.py", "repo_name": "silvacms/Products.SilvaNews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom zope.cachedescriptors.property import Lazy\n\nfrom silva.core.upgrade.upgrade import BaseUpgrader\nfrom silva.app.news.interfaces import IServiceNews\nfrom zope.component import getUtility\n\nfrom Products.SilvaMetadata.interfaces import IMetadataService\n\nVERSION_B2='2.2b2'\n\n\nclass NewsPublicationUpgrader(BaseUpgrader):\n \"\"\" upgrade obj._is_private to snn-np-settings: is_private\n metadata set\"\"\"\n\n @Lazy\n def metadata(self):\n return getUtility(IMetadataService)\n\n @Lazy\n def news(self):\n return getUtility(IServiceNews)\n\n def validate(self, container):\n return (container.__dict__.has_key('_is_private') or\n container._getOb('index', None) is None)\n\n def upgrade(self, container):\n if container.__dict__.has_key('_is_private'):\n if container._is_private:\n value = 'yes'\n else:\n value = 'no'\n binding = self.metadata.getMetadata(container)\n binding.setValues('snn-np-settings', {'is_private': value}, reindex=1)\n del container._is_private\n if container._getOb('index', None) is None:\n factory = container.manage_addProduct['silva.app.news']\n factory.manage_addNewsViewer(\n 'index', container.get_title_or_id())\n factory.manage_addNewsFilter(\n 'filter', 'Filter for %s' % container.get_title_or_id())\n\n viewer = container._getOb('index')\n filter = container._getOb('filter')\n\n # Configure the new filter and viewer.\n\n filter.set_subjects(\n self.news.get_subjects_tree().get_ids(1))\n filter.set_target_audiences(\n self.news.get_target_audiences_tree().get_ids(1))\n filter.add_source(container)\n viewer.add_filter(filter)\n\n return container\n\n\npublication_upgrader = NewsPublicationUpgrader(\n VERSION_B2, 'Silva News Publication', 100)\n\n" } ]
18
BorisMs55/Python-course-final-project
https://github.com/BorisMs55/Python-course-final-project
a642c420c8e5a59fe12c44e8bb60cc1c26c86d79
b3d0eb12e7043051b61a02b8e817b9e5852e2817
a340b00e9b4ba2742676e54ae1a08402946a8b32
refs/heads/master
2023-02-05T20:11:30.593215
2020-12-31T10:24:12
2020-12-31T10:24:12
320,345,382
0
0
null
2020-12-10T17:39:09
2020-12-30T18:31:22
2020-12-31T10:24:13
Python
[ { "alpha_fraction": 0.6717299818992615, "alphanum_fraction": 0.6717299818992615, "avg_line_length": 31.027027130126953, "blob_id": "4c8ec46f84ab8a02a48a81d0d1673ed9348ae28a", "content_id": "b3ff7a55fb147b1e8615b626077047824b366c68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1185, "license_type": "no_license", "max_line_length": 112, "num_lines": 37, "path": "/hr/api/serializers.py", "repo_name": "BorisMs55/Python-course-final-project", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom hr.employee import models\n\n\nclass EmployeeListSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Employee\n fields = ('first_name', 'last_name', 'job')\n\nclass EmployeeSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Employee\n fields = ('first_name', 'last_name', 'job')\n\nclass EmployeeDetailSerializer(serializers.ModelSerializer):\n\n manager = serializers.StringRelatedField(read_only=True)\n job = serializers.SlugRelatedField(slug_field=\"name\", read_only=True)\n department = serializers.SlugRelatedField(slug_field=\"name\", read_only=True)\n\n class Meta:\n model = models.Employee\n exclude = (\"commission_pct\",)\n # fields = ('first_name', 'last_name', 'email', 'phone_number', 'hire_date', 'salary', 'commission_pct',\n # 'manager', 'photo', 'job', 'department')\n\n\nclass JobSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Job\n fields = \"__all__\"\n\n\nclass DepartmentSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Department\n fields = ('name',)\n" }, { "alpha_fraction": 0.8571428656578064, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 27, "blob_id": "e6cadde0eb514cd148023ad1240626a38c4e79a5", "content_id": "739d1ed8d645c4b342e483b75b36e6eb29494275", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/readme.md", "repo_name": "BorisMs55/Python-course-final-project", "src_encoding": "UTF-8", "text": "Python course final project\n" }, { "alpha_fraction": 0.7504873275756836, "alphanum_fraction": 0.7504873275756836, "avg_line_length": 26, "blob_id": "86790db82403f44433600c173d329b878846dc2c", "content_id": "7cd7620742b460e01e45a3cc9e21e5b65a51fda7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 513, "license_type": "no_license", "max_line_length": 57, "num_lines": 19, "path": "/hr/employee/views.py", "repo_name": "BorisMs55/Python-course-final-project", "src_encoding": "UTF-8", "text": "from rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import viewsets\nfrom .models import Employee\n\n\n# Create your views here.\n\n\nclass EmployeeListView(APIView):\n \"\"\"Employee List\"\"\"\n\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'employee/employee_list.html'\n\n def get(self, request):\n queryset = Employee.objects.all()\n return Response({'employees': queryset})\n" }, { "alpha_fraction": 0.6945404410362244, "alphanum_fraction": 0.704906702041626, "avg_line_length": 33.4523811340332, "blob_id": "4c89300e30c676d3ae9bc52b1512b18c61d787a9", "content_id": "5fcfb6d5e9def4b12f273806bccb7e0fdba1e37e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1447, "license_type": "no_license", "max_line_length": 98, "num_lines": 42, "path": "/hr/employee/models.py", "repo_name": "BorisMs55/Python-course-final-project", "src_encoding": "UTF-8", "text": "from djmoney.models.fields import MoneyField\nfrom django.db import models\nfrom django.template.defaultfilters import slugify\nfrom django_extensions.db.fields import AutoSlugField\nfrom datetime import datetime\n\n\n# Create your models here.\n\nclass Employee(models.Model):\n first_name = models.CharField(max_length=75)\n last_name = models.CharField(max_length=75)\n email = models.EmailField()\n phone_number = models.CharField(max_length=16)\n hire_date = models.DateField()\n salary = MoneyField(max_digits=14, decimal_places=2, default_currency='ILS')\n commission_pct = models.DecimalField(max_digits=4, decimal_places=2)\n manager = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL)\n photo = models.ImageField(default='default.png', blank=True)\n job = models.ForeignKey('Job', null=True, on_delete=models.SET_NULL)\n department = models.ForeignKey('Department', null=True, blank=True, on_delete=models.SET_NULL)\n slug = AutoSlugField(populate_from=['first_name', 'last_name'])\n\n def slugify_function(self, content):\n return content.replace('_', '-').lower()\n\n def __str__(self):\n return self.first_name + \" \" + self.last_name\n\n\nclass Job(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n\nclass Department(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n" }, { "alpha_fraction": 0.6758241653442383, "alphanum_fraction": 0.6758241653442383, "avg_line_length": 25, "blob_id": "4c2b94c2aa6f347df0e653d08a965334f1b936ba", "content_id": "a47bebc621de016d2bb04f4e0b4302f4743e4b35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 60, "num_lines": 7, "path": "/hr/employee/urls.py", "repo_name": "BorisMs55/Python-course-final-project", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('list/', views.EmployeeListView.as_view()),\n # path('<int:pk>/', views.EmployeeDetailView.as_view()),\n]\n" }, { "alpha_fraction": 0.7422969341278076, "alphanum_fraction": 0.7422969341278076, "avg_line_length": 26.461538314819336, "blob_id": "374e2a5194059221eebc4ea156ed6431ef366487", "content_id": "2c3aaba0ab429d395447319b75c224409ec79316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "no_license", "max_line_length": 65, "num_lines": 13, "path": "/hr/employee/admin.py", "repo_name": "BorisMs55/Python-course-final-project", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Employee, Department, Job\n\n\n# class EmployeeAdmin(admin.ModelAdmin):\n# prepopulated_fields = {\"slug\": (\"first_name\", \"last_name\")}\n# readonly_fields = ('slug',)\n\n\n#admin.site.register(Employee, EmployeeAdmin)\nadmin.site.register(Employee)\nadmin.site.register(Department)\nadmin.site.register(Job)\n" }, { "alpha_fraction": 0.5285714268684387, "alphanum_fraction": 0.7107142806053162, "avg_line_length": 17.66666603088379, "blob_id": "72351a18b062c22f5b8c8bd2fa4e6ce23e8d484d", "content_id": "5fd140ba48de7c8523e81e997a1f57a08b959a3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 280, "license_type": "no_license", "max_line_length": 30, "num_lines": 15, "path": "/hr/requirements.txt", "repo_name": "BorisMs55/Python-course-final-project", "src_encoding": "UTF-8", "text": "asgiref==3.3.1\nDjango==3.1.4\ndjango-extensions==3.1.0\ndjango-js-asset==1.2.2\ndjango-money==1.2.1\ndjangorestframework==3.12.2\nmysql-connector-python==8.0.22\nmysqlclient==2.0.2\nPillow==8.0.1\nprotobuf==3.14.0\npy-moneyed==0.8.0\npytz==2020.4\nsix==1.15.0\nslugify==0.0.1\nsqlparse==0.4.1\n" }, { "alpha_fraction": 0.7562723755836487, "alphanum_fraction": 0.7562723755836487, "avg_line_length": 27, "blob_id": "c9428be8272f02ad729d9f7c1adea4ebf2e501bd", "content_id": "825f4a7d1fd6881a6338f0ec4c3488153a6bfe67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 59, "num_lines": 10, "path": "/hr/api/urls.py", "repo_name": "BorisMs55/Python-course-final-project", "src_encoding": "UTF-8", "text": "from django.urls import path, include\nfrom .views import EmployeeViewset\n# from rest_framework import routers\n# router = routers.DefaultRouter()\n#\n# router.register('Employees', views.EmployeeViewset)\n\nurlpatterns = [\n path('', EmployeeViewset.as_view, name=\"display_json\"),\n]" } ]
8
taehoshino/AWS_Comprehend_Translate_Tweepy
https://github.com/taehoshino/AWS_Comprehend_Translate_Tweepy
77d6edd1cfd44e3c6e1c0f50f60e752f6a43a167
27c6e49b82267ed7b0fa01f55a369b338a197581
cdd57429947ab01ce474822406e292150b801e88
refs/heads/master
2020-08-11T13:20:13.133284
2019-10-12T05:40:12
2019-10-12T05:40:12
214,571,274
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6610282063484192, "alphanum_fraction": 0.6669983267784119, "avg_line_length": 34.89285659790039, "blob_id": "ff704d3837fc1af3845579f662fdc8889e173158", "content_id": "f0c3a156557baf8e72aef78d08ad927cc8db23a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3015, "license_type": "no_license", "max_line_length": 155, "num_lines": 84, "path": "/AWS_Tweepy_sample1.py", "repo_name": "taehoshino/AWS_Comprehend_Translate_Tweepy", "src_encoding": "UTF-8", "text": "import tweepy as tw\nimport pandas as pd\nimport boto3\nimport os\nimport matplotlib.pyplot as plt\n\n# OAuth2 authentification for twitter\n# Define CONS_KEY, CONS_SECRET, ACCESS_KEY and ACCESS SECRET as environmental variables and get their values using os.getenv()\nauth = tw.OAuthHandler(os.getenv('CONS_KEY'), os.getenv('CONS_SECRET'))\nauth.set_access_token(os.getenv('ACCESS_KEY'), os.getenv('ACCESS_SECRET'))\napi = tw.API(auth, wait_on_rate_limit = True)\n\n# Define query conditions.\n# Refer to https://developer.twitter.com/en/docs/tweets/rules-and-filtering/overview/standard-operators\nsearch_word = '\"QUERY_PHRASE/WORD\" -filter:retweets -filter:replies filter:safe'\nsince_date = '2019-10-01'\nsearch_type = 'recent' #select from 'recent', 'popular', or 'mixed'\nnum_tweets = 5\n\n# Search and get tweets \ntweets = tw.Cursor(api.search, \n q=search_word, \n since=since_date,\n result_type=search_type\n #lang='ja' # turn on to search by language\n ).items(num_tweets)\n\ntext_list = []\nsentiment_list = []\nlang_list = []\nlocation_list = []\n\n# for each tweet\nfor tweet in tweets:\n text = tweet.text\n lang = tweet.lang\n \n # break tweet to text + https link and extract only text \n if len(tweet.entities['urls'])!=0:\n text = text.split(' https://')[0].strip() # remove whitespace at front and back\n \n if text in text_list: # Skip the following if text matches any one in the list\n continue \n \n text_list.append(text)\n lang_list.append(tweet.lang) # original language before translation\n location_list.append(tweet.user.location) # user location\n\n # setup AWS boto3 clients\n # Define ACCESS_KEY and ACCESS_SECRET as environmental variables/or you may define them as arguments of the following methods\n comprehend = boto3.client('comprehend')\n translate = boto3.client('translate')\n \n # if tweet not in the language list of .detect_sentiment method, translate text to English \n lang_choice = ['en','es','fr','de','it','pt']\n if lang not in lang_choice:\n try:\n text = translate.translate_text(Text=text, SourceLanguageCode='auto', TargetLanguageCode='en')['TranslatedText']\n lang = 'en'\n except: #ignore DetectedLanguageLowConfidenceException error\n text_list.pop()\n lang_list.pop()\n location_list.pop()\n continue\n \n # detect sentiment of tweet\n sentiment = comprehend.detect_sentiment(Text=text, LanguageCode=lang)['Sentiment']\n \n # add in lists\n sentiment_list.append(sentiment)\n\n# define dataframe\ndf = pd.DataFrame({'lang':lang_list, 'sentiment':sentiment_list, 'location':location_list, 'tweet':text_list}).set_index(['sentiment','lang']).sort_index()\nprint(df.head())\n\n# get counts per language for each sentiment\nsummary = df.groupby(level=[0,1]).size()\n\n# bar plot\nsummary.unstack().plot(kind='bar')\nplt.show()\nprint(summary)\n \nprint('Complete!')\n" }, { "alpha_fraction": 0.7696078419685364, "alphanum_fraction": 0.7745097875595093, "avg_line_length": 101, "blob_id": "816bb49abc2e973b5d8aa937313259a5de428d24", "content_id": "315863fb3a8cb7eefb8dfc2810b4dfc8e9010d55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 408, "license_type": "no_license", "max_line_length": 165, "num_lines": 4, "path": "/README.md", "repo_name": "taehoshino/AWS_Comprehend_Translate_Tweepy", "src_encoding": "UTF-8", "text": "## AWS_Tweepy_sample1\n- using AWS boto3 (Comprehend, Translate) and Twitter Tweepy\n- Search tweets by a query phrase, get sentiment of each tweet (translate to English if necessary), and show a a summary of counts per sentiment for each language. \n- Similar to 'Yahoo real-time search' (https://search.yahoo.co.jp/realtime) apart from that 'Yahoo real-time search' only detects tweets in Japanese language.\n" } ]
2
shahaashay21/Machine-Learning
https://github.com/shahaashay21/Machine-Learning
e367c615a0b940efb12d93a3e17c5b2bbc3d57bb
6f55c0a10b72fc0400ce81803970d50fbdeb2614
2ef223ab289fe7622a35a1ef7a422929c259a9e0
refs/heads/master
2020-12-06T14:10:43.552926
2020-01-12T18:18:18
2020-01-12T18:18:18
232,483,003
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6240555644035339, "alphanum_fraction": 0.6426383256912231, "avg_line_length": 35.014705657958984, "blob_id": "6513745634a5b730124c2530c5cc89639dc5c5ab", "content_id": "45151996b9dbab047145729fb9d043102cf8042a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4897, "license_type": "no_license", "max_line_length": 126, "num_lines": 136, "path": "/Part 2 - Regression/Section 5 - Multiple Linear Regression/Multiple_Linear_Regression/multiple_linear_regression.py", "repo_name": "shahaashay21/Machine-Learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 8 21:21:15 2020\n\n@author: aashays\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# importing the dataset\ndataset = pd.read_csv('50_Startups.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 4].values\n\n# Encoding categorical data\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\n# Encoding the Independent variable\nct = ColumnTransformer([('encoder', OneHotEncoder(), [3])], remainder = 'passthrough')\nX = np.array(ct.fit_transform(X), dtype = np.float)\n\n# Avoiding the Dummy Variable Trap\nX = X[:, 1:]\n\n# Split the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# Feature scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train).astype(float)\nX_test = sc_X.transform(X_test).astype(float)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train.reshape(-1, 1).astype(float))\"\"\"\n\n# Fitting Multiple Linear Regression to the Training set\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = regressor.predict(X_test);\n\n# Building the optimal model using Backward Elimination (Method 1)\nimport statsmodels.formula.api as sm\n# Equation is Yo = Bo + B1X1 + BnXn\n# We don't have Bo in our equation, in order get it we need to assume there is BoXo and Xo is always 1\n# For that, we need to prepend one column with value 1\nX = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1)\n# Let's start BE process\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\n# print(regressor_OLS.summary())\n\nX_opt = X[:, [0, 1, 3, 4, 5]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\n# print(regressor_OLS.summary())\n\nX_opt = X[:, [0, 3, 4, 5]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\n# print(regressor_OLS.summary())\n\nX_opt = X[:, [0, 3, 5]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\n# print(regressor_OLS.summary())\n\nX_opt = X[:, [0, 3]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\n# print(regressor_OLS.summary())\n\n# Same as Method 1 but in a function with a loop\nimport statsmodels.formula.api as sm\ndef backwardElimination(x, sl):\n numVars = len(x[0])\n for i in range(0, numVars):\n regressor_OLS = sm.OLS(y, x).fit()\n maxVar = max(regressor_OLS.pvalues).astype(float)\n if maxVar > sl:\n for j in range(0, numVars - i):\n if (regressor_OLS.pvalues[j].astype(float) == maxVar):\n x = np.delete(x, j, 1)\n regressor_OLS.summary()\n return x\n\n# Define significance level\nSL = 0.05\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\nX_Modeled = backwardElimination(X_opt, SL)\n\n\n# Predicting the Test set results after backward elimination process\nX_opt_train, X_opt_test, y_train, y_test = train_test_split(X_Modeled, y, test_size = 0.2, random_state = 0)\nregressor_with_be = LinearRegression()\nregressor_with_be.fit(X_opt_train, y_train)\ny_pred_with_be = regressor_with_be.predict(X_opt_test);\n\n\n# Backward Elimination with p-values and Adjusted R Squared (Method 2)\nimport statsmodels.formula.api as sm\ndef backwardElimination(x, SL):\n numVars = len(x[0])\n temp = np.zeros((50,6)).astype(int)\n for i in range(0, numVars):\n regressor_OLS = sm.OLS(y, x).fit()\n maxVar = max(regressor_OLS.pvalues).astype(float)\n adjR_before = regressor_OLS.rsquared_adj.astype(float)\n if maxVar > SL:\n for j in range(0, numVars - i):\n if (regressor_OLS.pvalues[j].astype(float) == maxVar):\n temp[:,j] = x[:, j]\n x = np.delete(x, j, 1)\n tmp_regressor = sm.OLS(y, x).fit()\n adjR_after = tmp_regressor.rsquared_adj.astype(float)\n if (adjR_before >= adjR_after):\n x_rollback = np.hstack((x, temp[:,[0,j]]))\n x_rollback = np.delete(x_rollback, j, 1)\n print (regressor_OLS.summary())\n return x_rollback\n else:\n continue\n regressor_OLS.summary()\n return x\n \nSL = 0.05\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\nX_Modeled_Adj_R = backwardElimination(X_opt, SL)\n\n# Predicting the Test set results after Backward Elimination with p-values and Adjusted R Squared\nX_opt_adj_r_train, X_opt_adj_r_test, y_train, y_test = train_test_split(X_Modeled_Adj_R, y, test_size = 0.2, random_state = 0)\nregressor_with_be_adj_r = LinearRegression()\nregressor_with_be_adj_r.fit(X_opt_adj_r_train, y_train)\ny_pred_with_be_adj_r = regressor_with_be_adj_r.predict(X_opt_adj_r_test);" }, { "alpha_fraction": 0.7142220139503479, "alphanum_fraction": 0.737851083278656, "avg_line_length": 32, "blob_id": "6bf510d7a1e8a2579372c1342c40e81b683b87b7", "content_id": "f8a07e9becd2412e3b23fb37bae80845ca210176", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2243, "license_type": "no_license", "max_line_length": 137, "num_lines": 68, "path": "/Part 2 - Regression/Section 6 - Polynomial Regression/Polynomial_Regression/polynomial_regression.py", "repo_name": "shahaashay21/Machine-Learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 11 19:03:00 2020\n\n@author: aashays\n\nNo Train and Test data because we are working with the assuption that new data has experience level between 6 and 7 and salary is 160,000\nNow here we are checking whether the above 6.5 level with 160,000 is right or not\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# importing the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2].values\n\n# Split the dataset into the Training set and Test set\n\"\"\"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\"\"\"\n\n# Feature scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train).astype(float)\nX_test = sc_X.transform(X_test).astype(float)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train.reshape(-1, 1).astype(float))\"\"\"\n\n# Fitting Linear Regression to the dataset\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\nlin_reg.fit(X, y)\n\n# Fitting Polynomial Regression to dataset\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg = PolynomialFeatures(degree = 4)\nX_poly = poly_reg.fit_transform(X)\nlin_reg2 = LinearRegression()\nlin_reg2.fit(X_poly, y)\n\n# Visulising the Linear Regression results\nplt.scatter(X, y, color = 'red')\nplt.plot(X, lin_reg.predict(X), color = \"blue\")\nplt.title('Truth or Bluff (Linear Regression)')\nplt.xlabel(\"Position Level\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n\n# Visulising the Polynomial Regression results\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape(len(X_grid), 1)\nplt.scatter(X, y, color = 'red')\nplt.plot(X_grid, lin_reg2.predict(poly_reg.fit_transform(X_grid)), color = \"blue\")\nplt.title('Truth or Bluff (Polynomial Regression)')\nplt.xlabel(\"Position Level\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n# Predicting a new result with Linear Regression\nlinear_model_predition = lin_reg.predict(np.array(6.5).reshape(-1, 1))\n\n# Predicting a new result with Polynomial Regression\npolynomial_model_predition = lin_reg2.predict(poly_reg.fit_transform(np.array(6.5).reshape(-1,1)))" }, { "alpha_fraction": 0.7043665051460266, "alphanum_fraction": 0.7244094610214233, "avg_line_length": 31.44186019897461, "blob_id": "c0b362834acb135a14eb452fc6f9e64c45c9565f", "content_id": "b9e5be922d62b45ab949b9f3fb98607cdf6fbf78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1397, "license_type": "no_license", "max_line_length": 92, "num_lines": 43, "path": "/Part 1 - Data Preprocessing/data_preprocessing.py", "repo_name": "shahaashay21/Machine-Learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 6 20:58:43 2020\n\n@author: aashays\n\"\"\"\n\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# importing the dataset\ndataset = pd.read_csv('Data.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 3].values\n\n# Taking care of missing data\nfrom sklearn.impute import SimpleImputer\nimputer = SimpleImputer(missing_values = np.nan, strategy = 'mean', verbose = 0)\nimputer = imputer.fit(X[:, 1:3])\nX[:, 1:3] = imputer.transform(X[:, 1:3])\n\n# Encoding categorical data\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\n# Encoding the Independent variable\nct = ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder = 'passthrough')\nX = np.array(ct.fit_transform(X), dtype = np.float)\n# Encoding the Dependent variable\ny = LabelEncoder().fit_transform(y)\n\n# Split the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# Feature scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train).astype(float)\nX_test = sc_X.transform(X_test).astype(float)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train.reshape(-1, 1).astype(float))\n\n\n" }, { "alpha_fraction": 0.7086864113807678, "alphanum_fraction": 0.7245762944221497, "avg_line_length": 29.95081901550293, "blob_id": "cdd520a5e6553f84c1bd40fcf7e647a13cffe661", "content_id": "8527242e4c93f52cae41ee5f9192ecb6433357c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1888, "license_type": "no_license", "max_line_length": 92, "num_lines": 61, "path": "/Part 2 - Regression/Section 4 - Simple Linear Regression/Simple_Linear_Regression/simple_linear_regression.py", "repo_name": "shahaashay21/Machine-Learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 7 21:17:42 2020\n\n@author: aashays\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# importing the dataset\ndataset = pd.read_csv('Salary_Data.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 1].values\n\n# Split the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)\n\n# Feature scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train).astype(float)\nX_test = sc_X.transform(X_test).astype(float)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train.reshape(-1, 1).astype(float))\"\"\"\n\n# Fitting Simple Linear Regression to the Training set\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# Predict the Test set results\ny_pred = regressor.predict(X_test)\ncustom_data = np.array([1.8, 4.2, 7.5, 10.1]).reshape(-1, 1)\ncustom_pred = regressor.predict(custom_data)\n\n# Visualize the Training set result\nplt.scatter(X_train, y_train, color = 'red')\nplt.plot(X_train, regressor.predict(X_train), color = 'blue')\nplt.title('Salary vs Experience (Training set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()\n\n# Visualize the Test set result\nplt.scatter(X_test, y_test, color = 'red')\nplt.plot(X_train, regressor.predict(X_train), color = 'blue')\nplt.title('Salary vs Experience (Test set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()\n\n# Visualize the Custom set result\nplt.scatter(custom_data, custom_pred, color = 'red')\nplt.plot(X_train, regressor.predict(X_train), color = 'blue')\nplt.title('Salary vs Experience (Custom set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()\n" }, { "alpha_fraction": 0.6999347805976868, "alphanum_fraction": 0.718199610710144, "avg_line_length": 26.89090919494629, "blob_id": "46f96bfdc9d65b983d16b80492ca54d56d9de51a", "content_id": "68501e00837548c16dad5ed29e8c4006d288de28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1533, "license_type": "no_license", "max_line_length": 92, "num_lines": 55, "path": "/Part 2 - Regression/Section 6 - Polynomial Regression/Polynomial_Regression/regression_template.py", "repo_name": "shahaashay21/Machine-Learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 11 19:57:56 2020\n\n@author: aashays\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# importing the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2].values\n\n# Split the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# Feature scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train).astype(float)\nX_test = sc_X.transform(X_test).astype(float)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train.reshape(-1, 1).astype(float))\"\"\"\n\n\n# Fitting the regression model to the dataset\n# CREATE YOUR REGRESSOR HERE\n\n\n\n# Predicting a new result with Polynomial Regression\ny_pred = regressor.predict(np.array(6.5).reshape(-1,1))\n\n# Visulising the Polynomial Regression results\nplt.scatter(X, y, color = 'red')\nplt.plot(X, regressor.predict(X), color = \"blue\")\nplt.title('Truth or Bluff (Regression Model)')\nplt.xlabel(\"Position Level\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n# Visulising the Polynomial Regression results\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape(len(X), 1)\nplt.scatter(X, y, color = 'red')\nplt.plot(X_grid, regressor.predict(X_grid), color = \"blue\")\nplt.title('Truth or Bluff (Regression Model)')\nplt.xlabel(\"Position Level\")\nplt.ylabel(\"Salary\")\nplt.show()" } ]
5
AaronVickers/Sudoku-Solver
https://github.com/AaronVickers/Sudoku-Solver
d6c1359f7153f81a2c965a58bac10ae9374489f8
06975f281fd37154bf4049b1d88a1569be15a511
3fe32499dbe22941343995c056ecce7352c5be95
refs/heads/master
2022-12-13T18:13:55.850322
2020-09-06T11:56:47
2020-09-06T11:56:47
293,266,747
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5491622090339661, "alphanum_fraction": 0.5886816382408142, "avg_line_length": 22.257352828979492, "blob_id": "b0ec19beaedd4310f2d28a934a9f1b28ce51fbf7", "content_id": "1fbfa272a527c0999ee161454a462ce00d987bd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3163, "license_type": "no_license", "max_line_length": 81, "num_lines": 136, "path": "/Bruteforce (Console).py", "repo_name": "AaronVickers/Sudoku-Solver", "src_encoding": "UTF-8", "text": "# Made without research, just using simple backtracking algorithm\n\n# Dependencies\nimport timeit # For timing\n\n# Initial board\nboard = [\n 0, 2, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 6, 0, 0, 0, 0, 3,\n 0, 7, 4, 0, 8, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 3, 0, 0, 2,\n 0, 8, 0, 0, 4, 0, 0, 1, 0,\n 6, 0, 0, 5, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 0, 7, 8, 0,\n 5, 0, 0, 0, 0, 9, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 4, 0\n]\n\n# Print the board in a readable format\ndef printBoard():\n print(\"-\"*25)\n \n for i1 in range(0, 9):\n row = \"\"\n\n for i2 in range(i1*9, i1*9+9):\n row += str(board[i2])+\", \"\n\n print(row[:-2])\n \n print(\"-\"*25)\n\n# List position to X co-ordinate\n# Returns integer (X co-ordinate)\ndef getX(pos):\n return pos%9\n\n# List position to Y co-ordinate\n# Returns integer (Y co-ordinate)\ndef getY(pos):\n return pos//9\n\n# Co-ordinates to list position\n# Returns integer (list position)\ndef getPos(x, y):\n return x + y*9\n\n# Get top left list position of 3x3 square that supplied list position is in\n# Returns integer (list position)\ndef getSquareTopLeft(pos):\n x = getX(pos)\n y = getY(pos)\n \n xTop = x-x%3\n yTop = y-y%3\n \n return getPos(xTop, yTop)\n\n# Check if given value is valid to be used in list position\n# Returns bool (valid state)\ndef isValid(val, pos):\n x = getX(pos)\n y = getY(pos)\n\n # Check row and column for duplicates\n for i in range(0, 9):\n testX = getPos(i, y)\n testY = getPos(x, i)\n\n if testX != x and board[testX] == val:\n return False\n elif testY != y and board[testY] == val:\n return False\n \n topLeft = getSquareTopLeft(pos)\n\n # Check 3x3 grid for duplicates\n for i1 in range(0, 3):\n for i2 in range(0, 3):\n testPos = topLeft + getPos(i1, i2)\n\n if testPos != pos and board[testPos] == val:\n return False\n \n return True\n\n# Increases value on board in supplied list position until valid integer is found\n# Returns integer (next valid number, or 0 if none are valid)\ndef getNextValid(pos):\n val = board[pos]\n\n for i in range(val+1, 10):\n if isValid(i, pos):\n return i\n\n return 0\n\n# Gets next empty (0) square in board from supplied list position\n# Returns integer (list position)\n# Returns None (when no empty squares)\ndef getNextEmptyFrom(pos):\n for i in range(pos, len(board)):\n if board[i] == 0:\n return i\n\nprint(\"Solving...\")\n\n# Start timer\nstartTime = timeit.default_timer()\n\n# Array of filled in list positions (for backtracking)\nfilled = []\n\n# Set current to first empty square\ncurrent = getNextEmptyFrom(0)\n\n# While there are still empty squares\nwhile current != None:\n nextValid = getNextValid(current)\n board[current] = nextValid\n\n if nextValid != 0:\n filled.append(current)\n \n current = getNextEmptyFrom(current)\n else:\n if len(filled) > 0:\n current = filled.pop()\n else:\n print(\"Unsolvable board!\")\n break\n\nendTime = timeit.default_timer()\n\nprintBoard()\nprint(f\"Took {endTime-startTime} seconds to complete\")\n" } ]
1
0x00-pl/rex
https://github.com/0x00-pl/rex
2775630202c616464d33667731771d559c6d6e73
e6484cc7e053819585162c692513bc407c64b536
3d6f84ce447cdda799e7896de0ec0e20f7428c8f
refs/heads/master
2022-10-24T02:59:39.007078
2019-07-10T05:49:49
2020-06-16T05:49:49
255,545,785
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5272523760795593, "alphanum_fraction": 0.5309855937957764, "avg_line_length": 29.555133819580078, "blob_id": "3e118935f553186d87dfc43b313fcb434fedfc20", "content_id": "bf933f12345d40d518d5a8f986c02125471e30ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8036, "license_type": "no_license", "max_line_length": 108, "num_lines": 263, "path": "/nfa.py", "repo_name": "0x00-pl/rex", "src_encoding": "UTF-8", "text": "import typing\n\nimport utils\n\n\n\n\nclass NFA:\n trans_func_type = typing.Callable[[utils.MatchingIter], typing.Optional[int]]\n\n class Edge:\n def __init__(self, transition: 'NFA.trans_func_type', dst: 'NFA.Node', name=None):\n self.transition = transition\n self.dst = dst\n self.name = name\n\n eps_builder: trans_func_type = utils.FunctionWithName(lambda it: 0, 'eps')\n\n class Node:\n def __init__(self, edges: typing.AbstractSet['NFA.Edge'] = None):\n self.edges: typing.MutableSet['NFA.Edge'] = set(edges) if edges is not None else set()\n\n def copy(self):\n return NFA.Node(self.edges)\n\n def add_edges(self, edges: typing.AbstractSet['NFA.Edge']):\n self.edges |= edges\n\n def add_eps_edge(self, node: 'NFA.Node'):\n self.edges.add(NFA.Edge(NFA.eps_builder, node, 'eps'))\n\n def discard_edge(self, edge: 'NFA.Edge'):\n self.edges.discard(edge)\n\n def __str__(self):\n return str(id(self))\n\n def edges_to_string(self):\n ret = ''\n for edge in self.edges:\n ret += str(self) + ' --> ' + str(edge.dst) + (' : ' + edge.name if edge.name else '') + '\\n'\n\n return ret\n\n def __init__(self, nodes: typing.AbstractSet['NFA.Node'], start_node: 'NFA.Node',\n end_nodes: typing.AbstractSet['NFA.Node']):\n self.nodes = set(nodes)\n self.start_node = start_node\n self.end_nodes = set(end_nodes)\n\n def gc_nodes(self):\n keep_nodes = {self.start_node}\n edge_nodes = {self.start_node}\n while len(edge_nodes) > 0:\n item = edge_nodes.pop()\n for edge in item.edges:\n dest = edge.dst\n if dest not in keep_nodes:\n keep_nodes.add(dest)\n edge_nodes.add(dest)\n\n self.nodes = keep_nodes\n\n def eliminate_eps(self):\n edges_need_be_removed = set()\n for node in self.nodes:\n for edge in node.edges:\n if edge.transition == self.eps_builder:\n edges_need_be_removed.add((node, edge))\n break\n\n for src_node, edge in edges_need_be_removed:\n src_node.add_edges(edge.dst.edges)\n src_node.discard_edge(edge)\n\n self.gc_nodes()\n\n def copy(self):\n mapping: typing.MutableMapping['NFA.Node', 'NFA.Node'] = {}\n for node in self.nodes:\n mapping[node] = node.copy()\n\n # relink\n for new_node in mapping.values():\n for edge in new_node.edges:\n edge.dst = mapping[edge.dst]\n\n return NFA(set(mapping.values()), mapping[self.start_node], set(mapping[i] for i in self.end_nodes))\n\n def __str__(self):\n ret = 'https://www.planttext.com/\\n@startuml\\n\\n'\n for node in self.nodes:\n ret += node.edges_to_string()\n ret += str(self.start_node) + ' : start\\n'\n for node in self.end_nodes:\n ret += str(node) + ' : end\\n'\n\n ret += '\\n@enduml\\n'\n return ret\n\n\ndef make_seq_nfa(transition_list: typing.Sequence[typing.Union[NFA.trans_func_type, NFA]]):\n ret_start = NFA.Node()\n ret_ends: typing.Set[NFA.Node] = {ret_start}\n ret_nodes: typing.Set[NFA.Node] = {ret_start}\n for transition in transition_list:\n if isinstance(transition, NFA):\n transition_nfa = transition.copy()\n ret_nodes |= transition_nfa.nodes\n for ret_end in ret_ends:\n ret_end.add_eps_edge(transition_nfa.start_node)\n\n ret_ends = transition_nfa.end_nodes\n else:\n new_end = NFA.Node()\n ret_nodes.add(new_end)\n for ret_end in ret_ends:\n ret_end.add_edges({NFA.Edge(transition, new_end, str(transition))})\n ret_ends = {new_end}\n\n ret = NFA(ret_nodes, ret_start, ret_ends)\n ret.eliminate_eps()\n return ret\n\n\ndef make_or_nfa(transition_list: typing.Sequence[typing.Union[NFA.trans_func_type, NFA]]):\n ret_start = NFA.Node()\n ret_ends: typing.Set[NFA.Node] = set()\n ret_nodes: typing.Set[NFA.Node] = {ret_start}\n for transition in transition_list:\n if isinstance(transition, NFA):\n tmp = transition.copy()\n ret_nodes |= tmp.nodes\n ret_start.add_eps_edge(tmp.start_node)\n ret_ends |= tmp.end_nodes\n else:\n new_end = NFA.Node()\n ret_start.add_edges({NFA.Edge(transition, new_end, str(transition))})\n ret_nodes.add(new_end)\n ret_ends |= {new_end}\n\n ret = NFA(ret_nodes, ret_start, ret_ends)\n ret.eliminate_eps()\n return ret\n\n\nclass StatePool:\n def __init__(self):\n self.states = {0: set()}\n\n def tick(self):\n assert (len(self.states[0]) == 0)\n new_states = dict()\n for k, v in self.states.items():\n if len(v) != 0:\n new_states[k - 1] = v\n\n self.states = new_states\n\n def add_state(self, node: NFA.Node, delta: int):\n p = self.states.get(delta, set())\n p.add(node)\n self.states[delta] = p\n\n def pop_state(self) -> typing.Iterable[NFA.Node]:\n p = self.states.get(0, set())\n while len(p) != 0:\n yield p.pop()\n\n def __len__(self):\n return sum(len(v) for k, v in self.states.items())\n\n def __str__(self):\n ret = 'states:\\n'\n for k, v in self.states.items():\n ret += '[' + str(k) + ']:' + ' '.join([str(it) for it in v]) + '\\n'\n return ret\n\n\ndef nfa_match(nfa: NFA, target: utils.MatchingIter):\n states = StatePool()\n states.add_state(nfa.start_node, 0)\n\n while len(states) > 0 and target.idx <= len(target.l):\n for state in states.pop_state():\n if state in nfa.end_nodes:\n return True\n\n if target.idx == len(target.l):\n return False\n\n for edge in state.edges:\n next_state = edge.dst\n trans_func = edge.transition\n delta = trans_func(target)\n if delta is not None:\n states.add_state(next_state, delta)\n states.tick()\n target.move_delta(1)\n\n return False\n\n\nclass NFABuilder:\n def __init__(self, s: str, args: utils.RexArguments):\n self.args = args\n self.s = s\n self.s_idx = 0\n\n def get_ch(self, offset=0):\n if self.s_idx >= len(self.s):\n return None\n ret = self.s[self.s_idx]\n self.s_idx += offset\n return ret\n\n def nfa_read_name(self):\n name = ''\n self.get_ch(1) # for '{'\n while self.get_ch() != '}':\n name += self.get_ch(1)\n\n self.get_ch(1) # for '}'\n return name\n\n def nfa_build_list(self):\n ret = []\n while self.get_ch() not in (']', ')', None):\n if self.get_ch() == '{':\n name = self.nfa_read_name()\n ret.append(self.args.get(name))\n elif self.get_ch() == '[':\n ret.append(self.nfa_build_or_list())\n elif self.get_ch() == '(':\n ret.append(self.nfa_build_seq_list())\n return ret\n\n def nfa_build_or_list(self):\n self.get_ch(1) # for '['\n ret = self.nfa_build_list()\n self.get_ch(1) # for ']'\n return make_or_nfa(ret)\n\n def nfa_build_seq_list(self):\n self.get_ch(1) # for '('\n ret = self.nfa_build_list()\n self.get_ch(1) # for ')'\n return make_seq_nfa(ret)\n\n def nfa_build(self):\n return make_seq_nfa(self.nfa_build_list())\n\n\ndef test():\n nfa = NFABuilder('{}{}{}{}{}', utils.RexArguments().add_list(\n [utils.Transitions.eq(it, ()) for it in [1, 2, 3, utils.Transitions.any_obj, 5]])).nfa_build()\n print(nfa)\n match_iter = utils.MatchingIter([1, 2, 3, 4, 5])\n match_result = nfa_match(nfa, match_iter)\n print(match_result, match_iter.is_end())\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4946572780609131, "alphanum_fraction": 0.5009121894836426, "avg_line_length": 25.832168579101562, "blob_id": "b169931d9a11a5124980ef92fead63c722d9559c", "content_id": "86274defa82b77b42a3a623a8cb6867b2633f696", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3837, "license_type": "no_license", "max_line_length": 118, "num_lines": 143, "path": "/rex.py", "repo_name": "0x00-pl/rex", "src_encoding": "UTF-8", "text": "import typing\n\nimport utils\n\n\nclass REXEnv:\n VALUE_UNBOUND = object()\n\n def __init__(self, prev_env=None):\n self.data = {}\n self.prev_env = prev_env\n\n def fork(self):\n return REXEnv(prev_env=self)\n\n def get_value(self, key, default=None):\n cur = self.data.get(key, REXEnv.VALUE_UNBOUND)\n if cur != REXEnv.VALUE_UNBOUND:\n return cur\n elif self.prev_env:\n return self.prev_env.get_value(key, default)\n else:\n return default\n\n def match_value(self, key, value):\n val = self.get_value(key, REXEnv.VALUE_UNBOUND)\n if val == REXEnv.VALUE_UNBOUND:\n self.data[key] = value\n return True\n else:\n return val == value\n\n\nclass REX:\n def __init__(self, func):\n self.func = func\n\n def match(self, l, env=None):\n env = env or {}\n if not isinstance(l, utils.MatchingIter):\n ll = utils.MatchingIter(l)\n else:\n ll = l\n return self.func(ll, env)\n\n\nclass REXFunc:\n def __init__(self):\n pass\n\n ty = typing.Callable[[utils.MatchingIter, REXEnv], typing.Optional[tuple[utils.MatchingIter, REXEnv]]]\n\n @staticmethod\n def end():\n def is_end(it: utils.MatchingIter, env):\n if it.is_end():\n return it, env\n else:\n return None\n\n return is_end\n\n @staticmethod\n def with_env(name: str, func):\n def with_env(it: utils.MatchingIter, env: REXEnv):\n fr = func(it, env)\n if fr is None:\n return None\n clip = it.clip(fr[0].idx)\n if env.match_value(name, clip):\n return fr\n else:\n return None\n\n return with_env\n\n @staticmethod\n def or_(*args):\n def or_(it: utils.MatchingIter, env: REXEnv):\n for func in args:\n new_env = env.fork()\n fr = func(it, new_env)\n if fr is None:\n continue\n else:\n return fr\n else:\n return None\n\n return or_\n\n @staticmethod\n def seq(*args):\n def seq(it: utils.MatchingIter, env: REXEnv):\n env = env.fork()\n for func in args:\n fr = func(it, env)\n if fr is None:\n return None\n else:\n it, env = fr\n return it, env\n\n return seq\n\n @staticmethod\n def eq(val):\n def eq(it: utils.MatchingIter, env: REXEnv):\n if it.get() == val:\n new_it = it.clone()\n new_it.move_delta(1)\n return new_it, env\n else:\n return None\n\n return eq\n\n @staticmethod\n def eq_list(val_list):\n val_list_len = len(val_list)\n\n def eq_list(it: utils.MatchingIter, env: REXEnv):\n if it.clip(it.idx + val_list_len) == val_list:\n new_it = it.clone()\n new_it.move_delta(val_list_len)\n return new_it, env\n else:\n return None\n\n return eq_list\n\n\ndef test():\n protocol = REXFunc.with_env(\"protocol\", REXFunc.or_(REXFunc.match_nfa(\"{}{}{}{}[(){}]\", \"h\", \"t\", \"t\", \"p\", \"s\")))\n digits = utils.FunctionWithName(is_digits_0_to_255, \"ip_digits\")\n digits_4x = REXFunc.seq(\n REXFunc.with_env(\"digits0\", digits), REXFunc.eq('.'),\n REXFunc.with_env(\"digits1\", digits), REXFunc.eq('.'),\n REXFunc.with_env(\"digits2\", digits), REXFunc.eq('.'),\n REXFunc.with_env(\"digits3\", digits))\n rex = REX(REXFunc.seq(protocol, REXFunc.eq_list('://'), digits_4x, REXFunc.end()))\n result_env = rex.match(\"https://114.114.114.114\", env={})\n print(result_env)\n" }, { "alpha_fraction": 0.5237113237380981, "alphanum_fraction": 0.5268041491508484, "avg_line_length": 22.658536911010742, "blob_id": "a831e1f43f747948004d39fd68c84b0fc6d26a17", "content_id": "ea4ea3eecc4cc174af6125beca5609a63f1d5d3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1940, "license_type": "no_license", "max_line_length": 76, "num_lines": 82, "path": "/utils.py", "repo_name": "0x00-pl/rex", "src_encoding": "UTF-8", "text": "class FunctionWithName:\n def __init__(self, func, name):\n self.func = func\n self.name = name\n\n def __call__(self, *args, **kwargs):\n return self.func(*args, **kwargs)\n\n def __str__(self):\n return self.name\n\n\nclass MatchingIter:\n def __init__(self, l):\n self.l = list(l)\n self.idx = 0\n\n def move_delta(self, delta):\n self.idx += delta\n\n def get_delta(self, delta):\n return self.l[self.idx + delta]\n\n def get(self):\n return self.get_delta(0)\n\n def is_end(self):\n return self.idx == len(self.l)\n\n def clone(self):\n ret = MatchingIter(self.l)\n ret.idx = self.idx\n return ret\n\n def clip(self, until_idx: int):\n return self.l[self.idx:until_idx]\n\n\nclass Transitions:\n any_obj = object()\n\n @staticmethod\n def eq(obj, exclude_types):\n for ty in exclude_types:\n if isinstance(obj, ty):\n return obj\n\n if obj is Transitions.any_obj:\n return FunctionWithName(lambda l: 1, '.')\n else:\n return FunctionWithName(lambda l: 1 if l.get() == obj else None,\n '<' + str(obj) + '>')\n\n\nclass RexArguments:\n def __init__(self):\n self.fetch_idx = 0\n self.value_list = []\n self.value_dict = {}\n\n def add(self, value, name=''):\n self.value_list.append(value)\n if name != '':\n self.value_dict[name] = value\n return self\n\n def add_list(self, value_list: list):\n for value in value_list:\n self.add(value)\n return self\n\n def add_dict(self, value_dict):\n for name, value in value_dict.items():\n self.add(value, name)\n return self\n\n def get(self, name=''):\n if name != '':\n return self.value_dict[name]\n idx = self.fetch_idx\n self.fetch_idx += 1\n return self.value_list[idx]\n" } ]
3
lahwran/tx_tlsrelay
https://github.com/lahwran/tx_tlsrelay
a7a13dd5408da09ed28f1dfbafc8da853bdb6628
1f623e99a76259bcf167eda093bc894f377db0f4
b26fb20afe1a7361fa0ef6f2e7423b7f7f65e3eb
refs/heads/master
2020-05-30T01:02:30.123491
2014-12-06T02:18:27
2014-12-06T02:18:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6583132743835449, "alphanum_fraction": 0.666987955570221, "avg_line_length": 22.850574493408203, "blob_id": "a4679bcb952665e420441074074290e16a725d4c", "content_id": "1e8e352f06c63e094681e0cc1701568b0c3993c4", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2075, "license_type": "permissive", "max_line_length": 79, "num_lines": 87, "path": "/test.sh", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# This file is licensed MIT. see license.txt.\n# warning: I'm bad at bash. this is a bit hacky\n\n# set up\nset -m # job control\nset -e # fast abort\nfunction cleanup() {\n set +e\n for job in `jobs -p`; do\n kill -9 $job\n done\n}\ntrap cleanup EXIT\nexport PYTHONUNBUFFERED=True\nBASEPORT=5000\n\n# reset and start relay\ncoverage erase\ncoverage run --rcfile=.coveragerc -p bin/tx_tlsrelay $BASEPORT --port-count 2 &\nrelaypid=\"$!\"\nsleep 0.5\n\nfunction serve() {\n rm /tmp/address >&/dev/null || true\n coverage run --rcfile=.coveragerc -p \"$@\" > /tmp/address &\n secondtolastpid=\"$lastpid\"\n lastpid=\"$!\"\n sleep 2\n hostname=\"$(cat /tmp/address | sed 's/:.*$//')\"\n port=\"$(cat /tmp/address | sed 's/^.*://')\"\n}\nfunction stopserver() {\n set +e\n kill -INT \"$lastpid\"\n wait \"$lastpid\"\n set -e\n}\nfunction stopserver2() {\n set +e\n kill -INT \"$secondtolastpid\"\n wait \"$secondtolastpid\"\n set -e\n}\n\nfunction app_nc () {\n python -m tx_tlsrelay.tls_netcat -k application_certs \"$@\"\n}\n\nserve bin/relayed_echoserver localhost $BASEPORT\necho \"--- expect to see 'hello world':\"\n(echo \"hello world\"; sleep 2) | app_nc $hostname $port\necho \"---\"; echo\nstopserver\n\nserve bin/relayed_echoserver localhost $BASEPORT\necho \"--- expect to see 'resumed':\"\nkill -STOP $lastpid\necho \"hello world\" | app_nc $hostname $port\nkill -CONT $lastpid\n(echo \"resumed\"; sleep 2) | app_nc $hostname $port\necho \"---\"; echo\nstopserver\n\necho \"--- expect to see 'no controller linked':\"\nsleep 2 | nc $hostname $port\necho\necho \"---\"; echo\n\nserve bin/relayed_echoserver localhost $BASEPORT\necho \"--- expect to see 'hi!' once every second, three times:\"\n(for x in 1 2 3; do echo \"hi!\"; sleep 1; done) | app_nc $hostname $port\necho \"---\"; echo\nstopserver\n\necho \"--- expect to see a RelayFullError and a failure to kill a process\"\nserve bin/relayed_echoserver localhost $BASEPORT\nserve bin/relayed_echoserver localhost $BASEPORT\nstopserver2\nstopserver\necho \"---\"; echo\n\nkill -INT \"$relaypid\"\nwait \"$relaypid\"\n\ncoverage combine\ncoverage html --omit=\"ve/*\"\n" }, { "alpha_fraction": 0.6489361524581909, "alphanum_fraction": 0.652019739151001, "avg_line_length": 30.33333396911621, "blob_id": "96f24e7345b3afd97a1eaf2ed208aa19328f7c20", "content_id": "6e71e806fb313510d9fc73e1f89a84b9906d08ff", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6486, "license_type": "permissive", "max_line_length": 74, "num_lines": 207, "path": "/tx_tlsrelay/server.py", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "# This file is licensed MIT. see license.txt.\n\n# note: usually I'd translate twisted's parlance of\n# \"factory\" and \"protocol\" to \"server\" and \"session\",\n# but in this case there are so many servers and clients\n# immediately adjacent that it got too confusing to user\n# \"server\". I kept \"session\", though.\n\n# note: this program contains refloops. I left those up to\n# the gc of <your interpreter here> to deal with.\n\n# note: this program does not differentiate connections by\n# any sort of ID, due to not having any way to notify the\n# reverse client of what the connection's ID is on connect\n# (since it's intended to be an extra-vanilla protocol for\n# reverse-connecting side).\n\n# note: this program is ipv4-only.\n\nfrom collections import deque\nimport argparse\nimport py\n\nfrom twisted.internet.protocol import Factory, Protocol\nfrom twisted.protocols.basic import LineOnlyReceiver\n\nfrom tx_tlsrelay.tlskeys import TLSKeys\n\n\nclass ChildSession(Protocol):\n def connectionMade(self):\n self.transport.setTcpKeepAlive(True)\n\n if self.control_session is None:\n self.transport.write(\"no controller linked\")\n self.transport.loseConnection()\n return\n\n # yay inheritance\n self.finish_setup()\n self.factory.sessions.append(self)\n\n def connectionLost(self, reason):\n self.pre_deinit()\n try:\n self.factory.sessions.remove(self)\n except ValueError:\n pass\n\n\nclass PublicSession(ChildSession):\n def __init__(self):\n self.queue = deque()\n self.reverse_session = None\n self.disconnected = False\n\n def finish_setup(self):\n self.control_session.public_ready(self)\n\n def dataReceived(self, data):\n # DOS vulnerability: connect to control session; connect to public\n # port; send lots of data without connecting to reverse port to\n # receive it.\n if not self.reverse_session:\n self.queue.append(data)\n else:\n self.reverse_session.transport.write(data)\n\n def pre_deinit(self):\n if self.reverse_session:\n self.reverse_session.transport.loseConnection()\n self.disconnected = True\n\n\nclass ReverseSession(ChildSession):\n def __init__(self):\n self.public_session = None\n\n def finish_setup(self):\n try:\n self.public_session = self.control_session.queue.popleft()\n except IndexError:\n # TODO: report to controller client that it made an\n # extra connection?\n self.transport.loseConnection()\n return\n self.public_session.reverse_session = self\n for data in self.public_session.queue:\n self.transport.write(data)\n if self.public_session.disconnected:\n self.transport.loseConnection()\n\n def dataReceived(self, data):\n self.public_session.transport.write(data)\n\n def pre_deinit(self):\n if self.public_session:\n self.public_session.transport.loseConnection()\n\n\nclass ChildFactory(Factory):\n def __init__(self):\n self.sessions = []\n self.control_session = None\n self.address = None\n\n def killall(self):\n for session in self.sessions:\n session.transport.loseConnection()\n\n def buildProtocol(self, addr):\n p = Factory.buildProtocol(self, addr)\n p.control_session = self.control_session\n return p\n\n\nclass ControlSession(LineOnlyReceiver):\n def __init__(self):\n self.reverse = None\n self.public = None\n self.queue = deque()\n\n def connectionMade(self):\n self.transport.setTcpKeepAlive(True)\n\n if not self.factory.reverse_factories:\n self.sendLine(\"no_available_listeners\")\n self.transport.loseConnection()\n return\n\n self.reverse = self.factory.reverse_factories.popleft()\n self.public = self.factory.public_factories.popleft()\n self.reverse.control_session = self\n self.public.control_session = self\n\n self.sendLine(\"public_listener \" + self.public.address)\n self.sendLine(\"reverse_listener \" + self.reverse.address)\n\n def connectionLost(self, reason):\n if not self.public:\n return\n\n # connections will linger for a moment, but new ones\n # will be set up correctly, so that's okay\n self.reverse.killall()\n self.public.killall()\n\n self.reverse.control_session = None\n self.public.control_session = None\n\n self.factory.reverse_factories.append(self.reverse)\n self.factory.public_factories.append(self.public)\n\n def public_ready(self, public_session):\n self.queue.append(public_session)\n self.sendLine(\"new_connection\")\n\n\nclass ControlFactory(Factory):\n protocol = ControlSession\n\n def __init__(self, port_count):\n self.reverse_factories = deque()\n self.public_factories = deque()\n for _ in range(port_count / 2):\n reverse = ChildFactory.forProtocol(ReverseSession)\n public = ChildFactory.forProtocol(PublicSession)\n self.reverse_factories.append(reverse)\n self.public_factories.append(public)\n\n self.all_child_factories = (list(self.reverse_factories) +\n list(self.public_factories))\n\n\ndef even_int(v): # pragma: no cover\n x = int(v)\n if x % 2 != 0:\n raise ValueError(\"must be divisible by 2\")\n return x\n\n\nparser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"port\", nargs=\"?\", default=12000, type=int,\n help=\"port to listen for control connections\")\nparser.add_argument(\"--port-count\", default=200, type=even_int,\n help=\"how many ports above --port to allocate for relaying\")\nparser.add_argument(\"--myhost\", default=\"127.0.0.1\",\n help=\"the host to report to clients that is 'me'\")\nparser.add_argument(\"-k\", \"--keys\", type=py.path.local,\n default=\"./relay_server_certs\")\n\n\ndef main():\n args = parser.parse_args()\n\n from twisted.internet import reactor\n control = ControlFactory(args.port_count)\n tls_keys = TLSKeys(reactor, args.keys)\n\n tls_keys.server(args.port).listen(control)\n for index, child_factory in enumerate(control.all_child_factories):\n port = index + 1 + args.port\n child_factory.address = \"%s:%d\" % (args.myhost, port)\n reactor.listenTCP(port, child_factory)\n\n reactor.run()\n" }, { "alpha_fraction": 0.7355623245239258, "alphanum_fraction": 0.7355623245239258, "avg_line_length": 19.5625, "blob_id": "5d0ff6987902bfc22ec49db4a895b96a8a17a029", "content_id": "a33f8d2d78f1dce2602f4a938422458107c380ce", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "permissive", "max_line_length": 45, "num_lines": 16, "path": "/bin/relayed_httpserver", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# This file is licensed MIT. see license.txt.\nimport os, sys\n\ntry:\n import _preamble\nexcept ImportError:\n sys.exc_clear()\n\nfrom twisted.web.server import Site\nfrom twisted.web.static import File\nfrom tx_tlsrelay.demo import demo\n\nresource = File(os.path.abspath('.'))\nsite = Site(resource)\ndemo(site)\n" }, { "alpha_fraction": 0.6656948328018188, "alphanum_fraction": 0.6669096350669861, "avg_line_length": 30.9069766998291, "blob_id": "d16202ad5969a74057843437c1414b5130c8244b", "content_id": "a54851ce0483431cb965b30b2d4c4f4ef2086059", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4116, "license_type": "permissive", "max_line_length": 86, "num_lines": 129, "path": "/tx_tlsrelay/client.py", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "# This file is licensed MIT. see license.txt.\n# note: this program is ipv4-only.\n\nfrom twisted.protocols.basic import LineOnlyReceiver\nfrom twisted.internet.defer import Deferred\nfrom twisted.internet.error import CannotListenError\nfrom twisted.internet.protocol import Factory\nfrom twisted.internet import address\nfrom twisted.internet import interfaces\nfrom zope.interface import implementer\n\nfrom tx_tlsrelay.tlskeys import SSL4ReverseServerEndpoint\n\n\nclass RelayFullError(CannotListenError):\n def __init__(self):\n pass\n\n def __str__(self):\n return \"RelayFullError()\"\n\n\nclass Address(address._IPAddress):\n def __repr__(self):\n return super(self, Address).__str__()\n\n def __str__(self):\n return \"%s:%d\" % (self.host, self.port)\n\n@implementer(interfaces.IListeningPort)\nclass ControlClient(LineOnlyReceiver):\n def __init__(self, reactor, childfactory, tls_server_options, listening_deferred):\n self.reactor = reactor\n self.childfactory = childfactory\n self.expected_count = 0\n self.public_address = None\n self.reverse_address = None\n self.reverse_endpoint = None\n self.listening_deferred = listening_deferred\n self.disconnect_deferred = Deferred()\n\n self.tls_server_options = tls_server_options\n\n self.childfactory.doStart()\n\n def lineReceived(self, line):\n message, _, tail = line.partition(\" \")\n handler = getattr(self, \"message_\" + message, None)\n if handler is None: # pragma: no cover\n print \"unknown message\", message, tail\n return\n handler(tail)\n\n def message_new_connection(self, tail):\n self.reverse_endpoint.connect(self.childfactory)\n\n def message_no_available_listeners(self, tail):\n self.listening_deferred.errback(RelayFullError())\n self.transport.loseConnection()\n\n def _splitaddress(self, text):\n host, _, port = text.rpartition(\":\")\n port = int(port)\n return Address(\"TCP\", host, port)\n\n def message_public_listener(self, tail):\n self.public_address = self._splitaddress(tail)\n if self.reverse_address: # pragma: no cover\n self.listening_deferred.callback(self)\n\n def message_reverse_listener(self, tail):\n self.reverse_address = addr = self._splitaddress(tail)\n self.reverse_endpoint = SSL4ReverseServerEndpoint(\n self.reactor, addr.host, addr.port, self.tls_server_options)\n if self.public_address:\n self.listening_deferred.callback(self)\n\n def connectionLost(self, reason):\n self.childfactory.doStop()\n self.disconnect_deferred.callback(self)\n\n # IListeningPort functions\n\n def startListening(self):\n pass\n\n def stopListening(self):\n self.transport.loseConnection()\n return self.disconnect_deferred\n\n def getHost(self):\n return self.public_address\n\n\nclass ControlClientFactory(Factory):\n def __init__(self, reactor, childfactory,\n tls_server_options, listening_deferred):\n self.reactor = reactor\n self.childfactory = childfactory\n self.tls_server_options = tls_server_options\n self.listening_deferred = listening_deferred\n\n def buildProtocol(self, addr):\n return ControlClient(self.reactor, self.childfactory,\n self.tls_server_options,\n self.listening_deferred)\n\n\n@implementer(interfaces.IStreamServerEndpoint)\nclass TLS4RelayServerEndpoint(object):\n def __init__(self, control_endpoint,\n tls_server_options,\n reactor=None):\n if reactor is None:\n from twisted.internet import reactor\n self.reactor = reactor\n\n self.tls_server_options = tls_server_options\n self.relayendpoint = control_endpoint\n\n def listen(self, childfactory):\n listening_deferred = Deferred()\n\n factory = ControlClientFactory(self.reactor,\n childfactory, self.tls_server_options,\n listening_deferred)\n self.relayendpoint.connect(factory)\n\n return listening_deferred\n" }, { "alpha_fraction": 0.6140350699424744, "alphanum_fraction": 0.6170142292976379, "avg_line_length": 34.541175842285156, "blob_id": "90a6df8eb4bcf70403f4be26bd213c905aa595a0", "content_id": "1a31a47f3db9272e72294d518356b91138b63610", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3021, "license_type": "permissive", "max_line_length": 95, "num_lines": 85, "path": "/tx_tlsrelay/tlskeys.py", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "import py\nfrom twisted.internet import ssl\nfrom twisted.protocols import tls\nfrom twisted.internet import defer\nfrom twisted.internet.endpoints import SSL4ClientEndpoint, SSL4ServerEndpoint, _WrappingFactory\nfrom twisted.internet import interfaces\nfrom zope.interface import implementer\n\n@implementer(interfaces.IStreamClientEndpoint)\nclass SSL4ReverseServerEndpoint(object):\n def __init__(self, reactor, host, port, server_options,\n timeout=30, outgoing_bind_address=None):\n self._reactor = reactor\n self._host = host\n self._port = port\n self._server_options = server_options\n self._timeout = timeout\n self._bindAddress = outgoing_bind_address\n\n def connect(self, factory):\n tls_factory = tls.TLSMemoryBIOFactory(self._server_options,\n isClient=False, wrappedFactory=factory)\n try:\n wf = _WrappingFactory(tls_factory)\n self._reactor.connectTCP(\n self._host, self._port, wf,\n timeout=self._timeout, bindAddress=self._bindAddress)\n return wf._onConnection\n except:\n return defer.fail()\n\n\nclass TLSKeys(object):\n def __init__(self, reactor, basedir):\n self.reactor = reactor\n basedir = py.path.local(basedir)\n\n #\n cadata = basedir.join(\"ca.crt.pem\").read()\n self.ca_cert = ssl.Certificate.loadPEM(cadata)\n\n try:\n clientdata = (\n basedir.join(\"client.crt.pem\").read_binary()\n + basedir.join(\"client.key.pem\").read_binary()\n )\n except py.error.ENOENT:\n self.has_client = False\n else:\n self.has_client = True\n self.client_cert = ssl.PrivateCertificate.loadPEM(clientdata)\n self.client_options = self.client_cert.options(self.ca_cert)\n\n #\n try:\n serverdata = (\n basedir.join(\"server.crt.pem\").read_binary()\n + basedir.join(\"server.key.pem\").read_binary()\n )\n except py.error.ENOENT:\n self.has_server = False\n else:\n self.has_server = True\n self.server_cert = ssl.PrivateCertificate.loadPEM(serverdata)\n self.server_options = self.server_cert.options(self.ca_cert)\n\n def server(self, port):\n if not self.has_server:\n raise RuntimeError(\"Missing server certs!\")\n return SSL4ServerEndpoint(self.reactor, port,\n self.server_options)\n\n def client(self, host, port):\n if not self.has_client:\n raise RuntimeError(\"Missing client certs!\")\n return SSL4ClientEndpoint(self.reactor, host, port,\n self.client_options)\n\n def relayed_server(self, control_endpoint):\n if not self.has_server:\n raise RuntimeError(\"Missing server certs!\")\n return TLS4RelayServerEndpoint(control_endpoint,\n self.server_options)\n\nfrom tx_tlsrelay.client import TLS4RelayServerEndpoint\n" }, { "alpha_fraction": 0.7164948582649231, "alphanum_fraction": 0.7164948582649231, "avg_line_length": 16.636363983154297, "blob_id": "257c7bfd307dcfa56bca0cd46a4379870da14af9", "content_id": "284805434d3ca894f378b336f598f95d49623659", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "permissive", "max_line_length": 45, "num_lines": 11, "path": "/bin/tx_tlsrelay", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# This file is licensed MIT. see license.txt.\nimport os, sys\n\ntry:\n import _preamble\nexcept ImportError:\n sys.exc_clear()\n\nfrom tx_tlsrelay.server import main\nmain()\n" }, { "alpha_fraction": 0.7448673844337463, "alphanum_fraction": 0.7547048926353455, "avg_line_length": 43.11320877075195, "blob_id": "a938edc742f138310aceaca3a8637cd28f8aa790", "content_id": "a5915c61475bab2358bb0bfaea07bea38d897ab3", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4676, "license_type": "permissive", "max_line_length": 90, "num_lines": 106, "path": "/readme.md", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "Cheapo TCP/TLS Relay\n====================\n\nThis was originally written as part of my interviewing process for the company I\ncurrently work at (as of the commit that edits this line). As it was written before\nI signed anything with that company, I own the copyright (verified with my boss).\n\nI'm releasing it under the MIT license. see license.txt.\n\nExplanation\n-----------\n\nFirst, lingo:\n\n- \"server\" means a program using the relay to provide a service\n- \"client\" means a program connecting to the relay to use a service\n- \"relay\" means the relay server itself; \"server\" will not be used to refer to this\n\n\nImplementation and Protocol\n---------------------------\n\nThe relay uses a very cheap approach: for each incoming connection, the server must\ninitiate a new TCP/TLS connection to the relay. This has all the drawbacks associated\nwith creating a new TCP/TLS connection, but means that you don't have to write a\nmultiplexer-protocol implementation to use it.\n\nOn startup, the relay allocates a pool of listening ports. This is done ahead of time\nto ensure that the frequent allocation and release of ports does not allow other\nprocesses on the system to grab ownership of the ports. The number of ports the relay\nallocates is configurable via --port-count, and must be divisible by 2, as the relay\nassigns two ports to each server: a public port and a reverse port.\n\nOther notes: the relay only supports ipv4 (it wouldn't be too hard to add ipv6, but\nI didn't bother). Also, the relay doesn't have any way to differentiate connections.\nHowever, as long as you don't write bugs and nobody tries to mess you up, everything\nwill work fine. Nothing to worry about. It'll be fine. Stop asking questions.\n\nUsage\n-----\n\nQuick version:\n\n1. start `bin/tx_tlsrelay`. defaults to port 12000, or takes port on command line;\n see --help. of note is --myhost, which should be set if used anywhere but localhost.\n2. connect to control port\n3. make sure the server did not send you a `no_available_listeners` message; if it\n did, the relay is out of ports, and you're out of luck\n4. parse the listener messages\n5. wait for \n\nWhen your server wants to use the relay, it must initiate a connection to the\n*control port*; 12000 by default. The control protocol is a very simple line-based\nprotocol (delimited by \\r\\n). Its syntax is very simple; a command, sometimes\nfollowed by an argument, space-separated. these are the messages defined:\n\n- `public_listener <HOSTNAME>:<PORT>` - tells the server what its public address is;\n this is the address clients should connect to when they want to use the server.\n- `reverse_listener <HOSTNAME>:<PORT>` - tells the server what its reverse address is;\n this is the address that the server should connect to to service clients.\n- `new_connection` - sent when a new client comes in. server should respond by\n connecting to the address provided by `reverse_listener`; that connection becomes\n a client connection.\n- `no_available_listeners` - sent by the relay when it has no more ports available\n to give to new servers. If the server receives this message, there's nothing it\n can do but wait and hope for another server to disconnect.\n\nAgain: when a new client connection comes in, your server must connect to the\nreverse port; that connection becomes the session with the client. With most socket\nlibraries this should only be a change in initialization code.\n\nExample session:\n\n- `server +> relay` server connects to localhost:12000\n- `server <= relay` relay sends back lines:\n\n public_listener localhost:12101\n reverse_listener localhost:12001\n\n- `......... relay <+ client` client connects to localhost:12101\n- `server <= relay .........` relay informs server of presence of new client with message:\n\n new_connection\n\n- `server +> relay` server connects to localhost:12001\n- `server <=> relay <=> client` \n server uses this new connection to communicate with client\n\nFor a reference implementation and examples you can run, see `tx_tlsrelay.client`\nand `bin/relayed_*server`.\n\nTwisted Usage\n-------------\n\nInstead of `TLS4ServerEndpoint`, use `tx_tlsrelay.client.TLS4RelayServerEndpoint`\nand pass it the address of the relay you wish to use. TLS4RelayServerEndpoint.listen()\nreturns a deferred that fires with an object that implements IListeningPort;\nthat object's .getHost() method returns an address object with .host and .port, which\nare your server's public address.\n\nSee also:\n\n- http://twistedmatrix.com/documents/current/core/howto/endpoints.html\n- the mentions of endpoints in\n https://twistedmatrix.com/documents/current/core/howto/servers.html\n- `bin/relayed_echoserver` and `bin/relayed_httpserver`\n" }, { "alpha_fraction": 0.6301546096801758, "alphanum_fraction": 0.630584180355072, "avg_line_length": 25.454545974731445, "blob_id": "c0af8fc8b7c83eb5df7e04ff43e54d20212decd8", "content_id": "b7057cef36362ef7eda0397d86050fd643b449bd", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2328, "license_type": "permissive", "max_line_length": 88, "num_lines": 88, "path": "/tx_tlsrelay/tls_netcat.py", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "# connect to server\n# read from stdin, write to server\n# read from server, write to stdout\n\nimport argparse\nimport py\nimport sys\nfrom twisted.internet import process\nfrom twisted.internet import protocol\nimport twisted\n\nfrom tx_tlsrelay.tlskeys import TLSKeys\n\ndef debug(msg):\n return\n sys.stderr.write(msg)\n sys.stderr.write(\"\\n\")\n sys.stderr.flush()\n\nclass Netcat(protocol.Protocol):\n def __init__(self, reactor):\n self.reactor = reactor\n\n def connectionMade(self):\n debug(\"outgoing connection made\")\n self.reader = process.ProcessReader(self.reactor, self, \"in\", 0)\n\n def dataReceived(self, data):\n debug(\"got data: %r\" % (data,))\n sys.stdout.write(data)\n sys.stdout.flush()\n\n def childDataReceived(self, fd, data):\n debug(\"got stdin data: %r\" % (data,))\n self.transport.write(data)\n\n def connectionLost(self, reason):\n debug(\"outgoing connection lost: %r\" % (reason,))\n try:\n self.reactor.stop()\n except twisted.internet.error.ReactorNotRunning:\n pass\n\n def childConnectionLost(self, fd, reason):\n debug(\"stdin connection lost: %r\" % (reason,))\n try:\n self.reactor.stop()\n except twisted.internet.error.ReactorNotRunning:\n pass\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"host\")\n parser.add_argument(\"port\", type=int)\n parser.add_argument(\"-k\", \"--tls-directory\",\n type=py.path.local, required=True)\n parser.add_argument(\"-r\", \"--reverse-server\", action=\"store_true\")\n try:\n args = parser.parse_args()\n except:\n print sys.argv\n raise\n\n from twisted.internet import reactor\n\n def print_and_shutdown(error):\n error.printBriefTraceback()\n try:\n reactor.stop()\n except twisted.internet.error.ReactorNotRunning:\n pass\n\n tls_keys = TLSKeys(reactor, args.tls_directory)\n\n if args.reverse_server:\n endpoint = tls_keys.reverse_server(args.host, args.port)\n else:\n endpoint = tls_keys.client(args.host, args.port)\n\n d = endpoint.connect(protocol.Factory.forProtocol(lambda *a, **kw: Netcat(reactor)))\n d.addErrback(print_and_shutdown)\n del d\n\n reactor.run()\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6775631308555603, "alphanum_fraction": 0.6857355237007141, "avg_line_length": 27.63829803466797, "blob_id": "241aac4e569e225de4b24fcbb5b6b740a813974b", "content_id": "6bb061fdb2fe9a1fa67c2f982920f0696c09604a", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1346, "license_type": "permissive", "max_line_length": 68, "num_lines": 47, "path": "/tx_tlsrelay/demo.py", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "# This file is licensed MIT. see license.txt.\n\nimport argparse\nimport twisted\nimport py\n\nfrom tx_tlsrelay.tlskeys import TLSKeys\n\nparser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"host\", default=\"127.0.0.1\",\n help=\"the host to report to clients that is 'me'\")\nparser.add_argument(\"port\", default=12000, type=int,\n help=\"port to listen for control connections\")\nparser.add_argument(\"-a\", \"--application-certs\", type=py.path.local,\n default=\"./application_certs\")\nparser.add_argument(\"-c\", \"--relay-certs\", type=py.path.local,\n default=\"./relay_client_certs\")\n\ndef demo(factory):\n args = parser.parse_args()\n\n def connected(listener):\n print listener.getHost()\n\n\n def print_and_shutdown(error):\n try:\n reactor.stop()\n except twisted.internet.error.ReactorNotRunning:\n pass\n return error\n\n from twisted.internet import reactor\n\n relay_keys = TLSKeys(reactor, args.relay_certs)\n application_keys = TLSKeys(reactor, args.application_certs)\n\n relay_client = relay_keys.client(args.host, args.port)\n server = application_keys.relayed_server(relay_client)\n\n d = server.listen(factory)\n d.addCallback(connected)\n d.addErrback(print_and_shutdown)\n del d\n\n reactor.run()\n" }, { "alpha_fraction": 0.7329699993133545, "alphanum_fraction": 0.7329699993133545, "avg_line_length": 19.38888931274414, "blob_id": "546629afe437980ff047187590a94e3713c5c8a5", "content_id": "96c5d0fa3681bc2c75131a1d246f652b7b20d7a8", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "permissive", "max_line_length": 55, "num_lines": 18, "path": "/bin/relayed_echoserver", "repo_name": "lahwran/tx_tlsrelay", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# This file is licensed MIT. see license.txt.\nimport os, sys\n\ntry:\n import _preamble\nexcept ImportError:\n sys.exc_clear()\n\nfrom twisted.internet.protocol import Protocol, Factory\nfrom tx_tlsrelay.demo import demo\n\nclass Echo(Protocol):\n\n def dataReceived(self, data):\n self.transport.write(data)\n\ndemo(Factory.forProtocol(Echo))\n" } ]
10
ismailhy58/server
https://github.com/ismailhy58/server
b01b04808a7ec038a4523f835794bd6769e88b0c
3909040b5ab63ecda7dd357729213a4e1729d0e9
c363e4a4b5656b9ae94496239a3dbf85a3c13097
refs/heads/main
2023-05-02T21:07:56.500562
2021-05-24T17:24:58
2021-05-24T17:24:58
370,431,865
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5153631567955017, "alphanum_fraction": 0.5405027866363525, "avg_line_length": 18.514286041259766, "blob_id": "d0aef783305083058f4529d1dfea304727fd3e4e", "content_id": "08f3edeafd0a947b529029682a60f2fdda71a062", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "no_license", "max_line_length": 68, "num_lines": 35, "path": "/pygame/data_gen.py", "repo_name": "ismailhy58/server", "src_encoding": "UTF-8", "text": "import csv\r\nimport random\r\nimport time\r\n\r\nx_value = 0\r\ntotal_1 = 0\r\n\r\n\r\nfieldnames = [\"x_value\", \"total_1\"]\r\n\r\n\r\nwith open('data.csv', 'w') as csv_file:\r\n csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\r\n csv_writer.writeheader()\r\n\r\nwhile True:\r\n\r\n with open('data.csv', 'a') as csv_file:\r\n csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\r\n\r\n info = {\r\n \"x_value\": x_value,\r\n \"total_1\": total_1\r\n }\r\n\r\n csv_writer.writerow(info)\r\n print(x_value, total_1)\r\n\r\n x_rand=random.randint(0,1)\r\n x_value += (10*x_rand)\r\n y_rand=random.randint(0, 1)\r\n total_1 += 10*y_rand\r\n \r\n\r\n time.sleep(0.5)" }, { "alpha_fraction": 0.6124230027198792, "alphanum_fraction": 0.6599075794219971, "avg_line_length": 24.33783721923828, "blob_id": "6b644b0c949ed38bae3c097f44525012110e1988", "content_id": "1f4ca7c4b62bda82061226a69af5734ff90065c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3896, "license_type": "no_license", "max_line_length": 94, "num_lines": 148, "path": "/pygame/main.py", "repo_name": "ismailhy58/server", "src_encoding": "UTF-8", "text": "from numpy import sqrt\r\nimport pygame\r\nimport pandas as pd \r\n#import time\r\n\r\n\r\n#initialize \r\npygame.init() \r\n\r\n#variables\r\nscreen_width = 800\r\nscreen_height = 600\r\ntreshold = 150\r\n\r\n\r\n#screen\r\nscreen = pygame.display.set_mode((screen_width,screen_height)) #create screen\r\nrunning = True\r\n\r\n\r\n#Title and icon\r\npygame.display.set_caption(\"DeviOn\")\r\nicon = pygame.image.load('devion.JPG')\r\npygame.display.set_icon(icon)\r\n\r\n#background\r\nbackground = pygame.image.load('person3.png')\r\n\r\n#location information\r\nfont = pygame.font.Font('freesansbold.ttf',20)\r\ntextX=800-140\r\ntextY=10\r\n\r\n#person\r\npersonImg = pygame.image.load('person3.png')\r\npersonX = 360\r\npersonY = 250\r\n\r\n\r\n\r\n#door\r\ndoorImg = pygame.image.load('door.png')\r\ndoorX = 800-64\r\ndoorY = 250\r\nwarning4Img=pygame.image.load('warning.png')\r\nwarning4X = doorX + 32\r\nwarning4Y = doorY + 40\r\n\r\n#artwork1\r\nartwork1Img = pygame.image.load('artwork1.png')\r\nartwork1X = 64\r\nartwork1Y = 250\r\nwarning1Img=pygame.image.load('warning.png')\r\nwarning1X = artwork1X + 32\r\nwarning1Y = artwork1Y + 32\r\n#artwork2\r\nartwork2Img = pygame.image.load('artwork2.png')\r\nartwork2X = 350\r\nartwork2Y = 64\r\nwarning2Img=pygame.image.load('warning.png')\r\nwarning2X = artwork2X + 32\r\nwarning2Y = artwork2Y + 32\r\n\r\n#artwork3\r\nartwork3Img = pygame.image.load('artwork3.png')\r\nartwork3X = 350\r\nartwork3Y = 600 - 64\r\nwarning3Img=pygame.image.load('warning.png')\r\nwarning3X = artwork3X + 32\r\nwarning3Y = artwork3Y + 32\r\n\r\n#origin\r\noriginImg = pygame.image.load('origin.png')\r\noriginX = -16\r\noriginY = -16\r\n\r\ndef show_location(value_x,value_y,x,y):\r\n location = font.render(\"X: \" + str(value_x) + \" Y: \" + str(value_y), True, (255,255,255) )\r\n screen.blit(location,(x,y))\r\n\r\ndef person(x,y):\r\n screen.blit(personImg,(x,y))\r\ndef artwork1(x,y):\r\n screen.blit(artwork1Img,(x,y))\r\ndef artwork2(x,y):\r\n screen.blit(artwork2Img,(x,y))\r\ndef artwork3(x,y):\r\n screen.blit(artwork3Img,(x,y))\r\ndef door(x,y):\r\n screen.blit(doorImg,(x,y))\r\ndef warning1(x,y):\r\n screen.blit(warning1Img,(x,y))\r\ndef warning2(x,y):\r\n screen.blit(warning2Img,(x,y))\r\ndef warning3(x,y):\r\n screen.blit(warning3Img,(x,y))\r\ndef warning4(x,y):\r\n screen.blit(warning4Img,(x,y))\r\ndef origin(x,y):\r\n screen.blit(originImg,(x,y))\r\n\r\ndef distance(x1,x2,y1,y2):\r\n distance = sqrt((x1-x2)**2+(y1-y2)**2)\r\n return distance\r\n\r\n#Game loop\r\nwhile running:\r\n #screen color RGB \r\n screen.fill((0,0,0))\r\n #personX += 0.1 #to right +, to left -\r\n #personY +=0.1 #to down + , to up - \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: #close check\r\n running=False \r\n \r\n data = pd.read_csv('data.csv')\r\n personX_pd = data['x_value']\r\n personY_pd = data['total_1']\r\n #print(\"read values array\") #debug\r\n #print(personX_pd.values) #debug\r\n #print(personY_pd.values) #debug\r\n personX=personX_pd.values[len(personX_pd.values)-1]\r\n personY=personY_pd.values[len(personY_pd.values)-1]\r\n #print(\"last read\") #debug\r\n #print(personX) #debug\r\n #print(personY) #debug\r\n person(personX, personY)\r\n show_location(personX,personY,textX,textY)\r\n origin(originX,originY)\r\n artwork1(artwork1X,artwork1Y)\r\n artwork2(artwork2X,artwork2Y)\r\n artwork3(artwork3X,artwork3Y)\r\n door(doorX,doorY)\r\n distance1 = distance(personX,artwork1X,personY,artwork1Y)\r\n distance2 = distance(personX,artwork2X,personY,artwork2Y)\r\n distance3 = distance(personX,artwork3X,personY,artwork3Y)\r\n distance4 = distance(personX,doorX,personY,doorY) \r\n if distance1 < treshold:\r\n warning1(warning1X,warning1Y)\r\n if distance2 < treshold:\r\n warning2(warning2X,warning2Y)\r\n if distance3 < treshold:\r\n warning3(warning3X,warning3Y)\r\n if distance4 < treshold:\r\n warning4(warning4X,warning4Y)\r\n \r\n #time.sleep(1)\r\n pygame.display.update()" } ]
2
ShreyDixit/PyTorch-Deep-Steganography-Using-Fourier-Transform
https://github.com/ShreyDixit/PyTorch-Deep-Steganography-Using-Fourier-Transform
3555e5fed18d87bde744ecab01a56bd950358767
9328308cfdfb7eca6284e5e77cdcb32acc9225d4
2a8ea97dd0b3b760870a736c3c5152d56a5680f9
refs/heads/master
2023-02-05T23:17:41.845160
2020-12-20T19:49:15
2020-12-20T19:49:15
295,414,804
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6275418400764465, "alphanum_fraction": 0.637837827205658, "avg_line_length": 38.64285659790039, "blob_id": "c8adf1a27c6471f3db3a665c2cdea2389051b629", "content_id": "fb04b936bf09160b4fc63976a94860b76c3501d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3885, "license_type": "no_license", "max_line_length": 119, "num_lines": 98, "path": "/main.py", "repo_name": "ShreyDixit/PyTorch-Deep-Steganography-Using-Fourier-Transform", "src_encoding": "UTF-8", "text": "# encoding: utf-8\n\"\"\"\n@author: Shrey Dixit\n@contact: [email protected]\n@version: 1.0\n@file: main.py\n@time: 2020/09/14\n\"\"\"\n\nimport os\nimport torch\nimport argparse\nimport numpy\nfrom functools import partial\n\nfrom utils import *\nfrom model import StegNet\n\nfrom fastai.core import parallel\nfrom fastai.basic_data import DataBunch\nfrom fastai.basic_train import Learner\nfrom fastai.train import fit_one_cycle, lr_find\n\nparser = argparse.ArgumentParser()\n\ngroup1 = parser.add_mutually_exclusive_group()\ngroup1.add_argument('-use', action='store_true', help='Use for Inference')\ngroup1.add_argument('-train', action='store_true', help='Train a new model')\n\ngroup2 = parser.add_mutually_exclusive_group()\ngroup2.add_argument('-encode', action='store_true', help='Use encoder to encode secret image in cover image')\ngroup2.add_argument('-decode', action='store_true', help='Use decoder to decode secret image from cover image')\n\nparser.add_argument('--datapath', type=str, metavar='', default='data', help='Path to Dataset folder')\nparser.add_argument('--num_train', type=int, metavar='', default=50000, help='Number of training pairs to be created')\nparser.add_argument('--num_val', type=int, metavar='', default=1000, help='Number of validation pairs to be created')\nparser.add_argument('--size', type=int, metavar='', default=300, help='Size of the images')\nparser.add_argument('--bs', metavar='', default=64, help='Batch Size')\nparser.add_argument('--epochs', type=int, metavar='', default=10, help='Number of Epochs')\nparser.add_argument('--model', metavar='', default=None, help='Path for the model file if you want to finetune')\nparser.add_argument('--fourierSeed', metavar='', default=42, \n help='Seed for generating the pseudorandom matrix for changing phase in fourier domain')\n\nargs = parser.parse_args()\nargs.size = (args.size, args.size)\n\ndef main():\n model = StegNet(10, 6)\n print(\"Created Model\")\n \n if args.train:\n data_train = ImageLoader(args.datapath + '/train', args.num_train, args.fourierSeed, args.size, args.bs)\n data_val = ImageLoader(args.datapath + '/val', args.num_val, args.fourierSeed, args.size, args.bs)\n data = DataBunch(data_train, data_val)\n \n print(\"Loaded DataSets\")\n \n if args.model is not None:\n model.load_state_dict(torch.load(args.model))\n print(\"Loaded pretrained model\")\n \n loss_fn = mse\n \n learn = Learner(data, model, loss_func = loss_fn, metrics = [mse_cov, mse_hidden])\n \n print(\"training\")\n fit_one_cycle(learn, args.epochs, 1e-2)\n \n torch.save(learn.model.state_dict(), \"model.pth\")\n print(\"model saved\")\n\n else:\n path = input(\"Enter path of the model: \") if args.model is None else args.model\n model.load_state_dict(torch.load(args.model))\n model.eval()\n \n if args.encode:\n f_paths = [args.datapath + '/cover/'+ f for f in os.listdir(args.datapath + '/cover')]\n try: \n os.mkdir(args.datapath+'/encoded')\n except OSError:\n pass\n fourier_func = partial(encrypt, seed = args.fourierSeed)\n encode_partial = partial(encode, model=model.encoder, size=args.size, fourier_func=fourier_func)\n parallel(encode_partial, f_paths)\n \n else: \n f_paths = [args.datapath + '/encoded/'+ f for f in os.listdir(args.datapath + '/encoded')]\n try: \n os.mkdir(args.datapath+'/decoded')\n except OSError:\n pass\n fourier_func = partial(decrypt, seed = args.fourierSeed)\n decode_partial = partial(decode, model=model.decoder, size=args.size, fourier_func=fourier_func)\n parallel(decode_partial, f_paths)\n \nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5039606690406799, "alphanum_fraction": 0.5310024619102478, "avg_line_length": 42.192771911621094, "blob_id": "0a01f006406b518222af8ef05fae869850e0591b", "content_id": "cdb3ccfc007130a999662757b0d5c60600917257", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3661, "license_type": "no_license", "max_line_length": 120, "num_lines": 83, "path": "/utils.py", "repo_name": "ShreyDixit/PyTorch-Deep-Steganography-Using-Fourier-Transform", "src_encoding": "UTF-8", "text": "import numpy as np\nimport os\nimport torch\nimport cv2\nimport random\nfrom functools import partial\nfrom torch.utils.data import Dataset, DataLoader\nfrom itertools import combinations\nimport torchvision.transforms as transforms\n\ndef encrypt(img_channel, seed = 42):\n np.random.seed(seed)\n f = np.fft.fft2(img_channel)\n mag, ang = np.abs(f), np.arctan2(f.imag, f.real)\n ns = np.random.uniform(0, 6.28, size = f.shape)\n ns = np.fft.fft2(ns)\n ns = np.arctan2(ns.imag, ns.real)\n ang_new = ang+ns\n noise_img = np.fft.ifft2(mag*np.exp((ang_new)*1j)).real\n return noise_img\n\ndef decrypt(img_channel, seed = 42):\n np.random.seed(seed)\n f = np.fft.fft2(img_channel)\n mag, ang = np.abs(f), np.arctan2(f.imag, f.real)\n ns = np.random.uniform(0, 6.28, size = f.shape)\n ns = np.fft.fft2(ns)\n ns = np.arctan2(ns.imag, ns.real)\n ang_new = ang-ns\n noise_img = np.fft.ifft2(mag*np.exp((ang_new)*1j)).real\n return noise_img\n\ndef image_crypto(f_path, size, func):\n img = cv2.imread(f_path)[:, :, [2, 1, 0]]\n img = cv2.resize(img, size)\n return np.stack([func(img[..., i]) for i in range(3)], 2)\n\ndef encode(f_path, idx, model, size, fourier_func):\n path, fname = '/'.join(f_path.split('/')[:-2]), f_path.split('/')[-1]\n x = cv2.resize(cv2.imread(f_path)[:, :, [2, 1, 0]], size).transpose((2,0,1))\n y = image_crypto(path + '/secret/'+ fname, size, fourier_func).transpose((2,0,1))\n x, y = torch.tensor(x), torch.tensor(y)\n X = torch.cat((x.float(), y.float()), 0)\n out = model(X[None]).squeeze().permute(1, 2, 0)[:, :, [2, 1, 0]].detach().numpy()\n cv2.imwrite(path + '/encoded/' + fname, out)\n \ndef decode(f_path, idx, model, size, fourier_func):\n path, fname = f_path.split('/')[:-2].join('/'), f_path.split('/')[-1]\n x = cv2.resize(cv2.imread(f_path)[:, :, [2, 1, 0]], size).transpose((2,0,1))\n x = torch.tensor(x)\n out = model(x[None]).squeeze().permute(1, 2, 0)[:, :, [2, 1, 0]].detach().numpy()\n out = np.stack([fourier_func(out[..., i]) for i in range(3)], 2) \n cv2.imwrite(path + '/decoded/' + fname, out) \n \ndef mse(y_pred, y): \n return ((y_pred - y)**2).mean()\ndef mse_cov(y_pred, y): \n return ((y_pred[:, 0] - y[:, 0])**2).mean()\ndef mse_hidden(y_pred, y): \n return ((y_pred[:, 1] - y[:, 1])**2).mean() \n\nclass Image_Data(Dataset):\n def __init__(self, path, data_len, fourier_seed, size):\n self.path = path\n self.encrypt_partial = partial(encrypt, seed=fourier_seed)\n self.size = size\n f_paths = [path + '/'+ f for f in os.listdir(path)]\n self.file_pairs = list(zip(random.choices(f_paths, k=data_len), random.choices(f_paths, k=data_len)))\n\n def __len__(self):\n return len(self.file_pairs)\n\n def __getitem__(self, idx):\n file_pair= self.file_pairs[idx]\n x = cv2.imread(file_pair[0])[:, :, [2, 1, 0]]\n x = cv2.resize(x, self.size).transpose((2,0,1))\n y = image_crypto(file_pair[1], self.size, self.encrypt_partial).transpose((2,0,1))\n x, y = torch.tensor(x), torch.tensor(y)\n X = torch.stack((x.float(), y.float()))\n return X, X\n \ndef ImageLoader(path, data_len, fourierSeed = 42, size=300, bs=64):\n return DataLoader(Image_Data(path, data_len, fourierSeed, size), bs)\n " }, { "alpha_fraction": 0.5415330529212952, "alphanum_fraction": 0.5779656171798706, "avg_line_length": 38.895347595214844, "blob_id": "449135d5fdfaae228d4e06dedf4cc657e970d5ba", "content_id": "ca5986396bccce79bceedd229ba12c2e5eb3ab4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3431, "license_type": "no_license", "max_line_length": 123, "num_lines": 86, "path": "/model.py", "repo_name": "ShreyDixit/PyTorch-Deep-Steganography-Using-Fourier-Transform", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom functools import partial\nfrom collections import OrderedDict\nfrom fastai.vision.models import DynamicUnet\n\nclass ReLUModified(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, x):\n return x.clamp_min(0.)-0.5\n\nclass Conv2dAuto(nn.Conv2d):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.padding = (self.kernel_size[0] // 2, self.kernel_size[1] // 2) # dynamic add padding based on the kernel_size\n \nconv3x3 = partial(Conv2dAuto, kernel_size=3)\n\ndef conv_bn(in_channels, out_channels, conv, *args, **kwargs):\n return nn.Sequential(OrderedDict({'conv': conv(in_channels, out_channels, *args, **kwargs), \n 'bn': nn.BatchNorm2d(out_channels) }))\n\nclass ResNetBasicBlock(nn.Module):\n def __init__(self, in_channels, out_channels, conv=conv3x3, activation = ReLUModified, *args, **kwargs):\n super().__init__()\n self.conv, self.in_channels, self.out_channels = conv, in_channels, out_channels\n self.blocks = nn.Sequential(\n conv_bn(self.in_channels, self.out_channels, conv=self.conv),\n activation(),\n conv_bn(self.out_channels, self.out_channels, conv=self.conv),\n )\n self.shortcut = nn.Sequential(OrderedDict(\n {\n 'conv' : nn.Conv2d(self.in_channels, self.out_channels, kernel_size=1),\n 'bn' : nn.BatchNorm2d(self.out_channels)\n \n })) if self.should_apply_shortcut else None\n \n def forward(self, x):\n residual = x\n if self.should_apply_shortcut: residual = self.shortcut(x)\n x = self.blocks(x)\n x += residual\n return x\n \n @property\n def should_apply_shortcut(self):\n return self.in_channels != self.out_channels\n \nclass ResNetLayer(nn.Module):\n def __init__(self, in_channels, out_channels, block=ResNetBasicBlock, n=1, activation = ReLUModified):\n super().__init__()\n \n self.blocks = nn.Sequential(\n block(in_channels , out_channels, activation=activation),\n *[block(out_channels, out_channels, activation=activation) for _ in range(n - 1)]\n )\n\n def forward(self, x):\n x = self.blocks(x)\n return x\n \n\nclass StegNet(nn.Module):\n def __init__(self, encoder_layers=5, decoder_layers=5):\n super().__init__()\n self.mean = torch.tensor([[[[[120.0647]], [[113.9922]], [[103.8980]]],\n [[[119.9911]], [[113.9572]], [[103.9110]]]]])\n self.std = torch.tensor([[[[[70.2821]], [[69.1352]], [[72.8606]]],\n [[[70.2184]], [[69.1267]], [[72.9056]]]]])\n res = ResNetLayer(6, 32, n = encoder_layers)\n self.encoder = DynamicUnet(list(res.children())[0], 3, (128, 128))\n self.decoder = nn.Sequential(ResNetLayer(3, 32, n = decoder_layers), \n nn.Conv2d(32, 3, kernel_size=(1, 1), bias=False),)\n \n def forward(self, X):\n X = (X-self.mean)/self.std\n concat_images = torch.cat((X[:, 0], X[:, 1]), 1)\n embedded_image = self.encoder(concat_images)\n decoded_image = self.decoder(embedded_image)\n out = torch.stack((embedded_image, decoded_image), 1)\n out = (out * self.std) + self.mean\n return out\n" }, { "alpha_fraction": 0.8611111044883728, "alphanum_fraction": 0.8611111044883728, "avg_line_length": 8, "blob_id": "2e53316c5dac6cf98a54623050be69ed08f7b435", "content_id": "9667322e25fe1b3c339c8f70df4a297f81146a59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 36, "license_type": "no_license", "max_line_length": 13, "num_lines": 4, "path": "/requirements.txt", "repo_name": "ShreyDixit/PyTorch-Deep-Steganography-Using-Fourier-Transform", "src_encoding": "UTF-8", "text": "torch\nfastai\nargparse\nopencv-python\n" }, { "alpha_fraction": 0.6056616306304932, "alphanum_fraction": 0.6056616306304932, "avg_line_length": 28.230770111083984, "blob_id": "719178d067ce0e58a62e6495318fd1c21c97bdeb", "content_id": "f339e02c780de23da80d9c3f3356f40ab9da4765", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1519, "license_type": "no_license", "max_line_length": 76, "num_lines": 52, "path": "/README.md", "repo_name": "ShreyDixit/PyTorch-Deep-Steganography-Using-Fourier-Transform", "src_encoding": "UTF-8", "text": "# PyTorch-Deep-Steganography-Using-Fourier-Transform\n\n## Usage\n```\nmain.py [-h] [-use | -train] [-encode | -decode] [--datapath]\n [--num_train] [--num_val] [--size] [--bs] [--epochs] [--model]\n [--fourierSeed]\n```\n\n#### Optional Args\n```\n -h, --help show this help message and exit\n -use Use for Inference\n -train Train a new model\n -encode Use encoder to encode secret image in cover image\n -decode Use decoder to decode secret image from cover image\n --datapath Path to Dataset folder\n --num_train Number of training pairs to be created\n --num_val Number of validation pairs to be created\n --size Size of the images\n --bs Batch Size\n --epochs Number of Epochs\n --model Path for the model file if you want to finetune\n --fourierSeed Seed for generating the pseudorandom matrix for changing\n phase in fourier domain\n```\n### Tiny Deviations \n* deviation between cover and contianer \n <table align='center'>\n <tr align='center'>\n <td> cover image </td>\n <td> container image </td>\n </tr>\n <tr>\n <td><img src = 'results/cover.jpeg'>\n <td><img src = 'results/container.jpeg'>\n </tr>\n </table>\n\n\n\n* deviation between secret and revealed secret \n <table align='center'>\n <tr align='center'>\n <td> secret image </td>\n <td> revealed secret image </td>\n </tr>\n <tr>\n <td><img src = 'results/secret.png'>\n <td><img src = 'results/decoded.png'>\n </tr>\n </table>" } ]
5
rebel47/Weather-App
https://github.com/rebel47/Weather-App
c1a38f1aea3ed297aff421939e3a8f578129bf30
9bd25a4c43941f96df7774867275c44577c2ca50
a7319b73a6e011de3d78327e42c1ec50a32dcec4
refs/heads/master
2023-06-23T20:57:11.551305
2021-08-03T12:31:38
2021-08-03T12:31:38
391,943,472
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5990990996360779, "alphanum_fraction": 0.6238738894462585, "avg_line_length": 39.40909194946289, "blob_id": "27b16a1b1ce406ca6616ea6c4425be6c06e80fca", "content_id": "580ad53873bc598d3ce6c34e07cf3c876426cfc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 888, "license_type": "no_license", "max_line_length": 120, "num_lines": 22, "path": "/home/views.py", "repo_name": "rebel47/Weather-App", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport requests\n\ndef index(request):\n area = request.GET.get('area')\n area = str(area)\n baserUrl = 'https://api.weatherapi.com/v1/current.json?key=e7a6fabfe4ae403280593925210208&q={}&aqi=yes'.format(area)\n response = requests.get(baserUrl).json()\n\n city_weather = {\n 'City': response['location']['region'],\n 'Time': response['location']['localtime'],\n 'Celcius': response['current']['temp_c'],\n 'Fahrenheit': response['current']['temp_f'],\n 'Condition': response['current']['condition']['text'],\n 'Icon': response['current']['condition']['icon'],\n 'WindSpeed': response['current']['wind_mph'],\n 'WindDirection': response['current']['wind_dir'],\n 'Humidity': response['current']['humidity'],\n }\n \n return render(request, 'index.html', {'city_weather': city_weather})" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 15, "blob_id": "1ca97e4a8972d425180f6a161c07b7220fe4ca5a", "content_id": "bc5a6f9fc994a6242daeae1a8c6014aebed69aef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 80, "license_type": "no_license", "max_line_length": 42, "num_lines": 5, "path": "/README.md", "repo_name": "rebel47/Weather-App", "src_encoding": "UTF-8", "text": "# Weather-App\n\n## API used: 'https://www.weatherapi.com/'\n\n![Logo](Capture.JPG)\n" } ]
2
reekithak/Python-Workspace
https://github.com/reekithak/Python-Workspace
cbd0e7d0e56989455d1edf74c0f5d27f31f09ecc
360f70772b1069ff4557a1b49cbb7a4aee9b95e5
51a3c5da331dab8908eb93aa600a68c6a7c927ff
refs/heads/master
2023-03-13T18:47:33.621220
2021-03-02T18:55:22
2021-03-02T18:55:22
280,960,142
0
0
null
2020-07-19T22:16:24
2020-09-08T23:06:04
2020-09-08T23:07:39
Jupyter Notebook
[ { "alpha_fraction": 0.37140020728111267, "alphanum_fraction": 0.38695797324180603, "avg_line_length": 35.409637451171875, "blob_id": "827035b4ef0d7822e01d4761d7dd44ab1cb87bf2", "content_id": "3a5eabcb1f63db1148a7bb92c89087f099884aec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3021, "license_type": "no_license", "max_line_length": 80, "num_lines": 83, "path": "/pythondev/Adwaith Project - 12/book shop management/Source Code/Python files/Main.py", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "import Book \n\n\nc = 'y'\nwhile c.lower() == 'y':\n print(\"Book Shop Management\".center(89, '='))\n print('1. Register')\n print('2. Login')\n print('3. Exit')\n choice4 = int(input(\"Enter the serial number of your choice : \"))\n if choice4 == 1:\n Book.clrscreen()\n Book.add_user()\n elif choice4 == 2:\n Book.clrscreen()\n if Book.login():\n Book.clrscreen()\n C = 'y'\n while C.lower() == 'y':\n Book.clrscreen()\n print(\"Book Shop Management\".center(89, '='))\n print(\"1. Book Stock\")\n print(\"2. Book Selling\")\n print(\"3. Exit\")\n choice = int(input(\"Enter the serial number of your choice : \"))\n if choice == 1:\n Book.clrscreen()\n print(\"Book Book\".center(89, '='))\n print(\"1. Add a new Stock\")\n print(\"2. View all Stock\")\n print(\"3. Update an existing Stock\")\n print(\"4. Exit\")\n choice2 = int(input(\"Enter the choice : \"))\n if choice2 == 1:\n Book.clrscreen()\n Book.add_stock()\n elif choice2 == 2:\n Book.clrscreen()\n Book.view_stock()\n elif choice2 == 3:\n Book.clrscreen()\n Book.update_stock()\n elif choice2 == 4:\n print(\"Good Bye\")\n break\n else:\n print(\"INVALID CHOICE\")\n elif choice == 2:\n Book.clrscreen()\n print('Book Selling'.center(89, '='))\n print('1. Sell a book')\n print('2. View Sales this month')\n print(\"3. Exit\")\n choice3 = int(input(\"Enter your choice : \"))\n if choice3 == 1:\n Book.clrscreen()\n Book.sell_book() \n elif choice3 == 2:\n Book.clrscreen()\n Book.view_sales()\n elif choice3 == 3:\n print(\"Good Bye\")\n break\n else:\n print(\"INVALID CHOICE\")\n elif choice == 3:\n print(\"Good Bye\")\n break\n else:\n print(\"INVALID CHOICE\")\n C = input(\"Do you want to continue (y/[n]) : \")\n else:\n print(\"Good Bye\")\n else:\n print(\"Either your username or password is incorrect\") \n elif choice4 == 3:\n print(\"Good Bye\")\n break\n else:\n print(\"INVALID CHOICE\")\n c = input(\"Do you want to return to main menu (y/[n]) : \")\nelse:\n print(\"Good Bye\")" }, { "alpha_fraction": 0.6757164597511292, "alphanum_fraction": 0.6817496418952942, "avg_line_length": 33.894737243652344, "blob_id": "09cd9ceeaf19ce883f54337622d160208d269def", "content_id": "94da859a958e2d37c01f4f618002d566fe1a35ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1326, "license_type": "no_license", "max_line_length": 207, "num_lines": 38, "path": "/pythondev/Adwaith Project - 12/Actual source/6014 - Book Shop Management System/Book Shop Management/Readme.txt", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "Book Stall Management :-\n-------------------------------------\n\nPre-Requisites :-\n------------------------\n\n\t1. You have to have the following softwares for the successful running of this software; which are\n\n\t\tI) Python (Only for the First time), it is downloadable from 'www.python.org'.\n\t\n\t\tII) MySQL (Only for the First time), it is downloadable from 'www.mysql.org'.\n\n\nInstallation :-\n-------------------\n\t1. There will be two folders namely 'Python Files' and 'EXE files' in the folder 'Source Code'.\n\n\t2. The folder 'Python Files' will contain the source code of the software in python language. If you are running the software by the 3rd step mentioned below you have to pre install the following modules :-\n\t\t\n\t\tI) mysql.connector or pymysql\n\n\t\tII) matplotlib.\n\t\n\t3. Open the files in any python editors and run it to start and work on the software.\n\n\t4. The folder 'EXE files' will contain two files namely 'main.exe' and 'Tables_in_mysql.exe'.\n\n\t5. First run the 'Tables_in_mysql.exe' to create the tables in MySQL.\n\n\t6. Then run the file 'main.exe' to start and work on the software.\n\n\nCAUTION :-\n========= \n\t\n\tIf you are running the software through running the python files or by running the .exe files ; first run the file named 'Tables_in_mysql'.\n\t \n\tThe .exe file will take some time to run; so be PATIENT.\n" }, { "alpha_fraction": 0.516566276550293, "alphanum_fraction": 0.516566276550293, "avg_line_length": 24.576923370361328, "blob_id": "495e826c4ab517f0db97982403dae5c9a96aec20", "content_id": "e6b528c99dc0ffe18670aba4321c219dcc17b684", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 82, "num_lines": 26, "path": "/Omdena/cleantext.py", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "import re\ndef clean_text(\nstring:str ,\npunctuations=r'''!()-[]{};:'\"\\,<>./?@#$%^&*_~''',\nstop_words = ['the','a','and','be','is','be','will']) -> str:\n #URLS\n string = re.sub(r'https?://\\S+|www\\.\\S+', '', string)\n \n #HTML\n string = re.sub(r'<.*?>', '', string)\n \n #Punctuations\n for x in string.lower():\n if x in punctuations:\n string = string.replace(x,\"\")\n \n #TO lower convertion\n string = string.lower()\n \n #Removing stop words\n string = ' '.join([word for word in string.split() if word not in stop_words])\n \n #whitespaces\n string = re.sub(r'\\s+', ' ', string).strip()\n \n return string" }, { "alpha_fraction": 0.5991379022598267, "alphanum_fraction": 0.5991379022598267, "avg_line_length": 21.399999618530273, "blob_id": "ca10d682c271b29c16029135ebeedc6bff273d5e", "content_id": "db2c487ebfdfa0ab016d3da2eef6e348587d2591", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 51, "num_lines": 10, "path": "/pythondev/Codes-1/main.py", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "def my_print(txt):\r\n print(txt)\r\n\r\nmsg = \"\"\" hey {name} , {website}\"\"\"\r\n\r\ndef format_msg(name='akhil',website='ak.sh'):\r\n global msg\r\n msg_new = msg.format(name=name,website=website)\r\n #print(msg_new)\r\n return msg_new" }, { "alpha_fraction": 0.6899441480636597, "alphanum_fraction": 0.7076349854469299, "avg_line_length": 41.959999084472656, "blob_id": "d31d843e150193e57cc547ee6c02a0ee99d748c6", "content_id": "15ee6085fc97e8b27b64f1139600b0a29b76748b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1074, "license_type": "no_license", "max_line_length": 134, "num_lines": 25, "path": "/pythondev/Adwaith Project - 12/Actual source/6014 - Book Shop Management System/Book Shop Management/Source Code/Python files/Tables_in_mysql.py", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "try : import pymysql as cntr\nexcept ImportError : import mysql.connector as cntr\ndb = cntr.connect(host = 'localhost' , user = 'root' , passwd = 'manager')\nif str(cntr) == \"<module 'pymysql' from 'C:\\\\\\\\Program Files (x86)\\\\\\\\Python37\\\\\\\\lib\\\\\\\\site-packages\\\\\\\\pymysql\\\\\\\\__init__.py'>\" : \n db.autocommit = True\nelse : db.autocommit(True)\ncur = db.cursor()\ncur.execute(\"create database if not exists book_shop\")\ncur.execute(\"use book_shop\")\ncur.execute(\"create table stock\\\n (Book_No bigint primary key,\\\nBook_Name varchar(255),\\\nAuthor varchar(255),\\\nPublisher varchar(255),\\\nCost_per_Book float,\\\nAvailable_Stock bigint,\\\nqty_purchased bigint,\\\npurchased_on date)\")\ncur.execute(\"create table users(username varchar(255) , password varchar(255))\")\ncur.execute(\"create table purchased (Book_no bigint , purchased_on date , foreign key(Book_no) references stock(Book_No))\")\ncur.execute(\"create unique index Book_Index on stock(Book_No)\")\nprint(\"Database and Tables created successfully\")\nc = input(\"Press any key to continue-----> \")\ncur.close()\ndb.close()\n" }, { "alpha_fraction": 0.5609208345413208, "alphanum_fraction": 0.576080858707428, "avg_line_length": 38.20588302612305, "blob_id": "f767780cdf39a0ca901ab555eff0c52a1b8904c7", "content_id": "003f000d765c86f2fb9cc8326d410171d14ac82e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5343, "license_type": "no_license", "max_line_length": 339, "num_lines": 136, "path": "/pythondev/Adwaith Project - 12/book shop management/Source Code/Python files/Book.py", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "try : \n import pymysql as cntr\nexcept ImportError : \n import mysql.connector as cntr\nimport datetime as __dt , matplotlib.pyplot as plt\nfrom random import shuffle\nfrom tempfile import mktemp\nfrom os import system , startfile\n\n__db = cntr.connect(host = 'localhost' , user = 'root' , passwd = 'uninstall0987' , database = 'book_shop')\n__cur = __db.cursor()\nif str(cntr) == \"<module 'pymysql' from 'C:\\Program Files (x86)\\Python37\\lib\\site-packages\\pymysql\\__init__.py'>\" :\n __db.autocommit = True\nelse : \n __db.autocommit\n\n\n#Function to check is it leap year\nis_leapyear = lambda year : year % 4 == 0\n\n\n#Function to get last date of month\ndef last_month(month , year):\n if month in (1,3,5,7,8,10,12) : return 31\n elif month == 2 and is_leapyear(year) : return 29\n elif month == 2 : return 28\n else : return 30\n \n\nclrscreen = lambda : system(\"cls\")\n\n\ndef view_stock() :\n __cur.execute(\"select Book_No , Book_Name , Available_Stock from stock\")\n data = __cur.fetchall()\n print(\"Book Number Book Name Stock\")\n for row in data :\n if len(row[1]) >= 11 : print(row[0] , ' ' , row[1] , ' ' , row[2])\n else : print(row[0] , ' ' , row[1] , ' ' , row[2])\n\n \ndef add_stock() : \n print('Add Stock'.center(89 , '='))\n bno = unique_book_no()\n if bno:\n print(\"Book Number : \" , bno)\n else:\n bno = int(input(\"Enter book number : \"))\n bname = input(\"Enter the Book\\'s Name : \")\n auth = input(\"Enter the Author of the Book : \")\n publ = input(\"Enter the Publisher of the Book : \")\n cost = eval(input(\"Enter the Cost per Book : \"))\n stock = int(input(\"Enter the Quantity purchased : \"))\n __cur.execute(\"insert into stock values ({} , '{}' , '{}' , '{}' , {} , {} , {} , '{}')\".format(bno , bname , auth , publ , cost , stock , 0, __dt.date.today()))\n print(\"Inserted Sucessfully !!!\")\n \n\n \ndef add_user() :\n user = input(\"Enter the user name : \")\n passwd = input(\"Enter a Password : \")\n passwd2 = input(\"Enter Password to confirm : \")\n if passwd == passwd2 :\n __cur.execute(\"insert into users values('{}' , '{}')\".format(user , passwd))\n print(\"Created Successfully!!!\")\n elif passwd != passwd2 : print(\"You've entered different passwords\")\n \n\n \ndef sell_book() :\n print('Purchase')\n cname = input(\"Enter the Customer Name : \")\n phno = int(input(\"Enter the phone number : \"))\n bno = int(input(\"Enter book number : \"))\n bname = input(\"Enter the name of the book : \")\n cost = eval(input(\"Enter the cost of the book : \"))\n __cur.execute(\"insert into purchased values({} , '{}')\".format(bno , __dt.date.today()))\n __cur.execute(\"update stock set qty_purchased = qty_purchased + 1 where Book_No = {}\".format(bno))\n __cur.execute(\"update stock set Available_Stock = Available_Stock - 1 where Book_No = {}\".format(bno))\n print(\"Bought Successfully\")\n q = '''Book Shop\\nName : {}\\nPhone No : {}\\nBook Number : {}\\nBook Name : {}\\nCost : {}\\nDate Of Purchase : {}'''.format(cname , phno , bno , bname , cost , __dt.date.today())\n filename = mktemp('.txt')\n open(filename , 'w').write(q)\n startfile(filename , 'print')\n __cur.execute('select Book_Name , Book_No , Author from stock where Available_Stock = 0')\n if __cur.rowcount == 1 :\n print(\"STOCK OF \")\n print(\"Book Name : \" , __cur.fetchall()[0][0])\n print(\"Book Number : \" , __cur.fetchall()[0][1])\n print(\"Author : \" , __cur.fetchall()[0][2])\n print(\"EXHAUSTED\")\n __cur.execute('delete from stock where Available_Stock = 0')\n \n \n \ndef unique_book_no () :\n __cur.execute(\"select MAX(Book_No) from stock\")\n data = __cur.fetchall()\n if bool(data[0][0]) :\n L1 = [x for x in range((data[0][0] + 1) , (data[0][0] + 10000))]\n shuffle(L1)\n return L1.pop(0)\n else : return False\n\n\ndef view_sales () :\n print('Overall Sales This Month') \n __cur.execute(\"select distinct(s.Book_Name) , s.qty_purchased from stock s , purchased p where s.Book_No = p.Book_No and p.purchased_on between '{year}-{month}-01' and '{year}-{month}-{date}'\".format(year = __dt.date.today().year , month = __dt.date.today().month , date = last_month(__dt.date.today().month , __dt.date.today().year)))\n data = __cur.fetchall()\n L1 , L2 = [] , []\n for row in data :\n L1.append(row[0])\n L2.append(row[1])\n plt.bar(L1 , L2)\n plt.xlabel('Books')\n plt.ylabel('Sales')\n plt.title('Sales')\n plt.show() \n\n \ndef login():\n user = input(\"Enter the username : \")\n pwd = input(\"Enter the password : \")\n __cur.execute(\"select * from users where username = '{}' and password = '{}'\".format(user , pwd))\n return bool(__cur.rowcount)\n\n\ndef update_stock() :\n bno = int(input(\"Enter the book number : \"))\n __cur.execute(\"select Book_Name , Available_Stock from stock where Book_No = {}\".format(bno))\n data = __cur.fetchall()\n print(\"Book Name : \" , data[0][0])\n print(\"Available Stock : \" , data[0][1])\n stock = int(input(\"Enter the new stock purchased : \"))\n __cur.execute(\"update stock set Available_Stock = Available_Stock + {}\".format(stock))\n print(\"Updated Successfully\")\n\n \n \n" }, { "alpha_fraction": 0.5802838206291199, "alphanum_fraction": 0.5914861559867859, "avg_line_length": 28.09782600402832, "blob_id": "7aa340c0cdd5980c28400c9573414a17a035460d", "content_id": "53e4d9a5f3fc42b98d3638650c85f8bed4672d21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2678, "license_type": "no_license", "max_line_length": 138, "num_lines": 92, "path": "/Web scraping/Image scrapping selenium/scraper.py", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "\n\nfrom selenium import webdriver\nimport os\nimport urllib.request\nimport time\n\n\n\npath = r'D:\\working repos\\Python-Workspace\\Web scraping\\Image scrapping selenium\\webdriver\\chromedriver.exe'\n\nurl_prefix = \"https://www.google.com.sg/search?q=\"\nurl_postfix = \"&source=lnms&tbm=isch&sa=X&ei=0eZEVbj3IJG5uATalICQAQ&ved=0CAcQ_AUoAQ&biw=939&bih=591\"\n\nsave_folder = r'D:\\working repos\\Python-Workspace\\Web scraping\\Image scrapping selenium\\Images'\n\n\n\n\n\n'''topics = ['Cleaning products','dish-washing powder','detergents','Cigarettes','Alcohol','Coffee packet','sugar packet','takeaway meals'\n ,'pet food packet','Fruit and vegetables','Regular medicines',\n 'Computers',\n'Mobile phones',\n'Entertainment equipment',\n'Cameras',\n'Household furniture',\n'Washing machines','dishwashers',\n'Clothing',\n'Sports equipment',\n'plates', 'pots' , 'pans',\n'Luggage',\n'Perfumes' ,'cosmetics',\n'Running shoes',\n'Everyday jewelry',\n'House repairs tools', 'paint']'''\ntopics = [\n'Puzzle toys' ,'assembly toys',\n'Science toys',\n'optical toys',\n'Sound toys',\n'Spinning toys',\n'Wooden toys']\nnumber = [50,40,30]\n\n\n\n\nimport random\n\n\n\nfor topic in topics:\n save_folder = r'D:\\working repos\\Python-Workspace\\Web scraping\\Image scrapping selenium\\Images'\n save_folder = save_folder + str(\"\\{}\".format(topic))\n if not os.path.exists(save_folder):\n os.mkdir(save_folder)\n print(topic,\" On going\")\n n_images = random.choice(number)\n print(\"Total number = \",n_images)\n search_url = url_prefix+topic+url_postfix\n path = r'D:\\working repos\\Python-Workspace\\Web scraping\\Image scrapping selenium\\webdriver\\chromedriver.exe'\n driver = webdriver.Chrome(path)\n driver.get(search_url)\n value = 0\n for i in range(3):\n driver.execute_script(\"scrollBy(\"+ str(value) +\",+1000);\")\n value += 1000\n time.sleep(1)\n elem1 = driver.find_element_by_id('islmp')\n sub = elem1.find_elements_by_tag_name('img')\n \n \n count=0\n for j,i in enumerate(sub):\n if j < n_images:\n src = i.get_attribute('src') \n try:\n if src != None:\n src = str(src)\n #print(src)\n\n urllib.request.urlretrieve(src, os.path.join(save_folder, topic+str(j)+'.jpg'))\n\n else:\n raise TypeError\n except Exception as e: \n print(f'fail with error {e}')\n print(topic,\" done\")\n print(\"***************************************************\")\n print(\"***************************************************\")\n print(\"***************************************************\")\n\n driver.close()" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 7, "blob_id": "ac599ca84cf57ceba1b3f2fd46b118bf33b15a72", "content_id": "a4014a11df62b1fb738a3645ff4a6558567b2698", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9, "license_type": "no_license", "max_line_length": 7, "num_lines": 1, "path": "/..Trial/readme.md", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "Task4>> \n" }, { "alpha_fraction": 0.7341549396514893, "alphanum_fraction": 0.7482394576072693, "avg_line_length": 28.947368621826172, "blob_id": "30d5fdf2dfeb6a92a4843d4da7de186996786616", "content_id": "ca0a22f9c7484958c7a12b8dc5dc1f9bba5b7f49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 568, "license_type": "no_license", "max_line_length": 140, "num_lines": 19, "path": "/Firebase/Pdf-Firebase-Pull(Py)/fetch.py", "repo_name": "reekithak/Python-Workspace", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom firebase import Firebase \nfrom pyrebase import pyrebase\nimport webbrowser\n\n\nconfig = {\n \"apiKey\": \"yourapikey\",\n \"authDomain\": \"try-python-pull.firebaseapp.com\",\n \"databaseURL\": \"https://try-python-pull.firebaseio.com\",\n \"storageBucket\": \"try-python-pull.appspot.com\"\n}\n\nfirebase = pyrebase.initialize_app(config)\n\nstorage = firebase.storage()\n\nstorage.child(\"applsci-10-01245-v2.pdf\").download(filename =\"new_pdf.pdf\",path=\"D:/working repos/Machine_Learing_PDF/Pdf-Firebase-Pull(Py)\")\nwebbrowser.open_new(\"new_pdf.pdf\")" } ]
9
s-mahler/python-intro
https://github.com/s-mahler/python-intro
83f8ef49449a51bf4fd8859d411a978943f8865b
ebd7666094426e097bf76b2bf8a1282863447feb
10f45358062602ffc37ad296bf2e95b903510106
refs/heads/main
2023-01-24T07:54:21.465704
2020-12-02T19:51:14
2020-12-02T19:51:14
317,967,687
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6462264060974121, "alphanum_fraction": 0.6650943160057068, "avg_line_length": 22.66666603088379, "blob_id": "17795283ccbe4a27cd7a8cea459f3025a89b5b30", "content_id": "e2c795c68c38269b6f9a7ae68ddd34e4e740a118", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 212, "license_type": "no_license", "max_line_length": 33, "num_lines": 9, "path": "/string_reverse.py", "repo_name": "s-mahler/python-intro", "src_encoding": "UTF-8", "text": "def reverse_string(string):\n print(string [::-1])\n\ndef reverse_string_slice(string):\n x = slice(len(string), 0, -1)\n print(string[x] + string[0])\n\nreverse_string('yellow')\nreverse_string_slice('holding')" }, { "alpha_fraction": 0.5895522236824036, "alphanum_fraction": 0.6194030046463013, "avg_line_length": 15.625, "blob_id": "0984d235c109802f193dd835873786f82776816a", "content_id": "6368ab5551492a5ae51ebc1da3b1e4cafe115f9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "no_license", "max_line_length": 26, "num_lines": 8, "path": "/scripts.py", "repo_name": "s-mahler/python-intro", "src_encoding": "UTF-8", "text": "def hello_name(name):\n print('Hello ' + name)\n\ndef add(num1, num2):\n print(num1 + num2)\n\nhello_name('Sam')\nhello_name('Steve')\n\n" }, { "alpha_fraction": 0.4767080843448639, "alphanum_fraction": 0.5124223828315735, "avg_line_length": 21.20689582824707, "blob_id": "9d66181ea4cdbe1aee8c9563fd4d37b9231af822", "content_id": "6dde80ffeb24a5b97128464be88ce4eb62616e7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 644, "license_type": "no_license", "max_line_length": 40, "num_lines": 29, "path": "/repeater.py", "repo_name": "s-mahler/python-intro", "src_encoding": "UTF-8", "text": "def repeater(string):\n for x in range(0, len(string) - 1):\n if string[x] == string[x + 1]:\n print(string[x + 1], x + 1)\n break\n else: \n print('no repeating characters')\n\nrepeater('test')\nrepeater('congee')\nrepeater('little')\nrepeater('mississippi')\n\ndef number_repeater(array):\n count = 0\n most = 0\n for x in range(0, len(array) - 1):\n if array[x] == 1:\n count += 1\n if count > most:\n most = count\n elif array[x] == 0:\n count = 0\n else:\n print(most)\n\ntest = [0,1,1,1,1,0,1]\nnumber_repeater(test)\nnumber_repeater([1,1,0])\n" }, { "alpha_fraction": 0.8518518805503845, "alphanum_fraction": 0.8518518805503845, "avg_line_length": 27, "blob_id": "a53323036561f75c9a24b6c3d9967a3097c00486", "content_id": "e7e359f7ffc43fe40f9ab5c03ea5f8d041b15148", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/README.md", "repo_name": "s-mahler/python-intro", "src_encoding": "UTF-8", "text": "First time coding in python" } ]
4
asafer/escape-from-class
https://github.com/asafer/escape-from-class
8cbb835905fac15dc47f7607ccc105cb2524d5d9
774760851cd76a97bbb855d482f6e476df672d53
4de94e47ffdbee15dba9de2f9eb79ce61af946ad
refs/heads/master
2021-01-10T13:57:59.946499
2015-11-12T22:21:30
2015-11-12T22:21:30
43,095,419
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6264289617538452, "alphanum_fraction": 0.6332105994224548, "avg_line_length": 38.09848403930664, "blob_id": "a89b12c780f83ba2b94a1a1dc7e6a97ddf6fe1f7", "content_id": "4c44a86d3f204b9db15ace15451786c646c5f169", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5161, "license_type": "no_license", "max_line_length": 149, "num_lines": 132, "path": "/escape.py", "repo_name": "asafer/escape-from-class", "src_encoding": "UTF-8", "text": "import os\nfrom inventory import *\n\n# When you reach the end of your path - these are in a specific order on purpose\nendgames = {\"default\": \"You gave up.\", \\\n\"error\": \"You have managed to find a path that ends nowhere. Good luck with that.\", \\\n\"draw\": \"You draw a masterpiece which is bought for five million dollars. You decide to quit college and live off of that. Congratulations!\", \\\n\"smart\": \"You participate so much that the professor remembers your name for the rest of the semester. You still only get an A-.\", \\\n\"outside\": \"You have successfully escaped from class! Good luck passing without any notes.\"}\n\n# when we want to tell the player something. Max one per state right now.\ntexts = {\"sitting\": \"Maybe you should do something.\", \\\n\t\t\"looking\": \"You see a person hanging out by the door. They look like they might talk to you if you give them some information.\", \\\n\t\t\"LEVEL TWO\": \"The person seems pleased with the gossip. They point out a cool looking tunnel you could explore. And they give you a flashlight.\", \\\n\t\t\"in tunnel\": \"You are in the tunnel. Suddenly, the entrance shuts behind you. Good thing you have a flashlight!\"}\n\n# now we can store things yay!\nitory = None\n\ndef get_valid_int(start, end, text):\n\tchoice = -1\n\ttry:\n\t\tchoice = int(input(text))\n\texcept ValueError:\n\t\tchoice = -1\n\telse:\n\t\tif choice < start or choice >= end:\n\t\t\tchoice = -1\n\twhile (choice == -1):\n\t\tprint(\"That was not an option!\")\n\t\ttry:\n\t\t\tchoice = int(input(text))\n\t\texcept ValueError:\n\t\t\tchoice = -1\n\t\telse:\n\t\t\tif choice < start or choice >= end:\n\t\t\t\tchoice = -1\n\treturn choice\n\ndef escape():\n\tglobal itory\n\tos.system(\"clear\")\n\titory = Inventory()\n\tprint(\"You are in class for an hour and a half. Good luck.\")\n\tstate = [\"sitting\", \"default\"]\n\tquit = 0\n\twhile (not quit):\n\t\tprint()\n\t\tif state[0] in texts:\n\t\t\tprint(texts[state[0]])\n\t\tprint(\"Your current state is:\", state[0])\n\t\tprint(\"What would you like to do next?\")\n\t\toptions = get_options(state[0])\n\t\ti = 0\n\t\tfor option in options:\n\t\t\ti += 1\n\t\t\tprint(str(i) + \": \" + option)\n\t\tchoice = get_valid_int(1, len(options)+1, \"Type the number of your choice: \")\n\t\tstate = do_option(options[choice-1], state[0])\n\t\tif state[0] == \"quit\":\n\t\t\tquit = 1\n\t\t\tprint(endgames[state[1]])\n\n\n# method takes a string parameter state and returns a list of string options\ndef get_options(state):\n\tstates = {\"sitting\": [\"listen\", \"gossip\", \"stand\", \"doodle\"], \\\n\t\"listening\": [\"participate\", \"stop listening\"], \\\n\t\"talking\": [\"stop talking\", \"keep talking\"], \\\n\t\"standing\": [\"sit\", \"leave class\"], \\\n\t\"drawing\": [\"stop drawing\", \"make masterpiece\"], \\\n\t\"participating\": [\"stop participating\", \"keep participating!\"], \\\n\t\"outside\": [\"go back in\", \"look around\"], \\\n\t\"looking\": [\"talk to person\", \"go back in\"], \\\n\t\"LEVEL TWO\": [\"enter tunnel\"], \\\n\t\"in tunnel\": [\"explore tunnel\", \"try to escape from tunnel\"], \\\n\t\"exploring\": [], \\\n\t\"trying to escape\": []} # add story here!!\n\n\toptions = [\"quit\", \"check inventory\"]\n\tif state in states:\n\t\toptions += states[state]\n\treturn options\n\n# method takes two string parameters option and state and returns a string state and an exit code\n# the program will only run the exit code if the state is \"quit\"\n# thinking about making inventory additions into a class for easier program reading\ndef do_option(option, state):\n\tglobal itory\n\tif option == \"quit\":\n\t\treturn [\"quit\", \"default\"]\n\telif option == \"check inventory\":\n\t\tprint(itory)\n\t\treturn [state, \"default\"]\n\telse:\n\t\tstates = {\"sitting\": {\"listen\": [\"listening\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"gossip\": [\"talking\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"stand\": [\"standing\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"doodle\": [\"drawing\", \"default\"]}, \\\n\t\t\t\t\t\"talking\": {\"stop talking\": [\"sitting\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"keep talking\": [\"talking\", \"default\", [(0, \"valuable gossip\", 1)]]}, \\\n\t\t\t\t\t\"listening\": {\"stop listening\": [\"sitting\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"participate\": [\"participating\", \"default\"]}, \\\n\t\t\t\t\t\"standing\": {\"sit\": [\"sitting\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"leave class\": [\"outside\", \"default\"]}, \\\n\t\t\t\t\t\"participating\": {\"stop participating\": [\"sitting\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"keep participating!\": [\"quit\", \"smart\"]}, \\\n\t\t\t\t\t\"drawing\": {\"stop drawing\": [\"sitting\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"make masterpiece\": [\"quit\", \"draw\"]}, \\\n\t\t\t\t\t\"outside\": {\"go back in\": [\"standing\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"look around\": [\"looking\", \"default\"]}, \\\n\t\t\t\t\t\"looking\": {\"go back in\": [\"standing\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"talk to person\": [\"LEVEL TWO\", \"default\", [(1, \"valuable gossip\"), (0, \"flashlight\", 1)]]}, \\\n\t\t\t\t\t\"LEVEL TWO\": {\"enter tunnel\": [\"in tunnel\", \"default\"]}, \\\n\t\t\t\t\t\"in tunnel\": {\"explore tunnel\": [\"exploring\", \"default\"], \\\n\t\t\t\t\t\t\t\t\"try to escape from tunnel\": [\"trying to escape\", \"default\"]}}\n\t\tif state in states and option in states[state]:\n\t\t\tvalue = states[state][option]\n\t\t\tif len(value) == 2: # don't do anything with inventory\n\t\t\t\treturn value\n\t\t\telse: # do something with inventory (list of tuples)\n\t\t\t\tfor tup in value[2]:\n\t\t\t\t\tif tup[0] == 0: # add\n\t\t\t\t\t\titory.add(tup[1], tup[2])\n\t\t\t\t\telif tup[0] == 1: # use\n\t\t\t\t\t\tsuccess = itory.use(tup[1])\n\t\t\t\t\t\tif not success:\n\t\t\t\t\t\t\treturn [state, \"default\"]\n\t\t\t\treturn value[:2]\n\treturn [\"quit\", \"error\"]\n\nescape()\n" }, { "alpha_fraction": 0.5973201990127563, "alphanum_fraction": 0.607898473739624, "avg_line_length": 25.240739822387695, "blob_id": "f0bb46a18313ad51f097b3b07e6fa2e24d173cc1", "content_id": "ee21181b8f90f162079e1263ddd4e9339b1c2a07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1418, "license_type": "no_license", "max_line_length": 67, "num_lines": 54, "path": "/inventory.py", "repo_name": "asafer/escape-from-class", "src_encoding": "UTF-8", "text": "class Inventory:\n\n\t# organization: dictionary where keys = item names\n\t# each key has a list of length two [max, current]\n\t# contains max number of items permitted and\n\t# how many items we currently have\n\n\tdef __init__(self):\n\t\tself.items = {}\n\n\tdef __str__(self):\n\t\tif self.is_empty():\n\t\t\treturn \"\\nYour inventory is empty!\"\n\t\ts = \"\\nInventory contents:\\n\" # fix later\n\t\tfor item in self.items:\n\t\t\tif self.items[item][1] > 0:\n\t\t\t\ts += item\n\t\t\t\ts += \" x\" + str(self.items[item][1])\n\t\treturn s\n\n\tdef add(self, name, max_num):\n\t\tprint()\n\t\tif name in self.items:\n\t\t\tif self.items[name][0] == self.items[name][1]:\n\t\t\t\tprint(\"You can't add any more \" + name + \" to your inventory!\")\n\t\t\telse:\n\t\t\t\tself.items[name][1] += 1\n\t\t\t\tprint(\"You have added \" + name + \" to your inventory!\")\n\t\telse:\n\t\t\tself.items[name] = [max_num, 1]\n\t\t\tprint(\"You have added \" + name + \" to your inventory!\")\n\n\tdef use(self, name):\n\t\tprint()\n\t\tif name in self.items and self.items[name][1] > 0:\n\t\t\tself.items[name][1] -= 1\n\t\t\tprint(\"You have used the item \\\"\" + name + \"\\\"!\")\n\t\t\treturn True\n\t\telse:\n\t\t\tprint(\"You don't have the item \\\"\" + name + \"\\\"!\")\n\t\t\treturn False\n\n\tdef update_max(self, name, max_num):\n\t\tprint()\n\t\tif name in self.items:\n\t\t\tself.items[name][0] = max_num\n\t\telse:\n\t\t\tprint(\"You don't have the item \\\"\" + name + \"\\\"!\")\n\n\tdef is_empty(self):\n\t\tfor item in self.items:\n\t\t\tif self.items[item][1] > 0:\n\t\t\t\treturn False\n\t\treturn True\n\n" }, { "alpha_fraction": 0.7214611768722534, "alphanum_fraction": 0.7305936217308044, "avg_line_length": 30.285715103149414, "blob_id": "c85d9cf259445562ed63fb5ba1fdf31d0de95da2", "content_id": "3d25b59f02a73e3207ad6c4d32cb741f367ea259", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 219, "license_type": "no_license", "max_line_length": 78, "num_lines": 7, "path": "/README.md", "repo_name": "asafer/escape-from-class", "src_encoding": "UTF-8", "text": "# escape-from-class\nRun this command line Python program to try to survive through a boring class!\n\nTo run: Download the file. In a linux/unix command line, type:\n `python3 escape.py`\n \n(You will need Python 3.x)\n" } ]
3
gaofrank1986/dutwav
https://github.com/gaofrank1986/dutwav
6341593f798fd76fb7bae047d6ce8409c3275586
3c61549006b99e7d863173483aac80f91fe1dd37
4727ec9bb9ea2a3f737f35d4c84fc2e7a02e9a28
refs/heads/master
2020-04-06T06:57:07.598935
2018-08-12T11:30:19
2018-08-12T11:30:19
51,981,640
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5332522392272949, "alphanum_fraction": 0.5652878880500793, "avg_line_length": 28.698795318603516, "blob_id": "d7d46bc525325f055e44c8bb611b5dc7fc782c9b", "content_id": "d84246f0fe0ef26ccbe1064c8d3c5c304e31e95b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2466, "license_type": "no_license", "max_line_length": 75, "num_lines": 83, "path": "/dutwav/postprocess.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "# @func: generate r1,r2,r3\n# @param: [path] = file path\n# @desrcipt: read r1,r2 from each line of file, calc r3, return (r1,r2,r3)\ndef parse_result(path):\n with open(path,\"rb\") as f:\n r = f.readlines()\n r1={}\n r2={}\n r3={}\n for i in range(len(r)):\n tmp=[float(j) for j in r[i].split()]\n r1[i+1]=tmp[1]\n r2[i+1]=tmp[2]\n r3[i+1]=tmp[2]-tmp[1]\n return (r1,r2,r3) \n\ndef display_value(fi,fo,mesh):\n import dutwav.mesh\n assert(isinstance(mesh,dutwav.mesh.Mesh))\n with open(fi,\"rb\") as f:\n r = f.readlines()\n r1={}\n for i in range(len(r)):\n tmp=[float(j) for j in r[i].split()]\n #tmp[0] is node id\n r1[i+1]=tmp[1]\n # print len(r1),len(mesh.nodes)\n mesh.tecplt_value(fo,[r1],1,kind=2) \n\n\n# @param path : file path\n# @param mesh : mesh object\n# @param ubound : upper bounder of time counting from time 000\n# @param prefix : \ndef create_animation(mesh,prefix,postfix='.out',loc=\"./\",kind=1):\n import dutwav.mesh\n from os.path import isfile,isdir\n from os import mkdir,rename\n from shutil import rmtree\n assert(isinstance(mesh,dutwav.mesh.Mesh))\n fd=loc+prefix+'_anim'\n fd2=loc+prefix\n if(not(isdir(fd))):\n mkdir(fd)\n else:\n rmtree(fd)\n mkdir(fd)\n if(not(isdir(fd2))): \n mkdir(fd2)\n\n i=0\n while(True):\n if(kind==1):\n infile=loc+prefix+'.'+'{0:0>7d}'.format(i)+postfix\n mov_dest=loc+prefix+'/'+prefix+'.'+'{0:0>7d}'.format(i)+postfix\n else:\n infile=loc+prefix+'/'+prefix+'.'+'{0:0>7d}'.format(i)+postfix\n\n if(not(isfile(infile))):\n break\n \n print(infile)\n outfile=fd+'/'+prefix+'.'+'{0:0>7d}'.format(i)+'.dat'\n (r1,r2,r3)=parse_result(infile)\n mesh.tecplt_value(outfile,[r1,r2,r3],i)\n # print mov_dest\n if(kind==1):\n rename(infile,mov_dest)\n i=i+1\n\n\n# @param path : file path\n# @param mesh : mesh object\n# @param ubound : upper bounder of time counting from time 000\n# @param prefix : \ndef create_animation_old(path,mesh,ubound,prefix=\"./fort.7\"):\n import dutwav.mesh\n assert(isinstance(mesh,dutwav.mesh.Mesh))\n for i in range(ubound):\n infilename=prefix+'{0:0>3d}'.format(i)\n outfilename=\"./tecplt_animation_\"+'{0:0>4d}'.format(i)+'.dat'\n (r1,r2,r3)=parse_result(infilename)\n mesh.tecplt_value(outfilename,[r1,r2,r3],i)\n\n" }, { "alpha_fraction": 0.4735660254955292, "alphanum_fraction": 0.5437844395637512, "avg_line_length": 23.12807846069336, "blob_id": "45f32d75b45a43a4a7a006fcb74041cac573e492", "content_id": "4b6894fb0b83caffa4ee448d97cec94c9bffe28a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4899, "license_type": "no_license", "max_line_length": 75, "num_lines": 203, "path": "/dutwav/script/open_shell.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "from numpy import *\nfrom dutwav.mesh import Mesh\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom numpy.linalg import norm\n\n\n# input total number of elements on circle\nn1 = 10\n# input total number of elements along radius\nn2 = 2\n\n# input openning angle \ntheta = 30\n#input elements vertical\nn3 = 2\n\n# input depth \n# inner radius\n# outer radius\ndepth =3\nirad = 5\norad = 2\n\n\n\nstart_angle=0.+theta/2.\nend_angle=360.-theta/2.\n\n#points on circular\np1=deg2rad(linspace(start_angle,end_angle,2*n1+1))\n# print rad2deg(p1)\n#points on radical\np2=linspace(irad,orad,2*n2+1)\n#points on vertical\np3=linspace(0,0-depth,2*n3+1)\n\nm = Mesh()\ndp = m.get_precision()\n\nt1 = cos(p1)\nt2 = sin(p1)\n\nx=list()\ny=list()\nz=list()\n\n\n#-------- Part 1--------------------\npms=(2*n1+1,2*n3+1)\nids = 1\n#Generate the nodes\nfor j in range(pms[1]):\n for i in range(pms[0]):\n tmp=(round(irad*t1[i],dp),round(irad*t2[i],dp),round(p3[j],dp))\n m.nodes[ids]=tmp\n tmp=tmp/norm(tmp)\n m.nrmls[ids]=(ids,tmp[0],tmp[1],0)\n ids+=1\n\n# Numbering the elements\nids = 1\nfor k in range(1,pms[1]-1,2):\n for j in range(1,pms[0]-1,2):\n i=j+(k-1)*pms[0]\n nodelist = (i,i+1,i+2,i+pms[0]+2,i+2*pms[0]+2,i+ \\\n 2*pms[0]+1,i+2*pms[0],i+pms[0])\n m.elems[ids] = ['mesh',8,nodelist,nodelist]\n ids+=1\nm._recreate_avail_info()\n\n#-------- Part 2--------------------\nm1=Mesh()\nids=1\npms=(2*n1+1,2*n3+1)\n#Generate the nodes\nfor j in range(pms[1]):\n for i in range(pms[0]):\n tmp=(round(orad*t1[i],dp),round(orad*t2[i],dp),round(p3[j],dp))\n m1.nodes[ids]=tmp\n tmp=tmp/norm(tmp)\n m1.nrmls[ids]=(ids,-tmp[0],-tmp[1],0)\n ids+=1\n# Numbering the elements\nids = 1\nfor k in range(1,pms[1]-1,2):\n for j in range(1,pms[0]-1,2):\n i=j+(k-1)*pms[0]\n nodelist = (i,i+1,i+2,i+pms[0]+2,i+2*pms[0]+2,i+ \\\n 2*pms[0]+1,i+2*pms[0],i+pms[0])\n m1.elems[ids] = ['mesh',8,nodelist,nodelist]\n ids+=1\nm.devour_mesh(m1)\n\n#-------- Part 3--------------------\nm1=Mesh()\nids=1\npms=(2*n1+1,2*n2+1)\n#Generate the nodes\nfor j in range(pms[1]):\n for i in range(pms[0]):\n tmp=(round(p2[j]*t1[i],dp),round(p2[j]*t2[i],dp),round(p3[0],dp))\n m1.nodes[ids]=tmp\n m1.nrmls[ids]=(ids,0.,0.,1.)\n ids+=1\n# Numbering the elements\nids = 1\nfor k in range(1,pms[1]-1,2):\n for j in range(1,pms[0]-1,2):\n i=j+(k-1)*pms[0]\n nodelist = (i,i+1,i+2,i+pms[0]+2,i+2*pms[0]+2,i+ \\\n 2*pms[0]+1,i+2*pms[0],i+pms[0])\n m1.elems[ids] = ['mesh',8,nodelist,nodelist]\n ids+=1\n\nm.devour_mesh(m1)\n\n#-------- Part 4--------------------\nm1=Mesh()\nids=1\npms=(2*n1+1,2*n2+1)\n#Generate the nodes\nfor j in range(pms[1]):\n for i in range(pms[0]):\n tmp=(round(p2[j]*t1[i],dp),round(p2[j]*t2[i],dp),round(p3[-1],dp))\n m1.nodes[ids]=tmp\n m1.nrmls[ids]=(ids,0.,0.,-1.)\n ids+=1\n# Numbering the elements\nids = 1\nfor k in range(1,pms[1]-1,2):\n for j in range(1,pms[0]-1,2):\n i=j+(k-1)*pms[0]\n nodelist = (i,i+1,i+2,i+pms[0]+2,i+2*pms[0]+2,i+ \\\n 2*pms[0]+1,i+2*pms[0],i+pms[0])\n m1.elems[ids] = ['mesh',8,nodelist,nodelist]\n ids+=1\n\nm.devour_mesh(m1)\n\n#-------- Part 5--------------------\nm1=Mesh()\nids=1\npms=(2*n2+1,2*n3+1)\n#calc norm direction\nalpha = float(theta)/2+90\n# print \"alpha=\",alpha\nalpha = deg2rad(alpha)\n#Generate the nodes\nfor j in range(pms[1]):\n for i in range(pms[0]):\n tmp=(round(p2[i]*t1[0],dp),round(p2[i]*t2[0],dp),round(p3[j],dp))\n m1.nodes[ids]=tmp\n m1.nrmls[ids]=(ids,cos(alpha),sin(alpha),0.)\n ids+=1\n# Numbering the elements\nids = 1\nfor k in range(1,pms[1]-1,2):\n for j in range(1,pms[0]-1,2):\n i=j+(k-1)*pms[0]\n nodelist = (i,i+1,i+2,i+pms[0]+2,i+2*pms[0]+2,i+ \\\n 2*pms[0]+1,i+2*pms[0],i+pms[0])\n m1.elems[ids] = ['mesh',8,nodelist,nodelist]\n ids+=1\n\nm.devour_mesh(m1)\n\n#----------------\n\n#-------- Part 5--------------------\nm1=Mesh()\nids=1\npms=(2*n2+1,2*n3+1)\n#calc norm direction\nalpha = -float(theta)/2-90\n# print \"alpha=\",alpha\nalpha = deg2rad(alpha)\n#Generate the nodes\nfor j in range(pms[1]):\n for i in range(pms[0]):\n tmp=(round(p2[i]*t1[-1],dp),round(p2[i]*t2[-1],dp),round(p3[j],dp))\n m1.nodes[ids]=tmp\n m1.nrmls[ids]=(ids,cos(alpha),sin(alpha),0.)\n ids+=1\n# Numbering the elements\nids = 1\nfor k in range(1,pms[1]-1,2):\n for j in range(1,pms[0]-1,2):\n i=j+(k-1)*pms[0]\n nodelist = (i,i+1,i+2,i+pms[0]+2,i+2*pms[0]+2,i+ \\\n 2*pms[0]+1,i+2*pms[0],i+pms[0])\n m1.elems[ids] = ['mesh',8,nodelist,nodelist]\n ids+=1\n\nm.devour_mesh(m1)\n\n#----------------u\n#TODO remove unused nodes,and renumber model\n# m1.nodes.pop(7)\nprint 'nodes=',len(m.nodes)\nprint 'nrmls=',len(m.nrmls)\nm._renum_model()\nm.tecplt_nrml(\"./ml.dat\")\n\n" }, { "alpha_fraction": 0.47255194187164307, "alphanum_fraction": 0.5038946866989136, "avg_line_length": 28.790054321289062, "blob_id": "f87494346ac20455fc0a37ab362005939b97e4ae", "content_id": "70f2468e3083d9f09c3ac679cfc5de268c50b86c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5392, "license_type": "no_license", "max_line_length": 94, "num_lines": 181, "path": "/dutwav/util.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "# @func: print node dictionary [ndic] to file at [filepath]\ndef print_nodedic(filepath,ndic):\n f = open(filepath,\"w\")\n tmp =[]\n for i in ndic:\n line = \"{:10d} {:12.6f} {:12.6f} {:12.6f}\".format(i,ndic[i][0],ndic[i][1],ndic[i][2])\n #for j in range(ndic[i][1]):\n #line += \" {:12.6f}\".format(ndic[i][2][j])\n line += \"\\n\"\n tmp.append(line)\n f.writelines(tmp)\n f.close()\n\n# @func: print elem dict [ndict] at [filepath] with string prefix [line]\n# @param: [line] is prefix put at beginning\ndef print_elemdic(filepath,ndic,line):\n f = open(filepath,\"w\")\n if (line[-1]!='\\n'):\n line+='\\n'\n tmp =[line]\n for i in ndic:\n line = \"{:5d} {:5d}\".format(i,ndic[i][1])\n for j in range(ndic[i][1]):\n line += \" {:5d}\".format(ndic[i][2][j])\n line += \"\\n\"\n tmp.append(line)\n f.writelines(tmp)\n f.close()\n\n# @func: given element dict [edic] ,retrun node to element relationship\n# @descript: find out which elements is connected to a node \ndef get_node_linking(edic):\n node_elem_rela ={}\n for i in edic:\n for j in range(edic[i][1]):\n node = edic[i][2][j]\n if node in node_elem_rela:\n node_elem_rela[node]['elem'].append(i)\n node_elem_rela[node]['pos'].append(j+1)\n else:\n node_elem_rela[node] ={}\n node_elem_rela[node]['elem']=[i]\n node_elem_rela[node]['pos']=[j+1]\n for i in node_elem_rela:\n node_elem_rela[i]['num_links'] = len(node_elem_rela[i]['elem'])\n node_elem_rela[i]['elem'] = tuple(node_elem_rela[i]['elem'])\n node_elem_rela[i]['pos'] = tuple(node_elem_rela[i]['pos'])\n return node_elem_rela\n\n# @func: given nrml connected to a node \ndef get_nrml_on_node(edic):\n nelem = len(edic.keys())\n node_nrml_rela={}\n print(\"{:d} elemnts\".format(nelem))\n for i in range(nelem):\n etype = edic[i+1][1]\n for k in range(etype):#not all elem has 8 node\n nid = edic[i+1][2][k]\n mid = edic[i+1][3][k]\n if nid in node_nrml_rela:\n #print nid\n node_nrml_rela[nid].add(mid)\n else:\n node_nrml_rela[nid]=set()\n node_nrml_rela[nid].add(mid)\n return node_nrml_rela\n\n\n# @func: return a function define the damping zone characteristics using [r],[alpha],[L]\n# @param: [L] define the length of damping zone\n# @param: [r] define the beginning position \n# @param: [alpha] is coefficient\ndef def_damp_func(r,alpha,L):\n r = float(r)\n alpha = float(alpha)\n L = float(L)\n def f(x):\n if x<r:\n return 0.\n else:\n value = (alpha*((x-r)/L)**2)\n if value>1:\n return 1.\n return value\n return f\n\n\n\n# @func: give surface potential value using analytical solution for finite depth\n# @param: [m] order of expansion\n# @param: [num]\n# @param: [amp] amplitude\n# @param: [omeg] frequency\n# @param: [depth] water depth\n# @param: [wk] wave number\ndef get_sufrace_potential(m,num,amp,omeg,depth,wk):\n import numpy as np\n g=9.801\n res={}\n for i in range(num):\n x=m.nodes[i+1][0]\n y=m.nodes[i+1][1]\n z=m.nodes[i+1][2]\n theta = np.arctan2(y,x)\n r=np.sqrt(x**2+y**2)\n phi=-1j*g*amp/omeg\n phi=phi*np.cosh(wk*(z+depth))/np.cosh(wk*depth)\n phi=phi*np.exp(1j*wk*r*np.cos(theta))\n res[i+1]=phi\n return res\n\ndef get_ind_potential(mesh,num,amp,omeg,depth,wk): \n '''\n for cylinder in indefinite water ???\n '''\n import numpy as np\n from dutwav.analytical import bj\n from scipy.special import jv\n mesh.nodes[1]\n g=9.801\n res={}\n for i in range(num):\n x=mesh.nodes[i+1][0]\n y=mesh.nodes[i+1][1]\n z=mesh.nodes[i+1][2]\n theta = np.arctan2(y,x)\n r=np.sqrt(x**2+y**2)\n tmp=0.\n for m in range(10):\n eps=2.\n if m==0:\n eps=1.\n tp=-1j*g*amp/omeg\n tp=tp*np.cosh(wk*(z+depth))/np.cosh(wk*depth)\n tp=tp*eps*(1j)**m*bj(wk*r,m)*np.cos(m*theta)\n # tp=tp*eps*(1j)**m*jv(m,wk*r)*np.cos(m*theta)\n tmp+=tp\n res[i+1]=tmp\n return res\n\n\n# @func: generate sippem kind of mesh for one element\ndef output_ss(path,mesh,eid,nid):\n with open(path,\"wb\") as f:\n f.write(' 3 8 1 8 3. 8\\n')\n info = mesh.elems[eid][2]\n j=0\n for i in [1,3,5,7,2,4,6,8]:\n j+=1 \n str1='{0:<5d}'.format(j)\n str1+=(' '.join('{0:<14.8f}'.format(i) for i in mesh.nodes[info[i-1]]))\n if (info[i-1]==nid):\n jth=i\n str1+='\\n'\n f.write(str1)\n f.write('1 1 2 3 4 5 6 7 8 -3\\n')\n str2=(' '.join('{0:<14.8f}'.format(i) for i in mesh.nodes[nid]))\n str2+='\\n'\n f.write(str2)\n if j==1: xi=[-1.,-1.]\n if j==2: xi=[1.,-1.]\n if j==3: xi=[1.,1.]\n if j==4: xi=[-1.,1.]\n if j==5: xi=[0.,-1.]\n if j==6: xi=[1.,0.]\n if j==7: xi=[0.,1.]\n if j==8: xi=[-1.,0.]\n f.write('{0:<14.8f} {0:<14.8f}'.format(xi[0],xi[1]))\n \n\n pass\n\n\n# parse c.err\ndef parse_cerr(err):\n p1=[]\n p2=[]\n for i in err:\n p1.append(i[0])\n p2.append(i[1])\n return (p1,p2)\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 17, "blob_id": "ecd8d8c5ec42805557df2171348194b7d4bc2984", "content_id": "48aa89021b4c6d74307500e41a75cd5028fe9e27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36, "license_type": "no_license", "max_line_length": 24, "num_lines": 2, "path": "/dutwav/analytical/test.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "import bessel_func as bf\nbf.bj(1,2)\n" }, { "alpha_fraction": 0.4377460777759552, "alphanum_fraction": 0.464084267616272, "avg_line_length": 37.75051498413086, "blob_id": "5c39f1c6094a1b77570f5b4ba3aee119762ed729", "content_id": "53aad3f702cfd5689c5c4e14b6ee5e8000d070d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18794, "license_type": "no_license", "max_line_length": 198, "num_lines": 485, "path": "/dutwav/draw.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "import dutwav.mesh\nfrom dutwav.__mesh_core import POS\n# from matplotlib.patches import FancyArrowPatch\nfrom mpl_toolkits.mplot3d import proj3d\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nfrom numpy import mean,zeros\n\ndef set_aspect_equal_3d(ax):\n \"\"\"Fix equal aspect bug for 3D plots.\"\"\"\n\n xlim = ax.get_xlim3d()\n ylim = ax.get_ylim3d()\n zlim = ax.get_zlim3d()\n\n xmean = mean(xlim)\n ymean = mean(ylim)\n zmean = mean(zlim)\n\n plot_radius = max([abs(lim - mean_)\n for lims, mean_ in ((xlim, xmean),\n (ylim, ymean),\n (zlim, zmean))\n for lim in lims])\n\n ax.set_xlim3d([xmean - plot_radius, xmean + plot_radius])\n ax.set_ylim3d([ymean - plot_radius, ymean + plot_radius])\n ax.set_zlim3d([zmean - plot_radius, zmean + plot_radius])\n \n# class Arrow3D(FancyArrowPatch):\n # def __init__(self, xs, ys, zs, *args, **kwargs):\n # FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\n # self._verts3d = xs, ys, zs\n\n # def draw(self, renderer):\n # xs3d, ys3d, zs3d = self._verts3d\n # xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n # self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\n # FancyArrowPatch.draw(self, renderer)\n \nclass DrawMesh(object):\n def __init__(self,mesh):\n assert(isinstance(mesh,dutwav.mesh.Mesh))\n self.__rMeshObj = mesh\n\n # This class is for drawing mesh func.\n\n\n def _draw_nrml(self,id,ax,scale):\n nrm[0:3,i] = self.__rMeshObj.nrmls[id][1:4]\n nrm[3:6,i] = self.__rMeshObj.nodes[self.__rMeshObj.nrmls[id][0]][0:3]\n b = nrm[3:6,i]#base\n e = nrm[0:3,i]*scale+b#end\n # a = Arrow3D([b[0],e[0]],[b[1],e[1]],[b[2],e[2]], mutation_scale=10, lw=1, arrowstyle=\"-|>\", color=\"k\")\n # ax.add_artist(a)\n\n \n def _draw_element(self,id,ax,c='red'):\n this_elem = self.__rMeshObj.elems[id]\n loc = zeros((3,this_elem[POS.TYPE]+1),dtype='float')\n nrm = zeros((6,this_elem[POS.TYPE]),dtype='float')\n for i in range(this_elem[POS.TYPE]):\n loc[0:3,i] = self.__rMeshObj.nodes[this_elem[POS.NODLIST][i]][0:3]\n loc[:,-1] = loc[:,0] \n ax.plot_wireframe(loc[0,:],loc[1,:],loc[2,:],rstride=5,cstride=5,color=c)\n \n def draw_lines(self,pi=[],s=10,points=[]):\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n for i in range(len(pi)-1):\n n1=pi[i]\n n2=pi[i+1]\n print (n1,n2)\n self._draw_line(n1,n2,ax,s=s)\n if len(points)!=0:\n loc=zeros((3,len(points)))\n p=0\n for i in points:\n loc[0,p] = self.__rMeshObj.nodes[i][0]\n loc[1,p] = self.__rMeshObj.nodes[i][1]\n loc[2,p] = self.__rMeshObj.nodes[i][2]\n p+=1\n ax.scatter(loc[0,:],loc[1,:],loc[2,:],color=\"g\",s=s*5)\n\n set_aspect_equal_3d(ax)\n plt.show()\n\n def _draw_line(self,n1,n2,ax,c='red',s=10):\n info1 = list(self.__rMeshObj.nodes[n1])\n info2 = list(self.__rMeshObj.nodes[n2])\n loc = zeros((3,2),dtype='float')\n loc[0:3,0] = info1[0:3]\n loc[0:3,1] = info2[0:3]\n ax.plot_wireframe(loc[0,:],loc[1,:],loc[2,:],rstride=5,cstride=5,color=c) \n ax.scatter(loc[0,:],loc[1,:],loc[2,:],color=\"g\",s=s)\n\n # def _draw_element_damp(self,id,ax,scale,c='red'):\n # this_elem = self.__rMeshObj.elems[id]\n # loc = zeros((3,this_elem[POS.TYPE]+1),dtype='float')\n # nrm = zeros((6,this_elem[POS.TYPE]),dtype='float')\n # for i in range(this_elem[POS.TYPE]):\n # loc[0:2,i] = self.__rMeshObj.nodes[this_elem[POS.NODLIST][i]][0:2]\n # loc[2,i] = self.__rMeshObj.damp_info[this_elem[POS.NODLIST][i]]\n # loc[:,-1] = loc[:,0] \n # ax.plot_wireframe(loc[0,:],loc[1,:],loc[2,:],rstride=5,cstride=5,color=c)\n \n \n def draw_model(self,scale=0.04,with_arrow=False,points=[],d = False):\n\n\n fig = plt.figure()\n # ax = fig.add_subplot(111,projection='3d')\n ax = fig.gca(projection='3d')\n # ax.set_aspect(\"equal\")\n for i in self.__rMeshObj.elems:\n if not d:\n self._draw_element(i,ax)\n else:\n self._draw_element_damp(i,ax)\n if with_arrow:\n for i in self.nrmls:\n _draw_nrml(i,ax,scale)\n if len(points)!=0:\n loc=zeros((3,len(points)))\n p=0\n for i in points:\n loc[0,p] = self.__rMeshObj.nodes[i][0]\n loc[1,p] = self.__rMeshObj.nodes[i][1]\n loc[2,p] = self.__rMeshObj.nodes[i][2]\n p+=1\n ax.scatter(loc[0,:],loc[1,:],loc[2,:],color=\"g\",s=100)\n set_aspect_equal_3d(ax)\n plt.show()\n \n #==================================================================\n\n # @func : export tecplot mesh using quad element\n def tecplt_quad(self,path):\n with open(path,\"wb\") as f:\n num_pts = len(self.__rMeshObj.nrmls)\n num_elms = len(self.__rMeshObj.elems)\n f.write(\"\"\"TITLE = \"3D Mesh Grid Data for Element Boundary\"\\n\\\n VARIABLES = \"X\", \"Y\", \"Z\",\"DX\",\"DY\",\"DZ\" \\n\"\"\")\n f.write('ZONE T=\"MESH\" N= {:d} ,E= {:d} \\\n ,F=FEPOINT,ET=QUADRILATERAL\\n'.format(num_pts,num_elms))\n \n for i in self.__rMeshObj.nrmls:\n info = self.__rMeshObj.nrmls[i]\n node = self.__rMeshObj.nodes[info[0]]\n f.write(' '.join('{0:<9.6f}'.format(j) for j in node[0:3]))\n f.write(' ')\n f.write(' '.join('{0:<9.6f}'.format(j) for j in info[1:4]))\n f.write(\"\\n\")\n for i in self.__rMeshObj.elems:\n n = self.__rMeshObj.elems[i][POS.TYPE]\n info = list(self.__rMeshObj.elems[i][POS.NRMLIST])\n # nlist = [info[0],info[2],info[4],info[6]] \n nlist = info[::2]\n if(n==6):\n nlist=[info[0],info[1],info[2],info[0]]\n f.write(' '.join('{0:<8d}'.format(j) for j in nlist))\n f.write(\"\\n\")\n\n\n\n # @func : export surface mesh using quad, also adding time info\n def tecplt_value_quad(self,path,value,soltime=1):\n\n assert(isinstance(value,list))\n for i in value:\n assert(len(self.__rMeshObj.nodes)==len(i))\n\n with open(path,\"wb\") as f:\n num_pts = len(self.__rMeshObj.nodes)\n num_elms = len(self.__rMeshObj.elems)\n str1='TITLE = \"3D Mesh Grid Data for Element Boundary\"\\n'+ \\\n 'VARIABLES = \"X\", \"Y\",\"Z\"'\n for i in range(len(value)):\n str1+=', \"v'+str(i+1)+'\"'\n str1+='\\n'\n f.write(str1)\n f.write('ZONE T=\"MESH\" N= {:d} ,E= {:d}'.format(num_pts,num_elms) \\\n +',F=FEPOINT,ET=QUADRILATERAL\\n')\n f.write('SolutionTime={:d}\\n'.format(soltime))\n f.write('StrandID={:d}\\n'.format(1))\n\n for i in self.__rMeshObj.nodes:\n node = self.__rMeshObj.nodes[i]\n # output x,y,z\n f.write(' '.join('{0:<9.6f}'.format(j) for j in node[0:3]))\n # output value info\n for j in range(len(value)):\n f.write(' ')\n f.write('{0:<9.6f}'.format(value[j][i]))\n f.write(\"\\n\")\n # output node connection list\n for i in self.__rMeshObj.elems:\n info = list(self.__rMeshObj.elems[i][POS.NODLIST])\n typ = self.__rMeshObj.elems[i][POS.TYPE]\n nlist = info[::2]\n if (typ==6):\n nlist=[info[0],info[1],info[2],info[0]]\n f.write(' '.join('{0:<8d}'.format(j) for j in nlist))\n f.write(\"\\n\")\n\n\n\n\n\n # @func: use polygon elem,have nrml info,no time info\n # plot tecplot, use node numbering\n def tecplt_poly_2(self,path):\n print(\"Nodes Numbering Used\")\n print(\"No nrml info,No time output\")\n MAX_LINE_HOLD=500\n with open(path,\"wb\") as f:\n num_pts = len(self.__rMeshObj.nodes)\n num_elem = len(self.__rMeshObj.elems)\n f.write(\"\"\"\n TITLE = \"3D Mesh Grid Data for Element Boundary\"\n VARIABLES = \"X\", \"Y\", \"Z\"\\n\n \"\"\")\n f.write('ZONE T=\"Mesh\", ZONETYPE=FEPOLYGON, NODES= {:6d}, ELEMENTS= {:6d}, Faces= {:6d}, NumConnectedBoundaryFaces=0,TotalNumBoundaryConnections=0\\n'.format(num_pts,num_elem,8*num_elem))\n \n psl = []\n for i in range(8): \n psl.append([])\n\n for i in self.__rMeshObj.nodes:\n node = self.__rMeshObj.nodes[i]\n for j in [0,1,2]:\n psl[j].append(node[j])\n\n for i in range(3):#3 is number of psl to output\n max_len = len(psl[0])\n cha = max_len/MAX_LINE_HOLD + 1\n for k in range(cha):\n f.write(' '.join('{0:<7.4f}'.format(j) for j in psl[i][k*MAX_LINE_HOLD:(k+1)*MAX_LINE_HOLD]))\n f.write('\\n')\n \n for i in self.__rMeshObj.elems.keys():\n n = self.__rMeshObj.elems[i][POS.TYPE]\n nlist = list(self.__rMeshObj.elems[i][POS.NODLIST])\n nlist.append(nlist[0])\n for k in range(n):\n f.write(' '.join('{0:<d}'.format(j) for j in nlist[k:k+2]))\n f.write(\"\\n\")\n psl[6].append(i)\n psl[7].append(0)\n\n for i in [6,7]:\n max_len = len(psl[6])\n cha = max_len/MAX_LINE_HOLD + 1\n for k in range(cha):\n f.write(' '.join('{0:<d}'.format(j) for j in psl[i][k*MAX_LINE_HOLD:(k+1)*MAX_LINE_HOLD]))\n f.write('\\n')\n\n\n # @func : export tecplot mesh using polygon element\n # use nrml for numbering\n def tecplt_poly_1(self,path):\n print(\"poly_1\")\n print(\"nrml Numbering Used\")\n print(\"No time output\")\n with open(path,\"wb\") as f:\n num_pts = len(self.__rMeshObj.nrmls)\n num_elem = len(self.__rMeshObj.elems)\n f.write(\"\"\"\n TITLE = \"3D Mesh Grid Data for Element Boundary\"\n VARIABLES = \"X\", \"Y\", \"Z\",\"DX\",\"DY\",\"DZ\"\\n\n \"\"\")\n f.write('ZONE T=\"Mesh\", ZONETYPE=FEPOLYGON, NODES= {:6d}, ELEMENTS= {:6d}, Faces= {:6d}, NumConnectedBoundaryFaces=0,TotalNumBoundaryConnections=0\\n'.format(num_pts,num_elem,8*num_elem))\n\n psl = []\n for i in range(8): \n psl.append([])\n #use nrml id for numbering\n for i in self.__rMeshObj.nrmls:\n info = self.__rMeshObj.nrmls[i]\n node = self.__rMeshObj.nodes[info[0]]\n for j in [0,1,2]:\n psl[j].append(node[j])\n psl[j+3].append(info[j+1]) \n\n # print psl[0] \n for i in range(6):\n max_len = len(psl[0])\n cha = max_len/500 + 1\n for k in range(cha):\n f.write(' '.join('{0:<7.4f}'.format(j) for j in psl[i][k*500:(k+1)*500]))\n f.write('\\n')\n\n \n for i in self.__rMeshObj.elems.keys():\n n = self.__rMeshObj.elems[i][POS.TYPE]\n nlist = list(self.__rMeshObj.elems[i][POS.NRMLIST])\n #add first node\n nlist.append(nlist[0])\n for k in range(n):\n f.write(' '.join('{0:<d}'.format(j) for j in nlist[k:k+2]))\n f.write(\"\\n\")\n psl[6].append(i)\n psl[7].append(0)\n\n for i in [6,7]:\n max_len = len(psl[6])\n cha = max_len/500 + 1\n for k in range(cha):\n f.write(' '.join('{0:<d}'.format(j) for j in psl[i][k*500:(k+1)*500]))\n f.write('\\n')\n\n # @func : export surface mesh using polygon,no time info,no nrml info\n def tecplt_value_poly(self,path,value):\n print(\"Nodes Numbering Used\")\n print(\"No Nrml Ouput,No time output\")\n with open(path,\"wb\") as f:\n num_pts = len(self.__rMeshObj.nodes)\n num_elem = len(self.__rMeshObj.elems)\n f.write(\"\"\"\n TITLE = \"3D Mesh Grid Data for Element Boundary\"\n VARIABLES = \"X\", \"Y\", \"Z\",\"v1\"\\n\n \"\"\")\n f.write('ZONE T=\"Mesh\", ZONETYPE=FEPOLYGON, NODES= {:6d}, ELEMENTS= {:6d}, Faces= {:6d}, NumConnectedBoundaryFaces=0,TotalNumBoundaryConnections=0\\n'.format(num_pts,num_elem,8*num_elem))\n\n psl = []\n for i in range(8): \n psl.append([])\n\n for i in self.__rMeshObj.nodes:\n node = self.__rMeshObj.nodes[i]\n for j in [0,1,2]:\n psl[j].append(node[j])\n psl[3].append(value[0][i])\n\n # psl[1..3]\n for i in range(4):\n max_len = len(psl[0])\n cha = max_len/500 + 1\n for k in range(cha):\n f.write(' '.join('{0:<7.4f}'.format(j) for j in psl[i][k*500:(k+1)*500]))\n f.write('\\n')\n \n for i in self.__rMeshObj.elems.keys():\n n = self.__rMeshObj.elems[i][POS.TYPE]\n nlist = list(self.__rMeshObj.elems[i][POS.NODLIST])\n nlist.append(nlist[0])\n for k in range(n):\n f.write(' '.join('{0:<d}'.format(j) for j in nlist[k:k+2]))\n f.write(\"\\n\")\n psl[6].append(i)\n psl[7].append(0)\n for i in [6,7]:\n max_len = len(psl[6])\n cha = max_len/500 + 1\n for k in range(cha):\n f.write(' '.join('{0:<d}'.format(j) for j in psl[i][k*500:(k+1)*500]))\n f.write('\\n')\n\n\n\n\n # @func : export tecplot mesh using polygon element\n # use nrml for numbering\n def tecplt_poly_3(self,path):\n print(\"poly_3\")\n print(\"nrml Numbering Used\")\n print(\"No time output\")\n from copy import copy\n with open(path,\"wb\") as f:\n num_pts = len(self.__rMeshObj.nrmls)\n num_elem = len(self.__rMeshObj.elems)\n\n\n bodystr=''\n psl = []\n for i in range(8): \n psl.append([])\n #use nrml id for numbering\n for i in self.__rMeshObj.nrmls:\n info = self.__rMeshObj.nrmls[i]\n node = self.__rMeshObj.nodes[info[0]]\n for j in [0,1,2]:\n psl[j].append(node[j])\n psl[j+3].append(info[j+1]) \n\n # print psl[0] \n for i in range(6):\n max_len = len(psl[0])\n cha = max_len/500 + 1\n for k in range(cha):\n bodystr += (' '.join('{0:<7.4f}'.format(j) for j in psl[i][k*500:(k+1)*500]))\n bodystr +=('\\n')\n\n \n for i in self.__rMeshObj.elems.keys():\n n = self.__rMeshObj.elems[i][POS.TYPE]\n nlist = list(self.__rMeshObj.elems[i][POS.NRMLIST])\n if(n==6):\n tmp=copy(nlist)\n nlist[2-1]=tmp[4-1]\n nlist[3-1]=tmp[2-1]\n nlist[4-1]=tmp[5-1]\n nlist[5-1]=tmp[3-1]\n\n \n #add first node\n nlist.append(nlist[0])\n for k in range(n):\n bodystr+=(' '.join('{0:<d}'.format(j) for j in nlist[k:k+2]))\n bodystr+=(\"\\n\")\n psl[6].append(i)\n psl[7].append(0)\n\n for i in [6,7]:\n max_len = len(psl[6])\n cha = max_len/500 + 1\n for k in range(cha):\n bodystr+=(' '.join('{0:<d}'.format(j) for j in psl[i][k*500:(k+1)*500]))\n bodystr+=('\\n')\n\n f.write(\"\"\"\n TITLE = \"3D Mesh Grid Data for Element Boundary\"\n VARIABLES = \"X\", \"Y\", \"Z\",\"DX\",\"DY\",\"DZ\"\\n\n \"\"\")\n f.write('ZONE T=\"Mesh\", ZONETYPE=FEPOLYGON, NODES= {:6d}, ELEMENTS= {:6d}, Faces= {:6d}, NumConnectedBoundaryFaces=0,TotalNumBoundaryConnections=0\\n'.format(num_pts,num_elem,len(psl[6])))\n f.write(bodystr)\n\n\n # @func : export surface mesh using polygon,no time info,no nrml info\n def tecplt_value_poly_2(self,path,value):\n print(\"Nodes Numbering Used\")\n print(\"No Nrml Ouput,No time output\")\n with open(path,\"wb\") as f:\n num_pts = len(self.__rMeshObj.nodes)\n num_elem = len(self.__rMeshObj.elems)\n ss=''\n\n psl = []\n for i in range(8): \n psl.append([])\n\n for i in self.__rMeshObj.nodes:\n node = self.__rMeshObj.nodes[i]\n for j in [0,1,2]:\n psl[j].append(node[j])\n psl[3].append(value[0][i])\n\n # psl[1..3]\n for i in range(4):\n max_len = len(psl[0])\n cha = max_len/500 + 1\n for k in range(cha):\n ss+=(' '.join('{0:<7.4f}'.format(j) for j in psl[i][k*500:(k+1)*500]))\n ss+=('\\n')\n \n for i in self.__rMeshObj.elems.keys():\n n = self.__rMeshObj.elems[i][POS.TYPE]\n nlist = list(self.__rMeshObj.elems[i][POS.NODLIST])\n if(n==6):\n tmp=copy(nlist)\n nlist[2-1]=tmp[4-1]\n nlist[3-1]=tmp[2-1]\n nlist[4-1]=tmp[5-1]\n nlist[5-1]=tmp[3-1]\n nlist.append(nlist[0])\n for k in range(n):\n ss+=(' '.join('{0:<d}'.format(j) for j in nlist[k:k+2]))\n ss+=(\"\\n\")\n psl[6].append(i)\n psl[7].append(0)\n for i in [6,7]:\n max_len = len(psl[6])\n cha = max_len/500 + 1\n for k in range(cha):\n ss+=(' '.join('{0:<d}'.format(j) for j in psl[i][k*500:(k+1)*500]))\n ss+=('\\n')\n\n f.write(\"\"\"\n TITLE = \"3D Mesh Grid Data for Element Boundary\"\n VARIABLES = \"X\", \"Y\", \"Z\",\"v1\"\\n\n \"\"\")\n f.write('ZONE T=\"Mesh\", ZONETYPE=FEPOLYGON, NODES= {:6d}, ELEMENTS= {:6d}, Faces= {:6d}, NumConnectedBoundaryFaces=0,TotalNumBoundaryConnections=0\\n'.format(num_pts,num_elem,len(psl[6])))\n\n f.write(ss)\n" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 24, "blob_id": "6359f27322c8720a7d8debe25cfb4481a68b0a7e", "content_id": "dc91776c4e233bf6137f3e0b9f44691d0a354cb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50, "license_type": "no_license", "max_line_length": 24, "num_lines": 2, "path": "/dutwav/__init__.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "# from .mesh import Mesh\n# from .wave import Wave\n" }, { "alpha_fraction": 0.40622973442077637, "alphanum_fraction": 0.46073979139328003, "avg_line_length": 31.595745086669922, "blob_id": "469a8d08b2342e129eeec510e9622a3762ff4169", "content_id": "aa24e00fa5f2d8b760555638543dcbdf7fe10811", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1541, "license_type": "no_license", "max_line_length": 88, "num_lines": 47, "path": "/dutwav/preprocess.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "# @func: return a function define the damping zone characteristics using [r],[alpha],[L]\n# @param: [L] define the length of damping zone\n# @param: [r] define the beginning position \n# @param: [alpha] is coefficient\ndef def_damp_func(r,alpha,L):\n r = float(r)\n alpha = float(alpha)\n L = float(L)\n def f(x):\n if x<r:\n return 0.\n else:\n value = (alpha*((x-r)/L)**2)\n if value>1:\n return 1.\n return value\n return f\n\n# @func: generate sippem kind of mesh for one element\n# @var : [nid] is node number for source point\n# @var : [eid] element id for target elem\ndef output_ss(path,mesh,eid,nid):\n with open(path,\"wb\") as f:\n f.write(' 3 8 1 8 3. 8\\n')\n info = mesh.elems[eid][2]\n j=0\n for i in [1,3,5,7,2,4,6,8]:\n j+=1 \n str1='{0:<5d}'.format(j)\n str1+=(' '.join('{0:<14.8f}'.format(i) for i in mesh.nodes[info[i-1]]))\n if (info[i-1]==nid):\n jth=i\n str1+='\\n'\n f.write(str1)\n f.write('1 1 2 3 4 5 6 7 8 -3\\n')\n str2=(' '.join('{0:<14.8f}'.format(i) for i in mesh.nodes[nid]))\n str2+='\\n'\n f.write(str2)\n if j==1: xi=[-1.,-1.]\n if j==2: xi=[1.,-1.]\n if j==3: xi=[1.,1.]\n if j==4: xi=[-1.,1.]\n if j==5: xi=[0.,-1.]\n if j==6: xi=[1.,0.]\n if j==7: xi=[0.,1.]\n if j==8: xi=[-1.,0.]\n f.write('{0:<14.8f} {0:<14.8f}'.format(xi[0],xi[1]))\n \n" }, { "alpha_fraction": 0.4191591441631317, "alphanum_fraction": 0.4451185166835785, "avg_line_length": 28.886075973510742, "blob_id": "29c687ee6119cbb5316630681ef2bc1c5464fc99", "content_id": "a71ac96f705c0288d78e8591e5820cdc6959e1c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7088, "license_type": "no_license", "max_line_length": 86, "num_lines": 237, "path": "/dutwav/result.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "import numpy as np\nclass FreeTerm2(object):\n def __init__(self):\n self.result = {}\n # self.result2 ={}\n self.__dp = 4\n self.list1=[]#frc31 > threshold\n self.list2=[]#frc32 > threshold\n self.info={}\n # self.info2={}\n def read_result(self,path,dp=4):\n list1=[]\n list2=[]\n with open(path,\"rb\") as f:\n lines = f.readlines()\n acc = 0\n for line in lines:\n acc+=1\n tmp = [float(i) for i in line.split()]\n key = int(tmp[0]) \n self.result[key] = tmp[1:]\n self.info[acc] = key \n if abs(tmp[2])>1e-2:\n list1.append(acc)\n if abs(tmp[3])>1e-2:\n list2.append(acc)\n self.list1=list1\n self.list2=list2\n\nclass FreeTerm(object):\n def __init__(self):\n self.result = {}\n # self.result2 ={}\n self.__dp = 4\n self.list1=[]#frc31 > threshold\n self.list2=[]#frc32 > threshold\n self.info={}\n # self.info2={}\n\n def read_result(self,path,dp=4):\n list1=[]\n list2=[]\n with open(path,\"rb\") as f:\n lines = f.readlines()\n acc = 0\n for line in lines:\n acc+=1\n tmp = [float(i) for i in line.split()]\n # key = tuple(np.round(tmp[0:2],dp))\n key = (round(tmp[0],dp),round(tmp[1],dp))\n self.result[key] = tmp[2:]\n self.info[acc] = key \n # self.info2[key] = acc\n # self.result2[acc] = tmp[2:6]\n if abs(tmp[3])>1e-2:\n list1.append(acc)\n if abs(tmp[4])>1e-2:\n list2.append(acc)\n self.list1=list1\n self.list2=list2\n \n def calc_fterm(self,r2):\n for (pos,fterm) in self.result.items():\n if pos in r2.result.keys():\n f2 = r2.result[pos]\n fterm[0] = 0. - f2[0]\n fterm[1] = 0. - f2[1]\n fterm[2] = 0. - f2[2]\n fterm[3] = f2[3]# NOTE 1- is taken away\n\n else:\n fterm[0] = 0.\n fterm[1] = 0.\n fterm[2] = 0.\n fterm[3] = 0.5\n self.result[pos][0:4]=fterm[0:4]\n\n def print_fterm(self):\n for (i,key) in self.info.items():\n print(self.result[key])\n\n def output_fterm(self,path):\n with open(path,\"wb\") as f:\n for (i,key) in self.info.items():\n f.write(('{0:<5d}'.format(i)))\n f.write(' '.join('{0:<12.8f}'.format(j) for j in self.result[key]))\n f.write(\"\\n\")\n\n\n\nclass AnalyticalPotential(object):\n def __init__(self):\n self.vec=None\n self.eti=None\n self.waves={}\n self.w=0.0\n\n def read_vector(self,path):\n with open(path,\"rb\") as f:\n tmp = f.readlines()\n vec = np.zeros((len(tmp)),dtype = 'complex128')\n for i in range(len(tmp)):\n s = tmp[i]\n s2=[float(j) for j in s.split()]\n vec[i] = s2[1]+1j*s2[2]\n self.vec=vec\n # def get_eti(self,omega):\n # # eti = iw/g * potential\n # self.eti = self.vec*1j*omega/9.807\n\n def get_eti(self):\n # eti = iw/g *phi\n self.eti = self.vec*1j*self.w/9.807\n\n def generate_wave(self,m,maxT,deltaT,factor=1,prefix='wave'):\n '''\n generate_wave( m,maxT,deltaT)\n '''\n from numpy import exp,floor\n from dutwav.vtk import ValuetoVTK\n from dutwav.mesh import Mesh\n assert(isinstance(m,Mesh))\n assert(len(m.nodes)==len(self.vec))\n #compute total iteration\n niter=np.int(floor(maxT/deltaT))\n # print maxT,\"maxT\",deltaT,\"deltaT\"\n # print niter,\" max iteration\"\n self.get_eti()\n for i in range(niter):\n value={}\n t=i*deltaT\n print(exp(-1j*self.w*t))\n for j in m.nodes:\n # self.waves=self.eti*exp(-1j*self.w*t)\n tmp = self.eti[j-1]*exp(-1j*self.w*t)\n value[j]=tmp.real*factor\n self.waves=value\n\n name=prefix+'.'+ '{:0>7d}'.format(i)\n ValuetoVTK(m,name,value)\n\n\n def output(self,path):\n re= np.zeros((self.vec.shape[0],2),dtype='float64')\n re[:,0]=self.vec.real[:]\n re[:,1]=self.eti.real[:]\n np.savetxt(path,re)\n\n\n\nclass BoundaryValue(object):\n def __init__(self):\n self.bc=None\n\n def read_bc(self,path):\n with open(path,\"rb\") as f:\n tmp = f.readlines()\n vec = np.zeros((len(tmp),1),dtype = 'float64')\n for i in range(len(tmp)):\n vec[i,0] = float(tmp[i])\n self.bc=vec\n\nclass MatrixA(object):\n def __init__(self):\n self.C=None\n self.A=None\n self.n=0\n self.m=0\n self.err={}\n self.derr={}\n def read_matrix(self,path):\n self.A = np.loadtxt(path,dtype='float64')\n n = int(np.sqrt(self.A.size))\n self.A.resize(n,n)\n self.n=n\n\n def read_matrix_c(self,path):\n self.C = np.loadtxt(path,dtype='float64')\n m = int(self.C.size/self.n)\n self.C.resize(self.n,m)\n self.m=m\n\n def analysis_matrix(self,threshold):\n import copy\n self.err={}\n self.derr={}\n b = copy.copy(self.A)\n while (b.max()) >threshold:\n n1 = b.argmax()/self.n\n n2 = b[n1,:].argmax()\n key = (n1+1,n2+1)\n if n1!=n2:\n self.err[key]=b[n1,n2]\n else:\n self.derr[key]=b[n1,n2]\n b[n1,n2]=0.\n\n\nclass ElemValue():\n def __init__(self):\n self.res={}\n\n def read_result(self,path):\n with open(path,\"rb\") as f:\n acc=0\n for line in f:\n line = line.split()\n acc+=1\n value=[float(j) for j in line[3:]]\n eid = int(line[1])\n nid = int(line[0])\n self.res[nid]=self.res.get(nid,{})\n self.res[nid][eid]=self.res[nid].get(eid,{})\n flag = int(line[2])\n if acc==1:\n self.res[nid][eid]['amat']=value\n if acc==2:\n self.res[nid][eid]['bmat']=value\n if acc==3:\n self.res[nid][eid]['aval']=value\n if acc==4:\n self.res[nid][eid]['bval']=value\n acc=0\n def pp_print(self,nid,eid):\n value = None\n try:\n value = self.res[nid][eid]\n except:\n print(\"Error Accessing, Check input number\")\n if value:\n for i in value:\n str1='{0:5d} {0:5d} '.format(nid,eid)\n str1+=i\n str1+=\" \"\n for j in range(8):\n str1 += \"{0:14.8f}\".format(value[i][j])\n print(str1)\n\n\n\n\n\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 25, "blob_id": "5d91e90129bd29da48e51b96c1a6e2a980fc18f5", "content_id": "1f63ce1c7d9bc211bfe7fb8a55ab160a05220054", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26, "license_type": "no_license", "max_line_length": 25, "num_lines": 1, "path": "/dutwav/analytical/__init__.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "from bessel_func import *\n" }, { "alpha_fraction": 0.48882409930229187, "alphanum_fraction": 0.5140913724899292, "avg_line_length": 29.235294342041016, "blob_id": "5c4b5e6055f1fe1ca22a6b9a148e427c1ef5ea1e", "content_id": "2ed120b2cf9def1823fe19199aaeb60db31dc0c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 94, "num_lines": 34, "path": "/dutwav/io.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "# @func: print node dictionary [ndic] to file at [filepath]\ndef print_nodedic(filepath,ndic):\n '''\n given a node dict,output at given loc\n '''\n f = open(filepath,\"w\")\n tmp =[]\n for i in ndic:\n line = \"{:10d} {:12.6f} {:12.6f} {:12.6f}\".format(i,ndic[i][0],ndic[i][1],ndic[i][2])\n #for j in range(ndic[i][1]):\n #line += \" {:12.6f}\".format(ndic[i][2][j])\n line += \"\\n\"\n tmp.append(line)\n f.writelines(tmp)\n f.close()\n\n# @func: print elem dict [ndict] at [filepath] with string prefix [line]\n# @param: [line] is prefix put at beginning\ndef print_elemdic(filepath,ndic,line):\n '''\n given a elem dict, output a given loc\n '''\n f = open(filepath,\"w\")\n if (line[-1]!='\\n'):\n line+='\\n'\n tmp =[line]\n for i in ndic:\n line = \"{:5d} {:5d}\".format(i,ndic[i][1])\n for j in range(ndic[i][1]):\n line += \" {:5d}\".format(ndic[i][2][j])\n line += \"\\n\"\n tmp.append(line)\n f.writelines(tmp)\n f.close()\n\n" }, { "alpha_fraction": 0.4631962478160858, "alphanum_fraction": 0.4788825213909149, "avg_line_length": 32.890586853027344, "blob_id": "f512f9a4488805dbe079691fad3aa3fc04139730", "content_id": "8d00984a391cc0196172a830118833e0d8abb283", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28815, "license_type": "no_license", "max_line_length": 128, "num_lines": 850, "path": "/dutwav/__mesh_core.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "import logging\nfrom enum import Enum\nfrom copy import deepcopy\nfrom scipy.linalg import norm\nimport numpy as np\nfrom numpy import cos,sin,deg2rad,array,sqrt\nfrom numpy import round as npround\n\n\nclass POS(Enum):\n TAG=0\n TYPE=1\n NODLIST=2\n NRMLIST=3\n\nclass FILETYPE(Enum):\n BODY=0\n SURFACE_WO_DAMP=1\n SURFACE_W_DAMP=2\n SURFACE_AUTO_DAMP=3\n EXTERNAL = 9\n\n# class Node(object):\n # # __slots__={'pos','id'}\n # def __init__(self,id,pos):\n # self.pos= pos\n # self.id = id\n # self.connected_elem=[]\n # self.connected_edge=[]\n # self.associated_nrml=[]\n # self.coor = None\n \n # def print_node(self):\n # pass\n\n# class Normal(object):\n # # __slots__={'pos','id'}\n # def __init__(self,id,pos):\n # self.pos= pos\n # self.id = id\n # self.associated_node=[]\n \n # def print_nrml(self):\n # pass\n\n# class Coordinate(object):\n # def __init__(self,id,ctype,offset):\n # self.id = id\n # self.type = ctype\n # self.offset = offset\n\n # def print_coor():\n # pass\n\n# ====================================\n# class Element(object):\n # # __slots__={'nl','nrl','etype','kind','id'}\n # def __init__(self,ename):\n # self.tag = tag\n # self.etype = -1#6 for triangle,8 for rectangular,4 for 4 node rect,3 for 3 node triangle\n # self.nl=[]\n # self.nrl=[]\n\n # def print_elem(self,flag=0): # flag =0 for nodelist,flag=1 for nrml list\n # pass\n\n\n#=============================================\n'''\n define the most basic data strucutre for mesh object\n Mesh---------\n nsys : symmetric info /currently not used\n nodes : [dict] contains tuple (x,y,z)\n nodes : [dict] contains tuple (base,x,y,z)\n elems : [dict] tuple('type',node_count,[nodelist],[nrmlist])\n rev_nd : [dict] given key (x,y,z) rounded for __dp, return node id\n rev_nm : refer to above\n edges : [dict] tuple (node id 1,node id 2) 1 is smaller than 2,ordered \n'''\n\nclass _Mesh_core(object):\n def __init__(self,dp=4):\n self.nsys = 0\n\n self.nodes = {}\n self.elems = {}\n self.rev_nd = {}\n self.rev_nm = {}\n self.nrmls ={}\n # self.coors = {}\n self.edges={}\n\n self.__cur_avail_nd_id=1\n self.__cur_avail_el_id=1\n self.__cur_avail_nm_id=1\n self.__dp=dp\n\n def get_precision(self):\n '''\n __dp is used for rounding up, used in rev_nm,rev_nd\n '''\n return self.__dp\n\n def _is_exist_node(self,pos):\n '''\n '''\n assert(len(pos)==3)\n key = (round(pos[0],self.__dp),round(pos[1],self.__dp),round(pos[2],self.__dp))\n return(key in self.rev_nd)\n\n def _is_exist_nrml(self,node_id,pos):\n assert(len(pos)==3)\n key = (node_id,round(pos[0],self.__dp),round(pos[1],self.__dp),round(pos[2],self.__dp))\n return(key in self.rev_nd)\n\n #see if node is on free surface\n def _is_node_fs(self,n,z=0):\n xyz=self.nodes[n]\n if abs(xyz[2]-z)<1e-7:\n return True\n return False\n \n \n \n\n def _redo_bd_nrml(self):\n \"\"\"\n Create nrml for cylinder body (without bottom) ,pointing outward\n -----------------------\n Note: only check those element with 'body' tag\n Note: all elements should be taged 'body'\n \"\"\"\n print (\"Create nrml for cylinder body (without bottom) ,pointing outward\")\n flag = True\n for i in self.elems:\n if self.elems[i][0] != 'body':\n flag = False\n if not flag:\n print (\"Please make sure all elements is defined as 'body'\")\n return\n self.rev_nm={}\n for i in self.nrmls:\n info = self.nrmls[i]\n # xyz = array(self.nodes[info[0]],dtype='float64')\n xyz=np.array(self.nodes[info[0]])\n xyz[2] = 0.\n nrml = xyz/norm(xyz)#normalize vector \n self.nrmls[i] = (info[0],nrml[0],nrml[1],nrml[2])\n nrml = npround(nrml,self.__dp)\n key = (info[0],nrml[0],nrml[1],nrml[2])\n self.rev_nm[key] = i\n return\n\n def _update_all_nrml(self,vector):\n '''\n update all nrmls with given vector\n '''\n print (\"vector will be auto normalized\")\n assert(len(vector)==3)\n self.rev_nm={}\n for i in self.nrmls:\n info = self.nrmls[i]\n xyz = array(vector,dtype='float64')\n nrml = xyz/norm(xyz)#normalize vector \n self.nrmls[i] = (info[0],nrml[0],nrml[1],nrml[2])\n nrml = npround(nrml,self.__dp)\n key = (info[0],nrml[0],nrml[1],nrml[2])\n self.rev_nm[key] = i\n \n\n\n \n\n\n def _rebuild_rev_info(self):\n '''\n assumption: no coincident nodes\n reintialized rev_nd,rev_nm and generate corresponding info based current nodes,nrmls\n '''\n self.rev_nd = {}\n self.rev_nm = {}\n for i in self.nodes:\n xyz = self.nodes[i]\n key = (round(xyz[0],self.__dp),round(xyz[1],self.__dp),round(xyz[2],self.__dp))\n self.rev_nd[key] = i\n for i in self.nrmls:\n info = self.nrmls[i]\n key = (info[0],round(info[1],self.__dp),round(info[2],self.__dp),round(info[3],self.__dp))\n self.rev_nm[key] = i\n\n def _recreate_avail_info(self):\n '''\n recalcuate __cur_avail info for node/norml/element using current elems/nodes/nrmls\n '''\n self.__cur_avail_el_id = len(self.elems)+1\n self.__cur_avail_nd_id = len(self.nodes)+1\n self.__cur_avail_nm_id = len(self.nrmls)+1\n\n\n def _rm_unused_node(self):\n '''\n remove unused node from the model\n '''\n c1 = set()\n l1 =list()\n for i in self.elems:\n tmp = self.elems[i][POS.NODLIST]\n c1.update(tmp)\n for i in self.nodes:\n if not(i in c1):\n l1.append(i)\n for i in l1:\n self.nodes.pop(i)\n\n def _rm_unused_nrml(self):\n '''\n remove unused nrml from the model\n '''\n c1 = set()\n l1 =list()\n for i in self.elems:\n tmp = self.elems[i][POS.NRMLIST]\n c1.update(tmp)\n\n for i in self.nrmls:\n if not(i in c1):\n l1.append(i)\n for i in l1:\n self.nrmls.pop(i)\n\n def _renum_model(self):\n self._rm_unused_node()\n self._rm_unused_nrml()\n # print 'nodes=',len(self.nodes)\n # print 'nrmls=',len(self.nrmls)\n new_nodes={}\n new_nrmls={}\n re_node={}\n re_nrml={}\n ids=1\n ### Assume no coincident nodes/nrmls\n for i in self.nodes:\n new_nodes[ids] = self.nodes[i]\n re_node[i]=ids \n ids+=1\n \n ids=1\n # print re_node\n for i in self.nrmls:\n info=list(self.nrmls[i])\n info[0]=re_node[info[0]]\n new_nrmls[ids] = tuple(info)\n re_nrml[i]=ids \n ids+=1\n\n self.nodes=new_nodes\n self.nrmls=new_nrmls\n\n for i in self.elems:\n info = self.elems[i]\n nlist=info[POS.NODLIST]\n nrmlist=info[POS.NRMLIST] \n tmp1=list()\n tmp2=list()\n for j in range(info[POS.TYPE]):\n tmp1.append(re_node[nlist[j]])\n tmp2.append(re_nrml[nrmlist[j]])\n self.elems[i]=[info[0],info[1],tuple(tmp1),tuple(tmp2)]\n\n self._rebuild_rev_info()\n self._recreate_avail_info()\n\n \n\n\n\n\n def check_coincident_nodes(p=False):\n\n pass\n\n \n def get_edge_info(self):\n '''\n generate edge information using current elem\n '''\n self.edges = {}\n # self._edge_info = True\n for i in self.elems:\n elem_info = self.elems.get(i,None)\n logging.debug(\"process elem\",i)\n nodelist = elem_info[POS.NODLIST]\n nodelist = list(nodelist)\n nodelist.append(nodelist[0]) \n logging.debug(nodelist)\n for i in range(elem_info[POS.TYPE]/2):\n e = tuple(sorted([nodelist[2*i],nodelist[2*i+2]]))\n self.edges[e]=nodelist[2*i+1]\n \n\n def _find_mid_point(self,e):\n ''' \n if edge e exist in current model, return exisit middle node\n if e not exist, create new node, update nodes,rev_nd,edge\n ------------------\n return value is ----1) exisiting node id\n 2) new generated node id\n '''\n \n pos = self.edges.get(e,None)\n dp = self.__dp\n if pos == None:\n # NOTE:establish new middle node, but check coincident node\n n1 = e[0]\n n2 = e[1]\n xyz =[0.,0.,0.]\n for i in range(3):\n xyz[i] = (self.nodes[n1][i]+self.nodes[n2][i])/2.\n key = (round(xyz[0],dp),round(xyz[1],dp),round(xyz[2],dp))\n pos = self.rev_nd.get(key,self.__cur_avail_nd_id)\n if pos == self.__cur_avail_nd_id:\n # TODO update rev_nd \n self.nodes[pos] = tuple(xyz)\n self.rev_nd[key]=pos\n self.edges[e]=pos\n self.__cur_avail_nd_id += 1\n return pos\n \n def horiz_r(self,nid):\n '''\n calculate radius\n --------------\n nid: node id\n '''\n from numpy import sqrt\n n=self.nodes[nid]\n r=sqrt(n[0]**2+n[1]**2)\n return r\n\n def renew_circular_midpoint(self,ctr=[0.,0.]):\n '''\n regenerate midpoints for circular edge if initally set straight\n '''\n from math import acos\n from numpy import sign\n tol = 10e-7\n for e in self.edges:\n n1 = e[0]\n n2 = e[1]\n if abs(self.nodes[n1][2]-self.nodes[n2][2]) < 1e-7:\n r1 = self.horiz_r(n1)\n r2 = self.horiz_r(n2)\n if (abs(r1-r2)<tol):\n n3=self._find_mid_point(e) \n r3= self.horiz_r(n3)\n info=list(self.nodes[n3])\n theta = acos(info[0]/r3)\n info[0] = sign(info[0])*abs(r1*cos(theta))\n info[1] = sign(info[1])*abs(r1*sin(theta))\n self.nodes[n3]=tuple(info)\n\n\n\n ###################################\n # \n # Mesh Operation\n #\n ###################################\n\n\n def shift_mesh(self,vector):\n '''\n Mesh translation\n '''\n assert(len(vector)==3)\n for i in self.nodes:\n info=list(self.nodes[i])\n for j in range(3):\n info[j]+=vector[j]\n self.nodes[i]=tuple(info)\n self._rebuild_rev_info()\n #FIXME rebuild revnodes\n\n def scale_mesh(self,factor):\n '''\n Mesh scale\n '''\n assert(factor>0)\n for i in self.nodes:\n info=list(self.nodes[i])\n for j in range(3):\n info[j]=info[j]*factor\n self.nodes[i]=tuple(info) \n self._rebuild_rev_info\n\n # def mirror_mesh(self,kind=2,base=[0,0,0]):\n # TODO there is direction problem with this function\n # \"\"\"mirror_mesh(kind=2,base=[0,0,0])\n # kind=0,along yz plane\n # kind=1,along xz plane\n # kind=2,along xz plane\n # \"\"\"\n # n = deepcopy(self)\n # for i in n.nodes:\n # info = list(n.nodes[i])\n # info[kind] = 2*base[kind]-info[kind] \n # n.nodes[i]=tuple(info)\n # for i in n.nrmls:\n # info = list(n.nrmls[i])\n # info[kind+1] =-info[kind+1] \n # n.nrmls[i]=tuple(info)\n # n._rebuild_rev_info()\n # return n\n \n # def combine_mesh(m1,m2):\n # '''\n # n = m1.combine_mesh(m1,m2)\n # combine m1,m2 and return the new mesh\n # '''\n # m3 = deepcopy(m1)\n # m3.devour_mesh(m2)\n # return m3\n\n def devour_mesh(self, new_mesh):\n '''\n n.devour_mesh(m1)\n add m1 to exisiting mesh n\n '''\n dp = self.__dp\n renum_node ={}\n for i in new_mesh.nodes:\n xyz = new_mesh.nodes[i]\n key = (round(xyz[0],dp),round(xyz[1],dp),round(xyz[2],dp))\n pos = self.rev_nd.get(key,self.__cur_avail_nd_id)\n renum_node[i]=pos\n if pos == self.__cur_avail_nd_id:\n # create new id, record in rev_nd\n self.nodes[pos] = xyz\n self.rev_nd[key] = pos\n self.__cur_avail_nd_id+=1\n logging.debug(renum_node)\n renum_nrml={}\n for i in new_mesh.nrmls:\n nlist = list(new_mesh.nrmls[i])\n # logging.debug(nlist)\n nlist[0] = renum_node[nlist[0]]\n # logging.debug(nlist)\n key = tuple(nlist)\n pos = self.rev_nm.get(key,self.__cur_avail_nm_id)\n renum_nrml[i] = pos\n if pos == self.__cur_avail_nm_id:\n self.nrmls[pos] = key\n self.rev_nm[key] = pos\n self.__cur_avail_nm_id+=1\n # logging.debug(renum_nrml) \n # NOTE:no element coincidence check\n for i in new_mesh.elems:\n einfo = new_mesh.elems[i]\n nodelist = list(einfo[POS.NODLIST])\n nrmlist = list(einfo[POS.NRMLIST])\n # logging.debug(nrmlist)\n for j in range(einfo[POS.TYPE]):\n nodelist[j] = renum_node[nodelist[j]]\n nrmlist[j] = renum_nrml[nrmlist[j]]\n # logging.debug(nrmlist)\n self.elems[self.__cur_avail_el_id] = [einfo[0],einfo[1],tuple(nodelist),tuple(nrmlist)]\n self.__cur_avail_el_id+=1\n \n \n\n def __test(self):\n print(\"i am here\")\n pass\n\n\n\n ###################################################################\n # #\n # INPUT AND OUTPUT PART OF CLASS #\n # #\n ###################################################################\n def output_mesh(self,path,kind):\n \"\"\"\n output_mesh(path,kind)\n kind = 0, body mesh\n kind = 1, no damp info\n kind = 2, damp info =0,mesh do not need to have damp info setup\n kind = 3, need damp info setup\n currently: only 8-node elem\n \"\"\"\n if kind == FILETYPE.BODY:\n self.__output_as_bd(path)\n if kind == FILETYPE.SURFACE_WO_DAMP:\n self.__output_as_fs(path,0)\n if kind == FILETYPE.SURFACE_W_DAMP:\n self.__output_as_fs(path,2)\n if kind == FILETYPE.SURFACE_AUTO_DAMP:\n self.__output_as_fs(path,1)\n \n def __output_as_fs(self,path,kind=1):\n \"\"\"\n _output_as_fs(path,kind=1)\n kind = 0, no damp info\n kind = 1, damp info =0,mesh do not need to have damp info setup\n kind = 2, need damp info setup\n currently: only 8-node elem\n \"\"\"\n print(\"only 8-node elem has been implemented\")\n \n f_sf = open(path,\"w\")\n f_sf.write('{0:<5d}'.format(self.__cur_avail_el_id-1) \\\n + '{0:<5d}\\n'.format(self.__cur_avail_nd_id-1))\n acc_sf_elem = 1\n for i_elem in self.elems:\n str1 = ''\n str2 = ''\n str3 = ''\n nodelist = self.elems[i_elem][POS.NODLIST]\n for j in range(8):#TODO add triangle support\n \n str1 += '{0:<9.6f} '.format(self.nodes[nodelist[j]][0])\n str2 += '{0:<9.6f} '.format(self.nodes[nodelist[j]][1])\n if kind==2:\n #NOTEME damp info is not defined in this class\n assert(hasattr(self,'damp_info'))\n dval = self.damp_info.get(nodelist[j],0.)\n str3 += '{0:<9.6f} '.format(dval)\n if kind==1:\n str3 += '{0:<9.6f} '.format(0.)\n\n f_sf.write(('{0:<6d} 8\\n').format(acc_sf_elem))\n f_sf.write(str1+'\\n')\n f_sf.write(str2+'\\n')\n if kind:\n f_sf.write(str3+'\\n')\n acc_sf_elem += 1\n f_sf.close()\n\n def __output_as_bd(self,path):\n \"\"\"\n _output_as_bd(path)\n output using body mesh format\n \"\"\"\n f = open(path,\"w\")\n f.write('0\\n') # write isys\n # READ(2,*) NELEMB, NNB, NNBD, IPOL\n f.write(' '.join([' ',str((len(self.elems))),str(len(self.nodes)),str(len(self.nrmls)),'1']))\n f.write(\"\\n\")\n f.write('1 0 0.00 0.00 0.00')# FIXME second maybe 0\n f.write(\"\\n\")\n\n for i_node in self.nodes:\n f.write(('{0:<7d}'.format(i_node)))\n f.write('1 ')\n f.write(' '.join('{0:<9.4f}'.format(i) for i in self.nodes[i_node]))\n f.write(\"\\n\")\n\n for i_norm in self.nrmls:\n f.write(('{0:<7d}'.format(i_norm)))\n f.write('1 ')\n f.write(' '.join('{0:<9.4f}'.format(i) for i in self.nrmls[i_norm][1:4]))\n f.write(\"\\n\")\n\n for i_elem in self.elems:\n f.write(('{0:<7d} 8\\n').format(i_elem))\n #f.write(('{0:<5d}'.format(i_elem)))\n f.write(' '.join(str(i) for i in self.elems[i_elem][POS.NODLIST]))\n f.write(\"\\n\")\n\n for i_elem in self.elems:\n f.write(('{0:<7d} 8\\n').format(i_elem))\n #f.write(('{0:<5d}'.format(i_elem)))\n f.write(' '.join(str(i) for i in self.elems[i_elem][POS.NRMLIST]))\n f.write(\"\\n\")\n\n f.close()\n\n\n ###################################################################\n # #\n # INPUT AND OUTPUT PART OF CLASS #\n # #\n ###################################################################\n def read_mesh(self,path,kind,vector=[0,0,0]):\n '''\n def read_mesh(self,path,kind,vector=[0,0,0])\n \n kind=0 for body\n kind=1 for surface w/o damp info\n kind=2 for surface w damp info\n kind=9 for external 4node data\n vector apply to external only\n\n '''\n if kind == FILETYPE.BODY:\n self.__read_body_fmt(path)\n if kind == FILETYPE.SURFACE_WO_DAMP:\n self.__read_surface_fmt(path,False)\n if kind == FILETYPE.SURFACE_W_DAMP:\n self.__read_surface_fmt(path,True)\n if kind == FILETYPE.EXTERNAL:\n self.__read_external(path,[0,0,0]) \n\n\n def __read_surface_fmt(self,path,flag_damp=True):\n '''\n Suppose surface only have 8 nodes element\n '''\n\n with open(path,\"r\") as f:\n num_elem =[int(i) for i in f.readline().split()][0]\n dp = self.__dp\n for i_elem in range(num_elem):\n tmp = f.readline().split()\n tmp1 = [float(i) for i in f.readline().split()]\n tmp2 = [float(i) for i in f.readline().split()]\n if flag_damp==True:\n tmp3 = [float(i) for i in f.readline().split()]\n\n nodelist = []\n for j in range(8):\n node = (round(tmp1[j],dp),round(tmp2[j],dp),round(0.0,dp))\n if node in self.rev_nd:\n pos = self.rev_nd[node]\n nodelist.append(pos)\n else:\n self.rev_nd[node] = self.__cur_avail_nd_id#create new node in rev dict\n self.nodes[self.__cur_avail_nd_id] = (tmp1[j],tmp2[j],0.0)#create new node in dict_fs_node\n nodelist.append(self.__cur_avail_nd_id)\n if flag_damp:\n self.damp_info[self.__cur_avail_nd_id] = tmp3[j]\n self.__cur_avail_nd_id+=1\n self.elems[self.__cur_avail_el_id] = ['free surface',8,tuple(nodelist),tuple(nodelist)]\n self.__cur_avail_el_id += 1\n for i_node in self.nodes:\n key = (i_node,round(0.0,self.__dp),round(0.0,self.__dp),round(1.,self.__dp))\n self.nrmls[self.__cur_avail_nm_id] = key \n self.rev_nm[key] = self.__cur_avail_nm_id\n self.__cur_avail_nm_id+=1\n \n\n\n def __read_body_fmt(self,path):\n dp = self.__dp\n f = open(path,'r')\n flag =[int(i) for i in f.readline().split()][0]\n # read number of elem,node,normal, axis\n tmp = [int(i) for i in f.readline().split()]\n num_bd_elem = tmp[0]\n num_bd_node = tmp[1]\n num_bd_nrml = tmp[2]\n num_bd_axis = tmp[3]\n ####----------header finished-----\n dict_axis = {}\n for i in range(num_bd_axis):\n tmp = [float(i) for i in f.readline().split()]\n dict_axis[int(tmp[0])] = (int(tmp[1]),tmp[2:5]) \n # first number: index ,sec : 1: polar,0:cartesian ,third-fifth: offset coordinates\n ##--------coordinate info finished----------\n\n renum_bd_node = {}#key is newly assigned id, value is old id\n for i_node in range(num_bd_node): \n tmp = [float(i) for i in f.readline().split()]\n offset = dict_axis[int(tmp[1])][1]\n axis_type = dict_axis[int(tmp[1])][0]\n if(axis_type==0):\n x = tmp[2]+offset[0]\n y = tmp[3]+offset[1]\n if(axis_type==1):\n x = tmp[2]*cos(deg2rad(tmp[3]))+offset[0]\n y = tmp[2]*sin(deg2rad(tmp[3]))+offset[1]\n key = (round(x,dp),round(y,dp),round(tmp[4],dp))\n \n if (key in self.rev_nd):\n pos = self.rev_nd[key]\n renum_bd_node[int(tmp[0])] = pos \n\n else:\n self.rev_nd[key] = self.__cur_avail_nd_id\n renum_bd_node[int(tmp[0])] = self.__cur_avail_nd_id \n self.nodes[self.__cur_avail_nd_id] = (x,y,tmp[4])\n self.__cur_avail_nd_id+=1\n\n\n ####-----------------------------------------\n # processing normal data \n '''\n read in nrml data, saved in tmp database\n no need renumbering, no need create loop-up dic\n '''\n tmp_nrmls={}\n for i_nrml in range(num_bd_nrml):\n tmp = [float(i) for i in f.readline().split()]\n offset = dict_axis[int(tmp[1])][1]\n axis_type = dict_axis[int(tmp[1])][0]\n if(axis_type==0):\n x = tmp[2]+offset[0]\n y = tmp[3]+offset[1]\n if(axis_type==1):\n x = tmp[2]*cos(deg2rad(tmp[3]))+offset[0]\n y = tmp[2]*sin(deg2rad(tmp[3]))+offset[1]\n ######--------------------\n tmp_nrmls[int(tmp[0])] = (x,y,tmp[4]) \n\n ###############NOTE:read in elem info---\n renum_elem={}\n for i_elem in range(num_bd_elem):\n tmp = [int(i) for i in f.readline().split()]\n tmp1 = [int(i) for i in f.readline().split()]\n nodelist = []\n renum_elem[tmp[0]]=self.__cur_avail_el_id\n ## update node number in nodelist\n for k in range(tmp[1]):\n nodelist.append(renum_bd_node[tmp1[k]])\n self.elems[self.__cur_avail_el_id] = ['body',tmp[1],tuple(nodelist)] \n nodelist.append(nodelist[0])#for use(n,n+1) edge pair\n self.__cur_avail_el_id+=1\n\n #===============================================================\n tmp_elem_nrml={}# tmporialy save nrmlist info\n for i_elem in range(num_bd_elem):\n tmp = [int(i) for i in f.readline().split()]\n tmp1 = [int(i) for i in f.readline().split()]\n tmp_elem_nrml[renum_elem[i_elem+1]]=tmp1[0:9] # pair nrmlist with renumber elem id \n \n '''\n for each element, associate node with corresponding nrml\n renumber nrml, find associated note create self.nrmls dict,update\n self.elems with nrmlist\n '''\n renum_nrml = {}\n processed_nrml=[]\n for ie in tmp_elem_nrml:\n nrmlist = tmp_elem_nrml[ie]\n for j in range(len(nrmlist)):\n if nrmlist[j] in processed_nrml:\n nrmlist[j] = renum_nrml[nrmlist[j]]# update id in old nrmlist\n else:\n anode = self.elems[ie][2][j] #associated node = jth node in node list \n cnrml = nrmlist[j]\n pos = tmp_nrmls[cnrml]\n key = (anode,round(pos[0],self.__dp),round(pos[1],self.__dp),round(pos[2],self.__dp))\n \n loc = self.rev_nm.get(key,self.__cur_avail_nm_id)\n renum_nrml[cnrml] = loc# record id change\n #FIXME NO there one to multiple case\n nrmlist[j] = loc# update id in old nrmlist\n processed_nrml.append(cnrml)\n \n if loc == self.__cur_avail_nm_id: \n self.nrmls[self.__cur_avail_nm_id]=key#record new nrml\n self.rev_nm[key] = self.__cur_avail_nm_id#record new key\n self.__cur_avail_nm_id+=1\n else:\n pass\n self.elems[ie].append(tuple(nrmlist))#append updated nrmlist\n\n def __read_external(self,path,vector,z_offset=0.,tag='external'):\n print(\"pls make sure edge info is ready,if you want to use old middle points\")\n assert(isinstance(vector,list))\n assert(len(vector)==3)\n # vector is nrml vector,kind is elem kind('free','body',or user defined)\n \n dp = self.__dp\n # num_add_node = 12\n # num_add_elem = 6\n\n node_set=set()\n \n #TODO complete this, make sure edge_info is generated before read add\n f = open(path,\"r\")\n renum_add_node = {}\n # for i_node in range(num_add_node): \n \n while True:\n tmp = [float(i) for i in f.readline().replace('elem','0').split()]\n if len(tmp) != 4:\n break\n x = tmp[1]\n y = tmp[2]\n z = tmp[3]+z_offset \n key = (round(x,dp),round(y,dp),round(z,dp))\n pos = self.rev_nd.get(key,self.__cur_avail_nd_id)\n renum_add_node[int(tmp[0])] = pos \n node_set.add(pos)\n if pos == self.__cur_avail_nd_id:\n self.rev_nd[key] = pos\n self.nodes[pos] = (x,y,z)\n self.__cur_avail_nd_id+=1\n logging.debug(renum_add_node)\n logging.debug(len(renum_add_node))\n\n flag = True\n tmp = [int(i) for i in tmp]#first line for elem already read\n renum_elem={}\n\n # TODO throw duplicate elems\n # for i_elem in range(num_add_elem):\n while flag == True:\n print(tmp)\n nodelist = []\n ## update node number in nodelist\n for k in range(4):#FIXME add traingle support\n nodelist.append(renum_add_node[tmp[k+2]])\n nodelist.append(0)\n nodelist.append(nodelist[0])\n for e in range(4):#FIXME add triangle support\n edge = tuple(sorted([nodelist[2*e],nodelist[2*e+2]]))\n midp = self._find_mid_point(edge)\n nodelist[2*e+1] = midp\n node_set.add(midp)\n\n # renum_add_node[midp]=midp#NOTE {not work with coincident node for input}this fixed nrml generation problem\n nodelist.pop(8)\n # logging.debug(nodelist)\n # nrmlist = np.array(nodelist)+self.__cur_avail_nm_id-1# nrmlist id shoud be offset according to current num of nrmls\n renum_elem[tmp[0]]=self.__cur_avail_el_id\n self.elems[self.__cur_avail_el_id] = [tag,8,tuple(nodelist)]#,tuple(nrmlist)] \n self.__cur_avail_el_id+=1\n tmp = [int(i) for i in (f.readline().replace('elem','0')).split()]\n if len(tmp)==0:\n flag = False\n\n\n\n \n node_2_nrml={}\n for i_node in node_set :\n key=(i_node,round(vector[0],dp),round(vector[1],dp),round(vector[2],dp))\n # NOTE didn't check coincident nrml\n self.nrmls[self.__cur_avail_nm_id] = key\n self.rev_nm[key] = self.__cur_avail_nm_id\n node_2_nrml[i_node] = self.__cur_avail_nm_id\n\n self.__cur_avail_nm_id+=1\n # logging.debug(renum_elem)\n logging.debug(node_2_nrml)\n for i_elem in renum_elem:\n elem = self.elems[renum_elem[i_elem]]\n nodelist = elem[2]\n nrmlist=[]\n logging.debug(nodelist)\n for j in range(elem[1]):\n logging.debug(j)\n nrmlist.append(node_2_nrml[nodelist[j]])\n self.elems[renum_elem[i_elem]].append(nrmlist)\n\n\n \n #TODO update nrmls and rev_nrmls\n \n\n" }, { "alpha_fraction": 0.49346983432769775, "alphanum_fraction": 0.5005294680595398, "avg_line_length": 36.27631759643555, "blob_id": "5960109edda7cfb347682f91346a43e5dde5af4a", "content_id": "1efccd1e30f781d51dd09c436a6b5529ec01a9f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2833, "license_type": "no_license", "max_line_length": 73, "num_lines": 76, "path": "/dutwav/rgd_body.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "class Rigid_Body(object):\n \"\"\"\n class for store mass information\n \"\"\"\n def __init__(self):\n self._flag = -1\n self.rot_ctr = None\n self.mass_ctr = None\n self.water_plane_info = None\n self.displacement = None\n self.disp_ctr = None\n self.mass = None\n self.mass_mtx = None\n self.hyres_mtx = None\n self.lin_damp_mtx = None\n self.quad_damp_mtx = None\n self.stif_mtx = None\n self.info = {}\n\n def read_mass_info(self,path):\n import numpy as np\n with open(path,\"r\") as f:\n tmp = f.readline().strip()\n flag =[int(i) for i in f.readline().split()][0]\n self.info[tmp] = flag\n self._flag = flag\n\n tmp = f.readline().strip()\n rotation_ctr =[float(i) for i in f.readline().split()]\n self.info[tmp] = rotation_ctr\n self.rot_ctr = np.array(rotation_ctr)\n\n tmp = f.readline().strip()\n mass_ctr =[float(i) for i in f.readline().split()]\n self.info[tmp] = mass_ctr\n self.mass_ctr = np.array(mass_ctr)\n\n tmp = f.readline().strip()\n water_plane_info =[float(i) for i in f.readline().split()]\n self.info[tmp] = water_plane_info\n self.water_plane_info = water_plane_info\n\n tmp = f.readline().strip()\n displace =[float(i) for i in f.readline().split()]\n self.info['displacement/volume'] = displace[0]\n self.info['displacement/buoy center'] = displace[1:4]\n self.displacement = displace[0]\n self.disp_ctr = np.array(displace[1:4])\n\n tmp = f.readline().strip()\n mass =[float(i) for i in f.readline().split()][0]\n self.info['mass'] = mass\n self.mass = mass\n \n mat_mass = []\n for i in range(3):\n mat_mass.append([float(i) for i in f.readline().split()])\n mat_mass = np.array(mat_mass)\n self.info['mass matrix'] = mat_mass\n self.mass_mtx = mat_mass\n mat_list = []\n for j in range(4):\n tmp = f.readline()\n mat = []\n for i in range(6):\n mat.append([float(i) for i in f.readline().split()])\n mat = np.array(mat)\n mat_list.append(mat)\n self.info['hydro_storing matrix'] = mat_list[0]\n self.info['stiffness matrix'] = mat_list[1]\n self.info['linear viscous damping matrix'] = mat_list[2]\n self.info['quadratic viscous damping matrix'] = mat_list[3]\n self.hyres_mtx = mat_list[0]\n self.stif_mtx = mat_list[1]\n self.lin_damp_mtx = mat_list[2]\n self.quad_damp_mtx = mat_list[3]\n" }, { "alpha_fraction": 0.5668604373931885, "alphanum_fraction": 0.5726743936538696, "avg_line_length": 30.090909957885742, "blob_id": "2f238ac07d1aa21e3c94762032b9b17217b20300", "content_id": "698d3978a550166cece8f99f052a8f2e58d562b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 64, "num_lines": 11, "path": "/setup.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(name='dutwav',version='1.2',\n description=\"pre-processing tool for DUTWAV\",\n url='',\n author ='frank gao',\n author_email='[email protected]',\n include_package_data = True,\n license='MIT',\n packages=['dutwav','dutwav.analytical'],#,'wave','mass']\n zip_safe=False)\n\n\n" }, { "alpha_fraction": 0.49538910388946533, "alphanum_fraction": 0.5039361119270325, "avg_line_length": 31.327272415161133, "blob_id": "c6b4bc8dd47085ec86d61b628a108f3c236106f2", "content_id": "025ff1d6e660bb1905a84e2045aea84d2f4aa6a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8892, "license_type": "no_license", "max_line_length": 76, "num_lines": 275, "path": "/dutwav/mesh.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "import logging\nfrom dutwav.__mesh_core import *\nfrom dutwav.__mesh_core import _Mesh_core\nfrom dutwav.draw import DrawMesh\nfrom numpy import sqrt,round\n\n\nclass Mesh(_Mesh_core):\n def __init__(self,dp=4):\n _Mesh_core.__init__(self,dp)\n # self._num_fs_elem = 0\n # self._num_bd_elem = 0\n self.damp_info={}\n self.__rdrawObj=DrawMesh(self)\n # self._zonelist=[]\n # self._waterline=[]\n\n # self.xyz=None\n # self.dxyz=None\n # self.ncn=None\n\n self._waterline={}\n\n #\n def test_dp(self):\n print(self.__cur_avail_nd_id)\n\n # @func : update nrml vecotr for same tag group\n def _update_tag_nrml(self,taglist,vector):\n assert(len(vector)==3)\n nset=set()\n for i in self.elems:\n if self.elems[i][POS.TAG] in taglist:\n info=self.elems[i][POS.NRMLIST]\n for j in info:\n nset.add(j)\n print(nset )\n for i in nset:\n info = list(self.nrmls[i][0:1])+vector\n print(info)\n self.nrmls[i] = info \n self._rebuild_rev_info() \n\n # @func : reverse nrml direction for whole model\n def _reverse_nrml(self):\n for i in self.nrmls:\n info=list(self.nrmls[i])\n for j in [1,2,3]:\n info[j] = -info[j]\n self.nrmls[i]=tuple(info)\n\n # @func : give surface elems tag name 'surface'\n def _mark_surface_elems(self):\n self._mark_elems_at_z(0.0,'surface')\n\n # @func : mark element [pos]th position around value [v] with name [tag]\n def _mark_elems_at(self,pos,v,tag='marked'):\n s_node = set()\n s_elem = set()\n\n for i in self.nodes:\n if(abs(self.nodes[i][pos]-v)<1e-5):\n s_node.add(i)\n for i in self.elems:\n nodelist = set(self.elems[i][POS.NODLIST]) \n if nodelist.issubset(s_node):\n s_elem.add(i)\n for i in s_elem:\n self.elems[i][0] = tag\n\n # @func : mark element with veritcal pos around [z] using name [tag]\n def _mark_elems_at_z(self,z,tag='marked'):\n s_node = set()\n s_elem = set()\n\n for i in self.nodes:\n if(abs(self.nodes[i][2]-z)<1e-5):\n s_node.add(i)\n for i in self.elems:\n nodelist = set(self.elems[i][POS.NODLIST]) \n if nodelist.issubset(s_node):\n s_elem.add(i)\n for i in s_elem:\n self.elems[i][0] = tag\n\n # @func : list all nodes btw radius [rlow] and [rhigh]\n def _list_node_withr(self,rlow=0.,rhigh=1.):\n surface_node=set()\n for i in self.nodes:\n r = sqrt((self.nodes[i][1])**2+(self.nodes[i][0])**2)\n if(r<rhigh) and (r>rlow):\n surface_node.add(i)\n return(list(surface_node)) \n\n\n # @func : mark elems btw radius [rlow] and [rhigh]\n def _mark_elem_withr(self,rlow=0,rhigh=1,tag='marked'):\n surface_node = set(self._list_node_withr(rlow,rhigh))\n surface_elem = set()\n # for i in self.nodes:\n # r = sqrt((self.nodes[i][1])**2+(self.nodes[i][0])**2)\n # if(r<rhigh) and (r>rlow):\n # surface_node.add(i)\n for i in self.elems:\n nodelist = set(self.elems[i][POS.NODLIST]) \n if nodelist.issubset(surface_node):\n surface_elem.add(i)\n\n for i in surface_elem:\n self.elems[i][0] = tag\n\n # @func: change groups in list [tag_list] to name [new_tag]\n def _update_tag(self,tag_list,new_tag):\n assert(isinstance(tag_list,list))\n assert(isinstance(new_tag,str))\n for i in self.elems:\n if self.elems[i][0] in tag_list:\n self.elems[i][0] = new_tag\n\n\n # @func: count elem number in each tag group\n def _count_elem(self):\n result={}\n for i in self.elems:\n key = self.elems[i][0]\n result[key] = result.get(key,0)+1\n return result \n\n #===================================================\n #===================================================\n\n # @func: given damp function [f], define damp value for the surface nodes\n def _generate_damp_info(self,f=None):\n surface_node = set()\n for i in self.nodes:\n if(abs(self.nodes[i][2])<1e-5):\n surface_node.add(i)\n for i in surface_node:\n r = sqrt(self.nodes[i][0]**2+self.nodes[i][1]**2)\n if f:\n self.damp_info[i] = f(r)\n if not f:\n self.damp_info[i] = 0.0\n\n\n # @func: get set of waterline nodes\n def _get_waterline_node(self):\n print(\"elements in mesh must have well-defined tag\\n\\\n only 'body' elements will be looked into\")\n nodes=set()\n for i in self.elems:\n info = self.elems[i]\n if info[0]=='body':\n nodelist = info[POS.NODLIST]\n for j in range(info[POS.TYPE]):\n if self._is_node_fs(nodelist[j]):\n nodes.add(nodelist[j])\n self._init_waterline(nodes)\n return(nodes) \n\n def _get_btm_node(self,z=-1):\n print(\"elements in mesh must have well-defined tag\\n\\\n only 'body' elements will be looked into\")\n nodes=set()\n for i in self.elems:\n info = self.elems[i]\n if info[0]=='body':\n nodelist = info[POS.NODLIST]\n for j in range(info[POS.TYPE]):\n xyz=self.nodes[nodelist[j]]\n if (abs(xyz[2]-z)<1e-5):\n nodes.add(nodelist[j])\n return(nodes) \n\n\n def _init_waterline(self,wset):\n for i in wset:\n key=round(list(self.nodes[i]),self.get_precision())\n self._waterline[tuple(key)] = None\n\n\n #===================================================\n #===================================================\n\n def validate_mesh(self):\n \"\"\"\n first n node must be surface node\n first elems must be surface elems\n check coincident nodes\n check coincident nrmls\n check coincident elems\n \"\"\"\n pass \n\n #===================================================\n #===================================================\n\n def draw_model(self,points=[]):\n self.__rdrawObj.draw_model(points=points)\n\n def draw_lines(self,p=[],points=[]):\n self.__rdrawObj.draw_lines(p,points=points)\n\n def tecplt_value(self,path,value,soltime=1,kind =1):\n # if kind==2:\n # self.__rdrawObj.tecplt_value_poly(path,value)\n if kind==1:\n self.__rdrawObj.tecplt_value_quad(path,value,soltime)\n if kind==2:\n self.__rdrawObj.tecplt_value_poly_2(path,value)\n\n def tecplt_nrml(self,path,kind =1):\n if kind==2:\n # quad, node numbering, has nrml info\n self.__rdrawObj.tecplt_quad(path)\n if kind==1:\n #use nrml numbering, has nrml output\n self.__rdrawObj.tecplt_poly_3(path)\n if kind==3:\n #use node numbering, no nrml output\n self.__rdrawObj.tecplt_poly_2(path)\n# if kind==4:\n # #use node numbering, no nrml output\n # self.__rdrawObj.tecplt_poly_3(path)\n\n\n\n #===================================================\n #===================================================\n def extract_mesh(self,criteria):\n \"\"\"\n new_mesh = extract_mesh([taglist])\n extract a new mesh from elements marked in taglist\n \"\"\"\n assert(isinstance(criteria,list))\n # super class private cannot be accessed directly\n n = Mesh(self.get_precision())\n s_elem=set()\n s_node=set()\n s_nrml=set()\n # Gather all nrmls,nodes and elems from critia\n for e in self.elems:\n if self.elems[e][POS.TAG] in criteria:\n s_elem.add(e)\n s_node=s_node.union(set(self.elems[e][POS.NODLIST]))\n s_nrml=s_nrml.union(set(self.elems[e][POS.NRMLIST]))\n\n s_node = sorted(list(s_node))\n renum_node = {}\n for i in range(len(s_node)):\n n.nodes[i+1] = self.nodes[s_node[i]]\n renum_node[s_node[i]]=i+1\n # ============================ \n s_nrml = sorted(list(s_nrml))\n renum_nrml={}\n for i in range(len(s_nrml)):\n info = list(self.nrmls[s_nrml[i]])\n info[0] = renum_node[info[0]]\n n.nrmls[i+1] = info\n renum_nrml[s_nrml[i]]=i+1\n #\n s_elem = sorted(list(s_elem))\n for i in range(len(s_elem)):\n info = self.elems[s_elem[i]]\n nodelist = list(info[2])\n nrmlist = list(info[3])\n for j in range(info[1]):\n nodelist[j] = renum_node[nodelist[j]]\n nrmlist[j] = renum_nrml[nrmlist[j]]\n n.elems[i+1] = ['extract',info[1],tuple(nodelist),tuple(nrmlist)]\n\n n._rebuild_rev_info()\n n._recreate_avail_info()\n\n return n\n\n\n" }, { "alpha_fraction": 0.4050244987010956, "alphanum_fraction": 0.4577205777168274, "avg_line_length": 29.203702926635742, "blob_id": "68bdbaddcea09c7aba9ca458510d2e572ed9e0b8", "content_id": "3b1ff7099e7a2ef208ae3d4ccaca0dea38b3cbfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1632, "license_type": "no_license", "max_line_length": 136, "num_lines": 54, "path": "/dutwav/wave.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "from numpy import sqrt\nclass Wave(object):\n import numpy as np\n k = np.nan\n freq = np.nan\n wav_len = None\n A = np.nan\n beta = None\n d = None \n\n def compute_wav_num(sigma,h):\n if (sigma < 0):\n print(\"Error,in compute_wav_num, wave_frequency = \", sigma)\n else:\n if (h > 0):\n B = _g*h\n Y = sigma**2*h/_g\n A = 1.0/(1.0+Y*(0.66667+Y*(0.35550+Y*(0.16084+Y*(0.063201+Y*(0.02174+Y*(0.00654+Y*(0.00171+Y*(0.00039+Y*0.00011)))))))))\n _wave_celerity=SQRT(B/(Y+A))\n _wave_num = sigma/_wave_celerity\n else:\n if(h < 0):\n _wav_num = sigma**2/_g\n return _wav_num\n\n def read_data(self,path):\n G = 9.807\n\n with open(path,\"r\") as f:\n data1 = [int(i) for i in f.readline().split()]\n data2 = [float(i) for i in f.readline().split()]\n \n self.d = data2[0]\n self.A = data2[1]\n self.beta = data2[3]\n\n if (data1[1] ==0):\n self.k = data2[2]\n if self.d < 0:\n self.freq = sqrt(G*self.k)\n else:\n self.freq = sqrt(G*self.k*tanh(self.k*self.d))\n else:\n self.wave_len = data2[2]\n self.k = compute_wav_num(self.freq,self.d)\n\n # self.A = data2[1]\n @property\n def info(self):\n print(\"wave number: \",self.k,\"\\n\")\n print(\"wave frequency: \",self.freq,\"\\n\")\n print(\"wave amplitude: \",self.A,\"\\n\")\n print(\"water depth: \",self.d,\"\\n\")\n print(\"wave angle:\",self.beta,\"\\n\")\n\n" }, { "alpha_fraction": 0.49480170011520386, "alphanum_fraction": 0.5117443203926086, "avg_line_length": 26.336841583251953, "blob_id": "30b5cb43078f387146e2a4303d309444324e234e", "content_id": "4bec327d7283353162b6b44b91c1b6594b13066e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2597, "license_type": "no_license", "max_line_length": 54, "num_lines": 95, "path": "/dutwav/vtk.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "from dutwav.mesh import Mesh\nfrom pyvtk import *\nfrom dutwav.__mesh_core import POS\nfrom copy import copy\ndef MeshtoVTK(m,path):\n '''\n draw the mesh in vtk format\n ---------------------\n Note: triangle support added\n '''\n assert(isinstance(m,Mesh))\n points=[]\n polygons=[]\n for i in m.nodes:\n info = m.nodes[i]\n points.append(list(info))\n for i in m.elems.keys():\n n = m.elems[i][POS.TYPE]\n nlist = list(m.elems[i][POS.NODLIST])\n if(n==6):\n tmp=copy(nlist)\n nlist[2-1]=tmp[4-1]\n nlist[3-1]=tmp[2-1]\n nlist[4-1]=tmp[5-1]\n nlist[5-1]=tmp[3-1] \n for j in range(len(nlist)):\n nlist[j]=nlist[j]-1\n polygons.append(nlist)\n s=PolyData(points=points,polygons=polygons)\n n=[]\n\n# for i in m.nodes:\n # info = m.nodes[i]\n # n.append(list(info[1:]))\n # pointdata=PointData(Normals(n,name='normal'))\n # vtk=VtkData(s,pointdata)\n vtk=VtkData(s)\n vtk.tofile(path,'ascii')\n\ndef ValuetoVTK(m,name,value):\n '''\n draw the given value on the mesh in vtk format\n -------------------------\n Note: value should be a dict \n Note: value is used to replace z \n '''\n assert(isinstance(value,dict))\n points=[]\n polygons=[]\n for i in m.nodes:\n info = list(m.nodes[i])\n # replace z value with wave elevation\n info[2] = value[i] \n points.append(info)\n\n for i in m.elems.keys():\n n = m.elems[i][POS.TYPE]\n nlist = list(m.elems[i][POS.NODLIST])\n if(n==6):\n tmp=copy(nlist)\n nlist[2-1]=tmp[4-1]\n nlist[3-1]=tmp[2-1]\n nlist[4-1]=tmp[5-1]\n nlist[5-1]=tmp[3-1] \n for j in range(len(nlist)):\n nlist[j]=nlist[j]-1\n polygons.append(nlist)\n s=PolyData(points=points,polygons=polygons)\n vtk=VtkData(s)\n vtk.tofile(name,'ascii')\n\n\ndef waveVtk(m,path,fi):\n \"\"\"\n waveVtk(m,path,fi)\n\n m: mesh\n path : output vtk name\n fi: input value file\n ----------------------\n Note : used as a extension for ValuetoVTK\n Note : second column in fi is used for output\n \"\"\"\n assert(isinstance(m,Mesh))\n # assert(len(m.nodes)==len(value))\n with open(fi,\"rb\") as f:\n r = f.readlines()\n r1={}\n assert(len(m.nodes)==len(r))\n for i in range(len(r)):\n tmp=[float(j) for j in r[i].split()]\n #tmp[0] is node id\n r1[i+1]=tmp[1]\n\n ValuetoVTK(m,path,r1)\n" }, { "alpha_fraction": 0.4644595980644226, "alphanum_fraction": 0.524829626083374, "avg_line_length": 29.55223846435547, "blob_id": "f4bbee777cc6dcd63f76ff6b60437ad037bfb5d2", "content_id": "c5363752cf8cc46a2cbf1249bc956f262563e49a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2054, "license_type": "no_license", "max_line_length": 59, "num_lines": 67, "path": "/dutwav/box.py", "repo_name": "gaofrank1986/dutwav", "src_encoding": "UTF-8", "text": "\nfrom dutwav.mesh import Mesh\nfrom numpy import sign\n\nclass Box(Mesh):\n def __init__(self):\n Mesh.__init__(self)\n self.x1=-0.5\n self.x2=0.5\n self.y1=0.5\n self.y2=-0.5\n self.z=-1.\n\n def box_body_renrml(self):\n \n self._mark_elems_at(0,self.x1,'x1')\n self._mark_elems_at(0,self.x2,'x2')\n self._mark_elems_at(1,self.y1,'y1')\n self._mark_elems_at(1,self.y2,'y2')\n self._mark_elems_at(2,self.z,'z')\n mx1=self.extract_mesh(['x1'])\n mx2=self.extract_mesh(['x2'])\n my2=self.extract_mesh(['y2'])\n my1=self.extract_mesh(['y1'])\n mz=self.extract_mesh(['z'])\n mx1._update_all_nrml([sign(self.x1),0.,0.0])\n mx2._update_all_nrml([sign(self.x2),0.,0.0])\n my1._update_all_nrml([0.,sign(self.y1),0.0])\n my2._update_all_nrml([0.,sign(self.y2),0.0])\n mz._update_all_nrml([0.,0.0,sign(self.z)])\n mx1.devour_mesh(mx2)\n mx1.devour_mesh(my2)\n mx1.devour_mesh(my1)\n mx1.devour_mesh(mz)\n return mx1\n\n\nclass Cylinder(Mesh):\n def __init__(self):\n Mesh.__init__(self)\n self.z1=-1\n self.z2=-6\n self.r1=1\n self.r2=8\n\n def cylinder_nrml(self):\n\n self._mark_elems_at(2,self.z1,'z1')\n self._mark_elems_at(2,self.z2,'z2')\n self._mark_elem_withr(self.r1-0.1,self.r1+0.1,'r1')\n self._mark_elem_withr(self.r2-0.5,self.r2+0.5,'r2')\n self._count_elem()\n mz1=self.extract_mesh(['z1'])\n mz2=self.extract_mesh(['z2'])\n mr2=self.extract_mesh(['r2'])\n # mr2.draw_model()\n mr1=self.extract_mesh(['r1'])\n mr1._update_tag(['extract'],'body')\n mr2._update_tag(['extract'],'body')\n mr1._redo_bd_nrml()\n mr1._reverse_nrml()\n mr2._redo_bd_nrml()\n mz1._update_all_nrml([0.,0.0,-sign(self.z1)])\n mz2._update_all_nrml([0.,0.0,sign(self.z1)])\n mr2.devour_mesh(mz2)\n mr2.devour_mesh(mr1)\n mr2.devour_mesh(mz1)\n return mr2\n\n\n\n\n\n\n" } ]
17
nmcveity/QR-barcode-decorator
https://github.com/nmcveity/QR-barcode-decorator
a020e9ae291ae8c9af5edea03bf2cc29d21df0b0
b609c4db03117f6454d8889680cb2322fa7210c3
181b2ac153a3bee2070e78d16a8cfc51403086d5
refs/heads/master
2020-05-18T12:30:35.455011
2011-02-11T04:24:00
2011-02-11T04:24:00
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6509703397750854, "alphanum_fraction": 0.6709474921226501, "avg_line_length": 35.45833206176758, "blob_id": "86a96d9c0ec99a225257eefc960a4be9e5a01534", "content_id": "470a05aee62a001ad9cbbbd6f0fdd8e0c422f13b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3504, "license_type": "no_license", "max_line_length": 129, "num_lines": 96, "path": "/qrgen.py", "repo_name": "nmcveity/QR-barcode-decorator", "src_encoding": "UTF-8", "text": "import PIL\nimport PIL.Image\nimport random\nimport urllib\nimport cStringIO\n\ndef encode(data):\n\tdata = cStringIO.StringIO(urllib.urlopen(\"http://chart.apis.google.com/chart?chs=200x200&cht=qr&chl=%s\" % str(data)).read())\n\t\n\timage = PIL.Image.open(data)\n#\timage.save(\"fetched.png\")\n\t\n\t## This function is a little hacky. To extract the module bitmap from the qr code generated by google\n\t## we need to crop off the outer blank area AND calculate the size of each module in pixels. To \n\t## calculate the crop area we look for the first black pixel in the image and count the number of \n\t## black pixels in a row. The coordinate of the first black pixel tells us what we can crop off the\n\t## image AND the size of the first run of black pixels (which is 7 modules wide - as per standard) can\n\t## tell us the module size.\n\t##\n\t## http://en.wikipedia.org/wiki/QR_Code (see Overview)\n\t\n\tdef find_code(image):\n\t\tfor y in range(0, image.size[1]):\n\t\t\tfor x in range(0, image.size[0]):\n\t\t\t\tdata = image.getpixel((x, y))\n\t\t\t\tif data[0] == 0:\n\t\t\t\t\tlen = 0\n\t\t\t\t\ti = x\n\t\t\t\t\t\n\t\t\t\t\twhile data[0] == 0:\n\t\t\t\t\t\ti = i + 1\n\t\t\t\t\t\tlen = len + 1\n\t\t\t\t\t\tdata = image.getpixel((i, y))\n\t\t\t\t\t\t\n\t\t\t\t\treturn x, y, len / 7\n\t\n\tleft, top, module_size = find_code(image)\n\t\n\timage = image.crop((left, top, image.size[0] - left, image.size[1] - top))\n\timage = image.resize((image.size[0] / module_size, image.size[1] / module_size))\n#\timage.save(\"small.png\")\n\t\n\treturn image\n\t\ndef decorate(modules_tiles, code):\n\t# we take the module size (in pixels) for our output image based upon the largest input image. Note\n\t# you will get the best results if all images are the same size\n\twidths = [image.size[0] for image in modules_tiles]\n\theights = [image.size[1] for image in modules_tiles]\n\t\t\n\tmax_width = max(widths)\n\tmax_height = max(heights)\n\t\n\t# note that the image is slightly larger, the convention is to leave a 4 module boundary around\n\t# the image without noise - it makes it easier to read.\n\tout = PIL.Image.new(\"RGBA\", (max_width*(code.size[0]+8), max_height*(code.size[1]+8)), (255,255,255,255))\n\t\n\tdef is_light(val):\n\t\treturn val[0] > 127 and val[1] > 127 and val[2] > 127\n\t\n\tfor x in range(0, code.size[0]):\n\t\tfor y in range(0, code.size[1]):\n\t\t\t\tif not is_light(code.getpixel((x, y))):\n\t\t\t\t\tgem = random.choice(modules_tiles)\n\t\t\t\t\tout.paste(gem, ((x+4)*max_width, (y+4)*max_height), gem)\n\n\treturn out\n\nif __name__ == \"__main__\":\n\tfrom optparse import OptionParser\n\t\n\tparser = OptionParser()\n\tparser.add_option(\"-i\", \"--image\", dest=\"images\", help=\"FILES to use in the QR code\", metavar=\"FILES\", action=\"append\")\n\tparser.add_option(\"-d\", \"--data\", dest=\"data\", help=\"Data to encode in qr code\", action=\"store\")\n\tparser.add_option(\"-o\", \"--output\", dest=\"output\", help=\"FILE to write generated qr code into\", action=\"store\")\n\tparser.add_option(\"-s\", \"--scale\", dest=\"scale\", type=\"int\", help=\"Percent the scale the resulting image by\", action=\"store\")\n\n\t(options, args) = parser.parse_args()\n\t\n\tif options.images is None:\n\t\tparser.error(\"You need to specify at least one image\")\n\n\tif options.data is None:\n\t\tparser.error(\"You need to the data to encode\")\n\n\tif options.output is None:\n\t\tparser.error(\"You need to specify the output file\")\n\n\ttiles = [PIL.Image.open(x) for x in options.images]\n\t\n\timg = decorate(tiles, encode(options.data))\n\t\n\tif options.scale is not None:\n\t\timg = img.resize((int(img.size[0] * (options.scale / 100.0)), int(img.size[1] * (options.scale / 100.0))), PIL.Image.ANTIALIAS)\n\t\n\timg.save(options.output)\n\n\n\n\n" } ]
1
PacoMtz1999/proyecto-django
https://github.com/PacoMtz1999/proyecto-django
dc8cf59b6a4ee520138dcbb75cbe8a3b302aa345
bcd00e6ada735a90a856b19e8eaa9aec679d3916
8ff0011813fe645bfa80fe619e5906e70484da5d
refs/heads/main
2023-07-12T13:05:19.859850
2021-08-18T19:23:01
2021-08-18T19:23:01
395,027,069
0
0
null
2021-08-11T15:00:27
2021-08-11T17:13:05
2021-08-18T19:23:01
JavaScript
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 11.5, "blob_id": "e264415dd6e6985cefc206664224b549e42af8df", "content_id": "058806885e32d8963e4b247e8e4a956fa196b3a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 17, "num_lines": 2, "path": "/README.md", "repo_name": "PacoMtz1999/proyecto-django", "src_encoding": "UTF-8", "text": "# proyecto-django\nPrueba\n" }, { "alpha_fraction": 0.639072835445404, "alphanum_fraction": 0.6396247148513794, "avg_line_length": 27.328125, "blob_id": "6c006ee17ee170090f3f94704909ecb6821feba6", "content_id": "25fad0b8eb97fb31fe4c7e6bd8aaea6661ef6ce9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1813, "license_type": "no_license", "max_line_length": 73, "num_lines": 64, "path": "/prueba/registros/admin.py", "repo_name": "PacoMtz1999/proyecto-django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Alumnos\nfrom .models import Comentario\nfrom .models import ComentarioContacto\n\n# Register your models here.\nclass AdministrarModelo(admin.ModelAdmin):\n readonly_fields = ('created', 'updated')\n list_display = ('matricula', 'nombre', 'carrera', 'turno', 'created')\n search_fields = ('matricula', 'nombre', 'carrera', 'turno')\n date_hierarchy = 'created'\n list_filter = ('carrera', 'turno')\n\n def get_readonly_fields(self, request, obj=None):\n if request.user.groups.filter(name=\"Usuarios\").exists():\n return('created', 'updated', 'matricula', 'carrera', 'turno')\n else:\n return('created', 'updated')\n\nadmin.site.register(Alumnos, AdministrarModelo)\n\n\nclass AdministrarComentarios(admin.ModelAdmin):\n list_display = ('id', 'coment')\n search_fields = ('id', 'created')\n date_hierarchy = 'created'\n list_filter = ('created', 'id')\n\nadmin.site.register(Comentario, AdministrarComentarios)\n\n\nclass AdministrarComentariosContacto(admin.ModelAdmin):\n list_display = ('id', 'mensaje')\n search_fields = ('id', 'created')\n date_hierarchy = 'created'\n list_filter = ('created', 'id')\n\nadmin.site.register(ComentarioContacto, AdministrarComentariosContacto)\n\n\n\n\n\n\n\"\"\" #Paginación\n list_per_page = 3\n \n #Desplegar opciones avanzadas\n fieldsets = (\n (None, {\n 'fields' : ('nombre',)\n }),\n ('Opciones avanzadas', {\n 'classes' : ('collapse', 'wide', 'extrapretty'),\n 'fields': ('matricula', 'carrera', 'turno', 'created')\n })\n )\n\n #Columna personalizada\n def nombreMayus (self, obj):\n return obj.turno.upper()\n\n #Cambiar nombre de la columna\n nombreMayus.short_description='Nombre en mayusculas' \"\"\"" } ]
2
vincegarciausn/automating-aws-with-python
https://github.com/vincegarciausn/automating-aws-with-python
65cdfa86397a0de3b1a0e13fc081f111438cdb1b
592ac62a5a4a7a73e4d47ad9bffe1e0f9d3aacec
b2d8aca0c00c4cc197e6f6ec569bbb059b400270
refs/heads/master
2022-12-10T17:58:07.275219
2020-01-17T22:15:42
2020-01-17T22:15:42
223,051,991
0
0
null
2019-11-21T00:14:24
2020-01-17T22:16:06
2022-12-08T03:26:17
Python
[ { "alpha_fraction": 0.7651663422584534, "alphanum_fraction": 0.7788649797439575, "avg_line_length": 24.549999237060547, "blob_id": "9b4e30d6ebfe51ce15a97f8d3eaff1260ced4cb7", "content_id": "5eb9d1080ec73d43edeb57562ddc356ab93714e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 511, "license_type": "no_license", "max_line_length": 125, "num_lines": 20, "path": "/README.md", "repo_name": "vincegarciausn/automating-aws-with-python", "src_encoding": "UTF-8", "text": "# automating-aws-with-python\n\nRepository for the A Cloud Guru course *Automating AWS with Python*\n\n## 01-webotron\n\nwebotron is a script that will sync a local directory to an S3 bucke, and optionally configure Route53 and cloudfront as well\n\n###Features\n\nweobtron currently has the following features\n- List buckets\n- List bucket objects\n- Create and set up bucket for website\n- sync directory tree to bucket\n- Set AWS profile with --profile <profileName>\n\n## 02-notofon started\n\nGet langauge from a cloud guru\n" }, { "alpha_fraction": 0.7903226017951965, "alphanum_fraction": 0.7983871102333069, "avg_line_length": 46.69230651855469, "blob_id": "4d0ce663e26c9c80b69a82cbd1a266affe03175a", "content_id": "006979f6e67964f699bdf8d7e2bb66e55123ee5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 620, "license_type": "no_license", "max_line_length": 95, "num_lines": 13, "path": "/autoscale_example.py", "repo_name": "vincegarciausn/automating-aws-with-python", "src_encoding": "UTF-8", "text": "# coding: utf-8\ninmport boto3\nimport boto3\nsession = boto3.session(profile_name='automate')\nsession = boto3.Session(profile_name='automate')\nas_client = session.client{'autoscaling')\nas_client = session.client('autoscaling')\nas_client.decribe_auto-scaling_groups()\nas_client.describe_auto_scaling_groups()\nas_client.describe_policies()\nas_client.execute_policy(AutoScalingGroupName='notifon example group', PolicyName='scale down')\nas_client.execute_policy(AutoScalingGroupName='notifon example group', PolicyName='scale up')\nas_client.execute_policy(AutoScalingGroupName='notifon example group', PolicyName='scale up')\n" } ]
2
Simon-Hostettler/DiceImageGenerator
https://github.com/Simon-Hostettler/DiceImageGenerator
ebec7afccd1c79b7ad4afbc7310bfdea545facc9
9781d623a45028b8e2f84033ed8c3b5c4934e7d7
d61f5285d052c8ea6dc252c4b76f4930ef9bb440
refs/heads/master
2022-12-25T09:46:34.348649
2020-10-09T15:25:40
2020-10-09T15:25:40
302,327,544
8
0
null
2020-10-08T12:07:04
2020-10-09T07:59:42
2020-10-09T08:03:52
Python
[ { "alpha_fraction": 0.5559511780738831, "alphanum_fraction": 0.5757883787155151, "avg_line_length": 32.89655303955078, "blob_id": "216a8d92c8ed633e1a29ab26b9720b8cf1caeaf3", "content_id": "52b3d700dde26183bfc72351fade625aaf216418", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1966, "license_type": "permissive", "max_line_length": 94, "num_lines": 58, "path": "/main.py", "repo_name": "Simon-Hostettler/DiceImageGenerator", "src_encoding": "UTF-8", "text": "from tkinter.filedialog import askopenfilename\nfrom PIL import Image\nimport numpy as np\nimport sys\n\nNEW_IMG_HEIGHT = 100\nNEW_IMG_NAME = \"DiceImage.jpg\"\nTEXT_FILE_NAME = \"DiceArrangement.txt\"\n\ndice = []\nfor x in range(0, 6):\n dice.append(Image.open(sys.path[0] + \"/Images/dice\" + str(x+1) + \".png\").resize((32, 32)))\n\n\ndef convert_to_dice_image(filename):\n img = Image.open(filename)\n gray_image = img.convert('L')\n width, height = img.size\n relative_size = width / height\n small_img = gray_image.resize((int(NEW_IMG_HEIGHT * relative_size), NEW_IMG_HEIGHT))\n\n pixel_matrix = np.array(small_img)\n new_size = (int(NEW_IMG_HEIGHT * relative_size * 32) - 32, NEW_IMG_HEIGHT * 32)\n dice_img = Image.new('L', new_size, color='white')\n\n with open(TEXT_FILE_NAME, \"w\") as f:\n for row in range(0, NEW_IMG_HEIGHT):\n last_dice = 0\n dice_counter = 0\n line = \"\"\n for column in range(0, int(NEW_IMG_HEIGHT * relative_size)):\n grey_val = pixel_matrix[row][column]\n dice_number = assign_dice_to_color(grey_val)\n dice_img.paste(dice[dice_number], (column*32, row*32))\n\n current_dice = dice_number + 1\n if (current_dice != last_dice) and (dice_counter != 0):\n line += f\"d{last_dice} x {dice_counter}, \"\n dice_counter = 1\n else:\n dice_counter += 1\n last_dice = current_dice\n line += f\"d{last_dice} x {dice_counter}\"\n f.write(line + \"\\n\")\n\n dice_img.save(NEW_IMG_NAME, quality=100)\n print(\"Done!\")\n print(\"In real life this image would measure:\"\n f\" {int((1.6*NEW_IMG_HEIGHT*relative_size))}cm x {int((1.6*NEW_IMG_HEIGHT))}cm.\")\n\n\ndef assign_dice_to_color(grey_value):\n return 5-int(grey_value/45)\n\n\nif __name__ == \"__main__\":\n image_name = askopenfilename()\n convert_to_dice_image(image_name)\n" }, { "alpha_fraction": 0.783088207244873, "alphanum_fraction": 0.783088207244873, "avg_line_length": 66.875, "blob_id": "8e2d65a594b21e9d1903ceb3dc1ac50b4be511eb", "content_id": "4fa480de2cc5641a9d5a5d2802bcf0fed1d9b8d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 544, "license_type": "permissive", "max_line_length": 258, "num_lines": 8, "path": "/README.md", "repo_name": "Simon-Hostettler/DiceImageGenerator", "src_encoding": "UTF-8", "text": "This python file converts an image to a downscaled black and white representation, where each pixel gets replaced by a die-face closest to its darkness. \nIt asks for an image input and saves the converted image as \"DiceImage.jpg\" in the same folder as the .py file. It also outputs a textfile \"DiceArrangement.txt\" with the order the dice should be placed in, in case you want to rebuild your image in real life.\n\nRequired external modules: numpy, Pillow\n\nExample:\n![Input Image](/Examples/dog.jpg)\n![Output Image](/Examples/dogDiceImage.jpg)\n\n" } ]
2
Ta11ega1/Snake
https://github.com/Ta11ega1/Snake
2bd29428e49317d9b429a4e71f2ea409ba9b20a4
88f5e82998f243fa61fe0f567af4f4b1a62403a5
83ea875ffffe662aa51dc9dfb8977a48f2300adc
refs/heads/master
2020-04-20T16:13:58.945206
2019-02-04T14:17:42
2019-02-04T14:17:42
168,952,674
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3764553666114807, "alphanum_fraction": 0.39068564772605896, "avg_line_length": 41.94444274902344, "blob_id": "a9686ad9f0c55495ddbea29a69c7ae21dbade637", "content_id": "f73bea2939ae1491b93afb92259b419c9a0970fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 83, "num_lines": 18, "path": "/setup.py", "repo_name": "Ta11ega1/Snake", "src_encoding": "UTF-8", "text": "import cx_Freeze\n\nexecutables = [cx_Freeze.Executable(\"serpiente.py\", base = \"Win32GUI\")]\n\nbuild_exe_options = {\"packages\": [\"pygame\"], \"include_files\":[\"arial_narrow_7.ttf\",\n \"25.jpg\",\n \"icon.png\",\"29.jpg\",\n \"Fondo jp-01.png\",\n \"song.ogg\",\n \"Sonig.ogg\"]}\n\ncx_Freeze.setup(\n name = \"serpiente\",\n version = \"1.0\",\n description = \"Juego de atrapar la manzana con una serpiente\",\n options={\"build_exe\": build_exe_options},\n executables = executables\n )\n" }, { "alpha_fraction": 0.5437670946121216, "alphanum_fraction": 0.5885992646217346, "avg_line_length": 36.76628494262695, "blob_id": "bf8a7c93553157b9497ddf22982dc998b092ec2d", "content_id": "f91c7aa78bdac59c51892af4dc3e96b1cba2b0ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9859, "license_type": "no_license", "max_line_length": 151, "num_lines": 261, "path": "/serpiente.py", "repo_name": "Ta11ega1/Snake", "src_encoding": "UTF-8", "text": "import os\nimport pygame\nimport random\nimport time\n\n\npygame.init()\ndef load_image(name):\n path = os.path.join('', name)\n return pygame.image.load(path).convert()\n \n\nBlanco = (255, 255, 255)\nNegro = (0, 0, 0)\nRojo = (255, 0, 0)\nAzul = (0, 0, 255)\nVerde = (0, 128, 0)\nLila = (204, 0, 204)\nColonial = (153, 0, 0)\n\nancho = 800\naltura = 500\nsuperficie = pygame.display.set_mode((ancho,altura))\nicono = pygame.image.load(\"icon.png\")\npygame.display.set_icon(icono)\nbackground = load_image(\"29.jpg\")\n\nsuperficie.blit(background, [0, 0])\n\npygame.display.set_caption(\"Serpiente\")\n\nreloj = pygame.time.Clock()\n\nserp_tamano = 20\n\nfont = pygame.font.SysFont(\"arial_narrow_7.ttf\", 35)\n\ndef pausa():\n pausado = True\n\n while pausado:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_c:\n pausado = False\n elif event.key == pygame.K_q:\n pygame.quit()\n quit()\n background = load_image(\"25.jpg\")\n superficie.blit(background, [0, 0])\n #superficie.fill(Blanco)\n message_to_screen(\"Para continuar presiona \\\"C\\\"\", Negro, 100)\n pygame.display.update()\n reloj.tick(5)\n\ndef puntos(score,velocidad):\n text = font.render(\"Puntos: \"+str(score)+\" Velocidad: \"+str(velocidad), True, Negro)\n superficie.blit(text, [0,0])\n\ndef intro_juego():\n intro = True\n while intro:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_c:\n intro = False\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n\n background = load_image(\"FONDO jp-01.png\")\n superficie.blit(background, [0, 0])\n message_to_screen(\"Bienvenido, bienvenida\", Colonial, -100)\n message_to_screen(\"El objetivo del juego es controlar una serpiente usando\", Negro, -75)\n message_to_screen(\"teclas flechas de movimiento para comer manzanas\", Negro, -50)\n message_to_screen(\"El puntaje por manzana es: Roja:+1 lila: +10\", Colonial, -25);\n message_to_screen(\"Cada tres puntos la manzana roja aumenta la velocidad en 1\", Colonial, 0);\n message_to_screen(\"Si se come la manzana verde la velocidad aumenta en 1\", Colonial, 25);\n message_to_screen(\"Si la serpiente toca el borde o se toca a si misma, pierdes.\", Negro, 50)\n message_to_screen(\"Para pausar partida, presiona tecla P.\", Negro, 75)\n message_to_screen(\"Para continuar partida, presiona tecla C\", Negro, 100)\n message_to_screen(\"Para terminar de jugar y salir, preciona tecla Q.\", Colonial, 125)\n pygame.display.update()\n reloj.tick(15)\n \ndef serpiente(serp_tamano, listaSerpiente):\n for i in listaSerpiente:\n pygame.draw.rect(superficie, Negro, [i[0], i[1], serp_tamano, serp_tamano])\n\ndef text_objetos(text, color):\n textSuperficie = font.render(text, True, color)\n return textSuperficie, textSuperficie.get_rect()\n\ndef message_to_screen(msg, color, y_displace=0):\n textSur, textRect = text_objetos(msg, color)\n textRect.center = (ancho/2), (altura/2) + y_displace\n superficie.blit(textSur, textRect)\n #pantalla_texto = font.render(msg, True, color)\n #superficie.blit(pantalla_texto,[300, 300])\n\ndef gameLoop():\n gameExit = False\n gameOver = False\n \n mover_x = 300\n mover_y = 300\n\n CPS = 15\n \n puntos_rojo = 0\n\n mover_x_cambio = 0\n mover_y_cambio = 0\n \n listaSerpiente = []\n largoSerpiente = 1\n #Manzana roja da 1 punto\n azarManzanaX = round(random.randrange(0, 300 - 20)/20.0)*20.0\n azarManzanaY = round(random.randrange(0, 300 - 20)/20.0)*20.0\n #Manzana verde de velocidad\n azarManzana2X = round(random.randrange(0, 300 - 20)/20.0)*20.0\n azarManzana2Y = round(random.randrange(0, 300 - 20)/20.0)*20.0\n #Manzana lila da 10 puntos\n azarManzana3X = round(random.randrange(0, 300 - 20)/20.0)*20.0\n azarManzana3Y = round(random.randrange(0, 300 - 20)/20.0)*20.0\n\n #Si manzana verde es igual a manzana roja\n if(azarManzana2X>(azarManzanaX-20) and azarManzana2X<(azarManzanaX+20) or azarManzana2Y>(azarManzanaY-20) and azarManzana2Y<(azarManzanaY+20)):\n azarManzana2X += 20\n azarManzana2Y += 20\n #Si manzana verde es igual a manzana lila\n if(azarManzana2X>(azarManzana3X-20) and azarManzana2X<(azarManzana3X+20) or azarManzana2Y>(azarManzana3Y-20) and azarManzana2Y<(azarManzana3Y+20)):\n azarManzana2X += 20\n azarManzana2Y += 20\n #Si manzana lila es igual a manzana verde\n if(azarManzana3X>(azarManzanaX-20) and azarManzana3X<(azarManzanaX+20) or azarManzana3Y>(azarManzanaY-20) and azarManzana3Y<(azarManzanaY+20)):\n azarManzana3X += 20\n azarManzana3Y += 20\n #Si manzana lila es igual a manzana roja \n if(azarManzana3X>(azarManzanaX-20) and azarManzana3X<(azarManzanaX+20) or azarManzana3Y>(azarManzanaY-20) and azarManzana3Y<(azarManzanaY+20)):\n azarManzana3X += 20\n azarManzana3Y += 20\n #Si manzana roja es igual a manzana lila\n if(azarManzanaX>(azarManzana3X-20) and azarManzanaX<(azarManzana3X+20) or azarManzanaY>(azarManzana3Y-20) and azarManzanaY<(azarManzana3Y+20)):\n azarManzanaX += 20\n azarManzanaY += 20\n #Si manzana roja es igual a manzana verde\n if(azarManzanaX>(azarManzana2X-20) and azarManzanaX<(azarManzana2X+20) or azarManzanaY>(azarManzana2Y-20) and azarManzanaY<(azarManzana2Y+20)):\n azarManzanaX += 20\n azarManzanaY += 20\n \n pulsar_sonido = pygame.mixer.Sound(\"song.ogg\")\n pulsar_sonido.set_volume(0.50)\n pulsar_sonido.play(18)\n \n \n while not gameExit:\n\n while gameOver == True:\n ##superficie.fill(blanco)\n superficie.blit(background, [0,0])\n pulsar_sonido.stop()\n message_to_screen(\"Game Over\", Negro, -50)\n message_to_screen(\"Para continuar presione C. Para terminar presione Q\", Rojo, 50)\n pygame.display.update()\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n gameExit = True\n gameOver = False\n if event.key == pygame.K_c:\n gameLoop()\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameExit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n mover_x_cambio = -serp_tamano\n mover_y_cambio = 0\n elif event.key == pygame.K_RIGHT:\n mover_x_cambio = serp_tamano\n mover_y_cambio = 0\n elif event.key == pygame.K_UP:\n mover_y_cambio = -serp_tamano\n mover_x_cambio = 0\n elif event.key == pygame.K_DOWN:\n mover_y_cambio = serp_tamano\n mover_x_cambio = 0\n elif event.key == pygame.K_p:\n pulsar_sonido.set_volume(0.0)\n pausa()\n pulsar_sonido.set_volume(0.50)\n \n\n if mover_x >= ancho or mover_x < 0 or mover_y >= altura or mover_y <0:\n gameOver = True\n \n mover_x += mover_x_cambio\n mover_y += mover_y_cambio\n #superficie.fill(Blanco)\n superficie.blit(background, [0,0])\n \n pygame.draw.rect(superficie, Rojo, [azarManzanaX, azarManzanaY, 20, 20])\n pygame.draw.rect(superficie, Verde, [azarManzana2X, azarManzana2Y, 20, 20])\n pygame.draw.rect(superficie, Lila, [azarManzana3X, azarManzana3Y, 20, 20])\n \n cabezaSerpiente = []\n cabezaSerpiente.append(mover_x)\n cabezaSerpiente.append(mover_y)\n listaSerpiente.append(cabezaSerpiente)\n if len(listaSerpiente) > largoSerpiente:\n del listaSerpiente[0]\n\n for eachSegment in listaSerpiente[:-1]:\n if eachSegment == cabezaSerpiente:\n gameOver = True\n \n serpiente(serp_tamano, listaSerpiente)\n puntos(largoSerpiente-1, CPS)\n pygame.display.update()\n #rojo\n if mover_x == azarManzanaX and mover_y == azarManzanaY:\n pygame.mixer.music.load(\"Sonig.ogg\")\n azarManzanaX = round(random.randrange(0, 300 - 20)/20.0)*20.0\n azarManzanaY = round(random.randrange(0, 300 - 20)/20.0)*20.0\n largoSerpiente += 1\n puntos_rojo += 1\n if puntos_rojo%3==0:\n CPS+=1\n pygame.mixer.music.play(0)\n \n #verde \n if mover_x == azarManzana2X and mover_y == azarManzana2Y:\n pygame.mixer.music.load(\"Sonig.ogg\")\n azarManzana2X = round(random.randrange(0, 300 - 20)/20.0)*20.0\n azarManzana2Y = round(random.randrange(0, 300 - 20)/20.0)*20.0\n pygame.mixer.music.play(0)\n CPS +=1\n #lila\n if mover_x == azarManzana3X and mover_y == azarManzana3Y:\n pygame.mixer.music.load(\"Sonig.ogg\")\n azarManzana3X = round(random.randrange(0, 300 - 20)/20.0)*20.0\n azarManzana3Y = round(random.randrange(0, 300 - 20)/20.0)*20.0\n largoSerpiente += 10\n pygame.mixer.music.play(0)\n \n reloj.tick(CPS)\n pygame.display.update()\n time.sleep(3)\n pygame.quit()\n quit()\nintro_juego()\ngameLoop()\n\n\n" } ]
2
Bairouk/PlantIll
https://github.com/Bairouk/PlantIll
245ffa220eb8c5e1384890073addbba7bc749193
d4908350b5ffa875185a2a2eac79247c8439faac
ec63bbc25cbaf9f0c334312c0d57208c4f9185d1
refs/heads/master
2020-08-22T02:05:08.292429
2020-01-15T18:22:46
2020-01-15T18:22:46
216,295,585
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6919242143630981, "alphanum_fraction": 0.7093718647956848, "avg_line_length": 28.485294342041016, "blob_id": "d9d52552b60cbe8eea6106a99f661f18be6b12d0", "content_id": "ab25de25c289a146d5b9b4424dc0ee7ae101468d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2006, "license_type": "no_license", "max_line_length": 191, "num_lines": 68, "path": "/README.md", "repo_name": "Bairouk/PlantIll", "src_encoding": "UTF-8", "text": "# PlantIll\n\nMobile application for plant disease recognition using a deep learning model \n \n## About :\n\nThis project is two parts :\n\n - Deep learning part: we did train a model for plant disease recognition, You can find the work under the folder /DPModel, more explanation below (Dataset, Weights, Training).\n \n - Mobile dev part: We build this part using Flutter.\n\n\n# 1-Deep Learning Model\n\n## Dataset: \n\n - The dataset we worked with contains 39 classes, The healthy plants are apart of these classes, there is also Background\n class, it refers to the images where there is no plant or plants which those not exist in our classes.\n \n - The link for the data is [here](https://drive.google.com/file/d/0B_voCy5O5sXMTFByemhpZllYREU/view?usp=sharing), a special thanks to Marko Arsenovic who provided this dataset.\n \n\n - The link for the weights we got after training [here](https://drive.google.com/drive/folders/1-5S1v6ydXjdHfUaBWsoXkO8v7vqegCIY?usp=sharing).\n \n## The Models we used :\n \nThis the models we did train:\n\n - ResNet18\n - AlexNet\n - VGG16\n - IceptionV3\n - ResNet34\n\n## The training:\n\nAll the models were trained to respect the following steps : \n - step 1 :\n We did transfer learning for the model, the last layer was trained on 39 classes. At the beggining we choose the image size to be 128 so we will be able to do progressive resizing later on.\n\n - step 2 : \n we unfreeze all the layers of the model and we train it again. \n\n - step 3 :\n we do the progressive resizing so we change the size of the image from 128 to the original size which is 265, then we unfreeze just the last two layers of the model and we train it.\n\n - step 4 :\n we unfreeze the last three layers of the model and we train it.\n\n - last step : \n we unfreeze all the model and we train it.\n \n## The results:\n\nThe following table shows \n\n![](results.png)\n\n## Deployment of the best model :\n \"TODO how you did your deployment \"\n \n\n\n\n \n \n# 2-Mobile Dev part \n" }, { "alpha_fraction": 0.7465753555297852, "alphanum_fraction": 0.7465753555297852, "avg_line_length": 28.200000762939453, "blob_id": "15b3c54d1c7e5845208f4a7798533a165c0b6a0b", "content_id": "6f34af493f4156c8b33f1e1498452a947ca6c089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 146, "license_type": "no_license", "max_line_length": 72, "num_lines": 5, "path": "/ModelDeploy/README.md", "repo_name": "Bairouk/PlantIll", "src_encoding": "UTF-8", "text": "# Model deployment\n\nthis is the flask app hosted in the server to hand the model predictions\n \n--> predict.html : this is just a test interface " }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6499691009521484, "avg_line_length": 24.603174209594727, "blob_id": "b126835b2a78e292378f85327fb82a15ae2aa20f", "content_id": "7652337c69b6a642ae2f327653c08f029d5201d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1617, "license_type": "no_license", "max_line_length": 78, "num_lines": 63, "path": "/ModelDeploy/predict.py", "repo_name": "Bairouk/PlantIll", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport PIL.Image\nfrom datetime import datetime\nimport io\nimport base64\nfrom flask import Flask,Blueprint,request,render_template,jsonify\n#from modules.dataBase import collection as db\nfrom fastai import *\nfrom fastai.vision import *\nfrom fastai.widgets import *\n\nimport fastai\nfastai.device = torch.device('cpu')\n\napp = Flask(__name__)\n\n\ndef get_model( ):\n global model \n path = Path('/home/anass_bairouk_um5s_net_ma/app')\n model = load_learner(path)\n print(\"model loaded\")\n\n\n\ndef preprocess_img(image):\n \n image = image.convert(\"RGB\")\n image = image.resize((256,256))\n image.save(\"out.jpg\", \"JPEG\", quality=80, optimize=True, progressive=True)\n #image = np.asarray(image)\n #image = np.expand_dims(image, axis=0)\n img = Image(pil2tensor(image, np.float32).div_(255))\n img.save(\"fast.jpg\")\n return img\n\nprint(\"Loading our model ...\")\nget_model()\n\[email protected](\"/predict\", methods=[\"POST\"])\n\ndef predict(): \n message = request.get_json(force=True)\n encoded = message['image']\n decoded = base64.b64decode(encoded)\n image = PIL.Image.open(io.BytesIO(decoded))\n processed_img = preprocess_img(image)\n pred_class,pred_idx,outputs = model.predict(processed_img)\n print(\"Our class is : \")\n print(str(pred_class))\n print(\"Accuracy: \")\n print(str(outputs[pred_idx]))\n response = {\n \"predi\":{\n \"status\":\"success\",\n \"prediction\":str(pred_class),\n \"confidence\":str(outputs[pred_idx].tolist()),\n \"upload_time\":datetime.now()\n }\n }\n\n return jsonify(response)\n\n\n\n\n" } ]
3
IngramProject/IngramProject
https://github.com/IngramProject/IngramProject
12cfa2bdda2fbfc5c61d3171fbcf9bb568ea3ad8
3767ab2fa0f30ccc5ee3d98f29297895ce2b9c36
1185fe99605968db69a3d5c80b78a3046369c570
refs/heads/master
2020-03-07T19:50:04.935535
2018-04-02T00:30:17
2018-04-02T00:30:17
127,681,145
1
0
null
2018-04-01T23:58:16
2018-04-02T00:28:45
2018-04-02T00:30:18
Python
[ { "alpha_fraction": 0.8162230849266052, "alphanum_fraction": 0.82256019115448, "avg_line_length": 19.763158798217773, "blob_id": "8b34dfd24027e8528b504f058ae9a8aeb8a5e74a", "content_id": "b527d3ae7b21338117ad41518818b585ef7c567c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 789, "license_type": "no_license", "max_line_length": 69, "num_lines": 38, "path": "/RetPondPi/testSendBatteryChargeEachMin.py", "repo_name": "IngramProject/IngramProject", "src_encoding": "UTF-8", "text": "import time\nimport datetime\nfrom wirelessConnection import WirelessConnection\nfrom battery import Battery\n\n\nbatteryLogFile = \"/home/pi/Desktop/testSendBatteryLogFileEachMin.log\"\n\n\nwirelessConnection = WirelessConnection()\nwirelessConnection.connectToOfficeUnit()\n\ntime.sleep(1)\n\ntimeStamp = str(datetime.datetime.now())\nwirelessConnection.sendData(timeStamp, batteryLogFile)\n\ntime.sleep(1)\n\n# This is for demo purposes\nofficeReply = wirelessConnection.receiveData()\nprint(officeReply)\n\ntime.sleep(1)\n\nbattery = Battery()\nbatteryLife = battery.getBatteryLife()\nwirelessConnection.sendData(batteryLife, batteryLogFile)\n\ntime.sleep(1)\n\n# This is for demo purposes\nofficeReply = wirelessConnection.receiveData()\nprint(officeReply)\n\ntime.sleep(1)\n\nwirelessConnection.endOutflowUnitConnection()\n" }, { "alpha_fraction": 0.8226950168609619, "alphanum_fraction": 0.8226950168609619, "avg_line_length": 27.200000762939453, "blob_id": "9bea36482224f2a67f297d61edb4b5ca647e20b2", "content_id": "bfba6208e459c9d304f047c34bee25fb4b1922f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 141, "license_type": "no_license", "max_line_length": 97, "num_lines": 5, "path": "/README.md", "repo_name": "IngramProject/IngramProject", "src_encoding": "UTF-8", "text": "# IngramProject\nThis repository contains the codebase and project description for the Texas State Ingram Project.\n\n\nREAD ALL DOCUMENTATION!!\n" }, { "alpha_fraction": 0.8506224155426025, "alphanum_fraction": 0.8506224155426025, "avg_line_length": 33.28571319580078, "blob_id": "50313e95ddd8d2f9f2a4739996593c9e681eb7a3", "content_id": "66e76aef0a726a4cbbcfeb4f28afb22f3e974163", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/RetPondPi/shutDownServer.py", "repo_name": "IngramProject/IngramProject", "src_encoding": "UTF-8", "text": "\n\n# This is used during testing to shut down the server if needed.\n\nfrom wirelessConnection import WirelessConnection\n\nwirelessConnection = WirelessConnection()\nwirelessConnection.connectToOfficeUnit()\nwirelessConnection.shutdownOfficeUnit()" }, { "alpha_fraction": 0.6745104789733887, "alphanum_fraction": 0.6798993945121765, "avg_line_length": 30.988506317138672, "blob_id": "8982f99da80fd7863cc1dc21ec0009b3f2a6cf5f", "content_id": "ead5b54990cf442cb9425e9c0fc3f9d8783676f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5627, "license_type": "no_license", "max_line_length": 88, "num_lines": 174, "path": "/OfficePi/pythonServer.py", "repo_name": "IngramProject/IngramProject", "src_encoding": "UTF-8", "text": "\n# The first six functions are used in the code. The code begins \n# at the very bottom with the line \n# “time.sleep(60)”\n\n# This script establishes a socket at a given port number on the OfficePi. \n# The OfficePi will wait and listen at the port number for the RetPondPi \n# to initiate a connection. Once a connection is established, the OfficePi \n# will receive data from the RetPondPi and save the data to the SD card.\n\n# The RetPondPi can control the OfficePi by sending commands to the OfficePi. \n\n# Example of how to control the OfficePi from the RetPondPi:\n\n# The following example string will be sent to the OfficePi:\n# “SEND /home/pi/Desktop/logFile.log your_Sensor_Data”\n\n# How pythonServer.py processes this example string:\n# In the function dataTransfer(), there is a line of code that reads \n# “dataMessage = data.split(‘ ‘,1)”\n# This line of code splits the string sent to the OfficePi into 2 parts. \n# Everything up until the first space will be stored in dataMessage[0] and \n# everything after the first space will be stored in dataMessage[1].\n# For our example: dataMessage[0] will contain the word “SEND” and dataMessage[1] \n# will contain the rest of the string “/home/pi/Desktop/logFile.log your_Sensor_Data”.\n\n# The code then checks the word stored in dataMessage[0]. \n# If it equals “SEND” which it does for our example, then the string \n# stored in dataMessage[1] is split again separating \n# “/home/pi/Desktop/logFile.log” and “your_Sensor_Data” in two. \n# The function SEND() is then called and the logFile and sensor_data is \n# passed into the function.\n\n# The SEND() function saves the data to the logFile name that was passed to it. \n# Then it calls the PROCESS() function. \n\n# For the our project, we used the PROCESS() function to check the “data_message” \n# that was sent. If “LOW” was sent, then the OfficePi will play a file that uses a \n# speaker to say “Low Battery” for the office employees to hear. \n\n# For a future sensor team, you will use the PROCESS() file to check \n# your “sensor_data_message” to see if outflow has occurred. (When outflow occurs, \n# you will probably send a message to the OfficePi that says something like “OUTFLOW”). \n# You will add an if statement to the PROCESS() function that checks to see if the \n# sent message = “OUTFLOW”. If it does, do what is needed. \n\n\nimport time\nimport socket\nimport os\n\n\nhost = ''\nport = 7823\n\n\n# This function creates a socket and binds it to a port number\ndef setupServer():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(\"Socket created.\")\n try:\n s.bind((host, port))\n except socket.error as msg:\n print(msg)\n print(\"Socket bind complete\")\n return s\n\n\n# Using this function, the server waits and listens at the port\n# for the RetPondPi to initiate a connection \ndef setupConnection():\n s.listen(1) #Allows one connection at a time\n connection, address = s.accept()\n print(\"Connected to: \" + address[0])\n return connection\n\n\n# This function is used for Senior Design demo purposes only\ndef PRINT(dataMessage):\n print(dataMessage[1])\n reply = \"Data displayed\"\n return reply\n\n\n# This function checks the dataMessage that is sent to the OfficePi\n# and reacts accordingly. \n# Example: when the battery data sent = \"LOW\", this function plays \n# a .wav file that uses a speaker to say \"Low Battery\". \ndef PROCESS(dataMessage, logFile):\n if logFile == \"/home/pi/Desktop/testBatteryLogFileEachMin.log\":\n if dataMessage == \"LOW\":\n os.system(\"aplay /home/pi/Desktop/lowBattery.wav\")\n\n\n # Future Ingram Teams: \n # this is where you alert that outflow has occurred\n # WRITE CODE HERE!\n\n # elif logFile == \"your log file name\":\n # if dataMessage = \"OUTFLOW\":\n # do whatever\n\n\n # For some reason the code wouldn't work without this function\n # containing a return statement so it was included here. \n reply = \"Data Saved\"\n return reply\n \n\n# This function saves the dataMessage to the SD card on the \n# OfficePi. It saves it to a file named in logFile.\ndef SEND(dataMessage, logFile):\n with open(logFile, \"a\") as theLogFile:\n theLogFile.write(dataMessage + '\\n')\n\n reply = PROCESS(dataMessage, logFile)\n\n return reply\n\n\n# This function receives the data from the RetPondPi. It then\n# splits the first word off of the data and uses it to determine\n# what to do next. \ndef dataTransfer(connection):\n\n # Sends/receives data until told not to\n while True:\n data = connection.recv(1024)\n data = data.decode('utf-8')\n\n # Split data into command word and rest of data\n dataMessage = data.split(' ', 1)\n command = dataMessage[0]\n\n if command == 'PRINT':\n reply = PRINT(dataMessage)\n\n elif command == 'SEND':\n dataMessage = dataMessage[1].split(' ', 1)\n logFile = dataMessage[0]\n dataMessage = dataMessage[1]\n reply = SEND(dataMessage, logFile)\n\n elif command == 'EXIT':\n print(\"Client has left\")\n break\n\n elif command == 'KILL':\n print(\"Server is shutting down\")\n file.close()\n s.close()\n break\n \n else:\n reply = 'Unknown command'\n\n # Send reply back to client\n connection.sendall(str.encode(reply))\n\n connection.close()\n\n\n\n\n# THIS IS WHERE THE CODE BEGINS\n\ntime.sleep(60)\ns = setupServer()\n\nwhile True:\n try:\n connection = setupConnection()\n dataTransfer(connection)\n except:\n break\n" }, { "alpha_fraction": 0.7379447817802429, "alphanum_fraction": 0.743265688419342, "avg_line_length": 37.02531814575195, "blob_id": "fcacd005a97501876347e80a449f9b7f21ec668c", "content_id": "e7bb3e7d2d6d8a5ccb70afcd07632ad186ffce1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3007, "license_type": "no_license", "max_line_length": 94, "num_lines": 79, "path": "/RetPondPi/wirelessConnection.py", "repo_name": "IngramProject/IngramProject", "src_encoding": "UTF-8", "text": "\n# This class implements all the functions necessary to establish a socket \n# connection with the OfficePi, send and receive data, end the connection, and \n# shutdown the server on the OfficePi. This code does not run or do anything on \n# its own. It must be imported into another script like sendBatteryCharge.py where \n# the code can be used. There is comments above each function that describes what \n# the functions do. \n\n\nimport socket\n\n\nclass WirelessConnection:\n\n\t# This is the constructor. This function runs automatically when\n\t# an instance of this class's object is called. An example of calling\n\t# an instance of theis class's object is found in sendBatteryCharge.py\n\t# where it reads: wirelessConnection = WirelessConnection().\n\t# self.host is the OfficePi server's IP address.\n\t# self.port is the port number that the OfficePi server is listening at.\n\t# self.s sets up TCP communication\n\tdef __init__(self):\n\t\tself.host = '172.24.1.1'\n\t\tself.port = 7823\n\t\tself.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\n\t# This function establishes a connection to the OfficePi server. \n\t# If a connection is established, it breaks out of the loop so the \n\t# program can continue running. If the server is down and a connection\n\t# cannot be established, it will continue to try to connect until\n\t# the connection is established. \n\tdef connectToOfficeUnit(self):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tself.s.connect((self.host, self.port))\t\n\t\t\t\tbreak\n\t\t\texcept:\n\t\t\t\tcontinue\n\n\n\t# This function will send data to the OfficePi and save the data to the \n\t# OfficePi's SD card. The data will then be processed to determine if\n\t# an alarm or alert must be made. \n\tdef sendData(self, data, logFile):\n\t\tself.s.send(str.encode('SEND ') + str.encode(logFile) + str.encode(' ') + str.encode(data)) \n\n\n\t# This function end the RetPondPi's connection with the OfficePi. It should\n\t# be called after data has been sent to the OfficePi.\n\tdef endOutflowUnitConnection(self):\n\t\tself.s.send(str.encode('EXIT'))\n\t\tself.s.close()\n\n\n\n\t# THE FOLLOWING THREE FUNCTIONS ARE FOR DEMO AND TESTING PURPOSES ONLY!!\n\n\n\t# This function is used for Senior Design demo purposes. It tells\n\t# the OfficePi the print the data that was sent to it to its console.\n\tdef printDataToConsole(self, data):\n\t\tself.s.send(str.encode('PRINT ') + str.encode(data)) \n\n\n\t# This function is used for Senior Desgin demo purposes. It receives \n\t# a response from the OfficePi letting the RetPondPi know that data\n\t# was received correctly. \n\tdef receiveData(self):\n\t\treply = self.s.recv(1024) \n\t\treturn reply.decode('utf-8')\n\n\n\t# This function is used to shutdown the OfficePi server. This should \n\t# NEVER be used during normal operation. This function is only used during \n\t# the writing code stage if you need to shutdown the server for some reason.\n\t# If you need to remotely shutdown the server, just run the python script\n\t# called shutDownServer.py instead of calling this function. \n\tdef shutdownOfficeUnit(self):\n\t\tself.s.send(str.encode('KILL'))\n\n\n" }, { "alpha_fraction": 0.6940639019012451, "alphanum_fraction": 0.6940639019012451, "avg_line_length": 12.6875, "blob_id": "1ed68dc83697e8286104e0b492f1fef1d434d7eb", "content_id": "53e202dbd67c41cdfc57015a0f76ea4ee9b6e660", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 39, "num_lines": 16, "path": "/RetPondPi/battery.py", "repo_name": "IngramProject/IngramProject", "src_encoding": "UTF-8", "text": "\n# imports go up here\n\n\nclass Battery:\n\n\tdef __init__(self):\n\n\t\tself.batteryLife = \"LOW\"\n\n\n\tdef getBatteryLife(self):\n\n\t\t# put everything you want your \n\t\t# code to automatically do right here\n\n\t\treturn self.batteryLife" }, { "alpha_fraction": 0.7882523536682129, "alphanum_fraction": 0.7926033139228821, "avg_line_length": 30.272727966308594, "blob_id": "2ddfc47852622fd72faf2d7c23c91539b6259d24", "content_id": "17e58d709b33f97c3bbe3c458f91b0923e399f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "no_license", "max_line_length": 69, "num_lines": 44, "path": "/RetPondPi/sendBatteryCharge.py", "repo_name": "IngramProject/IngramProject", "src_encoding": "UTF-8", "text": "\n# This script runs on the RetPondPi twice a day at 10am and 2pm. \n# The code to establish a socket connection and send the data is \n# found in wirelessConnection.py which is imported into this script. \n# The batteryLogFile below is the location and \n# name of the log file that will be stored on the OfficePi. \n# The code sleeps for one second three different times to give the \n# code plenty of time to finish each function before moving on. \n\n\nimport time\nimport datetime\nfrom wirelessConnection import WirelessConnection\nfrom battery import Battery\n\n\n# This is the name of the log file and the folder location on the \n# OfficePi where the data sent by this Python script will be stored. \nbatteryLogFile = \"/home/pi/Desktop/testBatteryLogFile.log\"\n\n\n# This establishes a connection with the OfficePi\nwirelessConnection = WirelessConnection()\nwirelessConnection.connectToOfficeUnit()\n\ntime.sleep(1)\n\n\n# This gets the current date and time and sends it to the OfficePi\ntimeStamp = str(datetime.datetime.now())\nwirelessConnection.sendData(timeStamp, batteryLogFile)\n\ntime.sleep(1)\n\n\n# This gets the current battery charge and sends it to the OfficePi.\nbattery = Battery()\nbatteryLife = battery.getBatteryLife()\nwirelessConnection.sendData(batteryLife, batteryLogFile)\n\ntime.sleep(1)\n\n\n# This ends the connection with the OfficePi.\nwirelessConnection.endOutflowUnitConnection()\n\n\n" } ]
7
lkachtik/blackjack
https://github.com/lkachtik/blackjack
4e0f892efb6ff19edf2080dd9113c0337e55d322
4700abbc71a4e6395a6483aac272302606323ff0
13d66c2eeb15e8f9128fe8dcfdaf8f239b2bca8e
refs/heads/master
2021-01-18T17:04:49.207249
2017-03-31T08:56:42
2017-03-31T08:56:42
86,785,145
0
4
null
2017-03-31T06:21:45
2017-03-31T08:04:23
2017-03-31T08:56:42
Python
[ { "alpha_fraction": 0.4483802020549774, "alphanum_fraction": 0.4649341404438019, "avg_line_length": 33.118751525878906, "blob_id": "cb14e82831c9d3b620e976321bf0628942db3554", "content_id": "635c11d7b4233f34ac868183d7de10036ec836da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11236, "license_type": "no_license", "max_line_length": 150, "num_lines": 320, "path": "/blackjack.py", "repo_name": "lkachtik/blackjack", "src_encoding": "UTF-8", "text": "from random import randrange\r\nfrom os import system\r\nfrom time import sleep\r\n\r\nclear = lambda: system('cls')\r\nclear()\r\n\r\nprint\"=== BLACKJACK ===\"\r\nprint\"Povolene prikazy:'ano', 'ne', cisla, 'help'.\\n\"\r\n\r\n# ZADEFINOVANI KONSTANT NA UVOD\r\na = [2,3,4,5,6,7,8,9,10,\"J\",\"Q\",\"K\",\"A\"]*4 # vytvori serazeny balicek karet\r\nb = [] # zamichany balicek karet\r\nu_p = 0 # hodnota karet hrace\r\npc_p = 0 # hodnota karet pocitace\r\notazka2 = \"whatever\"\r\nvklad = 0\r\nsazka = 0\r\nano = (\"ano\", \"a\", \"yes\", \"y\", \"\")\r\nne = (\"ne\", \"no\", \"n\")\r\npomoc = (\"pomoc\", \"help\", \"about\", \"o hre\")\r\n\r\no_hre = open(\"jak_to_asi_funguje.txt\",\"r\")\r\nabout = o_hre.read()\r\no_hre.close()\r\n\r\n# ZJISTENI, JESLTI MA HRAC 18 LET - V ZAVISLOSTI NA ODPOVEDI SE PROGRAM BUDE CHOVAT JINAK\r\nwhile True:\r\n otazka = raw_input(\"Je ti 18 let a vice? \")\r\n otazka = otazka.lower()\r\n if otazka in ano:\r\n print\"Protoze ti je vice nez 18, budes mit moznost sazet. Hodne stesti!\"\r\n sleep(1)\r\n break\r\n elif otazka in ne:\r\n print\"Hra pobezi v omezenm rezimu bez sazek. Hodne stesti!\"\r\n sleep(1)\r\n break\r\n elif otazka in pomoc:\r\n print \"\\n\" + about\r\n continue\r\n else:\r\n print\"Napis prosim ano nebo ne.\"\r\n continue\r\n\r\n# OTAZKA, KOLIK CHCE HRAC VLOZIT NA VKLAD\r\nwhile otazka in ano:\r\n try:\r\n vklad = raw_input(\"Jak velky chces provest vklad? \")\r\n vklad = vklad.lower()\r\n if vklad in pomoc:\r\n print \"\\n\" + about\r\n continue\r\n vklad = int(vklad)\r\n if vklad <= 0:\r\n print \"Zadej prosim cele cislo vetsi nez 0.\"\r\n continue\r\n break\r\n except ValueError:\r\n print(\"Zadej prosim cele cislo.\")\r\n continue\r\n\r\n# ZAMICHA BALICEK KARET\r\nfor i in range(52): \r\n x = randrange(0,52-i)\r\n b.append(a[x]) # vezme nahodnou kartu z balicku \"a\" a prida ji do balicku \"b\"\r\n del a[x] # odstrani danou kartu z balicku \"a\"\r\n # tohle se stane celkem 52x\r\n\r\n# SMYCKA, KTERA BEZI, DOKUD NEREKNU, ZE UZ NECHCI HRAT\r\nwhile otazka in ano or otazka in ne:\r\n \r\n if otazka in ano: \r\n while True:\r\n try:\r\n sazka = raw_input(\"Kolik chces vsadit do dalsi hry? \")\r\n sazka = sazka.lower()\r\n if sazka in pomoc:\r\n print \"\\n\" + about\r\n continue\r\n sazka = int(sazka)\r\n if sazka <= 0:\r\n print \"Zadej prosim cele cislo vetsi nez 0.\"\r\n continue\r\n elif sazka > vklad:\r\n print \"Mas pouze \" + str(vklad) + \". Zadej prosim mensi hodnotu.\"\r\n continue\r\n break\r\n except ValueError:\r\n print(\"Zadej prosim cele cislo.\")\r\n continue\r\n \r\n u_v = 0 # soucet bodu hrace\r\n pc_v = 0 # soucet bodu pocitace\r\n u_ace = 0 # pocet Es hrace v ruce\r\n pc_ace = 0 # pocet Es pocitace v ruce\r\n u_karty = [] # karty v ruce hrace\r\n pc_karty = [] # karty v ruce pocitace\r\n c = [] # karty na stole\r\n d = [] # zamichane karty ze stolu\r\n\r\n # TAHNE PRVNI KARTU PRO HRACE\r\n u = b[0] # vytahne prvni kartu z balicku\r\n u_karty.append(u) # vlozi ji uzivatelovi do ruky\r\n if u == \"J\" or u == \"Q\" or u == \"K\": # priradi hodnotam J, Q a K hodnotu 10\r\n u = 10\r\n if u == \"A\": # priradi Esu hodnotu 11\r\n u = 11\r\n u_ace += 1 # pocita, kolik ma hrac v ruce Es, aby jim pak pripadne mohl snizovat hodnotu z 11 na 1\r\n u_v += u # prida hodnotu karty k celkove hodnote vsech karet\r\n c.append(b[0]) # prida kartu mezi karty na stole\r\n del b[0] # odebere kartu z hraciho balicku\r\n \r\n # TAHNE PRVNI KARTU PRO POCITAC\r\n pc = b[0]\r\n pc_karty.append(pc)\r\n if pc == \"J\" or pc == \"Q\" or pc == \"K\": # vsechny karty vetsi nez 10 maji hodnotu 10\r\n pc = 10\r\n if pc == \"A\": # pocitadlo Es hrace\r\n pc = 11\r\n pc_ace += 1\r\n pc_v += pc\r\n c.append(b[0])\r\n del b[0]\r\n \r\n # TAHNE DRUOU KARTU PRO HRACE\r\n u = b[0] # vytahne prvni kartu z balicku\r\n u_karty.append(u) # vlozi ji uzivatelovi do ruky\r\n if u == \"J\" or u == \"Q\" or u == \"K\": # priradi hodnotam J, Q a K hodnotu 10\r\n u = 10\r\n if u == \"A\": # priradi Esu hodnotu 11\r\n u = 11\r\n u_ace += 1 # pocita, kolik ma hrac v ruce Es, aby jim pak pripadne mohl snizovat hodnotu z 11 na 1\r\n u_v += u # prida hodnotu karty k celkove hodnote vsech karet\r\n c.append(b[0]) # prida kartu mezi karty na stole\r\n del b[0] # odebere kartu z hraciho balicku\r\n \r\n # Jaka je pravdepodobnost, ze na zacatku dostanu 2 Esa? Mala, ale mne uz se to stalo a vypsalo mi to soucet 22, pfff. \r\n if u_v > 21 and u_ace > 0: # +2 - podminka - pokud je muj soucet vetsi nez 21 a zaroven je jedna ma karta Eso, tak zmensit muj souect o 10\r\n u_v -= 10\r\n u_ace -=1\r\n \r\n n = len(u_karty)\r\n u_karty2 = \"\"\r\n for i in range(n):\r\n u_karty2 += str(u_karty[i]) + \" \"\r\n \r\n n = len(pc_karty)\r\n pc_karty2 = \"\"\r\n for i in range(n):\r\n pc_karty2 += str(pc_karty[i]) + \" \"\r\n\r\n print \"Tve karty - \" + str(u_karty2) + \"- soucet: \" + str(u_v)\r\n print \"Karty pocitace - \" +str(pc_karty2) + \"- soucet:\" + str(pc_v) \r\n \r\n while True:\r\n u=raw_input(\"Chces dalsi kartu? \")\r\n u = u.lower()\r\n if u in pomoc:\r\n print \"\\n\" + about\r\n continue\r\n if u in ano:\r\n u = b[0]\r\n u_karty.append(u)\r\n if u == \"J\" or u == \"Q\" or u == \"K\": # vsechny karty vetsi nez 10 maji hodnotu 10\r\n u = 10\r\n if u == \"A\": # pocitadlo Es hrace\r\n u = 11 \r\n u_ace += 1 \r\n u_v += u\r\n c.append(b[0])\r\n del b[0]\r\n if u_v > 21 and u_ace > 0: # +2 - podminka - pokud je muj soucet vetsi nez 21 a zaroven je jedna ma karta Eso, tak zmensit muj souect o 10\r\n u_v -= 10\r\n u_ace -=1\r\n \r\n n = len(u_karty)\r\n u_karty2 = \"\"\r\n for i in range(n):\r\n u_karty2 += str(u_karty[i]) + \" \"\r\n \r\n n = len(pc_karty)\r\n pc_karty2 = \"\"\r\n for i in range(n):\r\n pc_karty2 += str(pc_karty[i]) + \" \"\r\n \r\n print \"Tve karty - \" + str(u_karty2) + \"- soucet: \" + str(u_v)\r\n print \"Karty pocitace - \" +str(pc_karty2) + \"- soucet:\" + str(pc_v)\r\n if u_v > 21:\r\n print \"\\nPrekrocil jsi v souctu 21\"\r\n sleep(1)\r\n break\r\n continue\r\n elif u in ne:\r\n break\r\n else:\r\n print\"Napis prosim ano nebo ne.\"\r\n continue\r\n \r\n while pc_v < 17:\r\n pc = b[0]\r\n pc_karty.append(pc)\r\n if pc == \"J\" or pc == \"Q\" or pc == \"K\": # vsechny karty vetsi nez 10 maji hodnotu 10\r\n pc = 10\r\n if pc == \"A\": # pocitadlo Es hrace\r\n pc = 11\r\n pc_ace += 1\r\n pc_v += pc\r\n c.append(b[0])\r\n del b[0]\r\n \r\n if pc_v > 21 and pc_ace > 0: # pokud je muj soucet vetsi nez 21 a zaroven je jedna ma karta Eso, tak pocita Eso jako jednicku\r\n pc_v -= 10\r\n pc_ace -=1\r\n \r\n n = len(u_karty)\r\n u_karty2 = \"\"\r\n for i in range(n):\r\n u_karty2 += str(u_karty[i]) + \" \"\r\n \r\n n = len(pc_karty)\r\n pc_karty2 = \"\"\r\n for i in range(n):\r\n pc_karty2 += str(pc_karty[i]) + \" \"\r\n \r\n print \"Tve karty: \" + str(u_karty2) + \", soucet: \" + str(u_v)\r\n print \"Karty pocitace: \" +str(pc_karty2) + \", soucet:\" + str(pc_v)\r\n print \"\\n\"\r\n if u_v > 21: # +9 - vypsani vysledku\r\n print \"Prohral jsi\"\r\n pc_p += 1\r\n vklad -= sazka\r\n elif pc_v > 21 and u_v <=21:\r\n print \"Vyhral jsi\"\r\n u_p += 1\r\n vklad += sazka\r\n elif u_v == pc_v:\r\n print \"Remiza\"\r\n elif u_v > pc_v:\r\n print \"Vyhral jsi\"\r\n vklad += sazka\r\n u_p += 1\r\n else:\r\n print \"Prohral jsi\"\r\n pc_p += 1\r\n vklad -= sazka\r\n \r\n c_n = len(c) # +4 - zamichani karet, ktere jsou na stole\r\n for i in range(c_n):\r\n x = randrange(0,c_n-i)\r\n d.append(c[x])\r\n del c[x]\r\n \r\n print \"HRAC: \" + str(u_p) + \" : \" + str(pc_p) + \" POCITAC\"\r\n if otazka in ano:\r\n print \"Tvuj zustatek: \" + str(vklad)\r\n \r\n b.extend(d) # vlozeni zamichanych karet ze stolu na spodek hraciho balicku\r\n \r\n while True:\r\n if otazka in ano:\r\n if vklad == 0:\r\n prachy = raw_input(\"Hodnota tveho vkladu je na nule. Chces vlozit dalsi penize? \")\r\n prachy = prachy.lower()\r\n if prachy in pomoc:\r\n print \"\\n\" + about\r\n continue\r\n if prachy in ano:\r\n while True:\r\n try:\r\n dobit = raw_input(\"Zadej castku kterou chces dobit: \")\r\n dobit = dobit.lower()\r\n if dobit in pomoc:\r\n print \"\\n\" + about\r\n continue\r\n dobit = int(dobit)\r\n if dobit <= 0:\r\n print \"Zadej prosim cele cislo vetsi nez 0.\"\r\n continue\r\n break\r\n except ValueError:\r\n print(\"Zadej prosim cele cislo.\")\r\n continue\r\n \r\n print\"Dobito!\"\r\n vklad += dobit\r\n sleep(1)\r\n elif prachy in ne:\r\n print\"\\n\"\r\n print\"=== VYSLEDNE SKORE ===\"\r\n print \"HRAC: \" + str(u_p) + \" : \" + str(pc_p) + \" POCITAC\"\r\n if otazka == \"ano\":\r\n print \"Hodnota tveho vkladu: \" + str(vklad)\r\n otazka = \"whatever\"\r\n print\"\\n\"\r\n raw_input(\"Diky za hru. V pripade nalezeni nejake chyby mi nevahej napsat na [email protected]. Pro ukonceni zmackni Enter.\")\r\n break\r\n else:\r\n print\"Napis prosim ano nebo ne.\"\r\n continue\r\n otazka2 = raw_input(\"Chces hrat znovu? \")\r\n otazka2 = otazka2.lower()\r\n if otazka2 in pomoc:\r\n print \"\\n\" + about\r\n continue\r\n if otazka2 in ano:\r\n break\r\n if otazka2 in ne:\r\n print\"\\n\"\r\n print\"=== VYSLEDNE SKORE ===\"\r\n print \"HRAC: \" + str(u_p) + \" : \" + str(pc_p) + \" POCITAC\"\r\n if otazka == \"ano\":\r\n print \"Hodnota tveho vkladu: \" + str(vklad)\r\n otazka = \"easteregg\"\r\n print\"\\n\"\r\n raw_input(\"Diky za hru. V pripade nalezeni nejake chyby mi nevahej napsat na [email protected]. Pro ukonceni zmackni Enter.\")\r\n break\r\n else:\r\n print\"Napis prosim ano nebo ne.\"\r\n continue" }, { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 5.666666507720947, "blob_id": "ccff0f7782e82d0d6341b99d510322c3ceb5472e", "content_id": "4bc1f20d54405f7d52e415367727ef721d60a91e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 11, "num_lines": 3, "path": "/README.md", "repo_name": "lkachtik/blackjack", "src_encoding": "UTF-8", "text": "# blackjack\n\nKontraadmiral Zuza" } ]
2
Anjali555/django-terracross
https://github.com/Anjali555/django-terracross
8ecc418ec227b58024a1509fdada6be0628e5ff4
ed186cf96076b01dcafd2c98503df2c5b709b663
6a5147624d38af16905069eaa227ba9e7bf04c0a
refs/heads/master
2020-03-08T16:34:50.481516
2018-04-05T17:41:02
2018-04-05T17:41:02
128,242,408
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5850340127944946, "alphanum_fraction": 0.6207482814788818, "avg_line_length": 28.450000762939453, "blob_id": "40e129b568048cf27d0a322da602e3720c5b8ff4", "content_id": "c8359d76954e15e8ef8bd0655cae45253fc55349", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 588, "license_type": "no_license", "max_line_length": 67, "num_lines": 20, "path": "/countdown/polls/views.py", "repo_name": "Anjali555/django-terracross", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import Email\nfrom datetime import datetime\nimport re\n\n# Create your views here.\ndef index(request):\n test_date = datetime.fromtimestamp(1518517440)\n r_t = str(datetime.now() - test_date)\n r_t = r_t.split()\n r_t1 = re.split(r'[:]',r_t[2])\n\n r_t2 = round(float(r_t1[2]))\n\n d = {'day':r_t[0],'hour':r_t1[0],'min':r_t1[1],'sec':str(r_t2)}\n if request.method == 'POST':\n email = request.POST.get('EMAIL')\n email_obj = Email(email = email)\n email_obj.save()\n return render(request,'polls/index.html')" }, { "alpha_fraction": 0.8235294222831726, "alphanum_fraction": 0.8235294222831726, "avg_line_length": 29, "blob_id": "c0cdb9445f0827e05c7fefc0230b35da6e4e9427", "content_id": "fdcdbdf5ea004162d1530559ff4cba1600d14690", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/countdown/polls/admin.py", "repo_name": "Anjali555/django-terracross", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom polls.models import Email\n# Register your models here.\nadmin.site.register(Email)" } ]
2
marianamendezrdz/marianamendezsite
https://github.com/marianamendezrdz/marianamendezsite
e951d6f241116247bf37a82b1c3bf4eb1fb1c97a
a1feecb47ba0238b59651d9c668aea42e11fe9bd
c21f78dd1841121b52b861fd61e25e1a690b53dc
refs/heads/master
2020-05-15T20:00:32.301518
2019-05-01T12:15:40
2019-05-01T12:15:40
182,471,093
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6830986142158508, "alphanum_fraction": 0.6830986142158508, "avg_line_length": 37.727272033691406, "blob_id": "0e4db500d97a1687ec8cb3d1b50d7e92b17af9b6", "content_id": "432a9a62d4634f1efb266a4c7c42f2d5df9b284c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 115, "num_lines": 11, "path": "/posts/urls.py", "repo_name": "marianamendezrdz/marianamendezsite", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom django.contrib import admin\nfrom marianamendezsiteapp import views\nfrom . import views #. means from all\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^$', views.index, name='index'),\n url(r'^details/(?P<id>\\d+)/$', views.details, name='details'),\n #?P = parameter; <id> specifies id parameter; \\d means its a digit(number); + means at least one or more digits\n]\n" }, { "alpha_fraction": 0.8086956739425659, "alphanum_fraction": 0.8086956739425659, "avg_line_length": 22, "blob_id": "4d3962ec1868ca3ebd4c0fa30b2fe5af74b0aab9", "content_id": "e3e6ecda85b00ec1c43a0f3ce0ee3126605f3dfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 115, "license_type": "no_license", "max_line_length": 44, "num_lines": 5, "path": "/marianamendezsiteapp/apps.py", "repo_name": "marianamendezrdz/marianamendezsite", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass MarianamendezsiteappConfig(AppConfig):\n name = 'marianamendezsiteapp'\n" }, { "alpha_fraction": 0.48543688654899597, "alphanum_fraction": 0.6893203854560852, "avg_line_length": 16.16666603088379, "blob_id": "a3240748c1f5d95fd42b7f15c107bcc645f1e7dd", "content_id": "f8c164cb51cb772b2c10647833b2a855e9c31d40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 103, "license_type": "no_license", "max_line_length": 22, "num_lines": 6, "path": "/requirements.txt", "repo_name": "marianamendezrdz/marianamendezsite", "src_encoding": "UTF-8", "text": "dj-database-url==0.5.0\nDjango==1.10\ngunicorn==19.6.0\nPillow==5.2.0\nwhitenoise==3.2.1\npsycopg2==2.7.3.2\n" }, { "alpha_fraction": 0.7192546725273132, "alphanum_fraction": 0.7229813933372498, "avg_line_length": 39.25, "blob_id": "5fa12d201db8b6a9918e5df271d3fb7c3005e611", "content_id": "d19c34c5d103ddbffce01a89847f2afd9381382c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 805, "license_type": "no_license", "max_line_length": 112, "num_lines": 20, "path": "/posts/models.py", "repo_name": "marianamendezrdz/marianamendezsite", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom django.db import models\nfrom datetime import datetime\n\n# Create your models here.\nclass Posts(models.Model):\n title = models.CharField(max_length=200)\n body = models.TextField()\n created_at = models.DateTimeField(default=datetime.now, blank=True)\n def __str__(self):\n return self.title #makes it so that list of blog posts in django admin are entitled as the title written\n class Meta:\n verbose_name_plural = \"Posts\" #makes it so that new model in django admin is not plural\n\n#make sure to migrate new models!!!!!\n#make sure to migrate new models!!!!!\n#make sure to migrate new models!!!!!\n\n# create database file: --> python manage.py makemigrations [replace with model name]\n# create database table: --> python manage.py migrate\n" }, { "alpha_fraction": 0.8500000238418579, "alphanum_fraction": 0.8500000238418579, "avg_line_length": 19, "blob_id": "5154402b1571a98ee167417cf6e7dba104322cb9", "content_id": "215fde09b6e7d8fa23dc9296b14f4989d68eedbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 100, "license_type": "no_license", "max_line_length": 19, "num_lines": 5, "path": "/README.md", "repo_name": "marianamendezrdz/marianamendezsite", "src_encoding": "UTF-8", "text": "# marianamendezsite\n# marianamendezsite\n# marianamendezsite\n# marianamendezsite\n# marianamendezsite\n" } ]
5
boryas/eidetic
https://github.com/boryas/eidetic
2208d28486e08a2e14d9bbeaefca7eb47a5522d3
591f9ed8e06f349e127f470d5f1a03c71f4b4fcb
d871ffae6ec94195865a04d04aef6559efb6726c
refs/heads/master
2021-01-10T14:15:40.654350
2016-03-20T01:45:31
2016-03-20T01:45:31
53,647,022
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6681416034698486, "alphanum_fraction": 0.6681416034698486, "avg_line_length": 21.600000381469727, "blob_id": "1f8e643edaa56ae47e44cfcabc7250338e4703ad", "content_id": "0585771f1345eff1b7317101c7bfa67cea64ba94", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 226, "license_type": "permissive", "max_line_length": 67, "num_lines": 10, "path": "/lib/forget.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import rethinkdb as r\n\nimport db\n\ndef _forget_project(name, conn):\n db.get_table().filter(r.row['name'] == name).delete().run(conn)\n\ndef forget_project(name):\n conn = db.get_conn()\n return _forget_project(name, conn)\n" }, { "alpha_fraction": 0.6473684310913086, "alphanum_fraction": 0.6473684310913086, "avg_line_length": 26.941177368164062, "blob_id": "cfcef929fb79d1d7994510313849f16c3426ad81", "content_id": "cf565ae6fc098076a2be6d322aa0420220579603", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 950, "license_type": "permissive", "max_line_length": 81, "num_lines": 34, "path": "/cli/remember.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import click\n\nimport lib.remember\n\[email protected]()\[email protected]('-f', '--project-file', type=click.File('rb'))\ndef remember(project_file):\n '''\n Ask Eidetic to remember some information.\n\n You can pass a project file in a dead simple markdown format.\n If not, Eidetic will open up $EDITOR to let you edit a project\n in a tmp file.\n\n \\b\n Expected format:\n # <description>\n ## Purpose\n <High level purpose of the project>\n ## Desired outcomes\n * <outcome>\n ## Waiting on\n * <blocker>\n ## Actions\n * <action>\n ## Next Action\n * <action>'''\n if not project_file:\n name = click.prompt('Project name')\n category = click.prompt('Project category (e.g. business, pleasure)')\n project = lib.remember.parse_markdown_project_from_editor(name, category)\n else:\n project = lib.remember.parse_markdown_project_from_file(project_file)\n lib.remember.store_project(project)\n" }, { "alpha_fraction": 0.6506602764129639, "alphanum_fraction": 0.6530612111091614, "avg_line_length": 26.766666412353516, "blob_id": "31665b071bf8a2149c693e2e2d6da3021dfc2f96", "content_id": "b274a0ab8541088ba5e32a6b26935a9b8b3f7166", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 833, "license_type": "permissive", "max_line_length": 67, "num_lines": 30, "path": "/lib/recall/next_action.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import rethinkdb as r\n\nimport lib.db as db\n\ndef _get_next_action(actions):\n next_actions = [a for a in actions if a['next']]\n if not next_actions:\n return None\n return next_actions[0]['description']\n\ndef _recall_next_action(name, conn):\n c = db.get_table().filter({'name': name})['actions'].run(conn)\n project_actions = [actions for actions in c]\n if not project_actions:\n return None\n actions = project_actions[0]\n return _get_next_action(actions)\n\ndef _recall_next_actions(conn):\n c = db.get_table().run(conn)\n for project in c:\n yield project['name'], _get_next_action(project['actions'])\n\ndef recall_next_actions():\n conn = db.get_conn()\n return _recall_next_actions(conn)\n\ndef recall_next_action(name):\n conn = db.get_conn()\n return _recall_next_action(name, conn)\n" }, { "alpha_fraction": 0.6026375889778137, "alphanum_fraction": 0.603210985660553, "avg_line_length": 30.14285659790039, "blob_id": "0c2d74a94350e392c8471f4d3d065ee2ee1a702e", "content_id": "1cd77d9163108942b414ad71702afbb8a36ac9c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1744, "license_type": "permissive", "max_line_length": 68, "num_lines": 56, "path": "/lib/recall/project.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import markdown\nimport rethinkdb as r\n\nimport lib.db as db\n\ndef _format_project_html(project):\n md = _format_project_markdown(project)\n html = markdown.markdown(md, output_format='html5')\n return html\n\ndef _format_project_markdown(project):\n lines = []\n lines.append('# {}'.format(project['description']))\n lines.append('')\n lines.append('## Purpose')\n lines.append(project['purpose'])\n if 'outcomes' in project:\n lines.append('')\n lines.append('## Desired Outcomes')\n for outcome in project['outcomes']:\n lines.append(\"* {}\".format(outcome['description']))\n if 'waitings' in project:\n lines.append('')\n lines.append('## Waiting')\n for waiting in project['waitings']:\n lines.append(\"* {}\".format(waiting['description']))\n if 'actions' in project:\n lines.append('')\n lines.append('## Actions')\n for action in project['actions']:\n lines.append(\"* {}\".format(action['description']))\n return \"\\n\".join(lines)\n\ndef _recall_project(name, conn, format_fn):\n c = db.get_table().filter(r.row['name'] == name).run(conn)\n p = c.next()\n if not p:\n return None\n return format_fn(p)\n\ndef recall_project(name, format='md'):\n conn = db.get_conn()\n if format == 'md':\n return _recall_project(name, conn, _format_project_markdown)\n if format == 'html':\n return _recall_project(name, conn, _format_project_html)\n if format == 'json':\n return _recall_project(name, conn, id)\n\ndef _recall_names(conn):\n c = db.get_table().pluck('name').distinct().run(conn)\n return \" \".join([n['name'] for n in c])\n\ndef recall_names():\n conn = db.get_conn()\n return _recall_names(conn)\n" }, { "alpha_fraction": 0.7336448431015015, "alphanum_fraction": 0.7336448431015015, "avg_line_length": 24.68000030517578, "blob_id": "b8926ba30cff5f00f879eee04a7ba1ea18ffcfb0", "content_id": "36511b732ea0f03c26e0bf47d459249a49aab4ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 642, "license_type": "permissive", "max_line_length": 74, "num_lines": 25, "path": "/Readme.md", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "# Eidetic, a simple framework for Getting Things Done\n\n## Purpose\nEidetic remembers everything you tell it about your life's projects\nso that you can focus on completing them.\n\n## What does it do though?\nEidetic can remember a project for you, recall a project it has remembered\nand forget a project you aren't working on anymore.\n\n## More specifics?\n\n> Usage: edtc [OPTIONS] COMMAND [ARGS]...\n> \n> Options:\n>\n> --help Show this message and exit.\n> \n> Commands:\n>\n> forget Forget information Eidetic has remembered.\n>\n> recall Display information Eidetic has remembered.\n>\n> remember Ask Eidetic to remember some information.\n" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.550000011920929, "avg_line_length": 19, "blob_id": "a4f4e18671c62fde32d56f006faa53b97ee732d7", "content_id": "f5284438ae4c3a2604d598a85e07972964408306", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 60, "license_type": "permissive", "max_line_length": 26, "num_lines": 3, "path": "/server/main.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import server\nif __name__ == \"__main__\":\n server.serve()\n" }, { "alpha_fraction": 0.6281406879425049, "alphanum_fraction": 0.6532663106918335, "avg_line_length": 17.090909957885742, "blob_id": "c04c6d8e7ffaff80d935b9af7a1d107430de0039", "content_id": "483c93e42f921ecb67a94ee1bcac05192adfc27a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 199, "license_type": "permissive", "max_line_length": 57, "num_lines": 11, "path": "/lib/db.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import rethinkdb as r\n\nDB = 'eidetic'\nTABLE = 'projects'\n\ndef get_conn():\n conn = r.connect(host=\"localhost\", port=28015, db=DB)\n return conn\n\ndef get_table():\n return r.db(DB).table(TABLE)\n" }, { "alpha_fraction": 0.7788461446762085, "alphanum_fraction": 0.7788461446762085, "avg_line_length": 13.857142448425293, "blob_id": "74fbe8b9ab6930064fe64cd1e7df616965483d67", "content_id": "1ddca3c02c944288779ad8be5364e9c41d1d01bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "permissive", "max_line_length": 34, "num_lines": 14, "path": "/cli/edtc.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import readline\nimport click\n\nimport forget\nimport recall\nimport remember\n\[email protected]()\ndef cli():\n pass\n\ncli.add_command(forget.forget)\ncli.add_command(remember.remember)\ncli.add_command(recall.recall)\n" }, { "alpha_fraction": 0.6993603706359863, "alphanum_fraction": 0.6993603706359863, "avg_line_length": 23.6842098236084, "blob_id": "5ac76f676e4326cbc3f3dbef5da55449368847be", "content_id": "8957296a330541a9cfe3ec4be8316efb08dbec41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "permissive", "max_line_length": 73, "num_lines": 19, "path": "/cli/forget.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import click\nimport lib.forget\nimport lib.recall\n\[email protected]()\[email protected]_context\[email protected]('name', required=False)\ndef forget(ctx, name):\n '''\n Forget information Eidetic has remembered.\n\n If no name is given, Eidetic will list available project names\n\n If a name is given, Eidetic will forget everything about that project\n '''\n if not name:\n click.echo(lib.recall.recall_names())\n else:\n lib.forget.forget_project(name)\n" }, { "alpha_fraction": 0.6723163723945618, "alphanum_fraction": 0.6723163723945618, "avg_line_length": 24.8125, "blob_id": "c9a189a2099dae5053ecd2574690732d3a3f8d43", "content_id": "7d650b3784e64989c7485b3ac01063fb62d9ee5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1239, "license_type": "permissive", "max_line_length": 81, "num_lines": 48, "path": "/cli/recall.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import click\n\nimport lib.recall.next_action\nimport lib.recall.project\n\[email protected]()\[email protected]_context\ndef recall(ctx):\n '''\n Display information Eidetic has remembered.\n\n Can recall projects and next actions.\n '''\n pass\n\[email protected]()\[email protected]_context\[email protected]('name', required=False)\ndef project(ctx, name):\n '''\n Display information about a project.\n\n If no name is given, Eidetic will list available project names\n\n If a name is given, Eidetic will show detailed information about that project\n '''\n if not name:\n click.echo(lib.recall.project.recall_names())\n else:\n for p_md in lib.recall.project.recall_project(name):\n click.echo(p_md)\n\[email protected]()\[email protected]_context\[email protected]('name', required=False)\ndef next_action(ctx, name):\n '''\n Display information about next actions to take\n\n If no name is given, return all next actions.\n\n If a name is given, return the next action for that project.\n '''\n if not name:\n for p, next_action in lib.recall.next_action.recall_next_actions():\n click.echo('{}: {}'.format(p, next_action))\n else:\n click.echo(lib.recall.next_action.recall_next_action(name))\n" }, { "alpha_fraction": 0.7214611768722534, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 18.909090042114258, "blob_id": "6aae2543ed678462abfeb30325cf3d7c768e108f", "content_id": "c11dad8391bbe6dcf808a905dd222f46cf45f2a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "permissive", "max_line_length": 41, "num_lines": 11, "path": "/server/server.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import BaseHTTPServer\n\nimport handler\n\nSERVER_CLS = BaseHTTPServer.HTTPServer\nHANDLER_CLS = handler.EideticHTTPHandler\nADDR = ('', 8000)\n\ndef serve():\n httpd = SERVER_CLS(ADDR, HANDLER_CLS)\n httpd.serve_forever()\n" }, { "alpha_fraction": 0.5644055008888245, "alphanum_fraction": 0.5724085569381714, "avg_line_length": 26.621051788330078, "blob_id": "574d5a5d6cf3e76195b645956c6d493f2395f7a0", "content_id": "85a302e6a6cb531a396f76ec22739829f4ac2cac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2624, "license_type": "permissive", "max_line_length": 63, "num_lines": 95, "path": "/lib/remember.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import os\nimport rethinkdb as r\nimport subprocess\nimport tempfile\n\nimport db\n\nMD_FORMAT = \"\"\"# <description>\n## Purpose\n<High level purpose of the project>\n## Desired outcomes\n* <outcome>\n## Waiting on\n* <blocker>\n## Actions\n* <action>\n## Next Action\n* <action>\"\"\"\n\ndef _get_tags_from_filename(fname):\n dir, file = os.path.split(fname)\n _, dir = os.path.split(dir)\n file, _ = os.path.splitext(file)\n return dir, file\n\ndef _parse_h2(h2):\n h2 = h2.lower()\n if 'action' in h2:\n if 'next' in h2:\n return 'action', True\n return 'action', False\n if 'outcome' in h2:\n return 'outcome', False\n if 'waiting' in h2:\n if 'blocked' in h2:\n return 'waiting', True\n return 'waiting', False\n return h2, False\n\ndef _pluralize(s):\n return s+'s'\n\ndef _depluralize(s):\n if s.endswith('s'):\n return s[:-1]\n\ndef _parse_markdown_project(project_lines, name, category):\n project = {'name': name, 'tags': [category]}\n for line in project_lines:\n line = line.strip()\n if not line:\n continue\n if line.startswith('# '):\n project['description'] = line.rpartition('# ')[2]\n elif line.startswith('## '):\n h2, next = _parse_h2(line.rpartition('## ')[2])\n else:\n if line.startswith('* '):\n if _pluralize(h2) not in project:\n project[_pluralize(h2)] = []\n item = line.rpartition('* ')[2]\n project[_pluralize(h2)].append(\n {'description': item,\n 'next': next})\n else:\n project[h2] = line\n return project\n\ndef _get_project_from_editor():\n EDITOR = os.environ.get('EDITOR', 'vim')\n with tempfile.NamedTemporaryFile(suffix=\".md\") as f:\n f.write(MD_FORMAT)\n f.flush()\n subprocess.call([EDITOR, f.name])\n f.seek(0)\n return f.readlines()\n\ndef parse_markdown_project_from_editor(name, category):\n lines = _get_project_from_editor()\n return _parse_markdown_project(lines, name, category)\n\ndef parse_markdown_project_from_file(project_file):\n category, name = _get_tags_from_filename(project_file.name)\n lines = project_file.readlines()\n return _parse_markdown_project(lines, name, category)\n\ndef store_project(project):\n conn = db.get_conn()\n f = r.row['name'] == project['name']\n exists = bool(list(\n db.get_table().filter(f).run(conn)))\n if exists:\n db.get_table().filter(f).update(project).run(conn)\n else:\n db.get_table().insert(project).run(conn)\n" }, { "alpha_fraction": 0.49367088079452515, "alphanum_fraction": 0.501265823841095, "avg_line_length": 16.954545974731445, "blob_id": "a4911e364fc4409ef911b2cc3b9eb06122730863", "content_id": "e815f426483d15dc1f27e30ebfde06b33c52e6f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "permissive", "max_line_length": 43, "num_lines": 22, "path": "/setup.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nsetup(\n name='eidetic',\n version='0.1.0',\n packages=find_packages(),\n install_requires=[\n 'click',\n 'markdown',\n 'rethinkdb',\n ],\n package_data = {\n '': ['*.md'],\n },\n author='Boris Burkov',\n author_email='[email protected]',\n\n entry_points='''\n [console_scripts]\n edtc=cli.edtc:cli\n ''',\n)\n" }, { "alpha_fraction": 0.5512934923171997, "alphanum_fraction": 0.566458523273468, "avg_line_length": 31.02857208251953, "blob_id": "17bdbfda9f73c353221418164e5c0ba66fcf803a", "content_id": "49b5193856d25ac918bfc482f21274abe89a535a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1121, "license_type": "permissive", "max_line_length": 76, "num_lines": 35, "path": "/server/handler.py", "repo_name": "boryas/eidetic", "src_encoding": "UTF-8", "text": "import BaseHTTPServer\n\nimport lib.recall.project\n\nclass EideticHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n\n def _send_headers(self):\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n\n def _send_html(self, title, html):\n self.wfile.write(\"<html>\")\n self.wfile.write(\"<head><title>{}</title></head>\".format(title))\n self.wfile.write(\"<body>{}</body>\".format(html))\n self.wfile.write(\"</html>\")\n\n def do_HEAD(self):\n self.send_response(200)\n self._send_headers()\n\n def do_GET(self):\n chunks = self.path.split('/')[1:]\n if len(chunks) == 0:\n self.send_response(404)\n if len(chunks) == 1:\n command = chunks[0]\n self.send_response(200)\n self._send_headers()\n elif len(chunks) == 2:\n command, project = chunks\n self.send_response(200)\n self._send_headers()\n title = '{}:{}'.format(command, project)\n html = lib.recall.project.recall_project(project, format='html')\n self._send_html(title, html)\n" } ]
14
doytsujin/tacticalrmm
https://github.com/doytsujin/tacticalrmm
e1be7ad7950bb95c4b37dd63ac03eb323115d866
7fb79e0bcce62dbb892fb36665ff6d7135d7bebf
30268e3918f8dc079a757e985fee374605c931b2
refs/heads/master
2021-03-21T14:02:24.858487
2020-02-24T07:11:15
2020-02-24T07:11:15
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.595508337020874, "alphanum_fraction": 0.6027529835700989, "avg_line_length": 34.09321975708008, "blob_id": "133f319a7b5cbb22bc722822bd2f1617b04c833c", "content_id": "2df164a254b5354db71f046a6ecb693ee906511f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8282, "license_type": "permissive", "max_line_length": 114, "num_lines": 236, "path": "/api/tacticalrmm/agents/tasks.py", "repo_name": "doytsujin/tacticalrmm", "src_encoding": "UTF-8", "text": "import os\nimport subprocess\nfrom loguru import logger\nfrom time import sleep\n\nfrom tacticalrmm.celery import app\nfrom django.conf import settings\n\nfrom agents.models import Agent\n\nlogger.configure(**settings.LOG_CONFIG)\n\n\[email protected]\ndef get_wmi_detail_task(pk):\n sleep(30)\n agent = Agent.objects.get(pk=pk)\n resp = agent.salt_api_cmd(\n hostname=agent.salt_id, timeout=30, func=\"system_info.system_info\"\n )\n agent.wmi_detail = resp.json()[\"return\"][0][agent.salt_id]\n agent.save(update_fields=[\"wmi_detail\"])\n return \"ok\"\n\n\[email protected]\ndef sync_salt_modules_task(pk):\n agent = Agent.objects.get(pk=pk)\n logger.info(f\"Attempting to sync salt modules on {agent.hostname}\")\n sleep(10)\n resp = agent.salt_api_cmd(hostname=agent.salt_id, timeout=30, func=\"test.ping\")\n try:\n data = resp.json()\n except Exception as e:\n logger.error(f\"Unable to contact agent {agent.hostname}: {e}\")\n return f\"Unable to contact agent {agent.hostname}: {e}\"\n else:\n try:\n ping = data[\"return\"][0][agent.salt_id]\n except KeyError as j:\n logger.error(f\"{j}: Unable to contact agent (is salt installed properly?)\")\n return f\"{j}: Unable to contact agent (is salt installed properly?)\"\n else:\n resp2 = agent.salt_api_cmd(\n hostname=agent.salt_id, timeout=60, func=\"saltutil.sync_modules\"\n )\n try:\n data2 = resp2.json()\n except Exception as f:\n logger.error(f\"Unable to contact agent {agent.hostname}: {f}\")\n return f\"Unable to contact agent {agent.hostname}: {f}\"\n else:\n # TODO fix return type\n logger.info(f\"Successfully synced salt modules on {agent.hostname}\")\n return f\"Successfully synced salt modules on {agent.hostname}\"\n\n\[email protected]\ndef uninstall_agent_task(pk, wait=True):\n agent = Agent.objects.get(pk=pk)\n agent.uninstall_inprogress = True\n agent.save(update_fields=[\"uninstall_inprogress\"])\n logger.info(f\"{agent.hostname} uninstall task is running\")\n\n if wait:\n logger.info(f\"{agent.hostname} waiting 90 seconds before uninstalling\")\n sleep(90) # need to give salt time to startup on the minion\n\n resp2 = agent.salt_api_cmd(\n hostname=agent.salt_id,\n timeout=60,\n func=\"cp.get_file\",\n arg=[\"salt://scripts/removeagent.exe\", \"C:\\\\Windows\\\\Temp\\\\\"],\n )\n data2 = resp2.json()\n if not data2[\"return\"][0][agent.salt_id]:\n logger.error(f\"{agent.hostname} unable to copy file\")\n return f\"{agent.hostname} unable to copy file\"\n\n agent.salt_api_cmd(\n hostname=agent.salt_id,\n timeout=500,\n func=\"cmd.script\",\n arg=\"salt://scripts/uninstall.bat\",\n )\n\n logger.info(f\"{agent.hostname} was successfully uninstalled\")\n return f\"{agent.hostname} was successfully uninstalled\"\n\n\ndef service_action(hostname, action, service):\n return Agent.salt_api_cmd(\n hostname=hostname,\n timeout=30,\n func=\"cmd.script\",\n arg=\"C:\\\\Program Files\\\\TacticalAgent\\\\nssm.exe\",\n kwargs={\"args\": f\"{action} {service}\"},\n )\n\n\[email protected]\ndef update_agent_task(pk, version):\n\n agent = Agent.objects.get(pk=pk)\n\n errors = []\n file = f\"/srv/salt/scripts/{version}.exe\"\n ver = version.split(\"winagent-v\")[1]\n\n # download the release from github if the file doesn't already exist in /srv\n if not os.path.exists(file):\n r = Agent.get_github_versions()\n git_versions = r[\"versions\"]\n data = r[\"data\"] # full response from github\n versions = {}\n\n for i, release in enumerate(data):\n versions[i] = release[\"name\"]\n\n key = [k for k, v in versions.items() if v == version][0]\n\n download_url = data[key][\"assets\"][0][\"browser_download_url\"]\n\n p = subprocess.run([\"wget\", download_url, \"-O\", file], capture_output=True)\n\n app_dir = \"C:\\\\Program Files\\\\TacticalAgent\"\n temp_dir = \"C:\\\\Windows\\\\Temp\"\n\n logger.info(\n f\"{agent.hostname} is attempting update from version {agent.version} to {ver}\"\n )\n\n # send the release to the agent\n r = agent.salt_api_cmd(\n hostname=agent.salt_id,\n timeout=300,\n func=\"cp.get_file\",\n arg=[f\"salt://scripts/{version}.exe\", temp_dir],\n )\n # success return example: {'return': [{'HOSTNAME': 'C:\\\\Windows\\\\Temp\\\\winagent-v0.1.12.exe'}]}\n # error return example: {'return': [{'HOSTNAME': ''}]}\n if not r.json()[\"return\"][0][agent.salt_id]:\n agent.is_updating = False\n agent.save(update_fields=[\"is_updating\"])\n logger.error(\n f\"{agent.hostname} update failed to version {ver} (unable to copy installer)\"\n )\n return f\"{agent.hostname} update failed to version {ver} (unable to copy installer)\"\n\n services = (\n \"tacticalagent\",\n \"checkrunner\",\n \"winupdater\",\n )\n\n for svc in services:\n r = service_action(agent.salt_id, \"stop\", svc)\n # returns non 0 if error\n if r.json()[\"return\"][0][agent.salt_id][\"retcode\"]:\n errors.append(f\"failed to stop {svc}\")\n logger.error(\n f\"{agent.hostname} was unable to stop service {svc}. Update cancelled\"\n )\n\n # start the services if some of them failed to stop, then don't continue\n if errors:\n agent.is_updating = False\n agent.save(update_fields=[\"is_updating\"])\n for svc in services:\n service_action(agent.salt_id, \"start\", svc)\n return \"stopping services failed. started again\"\n\n # install the update\n # success respose example: {'return': [{'HOSTNAME': {'retcode': 0, 'stderr': '', 'stdout': '', 'pid': 3452}}]}\n # error response example: {'return': [{'HOSTNAME': 'The minion function caused an exception: Traceback...'}]}\n try:\n r = agent.salt_api_cmd(\n hostname=agent.salt_id,\n timeout=120,\n func=\"cmd.script\",\n arg=f\"{temp_dir}\\\\{version}.exe\",\n kwargs={\"args\": \"/VERYSILENT /SUPPRESSMSGBOXES\"},\n )\n except Exception:\n agent.is_updating = False\n agent.save(update_fields=[\"is_updating\"])\n return (\n f\"TIMEOUT: failed to run inno setup on {agent.hostname} for version {ver}\"\n )\n\n if \"minion function caused an exception\" in r.json()[\"return\"][0][agent.salt_id]:\n agent.is_updating = False\n agent.save(update_fields=[\"is_updating\"])\n return (\n f\"EXCEPTION: failed to run inno setup on {agent.hostname} for version {ver}\"\n )\n\n if r.json()[\"return\"][0][agent.salt_id][\"retcode\"]:\n agent.is_updating = False\n agent.save(update_fields=[\"is_updating\"])\n logger.error(f\"failed to run inno setup on {agent.hostname} for version {ver}\")\n return f\"failed to run inno setup on {agent.hostname} for version {ver}\"\n\n # update the version in the agent's local database\n r = agent.salt_api_cmd(\n hostname=agent.salt_id,\n timeout=45,\n func=\"sqlite3.modify\",\n arg=[\n \"C:\\\\Program Files\\\\TacticalAgent\\\\winagent\\\\agentdb.db\",\n f'UPDATE agentstorage SET version = \"{ver}\"',\n ],\n )\n # success return example: {'return': [{'FSV': True}]}\n # error return example: {'return': [{'HOSTNAME': 'The minion function caused an exception: Traceback...'}]}\n sql_ret = type(r.json()[\"return\"][0][agent.salt_id])\n if sql_ret is not bool and sql_ret is str:\n if (\n \"minion function caused an exception\"\n in r.json()[\"return\"][0][agent.salt_id]\n ):\n logger.error(f\"failed to update {agent.hostname} local database\")\n\n if not r.json()[\"return\"][0][agent.salt_id]:\n logger.error(\n f\"failed to update {agent.hostname} local database to version {ver}\"\n )\n\n # start the services\n for svc in services:\n service_action(agent.salt_id, \"start\", svc)\n\n agent.is_updating = False\n agent.save(update_fields=[\"is_updating\"])\n logger.info(f\"{agent.hostname} was successfully updated to version {ver}\")\n return f\"{agent.hostname} was successfully updated to version {ver}\"\n" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 11, "blob_id": "43ecdfba85e36cef0ada11b30647bc39511cf578", "content_id": "7bbc460ff7241138e2b7c77cbaa4eba30b9498c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 12, "license_type": "permissive", "max_line_length": 11, "num_lines": 1, "path": "/api/tacticalrmm/requirements-test.txt", "repo_name": "doytsujin/tacticalrmm", "src_encoding": "UTF-8", "text": "mock==4.0.1\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6228287816047668, "avg_line_length": 16.521739959716797, "blob_id": "ac1f64e2a78102631dd48573f5dd22c132acfeb5", "content_id": "1a3d75b407f0bede0ad7e4b6984d3b535fd0d17b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 403, "license_type": "permissive", "max_line_length": 80, "num_lines": 23, "path": "/scripts/removeagent.go", "repo_name": "doytsujin/tacticalrmm", "src_encoding": "UTF-8", "text": "package main\n\nimport(\n\t\"os/exec\"\n\t\"os\"\n)\n\nfunc main(){\n\tunins_file := \"C:\\\\Program Files\\\\TacticalAgent\\\\unins000.exe\"\n\n\tif fileExists(unins_file) {\n\t\tc := exec.Command(\"cmd\", \"/C\", unins_file, \"/VERYSILENT\", \"/SUPPRESSMSGBOXES\")\n\t\tc.Run()\n\t}\n}\n\nfunc fileExists(filename string) bool {\n info, err := os.Stat(filename)\n if os.IsNotExist(err) {\n return false\n }\n return !info.IsDir()\n}\n" }, { "alpha_fraction": 0.613545835018158, "alphanum_fraction": 0.613545835018158, "avg_line_length": 21.81818199157715, "blob_id": "a0586c8d273402a6b373dddf18f7fbc4def2b66f", "content_id": "daf73a106dbddb5cdbab4083d9158a8ec5e0f92f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "permissive", "max_line_length": 62, "num_lines": 11, "path": "/_modules/get_services.py", "repo_name": "doytsujin/tacticalrmm", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nimport psutil\n\n\ndef get_services():\n try:\n svc = [x.as_dict() for x in psutil.win_service_iter()]\n except Exception:\n svc = {\"error\": \"error getting services\"}\n finally:\n return svc\n" }, { "alpha_fraction": 0.4852173924446106, "alphanum_fraction": 0.6921738982200623, "avg_line_length": 15.428571701049805, "blob_id": "4db1067bcf1a2583ceb7766fff95369fcccb9df6", "content_id": "4ee59be97a6da3d1087a3b06a472ba1e9c183512", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 575, "license_type": "permissive", "max_line_length": 27, "num_lines": 35, "path": "/api/tacticalrmm/requirements.txt", "repo_name": "doytsujin/tacticalrmm", "src_encoding": "UTF-8", "text": "amqp==2.5.2\nasgiref==3.2.3\nbilliard==3.6.2.0\ncelery==4.4.0\ncertifi==2019.11.28\ncffi==1.14.0\nchardet==3.0.4\ncryptography==2.8\ndecorator==4.4.1\ndistro==1.4.0\nDjango==3.0.3\ndjango-cors-headers==3.2.1\ndjango-rest-knox==4.1.0\ndjangorestframework==3.11.0\nidna==2.8\nimportlib-metadata==1.5.0\nkombu==4.6.7\nloguru==0.4.1\nmore-itertools==8.2.0\npackaging==20.1\npsycopg2-binary==2.8.4\npycparser==2.19\npyotp==2.3.0\npyparsing==2.4.6\npytz==2019.3\nqrcode==6.1\nredis==3.4.1\nrequests==2.22.0\nsix==1.14.0\nsqlparse==0.3.0\nurllib3==1.25.8\nuWSGI==2.0.18\nvalidators==0.14.2\nvine==1.3.0\nzipp==2.2.0\n" } ]
5
fzjawed/123-Number-Flip
https://github.com/fzjawed/123-Number-Flip
65f8a0525b9ab329723779e88466d7e9374b7517
c46601a7f49a0dc03255dfd62cbe86f336212460
6b41c6bc8dc809460906757486d6c51a3a9f42d4
refs/heads/main
2023-05-27T11:53:45.855519
2021-05-28T14:33:57
2021-05-28T14:33:57
371,727,510
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7061946988105774, "alphanum_fraction": 0.7451327443122864, "avg_line_length": 61.55555725097656, "blob_id": "4fb4433868ce7d5975ab9dfdcae09e233f834cfa", "content_id": "1ebbe63c000877c4e75b6df212885c7dc1ca7520", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 571, "license_type": "no_license", "max_line_length": 277, "num_lines": 9, "path": "/README.md", "repo_name": "fzjawed/123-Number-Flip", "src_encoding": "UTF-8", "text": "# 123-Number-Flip\n\n>28th May 2021 05:30 PM\n\nThis question was easy but I initially got the wrong answer because I missed ``' '`` 🙂🔪\n\n***Question: You are given an integer n consisting of digits 1, 2, and 3 and you can flip one digit to a 3. Return the maximum number you can make.***\n\nBasically every number will only be made up of 1,2 or 3 and so you just have to find the first index that is not 3 and replace it with 3 and immediately break out of the loop. This question would be a little more complex if the numbers were made up of different digits I think. \n\n" }, { "alpha_fraction": 0.3686440587043762, "alphanum_fraction": 0.37711864709854126, "avg_line_length": 24.44444465637207, "blob_id": "f0545385773748c8b7c8c60cca59ceb30ed294a1", "content_id": "a5b43160617dd6de95a1e9de11296666ce2960d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 32, "num_lines": 9, "path": "/123-Flip.py", "repo_name": "fzjawed/123-Number-Flip", "src_encoding": "UTF-8", "text": "class Solution:\r\n def solve(self, n):\r\n x = list(str(n))\r\n for i in range(len(x)):\r\n if x[i] != '3':\r\n x[i] = '3'\r\n break\r\n result = int(\"\".join(x))\r\n return result" } ]
2
carpedavid/Quill
https://github.com/carpedavid/Quill
653c6fdb67b7abc3a5028162358c69deece1a58b
6761bf6be38a211e01ef5d6455f23e0b150eb5b4
0b9c5207fb278544317a140af6c77d58dfcd5915
refs/heads/master
2020-06-05T01:00:43.829527
2014-08-18T01:21:57
2014-08-18T01:21:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5717131495475769, "alphanum_fraction": 0.5756971836090088, "avg_line_length": 22.904762268066406, "blob_id": "53850eae26ec4e5376a70d03e5dde8a17e2833fe", "content_id": "37a1b66ed7c282cead3234be32df15314293f53a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2008, "license_type": "no_license", "max_line_length": 79, "num_lines": 84, "path": "/SceneEngine.py", "repo_name": "carpedavid/Quill", "src_encoding": "UTF-8", "text": "__author__ = 'carpedavid'\nimport GameEngine\n\n\nclass EventEffect:\n def __init__(self):\n self.target = 0\n self.attribute = \"\"\n self.value = 0\n\n\nclass EventPrerequisite:\n def __init__(self):\n self.target = 0\n self.attribute = \"\"\n self.value = 0\n\n def valid_event(self, character):\n if character.attitudes[self.attribute] >= self.value:\n return True\n else:\n return False\n\n\nclass Event:\n def __init__(self):\n self.event_id = 0\n self.display_text = \"\"\n self.effects = []\n self.prerequisites = []\n self.target = 0\n\n\nclass Line(Event):\n def __init__(self, event_id, display_text, effects, prerequisites, target):\n Event.__init__(self)\n self.event_id = event_id\n self.display_text = display_text\n self.effects = effects\n self.prerequisites = prerequisites\n self.target = target\n\n\nclass Action(Event):\n def __init__(self, event_id, display_text, effects, prerequisites, target):\n Event.__init__(self)\n self.event_id = event_id\n self.display_text = display_text\n self.effects = effects\n self.prerequisites = prerequisites\n self.target = target\n\n\nclass StageDirection(Event):\n def __init__(self, event_id, display_text, target):\n Event.__init__(self)\n self.event_id = event_id\n self.display_text = display_text\n self.target = target\n\n\nclass Choice(Event):\n def __init__(self, event_id, display_text):\n Event.__init__(self)\n self.event_id = event_id\n self.display_text = display_text\n self.events = []\n\n def make_choice(self, event_id):\n return self.events[event_id].target\n\n\nclass SceneEngine:\n def __init__(self):\n self.scene_id = 0\n self.characters = []\n self.events = []\n self.current_event_node = 0\n\n def load_scene(self, scene_id):\n pass\n\n def get_event(self, event_id):\n pass\n" }, { "alpha_fraction": 0.523809552192688, "alphanum_fraction": 0.5317460298538208, "avg_line_length": 17.071428298950195, "blob_id": "6c6a2f3134d722add8c7d331fc567f6ae652e52b", "content_id": "45c43f21f229a3307b60fd9af2bef41327975d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 28, "num_lines": 14, "path": "/GameEngine.py", "repo_name": "carpedavid/Quill", "src_encoding": "UTF-8", "text": "__author__ = 'carpedavid'\n\n\nclass Character:\n def __init__(self):\n self.name = \"\"\n self.attitudes = []\n self.affinities = []\n\n\nclass CharacterAttribute:\n def __init__(self):\n self.attribute = \"\"\n self.value = 10" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5, "avg_line_length": 12.333333015441895, "blob_id": "df3767c05d4d32a83d8398d3086fc0f9f2f31591", "content_id": "69bb11f49ca9f47bf98d5c6d5a0b447ad35c12b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 25, "num_lines": 6, "path": "/quill.py", "repo_name": "carpedavid/Quill", "src_encoding": "UTF-8", "text": "__author__ = 'carpedavid'\n\nclass Quill():\n\n def __init__(self):\n pass\n\n\n" } ]
3
Stephannils/mac_changer
https://github.com/Stephannils/mac_changer
229fcd77f4802f932701d0c46f8e260606298952
ecb50c0e3c786a13bddbd3fc9b98516c0cdafae6
1668e735058c5a78ef01ceeda817e38335508c18
refs/heads/main
2023-02-13T07:11:27.230532
2021-01-20T03:41:53
2021-01-20T03:41:53
329,123,713
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6232476830482483, "alphanum_fraction": 0.6244158744812012, "avg_line_length": 26.612903594970703, "blob_id": "70f0162d840dc5537a452012e60484e438f82e3b", "content_id": "7406e6db6443c87410b89a33a19316996db8f752", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1712, "license_type": "no_license", "max_line_length": 84, "num_lines": 62, "path": "/mac_changer.py", "repo_name": "Stephannils/mac_changer", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport subprocess\nimport optparse\nimport re\nimport sys\n\n\ndef get_arguments():\n parser = optparse.OptionParser()\n parser.add_option(\"-i\", \"--interface\", dest=\"interface\",\n help=\"Interface to change MAC address\")\n parser.add_option(\"-m\", \"--mac\", dest=\"new_mac\", help=\"New MAC address\")\n\n (options, arguments) = parser.parse_args()\n\n if not options.interface:\n parser.error(\n \"Please specifiy interface. Use --help for more information\")\n elif not options.new_mac:\n parser.error(\n \"Please specify new MAC address. User --help for more information\")\n\n return options\n\n\ndef change_mac(interface, new_mac):\n old_mac = get_mac(interface)\n print(\n f\"Changing MAC address for {interface} from {old_mac} to {new_mac}\")\n\n subprocess.call([\"sudo\", \"ifconfig\", interface, \"down\"])\n subprocess.call(\n [\"sudo\", \"ifconfig\", interface, \"hw\", \"ether\", new_mac])\n subprocess.call([\"sudo\", \"ifconfig\", interface, \"up\"])\n\n\ndef check_mac(req, res):\n if req == res:\n print(f\"MAC address changed to {req}\")\n else:\n print(f\"Could not change MAC address. Please try again\")\n\n\ndef get_mac(interface):\n ifconfig_result = subprocess.check_output([\"ifconfig\", interface])\n mac = re.search(r\"\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w\",\n str(ifconfig_result))\n\n if mac:\n return mac.group(0)\n else:\n print(\"Interface has no MAC address, Please try with a different interface\")\n sys.exit()\n\n\ntry:\n options = get_arguments()\n change_mac(options.interface, options.new_mac)\n check_mac(options.new_mac, get_mac(options.interface))\nexcept:\n pass\n" }, { "alpha_fraction": 0.6561086177825928, "alphanum_fraction": 0.7194570302963257, "avg_line_length": 54.25, "blob_id": "891db850f2903616829d248534d0b02adfe4472d", "content_id": "9f2d38dca07681cadaeca685853a25b93bfe5674", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 221, "license_type": "no_license", "max_line_length": 149, "num_lines": 4, "path": "/README.md", "repo_name": "Stephannils/mac_changer", "src_encoding": "UTF-8", "text": "# mac_changer\nJust a simple mac address changer for linux in python. use the interface (-i, --interface) and new mac address (-m, --mac) as command line arguments:\n\ne.g. python3 ma_changer.py -i eth0 -m 00:11:22:33:44:55\n" } ]
2
Kludex/serverping
https://github.com/Kludex/serverping
eb24bf3d1c77a4936c203d558ca587eaf31c72e8
573cd6818baed82b695250e7f8b8999b3ac43b7b
1f67291af6bb8bfc0133744d1f70ff9f0ab0a1dc
refs/heads/master
2023-01-25T04:03:54.495865
2020-11-27T00:31:59
2020-11-27T00:31:59
316,364,176
5
1
null
null
null
null
null
[ { "alpha_fraction": 0.626334547996521, "alphanum_fraction": 0.626334547996521, "avg_line_length": 13.789473533630371, "blob_id": "e6a3b17407b60e9b27f364d7c4815fc7a6954f43", "content_id": "84bccf27413433dde9d6abd6637c1eb433108de4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "permissive", "max_line_length": 33, "num_lines": 19, "path": "/serverpinger/config.py", "repo_name": "Kludex/serverping", "src_encoding": "UTF-8", "text": "from pydantic import BaseSettings\n\n\nclass Settings(BaseSettings):\n SERVER_NAME: str\n HOST: str\n PORT: int\n\n SLACK_API_TOKEN: str\n CHANNEL_ID: str\n\n PING_TIME: int\n\n class Config:\n case_sensitive = False\n env_file = \".env\"\n\n\nsettings = Settings()\n" }, { "alpha_fraction": 0.6753755807876587, "alphanum_fraction": 0.6753755807876587, "avg_line_length": 32.28260803222656, "blob_id": "80aa43cc03c00ccc974676f7087202ec201ead4b", "content_id": "4cfe35acb1ff768d2c168b2001c9ef50ca0098f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1531, "license_type": "permissive", "max_line_length": 86, "num_lines": 46, "path": "/serverpinger/main.py", "repo_name": "Kludex/serverping", "src_encoding": "UTF-8", "text": "import logging\nimport socket\n\nfrom fastapi import FastAPI\nfrom fastapi_utils.tasks import repeat_every\nfrom slack import WebClient\n\nfrom serverpinger.config import settings\nfrom serverpinger.constants import ServerState\n\napp = FastAPI()\n\nserver_state = ServerState.UP\n\nclient = WebClient(token=settings.SLACK_API_TOKEN)\n\nuvicorn_logger = logging.getLogger(\"uvicorn\")\nlogger = logging.getLogger(__name__)\nlogger.handlers = uvicorn_logger.handlers\nlogger.setLevel(logging.WARNING)\n\n\[email protected]_event(\"startup\")\n@repeat_every(seconds=settings.PING_TIME, raise_exceptions=True)\ndef startup_event() -> None:\n global server_state\n host, port = settings.HOST, settings.PORT\n channel_id = settings.CHANNEL_ID\n server = settings.SERVER_NAME\n\n args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)\n for family, socktype, proto, _, sockaddr in args:\n s = socket.socket(family, socktype, proto)\n try:\n s.connect(sockaddr)\n except socket.error:\n if server_state == ServerState.UP:\n client.chat_postMessage(channel=channel_id, text=f\"{server} is down!\")\n logger.warning(\"%s changed from ON to OFF.\", server)\n server_state = ServerState.DOWN\n else:\n if server_state == ServerState.DOWN:\n client.chat_postMessage(channel=channel_id, text=f\"{server} is up!\")\n logger.warning(\"%s changed from OFF to ON.\", server)\n server_state = ServerState.UP\n s.close()\n" }, { "alpha_fraction": 0.715049684047699, "alphanum_fraction": 0.715049684047699, "avg_line_length": 26.27083396911621, "blob_id": "916fff016c92ddcd3d9c43f06d79c1ffbb0a1e7e", "content_id": "7a6fcf61ca092487d4350eba4e487abb345fd456", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1309, "license_type": "permissive", "max_line_length": 142, "num_lines": 48, "path": "/README.md", "repo_name": "Kludex/serverping", "src_encoding": "UTF-8", "text": "# Server Ping\n\nA FastAPI application that pings a server from time to time to know its status.\n\n## Installation\n\nWe're using [poetry](https://python-poetry.org/) as package manager, so in case you don't have it:\n\n``` bash\npip install poetry\n```\n\nAs for the dependencies, you just need to:\n\n``` bash\npoetry install\n```\n\n## Usage\n\nThe usage is pretty simple. But I'll give the complete information you need to do it.\n\nFirst of all, you'll need an `.env` file, so I recommend you to copy the `env.example` and change its name.\n\n### Variables\n\nThe variables you need are:\n\n* `SLACK_API_TOKEN` : The slack API token that you can get from your [slack app environment](https://api.slack.com/apps/).\n* `CHANNEL_ID` : You can get it from web slack, as the channels always have the same format: `app.slack.com/client/<SERVER_ID>/<CHANNEL_ID>` .\n* `HOST` : Server host.\n* `PORT` : Server port.\n* `SERVER_NAME` : The server name, doesn't need to be the real one.\n* `PING_TIME` : Time interval on which you'll ping the server.\n\n### Run the server\n\nUvicorn is all we need.\n\n``` bash\nuvicorn serverping:app\n```\n\nYou can pass [additional parameters](https://www.uvicorn.org/settings/) to `uvicorn` if you want, but the above command should be enough.\n\n## License\n\nThis project is licensed under the terms of the MIT license.\n" }, { "alpha_fraction": 0.6172839403152466, "alphanum_fraction": 0.6172839403152466, "avg_line_length": 12.5, "blob_id": "83fde4aafe6c3c87c53842aadfea8dfe598b8a80", "content_id": "b0b81949f4dd9f34bdf8a433c5b1ec4e3e9efbf4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 81, "license_type": "permissive", "max_line_length": 24, "num_lines": 6, "path": "/serverpinger/constants.py", "repo_name": "Kludex/serverping", "src_encoding": "UTF-8", "text": "from enum import Enum\n\n\nclass ServerState(Enum):\n DOWN = \"down\"\n UP = \"up\"\n" }, { "alpha_fraction": 0.5802139043807983, "alphanum_fraction": 0.644385039806366, "avg_line_length": 18.6842098236084, "blob_id": "5993593d8d0561ea3316d20c420bac4c42f12bf4", "content_id": "eea1274128d1732c88cf1aff59b6c88280a7214a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 374, "license_type": "permissive", "max_line_length": 41, "num_lines": 19, "path": "/pyproject.toml", "repo_name": "Kludex/serverping", "src_encoding": "UTF-8", "text": "[tool.poetry]\nname = \"serverpinger\"\nversion = \"0.1.0\"\ndescription = \"\"\nauthors = [\"Marcelo Trylesinski <[email protected]>\"]\n\n[tool.poetry.dependencies]\npython = \"^3.6\"\nfastapi = \"^0.61.2\"\nfastapi-utils = \"^0.2.1\"\nslackclient = \"^2.9.3\"\nuvicorn = \"^0.12.3\"\n\n[tool.poetry.dev-dependencies]\npytest = \"^5.2\"\n\n[build-system]\nrequires = [\"poetry-core>=1.0.0\"]\nbuild-backend = \"poetry.core.masonry.api\"\n" } ]
5
terrybroad/Light-Field-Completion
https://github.com/terrybroad/Light-Field-Completion
4dfc66b9b171c08f92ac9acfdd9f40dc2d10bffb
ad2a1bed13ede33fdda4b818aff159ea3877152e
34df69e842b605e067c89d6df9c27f4165d13459
refs/heads/master
2021-01-23T07:03:24.070479
2015-05-13T10:05:13
2015-05-13T10:05:13
33,306,751
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.5685817003250122, "alphanum_fraction": 0.5821496844291687, "avg_line_length": 23.82631492614746, "blob_id": "dd462a2cf9c223a073625d7f5197716976c6c6fb", "content_id": "539c3318425e5dc3517fa7c8da5af9b9042e6938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4717, "license_type": "no_license", "max_line_length": 99, "num_lines": 190, "path": "/LFCompletion/LFCompletion.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include <iostream>\n#include \"DepthMap.cpp\"\n#include \"FillHoleDirected.cpp\"\n#include \"FocalStackPropagation.cpp\"\n#include \"pixelStruct.h\"\n\nusing namespace cv;\nusing namespace std;\nMat infocus, infocusS,inpainted;\nMat out, outS;\nMat mask, maskS;\nMat depthMap,depthMapS,depthMapF,depthMapFS,depthMapBlurred,depthMapFBlurred;\nvector<Mat> imgs;\nvector<Mat> laplacians;\nvector<int> segmentIndicies;\nvector<Mat> segments;\nvector<Mat> gauss;\nvector<Mat> windows;\n\nPoint prevPt(-1,-1);\n\n\n\nstatic void onMouse( int event, int x, int y, int flags, void* )\n{\n if( event == EVENT_LBUTTONUP || !(flags & EVENT_FLAG_LBUTTON) )\n prevPt = Point(-1,-1);\n else if( event == EVENT_LBUTTONDOWN )\n prevPt = Point(x,y);\n else if( event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON) )\n {\n Point pt(x,y);\n if( prevPt.x < 0 )\n prevPt = pt;\n line( maskS, prevPt, pt, Scalar::all(255), 5, 200, 0 );\n line( infocusS, prevPt, pt, Scalar(0,255,0), 5, 200, 0 );\n prevPt = pt;\n imshow(\"image\", infocusS);\n }\n}\n\n\n//------------------------------------------------------------\nstring retrieveString( char* buf, int max ) {\n\n size_t len = 0;\n while( (len < max) && (buf[ len ] != '\\0') ) {\n len++;\n }\n\n return string( buf, len );\n\n}\n\nint main(int argc, char** argv )\n{\n char* fn = argv[1];\n string filename = retrieveString(fn,100);\n\n bool imageLoad = true;\n int imNum = 0;\n\n\n while(imageLoad)\n {\n stringstream ss;\n string thisFilename;\n imgs.resize(imNum+1);\n ss << filename << imNum << \".jpg\";\n thisFilename = ss.str();\n imgs.at(imNum) = imread(thisFilename,3);\n if(imgs.at(imNum).empty())\n {\n imageLoad = false;\n imgs.resize(imNum);\n }\n else\n {\n imNum++;\n }\n }\n\n laplacians = laplacianFocalStack(imgs);\n gauss = differenceOfGaussianFocalStack(imgs);\n\n depthMap = createDepthMap(gauss);\n GaussianBlur(depthMap,depthMapBlurred,Size(15,15),0);\n\n infocus = createInFocusImage(depthMap,imgs);\n //infocus = createInFocusImageInterpolate(depthMapBlurred,imgs);\n\n\n\n\n\n Size size = infocus.size();\n Size smallSize = size/2;\n resize(depthMap, depthMapS,smallSize);\n resize(infocus, infocusS,smallSize);\n Mat originalS = infocusS.clone();\n mask = Mat::zeros(size, CV_8U);\n maskS = Mat::zeros(smallSize, CV_8U);\n\n imshow(\"image\", infocusS);\n setMouseCallback( \"image\", onMouse, 0 );\n\n bool notFilled = true;\n\n\n while(notFilled)\n {\n char c = (char)waitKey();\n //imshow(\"image\", infocusS);\n if( c == 27 )\n break;\n\n if( c == 'r' )\n {\n maskS = Scalar::all(0);\n infocusS = originalS.clone();\n imshow(\"image\", infocusS);\n }\n\n if( c == 'i' || c == ' ' )\n {\n\n resize(maskS,mask,size,INTER_CUBIC);\n notFilled = false;\n\n depthMapF= fillDepthMapDirected(depthMap,mask);\n GaussianBlur(depthMapF,depthMapFBlurred,Size(15,15),0);\n\n\n inpaint(infocus, mask, inpainted, 3, INPAINT_TELEA);\n\n out = fillImageDirected(inpainted,depthMapF,depthMapBlurred,mask,11,2000);\n\n resize(out,outS,smallSize);\n //imshow(\"out\",out);\n\n\n //out = infocus;\n cout<< \"image completed - next to propagate through the focal stack\" << endl;\n\n vector<Mat> outImages;\n outImages = propogateFocalStack(imgs, laplacians, out, mask, depthMapF, depthMapBlurred);\n\n\n for(int i = 0; i < outImages.size(); i++)\n {\n stringstream ss;\n string outputName;\n ss << filename << \"_completed\" << i << \".jpg\";\n outputName = ss.str();\n cout << \"writing \" << outputName << endl;\n //imshow(outputName, outImages.at(i));\n imwrite(outputName, outImages.at(i));\n }\n notFilled = false;\n }\n\n\n }\n\n\n resize(depthMapF,depthMapFS, smallSize);\n string name = filename+\"_filled.jpg\";\n imwrite(name,out);\n name = filename+\"_depthMapFilled.jpg\";\n imwrite(name,depthMapF);\n name = filename+\"_infocus.jpg\";\n imwrite(name,infocus);\n name = filename+\"_maskArea.jpg\";\n imwrite(name,infocusS);\n name = filename+\"_mask.jpg\";\n imwrite(name,mask);\n cout << \"finished, all files are written\" << endl;\n while(1)\n {\n imshow(\"filled_completed\",outS);\n //imshow(\"depthMap\",depthMapFS);\n }\n\n}\n" }, { "alpha_fraction": 0.4659845530986786, "alphanum_fraction": 0.4881230294704437, "avg_line_length": 31.51556396484375, "blob_id": "c764b55d6dc7d608963e8fb6c06ab9fe4fd1ffe5", "content_id": "cce2b7a264dc3b2623b6292a02659f85de43f4b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16713, "license_type": "no_license", "max_line_length": 267, "num_lines": 514, "path": "/LFCompletion/FillHole.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool inImage(int x, int y, const Mat &img)\n{\n return (x >= 0 && x < img.cols && y >= 0 && y < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool windowInImage(int x, int y, const Mat &img, int windowSize)\n{\n return (x - windowSize >= 0 && x + windowSize < img.cols && y - windowSize >= 0 && y + windowSize < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindow(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<int>(y, x, 0) = img.at<int>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n }\n }\n\n return output;\n}\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindowMask(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<uchar>(y, x, 0) = img.at<uchar>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n else\n {\n output.at<uchar>(y, x, 0) = (uchar)1;\n }\n }\n }\n\n return output;\n}\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDist(const Mat &templ8, const Mat &templ9, const Mat &mask1, const Mat &mask2, const Mat &gaussian,int windowSize)\n{\n double dist = 0;\n int count = 0;\n\n Mat diff;\n\n absdiff(templ8, templ9, diff);\n\n diff.mul(gaussian);\n\n for(int i = 0; i < (windowSize*2) + 1; i++)\n {\n for(int j = 0; j < (windowSize*2) + 1; j++)\n {\n if(!( i == windowSize && j == windowSize))\n {\n //if((int) mask1.at<uchar>(i,j) == 0 && (int) mask2.at<uchar>(i,j) == 0)\n {\n Vec3b a,b,c;\n a = templ8.at<Vec3b>(i,j);\n b = templ9.at<Vec3b>(i,j);\n c = diff.at<Vec3b>(i,j);\n for(int k = 0; k < 3; k++)\n {\n count++;\n if((int) mask1.at<uchar>(i,j) == 0 )\n {\n dist += (c.val[k]*2)^2;\n //dist += (c.val[k]*2);\n }\n else // penalise non-image elements\n {\n //\n dist += (c.val[k])^2;\n // dist += (c.val[k]);\n }\n }\n }\n }\n }\n }\n\n if(dist == 0)\n {\n cout << \"LUCKY NUMBER ZERO\" << endl;\n }\n\n return sqrt(dist)/count;\n //return dist/count;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDistSimple(const Mat &templ8, const Mat &templ9, int windowSize)\n{\n double dist = 0;\n int count = 0;\n\n Mat diff;\n absdiff(templ8, templ9, diff);\n\n\n for(int i = 0; i < (windowSize*2) + 1; i++)\n {\n for(int j = 0; j < (windowSize*2) + 1; j++)\n {\n if( i != windowSize && j != windowSize)\n {\n count++;\n dist += abs((int) diff.at<uchar>(i,j));\n }\n }\n }\n\n return dist/count;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\n\nbool isNeighbour(const Point2i pos, const Point2i ptemp, vector<Point2i> &linearArray, int windowSize,int cols)\n{\n bool isN = false;\n\n for(int y = (-1*windowSize)+1; y < windowSize; y++)\n {\n for(int x = (-1*windowSize)+1; x < windowSize; x++)\n {\n if(!(y == 0 && x == 0))\n {\n if(linearArray.at((pos.y+ y)*cols + pos.x+x) == ptemp)\n {\n isN = true;\n }\n }\n }\n }\n return isN;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nconst Point2i findBestPixel(const Mat &templ8, const vector<Mat> &templates, const Mat &gaussian,const Mat &mask,const vector<Mat> &masks, const Mat &sampleCount, const Mat &depthMap, int rows, int cols,const Point2i pos, vector<Point2i> &linearArray, int windowSize)\n{\n Point2i bestPixel = pos;\n Point2i ptemp;\n double bestValue = 100;\n\n\n int n = 1;\n int count = 0;\n\n\n for(int y = (-1*windowSize)+1; y < windowSize; y++)\n {\n for(int x = (-1*windowSize)+1; x < windowSize; x++)\n {\n int num = ((pos.y+y)*cols) + pos.x + x;\n if(num >= 0 && num < rows*cols)\n {\n ptemp = linearArray.at(num);\n ptemp.x = ptemp.x + x*-1;\n ptemp.y = ptemp.y + y*-1;\n\n if(ptemp.x != -1 && windowInImage(ptemp.x,ptemp.y,mask,windowSize))\n {\n if(pos!= ptemp && !isNeighbour(pos,ptemp,linearArray,windowSize,cols) && mask.at<uchar>(ptemp) == 0 && depthMap.at<uchar>(pos) == depthMap.at<uchar>(ptemp)) //!isNeighbour(pos,ptemp,linearArray,floor(windowSize/2),cols)\n {\n double dist = getDist(templ8, templates.at(ptemp.y*cols +ptemp.x),masks.at(pos.y*cols + pos.x),masks.at(ptemp.y*cols +ptemp.x),gaussian,windowSize);\n dist *= sampleCount.at<float>(pos.y*cols+pos.x);\n if(dist < bestValue)\n {\n bestValue = dist;\n bestPixel.x = ptemp.x;\n bestPixel.y = ptemp.y;\n }\n }\n }\n }\n }\n }\n\n if(bestValue < 0.12)\n {\n cout << \"Ashihkmin\" << endl;\n cout << bestValue << endl;\n }\n else\n {\n bestValue = 100;\n while(count < 1500 && n < 250)\n {\n for(int i = -1; i < 2; i+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+) -1,-1 ... -1,1 .. 1,-1,\n {\n for(int j = -1; j < 2; j+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+)\n {\n for(int c = 0; c < 2*n; c++)\n {\n if(i < 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) + c, pos.y + (n*j));}\n if(i < 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) - c );}\n if(i > 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) + c);}\n if(i > 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) - c, pos.y + (n*j));}\n\n if(windowInImage(ptemp.x,ptemp.y,mask,windowSize))\n {\n if((int) mask.at<uchar>(ptemp.y,ptemp.x,0) == 0)\n {\n if(depthMap.at<uchar>(pos) == depthMap.at<uchar>(ptemp))\n {\n if(!isNeighbour(pos,ptemp,linearArray,windowSize,cols))\n {\n double dist = getDist(templ8,templates.at(ptemp.y*cols + ptemp.x),masks.at(pos.y*cols + pos.x),masks.at(ptemp.y*cols + ptemp.x),gaussian,windowSize);\n dist *= sampleCount.at<float>(pos.y*cols+pos.x);\n if( sampleCount.at<float>(pos.y*cols+pos.x) < 2) { count++;}\n //count++;\n if(dist < bestValue)\n {\n bestValue = dist;\n bestPixel.x = ptemp.x;\n bestPixel.y = ptemp.y;\n }\n }\n }\n }\n }\n }\n }\n }\n n++;\n }\n cout << \"exhaustive search\" << endl;\n cout << bestValue << endl;\n }\n return bestPixel;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nconst Point2i findBestPixelSimple(const Mat &templ8, const vector<Mat> &templates, const Mat &mask, int rows, int cols, const Point2i pos, int windowSize)\n{\n Point2i bestPixel;\n Point2i ptemp;\n double bestValue = 100;\n //double dist = 0;\n\n int n = 1;\n int count = 0;\n bool yes = false;\n\n while(count < 30)\n {\n for(int i = -1; i < 2; i+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+) -1,-1 ... -1,1 .. 1,-1,\n {\n for(int j = -1; j < 2; j+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+)\n {\n for(int c = 0; c < 2*n; c++)\n {\n if(i < 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) + c, pos.y + (n*j));}\n if(i < 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) - c );}\n if(i > 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) + c);}\n if(i > 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) - c, pos.y + (n*j));}\n\n if(windowInImage(ptemp.x,ptemp.y,mask,windowSize))\n {\n if((int) mask.at<uchar>(ptemp.y,ptemp.x,0) == 0)\n {\n double dist = getDistSimple(templ8,templates.at(ptemp.y*cols + ptemp.x),windowSize);\n count++;\n if(dist < bestValue)\n {\n bestValue = dist;\n bestPixel.x = ptemp.x;\n bestPixel.y = ptemp.y;\n }\n }\n }\n }\n }\n }\n\n n++;\n }\n return bestPixel;\n}\n\nMat fillDepthMap(const Mat &depthMap, const Mat &inpaintMask)\n{\n Mat inpainted,maskBinary,output;\n int windowSize = 2;\n int winLength = (windowSize*2) + 1;\n inpaint(depthMap, inpaintMask, inpainted, 3, INPAINT_TELEA);\n output = inpainted.clone();\n\n vector<Mat> templates(inpainted.rows*inpainted.cols);\n for(int y = 0; y < inpainted.rows; y++)\n {\n for(int x = 0; x < inpainted.cols; x++)\n {\n if(windowInImage(x,y,inpainted,windowSize)) { templates.at(y*inpainted.cols + x) = getNeighbourhoodWindow(inpainted,Point2i(x,y),windowSize); }\n }\n }\n\n\n for(int y = 0; y < inpainted.rows; y++)\n {\n for(int x = 0; x < inpainted.cols; x++)\n {\n if( (int) inpaintMask.at<uchar>(y,x,0) != 0)\n {\n Mat templ8 = getNeighbourhoodWindow(inpainted,Point2i(x,y),windowSize);\n Point2i newPos = findBestPixelSimple(templ8,templates,inpaintMask,inpainted.rows,inpainted.cols,Point2i(x,y),windowSize);\n output.at<int>(y,x,0) = inpainted.at<int>(newPos.y,newPos.x,0);\n\n }\n }\n }\n\n return output;\n}\n\nMat fillImage(const Mat &srcBGR, const Mat &depthMap, const Mat &inpaintMask)\n{\n Mat srcLAB, texLAB, outLAB, outBGR, maskBinary,originalMask,eroded, border, strElement,sampleCount,borderBig,strElement2,strElement3,strElement4,inpainted,inpainted2,inpainted3,maskBig,maskBigger;\n\n RNG rng;\n\n int windowSize = 14;\n int winLength = (windowSize*2) + 1;\n\n int rows = srcBGR.rows;\n int cols = srcBGR.cols;\n\n strElement = getStructuringElement( MORPH_RECT,Size( 5, 5),Point(1,1));\n dilate(inpaintMask,inpaintMask,strElement,Point(-1, -1), 1, 1, 1);\n maskBinary = Mat::zeros(srcBGR.size(), CV_8U);\n threshold( inpaintMask, maskBinary, 127,255,0 );\n //strElement = getStructuringElement( MORPH_RECT,Size( 3, 3),Point(1,1));\n strElement2 = getStructuringElement( MORPH_RECT,Size( windowSize, windowSize),Point(-1,-1));\n strElement3 = getStructuringElement( MORPH_RECT,Size( windowSize, 1),Point(-1,-1));\n strElement4 = getStructuringElement( MORPH_RECT,Size( 1, windowSize),Point(-1,-1));\n eroded = Mat::zeros(maskBinary.size(), CV_8U);\n border = Mat::zeros(maskBinary.size(), CV_8U);\n borderBig = Mat::zeros(maskBinary.size(), CV_8U);\n sampleCount = Mat::ones(maskBinary.size(), CV_32F);\n\n double kernalsize = (double)windowSize / 6.0;\n kernalsize = sqrt(kernalsize);\n Mat tmpGaussian = getGaussianKernel(windowSize * 2 + 1, kernalsize);\n Mat gaussianMask = tmpGaussian * tmpGaussian.t();\n\n inpaint(srcBGR, inpaintMask, inpainted, 3, INPAINT_TELEA);\n dilate(inpaintMask,maskBig,strElement3,Point(-1, -1), 1, 1, 1);\n inpaint(srcBGR, maskBig, inpainted2, 3, INPAINT_TELEA);\n dilate(inpaintMask,maskBigger,strElement4,Point(-1, -1), 1, 1, 1);\n inpaint(srcBGR, maskBig, inpainted3, 3, INPAINT_TELEA);\n\n Mat inpaintCombine = inpainted.clone();\n\n int unfilledCount = 0;\n\n vector<Point2i> linearArray;\n linearArray.resize(rows*cols);\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n if((int) maskBinary.at<uchar>(y,x,0) != 0)\n {\n unfilledCount++;\n\n linearArray.at(y*cols + x).x = -1;\n linearArray.at(y*cols + x).y = -1;\n\n Vec3b a,b,c;\n a = inpainted.at<Vec3b>(y,x);\n b = inpainted2.at<Vec3b>(y,x);\n c = inpainted3.at<Vec3b>(y,x);\n int randInt = rng.uniform(-17,17);\n for(int i = 0; i < 3; i++)\n {\n int num = (int)((a.val[i] + b.val[i] + c.val[i] )/3) + randInt;\n if(num < 0){num = 0;}\n if(num > 255){num = 255;}\n a.val[i] = num;\n }\n inpaintCombine.at<Vec3b>(y,x) = a;\n }\n else\n {\n linearArray.at(y*cols + x).x = x;\n linearArray.at(y*cols + x).y = y;\n }\n }\n }\n int unfilledCountOriginal = unfilledCount;\n\n cvtColor(inpaintCombine, outLAB, CV_BGR2Lab);\n\n vector<Mat> templates(rows*cols);\n vector<Mat> masks(rows*cols);\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n if(windowInImage(x,y,outLAB,windowSize)) { templates.at(y*outLAB.cols + x) = getNeighbourhoodWindow(outLAB,Point2i(x,y),windowSize); }\n }\n }\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n masks.at(y*cols + x) = getNeighbourhoodWindowMask(maskBinary,Point2i(x,y),windowSize);\n }\n }\n\n\n originalMask = maskBinary.clone();\n int epoch = 0;\n\n Mat outSmall;\n Mat strElement5 = getStructuringElement( MORPH_RECT,Size( windowSize*10, windowSize*10),Point(-1,-1));\n\n while(unfilledCount > 0)\n {\n dilate(border,borderBig,strElement2,Point(-1, -1), 1, 1, 1);\n erode(maskBinary,eroded,strElement,Point(-1, -1), 1, 1, 1);\n subtract(maskBinary,eroded,border);\n\n // if(epoch == 0)\n // {\n // dilate(border,borderBig,strElement5,Point(-1, -1), 1, 1, 1);\n // }\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n if( (int) border.at<uchar>(y,x,0) != 0 )\n {\n unfilledCount--;\n if(windowInImage(x,y,originalMask,windowSize))\n {\n Mat templ8 = getNeighbourhoodWindow(outLAB,Point2i(x,y),windowSize);\n Point2i newPos = findBestPixel(templ8,templates,gaussianMask,originalMask,masks,sampleCount,depthMap,rows,cols,Point2i(x,y),linearArray,windowSize);\n outLAB.at<int>(y,x,0) = outLAB.at<int>(newPos.y,newPos.x,0);\n\n if(newPos != Point2i(x,y))\n {\n linearArray.at(y*cols + x) = newPos;\n }\n float s = sampleCount.at<float>(newPos.y*cols+newPos.x);\n s+=2;\n sampleCount.at<float>(newPos.y*cols+newPos.x) = s;\n cout << \"current out pixel X\" << endl; cout << x << endl;\n cout << \"current out pixel Y\" << endl; cout << y << endl;\n cout << \"picked pixel X\" << endl; cout << newPos.x << endl;\n cout << \"picked pixel Y\" << endl; cout << newPos.y << endl;\n cout << \"unfilled count \" << endl; cout << unfilledCount << endl;\n cout << \"epoch \" << endl; cout << epoch << endl;\n }\n }\n }\n }\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n if(windowInImage(x,y,outLAB,windowSize) && (int) borderBig.at<uchar>(y,x,0) != 0) { templates.at(y*cols + x) = getNeighbourhoodWindow(outLAB,Point2i(x,y),windowSize); }\n }\n }\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n if((int) borderBig.at<uchar>(y,x,0) != 0) { masks.at(y*cols + x) = getNeighbourhoodWindowMask(maskBinary,Point2i(x,y),windowSize); }\n }\n }\n\n cvtColor(outLAB, outBGR, CV_Lab2BGR);\n resize(outBGR,outSmall,outBGR.size()/2);\n imshow(\"progress\",outSmall);\n maskBinary = eroded.clone();\n epoch++;\n }\n\n\n cvtColor(outLAB, outBGR, CV_Lab2BGR);\n return outBGR;\n}\n" }, { "alpha_fraction": 0.7743362784385681, "alphanum_fraction": 0.7831858396530151, "avg_line_length": 36.66666793823242, "blob_id": "7347d583fffd8696170aba6cadfa10cc9059ae52", "content_id": "d23359b3d1e4b437cc011b1578750b16a81ab7a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 226, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/RandomImage/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( RandomImage )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( RandomImage RandomImage.cpp )\ntarget_link_libraries( RandomImage ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.7652581930160522, "alphanum_fraction": 0.7746478915214539, "avg_line_length": 34.66666793823242, "blob_id": "2a09c0b7c7e895651c9607438cc2557d26bfd2c5", "content_id": "b29cebc676e3864063e4ada7a5a24e3a90f4b786", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 213, "license_type": "no_license", "max_line_length": 48, "num_lines": 6, "path": "/OldTests/FillHole/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( FillHole )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( FillHole FillHole.cpp )\ntarget_link_libraries( FillHole ${OpenCV_LIBS} )" }, { "alpha_fraction": 0.7730769515037537, "alphanum_fraction": 0.7730769515037537, "avg_line_length": 25, "blob_id": "d8e86c280935ed66b795721b9ee746fd347251f7", "content_id": "466c9fed92b99e7f115827b042cabc93c22f8843", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 260, "license_type": "no_license", "max_line_length": 71, "num_lines": 10, "path": "/OldTests/DeconvLucy/CMakeFiles/deconvlucy.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/deconvlucy.dir/deconvlucy.cpp.o\"\n \"deconvlucy.pdb\"\n \"deconvlucy\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/deconvlucy.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.4258691966533661, "alphanum_fraction": 0.44425204396247864, "avg_line_length": 28.908367156982422, "blob_id": "69a6d32a67f2cc3ad82cd3a383f5ee28de064438", "content_id": "80f11ef03c0f0d532b7916efd737133be7819b24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7507, "license_type": "no_license", "max_line_length": 171, "num_lines": 251, "path": "/LFCompletion/DepthMap.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include <iostream>\n#include <algorithm>\n\nusing namespace cv;\nusing namespace std;\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nuchar getDepthMapColour(int depthIndex,int imgNum)\n{\n return (uchar) (int)(255 - depthIndex*(255/imgNum));\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nint getIndexFromDepthMap(uchar depthMapCol,int imgNum)\n{\n return (255-depthMapCol) / (255/imgNum);\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getIndexFromDepthMapFloat(uchar depthMapCol,int imgNum)\n{\n double d = 1 - depthMapCol/255;\n\n d *= imgNum;\n\n if(d < 0){d = 0;}\n if(d >= imgNum-1){d = imgNum-1;}\n\n return d;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDepthDistance(uchar val, uchar val2)\n{\n return (double) 1/ (1 - abs((int)val - (int)val2)/255);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nuchar getDepthDistanceUchar(uchar val, uchar val2)\n{\n return (uchar) abs((int)val - (int)val2);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Mat> laplacianFocalStack(vector<Mat> &imgs)\n{\n int imgNum = imgs.size();\n vector<Mat> laps;\n vector<Mat> imgsG;\n vector<Mat> smoothed;\n vector<Mat> boosted;\n\n imgsG.resize(imgNum);\n laps.resize(imgNum);\n smoothed.resize(imgNum);\n boosted.resize(imgNum);\n\n for(int i = 0; i < imgNum; i++)\n {\n cvtColor(imgs.at(i),imgsG.at(i), CV_BGR2GRAY);\n\n Laplacian(imgsG.at(i),laps.at(i),0,5);\n GaussianBlur(laps.at(i),smoothed.at(i),Size(55,55),10);\n smoothed.at(i).convertTo(boosted.at(i),0,2);\n }\n\n return boosted;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Mat> differenceOfGaussianFocalStack(vector<Mat> &imgs)\n{\n int imgNum = imgs.size();\n\n vector<Mat> imgsG;\n vector<Mat> gauss;\n vector<Mat> diffs;\n vector<Mat> gaussDiffs;\n vector<Mat> boosted;\n imgsG.resize(imgNum);\n gauss.resize(imgNum);\n diffs.resize(imgNum);\n gaussDiffs.resize(imgNum);\n boosted.resize(imgNum);\n\n for(int i = 0; i < imgNum; i++)\n {\n cvtColor(imgs.at(i),imgsG.at(i), CV_BGR2GRAY);\n GaussianBlur(imgsG.at(i),gauss.at(i),Size(11,11),11);\n diffs.at(i) = imgsG.at(i) - gauss.at(i);\n GaussianBlur(diffs.at(i),gaussDiffs.at(i),Size(101,101),11);\n gaussDiffs.at(i).convertTo(boosted.at(i),0,4);\n }\n\n return boosted;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat averageImages(vector<Mat> &imgs)\n{\n Mat avIm = Mat::zeros(imgs.at(0).size(), CV_8U);\n Mat avImBoosted = Mat::zeros(imgs.at(0).size(), CV_8U);;\n for(int y = 0; y < avIm.rows; y++)\n {\n for(int x = 0; x < avIm.cols; x++)\n {\n int val = 0;\n for(int i = 0; i < imgs.size(); i++)\n {\n val += (int) imgs.at(i).at<uchar>(y,x);\n }\n val /= imgs.size();\n avIm.at<uchar>(y,x) = (uchar) val;\n }\n }\n return avIm;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat createDepthMap(vector<Mat> &imgs)\n{\n Mat depthMap = Mat::zeros(imgs.at(0).size(), CV_8U);\n int rows = imgs.at(0).rows;\n int cols = imgs.at(0).cols;\n int imgNum = imgs.size();\n\n Mat av = averageImages(imgs);\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n int bestValue = 0;\n int depthIndex = 0;\n\n for(int i = 0; i < imgNum; i++)\n {\n int value = 0;\n for(int j = -1; j < 2; j++)\n {\n for(int k = -1; k < 2; k++)\n {\n if(y+j >= 0 && y+j < rows && x+k >= 0 && x+k < cols)\n {\n value += (int) imgs.at(i).at<uchar>(y+j,x+k) - av.at<uchar>(y+j,x+k);\n }\n }\n }\n\n if(value > bestValue)\n {\n bestValue = value;\n depthIndex = i;\n }\n }\n\n\n depthMap.at<uchar>(y,x) = getDepthMapColour(depthIndex, imgNum); //(uchar) 255 - depthIndex*(255/imgNum);\n }\n }\n return depthMap;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getRelativeDepthMap(const Mat &img, uchar depthValue,int imgNum)\n{\n Mat imgOut = Mat::ones(img.size(), CV_8U);\n\n for(int y = 0; y < imgOut.rows; y++)\n {\n for(int x = 0; x < imgOut.cols; x++)\n {\n imgOut.at<uchar>(y,x) = getDepthDistanceUchar(img.at<uchar>(y,x),depthValue);\n }\n }\n\n return imgOut;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Mat> getRelativeDepthMapStack(const Mat &img, int imgNum)\n{\n vector<Mat> imgsOut;\n imgsOut.resize(imgNum);\n\n for(int i = 0; i < imgNum; i++)\n {\n imgsOut.at(i) = getRelativeDepthMap(img, getDepthMapColour(i, imgNum),imgNum);\n }\n return imgsOut;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat createInFocusImage(Mat &depthMap, vector<Mat> &imgs)\n{\n Mat inFocus = Mat::zeros(depthMap.size(), CV_8UC3);\n int rows = inFocus.rows;\n int cols = inFocus.cols;\n int imgNum = imgs.size();\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n int depthIndex = 0;\n\n depthIndex = getIndexFromDepthMap(depthMap.at<uchar>(y,x), imgNum); //(255-depthMap.at<uchar>(y,x)) / (255/imgNum);\n inFocus.at<Vec3b>(y,x) = imgs.at(depthIndex).at<Vec3b>(y,x);\n\n }\n }\n return inFocus;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nVec3b getInterpolatedCol(const Vec3b col1, const Vec3b col2, float ratio)\n{\n Vec3b colOut;\n\n for(int i = 0; i < 3; i++)\n {\n colOut[i] = (uchar) (col1[i] * (ratio)) + (col2[i] * (1-ratio));\n }\n return colOut;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat createInFocusImageInterpolate(Mat &depthMapBlurred, vector<Mat> &imgs)\n{\n Mat inFocus = Mat::zeros(depthMapBlurred.size(), CV_8UC3);\n int rows = inFocus.rows;\n int cols = inFocus.cols;\n int imgNum = imgs.size();\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n double depthIndex;\n depthIndex = getIndexFromDepthMapFloat(depthMapBlurred.at<uchar>(y,x), imgNum); //(255-depthMap.at<uchar>(y,x)) / (255/imgNum);\n\n inFocus.at<Vec3b>(y,x) = getInterpolatedCol(imgs.at(floor(depthIndex)).at<Vec3b>(y,x),imgs.at(floor(depthIndex+1)).at<Vec3b>(y,x), floor(depthIndex+1) - depthIndex);\n }\n }\n return inFocus;\n}\n" }, { "alpha_fraction": 0.7616822719573975, "alphanum_fraction": 0.7710280418395996, "avg_line_length": 34.66666793823242, "blob_id": "239bfdf68369f4b6a31f0643eb0456d4f5182cb5", "content_id": "cb4a413f4a841146b2a8634a685ab57ffc7187e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 214, "license_type": "no_license", "max_line_length": 48, "num_lines": 6, "path": "/WeiSynth/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( WeiSynth )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( WeiSynth WeiSynth.cpp )\ntarget_link_libraries( WeiSynth ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.7702702879905701, "alphanum_fraction": 0.7792792916297913, "avg_line_length": 36, "blob_id": "9745eb66b828a877f755d7279de8ea5e10c03a62", "content_id": "5580aa69d0649dd382868f96130e37c51fb9c3c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 222, "license_type": "no_license", "max_line_length": 50, "num_lines": 6, "path": "/DeconvLucy/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( deconvlucy )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( deconvlucy deconvlucy.cpp )\ntarget_link_libraries( deconvlucy ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.7686274647712708, "alphanum_fraction": 0.7686274647712708, "avg_line_length": 24.5, "blob_id": "f9818c0828f9068a577d6aae773c3239198ce2ef", "content_id": "17cc0dbb5c83a654c8132384cc2765aefd8fe386", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 255, "license_type": "no_license", "max_line_length": 70, "num_lines": 10, "path": "/OldTests/BurImage/CMakeFiles/BlurImage.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/BlurImage.dir/BlurImage.cpp.o\"\n \"BlurImage.pdb\"\n \"BlurImage\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/BlurImage.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.5093783736228943, "alphanum_fraction": 0.5431404113769531, "avg_line_length": 24.216217041015625, "blob_id": "5c7ae103369b364cbc45c6d227d366064faa52d7", "content_id": "01b4f24bf33f9485bbf2de0c83eac8f73ab51a1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3732, "license_type": "no_license", "max_line_length": 122, "num_lines": 148, "path": "/FocalStack/FocalStack.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include <iostream>\n#include <algorithm>\n\nusing namespace cv;\nusing namespace std;\n\n\nint main(int argc, char** argv )\n{\n\n int imgNum = 11;\n vector<Mat> imgs;\n vector<Mat> laps;\n vector<Mat> imgsG;\n vector<Mat> smoothed;\n vector<Mat> gauss;\n vector<Mat> diffs;\n vector<Mat> gaussDiffs;\n\n imgs.resize(imgNum);\n imgsG.resize(imgNum);\n laps.resize(imgNum);\n smoothed.resize(imgNum);\n gauss.resize(imgNum);\n diffs.resize(imgNum);\n gaussDiffs.resize(imgNum);\n\n for(int i = 0; i < imgNum; i++)\n {\n char filename[50];\n\n //if(i < 10) { sprintf( filename, \"wasp-stk_0%d.jpg\", i ); } else { sprintf( filename, \"wasp-stk_%d.jpg\", i ); }\n sprintf( filename, \"stack4/reordered%d.jpg\", i );\n \t\t\t\timgs.at(i) = imread( filename, 1);\n\n /*if (!img)\n \t\t\t\t\t{\n \t\t\t\t\t\tprintf(\"Error: Image not found.\\n\");\n \t\t\t\t\t\treturn 2; //error : not found image\n \t\t\t\t\t} */\n\n cvtColor(imgs.at(i),imgsG.at(i), CV_BGR2GRAY);\n Laplacian(imgsG.at(i),laps.at(i),0,5);\n GaussianBlur(laps.at(i),smoothed.at(i),Size(55,55),10);\n\n GaussianBlur(imgsG.at(i),gauss.at(i),Size(11,11),11);\n diffs.at(i) = imgsG.at(i) - gauss.at(i);\n GaussianBlur(diffs.at(i),gaussDiffs.at(i),Size(101,101),11);\n\n // imshow( filename, smoothed.at(i) ); // Show our image inside it.\n imshow(filename,gaussDiffs.at(i));\n }\n\n int rows = laps.at(0).rows;\n int cols = laps.at(0).cols;\n\n Mat depthMap; Mat inFocus; Mat depthMap2; Mat inFocus2;\n depthMap = Mat::zeros(laps.at(0).size(), CV_8U);\n inFocus = Mat::zeros(imgs.at(0).size(), CV_8UC3);\n depthMap2 = Mat::zeros(laps.at(0).size(), CV_8U);\n inFocus2 = Mat::zeros(imgs.at(0).size(), CV_8UC3);\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n int bestValue = 0;\n int depthIndex = 0;\n int bestValue2 = 0;\n int depthIndex2 = 0;\n\n if( y >= 3 && y < rows-3 && x>= 3 && x < cols-3)\n {\n for(int i = 0; i < imgNum; i++)\n {\n int value = 0;\n int value2 = 0;\n for(int j = -1; j < 2; j++)\n {\n for(int k = -1; k < 2; k++)\n {\n value += (int) smoothed.at(i).at<uchar>(y+j,x+k);\n value2 += (int) gaussDiffs.at(i).at<uchar>(y+j,x+k);\n }\n }\n\n if(value > bestValue)\n {\n bestValue = value;\n depthIndex = i;\n }\n if(value2 > bestValue2)\n {\n bestValue2 = value2;\n depthIndex2 = i;\n }\n }\n }\n depthMap.at<uchar>(y,x) = (uchar) 255 - depthIndex*(255/imgNum);\n inFocus.at<Vec3b>(y,x) = imgs.at(depthIndex).at<Vec3b>(y,x);\n\n depthMap2.at<uchar>(y,x) = (uchar) 255 - depthIndex2*(255/imgNum);\n inFocus2.at<Vec3b>(y,x) = imgs.at(depthIndex2).at<Vec3b>(y,x);\n }\n }\n\n\n Mat diff = imgsG.at(4) - imgsG.at(8);\n\n Mat diff2 = diff-diffs.at(0);\n //Mat lapDiff;\n\n //Laplacian(diff,lapDiff,0,5);\n\n for(;;)\n {\n// imshow(\"im1\",diffs.at(0));\n imshow(\"diff\",diff);\n// imshow(\"diffs2\",diff2);\n //imshow(\"lapDiff\",lapDiff);\n }\n\n\n\n\n/*\n imshow(\"depthMap\",depthMap);\n imshow(\"blar\",inFocus);\n\n imwrite(\"stack4/depthMap1.jpg\",depthMap);\n imwrite(\"stack4/infocus1.jpg\",inFocus);\n\n\n imshow(\"depthMap2\",depthMap2);\n imshow(\"blar2\",inFocus2);\n\n imwrite(\"stack4/depthMap2.jpg\",depthMap2);\n imwrite(\"stack4/infocus2.jpg\",inFocus2);\n\n*/\n\n}\n" }, { "alpha_fraction": 0.773755669593811, "alphanum_fraction": 0.7828054428100586, "avg_line_length": 36, "blob_id": "7997c148bf6d9a8bfb65ec9f4c4a07ebcd3ec8b2", "content_id": "842fa4b3904e3818d89b4b3b58f6810bca312078", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 221, "license_type": "no_license", "max_line_length": 50, "num_lines": 6, "path": "/LFCompletion/GetInFocus/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( GetInFocus )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( GetInFocus GetInFocus.cpp )\ntarget_link_libraries( GetInFocus ${OpenCV_LIBS} )" }, { "alpha_fraction": 0.7773584723472595, "alphanum_fraction": 0.7773584723472595, "avg_line_length": 25.5, "blob_id": "a9022423c5a8b00c9f9cc0e8355c1a87ffdda7a2", "content_id": "7674cf9c85b7ca7d17e523e18689123af63dba88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 265, "license_type": "no_license", "max_line_length": 72, "num_lines": 10, "path": "/OldTests/RandomImage/CMakeFiles/RandomImage.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/RandomImage.dir/RandomImage.cpp.o\"\n \"RandomImage.pdb\"\n \"RandomImage\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/RandomImage.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7524271607398987, "alphanum_fraction": 0.762135922908783, "avg_line_length": 33.33333206176758, "blob_id": "2569b43d5a462f71d50fb119d911287dc784f663", "content_id": "21dc4e09c824b731925f5dcbf7d87b9f3962ac91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 206, "license_type": "no_license", "max_line_length": 46, "num_lines": 6, "path": "/OldTests/Deconv/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( deconv )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( deconv deconv.cpp )\ntarget_link_libraries( deconv ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.795918345451355, "alphanum_fraction": 0.8040816187858582, "avg_line_length": 40, "blob_id": "541bba3b355f21b2a6a38d06b10c239daa8949dd", "content_id": "73f22a089ac50bcebdbbd820cbf9b69305e8b83d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 245, "license_type": "no_license", "max_line_length": 56, "num_lines": 6, "path": "/LFCompletion/LFCompletionMask/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( LFCompletionMask )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( LFCompletionMask LFCompletionMask.cpp )\ntarget_link_libraries( LFCompletionMask ${OpenCV_LIBS} )" }, { "alpha_fraction": 0.6569555997848511, "alphanum_fraction": 0.6817188858985901, "avg_line_length": 27.020408630371094, "blob_id": "d8aad206cb85e55c6f1fe29a4fb22b63c00e1177", "content_id": "107f15c71c1e32d9fdda758124bd378cd5b32510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 87, "num_lines": 49, "path": "/lfptools/reorder.py", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "import pygame, glob, json, commands\nfrom pprint import pprint\n\nwhichFile = \"truck\"\njpegFilenames = glob.glob(whichFile + \"*.jpg\")\nshasumToJpeg = {}\nfor filename in jpegFilenames:\n shasum = commands.getstatusoutput(\"shasum \" + filename)[1]\n shasum = \"sha1-\" + shasum.split(\" \")[0]\n shasumToJpeg[shasum] = pygame.image.load(filename)\nprint \"Loading filenames:\", jpegFilenames\npprint(shasumToJpeg)\n\n#print \"Loading depth table\"\n#depths = [float(x.strip()) for x in open(whichFile + \"_depth.txt\")]\n#print len(depths), \"depth numbers found\"\n\nprint \"Loading jpeg -> depth table\"\nmetadata = json.load(open(whichFile + \"_table.json\"))\nimageArray = metadata[\"picture\"][\"accelerationArray\"][0][\"vendorContent\"][\"imageArray\"]\n\n\n # find closest jpeg\n\nli = []\nfor j, img in enumerate(imageArray):\n closestImg = None\n closestDepth = 100000000\n\n d = 0\n for i, img in enumerate(imageArray):\n delta = img[\"lambda\"]\n\n if ((delta < closestDepth) and (delta not in li)):\n closestDepth = delta\n closestImg = img[\"imageRef\"]\n closestImg = shasumToJpeg[closestImg]\n d = delta\n\n li.append(d)\n print li\n string = 'reorder/truck'\n string +=`j`\n string +='.jpg'\n jpegOut = pygame.Surface((1080, 1080))\n rect = pygame.Rect(0, 0, 1080, 1080)\n subSurf = closestImg.subsurface(rect)\n jpegOut.blit(subSurf,(0,0))\n pygame.image.save(jpegOut, string)\n" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 23.799999237060547, "blob_id": "302a5531d626a3927ef6798be916c42e171aa003", "content_id": "8af76251917cb7f2b4898ad6ade00e59ebea49cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 126, "license_type": "no_license", "max_line_length": 64, "num_lines": 5, "path": "/README.md", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "# Light-Field-Completion\n\nDissertation Project, working repository of all OpenCV C++ work.\n\nProject not currently finished.\n\n\n" }, { "alpha_fraction": 0.747706413269043, "alphanum_fraction": 0.7752293348312378, "avg_line_length": 35.33333206176758, "blob_id": "0774c4defee4388875bd294c11d503c58fee9373", "content_id": "f95db9839856baa444a944e31c0653412dddde86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 218, "license_type": "no_license", "max_line_length": 49, "num_lines": 6, "path": "/TexSynth2/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( TexSynth2 )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( TexSynth2 TexSynth2.cpp )\ntarget_link_libraries( TexSynth2 ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.7781955003738403, "alphanum_fraction": 0.8082706928253174, "avg_line_length": 65.5, "blob_id": "32cc2c8a5277ba9fa98445cb3013c9e5bf779599", "content_id": "6c96ac39008adbefeb3e6a0087a689ec533e51e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 266, "license_type": "no_license", "max_line_length": 125, "num_lines": 4, "path": "/Deconv/README.md", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "# deconvlucy\nAn implementation of Lucy-Richardson algorithm with OpenCV\nFor details please see my post https://gigadom.wordpress.com/2012/05/14/re-working-the-lucy-richardson-algorithm-in-opencv/. \nFor more similar posts visit my blog https://gigadom.wordpress.com/\n" }, { "alpha_fraction": 0.747706413269043, "alphanum_fraction": 0.7752293348312378, "avg_line_length": 35.33333206176758, "blob_id": "a38ee08438b21f9a1fb279d8f0815c9a33984f4b", "content_id": "ea47be3d9cdb8a49c1b6d48a8dca26aa22f7a541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 218, "license_type": "no_license", "max_line_length": 49, "num_lines": 6, "path": "/TexSynth1/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( TexSynth1 )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( TexSynth1 TexSynth1.cpp )\ntarget_link_libraries( TexSynth1 ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.7424242496490479, "alphanum_fraction": 0.752525269985199, "avg_line_length": 32, "blob_id": "270f770c1b6ae94c52dd27729b353c6ccb954bdd", "content_id": "8b58fdca81159496622a404d4ab88506789e4881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 198, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/fill/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( fill )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( fill fill.cpp )\ntarget_link_libraries( fill ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.7571428418159485, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 34, "blob_id": "af3798d8bcee519dfbffa92f646191f799dac96a", "content_id": "c519071bd0bd0c6ac846b3f2a83d9a167fbbb33b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 210, "license_type": "no_license", "max_line_length": 47, "num_lines": 6, "path": "/InPaint/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( inpaint )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( inpaint inpaint.cpp )\ntarget_link_libraries( inpaint ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.7591836452484131, "alphanum_fraction": 0.7591836452484131, "avg_line_length": 23.5, "blob_id": "48fb0e259aa8b286bd62047fdcfde76b996ea8ab", "content_id": "f537908849617821d63a31595eb158b789944efd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 245, "license_type": "no_license", "max_line_length": 68, "num_lines": 10, "path": "/InPaint/CMakeFiles/inpaint.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/inpaint.dir/inpaint.cpp.o\"\n \"inpaint.pdb\"\n \"inpaint\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/inpaint.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7814815044403076, "alphanum_fraction": 0.7814815044403076, "avg_line_length": 26, "blob_id": "9eeda60d4e8a83a6e18f5ce50ff36cd45d7fdf52", "content_id": "c97ecc11aa3bd1bd9d0cbaecabbaa01cef693634", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 270, "license_type": "no_license", "max_line_length": 73, "num_lines": 10, "path": "/LFCompletion/CMakeFiles/LFCompletion.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/LFCompletion.dir/LFCompletion.cpp.o\"\n \"LFCompletion.pdb\"\n \"LFCompletion\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/LFCompletion.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7639999985694885, "alphanum_fraction": 0.7639999985694885, "avg_line_length": 24, "blob_id": "b17c1557400cdab6dad9b4fec9b814b7d4519721", "content_id": "d9d95a78a2ddd62b64fb07f96e4d0371ef45b0d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 250, "license_type": "no_license", "max_line_length": 69, "num_lines": 10, "path": "/FillHole/CMakeFiles/FillHole.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/FillHole.dir/FillHole.cpp.o\"\n \"FillHole.pdb\"\n \"FillHole\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/FillHole.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.6223767995834351, "alphanum_fraction": 0.6633889079093933, "avg_line_length": 32.091270446777344, "blob_id": "7820933bfd192bcccdf11589569ae2936c2d7dee", "content_id": "fa2238f760cb78f5ff5c61f0872d7abcb9d16e9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8477, "license_type": "no_license", "max_line_length": 120, "num_lines": 252, "path": "/OldTests/Deconv/deconv.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "//======================================================================================================================\n// Wiener filter implemention using Gaussian blur kernel\n// Developed by: Tinniam V Ganesh\n// Date: 11 May 2012\n//======================================================================================================================\n//#include “stdafx.h”\n//#include “math.h”\n#include <cxcore.h>\n#include <cv.h>\n#include <highgui.h>\n\n#define kappa 10000\nint main(int argc, char ** argv)\n{\nint height,width,step,channels,depth;\nuchar* data1;\nCvMat *dft_A;\nCvMat *dft_B;\nCvMat *dft_C;\nIplImage* im;\nIplImage* im1;\nIplImage* image_ReB;\nIplImage* image_ImB;\n\nIplImage* image_ReC;\nIplImage* image_ImC;\nIplImage* complex_ImC;\nCvScalar val;\nIplImage* k_image_hdr;\nint i,j,k;\n\nFILE *fp;\nfp = fopen(“test.txt”,”w+”);\nint dft_M,dft_N;\nint dft_M1,dft_N1;\n\nCvMat* cvShowDFT1(IplImage*, int, int,char*);\nvoid cvShowInvDFT1(IplImage*, CvMat*, int, int,char*);\n\nim1 = cvLoadImage(\"reordered4.jpg\");\ncvNamedWindow(\"Original-Color\", 0);\ncvShowImage(\"Original-Color\", im1);\nim = cvLoadImage(\"reordered4.jpg\", CV_LOAD_IMAGE_GRAYSCALE );\nif( !im )\nreturn -1;\n\ncvNamedWindow(\"Original-Gray\", 0);\ncvShowImage(\"Original-Gray\", im);\nIplImage* k_image;\nint rowLength= 11;\nlong double kernels[11*11];\nCvMat kernel;\nint x,y;\nlong double PI_F=3.14159265358979;\n\n//long double SIGMA = 0.84089642;\nlong double SIGMA = 0.014089642;\n//long double SIGMA = 0.00184089642;\nlong double EPS = 2.718;\nlong double numerator,denominator;\nlong double value,value1;\nlong double a,b,c,d;\n\nnumerator = (pow((float)-3,2) + pow((float) 0,2))/(2*pow((float)SIGMA,2));\nprintf(“Numerator=%f\\n”,numerator);\ndenominator = sqrt((float) (2 * PI_F * pow(SIGMA,2)));\nprintf(“denominator=%1.8f\\n”,denominator);\n\nvalue = (pow((float)EPS, (float)-numerator))/denominator;\nprintf(“Value=%1.8f\\n”,value);\nfor(x = -5; x < 6; x++){\nfor (y = -5; y < 6; y++)\n{\n//numerator = (pow((float)x,2) + pow((float) y,2))/(2*pow((float)SIGMA,2));\nnumerator = (pow((float)x,2) + pow((float)y,2))/(2.0*pow(SIGMA,2));\ndenominator = sqrt((2.0 * 3.14159265358979 * pow(SIGMA,2)));\nvalue = (pow(EPS,-numerator))/denominator;\nprintf(” %1.8f “,value);\nkernels[x*rowLength +y+55] = (float)value;\n\n}\nprintf(“\\n”);\n}\nprintf(“———————————\\n”);\nfor (i=-5; i < 6; i++){\nfor(j=-5;j < 6;j++){\nprintf(” %1.8f “,kernels[i*rowLength +j+55]);\n}\nprintf(“\\n”);\n}\nkernel= cvMat(rowLength, // number of rows\nrowLength, // number of columns\nCV_32FC1, // matrix data type\n&kernels);\nk_image_hdr = cvCreateImageHeader( cvSize(rowLength,rowLength), IPL_DEPTH_32F,1);\nk_image = cvGetImage(&kernel,k_image_hdr);\n\nheight = k_image->height;\nwidth = k_image->width;\nstep = k_image->widthStep/sizeof(float);\ndepth = k_image->depth;\nchannels = k_image->nChannels;\n//data1 = (float *)(k_image->imageData);\ndata1 = (uchar *)(k_image->imageData);\ncvNamedWindow(“blur kernel”, 0);\ncvShowImage(“blur kernel”, k_image);\n\ndft_M = cvGetOptimalDFTSize( im->height – 1 );\ndft_N = cvGetOptimalDFTSize( im->width – 1 );\n//dft_M1 = cvGetOptimalDFTSize( im->height+99 – 1 );\n//dft_N1 = cvGetOptimalDFTSize( im->width+99 – 1 );\ndft_M1 = cvGetOptimalDFTSize( im->height+3 – 1 );\ndft_N1 = cvGetOptimalDFTSize( im->width+3 – 1 );\nprintf(“dft_N1=%d,dft_M1=%d\\n”,dft_N1,dft_M1);\n\n// Perform DFT of original image\ndft_A = cvShowDFT1(im, dft_M1, dft_N1,”original”);\n//Perform inverse (check)\n//cvShowInvDFT1(im,dft_A,dft_M1,dft_N1, “original”); – Commented as it overwrites the DFT\n// Perform DFT of kernel\ndft_B = cvShowDFT1(k_image,dft_M1,dft_N1,”kernel”);\n//Perform inverse of kernel (check)\n//cvShowInvDFT1(k_image,dft_B,dft_M1,dft_N1, “kernel”);- Commented as it overwrites the DFT\n// Multiply numerator with complex conjugate\ndft_C = cvCreateMat( dft_M1, dft_N1, CV_64FC2 );\nprintf(“%d %d %d %d\\n”,dft_M,dft_N,dft_M1,dft_N1);\n\n// Multiply DFT(blurred image) * complex conjugate of blur kernel\ncvMulSpectrums(dft_A,dft_B,dft_C,CV_DXT_MUL_CONJ);\n//cvShowInvDFT1(im,dft_C,dft_M1,dft_N1,”blur1?);\n\n// Split Fourier in real and imaginary parts\nimage_ReC = cvCreateImage( cvSize(dft_N1, dft_M1), IPL_DEPTH_64F, 1);\nimage_ImC = cvCreateImage( cvSize(dft_N1, dft_M1), IPL_DEPTH_64F, 1);\ncomplex_ImC = cvCreateImage( cvSize(dft_N1, dft_M1), IPL_DEPTH_64F, 2);\nprintf(“%d %d %d %d\\n”, dft_M,dft_N,dft_M1,dft_N1);\n//cvSplit( dft_C, image_ReC, image_ImC, 0, 0 );\ncvSplit( dft_C, image_ReC, image_ImC, 0, 0 );\n\n// Compute A^2 + B^2 of denominator or blur kernel\nimage_ReB = cvCreateImage( cvSize(dft_N1, dft_M1), IPL_DEPTH_64F, 1);\nimage_ImB = cvCreateImage( cvSize(dft_N1, dft_M1), IPL_DEPTH_64F, 1);\n\n// Split Real and imaginary parts\ncvSplit( dft_B, image_ReB, image_ImB, 0, 0 );\ncvPow( image_ReB, image_ReB, 2.0);\ncvPow( image_ImB, image_ImB, 2.0);\ncvAdd(image_ReB, image_ImB, image_ReB,0);\nval = cvScalarAll(kappa);\ncvAddS(image_ReB,val,image_ReB,0);\n//Divide Numerator/A^2 + B^2\ncvDiv(image_ReC, image_ReB, image_ReC, 1.0);\ncvDiv(image_ImC, image_ReB, image_ImC, 1.0);\n\n// Merge Real and complex parts\ncvMerge(image_ReC, image_ImC, NULL, NULL, complex_ImC);\n// Perform Inverse\ncvShowInvDFT1(im, (CvMat *)complex_ImC,dft_M1,dft_N1,”Weiner o/p k=10000 SIGMA=0.014089642″);\ncvWaitKey(-1);\nreturn 0;\n}\n\nCvMat* cvShowDFT1(IplImage* im, int dft_M, int dft_N,char* src)\n{\nIplImage* realInput;\nIplImage* imaginaryInput;\nIplImage* complexInput;\nCvMat* dft_A, tmp;\nIplImage* image_Re;\nIplImage* image_Im;\nchar str[80];\ndouble m, M;\nrealInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1);\nimaginaryInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1);\ncomplexInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 2);\ncvScale(im, realInput, 1.0, 0.0);\ncvZero(imaginaryInput);\ncvMerge(realInput, imaginaryInput, NULL, NULL, complexInput);\n\ndft_A = cvCreateMat( dft_M, dft_N, CV_64FC2 );\nimage_Re = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1);\nimage_Im = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1);\n\n// copy A to dft_A and pad dft_A with zeros\ncvGetSubRect( dft_A, &tmp, cvRect(0,0, im->width, im->height));\ncvCopy( complexInput, &tmp, NULL );\nif( dft_A->cols > im->width )\n{\ncvGetSubRect( dft_A, &tmp, cvRect(im->width,0, dft_A->cols – im->width, im->height));\ncvZero( &tmp );\n}\n// no need to pad bottom part of dft_A with zeros because of\n// use nonzero_rows parameter in cvDFT() call below\n\ncvDFT( dft_A, dft_A, CV_DXT_FORWARD, complexInput->height );\nstrcpy(str,”DFT -“);\nstrcat(str,src);\ncvNamedWindow(str, 0);\n\n// Split Fourier in real and imaginary parts\ncvSplit( dft_A, image_Re, image_Im, 0, 0 );\n// Compute the magnitude of the spectrum Mag = sqrt(Re^2 + Im^2)\ncvPow( image_Re, image_Re, 2.0);\ncvPow( image_Im, image_Im, 2.0);\ncvAdd( image_Re, image_Im, image_Re, NULL);\ncvPow( image_Re, image_Re, 0.5 );\n\n// Compute log(1 + Mag)\ncvAddS( image_Re, cvScalarAll(1.0), image_Re, NULL ); // 1 + Mag\ncvLog( image_Re, image_Re ); // log(1 + Mag)\ncvMinMaxLoc(image_Re, &m, &M, NULL, NULL, NULL);\ncvScale(image_Re, image_Re, 1.0/(M-m), 1.0*(-m)/(M-m));\ncvShowImage(str, image_Re);\nreturn(dft_A);\n}\n\nvoid cvShowInvDFT1(IplImage* im, CvMat* dft_A, int dft_M, int dft_N,char* src)\n{\nIplImage* realInput;\nIplImage* imaginaryInput;\nIplImage* complexInput;\nIplImage * image_Re;\nIplImage * image_Im;\ndouble m, M;\nchar str[80];\nrealInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1);\nimaginaryInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1);\ncomplexInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 2);\nimage_Re = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1);\nimage_Im = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1);\n\n//cvDFT( dft_A, dft_A, CV_DXT_INV_SCALE, complexInput->height );\ncvDFT( dft_A, dft_A, CV_DXT_INV_SCALE, dft_M);\nstrcpy(str,”DFT INVERSE – “);\nstrcat(str,src);\ncvNamedWindow(str, 0);\n// Split Fourier in real and imaginary parts\ncvSplit( dft_A, image_Re, image_Im, 0, 0 );\n// Compute the magnitude of the spectrum Mag = sqrt(Re^2 + Im^2)\ncvPow( image_Re, image_Re, 2.0);\ncvPow( image_Im, image_Im, 2.0);\ncvAdd( image_Re, image_Im, image_Re, NULL);\ncvPow( image_Re, image_Re, 0.5 );\n\n// Compute log(1 + Mag)\ncvAddS( image_Re, cvScalarAll(1.0), image_Re, NULL ); // 1 + Mag\ncvLog( image_Re, image_Re ); // log(1 + Mag)\ncvMinMaxLoc(image_Re, &m, &M, NULL, NULL, NULL);\ncvScale(image_Re, image_Re, 1.0/(M-m), 1.0*(-m)/(M-m));\n//cvCvtColor(image_Re, image_Re, CV_GRAY2RGBA);\ncvShowImage(str, image_Re);\n}\n" }, { "alpha_fraction": 0.7639999985694885, "alphanum_fraction": 0.7639999985694885, "avg_line_length": 24, "blob_id": "67d055d876c0364bba8db1dffd67b13469a2981b", "content_id": "9df19b6edcff4a658002f73bd4cd7b2bf5ad856a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 250, "license_type": "no_license", "max_line_length": 69, "num_lines": 10, "path": "/WeiSynth/CMakeFiles/WeiSynth.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/WeiSynth.dir/WeiSynth.cpp.o\"\n \"WeiSynth.pdb\"\n \"WeiSynth\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/WeiSynth.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7616822719573975, "alphanum_fraction": 0.7710280418395996, "avg_line_length": 34.66666793823242, "blob_id": "57a0f4c51adabceb6d248e74201fa921b32e094d", "content_id": "b476da37a93e17f54cbbc44f8598a0123fc7f77b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 214, "license_type": "no_license", "max_line_length": 48, "num_lines": 6, "path": "/filldemo/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( filldemo )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( filldemo filldemo.cpp )\ntarget_link_libraries( filldemo ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.5179487466812134, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 9.263157844543457, "blob_id": "c5af4dc51d1106b29232b0a60122328f284d53b9", "content_id": "4a47f30c04a506d88cd4efcb1a66270703532c3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 195, "license_type": "no_license", "max_line_length": 21, "num_lines": 19, "path": "/LFCompletion/pixelStruct.h", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#ifndef pixelStruct_h\n#define pixelStruct_h\n\nstruct pixelStruct\n{\n int x;\n int y;\n double distance;\n \n pixelStruct()\n {\n x = 0;\n y = 0;\n distance = 0;\n }\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7541666626930237, "alphanum_fraction": 0.7541666626930237, "avg_line_length": 23, "blob_id": "739b90f264c641689a53274696ddde7e7c5313a1", "content_id": "2ba7365e83c8d686b6001079597a76462d0aea4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 240, "license_type": "no_license", "max_line_length": 67, "num_lines": 10, "path": "/OldTests/Deconv/CMakeFiles/deconv.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/deconv.dir/deconv.cpp.o\"\n \"deconv.pdb\"\n \"deconv\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/deconv.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7434782385826111, "alphanum_fraction": 0.7434782385826111, "avg_line_length": 22, "blob_id": "4966aae786fdbb5b803ac9d1c0c2ea17df89dac2", "content_id": "b56e2a21c196dc2822881ba10fbe58c839481bca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 230, "license_type": "no_license", "max_line_length": 65, "num_lines": 10, "path": "/fill/CMakeFiles/fill.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/fill.dir/fill.cpp.o\"\n \"fill.pdb\"\n \"fill\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/fill.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.5186821818351746, "alphanum_fraction": 0.5689031481742859, "avg_line_length": 28.282352447509766, "blob_id": "d9fdea59a12faab645383b78b13429bbd4753868", "content_id": "a843267bae7519030510dda3ba7c34b325af8d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2489, "license_type": "no_license", "max_line_length": 135, "num_lines": 85, "path": "/OldTests/DeconvLucy/deconvlucy.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "// deconvlucy.cpp : Defines the entry point for the console application.\n//\n// ===================================================================================================================================\n// ========================================================Lucy-Richardson algorithm ===================================\n//\n// Author: Tinniam V Ganesh\n// Developed 14 May 2012\n// File: deconvlucy.cpp\n//=====================================================================================================================================\n//#include \"stdafx.h\"\n#include \"math.h\"\n#include <cxcore.h>\n#include <cv.h>\n#include <highgui.h>\n\n#define kappa 10000\nint main(int argc, char ** argv)\n{\nIplImage* im;\nIplImage* im_conv_kernel;\nIplImage* im_correction;\nIplImage* im_new;\nIplImage* im_new_est;\nIplImage* im1;\n\nchar str[80];\nint i;\nCvMat* cvShowDFT1(IplImage*, int, int,char*);\nIplImage* cvShowInvDFT1(IplImage*, CvMat*, int, int,char*);\n\nim1 = cvLoadImage(\"reordered4.jpg\");\ncvNamedWindow(\"Original-Color\", 0);\ncvShowImage(\"Original-Color\", im1);\nim = cvLoadImage(\"reordered4.jpg\", CV_LOAD_IMAGE_GRAYSCALE );\nif( !im )\nreturn -1;\n\ncvNamedWindow(\"Original-Gray\", 0);\ncvShowImage(\"Original-Gray\", im);\n\n// fk+1(x,y) = fk(x,y)\n\nfor(i=0;i < 10;i++) {\n\n// Convolve f0(x,y)= g(x,y) with blur kernel\n// f0(x,y) ** kernel\n\n// Create a blur kernel\n//double a[9]={-1,200,1,-1,200,1,-1,200,1};\n//double a[9]={0,-1,0,-1,4,-1,0,-1,0};\n//double a[9]={-4,40,4,-4,40,4,-4,40,4};\n//double a[9]={-1,2,-1,-1,2,-1,-1,2,-1};\ndouble a[9] = {0,40,0,0,40,0,0,40,0};\nCvMat kernel1 = cvMat(3,3,CV_32FC1,a);\n\n// Convolve the kernel with the blurred image as the seed i0(x,y) ** k(x,y)\nim_conv_kernel= cvCloneImage(im);\ncvFilter2D(im,im_conv_kernel,&kernel1,cvPoint(-1,-1));\n\ncvNamedWindow(\"conv\", 0);\ncvShowImage(\"conv\", im_conv_kernel);\n\n// Subtract from blurred image. Error correction = b(x,y) - ik(x,y) ** k(x.y)\nim_correction = cvCreateImage(cvSize(383,357),8,1);;\ncvSub(im,im_conv_kernel,im_correction, 0);\ncvNamedWindow(\"Sub\", 0);\ncvShowImage(\"Sub\", im_correction);\n\n// Add ik(x,y) with imCorrection - ik(x,y) + b(x,y) - ik(x,y) ** k(x,y)\nim_new_est = cvCreateImage(cvSize(383,357),8,1);;\ncvAdd(im,im_correction,im_new_est,NULL);\n\ncvNamedWindow(\"Add\", 0);\ncvShowImage(\"Add\", im_new_est);\nsprintf(str,\"Iteration - %d\",i);\ncvNamedWindow(str, 0);\ncvShowImage(str, im_new_est);\n\n//Set the estimate as the previous estimate and repeat\nim = im_new_est;\nim = cvCloneImage(im_new_est);\n}\ncvWaitKey(-1);\nreturn 0;\n}\n" }, { "alpha_fraction": 0.619123101234436, "alphanum_fraction": 0.6288959383964539, "avg_line_length": 22.962024688720703, "blob_id": "f5deb5e41c6db68a4195cbc83cd9b5a39f59c6ae", "content_id": "caed1158134c4f889e1c8b0f8055d3fc05daf4d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3786, "license_type": "no_license", "max_line_length": 94, "num_lines": 158, "path": "/LFCompletion/LFCompletionMask/LFCompletionMask.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include <iostream>\n#include \"../DepthMap.cpp\"\n#include \"../FillHoleDirected.cpp\"\n#include \"../FocalStackPropagation.cpp\"\n#include \"../pixelStruct.h\"\n\nusing namespace cv;\nusing namespace std;\n\n//LOAD ALL MATRICES AND ARRAY\nMat infocus, infocusS,inpainted;\nMat out, outS;\nMat mask, maskS;\nMat depthMap,depthMapS,depthMapF,depthMapFS,depthMapBlurred,depthMapFBlurred;\nvector<Mat> imgs;\nvector<Mat> laplacians;\nvector<int> segmentIndicies;\nvector<Mat> segments;\nvector<Mat> gauss;\nvector<Mat> windows;\n\n//PARSE STRING\n//------------------------------------------------------------\nstring retrieveString( char* buf, int max ) {\n\n size_t len = 0;\n while( (len < max) && (buf[ len ] != '\\0') ) {\n len++;\n }\n\n return string( buf, len );\n\n}\n\nint main(int argc, char** argv )\n{\n char* fn = argv[1];\n string filename = retrieveString(fn,100);\n\n bool imageLoad = true;\n int imNum = 0;\n\n //LOAD FOCAL STACK IMAGES\n while(imageLoad)\n {\n stringstream ss;\n string thisFilename;\n imgs.resize(imNum+1);\n ss << filename << imNum << \".jpg\";\n thisFilename = ss.str();\n imgs.at(imNum) = imread(thisFilename,3);\n if(imgs.at(imNum).empty())\n {\n imageLoad = false;\n imgs.resize(imNum);\n }\n else\n {\n imNum++;\n }\n }\n cout << \"images loaded\" << endl;\n\n //CREATE LAPLACIAN ARRAY\n laplacians = laplacianFocalStack(imgs);\n gauss = differenceOfGaussianFocalStack(imgs);\n\n //CREATE DEPTH MAP\n depthMap = createDepthMap(laplacians);\n\n GaussianBlur(depthMap,depthMapBlurred,Size(15,15),0);\n cout << \"depth map created\" << endl;\n\n infocus = createInFocusImage(depthMap,imgs);\n cout << \"infocus image created\" << endl;\n\n\n\n\n Size size = infocus.size();\n Size smallSize = size/2;\n resize(depthMap, depthMapS,smallSize);\n resize(infocus, infocusS,smallSize);\n Mat originalS = infocusS.clone();\n mask = Mat::zeros(size, CV_8U);\n maskS = Mat::zeros(smallSize, CV_8U);\n\n imshow(\"image\", infocusS);\n\n bool notFilled = true;\n\n string name;\n name = filename+\"_mask.jpg\";\n\n mask = imread(name,0);\n\n if(mask.empty())\n {\n return 0;\n }\n\n cout << \"mask read\" << endl;\n notFilled = false;\n\n depthMapF= fillDepthMapDirected(depthMap,mask);\n GaussianBlur(depthMapF,depthMapFBlurred,Size(15,15),0);\n\n //INPAINT IMAGE\n inpaint(infocus, mask, inpainted, 3, INPAINT_NS);\n\n cout<< \"image preliminary inpainted\" << endl;\n\n // PERFORM TEXTURE SYNTHSIS\n out = fillImageDirected(inpainted,depthMapF,depthMapFBlurred,mask,3,500);\n\n resize(out,outS,smallSize);\n imshow(\"in focus filled\",outS);\n\n\n //out = infocus;\n cout<< \"image completed - next to propagate through the focal stack\" << endl;\n\n // PROPAGATE THROUGH FOCAL STACK\n vector<Mat> outImages;\n outImages = propogateFocalStack(imgs, laplacians, out, mask, depthMapF, depthMapFBlurred);\n\n\n // WRITE IMAGES\n for(int i = 0; i < outImages.size(); i++)\n {\n stringstream ss;\n string outputName;\n ss << filename << \"_completed\" << i << \".jpg\";\n outputName = ss.str();\n cout << \"writing \" << outputName << endl;\n imwrite(outputName, outImages.at(i));\n }\n notFilled = false;\n\n resize(depthMapF,depthMapFS, smallSize);\n name = filename+\"_filled.jpg\";\n imwrite(name,out);\n name = filename+\"_depthMapFilled.jpg\";\n imwrite(name,depthMapF);\n name = filename+\"_infocus.jpg\";\n imwrite(name,infocus);\n\n cout << \"finished, all files are written\" << endl;\n\n return 0;\n\n}\n" }, { "alpha_fraction": 0.773755669593811, "alphanum_fraction": 0.7828054428100586, "avg_line_length": 36, "blob_id": "d32d327a7db6409b1838f4c4d8bafd38171453e0", "content_id": "99065e58479f133988bc26c6e5273f88baf1a6ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 221, "license_type": "no_license", "max_line_length": 50, "num_lines": 6, "path": "/FocalStack/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( FocalStack )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( FocalStack FocalStack.cpp )\ntarget_link_libraries( FocalStack ${OpenCV_LIBS} )" }, { "alpha_fraction": 0.7490196228027344, "alphanum_fraction": 0.7686274647712708, "avg_line_length": 24.5, "blob_id": "54fe8db50037fd937d5ca8e7d08f211baf698d29", "content_id": "fbc05d55b07bb247712c571ad071632f9e45365e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 255, "license_type": "no_license", "max_line_length": 70, "num_lines": 10, "path": "/TexSynth1/CMakeFiles/TexSynth1.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/TexSynth1.dir/TexSynth1.cpp.o\"\n \"TexSynth1.pdb\"\n \"TexSynth1\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/TexSynth1.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7475247383117676, "alphanum_fraction": 0.7574257254600525, "avg_line_length": 32.66666793823242, "blob_id": "d133833bdd8b2531f3ac5a9a443e9da548f9386b", "content_id": "dc985fd2909822ae883bfad6d3898916c73206b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 202, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/OldTests/Erode/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( Erode )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( Erode Erode.cpp )\ntarget_link_libraries( Erode ${OpenCV_LIBS} )\n" }, { "alpha_fraction": 0.7490196228027344, "alphanum_fraction": 0.7686274647712708, "avg_line_length": 24.5, "blob_id": "7f012879dcad0069406345df092be6a457ba1058", "content_id": "488e44031b868e033b687b32d3a059d74c013d03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 255, "license_type": "no_license", "max_line_length": 70, "num_lines": 10, "path": "/OldTests/TexSynth2/CMakeFiles/TexSynth2.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/TexSynth2.dir/TexSynth2.cpp.o\"\n \"TexSynth2.pdb\"\n \"TexSynth2\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/TexSynth2.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.4895744025707245, "alphanum_fraction": 0.5009045004844666, "avg_line_length": 29.443477630615234, "blob_id": "3b5604bcda8efc7ab0abba8f1e5897a0f0a3fad6", "content_id": "edbbf96f9687c599ac1e7771e71fb2830b4212a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10503, "license_type": "no_license", "max_line_length": 161, "num_lines": 345, "path": "/LFCompletion/FocalStackPropagation.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include <iostream>\n#include <algorithm>\n\nusing namespace cv;\nusing namespace std;\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<int> getDepthMapIndicies(const Mat &depthMap, const Mat &mask,int imgNum)\n{\n vector<int> indicies;\n int indexCount = 0;\n\n for(int y = 0; y < mask.rows; y++)\n {\n for(int x = 0; x < mask.cols; x++)\n {\n if((int) mask.at<uchar>(y,x) != 0)\n {\n if(indexCount == 0)\n {\n indexCount++;\n indicies.resize(indexCount);\n indicies.at(indexCount-1) = (int) depthMap.at<uchar>(y,x);\n }\n else\n {\n bool entered = false;\n for(int i = 0; i < indexCount; i++)\n {\n if(indicies.at(i) == (int) depthMap.at<uchar>(y,x))\n {\n entered = true;\n }\n }\n if(!entered)\n {\n indexCount++;\n indicies.resize(indexCount);\n indicies.at(indexCount-1) = (int) depthMap.at<uchar>(y,x);\n }\n }\n }\n }\n }\n\n for(int i = 0; i < indexCount; i++)\n {\n indicies.at(i) = getIndexFromDepthMap((uchar)indicies.at(i),imgNum);\n }\n\n sort(indicies.begin(),indicies.end());\n\n return indicies;\n}\n\n// //----------------------------------------------------------------------------------------------------------------------------------------\n// vector<Mat> splitSegments(const Mat &depthMap, const Mat &img, const Mat &mask, vector<int> &indicies, int imgNum)\n// {\n// int arrSize = indicies.size();\n// vector<Mat> segments;\n// segments.resize(arrSize);\n//\n// for(int i = 0; i < arrSize; i++)\n// {\n// uchar depthMapCol = getDepthMapColour(indicies.at(i),imgNum);\n// segments.at(i) = Mat::zeros(depthMap.size(), CV_8UC4);\n//\n// for(int y = 0; y < mask.rows; y++)\n// {\n// for(int x = 0; x < mask.cols; x++)\n// {\n// if((int) mask.at<uchar>(y,x) != 0 && (int)depthMap.at<uchar>(y,x) == (int)depthMapCol)\n// {\n// Vec4b s;\n// Vec3b im;\n// im = img.at<Vec3b>(y,x);\n// s.val[0] = im.val[0];\n// s.val[1] = im.val[1];\n// s.val[2] = im.val[2];\n// s.val[3] = (uchar) 255;\n//\n// segments.at(i).at<Vec4b>(y,x) = s;\n// }\n// else\n// {\n// segments.at(i).at<Vec4b>(y,x) = Vec4b(0,0,0,0);\n// }\n//\n// }\n// }\n// }\n// return segments;\n// }\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Mat> splitSegmentMasks(const Mat &depthMap, const Mat &mask, vector<int> &indicies, int imgNum)\n{\n int arrSize = indicies.size();\n vector<Mat> segments;\n segments.resize(arrSize);\n //vector<Mat> segmentsDilated;\n //segmentsDilated.resize(arrSize);\n //Mat strElement = getStructuringElement( MORPH_RECT,Size( 3, 3),Point(1,1));\n\n for(int i = 0; i < arrSize; i++)\n {\n uchar depthMapCol = getDepthMapColour(indicies.at(i),imgNum);\n segments.at(i) = Mat::zeros(depthMap.size(), CV_8U);\n\n for(int y = 0; y < mask.rows; y++)\n {\n for(int x = 0; x < mask.cols; x++)\n {\n if((int) mask.at<uchar>(y,x) != 0 && (int)depthMap.at<uchar>(y,x) == (int)depthMapCol)\n {\n segments.at(i).at<uchar>(y,x) = (uchar) 255;\n }\n else\n {\n segments.at(i).at<uchar>(y,x) = (uchar) 0;\n }\n }\n }\n string name = \"solo mask - \" + to_string(i) + \".jpg\";\n imwrite(name, segments.at(i));\n //dilate(segments.at(i), segmentsDilated.at(i),strElement,Point(-1, -1), 1, 1, 1);\n }\n\n return segments;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nRect getInFocusWindow(const Mat &laplace)\n{\n Mat small;\n int scale = laplace.rows/10;\n resize(laplace,small,laplace.size()/scale);\n\n Point2i bestPixel;\n int bestValue = 0;\n\n for(int y = 0; y < small.rows; y++)\n {\n for(int x = 0; x < small.cols; x++)\n {\n int value = (int) small.at<uchar>(y,x);\n if(value > bestValue)\n {\n bestValue = value;\n bestPixel = Point2i(x,y);\n }\n }\n }\n return Rect((bestPixel*scale),Size(scale,scale));\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Rect> getInFocusWindows(vector<Mat> &laplacians,vector<Mat> &relativeDepths)\n{\n vector<Rect> windows;\n windows.resize(laplacians.size());\n\n Mat av = averageImages(laplacians);\n for(int i = 0; i < laplacians.size(); i++)\n {\n windows.at(i) = getInFocusWindow(laplacians.at(i) - relativeDepths.at(i)*0.5);\n }\n\n return windows;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Mat> getCroppedImages(const Rect window, vector<Mat> &imgs, const Mat &distanceMap, int count)\n{\n vector<Mat> smallImgs;\n vector<Mat> smallImgsG;\n smallImgs.resize(imgs.size());\n smallImgsG.resize(imgs.size());\n\n\n for(int i = 0; i < imgs.size(); i++)\n {\n smallImgs.at(i) = imgs.at(i)(window);\n cvtColor(smallImgs.at(i),smallImgsG.at(i),CV_BGR2GRAY);\n smallImgsG.at(i) = smallImgsG.at(i) - distanceMap(window);\n }\n\n return smallImgsG;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble imDistance(const Mat &focused, const Mat &notFocused)\n{\n Mat diff;\n absdiff(notFocused,focused,diff);\n return mean(diff)[0];\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nint getCoeff(const Mat &focused, const Mat &notFocused)\n{\n Mat blurred;\n int bestCoeff = 0;\n double lowestDistance = 500;\n int stepSize = 1;\n int kSize = 0;\n\n for(int i = 1; i < 25; i++)\n {\n kSize = i*stepSize;\n kSize = (kSize*2)+1;\n\n GaussianBlur(focused,blurred,Size(kSize,kSize),kSize);\n\n Mat diff;\n\n absdiff(notFocused,blurred,diff);\n double dist = imDistance(blurred,notFocused);\n\n if(dist < lowestDistance)\n {\n bestCoeff = i*stepSize;\n lowestDistance = dist;\n }\n }\n\n return (bestCoeff*2)+1;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<int> getCoefficients(vector<Mat> &imgs, int focusedImage)\n{\n vector<int> coefficients;\n coefficients.resize(imgs.size());\n\n for(int i = 0; i < imgs.size(); i++)\n {\n if(i == focusedImage)\n {\n coefficients.at(i) = 0;\n }\n else\n {\n coefficients.at(i) = getCoeff(imgs.at(focusedImage), imgs.at(i));\n }\n }\n return coefficients;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat superImpose(const Mat &background, const Mat &foreground, const Mat &mask)\n{\n Mat out = background.clone();\n if(background.size() == foreground.size())\n {\n for(int y = 0; y < out.rows; y++)\n {\n for(int x = 0; x < out.cols; x++)\n {\n Vec3b bVal = background.at<Vec3b>(y,x);\n Vec3b foVal = foreground.at<Vec3b>(y,x);\n\n int alpha = (int) mask.at<uchar>(y,x);\n if(alpha > 0)\n {\n double ratio = ((double)alpha/255);\n\n for(int i = 0; i < 3; i++)\n {\n out.at<Vec3b>(y,x)[i] = (uchar) floor( (((double)bVal[i]) * (1-ratio) ) + ((double)foVal[i]* ratio) ) ;\n }\n }\n else\n {\n out.at<Vec3b>(y,x) = bVal;\n }\n }\n }\n }\n return out;\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Mat> propagateSegment(vector<Mat> &imgs, const Mat &infilled, const Mat &segmentMask, const Mat&relativeDepth, const Rect window, int imgIndex)\n{\n vector<Mat> imgsOut;\n vector<Mat> smallImgs;\n imgsOut.resize(imgs.size());\n smallImgs = getCroppedImages(window,imgs,relativeDepth,imgIndex);\n vector<int> coefficients = getCoefficients(smallImgs, imgIndex);\n\n Mat segmentMaskDilated,blurredMask, blurredMask2, blurredInfilled;\n\n\n\n GaussianBlur(segmentMask,blurredMask, Size(5,5), 5);\n for(int i = 0; i < imgs.size(); i++)\n {\n cout << \"propagating layer - \" + to_string(imgIndex) + \" to layer \" + to_string(i) << endl;\n int kSize = coefficients.at(i);\n if(i != imgIndex)\n {\n GaussianBlur(infilled, blurredInfilled, Size(kSize,kSize), kSize);\n imgsOut.at(i) = superImpose(imgs.at(i),blurredInfilled, blurredMask);\n Mat strElement = getStructuringElement( MORPH_RECT,Size( kSize, kSize),Point(1,1));\n dilate(segmentMask, segmentMaskDilated,strElement,Point(-1, -1), 1, 1, 1);\n GaussianBlur(segmentMaskDilated,blurredMask, Size(kSize,kSize), kSize);\n\n imgsOut.at(i) = superImpose(imgsOut.at(i),blurredInfilled, blurredMask - relativeDepth*0.25);\n imgsOut.at(i) = superImpose(imgsOut.at(i),blurredInfilled, blurredMask);\n }\n else\n {\n imgsOut.at(i) = superImpose(imgs.at(i),infilled, blurredMask);\n }\n }\n\n return imgsOut;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Mat> propogateFocalStack(vector<Mat> &imgs, vector<Mat> &laplacians, const Mat &infilled, const Mat &mask, const Mat &depthMap,const Mat &depthMapBlurred)\n{\n vector<Mat> imgsOut = imgs;\n vector<Mat> relativeDepths = getRelativeDepthMapStack(depthMapBlurred,imgs.size());\n vector<Rect> inFocusWindows = getInFocusWindows(laplacians,relativeDepths);\n\n vector<int> segmentIndicies = getDepthMapIndicies(depthMap,mask,imgs.size());\n vector<Mat> segments = splitSegmentMasks(depthMap,mask,segmentIndicies,imgs.size());\n\n for(int i = segments.size()-1; i > -1; i--)\n {\n int segmentIndex = segmentIndicies.at(i);\n imgsOut = propagateSegment(imgsOut, infilled, segments.at(i), relativeDepths.at(segmentIndex), inFocusWindows.at(segmentIndex), segmentIndex);\n }\n\n return imgsOut;\n}\n" }, { "alpha_fraction": 0.43904173374176025, "alphanum_fraction": 0.4597564935684204, "avg_line_length": 31.34782600402832, "blob_id": "6084336b7fc9bb50365638119c14c8acf9a456be", "content_id": "6e6e31e41c90518749eff9ec73379187649537de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12648, "license_type": "no_license", "max_line_length": 226, "num_lines": 391, "path": "/FillHole/FillHole.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\nMat srcBGR, srcLAB, texLAB, outLAB, outBGR,inpaintMask,inpainted;\nPoint prevPt(-1,-1);\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool inImage(int x, int y, const Mat &img)\n{\n return (x >= 0 && x < img.cols && y >= 0 && y < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool windowInImage(int x, int y, const Mat &img, int windowSize)\n{\n return (x - windowSize >= 0 && x + windowSize < img.cols && y - windowSize >= 0 && y + windowSize < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindow(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<int>(y, x, 0) = img.at<int>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n }\n }\n\n return output;\n}\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindowMask(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<uchar>(y, x, 0) = img.at<uchar>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n else\n {\n output.at<uchar>(y, x, 0) = (uchar)1;\n }\n }\n }\n\n return output;\n}\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDist(const Mat &templ8, const Mat &templ9, const Mat &mask1, const Mat &mask2, const Mat &gaussian,int windowSize)\n{\n double dist = 0;\n int count = 0;\n\n Mat diff;\n\n absdiff(templ8, templ9, diff);\n\n diff.mul(gaussian);\n\n for(int i = 0; i < (windowSize*2) + 1; i++)\n {\n for(int j = 0; j < (windowSize*2) + 1; j++)\n {\n if( i != windowSize && j != windowSize)\n {\n //if((int) mask1.at<uchar>(i,j) == 0 )//&& (int) mask2.at<uchar>(i,j) == 0)\n {\n Vec3b a,b,c;\n a = templ8.at<Vec3b>(i,j);\n b = templ9.at<Vec3b>(i,j);\n c = diff.at<Vec3b>(i,j);\n for(int k = 0; k < 3; k++)\n {\n count++;\n if((int) mask1.at<uchar>(i,j) == 0 )\n {\n dist += (c.val[k]*2)^2;\n }\n else // penalise non-image elements\n {\n dist += (c.val[k])^2;\n }\n }\n }\n }\n }\n }\n\n if(dist == 0)\n {\n cout << \"LUCKY NUMBER ZERO\" << endl;\n }\n\n return sqrt(dist)/count;\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nconst Point2i findBestPixel(const Mat &templ8, const vector<Mat> &templates, const Mat &gaussian,const Mat &mask,const vector<Mat> &masks, const Mat &sampleCount, int rows, int cols, RNG &rng,const Point2i pos, int windowSize)\n{\n Point2i bestPixel;\n Point2i ptemp;\n double bestValue = 100;\n //double dist = 0;\n\n int n = 1;\n int count = 0;\n bool yes = false;\n\n vector<Point2i> candidates;\n int numCan = 0;\n\n\n while(count < 1000)\n {\n for(int i = -1; i < 2; i+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+) -1,-1 ... -1,1 .. 1,-1,\n {\n for(int j = -1; j < 2; j+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+)\n {\n for(int c = 0; c < 2*n; c++)\n {\n if(i < 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) + c, pos.y + (n*j));}\n if(i < 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) - c );}\n if(i > 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) + c);}\n if(i > 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) - c, pos.y + (n*j));}\n\n if(windowInImage(ptemp.x,ptemp.y,mask,windowSize))\n {\n if((int) mask.at<uchar>(ptemp.y,ptemp.x,0) == 0)\n {\n double dist = getDist(templ8,templates.at(ptemp.y*cols + ptemp.x),masks.at(pos.y*cols + pos.x),masks.at(ptemp.y*cols + ptemp.x),gaussian,windowSize);\n dist *= sampleCount.at<float>(pos.y*cols+pos.x);\n if( sampleCount.at<float>(pos.y*cols+pos.x) < 2) { count++;}\n\n if(dist < bestValue)\n {\n //numCan++;\n //candidates.resize(numCan);\n //candidates.at(numCan-1) = ptemp;\n bestValue = dist;\n bestPixel.x = ptemp.x;\n bestPixel.y = ptemp.y;\n }\n }\n }\n }\n }\n }\n\n n++;\n }\n\n\n// cout << \"n \" << endl; cout << n << endl;\n// cout << \"bestPixel y\" << endl; cout << bestPixel.y << endl;\n// cout << \"bestPixel x\" << endl; cout << bestPixel.x << endl;\n// cout << \"dist\" << endl; cout << bestValue << endl;\n\n return bestPixel;//return candidates.at(rng.uniform(0,numCan-1));\n}\n\n\n\nstatic void onMouse( int event, int x, int y, int flags, void* )\n{\n if( event == EVENT_LBUTTONUP || !(flags & EVENT_FLAG_LBUTTON) )\n prevPt = Point(-1,-1);\n else if( event == EVENT_LBUTTONDOWN )\n prevPt = Point(floor(x/2),floor(y/2));\n else if( event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON) )\n {\n Point pt(x,y);\n if( prevPt.x < 0 )\n prevPt = pt;\n line( inpaintMask, prevPt, pt, Scalar::all(255), 5, 200, 0 );\n line( srcBGR, prevPt, pt, Scalar::all(255), 5, 200, 0 );\n // line( depthMap, prevPt, pt, Scalar::all(255), 5, 200, 0 );\n prevPt = pt;\n imshow(\"image\", srcBGR);\n }\n}\n\nint main(int argc, char** argv )\n{\n srcBGR = imread( argv[1], 3 );\n inpaintMask = Mat::zeros(srcBGR.size(), CV_8U);\n\n\n cvtColor(srcBGR, srcLAB, CV_BGR2Lab);\n\n int windowSize = 11;\n int winLength = (windowSize*2) + 1;\n\n Mat depth = imread( \"depthmap2.jpg\", 1);\n namedWindow( \"image\", CV_WINDOW_AUTOSIZE );\n /namedWindow( \"output\", CV_WINDOW_AUTOSIZE );\n\n imshow(\"image\", srcBGR);\n setMouseCallback( \"image\", onMouse, 0 );\n\n RNG rng;\n //rng.range(-25,25);\n\n for(;;)\n {\n char c = (char)waitKey();\n\n if( c == 27 )\n break;\n\n if( c == 'r' )\n {\n inpaintMask = Scalar::all(0);\n imshow(\"image\", srcBGR);\n }\n\n if( c == 'i' || c == ' ' )\n {\n Mat inpainted;\n inpaint(srcBGR, inpaintMask, inpainted, 3, INPAINT_TELEA);\n // imshow(\"inpainted image\", inpainted);\n cvtColor(inpainted, outLAB, CV_BGR2Lab);\n\n Mat maskBinary,originalMask,eroded, border, strElement,sampleCount,borderBig,strElement2;\n maskBinary = Mat::zeros(srcBGR.size(), CV_8U);\n threshold( inpaintMask, maskBinary, 127,255,0 );\n strElement = getStructuringElement( MORPH_RECT,Size( 3, 3),Point(1,1));\n strElement = getStructuringElement( MORPH_RECT,Size( windowSize, windowSize),Point(-1,-1));\n eroded = Mat::zeros(maskBinary.size(), CV_8U);\n border = Mat::zeros(maskBinary.size(), CV_8U);\n borderBig = Mat::zeros(maskBinary.size(), CV_8U);\n sampleCount = Mat::ones(maskBinary.size(), CV_32F);\n\n double kernalsize = (double)windowSize / 6.0;\n kernalsize = sqrt(kernalsize);\n Mat tmpGaussian = getGaussianKernel(windowSize * 2 + 1, kernalsize);\n Mat gaussianMask = tmpGaussian * tmpGaussian.t();\n\n\n\n int unfilledCount = 0;\n\n for(int y = 0; y < maskBinary.rows; y++)\n {\n for(int x = 0; x < maskBinary.cols; x++)\n {\n if((int) maskBinary.at<uchar>(y,x,0) != 0){ unfilledCount++; }\n }\n }\n int unfilledCountOriginal = unfilledCount;\n\n\n Mat blurred = outLAB.clone();\n GaussianBlur(outLAB,blurred,Size(75,75),0,0);\n\n for(int y = 0; y < outLAB.rows; y++)\n {\n for(int x = 0; x < outLAB.cols; x++)\n {\n if((int) maskBinary.at<uchar>(y,x,0) != 0)\n {\n Vec3b a;\n a = blurred.at<Vec3b>(y,x);\n for(int i = 0; i < 3; i++)\n {\n int num = a.val[i] + rng.uniform(-17,17);\n a.val[i] = num;\n }\n outLAB.at<Vec3b>(y,x) = a;\n }\n }\n }\n\n\n vector<Mat> templates(outLAB.rows*outLAB.cols);\n vector<Mat> masks(maskBinary.rows*maskBinary.cols);\n\n for(int y = 0; y < outLAB.rows; y++)\n {\n for(int x = 0; x < outLAB.cols; x++)\n {\n if(windowInImage(x,y,outLAB,windowSize)) { templates.at(y*outLAB.cols + x) = getNeighbourhoodWindow(outLAB,Point2i(x,y),windowSize); }\n }\n }\n for(int y = 0; y < maskBinary.rows; y++)\n {\n for(int x = 0; x < maskBinary.cols; x++)\n {\n masks.at(y*maskBinary.cols + x) = getNeighbourhoodWindowMask(maskBinary,Point2i(x,y),windowSize);\n }\n }\n\n originalMask = maskBinary.clone();\n int epoch = 0;\n\n while(unfilledCount > 0)\n {\n dilate(border,borderBig,strElement2,Point(-1, -1), 1, 1, 1);\n erode(maskBinary,eroded,strElement,Point(-1, -1), 1, 1, 1);\n subtract(maskBinary,eroded,border);\n\n\n for(int y = 0; y < outLAB.rows; y++)\n {\n for(int x = 0; x < outLAB.cols; x++)\n {\n if( (int) border.at<uchar>(y,x,0) != 0)\n {\n unfilledCount--;\n Mat templ8 = getNeighbourhoodWindow(outLAB,Point2i(x,y),windowSize);\n Point2i newPos = findBestPixel(templ8,templates,gaussianMask,originalMask,masks,sampleCount,outLAB.rows,outLAB.cols,rng,Point2i(x,y),windowSize);\n outLAB.at<int>(y,x,0) = outLAB.at<int>(newPos.y,newPos.x,0);\n\n float s = sampleCount.at<float>(newPos.y*outLAB.cols+newPos.x);\n s+=2;\n sampleCount.at<float>(newPos.y*outLAB.cols+newPos.x) = s;\n cout << \"current out pixel X\" << endl; cout << x << endl;\n cout << \"current out pixel Y\" << endl; cout << y << endl;\n cout << \"unfilled count \" << endl; cout << unfilledCount << endl;\n cout << \"epoch \" << endl; cout << epoch << endl;\n }\n }\n }\n\n for(int y = 0; y < outLAB.rows; y++)\n {\n for(int x = 0; x < outLAB.cols; x++)\n {\n if(windowInImage(x,y,outLAB,windowSize) && (int) borderBig.at<uchar>(y,x,0) != 0) { templates.at(y*outLAB.cols + x) = getNeighbourhoodWindow(outLAB,Point2i(x,y),windowSize); }\n }\n }\n for(int y = 0; y < maskBinary.rows; y++)\n {\n for(int x = 0; x < maskBinary.cols; x++)\n {\n if((int) borderBig.at<uchar>(y,x,0) != 0) { masks.at(y*maskBinary.cols + x) = getNeighbourhoodWindowMask(maskBinary,Point2i(x,y),windowSize); }\n }\n }\n\n maskBinary = eroded.clone();\n epoch++;\n }\n\n\n\n for(int y = 0; y < sampleCount.rows; y++)\n {\n for(int x = 0; x < sampleCount.cols; x++)\n {\n sampleCount.at<float>(y*sampleCount.cols + x) /= 255;\n }\n }\n\n // imshow(\"used\",sampleCount);\n\n cvtColor(outLAB, outBGR, CV_Lab2BGR);\n imshow(\"output\",outBGR);\n\n }\n imwrite(\"filled.jpg\",outBGR);\n imwrite(\"masked.jpg\",srcBGR);\n }\n\n\n\n\n\n\n\n\n\n\n}\n" }, { "alpha_fraction": 0.43658629059791565, "alphanum_fraction": 0.45045608282089233, "avg_line_length": 28.861940383911133, "blob_id": "0ffa4b49729c288fe8ab2f4d14167c8dc3c6a5a0", "content_id": "e1756b58082634ea5d06dd5cb135bb9e63163805", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8003, "license_type": "no_license", "max_line_length": 138, "num_lines": 268, "path": "/OldTests/TexSynth2/TexSynth2.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include <iostream>\n#include <algorithm> // std::shuffle\n#include <array> // std::array\n#include <random> // std::default_random_engine\n#include <chrono> // std::chrono::system_clock\n\nusing namespace std;\nusing namespace cv;\n\nMat src; Mat output;\nchar window_name1[] = \"Unprocessed Image\";\nchar window_name2[] = \"Processed Image\";\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool inImage(int x, int y, const Mat &img)\n{\n return (x >= 0 && x < img.cols && y >= 0 && y < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool windowInImage(int x, int y, const Mat &img, int windowSize)\n{\n return (x - windowSize >= 0 && x + windowSize < img.cols && y - windowSize >= 0 && y + windowSize < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindow(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<int>(y, x, 0) = img.at<int>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n }\n }\n\n return output;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDist(const Mat &templ8, const Mat &templ9, int windowSize)\n{\n double dist = 0;\n\n vector<Mat> channels1(3);\n vector<Mat> channels2(3);\n\n split(templ8,channels1);\n split(templ9,channels2);\n\n int count;\n\n for(int i = 0; i < windowSize+1; i++)\n {\n for(int j = 0; j < templ8.cols; j++)\n {\n count++;\n if( (i < windowSize) || (i == windowSize && j < windowSize))\n {\n for(int k = 0; k < 3; k++)\n {\n dist += abs((channels1.at(k).at<int>(i,j) - channels2.at(k).at<int>(i,j)))^2;\n }\n }\n }\n }\n\n return sqrt(dist)/count;\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nint findBestPixel(const Mat &templ8, const Mat &img,int windowSize)\n{\n Point2i bestPixel;\n double bestValue = -1;\n\n for(int y = 0; y < img.rows; y++)\n {\n for(int x = 0; x < img.cols; x++)\n {\n if(windowInImage(x,y,img,windowSize))\n {\n Mat templ9 = getNeighbourhoodWindow(src,Point2i(x,y),windowSize);\n\n double dist = getDist(templ8,templ9,windowSize);\n\n if(dist < bestValue || bestValue < 0)\n {\n bestValue = dist;\n bestPixel.x = x;\n bestPixel.y = y;\n }\n }\n }\n }\n cout << \"bestPixel x\" << endl; cout << bestPixel.x << endl;\n cout << \"bestPixel y\" << endl; cout << bestPixel.y << endl;\n cout << \"dist\" << endl; cout << bestValue << endl;\n\n return img.at<int>(bestPixel.y,bestPixel.x,0);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nint findBestPixelFast(const Mat &templ8, const vector<Mat> &templates,int rows, int cols,int windowSize)\n{\n Point2i bestPixel;\n double bestValue = -1;\n\n for(int y = windowSize; y < rows-windowSize; y++)\n {\n for(int x = windowSize; x < cols-windowSize; x++)\n {\n double dist = getDist(templ8,templates.at(y*cols + x),windowSize);\n\n if(dist < bestValue || bestValue < 0)\n {\n bestValue = dist;\n bestPixel.x = x;\n bestPixel.y = y;\n }\n }\n }\n cout << \"bestPixel x\" << endl; cout << bestPixel.x << endl;\n cout << \"bestPixel y\" << endl; cout << bestPixel.y << endl;\n cout << \"dist\" << endl; cout << bestValue << endl;\n\n return templates.at(bestPixel.y*cols+bestPixel.x).at<int>(windowSize,windowSize,0);\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\n// MAIN FUNCTION\n//----------------------------------------------------------------------------------------------------------------------------------------\nint main( int argc, char** argv )\n{\n /// Load the source image\n src = imread( argv[1], 3 );\n\n //Mat lab;\n //src = (1.0/255.0) * src;\n //cvtColor(src, lab, CV_RGB2Lab);\n\n namedWindow( window_name1, WINDOW_AUTOSIZE );\n imshow(\"Unprocessed Image\",src);\n\n output = src.clone();\n int rows = src.rows;\n int cols = src.cols;\n\n int windowSize = 4;\n int winLength = (windowSize*2) + 1;\n\n cout << rows << endl;\n cout << cols << endl;\n\n RNG rng( 0xFFFFFFFF );\n\n // -------------------------------------------------------\n // RANDOMIZE IMAGE\n // -------------------------------------------------------\n\n vector<Point2i> linearArray, newLinearArray;\n\n linearArray.resize(rows*cols);\n newLinearArray.resize(rows*cols);\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n linearArray.at(y*cols + x).x = x;\n linearArray.at(y*cols + x).y = y;\n }\n }\n\n random_shuffle(linearArray.begin(), linearArray.end());\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n Point2i p = linearArray.at(y*cols + x);\n output.at<int>(y,x,0) = src.at<int>(p.y, p.x,0);\n }\n }\n\n for(int i = 0; i < 1; i++)\n {\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n Mat templ8 = getNeighbourhoodWindow(output,Point2i(x,y),windowSize);\n vector<Point2i> candidates;\n vector<double> dist;\n candidates.resize(winLength*winLength);\n dist.resize(winLength*winLength);\n int count = 0;\n int bestValue = -1;\n double lowestValue = 0;\n\n for(int k = 0; k < winLength/2; k++)\n {\n for(int l = 0; l < winLength; l++)\n {\n Point2i relPos, refPos, rrPos;\n\n relPos = Point2i(x-(windowSize+l),y-(windowSize+k));\n\n if(windowInImage(relPos.x,relPos.y,output,windowSize))\n {\n refPos = linearArray.at(relPos.y*cols + relPos.x);\n\n if(windowInImage(refPos.x,refPos.y,output,windowSize))\n {\n rrPos = Point2i(refPos.x + (l-windowSize),refPos.y+(k-windowSize));\n\n if(windowInImage(rrPos.x,rrPos.y,output,windowSize))\n {\n candidates.at(count) = Point2i(rrPos.x,rrPos.y);\n Mat templ9 = getNeighbourhoodWindow(src,rrPos,windowSize);\n dist.at(count) = getDist(templ8,templ9,windowSize);\n\n if(dist.at(count) < lowestValue || count == 0)\n {\n bestValue = count;\n lowestValue = dist.at(count);\n }\n count++;\n }\n }\n }\n }\n }\n cout << bestValue << endl;\n cout << \"pos\" << endl;\n cout << x << endl;\n cout << y << endl;\n if(bestValue >= 0)\n {\n output.at<int>(y,x,0) = src.at<int>(candidates.at(bestValue).y,candidates.at(bestValue).x,0);\n newLinearArray.at(y*cols + x) = candidates.at(bestValue);\n }\n }\n }\n\n linearArray = newLinearArray;\n i++;\n }\n\n //Mat templ8 = getNeighbourhoodWindow(output,Point2i(40,30),2);\n\n namedWindow( window_name2, WINDOW_AUTOSIZE );\n imshow(\"Processed Image\",output);\n\n imwrite( \"Randomised_Image.tiff\", output );\n\n waitKey();\n return 0;\n}\n" }, { "alpha_fraction": 0.7816593647003174, "alphanum_fraction": 0.7903929948806763, "avg_line_length": 37.33333206176758, "blob_id": "6c22756945f5f37fb89753a7107e5ade086bc48c", "content_id": "6b5a5dd1bead24e0c7b902bdfe0b29279015e62a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 229, "license_type": "no_license", "max_line_length": 52, "num_lines": 6, "path": "/LFCompletion/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( LFCompletion )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( LFCompletion LFCompletion.cpp )\ntarget_link_libraries( LFCompletion ${OpenCV_LIBS} )" }, { "alpha_fraction": 0.5789120197296143, "alphanum_fraction": 0.5883142948150635, "avg_line_length": 22.265625, "blob_id": "8e818dca9a933deeef8b77acc75f8b2118caf753", "content_id": "1dc5f4684d1d7bac9d3b43c7b880fb2f5a64614c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1489, "license_type": "no_license", "max_line_length": 75, "num_lines": 64, "path": "/OldTests/RandomImage/RandomImage.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include <iostream>\n#include <algorithm> // std::shuffle\n#include <array> // std::array\n#include <random> // std::default_random_engine\n#include <chrono> // std::chrono::system_clock\n\nusing namespace std;\nusing namespace cv;\n\nMat src; Mat output;\nchar window_name1[] = \"Unprocessed Image\";\nchar window_name2[] = \"Processed Image\";\n\nint main( int argc, char** argv )\n{\n /// Load the source image\n src = imread( argv[1], 3 );\n\n namedWindow( window_name1, WINDOW_AUTOSIZE );\n imshow(\"Unprocessed Image\",src);\n\n output = src.clone();\n int rows = src.rows;\n int cols = src.cols;\n\n cout << rows << endl;\n cout << cols << endl;\n\n RNG rng( 0xFFFFFFFF );\n\n vector<int> linearArray;\n\n linearArray.resize(rows*cols);\n\n for(int i = 0; i < rows; i++)\n {\n for(int j = 0; j < cols; j++)\n {\n linearArray.at(j*rows + i) = j*rows + i;\n }\n }\n\n random_shuffle(linearArray.begin(), linearArray.end());\n\n for(int i = 0; i < rows; i++)\n {\n for(int j = 0; j < cols; j++)\n {\n int index = linearArray.at(j*rows + i);\n output.at<int>(i,j) = src.at<int>(index % rows, floor(index/cols));\n }\n }\n\n namedWindow( window_name2, WINDOW_AUTOSIZE );\n imshow(\"Processed Image\",output);\n\n imwrite( \"Randomised_Image.tiff\", output );\n imwrite(\"ShouldBeEmmaAgain?.tiff\", src);\n\n waitKey();\n return 0;\n}\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7866666913032532, "avg_line_length": 36.66666793823242, "blob_id": "84a926c7d9873f7e1b534204ca03f2d530194002", "content_id": "c5bc81a8b9e461f0f4e5bdac57fd1f88231aae28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 225, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/LFCompletion/GetDepthMap/CMakeLists.txt", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\nproject( GetDepthMap )\nfind_package( OpenCV )\ninclude_directories( ${OpenCV_INCLUDE_DIRS} )\nadd_executable( GetDepthMap GetDepthMap.cpp )\ntarget_link_libraries( GetDepthMap ${OpenCV_LIBS} )" }, { "alpha_fraction": 0.7639999985694885, "alphanum_fraction": 0.7639999985694885, "avg_line_length": 24, "blob_id": "d975fcc1c917520cf6bbed96e9f32af8d9340d90", "content_id": "2bd89071962d9fb16f3ab00a4cdf4be3e583e7a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 250, "license_type": "no_license", "max_line_length": 69, "num_lines": 10, "path": "/OldTests/filldemo/CMakeFiles/filldemo.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/filldemo.dir/filldemo.cpp.o\"\n \"filldemo.pdb\"\n \"filldemo\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/filldemo.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7730769515037537, "alphanum_fraction": 0.7730769515037537, "avg_line_length": 25, "blob_id": "720ce5b1a0599c4f31fa6e0c77b2200981fd72e3", "content_id": "8d2356b97fa5d7fc90bbb24a7a7102780e2aae21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 260, "license_type": "no_license", "max_line_length": 71, "num_lines": 10, "path": "/FocalStack/CMakeFiles/FocalStack.dir/cmake_clean.cmake", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/FocalStack.dir/FocalStack.cpp.o\"\n \"FocalStack.pdb\"\n \"FocalStack\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/FocalStack.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.46018874645233154, "alphanum_fraction": 0.4789147675037384, "avg_line_length": 28.486955642700195, "blob_id": "15986225cf8b2a52d27f964d9d3729ef8e2d8640", "content_id": "6c2fe95ffde93ab9b7ff0dc278ffabf3b5e048a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6782, "license_type": "no_license", "max_line_length": 138, "num_lines": 230, "path": "/WeiSynth/WeiSynth.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/imgproc/types_c.h\"\n#include <iostream>\n#include <algorithm> // std::shuffle\n#include <array> // std::array\n#include <random> // std::default_random_engine\n#include <chrono> // std::chrono::system_clock\n\nusing namespace std;\nusing namespace cv;\n\nMat src; Mat output; Mat downSrc; Mat upOut;\nchar window_name1[] = \"Unprocessed Image\";\nchar window_name2[] = \"Processed Image\";\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool inImage(int x, int y, const Mat &img)\n{\n return (x >= 0 && x < img.cols && y >= 0 && y < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool windowInImage(int x, int y, const Mat &img, int windowSize)\n{\n return (x - windowSize >= 0 && x + windowSize < img.cols && y - windowSize >= 0 && y + windowSize < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindow(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<int>(y, x, 0) = img.at<int>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n }\n }\n\n return output;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDist(const Mat &templ8, const Mat &templ9, int windowSize)\n{\n double dist = 0;\n\n vector<Mat> channels1(3);\n vector<Mat> channels2(3);\n\n Mat templ82,templ92;\n\n\n\n split(templ8,channels1);\n split(templ9,channels2);\n\n int count = 0;\n\n for(int i = 0; i < windowSize+1; i++)\n {\n for(int j = 0; j < templ8.cols; j++)\n {\n if( (i < windowSize) || (i == windowSize && j < windowSize))\n {\n Vec3b a,b;\n\n\n a = templ8.at<Vec3b>(i,j);\n b = templ9.at<Vec3b>(i,j);\n\n for(int k = 0; k < 3; k++)\n {\n count++;\n dist += abs((channels1.at(k).at<int>(i,j) - channels2.at(k).at<int>(i,j)))^2;\n\n cout << (int)a.val[k] - b.val[k]<< endl; cout << \"mad cunt\" << endl;\n }\n }\n }\n }\n\n return sqrt(dist/count);\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nint findBestPixel(const Mat &templ8, const Mat &img,int windowSize)\n{\n Point2i bestPixel;\n double bestValue = -1;\n\n for(int y = 0; y < img.rows; y++)\n {\n for(int x = 0; x < img.cols; x++)\n {\n if(windowInImage(x,y,img,windowSize))\n {\n Mat templ9 = getNeighbourhoodWindow(src,Point2i(x,y),windowSize);\n\n double dist = getDist(templ8,templ9,windowSize);\n\n if(dist < bestValue || bestValue < 0)\n {\n bestValue = dist;\n bestPixel.x = x;\n bestPixel.y = y;\n }\n }\n }\n }\n cout << \"bestPixel x\" << endl; cout << bestPixel.x << endl;\n cout << \"bestPixel y\" << endl; cout << bestPixel.y << endl;\n cout << \"dist\" << endl; cout << bestValue << endl;\n\n return img.at<int>(bestPixel.y,bestPixel.x,0);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nint findBestPixelFast(const Mat &templ8, const vector<Mat> &templates,int rows, int cols,int windowSize)\n{\n Point2i bestPixel;\n double bestValue = -1;\n\n for(int y = windowSize; y < rows-windowSize; y++)\n {\n for(int x = windowSize; x < cols-windowSize; x++)\n {\n double dist = getDist(templ8,templates.at(y*cols + x),windowSize);\n\n if(dist < bestValue || bestValue < 0)\n {\n bestValue = dist;\n bestPixel.x = x;\n bestPixel.y = y;\n }\n }\n }\n cout << \"bestPixel x\" << endl; cout << bestPixel.x << endl;\n cout << \"bestPixel y\" << endl; cout << bestPixel.y << endl;\n cout << \"dist\" << endl; cout << bestValue << endl;\n\n return templates.at(bestPixel.y*cols+bestPixel.x).at<int>(windowSize,windowSize,0);\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\n// MAIN FUNCTION\n//----------------------------------------------------------------------------------------------------------------------------------------\nint main( int argc, char** argv )\n{\n /// Load the source image\n Mat src0 = imread( argv[1]);\n\n cvtColor(src0, src, CV_BGR2Lab);\n namedWindow( window_name1, WINDOW_AUTOSIZE );\n\n\n int windowSize = 4;\n int winLength = (windowSize*2) + 1;\n RNG rng( 0xFFFFFFFF );\n\n int height = 50;\n int width = 50;\n\n output.create(floor(height),floor(width),16);\n\n/* downSrc.create(src.rows/2,src.cols/2,16);\n Mat downSrc2; downSrc2.create(src.rows/4,src.cols/4,16);\n Mat downSrc3; downSrc3.create(src.rows/8,src.cols/8,16);\n pyrDown(src,downSrc,downSrc.size());\n pyrDown(downSrc,downSrc2,downSrc2.size());\n pyrDown(downSrc2,downSrc3,downSrc3.size()); */\n\n imshow(\"Unprocessed Image\",src);\n\n for(int i = 0; i < output.rows; i++)\n {\n for (int j = 0; j < output.cols; j++)\n {\n output.at<int>(i,j,0) = rng.uniform(0,0xFFFFFFFF);\n }\n }\n\n vector<Mat> templates(src.rows*src.cols);\n\n for(int y = 0; y < src.rows; y++)\n {\n for(int x = 0; x < src.cols; x++)\n {\n if(windowInImage(x,y,src,windowSize))\n {\n templates.at(y*src.cols + x) = getNeighbourhoodWindow(src,Point2i(x,y),windowSize);\n }\n }\n }\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(windowInImage(x,y,output,windowSize))\n //if(1)\n {\n Mat templ8 = getNeighbourhoodWindow(output,Point2i(x,y),windowSize);\n\n //output.at<int>(y,x,0) = findBestPixel(templ8,src,windowSize);\n output.at<int>(y,x,0) = findBestPixelFast(templ8,templates,src.rows,src.cols,windowSize);\n\n cout << \"current out pixel Y\" << endl; cout << y << endl;\n cout << \"current out pixel X\" << endl; cout << x << endl;\n }\n }\n }\n Mat output0;\n cvtColor(output, output0, CV_Lab2BGR);\n\n namedWindow( window_name2, WINDOW_AUTOSIZE );\n imshow(\"Processed Image\",output0);\n imshow(\"LabImage\",output);\n imwrite( \"output Image.tiff\", output0 );\n\n waitKey();\n return 0;\n}\n" }, { "alpha_fraction": 0.4438965618610382, "alphanum_fraction": 0.46097415685653687, "avg_line_length": 28.802867889404297, "blob_id": "d22c1fda8170b66c58272c6fbb193500e0cc6ebb", "content_id": "611ce3c2f3177f4be5a90d134e19e9696c1289e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8315, "license_type": "no_license", "max_line_length": 175, "num_lines": 279, "path": "/OldTests/fill/fill.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\nstatic void help()\n{\n cout << \"\\nCool inpainging demo. Inpainting repairs damage to images by floodfilling the damage \\n\"\n << \"with surrounding image areas.\\n\"\n \"Using OpenCV version %s\\n\" << CV_VERSION << \"\\n\"\n \"Usage:\\n\"\n \"./inpaint [image_name -- Default ../data/fruits.jpg]\\n\" << endl;\n\n cout << \"Hot keys: \\n\"\n \"\\tESC - quit the program\\n\"\n \"\\tr - restore the original image\\n\"\n \"\\ti or SPACE - run inpainting algorithm\\n\"\n \"\\t\\t(before running it, paint something on the image)\\n\" << endl;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool inImage(int x, int y, const Mat &img)\n{\n return (x >= 0 && x < img.cols && y >= 0 && y < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool windowInImage(int x, int y, const Mat &img, int windowSize)\n{\n return (x - windowSize >= 0 && x + windowSize < img.cols && y - windowSize >= 0 && y + windowSize < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindow(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<int>(y, x, 0) = img.at<int>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n }\n }\n\n return output;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDist(const Mat &templ8, const Mat &templ9, int windowSize)\n{\n double dist = 0;\n\n vector<Mat> channels1(3);\n vector<Mat> channels2(3);\n\n split(templ8,channels1);\n split(templ9,channels2);\n\n int count = 0;\n\n for(int i = 0; i < windowSize+1; i++)\n {\n for(int j = 0; j < templ8.cols; j++)\n {\n if( (i < windowSize) || (i == windowSize && j < windowSize))\n {\n for(int k = 0; k < 3; k++)\n {\n count++;\n dist += abs((channels1.at(k).at<int>(i,j) - channels2.at(k).at<int>(i,j)))^2;\n }\n }\n }\n }\n\n return sqrt(dist/count);\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nconst Point2i findBestPixelGrow(const Mat &templ8, const vector<Mat> &templates, const Mat &mask,int rows, int cols,const vector<Mat> &masks, const Point2i pos,int windowSize)\n{\n Point2i bestPixel;\n Point2i ptemp;\n double bestValue = 100;\n //double dist = 0;\n\n int n = 1;\n\n bool yes = false;\n\n/*\n while(n < 100)\n {\n for(int i = -1; i < 2; i+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+) -1,-1 ... -1,1 .. 1,-1,\n {\n for(int j = -1; j < 2; j+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+)\n {\n for(int c = 0; c < 2*n; c++)\n {\n if(i < 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) + c, pos.y + (n*j));}\n if(i < 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) - c );}\n if(i > 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) + c);}\n if(i > 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) - c, pos.y + (n*j));}\n\n if(windowInImage(ptemp.x,ptemp.y,mask,windowSize))\n {\n //if(mask.at<int>(ptemp.y,ptemp.x,0) == 0)\n //{\n double dist = getDist(templ8,templates.at(ptemp.y*cols + ptemp.x),windowSize);\n\n if(dist < bestValue)\n {\n bestValue = dist;\n bestPixel.x = ptemp.x;\n bestPixel.y = ptemp.y;\n }\n if(bestValue < 0.05 )\n {\n yes = true;\n }\n }\n }\n }\n }\n\n n++;\n }\n\n*/\n\n for(int y = windowSize; y < rows-windowSize; y++)\n {\n for(int x = windowSize; x < cols-windowSize; x++)\n {\n double dist = getDist(templ8,templates.at(y*cols + x),windowSize);\n\n if(dist < bestValue || bestValue < 0)\n {\n bestValue = dist;\n bestPixel.x = x;\n bestPixel.y = y;\n }\n }\n }\n\n\n cout << \"n \" << endl; cout << n << endl;\n cout << \"bestPixel y\" << endl; cout << bestPixel.y << endl;\n cout << \"bestPixel x\" << endl; cout << bestPixel.x << endl;\n cout << \"dist\" << endl; cout << bestValue << endl;\n\n return bestPixel;\n}\n\n\nMat img, inpaintMask;\nPoint prevPt(-1,-1);\n\nstatic void onMouse( int event, int x, int y, int flags, void* )\n{\n if( event == EVENT_LBUTTONUP || !(flags & EVENT_FLAG_LBUTTON) )\n prevPt = Point(-1,-1);\n else if( event == EVENT_LBUTTONDOWN )\n prevPt = Point(x,y);\n else if( event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON) )\n {\n Point pt(x,y);\n if( prevPt.x < 0 )\n prevPt = pt;\n line( inpaintMask, prevPt, pt, Scalar::all(255), 5, 8, 0 );\n line( img, prevPt, pt, Scalar::all(255), 5, 8, 0 );\n prevPt = pt;\n imshow(\"image\", img);\n }\n}\n\n\nint main( int argc, char** argv )\n{\n char* filename = argc >= 2 ? argv[1] : (char*)\"../data/fruits.jpg\";\n //Mat img0 = imread(filename, 3);\n Mat img0 = imread( argv[1], 3 );\n if(img0.empty())\n {\n cout << \"Couldn't open the image \" << filename << \". Usage: inpaint <image_name>\\n\" << endl;\n return 0;\n }\n\n help();\n\n namedWindow( \"image\", WINDOW_NORMAL );\n namedWindow( \"inpainted image\", WINDOW_NORMAL );\n\n\n img = img0.clone();\n inpaintMask = Mat::zeros(img.size(), CV_8U);\n\n int windowSize = 4;\n int winLength = (windowSize*2) + 1;\n\n imshow(\"image\", img);\n setMouseCallback( \"image\", onMouse, 0 );\n\n for(;;)\n {\n char c = (char)waitKey();\n\n if( c == 27 )\n break;\n\n if( c == 'r' )\n {\n inpaintMask = Scalar::all(0);\n img0.copyTo(img);\n imshow(\"image\", img);\n }\n\n if( c == 'i' || c == ' ' )\n {\n Mat inpainted;\n inpaint(img, inpaintMask, inpainted, 3, INPAINT_NS);\n imshow(\"inpainted image\", inpainted);\n\n vector<Mat> templates(img.rows*img.cols);\n vector<Mat> masks(inpaintMask.rows*inpaintMask.cols);\n\n for(int y = 0; y < img.rows; y++)\n {\n for(int x = 0; x < img.cols; x++)\n {\n if(windowInImage(x,y,img,windowSize))\n {\n //templates.at(y*img.cols + x)\n templates.at(y*img.cols + x) = getNeighbourhoodWindow(img,Point2i(x,y),windowSize);\n masks.at(y*inpaintMask.cols + x) = getNeighbourhoodWindow(inpaintMask,Point2i(x,y),windowSize);\n }\n }\n }\n\n Mat texFilled;\n texFilled = inpainted.clone();\n\n for(int y = 0; y < texFilled.rows; y++)\n {\n for(int x = 0; x < texFilled.cols; x++)\n {\n if(inpaintMask.at<int>(y,x,0) != 0)\n {\n Point2i pos(x,y);\n Mat templ8 = getNeighbourhoodWindow(img,pos,windowSize);\n Point2i newPos = findBestPixelGrow(templ8,templates,inpaintMask,img.rows,img.cols,masks,pos,windowSize);\n texFilled.at<int>(pos.y,pos.x,0) = img.at<int>(newPos.y,newPos.x,0);\n inpainted.at<int>(newPos.y,newPos.x,0) = 0;\n\n cout << \"current out pixel Y\" << endl; cout << y << endl;\n cout << \"current out pixel X\" << endl; cout << x << endl;\n cout << \"COLOUR\" << endl; cout << texFilled.at<int>(y,x,0) << endl;\n }\n }\n }\n\n imshow(\"inpainted image\", inpainted);\n imshow(\"texfilled image\", texFilled);\n\n }\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.45266491174697876, "alphanum_fraction": 0.47102490067481995, "avg_line_length": 29.944869995117188, "blob_id": "76aefd97b993f925f8d8e20d3e8aa8683360576f", "content_id": "5004bbe2bb77a1e61f05c86b4db78552f5eac446", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20207, "license_type": "no_license", "max_line_length": 274, "num_lines": 653, "path": "/LFCompletion/FillHoleDirected.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include \"pixelStruct.h\"\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool inImage(int x, int y, const Mat &img)\n{\n return (x >= 0 && x < img.cols && y >= 0 && y < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nbool windowInImage(int x, int y, const Mat &img, int windowSize)\n{\n return (x - windowSize >= 0 && x + windowSize < img.cols && y - windowSize >= 0 && y + windowSize < img.rows);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindow(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<int>(y, x, 0) = img.at<int>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n }\n }\n\n return output;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindowFast(const Mat &img, Point2i pt, int windowSize)\n{\n return img(Rect(Point2i(pt.x - windowSize, pt.y - windowSize), Size(windowSize * 2 + 1, windowSize * 2 + 1)));\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getNeighbourhoodWindowMask(const Mat &img, Point2i pt, int windowSize)\n{\n Mat output = Mat(windowSize * 2 + 1, windowSize * 2 + 1, 16);\n\n for(int y = 0; y < output.rows; y++)\n {\n for(int x = 0; x < output.cols; x++)\n {\n if(inImage( pt.x - windowSize + x, pt.y - windowSize + y, img))\n {\n output.at<uchar>(y, x, 0) = img.at<uchar>(pt.y - windowSize + y, pt.x - windowSize + x, 0);\n }\n else\n {\n output.at<uchar>(y, x, 0) = (uchar)1;\n }\n }\n }\n\n return output;\n}\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDistSimple(const Mat &templ8, const Mat &templ9, int windowSize)\n{\n double dist = 0;\n int count = 0;\n\n Mat diff;\n absdiff(templ8, templ9, diff);\n\n\n for(int i = 0; i < (windowSize*2) + 1; i++)\n {\n for(int j = 0; j < (windowSize*2) + 1; j++)\n {\n if( i != windowSize && j != windowSize)\n {\n count++;\n dist += abs((int) diff.at<uchar>(i,j));\n }\n }\n }\n\n return dist/count;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nconst Point2i findBestPixelSimple(const Mat &templ8, const vector<Mat> &templates, const Mat &mask, int rows, int cols, const Point2i pos, int windowSize)\n{\n Point2i bestPixel;\n Point2i ptemp;\n double bestValue = 100;\n\n int n = 1;\n int count = 0;\n bool yes = false;\n\n while(count < 30)\n {\n for(int i = -1; i < 2; i+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+) -1,-1 ... -1,1 .. 1,-1,\n {\n for(int j = -1; j < 2; j+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+)\n {\n for(int c = 0; c < 2*n; c++)\n {\n if(i < 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) + c, pos.y + (n*j));}\n if(i < 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) - c );}\n if(i > 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) + c);}\n if(i > 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) - c, pos.y + (n*j));}\n\n if(windowInImage(ptemp.x,ptemp.y,mask,windowSize))\n {\n if((int) mask.at<uchar>(ptemp.y,ptemp.x,0) == 0)\n {\n double dist = getDistSimple(templ8,templates.at(ptemp.y*cols + ptemp.x),windowSize);\n count++;\n if(dist < bestValue)\n {\n bestValue = dist;\n bestPixel.x = ptemp.x;\n bestPixel.y = ptemp.y;\n }\n }\n }\n }\n }\n }\n\n n++;\n }\n return bestPixel;\n}\n\nMat fillDepthMapDirected(const Mat &depthMap, const Mat &inpaintMask)\n{\n Mat inpainted,maskBinary,output;\n int windowSize = 2;\n int winLength = (windowSize*2) + 1;\n inpaint(depthMap, inpaintMask, inpainted, 3, INPAINT_TELEA);\n output = inpainted.clone();\n\n vector<Mat> templates(inpainted.rows*inpainted.cols);\n for(int y = 0; y < inpainted.rows; y++)\n {\n for(int x = 0; x < inpainted.cols; x++)\n {\n if(windowInImage(x,y,inpainted,windowSize)) { templates.at(y*inpainted.cols + x) = getNeighbourhoodWindow(inpainted,Point2i(x,y),windowSize); }\n }\n }\n\n\n for(int y = 0; y < inpainted.rows; y++)\n {\n for(int x = 0; x < inpainted.cols; x++)\n {\n if( (int) inpaintMask.at<uchar>(y,x,0) != 0)\n {\n Mat templ8 = getNeighbourhoodWindow(inpainted,Point2i(x,y),windowSize);\n Point2i newPos = findBestPixelSimple(templ8,templates,inpaintMask,inpainted.rows,inpainted.cols,Point2i(x,y),windowSize);\n output.at<int>(y,x,0) = inpainted.at<int>(newPos.y,newPos.x,0);\n\n }\n }\n }\n\n return output;\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\n\nbool isNeighbour(const Point2i pos, const Point2i ptemp, vector<Point2i> &linearArray, int windowSize,int cols)\n{\n bool isN = false;\n\n for(int y = (-1*windowSize)+1; y < windowSize; y++)\n {\n for(int x = (-1*windowSize)+1; x < windowSize; x++)\n {\n if(!(y == 0 && x == 0))\n {\n if(linearArray.at((pos.y+ y)*cols + pos.x+x) == ptemp)\n {\n isN = true;\n }\n }\n }\n }\n return isN;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\n\ndouble IdenticalNeighbourWeight(const Point2i pos, const Point2i ptemp, vector<Point2i> &linearArray, int windowSize,int cols)\n{\n int w = 1;\n int c = 0;\n for(int y = (-1*windowSize)+1; y < windowSize; y++)\n {\n for(int x = (-1*windowSize)+1; x < windowSize; x++)\n {\n if(!(y == 0 && x == 0))\n {\n if(linearArray.at((pos.y+ y)*cols + pos.x+x) == ptemp)\n {\n w++;\n }\n c++;\n }\n }\n }\n\n return (double) 1 + ((1.45/(c)) * w);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble getDistDirected(const Mat &templ8, const Mat &templ9, const Mat &gaussian, int windowSize)\n{\n double dist = 0;\n int count = 0;\n\n Mat diff;\n\n absdiff(templ8, templ9, diff);\n\n diff.mul(gaussian);\n\n for(int i = 0; i < (windowSize*2) + 1; i++)\n {\n for(int j = 0; j < (windowSize*2) + 1; j++)\n {\n if(!( i == windowSize && j == windowSize))\n {\n for(int k = 0; k < 3; k++)\n {\n dist += (diff.at<Vec3b>(i,j)[k])^2;\n count++;\n }\n }\n }\n }\n\n return sqrt(dist)/count;\n}\n\n//ASHIKHMIN SEARCH SEE ALGORITHM 2\n//----------------------------------------------------------------------------------------------------------------------------------------\npixelStruct findBestPixelAshikhmin(const Mat &templ8, const vector<Mat> &templates, const Mat &gaussian, const Mat &mask, const Mat &depthMap, int rows, int cols, const Point2i pos, vector<Point2i> &linearArray, int windowSize)\n{\n Point2i bestPixel = pos;\n Point2i ptemp;\n double bestValue = 1000000;\n\n\n int n = 1;\n int count = 0;\n\n\n for(int y = (-1*windowSize)+1; y < windowSize; y++)\n {\n for(int x = (-1*windowSize)+1; x < windowSize; x++)\n {\n int num = ((pos.y+y)*cols) + pos.x + x;\n if(num >= 0 && num < rows*cols)\n {\n ptemp = linearArray.at(num);\n if(ptemp.x != -1)\n {\n ptemp.x = ptemp.x + x*-1;\n ptemp.y = ptemp.y + y*-1;\n\n if(pos!= ptemp && windowInImage(ptemp.x,ptemp.y,mask,windowSize) && !((int) mask.at<uchar>(ptemp.y,ptemp.x,0) != 0)) //!isNeighbour(pos,ptemp,linearArray,floor(windowSize/2),cols)\n {\n double dist = getDistDirected(templ8, templates.at(ptemp.y*cols +ptemp.x),gaussian,windowSize);\n double depthDistance = getDepthDistance(depthMap.at<uchar>(pos), depthMap.at<uchar>(ptemp));\n dist *= depthDistance;\n\n // if(isNeighbour(pos,ptemp,linearArray,windowSize,cols))\n // {\n // dist *= 1.4;\n // }\n\n dist *= IdenticalNeighbourWeight(pos,ptemp,linearArray,windowSize,cols);\n\n if(dist < bestValue)\n {\n bestValue = dist;\n bestPixel.x = ptemp.x;\n bestPixel.y = ptemp.y;\n }\n }\n }\n }\n }\n }\n\n pixelStruct p;\n\n if(pos != bestPixel)\n {\n p.x = bestPixel.x;\n p.y = bestPixel.y;\n p.distance = bestValue;\n }\n else\n {\n p.x = -2;\n p.y = -2;\n p.distance = 500;\n }\n\n return p;\n}\n\n//EXPANDING SEACH - SEE ALGORITHM 1 FOR EXPLANATION\n//----------------------------------------------------------------------------------------------------------------------------------------\nconst Point2i findBestPixelExhaustive(int searchRange, const Mat &templ8, const vector<Mat> &templates, const Mat &gaussian, const Mat &mask, const Mat &depthMap, int rows, int cols,const Point2i pos, vector<Point2i> &linearArray, int windowSize, RNG &rng, double threshold)\n{\n Point2i bestPixel = pos;\n Point2i ptemp;\n double bestValue = 100;\n vector<Point2i> points;\n points.resize(1);\n\n int n = 1;\n int count = 0;\n\n bestValue = 100;\n while(count < searchRange && n < 250)\n {\n for(int i = -1; i < 2; i+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+) -1,-1 ... -1,1 .. 1,-1,\n {\n for(int j = -1; j < 2; j+=2) //ALTERNATE SIGN (-,-) then (-,+) then (+,-) then (+,+)\n {\n for(int c = 0; c < 2*n; c++)\n {\n if(i < 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) + c, pos.y + (n*j));}\n if(i < 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) - c );}\n if(i > 0 && j < 0) {ptemp = Point2i(pos.x + (n*i) , pos.y + (n*j) + c);}\n if(i > 0 && j > 0) {ptemp = Point2i(pos.x + (n*i) - c, pos.y + (n*j));}\n\n if(windowInImage(ptemp.x,ptemp.y,mask,windowSize))\n {\n if(!((int) mask.at<uchar>(ptemp.y,ptemp.x,0) != 0))\n {\n double dist = getDistDirected(templ8, templates.at(ptemp.y*cols + ptemp.x),gaussian,windowSize);\n double depthDistance = getDepthDistance(depthMap.at<uchar>(pos), depthMap.at<uchar>(ptemp));\n\n dist *= depthDistance;\n\n// if(isNeighbour(pos,ptemp,linearArray,windowSize,cols))\n// {\n// dist *= 1.4;\n// }\n\n dist *= IdenticalNeighbourWeight(pos,ptemp,linearArray,windowSize,cols);\n\n count++;\n if(dist < threshold)\n {\n points.at(points.size()-1) = ptemp;\n points.resize(points.size()+1);\n }\n if(dist < bestValue)\n {\n bestValue = dist;\n bestPixel.x = ptemp.x;\n bestPixel.y = ptemp.y;\n }\n\n }\n }\n }\n }\n }\n n++;\n }\n\n\n if(points.size() > 1)\n {\n bestPixel = points.at( floor(rng.uniform(0,points.size()-1) ) );\n cout << \"Random Markov Field search\" << endl; cout << bestValue << endl;\n cout << \"Search num \" << endl; cout << points.size() << endl;\n }\n else{cout << \"Exhaustive search\" << endl; cout << bestValue << endl;}\n return bestPixel;\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Point2i> getLinearArray(const Mat &maskBinary)\n{\n vector<Point2i> linArr;\n linArr.resize(maskBinary.rows*maskBinary.cols);\n\n for(int y = 0; y < maskBinary.rows; y++)\n {\n for(int x = 0; x < maskBinary.cols; x++)\n {\n if((int) maskBinary.at<uchar>(y,x,0) != 0)\n {\n linArr.at(y*maskBinary.cols + x).x = -1;\n linArr.at(y*maskBinary.cols + x).y = -1;\n }\n else\n {\n linArr.at(y*maskBinary.cols + x).x = x;\n linArr.at(y*maskBinary.cols + x).y = y;\n }\n }\n }\n\n return linArr;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nvector<Mat> getTemplates(const Mat &img, int windowSize)\n{\n vector<Mat> templates;\n templates.resize(img.rows*img.cols);\n\n for(int y = 0; y < img.rows; y++)\n {\n for(int x = 0; x < img.cols; x++)\n {\n if(windowInImage(x,y,img,windowSize)) { templates.at(y*img.cols + x) = getNeighbourhoodWindowFast(img,Point2i(x,y),windowSize); }\n\n cout << \"Create template - x : \" + to_string(x) + \" y : \" + to_string(y) << endl;\n }\n }\n return templates;\n}\n\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat getGaussianMask(int windowSize)\n{\n double kernalsize = (double)windowSize / 6.0;\n kernalsize = sqrt(kernalsize);\n Mat tmpGaussian = getGaussianKernel(windowSize * 2 + 1, kernalsize);\n return tmpGaussian * tmpGaussian.t();\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\ndouble gaussianMaskWeight(const Mat &gaussianMask)\n{\n Mat blank = Mat::zeros(gaussianMask.size(), CV_8U);\n Mat white = Mat::ones(gaussianMask.size(), CV_8U);\n white*255;\n\n return getDistDirected(blank,white,gaussianMask,(gaussianMask.rows-1)/2);\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat addNoiseWithMask(const Mat &img, const Mat &maskBinary, RNG &rng)\n{\n Mat out = img.clone();\n for(int y = 0; y < img.rows; y++)\n {\n for(int x = 0; x < img.cols; x++)\n {\n if((int) maskBinary.at<uchar>(y,x,0) != 0)\n {\n Vec3b a;\n a = img.at<Vec3b>(y,x);\n int randInt = rng.uniform(-17,17);\n for(int i = 0; i < 3; i++)\n {\n int num = (int)a.val[i] + randInt;\n if(num < 0){num = 0;}\n if(num > 255){num = 255;}\n a.val[i] = num;\n }\n out.at<Vec3b>(y,x) = a;\n }\n }\n }\n return out;\n}\n\n//----------------------------------------------------------------------------------------------------------------------------------------\nint countUnfilled(const Mat &maskBinary)\n{\n int unfilledCount = 0;\n\n for(int y = 0; y < maskBinary.rows; y++)\n {\n for(int x = 0; x < maskBinary.cols; x++)\n {\n if((int) maskBinary.at<uchar>(y,x,0) != 0)\n {\n unfilledCount++;\n }\n }\n }\n\n return unfilledCount;\n}\n\n// FILL HOLE SEE ALGORITHM 3\n//----------------------------------------------------------------------------------------------------------------------------------------\nMat fillImageDirected(const Mat &inpainted, const Mat &depthMap, const Mat&depthMapBlurred, const Mat &inpaintMask, int windowSize, int searchSize)\n{\n Mat noisy, outLAB, outBGR;\n Mat maskBinary, originalMask, maskBig, maskBigger;\n Mat eroded, border, borderBig;\n Mat strElement,strElement2;\n Mat sampleCount;\n Mat gaussianMask;\n\n vector<Point2i> linearArray;\n vector<Mat> templates;\n\n RNG rng;\n\n int winLength = (windowSize*2) + 1;\n int rows = inpainted.rows;\n int cols = inpainted.cols;\n\n strElement = getStructuringElement( MORPH_RECT,Size( 3, 3),Point(-1,-1));\n strElement2 = getStructuringElement( MORPH_RECT,Size( windowSize+1, windowSize+1),Point(-1,-1));\n maskBinary = Mat::zeros(inpainted.size(), CV_8U);\n eroded = Mat::zeros(maskBinary.size(), CV_8U);\n border = Mat::zeros(maskBinary.size(), CV_8U);\n borderBig = Mat::zeros(maskBinary.size(), CV_8U);\n\n cout << \"initialised matricies\" << endl;\n\n threshold( inpaintMask, maskBinary, 127,255,0 );\n\n cout << \"created binary mask\" << endl;\n\n linearArray = getLinearArray(maskBinary);\n\n cout << \"position index array created\" << endl;\n\n noisy = addNoiseWithMask(inpainted,maskBinary, rng);\n\n // imwrite(\"impaintedNoise.jpg\", noisy);\n // cout << \"noise added\" << endl;\n\n cvtColor(inpainted, outLAB, CV_BGR2Lab);\n\n cout << \"convereted to LAB colour space\" << endl;\n\n templates = getTemplates(outLAB,windowSize);\n\n cout << \"templates created\" << endl;\n\n gaussianMask = getGaussianMask(windowSize);\n\n originalMask = maskBinary.clone();\n Mat maskExtended;\n dilate(originalMask,maskExtended,strElement2,Point(-1, -1), 1, 1, 1);\n\n int unfilledCount = countUnfilled(maskBinary);\n\n cout << \"pixels to be filled - \" + to_string(unfilledCount) << endl;\n\n int epoch = 0;\n\n double winSizeWeight = 0;\n winSizeWeight = gaussianMaskWeight(gaussianMask);\n\n winSizeWeight *= 1.9;\n\n winSizeWeight = 0.2;\n\n\n while(unfilledCount > 0)\n {\n erode(maskBinary,eroded,strElement,Point(-1, -1), 1, 1, 1);\n subtract(maskBinary,eroded,border);\n\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n if( (int) border.at<uchar>(y,x,0) != 0 )\n {\n unfilledCount--;\n if(windowInImage(x,y,originalMask,windowSize))\n {\n Mat templ8 = getNeighbourhoodWindowFast(outLAB,Point2i(x,y),windowSize);\n\n pixelStruct p; p.x = -2; p.y = -2; p.distance = 500;\n Point2i newPos;\n\n cout << \"threshold\" << endl; cout << winSizeWeight << endl;\n if(epoch > 0)\n {\n p = findBestPixelAshikhmin(templ8,templates,gaussianMask,maskExtended,depthMapBlurred,rows,cols,Point2i(x,y),linearArray,windowSize);\n }\n if(p.distance < winSizeWeight)\n {\n outLAB.at<int>(y,x,0) = outLAB.at<int>(p.y,p.x,0);\n newPos.x = p.x;\n newPos.y = p.y;\n\n cout << \"Ashikhmin search\" << endl; cout << p.distance << endl;\n }\n else\n {\n newPos = findBestPixelExhaustive(searchSize,templ8,templates,maskExtended,originalMask,depthMapBlurred,rows,cols,Point2i(x,y),linearArray,windowSize,rng,0.18);\n outLAB.at<int>(y,x,0) = outLAB.at<int>(newPos.y,newPos.x,0);\n\n }\n\n if(newPos != Point2i(x,y))\n {\n linearArray.at(y*cols + x) = newPos;\n }\n\n cout << \"current out pixel\" << endl; cout << Point2i(x,y) << endl;\n cout << \"picked pixel\" << endl; cout << newPos << endl;\n cout << \"unfilled count \" << endl; cout << unfilledCount << endl;\n cout << \"epoch \" << endl; cout << epoch << endl;\n }\n }\n }\n }\n\n\n dilate(border,borderBig,strElement2,Point(-1, -1), 1, 1, 1);\n for(int y = 0; y < rows; y++)\n {\n for(int x = 0; x < cols; x++)\n {\n if(windowInImage(x,y,outLAB,windowSize) && (int) borderBig.at<uchar>(y,x,0) != 0) { templates.at(y*cols + x) = getNeighbourhoodWindow(outLAB,Point2i(x,y),windowSize); }\n }\n }\n\n maskBinary = eroded.clone();\n epoch++;\n }\n\n\n cvtColor(outLAB, outBGR, CV_Lab2BGR);\n cout << \"convereted to BGR colour space\" << endl;\n return outBGR;\n}\n" }, { "alpha_fraction": 0.60819011926651, "alphanum_fraction": 0.6167846322059631, "avg_line_length": 21.735631942749023, "blob_id": "b4977e0f62b28562e6fe768afddcf4b6e4db350e", "content_id": "776bafe9677747d0f8f0471fd577c99121ca062a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1978, "license_type": "no_license", "max_line_length": 77, "num_lines": 87, "path": "/LFCompletion/GetInFocus/GetInFocus.cpp", "repo_name": "terrybroad/Light-Field-Completion", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"opencv2/imgproc/types_c.h\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/photo/photo.hpp\"\n#include <iostream>\n#include \"../DepthMap.cpp\"\n#include \"../FillHoleDirected.cpp\"\n#include \"../FocalStackPropagation.cpp\"\n#include \"../pixelStruct.h\"\n\nusing namespace cv;\nusing namespace std;\nMat infocus, infocusS,inpainted;\nMat out, outS;\nMat mask, maskS;\nMat depthMap,depthMapS,depthMapF,depthMapFS,depthMapBlurred,depthMapFBlurred;\nvector<Mat> imgs;\nvector<Mat> laplacians;\nvector<int> segmentIndicies;\nvector<Mat> segments;\nvector<Mat> gauss;\nvector<Mat> windows;\n\n//------------------------------------------------------------\nstring retrieveString( char* buf, int max ) {\n\n size_t len = 0;\n while( (len < max) && (buf[ len ] != '\\0') ) {\n len++;\n }\n\n return string( buf, len );\n\n}\n\nint main(int argc, char** argv )\n{\n char* fn = argv[1];\n string filename = retrieveString(fn,100);\n\n bool imageLoad = true;\n int imNum = 0;\n\n\n while(imageLoad)\n {\n stringstream ss;\n string thisFilename;\n imgs.resize(imNum+1);\n ss << filename << imNum << \".jpg\";\n thisFilename = ss.str();\n imgs.at(imNum) = imread(thisFilename,3);\n if(imgs.at(imNum).empty())\n {\n imageLoad = false;\n imgs.resize(imNum);\n }\n else\n {\n imNum++;\n }\n }\n\n //laplacians = laplacianFocalStack(imgs);\n gauss = differenceOfGaussianFocalStack(imgs);\n\n string name;\n name = filename+\"_depthMapEdited.jpg\";\n depthMap = imread(name,1);\n if(depthMap.empty())\n {\n depthMap = createDepthMap(gauss);\n name = filename+\"_depthMap.jpg\";\n imwrite(name,depthMap);\n }\n\n infocus = createInFocusImage(depthMap,imgs);\n\n name = filename+\"_infocus.jpg\";\n imwrite(name,infocus);\n\n cout << \"finished, all files are written\" << endl;\n\n return 0;\n}\n" } ]
48
lrsouthflorida/pirate_bartender
https://github.com/lrsouthflorida/pirate_bartender
12e532acdeac299a06035a71941f177b2efa5b40
4d0f78f76a04b3d16d4b9e5d1c2dbfebd12dc9ae
80c91446ed28950fae20275e322308a7a0ace8ca
refs/heads/master
2021-01-10T07:38:09.136494
2016-01-07T00:48:04
2016-01-07T00:48:04
48,865,209
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.2777777910232544, "alphanum_fraction": 0.3305555582046509, "avg_line_length": 17.52941131591797, "blob_id": "7cb629e431ab28927e17f6e2fe95f66f64398830", "content_id": "c10ba14004b33909e29c0aefb88960e940082897", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 43, "num_lines": 17, "path": "/fizzbuzz.py", "repo_name": "lrsouthflorida/pirate_bartender", "src_encoding": "UTF-8", "text": "n = 0\nwhile n < 101:\n if n % 5 == 0 and n % 3 == 0:\n print'FizzBuzz'\n elif n % 3 == 0:\n print'Fizz'\n elif n % 5 == 0:\n print'Buzz'\n \n else:\n print n\n print 'FizzBuzz counting up to 100'\n \n n = n + 1\n \n if n >= 101:\n break\n \n \n \n \n \n " }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.5263158082962036, "avg_line_length": 32, "blob_id": "f90e7753928a5c5c7f1c9b614cb78ae19021e0ff", "content_id": "e4a167492b1559a5583d0036a980045f9452f405", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2071, "license_type": "no_license", "max_line_length": 101, "num_lines": 59, "path": "/piratebartender.py", "repo_name": "lrsouthflorida/pirate_bartender", "src_encoding": "UTF-8", "text": "import random\n\nquestions = {\n \"sweet\": \"Do ye like your drinks sweet?\",\n \"sour\": \"Would ye like some sourness with yer poison?\",\n \"strong\": \"Are ye a buccaneer who likes a strong drink?\",\n \"salty\": \"Ahoy, Matey do ye like it with a salty tang?\",\n \"spicy\": \"Are ye a lubber who likes it spicy?\",\n}\n\n\ningredients = {\n \"sweet\": [\"sugar cube\", \"spoonful of honey\", \"splash of cola\"],\n \"sour\": [\"shake of grapefuit liquer\", \"splash of tonic\", \"lime juice\"],\n \"strong\": [\"glug of rum\", \"splash of absinthe\", \"splash of gin\"],\n \"salty\": [\"olive on a stick\", \"salt-dusted rim\", \"rasher of bacon\"],\n \"spicy\": [\"two jalapeno peppers\", \"slug of tequila\", \"splash of gin\"],\n}\n\ndef get_drink():\n value = False \n customer_preference = {}\n for option in questions:\n preference = input(questions[option]+ 'y = yes + n = no : ')\n if preference == 'y':\n value = True \n else:\n value = False\n \n customer_preference.update({option:value}) \n return customer_preference \n \ndef create_drinks(customer_preference):\n drinks = []\n for stuff in customer_preference:\n if customer_preference[stuff] == True:\n ingredient = random.choice(ingredients[stuff])\n drinks.append(ingredient)\n \n \n return drinks\n \n \nif __name__ == '__main__':\n choice = get_drink()\n print(choice)\n customer_drink = create_drinks(choice)\n print(customer_drink)\n \n cocktail_name =[\"Killer Mountain\", \"Wild Dog\", \"Spiced Snake\", \"Twisting Lotus\", \"Tornado Punch\"]\n print(random.choice(cocktail_name))\n \n while True: \n more_drinks = input(\"Do you want another drink? + 'y = yes + n = no : '\")\n if more_drinks == 'y':\n print(get_drink()) \n print(random.choice(cocktail_name))\n else:\n break\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" } ]
2
jamesfowkes/Snackspace
https://github.com/jamesfowkes/Snackspace
40993cfc26b23463939ebaa8fa37f666086be3c9
d93633aaf25039b9a548b073e69d8f23c94b71e3
871107e8ac9e7631057c9c9b02d3fd733e00fe2c
refs/heads/master
2018-12-30T10:56:48.786485
2013-10-24T20:49:04
2013-10-24T20:49:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5991400480270386, "alphanum_fraction": 0.6024569869041443, "avg_line_length": 37.761905670166016, "blob_id": "a119ecf2645ca75da0632fd897034dab267779fe", "content_id": "46f3dbc4a0966195e64461edd4eafad775f29909", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8140, "license_type": "no_license", "max_line_length": 126, "num_lines": 210, "path": "/Client/screens/productentry.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nproductentry.py\n\"\"\"\n\nfrom __future__ import division\n\nfrom screens.displayconstants import Colours, Screens\n\nfrom screens.screen import Screen\n\nfrom screens.productentry_gui import ProductEntryGUI\n\nfrom SimpleStateMachine import SimpleStateMachine\n\nfrom enum import Enum\n\nclass ProductEntry(Screen, ProductEntryGUI): #pylint: disable=R0902\n\n \"\"\" Implements the product entry screen\n pylint R0902 disabled as one 1 more attribute than recommened.\n Alternatives make code more complex than it needs to be for such a simple class\"\"\"\n \n def __init__(self, width, height, manager, owner):\n\n Screen.__init__(self, manager, owner, Screens.PRODUCTENTRY)\n ProductEntryGUI.__init__(self, width, height, self)\n\n self.states = Enum(\"BARCODE\", \"DESCRIPTION\", \"PRICE\", \"ADDING\", \"WARNING\")\n self.events = Enum(\"GUIEVENT\", \"SCAN\", \"BADSCAN\", \"KEYPRESS\", \"TIMEOUT\")\n\n self.barcode = \"\"\n self.price = 0\n self.description = \"\"\n \n self.sm = SimpleStateMachine(self.states.BARCODE, #pylint: disable=C0103\n [\n (self.states.BARCODE, self.events.GUIEVENT, self._on_gui_event),\n (self.states.BARCODE, self.events.SCAN, self._got_barcode),\n (self.states.BARCODE, self.events.BADSCAN, self._got_new_barcode),\n (self.states.BARCODE, self.events.KEYPRESS, lambda: self.states.BARCODE),\n\n (self.states.DESCRIPTION, self.events.GUIEVENT, self._on_gui_event),\n (self.states.DESCRIPTION, self.events.KEYPRESS, self._got_new_desc_char),\n (self.states.DESCRIPTION, self.events.SCAN, lambda: self.states.DESCRIPTION),\n (self.states.DESCRIPTION, self.events.BADSCAN, lambda: self.states.DESCRIPTION),\n\n (self.states.PRICE, self.events.GUIEVENT, self._on_gui_event),\n (self.states.PRICE, self.events.KEYPRESS, self._got_new_price_char),\n (self.states.PRICE, self.events.SCAN, lambda: self.states.DESCRIPTION),\n (self.states.PRICE, self.events.BADSCAN, lambda: self.states.DESCRIPTION),\n\n (self.states.ADDING, self.events.TIMEOUT, self._exit),\n (self.states.ADDING, self.events.GUIEVENT, lambda: self.states.ADDING),\n (self.states.ADDING, self.events.KEYPRESS, lambda: self.states.ADDING),\n (self.states.ADDING, self.events.SCAN, lambda: self.states.ADDING),\n (self.states.ADDING, self.events.BADSCAN, lambda: self.states.ADDING),\n \n (self.states.WARNING, self.events.TIMEOUT, lambda: self.states.BARCODE),\n (self.states.WARNING, self.events.GUIEVENT, lambda: self.states.WARNING),\n (self.states.WARNING, self.events.KEYPRESS, lambda: self.states.WARNING),\n (self.states.WARNING, self.events.SCAN, lambda: self.states.WARNING),\n (self.states.WARNING, self.events.BADSCAN, lambda: self.states.WARNING),\n ])\n\n def on_key_event(self, char):\n self.last_keypress = char\n self.sm.on_state_event(self.events.KEYPRESS)\n\n def on_gui_event(self, pos):\n self.last_gui_position = pos\n self.sm.on_state_event(self.events.GUIEVENT)\n\n def on_bad_scan(self, barcode):\n self.barcode = barcode\n self.sm.on_state_event(self.events.BADSCAN)\n\n def on_scan(self, __product):\n self.sm.on_state_event(self.events.SCAN)\n\n def _update_on_active(self):\n \"\"\" No need to change anything on active state \"\"\"\n pass\n \n def on_rfid(self):\n \"\"\" Do nothing on RFID scans \"\"\"\n pass\n \n def on_bad_rfid(self):\n \"\"\" Do nothing on RFID scans \"\"\"\n pass\n \n def _on_gui_event(self):\n\n \"\"\" Move focus and state to pressed object \"\"\" \n pos = self.last_gui_position\n button = self.get_object_id(pos)\n next_state = self.sm.state \n \n if button == self.buttons.BARCODE:\n self.barcode = \"\"\n self.set_active_entry(self.buttons.BARCODE)\n self._request_redraw()\n next_state = self.states.BARCODE\n\n if button == self.buttons.DESCRIPTION:\n self.description = \"\"\n self.set_active_entry(self.buttons.DESCRIPTION)\n self._request_redraw()\n next_state = self.states.DESCRIPTION\n\n if button == self.buttons.PRICE:\n self.price = 0\n self.set_active_entry(self.buttons.PRICE)\n self._request_redraw()\n next_state = self.states.PRICE\n\n if button == self.buttons.DONE:\n if self.data_ready():\n self.add_product()\n next_state = self.states.ADDING\n else:\n self.set_banner_with_timeout(\"One or more entries not valid!\", 4, Colours.WARN, self._banner_timeout)\n self._request_redraw()\n next_state = self.states.WARNING\n\n if button == self.buttons.CANCEL:\n self._exit()\n next_state = self.states.BARCODE\n\n #No GUI object hit:\n return next_state\n\n def _got_new_desc_char(self):\n \"\"\" Update the description field on keypress \"\"\"\n \n allow_desc_chars = \" !$%^&*(){}[]:@~;'#<>?,./\\\\\"\n \n if self.last_keypress.isalnum() or (self.last_keypress in allow_desc_chars):\n self.description += self.last_keypress\n elif self.last_keypress == \"\\b\":\n self.description = self.description[:-1]\n\n self.change_description(self.description)\n self._request_redraw()\n return self.states.DESCRIPTION\n\n def _got_new_price_char(self):\n \"\"\" Update the price field on keypress \"\"\"\n if self.last_keypress.isdigit():\n self.price *= 10\n self.price += int(self.last_keypress)\n elif self.last_keypress == \"\\b\":\n self.price = int(self.price / 10)\n\n self.change_price(self.price)\n self._request_redraw()\n return self.states.PRICE\n\n def data_ready(self):\n \"\"\" Determine if all data is set \"\"\"\n data_ready = len(self.barcode) > 0\n data_ready &= self.price > 0\n data_ready &= len(self.description) > 0\n return data_ready\n\n def add_product(self):\n \"\"\" Try to add the new product to the database \"\"\"\n self.owner.new_product(self.barcode, self.description, self.price, self._add_product_callback)\n \n def _add_product_callback(self, barcode, description, result):\n \"\"\" Callback from database when adding product \"\"\"\n if result:\n self.set_banner_with_timeout(\"New product %s added!\" % description, 3, Colours.INFO, self._banner_timeout)\n else:\n self.set_banner_with_timeout(\"New product %s was not added!\" % description, 3, Colours.WARN, self._banner_timeout)\n\n self._request_redraw()\n\n return self.states.ADDING\n \n def _got_new_barcode(self):\n \"\"\" On a new barcode scan, update the barcode field \"\"\"\n self.change_barcode(self.barcode)\n self._request_redraw()\n return self.states.BARCODE\n\n def _got_barcode(self):\n \"\"\" If the barcode scanned exists, warn the user \"\"\"\n self.set_banner_with_timeout(\"Barcode already exists!\", 4, Colours.WARN, self._banner_timeout)\n self._request_redraw()\n return self.states.WARNING\n\n def _banner_timeout(self):\n \"\"\" Callback from GUI indicating banner has timed out \"\"\"\n self.hide_banner()\n self._request_redraw()\n self.sm.on_state_event(self.events.TIMEOUT)\n\n def _request_redraw(self):\n \"\"\" Push a request for this screen to be drawn again \"\"\"\n self.screen_manager.req(Screens.PRODUCTENTRY)\n\n def _exit(self):\n \"\"\" Request a return to the intro screen \"\"\"\n self.reset_entry(self.buttons.BARCODE)\n self.reset_entry(self.buttons.PRICE)\n self.reset_entry(self.buttons.DESCRIPTION)\n \n self.screen_manager.req(Screens.INTROSCREEN)\n return self.states.BARCODE\n" }, { "alpha_fraction": 0.5831789970397949, "alphanum_fraction": 0.5857888460159302, "avg_line_length": 37.19292449951172, "blob_id": "e5781f38afe54b96156e79fa66991aa772ac6f6f", "content_id": "176f44b96933c50b152e27fe3a4211b8b9fb8956", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11878, "license_type": "no_license", "max_line_length": 131, "num_lines": 311, "path": "/Client/screens/mainscreen.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nmainscreen.py\n\"\"\"\n\nfrom __future__ import division\n\nimport logging\n\nfrom screenmanager import Screens\n\nfrom screens.displayconstants import Colours\n\nfrom screens.mainscreen_gui import MainScreenGUI\n\nfrom screens.screen import Screen\n\nfrom SimpleStateMachine import SimpleStateMachine\n\nfrom enum import Enum\n \nclass MainScreen(Screen, MainScreenGUI):\n\n \"\"\" Implements the main checkout screen \"\"\"\n \n def __init__(self, width, height, manager, owner):\n Screen.__init__(self, manager, owner, Screens.MAINSCREEN)\n MainScreenGUI.__init__(self, width, height, self)\n \n self.states = Enum(\"IDLE\", \"CHARGING\", \"PAYMENTMSG\", \"WARNING\")\n self.events = Enum(\"GUIEVENT\", \"SCAN\", \"BADSCAN\", \"RFID\", \"BADRFID\", \"CHARGED\", \"BANNERTIMEOUT\")\n \n self.sm = SimpleStateMachine(self.states.IDLE, #pylint: disable=C0103\n [\n [self.states.IDLE, self.events.GUIEVENT, self._on_idle_gui_event],\n [self.states.IDLE, self.events.SCAN, self._on_idle_scan_event],\n [self.states.IDLE, self.events.BADSCAN, self._on_idle_bad_scan_event],\n [self.states.IDLE, self.events.RFID, self._on_rfid_event],\n [self.states.IDLE, self.events.BADRFID, self._on_bad_rfid_event],\n\n [self.states.PAYMENTMSG, self.events.BANNERTIMEOUT, self._return_to_intro],\n [self.states.PAYMENTMSG, self.events.GUIEVENT, lambda: self.states.PAYMENTMSG],\n [self.states.PAYMENTMSG, self.events.SCAN, lambda: self.states.PAYMENTMSG],\n [self.states.PAYMENTMSG, self.events.BADSCAN, lambda: self.states.PAYMENTMSG],\n [self.states.PAYMENTMSG, self.events.RFID, lambda: self.states.PAYMENTMSG],\n [self.states.PAYMENTMSG, self.events.BADRFID, lambda: self.states.PAYMENTMSG],\n \n [self.states.CHARGING, self.events.CHARGED, lambda: self.states.PAYMENTMSG],\n [self.states.CHARGING, self.events.GUIEVENT, lambda: self.states.CHARGING],\n [self.states.CHARGING, self.events.SCAN, lambda: self.states.CHARGING],\n [self.states.CHARGING, self.events.BADSCAN, lambda: self.states.CHARGING],\n [self.states.CHARGING, self.events.RFID, lambda: self.states.CHARGING],\n [self.states.CHARGING, self.events.BADRFID, lambda: self.states.CHARGING],\n \n [self.states.WARNING, self.events.BANNERTIMEOUT, self._remove_warning],\n [self.states.WARNING, self.events.SCAN, self._on_idle_scan_event],\n [self.states.WARNING, self.events.BADSCAN, self._update_barcode_warning],\n [self.states.WARNING, self.events.RFID, self._on_rfid_event],\n [self.states.WARNING, self.events.BADRFID, self._on_bad_rfid_event],\n [self.states.WARNING, self.events.GUIEVENT, self._remove_warning],\n\n ])\n\n self.logger = logging.getLogger(\"MainScreen\")\n\n self.new_product = None\n self.badcode = \"\"\n \n \n def on_gui_event(self, pos):\n \"\"\" Called from owner to trigger a GUI press \"\"\"\n if self.active:\n self.last_gui_position = pos\n self.sm.on_state_event(self.events.GUIEVENT)\n \n def clear_all(self):\n pass\n \n def on_scan(self, product):\n \"\"\" Called from owner to trigger a known product scan \"\"\"\n self.new_product = product\n if self.active:\n self.sm.on_state_event(self.events.SCAN)\n\n def on_bad_scan(self, badcode):\n \"\"\" Called from owner to trigger an unknown product scan \"\"\"\n if self.active:\n self.badcode = badcode\n self.sm.on_state_event(self.events.BADSCAN)\n\n def on_key_event(self, key):\n \"\"\" Called from owner to trigger keyboard press \"\"\"\n pass\n\n def on_rfid(self):\n \"\"\" Called from owner to trigger a known RFID scan \"\"\"\n if self.active:\n self.sm.on_state_event(self.events.RFID)\n\n def on_bad_rfid(self):\n \"\"\" Called from owner to trigger an unknown RFID scan \"\"\"\n if self.active:\n self.sm.on_state_event(self.events.BADRFID)\n\n def user_allow_credit(self):\n \"\"\" Is the user allow to add credit to their account? \"\"\"\n try:\n return self.user.creditAllowed()\n except AttributeError:\n return False\n\n def user_added_credit(self):\n \"\"\" Has the user added credit to their account? \"\"\"\n return (self.user.Credit > 0)\n \n def total_price(self):\n \"\"\" Abstraction for total price \"\"\"\n return self.owner.total_price()\n \n def _update_on_active(self):\n \"\"\" When active state changes, this is called to update screen \"\"\"\n if self.user:\n self.set_user(self.user.name, self.user.balance, self.user.credit)\n else:\n self.set_unknown_user()\n\n for product in self.owner.products:\n self.on_scan(product)\n\n\n\n def _on_idle_gui_event(self):\n\n \"\"\" State machine function\n Runs when a GUI event has been triggered in idle\n \"\"\"\n pos = self.last_gui_position\n button = self.get_object_id(pos)\n\n # Default to staying in same state\n next_state = self.sm.state\n\n if button > -1:\n self.play_sound()\n\n if (button == self.ids.DONE):\n next_state = self._charge_user()\n\n if (button == self.ids.CANCEL):\n next_state = self._return_to_intro()\n\n if (button == self.ids.PAY):\n self.screen_manager.req(Screens.NUMERICENTRY)\n\n if (button == self.ids.DOWN):\n self.product_displays.move_down()\n self._request_redraw()\n\n if (button == self.ids.UP):\n self.product_displays.move_up()\n self._request_redraw()\n\n if (button == self.ids.REMOVE):\n\n product = self.product_displays.get_at_position(pos)\n self.logger.info(\"Removing product %s\" % product.barcode)\n\n if self.owner.remove_product(product) == 0:\n # No products of this type left in list\n self.product_displays.remove(product)\n\n self._request_redraw()\n\n return next_state\n\n def _on_idle_scan_event(self):\n \"\"\" State machine function\n Runs when a barcode scan has been triggered in idle\n \"\"\"\n self.logger.info(\"Got barcode %s\" % self.new_product.barcode)\n\n # Ensure that the warning banner goes away\n self.hide_banner()\n\n next_state = self.states.IDLE\n\n if self.user is not None:\n trans_allowed_state = self.user.transaction_allowed(self.new_product.price_in_pence)\n\n if trans_allowed_state == self.user.XACTION_ALLOWED:\n ## Add product, nothing else to do\n self.product_displays.add(self.new_product)\n elif trans_allowed_state == self.user.XACTION_OVERLIMIT:\n ## Add product, but also warn about being over credit limit\n self.product_displays.add(self.new_product)\n self.set_banner_with_timeout(\"Warning: you have reached your credit limit!\", 4, Colours.WARN, self._banner_timeout)\n next_state = self.states.WARNING\n elif trans_allowed_state == self.user.XACTION_DENIED:\n ## Do not add the product to screen. Request removal from product list and warn user\n self.set_banner_with_timeout(\"Sorry, you have reached your credit limit!\", 4, Colours.ERR, self._banner_timeout)\n self.owner.RemoveProduct(self.new_product)\n next_state = self.states.WARNING\n else:\n #Assume that the user is allowed to buy this\n self.product_displays.add(self.new_product)\n\n self._request_redraw()\n self.new_product = None\n\n return next_state\n\n def _on_idle_bad_scan_event(self):\n \"\"\" State machine function\n Runs when a bad barcode has been scanned in idle\n \"\"\"\n self.logger.info(\"Got unrecognised barcode %s\" % self.badcode)\n self.set_banner_with_timeout(\"Unknown barcode: '%s'\" % self.badcode, 4, Colours.ERR, self._banner_timeout)\n self._request_redraw()\n self.badcode = \"\"\n\n return self.states.WARNING\n\n def _on_rfid_event(self):\n \"\"\" State machine function\n Runs when a known RFID card has been scanned in idle\n \"\"\"\n self.logger.info(\"Got user %s\" % self.user.name)\n self.hide_banner()\n self.set_user(self.user.name, self.user.balance, self.user.credit)\n self._request_redraw()\n\n return self.sm.state\n\n def _on_bad_rfid_event(self):\n \"\"\" State machine function\n Runs when an unknown RFID card has been scanned in idle\n \"\"\"\n self.set_banner_with_timeout(\"Unknown RFID card!\", 4, Colours.ERR, self._banner_timeout)\n self._request_redraw()\n return self.states.WARNING\n\n def _banner_timeout(self):\n \"\"\" Callback from GUI indicating banner has timed out \"\"\"\n self.sm.on_state_event(self.events.BANNERTIMEOUT)\n\n def _update_barcode_warning(self):\n \"\"\" Show a warning about an unknown barcode \"\"\" \n self.logger.info(\"Got unrecognised barcode %s\" % self.badcode)\n self.set_banner_with_timeout(\"Unknown barcode: '%s'\" % self.badcode, 4, Colours.ERR, self._banner_timeout)\n self._request_redraw()\n return self.states.WARNING\n\n def _remove_warning(self):\n \"\"\" Get rid of any banner \"\"\"\n self.hide_banner()\n self._request_redraw()\n return self.states.IDLE\n\n def _return_to_intro(self):\n \"\"\" Request a return to the intro screen \"\"\"\n self.hide_banner()\n \n ## Forget everything about the user and products\n self.clear_products()\n self.set_unknown_user()\n self.owner.forget_user()\n self.owner.forget_products()\n \n self.screen_manager.req(Screens.INTROSCREEN)\n return self.states.IDLE\n\n def _charge_user(self):\n\n \"\"\"Request to charge the user and wait for reply \"\"\"\n self.set_banner_with_timeout(\"Charging...\", 0, Colours.INFO, None)\n \n self.owner.charge_all(self._charge_user_callback)\n self._request_redraw()\n return self.states.CHARGING\n \n def _charge_user_callback(self, total_price, credit, success):\n \n \"\"\" Show appropriate banner \"\"\"\n \n amountinpounds = total_price / 100\n creditinpounds = credit / 100\n banner_width = 0.6\n \n if success:\n text = u\"Thank you! You have been charged \\xA3%.2f\" % amountinpounds\n if creditinpounds > 0:\n text += u\" and credited \\xA3%.2f\" % creditinpounds\n banner_width = 0.8\n\n self.set_banner_with_timeout(text, 8, Colours.INFO, self._banner_timeout)\n self.set_banner_width_fraction(banner_width)\n else:\n self.set_banner_with_timeout(\"An error occurred and has been logged.\", 10, Colours.ERR, self._banner_timeout)\n self.logger.error(\"Failed to charge user %s %d pence\")\n\n self._request_redraw()\n\n self.sm.on_state_event(self.events.CHARGED)\n \n def _request_redraw(self):\n \"\"\" Push a request for this screen to be drawn again \"\"\"\n self.screen_manager.req(self.screen_id)\n \n @property\n def user(self):\n \"\"\" Easy access to the user \"\"\"\n return self.owner.user\n" }, { "alpha_fraction": 0.6198190450668335, "alphanum_fraction": 0.6231853365898132, "avg_line_length": 29.863636016845703, "blob_id": "5685e214d0759413edf9aba28cd21a350ef90e37", "content_id": "73effebf43a3e2e4c4061ff16d586fc5e1875594", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4753, "license_type": "no_license", "max_line_length": 95, "num_lines": 154, "path": "/Common/messaging.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "'''\nmessaging.py\n\nCreates or decodes XML for communicating between\nclient and server\n\nThe structure of the XML to be transferred is:\n<xml>\n <packet type=\"packettype\">\n <datatype>data</datatype>\n </packet>\n <packet type=\"packettype\">\n <datatype>data</datatype>\n </packet>\n ...\n</xml>\n\nWhere packettype is the context of the packet data(\"transaction\", \"getuser\", \"ping\" etc.)\nand datatype is the context of the individual data items enclosed, e.g <barcode>12345</barcode>\n\nThis file is responsible for pushing data to/from Python data structures and XML\nDOM objects.\n\n'''\n\nfrom xml.dom.minidom import parseString\nfrom xml.dom.minidom import getDOMImplementation\n\nfrom const import Const\n\n## Constants defining packet types\n\nPacketTypes = Const()\nPacketTypes.Ping = \"ping\"\nPacketTypes.PingReply = \"pingreply\"\nPacketTypes.GetRandomProduct = \"randomproduct\"\nPacketTypes.AddCredit = \"addcredit\"\nPacketTypes.AddProduct = \"addproduct\"\nPacketTypes.Transaction = \"transaction\"\nPacketTypes.GetUser = \"getuser\"\nPacketTypes.GetProduct = \"getproduct\"\nPacketTypes.ProductData = \"productdata\"\nPacketTypes.UserData = \"userdata\"\nPacketTypes.UnknownProduct = \"unknownproduct\"\nPacketTypes.UnknownUser = \"unknownuser\"\nPacketTypes.RandomProduct = \"randomproduct\"\nPacketTypes.Result = \"result\"\n\nclass InputException(Exception):\n \"\"\" To be raised when a packet could not be created due to bad input \"\"\"\n pass\n\nclass Packet:\n \"\"\" Implements a single command, data or request for passing \n between client and server\"\"\"\n def __init__(self, packettype, data_dict = None):\n self.type = packettype\n self.data = data_dict\n self.doc = None\n \n def add_to_dom(self, dom):\n\n \"\"\" Create a new packet DOM element at the root of the DOM\n with the specified packet type and return the packet DOM node \"\"\"\n \n packet_element = dom.createElement('packet')\n packet_element.setAttribute('type', self.type)\n\n try:\n for datatype, data in self.data.iteritems():\n\n ## Add these dictionary items to the DOM node.\n ## For example, a {'barcode':12345} dictionary entry\n ## becomes <barcode>12345</barcode>\n data_element = dom.createElement(datatype)\n text_node = dom.createTextNode(str(data))\n data_element.appendChild(text_node)\n packet_element.appendChild(data_element)\n except AttributeError:\n pass #data might be None - this is fine\n\n dom.childNodes[0].appendChild(packet_element)\n\n @classmethod\n def from_dom_packet_element(cls, ele):\n \"\"\" Creates Packet object from an XML packet \"\"\"\n packet_type = ele.attributes.getNamedItem(\"type\").value\n data_dict = {}\n\n for node in ele.childNodes:\n try:\n data_dict[node.localName] = node.firstChild.nodeValue\n except AttributeError:\n pass\n\n return cls(packet_type, data_dict)\n\nclass Message:\n \"\"\" Implements a collection of packets as an XML document \"\"\"\n def __init__(self, packet = None, debugme = False):\n self.debugme = debugme\n self.doc = None\n self.clear()\n self.packets = []\n\n if isinstance(packet, list):\n self.packets = packet\n elif isinstance(packet, Packet):\n self.packets = [packet]\n elif isinstance(packet, str):\n self.packets = [Packet(packet)]\n\n def add_packet(self, packet):\n \"\"\" Adds a new packet to the message \"\"\"\n self.packets.append(packet)\n\n def get_xml(self):\n \"\"\" Returns an XML representation of the message \"\"\"\n self.build_xml()\n return self.doc.toxml()\n\n def build_xml(self):\n \"\"\" Builds an XML representation of the message \"\"\"\n impl = getDOMImplementation()\n self.doc = impl.createDocument(None, \"xml\", None)\n\n ## Let each packet add itself to the DOM tree\n for packet in self.packets:\n packet.add_to_dom(self.doc)\n\n def clear(self):\n \"\"\" Delete all packets and associated XML \"\"\"\n self.packets = {}\n self.doc = None\n\n @staticmethod\n def parse_xml(xml):\n \"\"\" Parses an XML tree for packets and returns a list Packet objects \"\"\"\n packetlist = []\n\n if len(xml):\n try:\n dom = parseString(xml)\n packets = dom.getElementsByTagName('packet')\n\n for packet in packets:\n packetlist.append( Packet.from_dom_packet_element(packet) )\n\n except:\n raise\n else:\n raise InputException\n\n return packetlist\n" }, { "alpha_fraction": 0.5946031808853149, "alphanum_fraction": 0.6041269898414612, "avg_line_length": 32.51063919067383, "blob_id": "49bf3d6ea7b23c3532615fe58d59d22445c55161", "content_id": "61330614a02fa910f28f55bf9e2115c2f2a7f3ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3150, "license_type": "no_license", "max_line_length": 112, "num_lines": 94, "path": "/Client/screens/introscreen_gui.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nintroscreen_gui.py\n\"\"\"\n\nimport pygame #@UnresolvedImport\nimport inspect, os\n\nfrom screens.displayconstants import Colours\n\nfrom LCARSGui import LCARSImage, LCARSText, TextAlign\n\nfrom screens.border import Border\nfrom screens.screen_gui import ScreenGUI\n\nif pygame.image.get_extended() != 0:\n LOGO_PATH = \"/hackspace_logo.png\"\nelse:\n LOGO_PATH = \"/hackspace_logo.bmp\"\n\nclass IntroScreenGUI(ScreenGUI):\n\n \"\"\" Describes the graphical elements of the intro screen and\n provides methods for setting introduction text \"\"\"\n \n def __init__(self, width, height, owner):\n\n ScreenGUI.__init__(self, width, height, owner)\n\n self.border = Border(width, height)\n\n ##\n ## Fixed position objects\n ##\n self.path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory\n self.objects = {\n 'titleimage' : LCARSImage(pygame.Rect(width/2, height*3/5, 0, 0), self.path + LOGO_PATH, True),\n }\n\n ##\n ## Import standard objects\n\n self.objects.update(self.border.get_border())\n\n ##\n ## Position-dependant objects\n ##\n\n self.set_intro_text(\"Searching for remote database...\", Colours.FG)\n self.set_intro_text_2(\"Don't have a card? Seeing error messages?\", Colours.FG)\n self.set_intro_text_3(\"Pop money in the pot instead!\", Colours.FG)\n\n def set_intro_text(self, text, color):\n \"\"\" The intro text is positioned centrally between the sweep and image \"\"\"\n text_y_position = (self.border.inner_y() + self.objects['titleimage'].t()) / 2\n self.objects['introtext'] = LCARSText((self.width/2, text_y_position),\n text,\n 36,\n TextAlign.XALIGN_CENTRE, color, Colours.BG, True)\n\n def set_intro_text_2(self, text, color):\n \"\"\" The intro text is positioned between the image and the base \"\"\"\n text_y_position = (self.objects['titleimage'].b() + self.border.bottom()) / 2\n\ttext_y_position = text_y_position - 30\n self.objects['introtext2'] = LCARSText((self.width/2, text_y_position),\n text,\n 36,\n TextAlign.XALIGN_CENTRE, color, Colours.BG, True)\n\n def set_intro_text_3(self, text, color):\n \"\"\" The intro text is positioned between the image and the base \"\"\"\n text_y_position = self.objects['introtext2'].t() + 80\n self.objects['introtext3'] = LCARSText((self.width/2, text_y_position),\n text,\n 36,\n TextAlign.XALIGN_CENTRE, color, Colours.BG, True)\n\n def draw(self, window):\n \n \"\"\" Draw the screen objects on the supplied window \"\"\"\n \n window.fill(Colours.BG)\n\n for draw_obj in self.objects.values():\n draw_obj.draw(window)\n\n #Ensure text is drawn on top\n self.objects['introtext'].draw(window)\n self.objects['introtext2'].draw(window)\n self.objects['introtext3'].draw(window)\n \n if self.banner is not None:\n self.banner.draw(window)\n \n pygame.display.flip()\n" }, { "alpha_fraction": 0.58918297290802, "alphanum_fraction": 0.6029919385910034, "avg_line_length": 28, "blob_id": "06b528aef2b1c8915d9237f3d6ebcd1c150fea6d", "content_id": "6913c0a4b8c39083fe9754a3097134173f31b8a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 869, "license_type": "no_license", "max_line_length": 77, "num_lines": 30, "path": "/Common/const.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "'''\nconst.py\n\nSimple class for defining constants\n'''\n\nfrom copy import deepcopy\n\nclass ConstSetException(Exception):\n \"\"\" When attempting to set a constant, this is thrown \"\"\"\n def __init__(self, value): #pylint: disable=W0231\n self.value = value\n def __str__(self):\n repr(self.value)\n \nclass Const(object): #pylint: disable=R0902,R0903\n\n \"\"\" A small class for holding constants \"\"\"\n def __setattr__(self, name, value):\n if self.__dict__.has_key(name):\n raise ConstSetException(\"Attempt to set the value of a constant\")\n self.__dict__[name] = value\n\n def __getattr__(self, name, value):\n if self.__dict__.has_key(name):\n return deepcopy(self.__dict__[name])\n\n def __delattr__(self, item):\n if self.__dict__.has_key(item):\n print 'NOOOOO' # throw exception if needed" }, { "alpha_fraction": 0.5628235936164856, "alphanum_fraction": 0.5675029754638672, "avg_line_length": 34.86785888671875, "blob_id": "1e45a421f9237925dc5b120189abb95a2c441fb2", "content_id": "220f46102ee2b5506cc1bea5227c831acbbfb6d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10044, "license_type": "no_license", "max_line_length": 128, "num_lines": 280, "path": "/Client/dbclient.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\" dbclient.py\n\nImplements low-level functionality to communicate with \nthe database server\n\"\"\"\n \nimport socket\nimport logging\n\nfrom messaging import Message, Packet, PacketTypes, InputException\n\nfrom xml.dom.minidom import parseString\n\nimport threading\nimport Queue\n\nclass BadReplyException(Exception):\n \"\"\" Exception raised when a message to the server does not receive the expected reply \"\"\"\n pass\n\nclass TimeoutException(Exception):\n \"\"\" Exception raised when socket fails to receive response \"\"\"\n pass\n\nclass MessagingQueueItem: #pylint: disable=R0903\n \n \"\"\" An item to be placed on the send queue for the database \"\"\"\n \n def __init__(self, msg_type, message, queue):\n \"\"\" Init the message queue item \"\"\"\n self.type = msg_type\n self.message = message\n self.queue = queue\n \nclass DbClient(threading.Thread):\n\n \"\"\" Implementation of DbClient class \"\"\"\n def __init__(self, host_ip, task_handler, callback):\n\n \"\"\" Initialise the database client thread \"\"\"\n \n threading.Thread.__init__(self)\n \n self.server_host = str(host_ip)\n self.callbacks = []\n self.send_queue = Queue.Queue()\n \n self.sock = None\n \n self.found_server = False\n self.state_callback = callback\n self.test_port = 10000\n self.first_update = True\n \n self.stopReq = threading.Event()\n self.stopped = False\n \n self.server_address = ()\n \n logging.basicConfig(level=logging.DEBUG)\n self.logger = logging.getLogger(\"DBClient\")\n \n self.task_handler = task_handler\n self.test_connection_task = self.task_handler.add_function(self.test_connection, 2000, True)\n \n def run(self):\n \n self.reset_and_begin_search()\n \n while (not self.stopReq.isSet()):\n \n try:\n item = self.send_queue.get(False)\n self.process_item(item)\n \n except Queue.Empty:\n pass\n \n self.stopped = True\n \n def stop(self):\n self.stopReq.set()\n \n def process_item(self, item):\n \n if item.type == PacketTypes.Ping:\n reply, recvd = self.send(item.message, True)\n else:\n reply, recvd = self.send(item.message)\n \n if recvd > 0:\n try:\n packets = Message.parse_xml(reply)\n \n for packet in packets:\n \n if packet.type in (PacketTypes.UserData, PacketTypes.UnknownUser):\n item.queue.put(packet)\n elif packet.type == PacketTypes.PingReply:\n self.got_ping_reply(packet, recvd)\n elif packet.type in (PacketTypes.ProductData, PacketTypes.UnknownProduct):\n item.queue.put(packet)\n elif packet.type in (PacketTypes.RandomProduct):\n item.queue.put(packet)\n elif packet.type == PacketTypes.Result:\n if packet.data['action'] == PacketTypes.Transaction:\n item.queue.put(packet)\n if packet.data['action'] == PacketTypes.AddProduct:\n item.queue.put(packet)\n if packet.data['action'] == PacketTypes.AddCredit:\n item.queue.put(packet)\n\n except InputException:\n pass ## Let the ping task deal with finding the server has gone\n else:\n if (item.type == PacketTypes.Ping):\n self.got_ping_reply(None, 0)\n \n def test_connection(self):\n \"\"\" Periodic task to ping the server and check it's still there \"\"\"\n if self.found_server == False:\n # The server hasn't been found yet, so keep testing\n self.server_address = (self.server_host, self.test_port)\n self.ping_server()\n else:\n # There should still be a server there, so ping it\n self.ping_server()\n\n \n def reset_and_begin_search(self):\n \"\"\" Resets local server information and begins searching for it again \"\"\"\n self.found_server = False\n self.test_port = 10000\n self.test_connection_task.set_period(2000)\n self.test_connection_task.trigger_now()\n\n def get_product(self, barcode, queue):\n \"\"\" Get the product data associated with the barcode \"\"\"\n packet = Packet(PacketTypes.GetProduct, {\"barcode\":barcode})\n message = Message(packet).get_xml()\n \n self.send_queue.put( MessagingQueueItem(PacketTypes.GetProduct, message, queue))\n \n def get_user_data(self, rfid, queue):\n \"\"\" Get the user data associated with the rfid \"\"\"\n packet = Packet(PacketTypes.GetUser, {\"rfid\":rfid})\n message = Message(packet).get_xml()\n\n self.send_queue.put( MessagingQueueItem(PacketTypes.GetUser, message, queue) )\n\n \n def send_transactions(self, productdata, member_id, queue):\n \"\"\" Send transaction requests to the server \"\"\"\n self.logger.info(\"Sending transactions\")\n\n message = Message()\n\n for (barcode, count) in productdata:\n packet = Packet(PacketTypes.Transaction, {\"barcode\":barcode, \"memberid\":member_id, \"count\":count})\n message.add_packet(packet)\n\n self.send_queue.put( MessagingQueueItem(PacketTypes.Transaction, message.get_xml(), queue) )\n\n def add_product(self, barcode, description, price_in_pence, queue):\n \"\"\" Add a new product to the database \"\"\"\n packet = Packet(PacketTypes.AddProduct, {\"barcode\":barcode, \"description\":description, \"price_in_pence\":price_in_pence})\n message = Message(packet).get_xml()\n\n self.send_queue.put( MessagingQueueItem(PacketTypes.AddProduct, message, queue))\n \n def add_credit(self, member_id, amountinpence, queue):\n \"\"\" Add credit to a user account \"\"\"\n packet = Packet(PacketTypes.AddCredit, {\"memberid\":member_id, \"amountinpence\":amountinpence})\n message = Message(packet).get_xml()\n\n self.send_queue.put( MessagingQueueItem(PacketTypes.AddCredit, message, queue))\n \n def get_random_product(self, queue):\n \"\"\" Pull the data for a random product - useful for testing \"\"\"\n packet = Packet(PacketTypes.RandomProduct, {})\n message = Message(packet).get_xml()\n \n self.send_queue.put( MessagingQueueItem(PacketTypes.GetRandomProduct, message, queue))\n \n def ping_server(self):\n \"\"\" Ping the server to test it's still there \"\"\" \n self.logger.info(\"Testing connection on %s port %d\" % self.server_address)\n \n message = Message(PacketTypes.Ping).get_xml()\n \n self.send_queue.put( MessagingQueueItem(PacketTypes.Ping, message, None ))\n \n def got_ping_reply(self, reply, received):\n \n old_connection_state = self.found_server\n \n if received > 0:\n if reply.type == PacketTypes.PingReply:\n self.logger.info(\"Connected to remote server\")\n self.found_server = True\n else:\n self.logger.info(\"Unexpected reply from remote server\")\n self.found_server = False\n else:\n self.logger.info(\"No reply to ping received!\")\n self.found_server = False\n \n if not old_connection_state:\n if not self.found_server:\n #Keep looking for the server\n self.test_port = (self.test_port + 1) if (self.test_port < 10010) else 10000\n else:\n #Found the server, reduce ping rate\n self.test_connection_task.set_period(10000)\n else:\n if not self.found_server:\n # Lost the current server, so start search again\n self.reset_and_begin_search()\n \n self.state_callback(old_connection_state, self.found_server, self.first_update)\n self.first_update = False\n \n def send(self, message, force = False):\n \"\"\" Sends message on current socket and waits for response \"\"\"\n received = 0\n data = ''\n\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n self.test_connection_task.active = False\n \n if self.found_server or force:\n try:\n self.sock.connect(self.server_address)\n \n self.logger.info(\"Sending %s\" % message)\n \n length = len(message)\n message = \"%5s%s\" % (length, message)\n \n self.sock.settimeout(5)\n self.sock.sendall(message)\n try:\n length = int(self.sock.recv(5))\n data = self.sock.recv(length)\n except ValueError:\n pass\n \n received = len(data)\n \n except socket.timeout:\n received = 0\n data = ''\n except socket.error as err:\n self.logger.info(\"Socket open failed with '%s'\" % err.strerror)\n received = 0\n data = ''\n \n finally:\n self.sock.close()\n self.test_connection_task.active = True\n\n return data, received\n\n def timeout_handler(self, __signum, __frame):\n \"\"\" If no response is received before timeout, this is called \"\"\"\n self.found_server = False\n raise TimeoutException\n\ndef parse_reply(message):\n \"\"\" Convert byte-level message into XML \"\"\"\n dom = parseString(message)\n\n packets = dom.getElementsByTagName('packet')\n\n for packet in packets:\n packettype = packet.attributes.getNamedItem(\"type\").value\n\n if packettype == PacketTypes.Ping:\n return Message(PacketTypes.PingReply)\n\n" }, { "alpha_fraction": 0.5695876479148865, "alphanum_fraction": 0.5824742317199707, "avg_line_length": 19.473684310913086, "blob_id": "c496d3c74bdfc80aa4d0c91222c486baf8765194", "content_id": "8cb6bbd71f037b0d0658aff7c504dca776860c5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 388, "license_type": "no_license", "max_line_length": 57, "num_lines": 19, "path": "/Client/dbtester.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "from dbclient import DbClient\nfrom task import TaskHandler\nfrom time import sleep\n\nclass DBTester:\n\n def __init__(self):\n self.task_handler = TaskHandler(self)\n \n self.dbaccess = DbClient(True, self.task_handler)\n \n def start(self):\n while (1):\n sleep(0.001)\n self.task_handler.tick()\n \ndb = DBTester()\n\ndb.start()" }, { "alpha_fraction": 0.5922127366065979, "alphanum_fraction": 0.5976012349128723, "avg_line_length": 30.91666603088379, "blob_id": "52e2624a75fcd351d1b48cdac43fcd3753aff866", "content_id": "6fb3dff2f26c87702f0413326018ef15be1704a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5753, "license_type": "no_license", "max_line_length": 118, "num_lines": 180, "path": "/Client/screens/productdisplay.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "'''\nproductdisplay.py\n\nClasses to handle display of products on snackspace main screen\n'''\n\nfrom __future__ import division\n\nfrom const import Const\n\nfrom screens.displayconstants import Colours\n\nfrom LCARSGui import LCARSCappedBar, CapLocation\n\nclass ProductDisplay():\n\n \"\"\"\n Class representing the display objects for a single product entry\n \"\"\"\n \n def __init__(self, product):\n\n self.product = product\n\n self.formats = Const()\n self.formats.desc_pence = \"%s (%dp)\"\n self.formats.desc_pounds = u\"%s (\\xA3%.2f)\"\n\n self.formats.price_pence = \"%dp\"\n self.formats.price_pounds = \"\\xA3%.2f\"\n\n self.lcars_objects = [None] * 3\n\n self.description = ''\n self.price_string = ''\n \n self.visible = True\n \n def set_visible(self, visible):\n \"\"\" Sets the visible state of the product display \"\"\" \n self.visible = visible\n \n def collide_on_remove(self, pos):\n \"\"\" Remove the product entry at the given position \"\"\"\n collide = False\n\n if self.visible:\n try:\n collide = self.lcars_objects[2].collidePoint(pos)\n except AttributeError:\n # Off-screen products might not have GUI objects.\n # This is OK.\n pass\n\n return collide\n\n def update_strings(self):\n \"\"\" Sets internal strings from the associated snackspace product \"\"\"\n description = self.product.description\n priceinpence = self.product.price_in_pence\n totalprice = self.product.total_price\n\n self.description = self.format_desciption(description, priceinpence)\n self.price_string = self.format_price(totalprice)\n\n def format_desciption(self, description, priceinpence):\n \"\"\" Returns a formatted description string \"\"\"\n if (priceinpence < 100):\n description = self.formats.desc_pence % (description, priceinpence)\n else:\n description = self.formats.desc_pounds % (description, int(priceinpence) / 100)\n\n return description\n\n def format_price(self, price_in_pence):\n \"\"\" Returns a formatted price string \"\"\"\n if (price_in_pence < 100):\n price_string = self.formats.price_pence % price_in_pence\n else:\n price_string = self.formats.price_pounds % (int(price_in_pence) / 100)\n\n return price_string\n\n def draw(self, layout, index, remove_width, window):\n\n \"\"\"\n Draws the three product LCARS objects with the requested layout, y position and remove button width\n \"\"\"\n \n self.update_strings()\n\n # Redraw description bar\n self.lcars_objects[0] = LCARSCappedBar(\n layout.get_description_rect(index),\n CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, self.description, Colours.FG, Colours.BG, self.visible)\n\n self.lcars_objects[0].draw(window)\n\n # Redraw total price bar\n self.lcars_objects[1] = LCARSCappedBar(\n layout.get_price_rect(index), \n CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, self.price_string, Colours.FG, Colours.BG, self.visible)\n\n self.lcars_objects[1].draw(window)\n\n # Redraw remove button\n self.lcars_objects[2] = LCARSCappedBar(\n layout.get_remove_rect(index, remove_width),\n CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Remove\", Colours.FG, Colours.BG, self.visible)\n\n self.lcars_objects[2].draw(window)\n\nclass ProductDisplayCollection():\n \n \"\"\"\n A collection of product display objects\n \"\"\"\n \n def __init__(self, display_limit):\n \n # Array of ProductDisplays\n self.product_displays = []\n self.top_index = 0\n self.display_limit = display_limit\n \n def __iter__(self):\n return iter(self.product_displays)\n \n def __len__(self):\n return len(self.product_displays)\n \n def __getitem__(self, key):\n return self.product_displays[key]\n \n def __delitem__(self, key):\n self.remove(key)\n \n def __setitem__(self, key):\n pass\n \n def add(self, product):\n \"\"\" Add a new product to the list \"\"\"\n if product not in [displayproduct.product for displayproduct in self.product_displays]:\n self.product_displays.append(ProductDisplay(product))\n \n def get_at_position(self, pos):\n \"\"\" Get the product at a specific location \"\"\"\n product = next((product.product for product in self.product_displays if product.collide_on_remove(pos)), None)\n return product\n\n def remove(self, product_to_remove):\n \"\"\" Delete a product entry from the list \"\"\"\n self.product_displays = [product for product in self.product_displays if product_to_remove != product.product]\n\n if self.top_index > 0:\n self.top_index -= 1\n \n def move_up(self):\n \"\"\" Shift the displayed products list up \"\"\"\n if self.top_index > 0:\n self.top_index -= 1\n\n def move_down(self):\n \"\"\" Shift the displayed products list down \"\"\"\n if (self.top_index + self.display_limit) < len(self.product_displays):\n self.top_index += 1\n \n def collide_on_remove(self, pos):\n \"\"\" Return the product if its remove button was pressed \"\"\"\n found_product = None\n for product in self.product_displays:\n if product.collide_on_remove(pos):\n found_product = product\n \n return found_product\n \n def clear(self):\n \"\"\" Reset the products list to nothing \"\"\"\n self.product_displays = []\n self.top_index = 0\n " }, { "alpha_fraction": 0.6105702519416809, "alphanum_fraction": 0.6110338568687439, "avg_line_length": 32.20000076293945, "blob_id": "cfdc5c14013630e610a586b320bf708cda421dd0", "content_id": "602202fdfd03760e173b0f4593127a50fce4d43b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2157, "license_type": "no_license", "max_line_length": 115, "num_lines": 65, "path": "/Client/screens/introscreen.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\" \nintroscreen.py\nThe first screen to be displayed when snackspace starts.\n\"\"\"\n\nfrom .displayconstants import Colours, Screens\n\nfrom .screen import Screen\nfrom .introscreen_gui import IntroScreenGUI\n\nclass IntroScreen(Screen, IntroScreenGUI):\n \"\"\" Implementation of introduction screen \"\"\"\n def __init__(self, width, height, manager, owner):\n \n Screen.__init__(self, manager, owner, Screens.INTROSCREEN)\n IntroScreenGUI.__init__(self, width, height, self)\n\n def _update_on_active(self):\n pass\n\n def on_rfid(self):\n \"\"\" Handle RFID swipe: just request a switch to main screen \"\"\"\n if self.active:\n self.screen_manager.req(Screens.MAINSCREEN)\n \n def on_bad_rfid(self):\n \"\"\" Do nothing on touchscreen press \"\"\" \n pass\n \n def on_gui_event(self, pos):\n \"\"\" Do nothing on touchscreen press \"\"\" \n pass\n\n def on_key_event(self, key):\n \"\"\" Do nothing on keyboard press \"\"\"\n pass\n\n def on_scan(self, __product):\n \"\"\" Handle barcode scan: just request a switch to main screen \"\"\"\n if self.active:\n self.screen_manager.req(Screens.MAINSCREEN)\n\n def on_bad_scan(self, __barcode):\n \"\"\" Handle invalid barcode scan: show a banner \"\"\"\n if self.active:\n self.set_banner_with_timeout(\"Unknown barcode: '%s'\" % __barcode, 4, Colours.ERR, self._banner_timeout)\n self._request_redraw()\n\n def set_db_state(self, db_connected):\n \"\"\" Handle change of database state: update GUI to reflect \"\"\"\n if not db_connected:\n self.set_intro_text(\"ERROR: Cannot access Snackspace remote database\", Colours.ERR)\n else:\n self.set_intro_text(\"Scan an item or swipe your card to start\", Colours.FG)\n \n self._request_redraw()\n \n def _banner_timeout(self):\n \"\"\" Callback from GUI indicating banner has timed out \"\"\"\n self.hide_banner()\n self._request_redraw()\n \n def _request_redraw(self):\n \"\"\" Push a request for this screen to be drawn again \"\"\"\n self.screen_manager.req(self.screen_id)" }, { "alpha_fraction": 0.5761570930480957, "alphanum_fraction": 0.5845722556114197, "avg_line_length": 28.221311569213867, "blob_id": "a4fa22c387967f5220c11034999d1e470e20a96f", "content_id": "f6a299b3adddc702cee7ff92910638c64248b104", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3565, "license_type": "no_license", "max_line_length": 88, "num_lines": 122, "path": "/Server/server.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nserver.py\n\nServer-side TCP comms layer\n\n\"\"\"\n\nimport socket\n\nimport argparse #@UnresolvedImport\n\nimport ConfigParser\n\nimport logging\n\nfrom dbserver import DbServer\nfrom messaging import Message\n\nclass Server:\n \"\"\" Implementation of the Server \"\"\"\n \n def __init__(self, database):\n\n logging.basicConfig(level=logging.DEBUG)\n self.logger = logging.getLogger(\"SSServer\")\n\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.dbase = database\n\n \n server_port = 10000\n\n started = False\n\n while (not started) and (server_port < 11000):\n server_address = ('', server_port)\n try:\n self.logger.info('Trying server start on %s port %s' % server_address)\n self.sock.bind(server_address)\n started = True\n except socket.error:\n server_port = server_port + 1\n\n if started:\n self.server_loop()\n else:\n self.logger.error(\"Could not start server on any port on %s!\" % server_host)\n\n def server_loop(self):\n\n \"\"\" Server loops here listening for connections \"\"\"\n \n self.sock.listen(1)\n\n #Wait for connection from client\n while(True):\n\n self.logger.info(\"Waiting for client to connect...\")\n\n connection, client_address = self.sock.accept()\n data = \"\"\n\n self.logger.info(\"Waiting for client at %s port %s\" % client_address)\n try:\n ## The recv and sendall methods are dynamically bound\n ## to the socket object, so pylint complains about them\n ## not existing. E1101 is disabled for these lines\n length = int(connection.recv(5)) #pylint: disable=E1101\n self.logger.info(\"Receiving %d bytes\" % length)\n data = connection.recv(length) #pylint: disable=E1101\n returndata = self.handle_message(data)\n if (returndata is not None):\n\n self.logger.info(\"Sending %s\" % returndata)\n\n length = len(returndata)\n returndata = \"%5s%s\" % (length, returndata)\n\n connection.sendall(returndata) #pylint: disable=E1101\n finally:\n connection.close()\n\n def handle_message(self, message):\n \"\"\" Pass message to database layer and get reply \"\"\" \n packets = Message.parse_xml(message)\n\n reply = self.dbase.process_packets(packets)\n\n return reply\n\ndef main(_argv = None):\n \n \"\"\" The entry point for the snackspace server \"\"\"\n \n ## Read arguments from command line\n argparser = argparse.ArgumentParser(description='Snackspace Server')\n argparser.add_argument('--file', dest='conffile', nargs='?', default='')\n argparser.add_argument('-L', dest='local_db', nargs='?', default='n', const='y')\n\n args = argparser.parse_args()\n\n ## Read arguments from configuration file\n try:\n confparser = ConfigParser.ConfigParser()\n confparser.readfp(open(args.conffile))\n except IOError:\n ## Configuration file does not exist, or no filename supplied\n confparser = None\n \n if confparser is None:\n ## Use command line options\n local_db = args.local_db == 'y'\n else:\n ## Use configuration file options:\n local_db = confparser.get('ServerConfig','local_db') == 'y'\n\n database = DbServer(local_db)\n __server = Server(database)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6149122714996338, "alphanum_fraction": 0.7245613932609558, "avg_line_length": 34.625, "blob_id": "2a71f917f1fbbf46de815ebe05cacfa2a352e5fa", "content_id": "1d128362c94176c9f87da05a885e982f83de1903", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 124, "num_lines": 32, "path": "/Client/screens/displayconstants.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\ndisplay_constants.py\n\nConstant values for layout, color, etc.\n\npylint message C0103 disabled due to requiring UPPERCASE identifiers for constants\nand Proper Case for classes/collections\n\"\"\"\n\nfrom enum import Enum\nfrom const import Const\n\n# Available snackspace screens\nScreens = Enum(\"BLANKSCREEN\", \"INTROSCREEN\", \"MAINSCREEN\", \"NUMERICENTRY\", \"PRODUCTENTRY\", \"WAITING\") #pylint: disable=C0103\n\n# Global widths for LCARS style interface\nWidths = Const() #pylint: disable=C0103\nWidths.BORDER = 20 #pylint: disable=W0201,C0103\nWidths.LARGE_BAR = 60 #pylint: disable=W0201,C0103\nWidths.SMALL_BAR = 30 #pylint: disable=W0201,C0103\n\n# Global colour pallette\nColours = Const() #pylint: disable=C0103\nColours.BG = ( 0, 0, 0) #pylint: disable=W0201,C0103\nColours.FG = ( 40, 89, 45) #pylint: disable=W0201,C0103\nColours.WARN = (255, 255, 0) #pylint: disable=W0201,C0103\nColours.ERR = (255, 0, 0) #pylint: disable=W0201,C0103\nColours.INFO = ( 0, 255, 0) #pylint: disable=W0201,C0103\nColours.ENTRY = ( 0, 128, 0) #pylint: disable=W0201,C0103\n\n# Name of sound file for touchscreen press \nSOUNDFILE = \"press_sound.ogg\"\n" }, { "alpha_fraction": 0.5972978472709656, "alphanum_fraction": 0.6009635329246521, "avg_line_length": 34.2975959777832, "blob_id": "d4c3bd7b74be1c798cf5697857c010a51561273e", "content_id": "fbb46450cdb91e9752aa9a50eea863df96512569", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19096, "license_type": "no_license", "max_line_length": 141, "num_lines": 541, "path": "/Client/snackspace.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nsnackspace\n\nA \"self-checkout\" application for Nottingham Hackspace\n\nIntended to run on a raspberry pi with USB barcode scanner and serial RFID reader\n\nCommunicates with server-side snackspace application via XML packets over TCP socket\n\"\"\"\n\nimport sys\nimport os\nimport pygame # @UnresolvedImport\n\nimport argparse # @UnresolvedImport\n\nimport ConfigParser\n\nimport logging\n\nimport time\n\nimport Queue\n\nfrom rfid import RFIDReader\n\nfrom screenmanager import Screens\n\nfrom product import Product\nfrom user import User\n\nfrom dbclient import DbClient\n\nfrom screenmanager import ScreenManager\n\nfrom task import TaskHandler\n\nfrom collections import namedtuple\n\nfrom messaging import PacketTypes\n\nSnackspaceOptions = namedtuple(\"SnackspaceOptions\", \"hostip rfid_port limit_action credit_action, start_fullscreen\") # pylint: disable=C0103\n\nclass ChargeAllHandler:\n \n \"\"\" Handles the \"charge all\" functionality, where:\n 1. The user is charged for products purchased and the database\n transactions tables is updated\n 2. The user is credited with any extra monies added\n \n As these are handled as two seperate DB transactions, a distinct class\n makes handling easier\n \"\"\"\n \n def __init__(self, db, user, products, callback, queue):\n \n self.callback = callback\n self.transaction_total = 0\n self.user = user\n self.dbaccess = db\n self.reply_queue = queue\n self.transaction_count = len(products)\n self.transaction_replies = 0\n \n if user is not None:\n if self.transaction_count:\n products = [(product.barcode, product.count) for product in products]\n self.dbaccess.send_transactions(products, self.user.member_id, self.reply_queue)\n elif (self.user.credit > 0):\n ## No transactions, but need to credit the user's account\n self.dbaccess.add_credit(self.user.member_id, self.user.credit, self.reply_queue)\n else:\n callback(0, 0, False)\n else:\n callback(0, 0, False)\n \n\n def on_db_send_transactions_callback(self, packet):\n \n member_id = packet.data['memberid']\n success = (packet.data['result'] == \"Success\") and (member_id == self.user.member_id)\n \n self.transaction_replies = self.transaction_replies + 1\n \n if success:\n\n self.transaction_total = self.transaction_total + int(packet.data['total'])\n \n if (self.transaction_count == self.transaction_replies):\n ## All transactions processed\n if (self.user.credit > 0):\n ## Also need to credit the user's account\n self.dbaccess.add_credit(self.user.member_id, self.user.credit, self.reply_queue)\n else:\n self.callback(self.transaction_total, 0, success)\n else:\n self.callback(0, 0, False) #Something went wrong\n \n \n def on_db_add_credit_callback(self, packet):\n \n member_id = packet.data['memberid']\n success = (packet.data['result'] == \"Success\") and (member_id == self.user.member_id)\n \n if success:\n self.callback(self.transaction_total, int(packet.data['credit']), success)\n else:\n self.callback(self.transaction_total, 0, success)\n\nclass InputHandler: # pylint: disable=R0903\n \"\"\" Implements functionality for managing keyboard input \"\"\"\n \n NEW_SCANNED_INPUT = 0\n PRODUCT_ENTRY = 1\n FAKE_RFID = 2\n FAKE_GOOD_PRODUCT = 3\n FAKE_BAD_PRODUCT = 4\n FULLSCREEN_TOGGLE = 5\n CURSOR_TOGGLE = 6\n QUIT = 7\n \n def __init__(self):\n \"\"\" Initialise the class \"\"\"\n self.scanned_input = ''\n \n # # Only numeric keys are valid\n self.valid_scan_keys = [\n pygame.K_0, pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4,\n pygame.K_5, pygame.K_6, pygame.K_7, pygame.K_8, pygame.K_9\n ]\n \n def new_event(self, event):\n \"\"\" For each key event, translate into appropriate snackspace event \"\"\" \n key = event.dict['unicode']\n result = None\n \n if (event.key in self.valid_scan_keys):\n # Add new keypress to buffer\n self.scanned_input += key\n \n elif (event.key == pygame.K_RETURN):\n result = self.NEW_SCANNED_INPUT\n \n elif (event.key == pygame.K_a) and (pygame.key.get_mods() & pygame.KMOD_CTRL):\n result = self.PRODUCT_ENTRY\n \n elif (event.key == pygame.K_u) and (pygame.key.get_mods() & pygame.KMOD_CTRL):\n result = self.FAKE_RFID\n \n elif (event.key == pygame.K_p) and (pygame.key.get_mods() & pygame.KMOD_CTRL):\n result = self.FAKE_GOOD_PRODUCT\n \n elif (event.key == pygame.K_f) and (pygame.key.get_mods() & pygame.KMOD_CTRL):\n result = self.FAKE_BAD_PRODUCT\n \n elif (event.key == pygame.K_s) and (pygame.key.get_mods() & pygame.KMOD_CTRL):\n result = self.FULLSCREEN_TOGGLE\n \n elif (event.key == pygame.K_m) and (pygame.key.get_mods() & pygame.KMOD_CTRL):\n result = self.CURSOR_TOGGLE\n \n elif (event.key == pygame.K_c) and (pygame.key.get_mods() & pygame.KMOD_CTRL):\n result = self.QUIT\n \n return result\n\nclass Snackspace: # pylint: disable=R0902\n \"\"\" Implements the main snackspace class. Responsible for:\n DB and screen managers\n RFID and barcode scanners\n UI interaction via pygame\n pylint R0902 disabled: too many instance attributes\n \"\"\"\n def __init__(self, window, size, options):\n\n \"\"\" Initialise and start the snackspace application \"\"\"\n \n self.inittime = int(time.time())\n\n self.options = options\n\n self.input_handler = InputHandler()\n \n self.task_handler = TaskHandler(self)\n self.task_handler.add_function(self.rfid_task, 500, True)\n \n self.logger = logging.getLogger(\"snackspace\")\n\n self.rfid = RFIDReader(self.options.rfid_port)\n \n self.is_fullscreen = True\n self.cursor_visible = False\n \n self.window_size = size\n self.screen_manager = ScreenManager(self, window, size)\n\n self.user = None\n self.products = []\n\n self.reply_queue = Queue.Queue()\n \n self.dbaccess = DbClient(self.options.hostip, self.task_handler, self.db_state_callback)\n self.dbaccess.daemon = True\n self.dbaccess.start()\n \n def start(self):\n \"\"\" The main snackspace event loop \"\"\"\n ticks = 0\n\n while (1):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.quit()\n if event.type == pygame.MOUSEBUTTONUP:\n self.logger.debug(\"GUI Event\")\n self.screen_manager.current.on_gui_event(event.pos)\n\n if event.type == pygame.KEYDOWN:\n self.keypress(event)\n\n try:\n packet = self.reply_queue.get(False)\n self.handle_new_packet(packet)\n \n except Queue.Empty:\n pass\n \n if (pygame.time.get_ticks() - ticks) > 0:\n\n ticks = pygame.time.get_ticks()\n\n self.task_handler.tick()\n \n def quit(self):\n \n #Request the DB client thread stop and wait for it to stop\n self.dbaccess.stop()\n while self.dbaccess.is_alive():\n pass\n sys.exit()\n \n def set_fullscreen(self, fullscreen):\n \n screen = pygame.display.get_surface()\n tmp = screen.convert()\n caption = pygame.display.get_caption() \n \n flags = screen.get_flags()\n \n if fullscreen:\n flags = flags | pygame.FULLSCREEN\n else:\n flags = flags & ~pygame.FULLSCREEN\n \n bits = screen.get_bitsize()\n \n #pygame.display.quit()\n #pygame.display.init()\n \n screen = pygame.display.set_mode(self.window_size, flags, bits)\n screen.blit(tmp,(0,0))\n pygame.display.set_caption(*caption)\n \n self.is_fullscreen = fullscreen\n \n def handle_new_packet(self, packet):\n if packet.type == PacketTypes.ProductData:\n self.on_db_got_product_data(packet)\n elif packet.type == PacketTypes.UnknownProduct:\n self.on_db_got_unknown_product(packet)\n elif packet.type == PacketTypes.UserData:\n self.on_db_got_user_data(packet)\n elif packet.type == PacketTypes.RandomProduct:\n self.on_db_random_product_callback(packet)\n elif packet.type == PacketTypes.Result:\n if packet.data['action'] == PacketTypes.Transaction:\n self.charge_all_handler.on_db_send_transactions_callback(packet)\n elif packet.data['action'] == PacketTypes.AddCredit:\n self.charge_all_handler.on_db_add_credit_callback(packet)\n elif packet.data['action'] == PacketTypes.AddProduct:\n self.on_db_add_product_callback(packet)\n\n \n def keypress(self, event):\n \"\"\" Handle a keyboard press or barcode scan character \"\"\" \n # Push keypress to the current screen\n self.screen_manager.current.on_key_event(event.dict['unicode'])\n \n # Then do our own handling via the input handler\n result = self.input_handler.new_event(event)\n \n if result == InputHandler.FAKE_BAD_PRODUCT:\n # # Fake a bad product scan\n self.on_scan_event('BADBARCODE')\n \n elif result == InputHandler.FAKE_GOOD_PRODUCT:\n # # Fake a good product scan\n self.dbaccess.get_random_product(self.reply_queue)\n \n elif result == InputHandler.FAKE_RFID:\n # # Fake an RFID swipe\n self.rfid.set_fake_rfid()\n \n elif result == InputHandler.NEW_SCANNED_INPUT:\n # # Buffer is complete, process it\n scanned_input = self.input_handler.scanned_input\n self.input_handler.scanned_input = ''\n self.logger.debug(\"Got raw input '%s'\" % scanned_input)\n self.on_scan_event(scanned_input)\n \n elif result == InputHandler.PRODUCT_ENTRY:\n # # Go to product entry screen\n self.screen_manager.req(Screens.PRODUCTENTRY)\n \n elif result == InputHandler.FULLSCREEN_TOGGLE:\n self.set_fullscreen(not self.is_fullscreen)\n self.screen_manager.req(self.screen_manager.currentscreen, True)\n \n elif result == InputHandler.CURSOR_TOGGLE:\n self.cursor_visible = not self.cursor_visible\n pygame.mouse.set_visible(self.cursor_visible)\n \n elif result == InputHandler.QUIT:\n self.quit()\n\n def rfid_task(self):\n \"\"\" To be run periodically to check for an RFID swipe \"\"\"\n rfid = self.rfid.poll()\n \n if rfid is not None:\n self.on_swipe_event(self.rfid.mangle_rfid(rfid))\n\n def db_state_callback(self, old_state, new_state, first_update):\n \"\"\" Callback when database state changes \"\"\"\n \n if old_state != new_state or first_update:\n self.screen_manager.get(Screens.INTROSCREEN).set_db_state(new_state)\n if not new_state:\n self.screen_manager.get(Screens.MAINSCREEN).clear_all()\n self.forget_products()\n self.forget_user()\n \n def on_swipe_event(self, cardnumber):\n \"\"\" When an RFID swipe is made, gets user from the database \"\"\"\n if not self.dbaccess.found_server:\n return\n else:\n self.dbaccess.get_user_data(cardnumber, self.reply_queue)\n\n def on_scan_event(self, barcode):\n \"\"\" When a barcode scan is made, pulls product from the database \"\"\" \n if not self.dbaccess.found_server or len(barcode) == 0:\n return\n\n self.add_product_to_basket(barcode)\n\n def charge_all(self, callback):\n \"\"\" Charge the current user for the current set of products \"\"\"\n self.charge_all_handler = ChargeAllHandler(self.dbaccess, self.user, self.products, callback, self.reply_queue)\n \n def credit_user(self, amount):\n \"\"\" Adds credit to a user's account \"\"\"\n self.user.add_credit(amount)\n\n def forget_user(self):\n \"\"\" Clear the user \"\"\"\n self.user = None\n\n def total_price(self):\n \"\"\" Get the total price of the basket \"\"\"\n return sum([product.total_price for product in self.products])\n\n def remove_product(self, product_to_remove):\n \"\"\" Remove a product from the basket \"\"\"\n \n # First reduce the count of this product.\n # If zero, the product itself can be removed from the list\n if product_to_remove.decrement() == 0:\n self.products = [product for product in self.products if product != product_to_remove]\n\n return product_to_remove.count\n\n def forget_products(self):\n \"\"\" Delete the product basket \"\"\"\n self.products = []\n\n def new_product(self, barcode, description, priceinpence, callback):\n \"\"\" Add a new product to the database \"\"\"\n self.dbaccess.add_product(barcode, description, priceinpence, callback)\n \n def add_product_to_basket(self, barcode):\n \"\"\" Adds a new scanned product to the list ('basket') of scanned products \"\"\"\n product = next((product for product in self.products if barcode == product.barcode), None)\n\n if product is not None:\n product.increment() # Product already exists once, so just increment its count\n self.screen_manager.current.on_scan(product)\n else:\n # Otherwise need to get product info from the database\n self.dbaccess.get_product(barcode, self.reply_queue)\n \n def on_db_random_product_callback(self, packet):\n \"\"\" Callback when random product data is returned from the database \"\"\"\n barcode = packet.data['barcode']\n self.on_scan_event(barcode)\n \n def on_db_got_user_data(self, packet):\n \"\"\" Callback when user data returned \"\"\"\n \n member_id = packet.data['memberid']\n username = packet.data['username']\n balance = packet.data['balance']\n credit_limit = packet.data['limit']\n \n self.user = User(member_id, username, balance, credit_limit, self.options)\n self.logger.debug(\"Got user %s\" % self.user.name)\n self.screen_manager.current.on_rfid()\n \n def on_db_got_unknown_user(self, packet):\n self.logger.debug(\"Bad RFID %s\" % packet.data['rfid'])\n self.screen_manager.current.OnBadRFID()\n \n def on_db_got_product_data(self, packet):\n \"\"\" Called when product data returned \"\"\"\n barcode = packet.data['barcode']\n description = packet.data['description']\n priceinpence = packet.data['priceinpence']\n \n product = Product(barcode, description, priceinpence) # pylint: disable=W0142\n\n if product.valid:\n self.products.append(product) \n self.screen_manager.current.on_scan(product)\n \n def on_db_got_unknown_product(self, packet):\n \"\"\" Called when user data request failed \"\"\"\n barcode = packet.data['barcode']\n self.screen_manager.current.on_bad_scan(barcode)\n\ndef add_credit_successful(packet):\n \"\"\" Parses reply for a successful addition of credit to user account \"\"\"\n success = False\n\n if packet.type == \"result\" and packet.data['action'] == \"addcredit\":\n success = (packet.data['result'] == \"Success\")\n return success\n\ndef transaction_total(packets):\n \"\"\" Parses reply for the sum of all transactions \"\"\"\n transaction_sum = 0\n\n for packet in packets:\n if packet.type == \"result\" and packet.data['action'] == \"transaction\":\n transaction_sum = transaction_sum + int(packet.data['total'])\n\n return transaction_sum\n\ndef add_product_successful(packet):\n \"\"\" Parses reply for a successful addition of product to database \"\"\"\n success = False\n\n if packet.type == \"result\" and packet.data['action'] == \"addproduct\":\n success = (packet.data['result'] == \"Success\")\n return success\n\ndef get_options():\n \n argparser = argparse.ArgumentParser(description='Snackspace Server')\n argparser.add_argument('-H', dest='host_ip', nargs='?', default='localhost', const='localhost')\n argparser.add_argument('-P', dest='rfid_port', nargs='?', default=None)\n argparser.add_argument('--limitaction', dest='limit_action', nargs='?', default='ignore')\n argparser.add_argument('--creditaction', dest='credit_action', nargs='?', default='disallow')\n argparser.add_argument('--fullscreen', dest='start_fullscreen', nargs='?', default='n')\n argparser.add_argument('--file', dest='conffile', nargs='?', default='')\n\n args = argparser.parse_args()\n\n # # Read arguments from configuration file\n try:\n confparser = ConfigParser.ConfigParser()\n print os.getcwd()\n confparser.readfp(open(\"Client/\" + args.conffile))\n\n except IOError:\n # # Configuration file does not exist, or no filename supplied\n confparser = None\n \n if confparser is None:\n host_ip = args.host_ip\n rfid_port = args.rfid_port\n limit_action = args.limit_action\n credit_action = args.credit_action\n start_fullscreen = args.start_fullscreen\n else:\n host_ip = confparser.get('ClientConfig', 'host_ip')\n limit_action = confparser.get('ClientConfig', 'limit_action')\n credit_action = confparser.get('ClientConfig', 'credit_action')\n start_fullscreen = confparser.get('ClientConfig', 'start_fullscreen')\n try:\n rfid_port = confparser.get('ClientConfig', 'rfid_port')\n except ConfigParser.NoOptionError:\n rfid_port = None\n \n options = SnackspaceOptions(host_ip, rfid_port, limit_action, credit_action, start_fullscreen)\n \n return options\n\ndef init_pygame(fullscreen):\n \n \"\"\" Initialises the pygame module and generates window\n to draw on. Return the window and the size \"\"\"\n \n pygame.init()\n \n size = [800, 600]\n\n if fullscreen:\n window = pygame.display.set_mode(size, pygame.FULLSCREEN)\n else:\n window = pygame.display.set_mode(size)\n\n pygame.mouse.set_visible(False)\n \n return window, size\n \ndef main(_argv=None):\n \n \"\"\" Entry point for snackspace client application \"\"\"\n \n options = get_options()\n \n window, size = init_pygame(options.start_fullscreen == 'y')\n \n snackspace = Snackspace(window, size, options)\n\n logging.basicConfig(level=logging.DEBUG)\n\n snackspace.start()\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7835051417350769, "alphanum_fraction": 0.7835051417350769, "avg_line_length": 23, "blob_id": "cb51469ea2eb5de656d9c057fdec25071c334329", "content_id": "9cd4935419a1294673ed33959a416a562ee116b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 97, "license_type": "no_license", "max_line_length": 55, "num_lines": 4, "path": "/StartServer.sh", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nexport PYTHONPATH=$PYTHONPATH:Common:Server:Server/data\npython Server/server.py -L\n\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.6410256624221802, "avg_line_length": 38, "blob_id": "f488e72ec6153899fa1cefd37225e0bbee719e5e", "content_id": "2499ac53ce21a5078b779d12a0083b88ba9ee557", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39, "license_type": "no_license", "max_line_length": 38, "num_lines": 1, "path": "/Client/screens/__init__.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "## Blank __init__.py for the LCARS GUI\n" }, { "alpha_fraction": 0.625984251499176, "alphanum_fraction": 0.6417322754859924, "avg_line_length": 30.875, "blob_id": "13323c0bd5cd3bbd5bb9670263c5301b8b4525d4", "content_id": "b6b6bfc68be0032a62d55c6069fb61960c2def1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "no_license", "max_line_length": 76, "num_lines": 8, "path": "/Client/enum.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nenum.py\n\"\"\" \n \ndef Enum(*sequential, **named): #pylint: disable=C0103\n \"\"\" Simple C-like enumeration class. Each item available as integer \"\"\" \n enums = dict(zip(sequential, range(len(sequential))), **named)\n return type('Enum', (), enums)" }, { "alpha_fraction": 0.5945835113525391, "alphanum_fraction": 0.6036109924316406, "avg_line_length": 35.37313461303711, "blob_id": "06de44fe4d27e484fb9ba7ef1dc668944557f9e4", "content_id": "8ccdf6120096e8df18326b23284d3395a6cb3fd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2437, "license_type": "no_license", "max_line_length": 100, "num_lines": 67, "path": "/Client/screens/border.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nborder.py\n\"\"\"\nimport pygame #@UnresolvedImport\n\nfrom screens.displayconstants import Widths, Colours\n\nfrom LCARSGui import LCARSText, TextAlign, LCARSSweep, LCARSCappedBar, CapLocation\n\n##\n## Standard Border for all Snackspace LCARS screens\n##\n\nclass Border:\n \"\"\" Defines objects for the Snackspace border (LCARS sweep and title text) \"\"\"\n def __init__(self, width, height):\n\n self.ENDCAP = -1 #pylint: disable=C0103\n self.TEXT = -2 #pylint: disable=C0103\n self.SWEEP = -3 #pylint: disable=C0103\n\n capped_bar_length = width / 16\n sweep_end_y = height - Widths.BORDER\n sweep_height = sweep_end_y - Widths.BORDER\n\n self.objects = {\n self.ENDCAP : LCARSCappedBar(pygame.Rect(width - Widths.BORDER - capped_bar_length, \n Widths.BORDER, capped_bar_length, Widths.LARGE_BAR),\n CapLocation.CAP_RIGHT, '', Colours.FG, Colours.BG, True)\n }\n\n ## The title text is to the immediate left of the endcap\n text_right = self.objects[self.ENDCAP].l() - Widths.BORDER\n self.objects[self.TEXT] = LCARSText((text_right, Widths.BORDER + Widths.LARGE_BAR/2),\n \"SNACKSPACE v1.0\",\n 80,\n TextAlign.XALIGN_RIGHT, Colours.FG, Colours.BG, True)\n\n ## The sweep starts at the immediate left of the text\n sweep_end_x = self.objects[self.TEXT].l() - Widths.BORDER\n sweep_width = sweep_end_x - Widths.BORDER\n\n self.objects[self.SWEEP] = LCARSSweep(\n pygame.Rect(Widths.BORDER, Widths.BORDER, sweep_width, sweep_height),\n 'TL', Widths.SMALL_BAR, Widths.LARGE_BAR, Colours.FG, Colours.BG, True)\n\n def inner_y(self):\n \"\"\"\n The sweep defines the inner edge of the snackspace screen\n Return the y location of the inner edge of the border\n \"\"\"\n return self.objects[self.ENDCAP].b()\n\n def inner_x(self):\n \"\"\"\n The sweep defines the inner edge of the snackspace screen\n Return the x location of the inner edge of the border\n \"\"\"\n return self.objects[self.SWEEP].l()\n\n def bottom(self):\n \"\"\" y-coordinate of the bottom of the sweep \"\"\"\n return self.objects[self.SWEEP].b()\n\n def get_border(self):\n \"\"\" The LCARS objects constituting the border \"\"\"\n return self.objects\n" }, { "alpha_fraction": 0.6524410843849182, "alphanum_fraction": 0.6531239151954651, "avg_line_length": 36.075950622558594, "blob_id": "9cbcba9e5bc9400c4f50fdfdef6c1371b13563f8", "content_id": "c53a36a22236d3f84839958765f8e59cfa5774aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2929, "license_type": "no_license", "max_line_length": 104, "num_lines": 79, "path": "/Client/screenmanager.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\" \nscreenmanager.py\n\nHandles switching between snackspace SCREENS\n\"\"\"\n\nimport logging\n\nfrom screens.displayconstants import Screens\n\nfrom screens.introscreen import IntroScreen\nfrom screens.numericentry import NumericEntry\nfrom screens.mainscreen import MainScreen\nfrom screens.productentry import ProductEntry\n \nclass ScreenManager:\n \"\"\" Implements a management class for handling screens and transitions between them \"\"\"\n def __init__(self, owner, window, size):\n\n width, height = size[0], size[1]\n \n self.window = window\n\n # Instantiate all the SCREENS now\n self.screens = {\n Screens.INTROSCREEN : IntroScreen(width, height, self, owner),\n Screens.NUMERICENTRY : NumericEntry(width, height, self, owner),\n Screens.MAINSCREEN : MainScreen(width, height, self, owner),\n Screens.PRODUCTENTRY : ProductEntry(width, height, self, owner)\n }\n\n self.valid_screen_transitions = {\n Screens.BLANKSCREEN : [Screens.INTROSCREEN],\n Screens.INTROSCREEN : [Screens.MAINSCREEN, Screens.PRODUCTENTRY],\n Screens.MAINSCREEN : [Screens.INTROSCREEN, Screens.NUMERICENTRY],\n Screens.NUMERICENTRY : [Screens.MAINSCREEN],\n Screens.PRODUCTENTRY : [Screens.INTROSCREEN]\n }\n\n self.logger = logging.getLogger(\"screenmanager\")\n\n self.screens[Screens.INTROSCREEN].active = False\n self.screens[Screens.NUMERICENTRY].active = False\n self.screens[Screens.MAINSCREEN].active = False\n\n self.currentscreen = Screens.BLANKSCREEN\n self.req(Screens.INTROSCREEN)\n\n def get(self, screen):\n \"\"\" Get the requested screen object \"\"\"\n return self.screens[screen]\n\n @property\n def current(self):\n \"\"\" Return the current screen object \"\"\"\n return self.screens[self.currentscreen]\n\n def req(self, newscreen, force = False):\n \"\"\" Request to show a new screen \"\"\"\n valid = False\n if (newscreen == self.currentscreen) or self.is_valid_transition(newscreen) or force:\n self.logger.debug(\"Changing screen from %s to %s\" % (self.currentscreen, newscreen))\n\n if self.currentscreen not in [Screens.BLANKSCREEN, newscreen]:\n self.screens[self.currentscreen].set_active(False)\n self.currentscreen = newscreen\n self.screens[newscreen].set_active(True)\n\n valid = True\n self.screens[newscreen].draw(self.window)\n else:\n self.logger.debug(\"Could not change screen from %s to %s\" % (self.currentscreen, newscreen))\n\n return valid\n\n def is_valid_transition(self, newscreen):\n \"\"\" Returns true if the new screen is reachable from the current one \"\"\"\n valid_transitions = self.valid_screen_transitions[self.currentscreen]\n return newscreen in valid_transitions\n" }, { "alpha_fraction": 0.6211828589439392, "alphanum_fraction": 0.6254348754882812, "avg_line_length": 32.16666793823242, "blob_id": "3a49ce0c3dbbb6af06673268a3a0db381d1b47bf", "content_id": "1f08c6acef8c587f552fd56f012cb9141a36a035", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2587, "license_type": "no_license", "max_line_length": 111, "num_lines": 78, "path": "/Client/SimpleStateMachine.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "'''\nSimpleStateMachine.py\n\nImplements a basic state machine.\n\nStates are defined as integers.\nEach state can have events associated with it.\nEach state-event pair has a function handler that returns the next state.\n\n'''\n\nimport logging\nfrom collections import namedtuple\n\nclass SimpleStateMachine:\n\n \"\"\" Implementation of the state machine \"\"\"\n \n class StateNotFoundException(Exception):\n \"\"\"Exception to be issued when a state cannot be found\"\"\"\n pass\n\n class EventNotFoundException(Exception):\n \"\"\"Exception to be issued when an event cannot be found\"\"\"\n pass\n\n class BadHandlerException(Exception):\n \"\"\"Exception to be issued when a handler does not return a new state \"\"\"\n pass\n\n def __init__(self, startstate, entries):\n self.state = startstate\n \n #Make each entry a named tuple. This aids in writing the event handler.\n SimpleStateMachineEntry = namedtuple('Entry', ['state', 'event', 'handler']) #pylint: disable=C0103 \n self.entries = [SimpleStateMachineEntry(entry[0], entry[1], entry[2]) for entry in entries]\n \n self.event_queue = []\n self.executing = False\n self.logger = logging.getLogger(\"SimpleStateMachine\")\n\n def on_state_event(self, event):\n \"\"\" Queues an event for execution \"\"\"\n self.event_queue.append(event)\n\n if not self.executing:\n self.handle_event_queue()\n\n def handle_event_queue(self):\n \"\"\" Handles transition from state->state based on event and handler function \"\"\" \n self.executing = True\n while len(self.event_queue) > 0:\n\n event = self.event_queue[0]\n self.event_queue = self.event_queue[1:]\n\n old_state = self.state\n\n # Find entries for this state\n entries = [entry for entry in self.entries if entry.state == self.state]\n\n if len(entries) == 0:\n raise self.StateNotFoundException(\"State %s not found\" % self.state)\n\n # Find the handler for this event\n try:\n [handler] = [entry.handler for entry in entries if entry.event == event]\n except ValueError:\n raise self.EventNotFoundException(\"Event %s in state %s\" % (event, self.state))\n\n self.state = handler()\n\n if self.state is None:\n raise self.BadHandlerException(\"Handler did not return next state\")\n\n self.logger.info(\"Got event %s in state %s, new state %s\" % (event, old_state, self.state))\n\n self.executing = False\n" }, { "alpha_fraction": 0.5699967741966248, "alphanum_fraction": 0.576462984085083, "avg_line_length": 27.9158878326416, "blob_id": "f36634fa3e6907fc440942ed80d05542d35062c0", "content_id": "57a758c3b7124a5c83f66f8feca2e78d60c468f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3093, "license_type": "no_license", "max_line_length": 107, "num_lines": 107, "path": "/Client/screens/screen_gui.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nscreen_gui.py\n\nBase class for a snackspace screen GUI\n\"\"\"\n\nimport pygame #@UnresolvedImport\n\nfrom threading import Timer\n\nfrom screens.displayconstants import Colours, Widths\n\nfrom LCARSGui import LCARSCappedBar, CapLocation\n\nclass Banner(LCARSCappedBar):\n \n \"\"\" A banner to be shown for a period of time \"\"\"\n def __init__(self, x_full, y_full, text, colour):\n \n #pylint: disable=W0231\n self.x_full = x_full\n self.y_full = y_full\n self.banner_text = text\n self.colour = colour\n self.banner_width = self.x_full * 0.6\n self.refresh()\n \n def set_width_fraction(self, fraction):\n \"\"\" Change the default width fraction for this banner \"\"\"\n self.banner_width = self.x_full * fraction\n self.refresh()\n \n def refresh(self):\n \"\"\" Recalculate the position and dimensions for this banner \"\"\"\n x = (self.x_full - self.banner_width) / 2 #pylint: disable=C0103\n y = (self.y_full - Widths.LARGE_BAR) / 2 #pylint: disable=C0103\n \n LCARSCappedBar.__init__(self, \n pygame.Rect(x, y, self.banner_width, Widths.LARGE_BAR),\n CapLocation.CAP_RIGHT + CapLocation.CAP_LEFT, self.banner_text, self.colour, Colours.BG , True)\n\n \nclass ScreenGUI:\n\n \"\"\" The implementation of the screen GUI \"\"\"\n \n def __init__(self, width, height, owner):\n self.screen = owner\n self.width = width\n self.height = height\n self.last_press_id = -1\n self.banner = None\n self.timer = None\n self.objects = {}\n \n try:\n pass #self.sound = pygame.mixer.Sound(SOUNDFILE)\n except:\n raise\n\n def get_object_id(self, pos):\n\n \"\"\" Return the ID of the object clicked \"\"\"\n\n object_id = -1\n\n if self.screen.active:\n for key, gui_object in self.objects.items():\n if gui_object.collidePoint(pos) and gui_object.visible:\n object_id = key\n break\n\n if object_id > -1:\n self.last_press_id = object_id\n\n return object_id\n\n def play_sound(self):\n \"\"\" Play the GUI click sound \"\"\"\n pass #self.sound.play()\n\n def set_banner_width_fraction(self, fraction):\n \"\"\"Set the banner width as a fraction of the screen width \"\"\"\n self.banner.set_width_fraction(fraction)\n \n def set_banner_with_timeout(self, text, timeout, colour, callback):\n \"\"\" Displays a banner on the screen with a timeout.\n Calls callback when timeout expires \"\"\"\n try:\n self.timer.cancel()\n except AttributeError:\n pass\n\n self.banner = Banner(self.width, self.height, text, colour)\n\n if timeout > 0:\n self.timer = Timer(timeout, callback)\n self.timer.start()\n\n\n def hide_banner(self):\n \"\"\" Allows a banner to be hidden ahead of any timeout expiring\"\"\"\n try:\n self.timer.cancel()\n except AttributeError:\n pass\n self.banner = None" }, { "alpha_fraction": 0.5560693740844727, "alphanum_fraction": 0.5567116141319275, "avg_line_length": 32.269229888916016, "blob_id": "a0a07b7d4a069ac8ced5389035e4fc974205b9cb", "content_id": "4540753140bee791bae58ac6af2d760e8c69f482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7785, "license_type": "no_license", "max_line_length": 144, "num_lines": 234, "path": "/Server/db.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\ndbase.py\n\nServer-side database connection layer\n\"\"\"\n\nimport os\nimport sqlsoup #@UnresolvedImport\nimport sqlalchemy\nimport urllib\nimport re\nfrom sqlsoup import Session\n\nimport random\n\nTEST_DB_PATH = \"Server/data/test.dbase\"\nTEST_DATA_PATH = \"Server/data/test_data.sql\"\n\nREAL_DB_PATH = \"snackspace:%s@rommie/instrumentation\"\n\nONLINE_SQL_URL = 'https://nottinghack-instrumentation.googlecode.com/svn/db/'\n\n#List of TABLES that the Snackspace application needs\nTABLES = ['rfid_tags', 'members', 'transaction', 'products']\n\ndef get_password():\n \"\"\"\n This system is not particularly secure.\n The database password is stored in plaintext\n in a file (\".sspwd\") that should be in the same directory\n as this file.\n The password only grants MySQL access to the 'snackspace'\n MySQL user, so access is restricted to CRU anyway.\n Any further security improvements are left as an exercise for the reader.\n \"\"\"\n\n try:\n pwd = open(\".sspwd\")\n pwd = pwd.readline()\n except IOError:\n return False\n\n return pwd\n\nclass Database:\n \"\"\" Implementation of Database class \"\"\"\n def __init__(self, use_test_db):\n\n if use_test_db:\n\n self.dbase = sqlsoup.SQLSoup(\"sqlite:///%s\" % TEST_DB_PATH)\n\n if not os.path.exists(TEST_DB_PATH):\n self.create_test_db()\n\n else:\n real_db_path = REAL_DB_PATH % get_password()\n\n self.dbase = sqlsoup.SQLSoup(\"mysql://%s\" % real_db_path)\n\n random.seed()\n \n def get_user(self, rfid):\n \"\"\" Query database for user based on rfid \"\"\"\n result = {}\n\n try:\n labelled_rfid = self.dbase.with_labels(self.dbase.rfid_tags)\n labelled_members = self.dbase.with_labels(self.dbase.members)\n user_data = self.dbase.join(labelled_rfid, labelled_members, labelled_members.members_member_id== labelled_rfid.rfid_tags_member_id)\n user_data = user_data.filter(labelled_rfid.rfid_tags_rfid_serial==rfid).one()\n\n result['rfid'] = user_data.rfid_tags_rfid_serial\n result['username'] = user_data.members_name\n result['balance'] = user_data.members_balance\n result['limit'] = user_data.members_credit_limit\n result['memberid'] = user_data.members_member_id\n\n except SQLError:\n result = None\n\n return result\n\n def get_random_product(self):\n \"\"\" Get a random product \"\"\"\n result = {}\n product_count = self.dbase.products.count() - 1\n\n session = Session()\n random_index = random.randint(0, product_count)\n \n product_data = session.query(self.dbase.products)[random_index]\n result['barcode'] = product_data.barcode\n result['shortdesc'] = product_data.shortdesc\n result['price'] = product_data.price\n \n return result\n \n def get_product(self, barcode):\n \"\"\" Query database for product based on barcode \"\"\"\n result = {}\n\n try:\n product_data = self.dbase.products.filter(self.dbase.products.barcode==barcode).one()\n result['barcode'] = product_data.barcode\n result['shortdesc'] = product_data.shortdesc\n result['price'] = product_data.price\n\n except (SQLError, sqlalchemy.orm.exc.NoResultFound):\n result = None\n\n return result\n\n def transaction(self, memberid, barcode, count):\n \"\"\" Update member records based on purchased product \"\"\"\n product_data = self.dbase.products.filter(self.dbase.products.barcode==barcode).one()\n member_data = self.dbase.members.filter(self.dbase.members.member_id==memberid).one()\n\n try:\n for __count in range(0, count):\n self.dbase.transactions.insert(\n member_id = memberid,\n amount = -product_data.price,\n transaction_type = \"SNACKSPACE\",\n transaction_status = \"COMPLETE\",\n transaction_desc = product_data.shortdesc,\n product_id = product_data.product_id)\n\n member_data.balance -= product_data.price\n\n self.dbase.commit()\n\n result = True, product_data.price * count\n\n except SQLError:\n result = False, 0\n\n return result\n\n def add_credit(self, memberid, amountinpence):\n \"\"\" Update member record with additional credit \"\"\"\n member_data = self.dbase.members.filter(self.dbase.members.member_id==memberid).one()\n\n try:\n member_data.balance += amountinpence\n self.dbase.commit()\n result = True\n\n except SQLError:\n result = False\n\n return result\n\n def add_product(self, _barcode, _description, _priceinpence):\n \"\"\" Add a new product to the database \"\"\"\n try:\n self.dbase.products.insert(barcode = _barcode, shortdesc = _description, price = _priceinpence)\n self.dbase.commit()\n result = True\n\n except SQLError:\n result = False\n\n return result\n\n def create_test_db(self):\n\n \"\"\"\n Takes MySQL create table queries and botches them to work with SQLite\n \"\"\"\n\n for table in TABLES:\n filename = \"tb_%s.sql\" % table\n localpath = \"data/%s\" % filename\n if not os.path.exists(localpath):\n urllib.urlretrieve(ONLINE_SQL_URL + filename, localpath)\n\n sql = open(localpath).readlines()\n new_sql = []\n\n if table == 'transaction':\n table = 'transactions' ## Special case, filename != table name\n\n drop_sql = \"drop table if exists %s;\" % table\n\n has_primary_key = False\n primary_keys = None\n\n for line in sql:\n\n ## Remove the \"drop table\" line\n line = line.replace(drop_sql, '')\n\n #Remove any engine specifier\n line = re.sub(r'ENGINE = \\w*', '', line)\n\n ## Remove any \"primary key\" lines, but save for later\n if 'primary key' in line:\n primary_keys = line\n line = \"\"\n\n ## Replace MySQL auto_increment with PRIMARY KEY AUTOINCREMENT for SQLite\n if 'auto_increment' in line:\n line = line.replace('auto_increment', 'INTEGER PRIMARY KEY AUTOINCREMENT')\n line = line.replace('int', '')\n line = line.replace('not null', '')\n line = line.replace('NOT NULL', '')\n has_primary_key = True\n\n new_sql.append(line)\n\n ## If we didn't find an auto-increment integer key,make sure the original key is created\n if not has_primary_key and primary_keys is not None:\n new_sql.insert(-1, primary_keys)\n\n new_sql = \"\".join(new_sql)\n\n #The last statement shouldn't have a comma after it\n #which is same as not having a closing paren following a comma\n new_sql = re.sub(r\",\\s*\\)\", \")\", new_sql)\n\n # Execute the drop table line, then the create statement\n self.dbase.execute(drop_sql)\n self.dbase.commit()\n\n\n self.dbase.execute(new_sql)\n self.dbase.commit()\n\n # Insert test data\n sql = open(TEST_DATA_PATH).readlines()\n for line in sql:\n self.dbase.execute(line)\n self.dbase.commit()\n" }, { "alpha_fraction": 0.7582417726516724, "alphanum_fraction": 0.7582417726516724, "avg_line_length": 22, "blob_id": "9acef1dee6479d847b35cbe5d11b4d31286a4ee4", "content_id": "64cb3dd0fd3ef0f7bf71b4819448abb46488b33c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 91, "license_type": "no_license", "max_line_length": 68, "num_lines": 4, "path": "/Client/README.md", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "Snackspace\n==========\n\nTouchscreen user interface for the Nottingham hackspace \"snackspace\"" }, { "alpha_fraction": 0.6016339063644409, "alphanum_fraction": 0.6267263293266296, "avg_line_length": 50.40999984741211, "blob_id": "985e808bdb9e3db03bced22585506d7453a3de80", "content_id": "5da6abcb049672ccac6e782e3e6028e3e82d1dde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5141, "license_type": "no_license", "max_line_length": 193, "num_lines": 100, "path": "/Client/screens/numericentry_gui.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nnumericentry_gui.py\n\"\"\"\n\nfrom __future__ import division\n\nimport pygame #@UnresolvedImport\n\nfrom enum import Enum\n\nfrom screens.displayconstants import Widths, Colours\n\nfrom LCARSGui import LCARSCappedBar, CapLocation\n\nfrom screens.border import Border\nfrom screens.screen_gui import ScreenGUI\n\nclass NumericEntryGUI(ScreenGUI):\n \n \"\"\" Describes the graphical elements of the numeric entry screen \"\"\"\n \n def __init__(self, width, height, owner):\n\n ScreenGUI.__init__(self, width, height, owner)\n\n border = Border(width, height)\n\n ##\n ## Fixed position objects\n ##\n\n buttonw = 100\n largebuttonw = buttonw * 2\n amountentryw = (buttonw * 4) + (Widths.BORDER * 4)\n\n ## Column and row x, y locations\n cx = [0, 0, 0, 0] #pylint: disable=C0103\n cx[0] = 200\n cx[1] = cx[0] + buttonw + Widths.BORDER\n cx[2] = cx[1] + buttonw + Widths.BORDER\n cx[3] = cx[2] + buttonw + Widths.BORDER + Widths.BORDER\n buttonh = 50\n amountentryh = buttonh * 1.5\n\n ry = [0, 0, 0, 0] #pylint: disable=C0103\n ry[0] = 125\n ry[1] = ry[0] + amountentryh + Widths.BORDER\n ry[2] = ry[1] + buttonh + Widths.BORDER\n ry[3] = ry[2] + buttonh + Widths.BORDER\n r5y = ry[3] + buttonh + Widths.BORDER\n r6y = r5y + buttonh + Widths.BORDER\n\n cancelbuttonx = cx[3] + buttonw - largebuttonw #Right align the \"cancel\" button\n \n self.keys = Enum(\"KEY0\", \"KEY1\", \"KEY2\", \"KEY3\", \"KEY4\", \"KEY5\", \"KEY6\", \"KEY7\", \"KEY8\", \"KEY9\",\n \"FIVEPOUNDS\", \"TENPOUNDS\", \"TWENTYPOUNDS\", \"DONE\", \"CANCEL\", \"AMOUNT\")\n \n self.objects = {\n self.keys.AMOUNT : LCARSCappedBar(pygame.Rect(cx[0], ry[0], amountentryw, amountentryh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"\\xA30.00\", Colours.FG, Colours.BG, True),\n\n self.keys.KEY0 : LCARSCappedBar(pygame.Rect(cx[0], r5y, buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"0\", Colours.FG, Colours.BG, True),\n self.keys.KEY1 : LCARSCappedBar(pygame.Rect(cx[0], ry[3], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"1\", Colours.FG, Colours.BG, True),\n self.keys.KEY2 : LCARSCappedBar(pygame.Rect(cx[1], ry[3], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"2\", Colours.FG, Colours.BG, True),\n self.keys.KEY3 : LCARSCappedBar(pygame.Rect(cx[2], ry[3], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"3\", Colours.FG, Colours.BG, True),\n self.keys.KEY4 : LCARSCappedBar(pygame.Rect(cx[0], ry[2], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"4\", Colours.FG, Colours.BG, True),\n self.keys.KEY5 : LCARSCappedBar(pygame.Rect(cx[1], ry[2], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"5\", Colours.FG, Colours.BG, True),\n self.keys.KEY6 : LCARSCappedBar(pygame.Rect(cx[2], ry[2], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"6\", Colours.FG, Colours.BG, True),\n self.keys.KEY7 : LCARSCappedBar(pygame.Rect(cx[0], ry[1], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"7\", Colours.FG, Colours.BG, True),\n self.keys.KEY8 : LCARSCappedBar(pygame.Rect(cx[1], ry[1], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"8\", Colours.FG, Colours.BG, True),\n self.keys.KEY9 : LCARSCappedBar(pygame.Rect(cx[2], ry[1], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"9\", Colours.FG, Colours.BG, True),\n\n self.keys.FIVEPOUNDS : LCARSCappedBar(pygame.Rect(cx[3], ry[1], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, u\"\\xA35\", Colours.FG, Colours.BG, True),\n self.keys.TENPOUNDS : LCARSCappedBar(pygame.Rect(cx[3], ry[2], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, u\"\\xA310\", Colours.FG, Colours.BG, True),\n self.keys.TWENTYPOUNDS : LCARSCappedBar(pygame.Rect(cx[3], ry[3], buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, u\"\\xA320\", Colours.FG, Colours.BG, True),\n\n self.keys.DONE : LCARSCappedBar(pygame.Rect(cx[0], r6y, largebuttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Done\", Colours.FG, Colours.BG, True),\n self.keys.CANCEL : LCARSCappedBar(pygame.Rect(cancelbuttonx, r6y, largebuttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Cancel\", Colours.FG, Colours.BG, True),\n }\n\n ##\n ## Import standard objects\n\n self.objects.update(border.get_border())\n\n ##\n ## Position-dependant objects\n ##\n\n def update_amount(self, amount):\n \"\"\" Set the total amount text \"\"\"\n self.objects[self.keys.AMOUNT].setText(\"\\xA3%.2f\" % (amount / 100))\n\n def draw(self, window):\n \"\"\" Redraw the numeric entry screen \"\"\"\n window.fill(Colours.BG)\n\n for gui_object in self.objects.values():\n gui_object.draw(window)\n\n pygame.display.flip()\n" }, { "alpha_fraction": 0.5764583945274353, "alphanum_fraction": 0.64411461353302, "avg_line_length": 89.53125, "blob_id": "78a5acc55f0edba7131727bd6da070ea45ef4247", "content_id": "e498824d2e36c9c96058477ff7d7892c2edd7e93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 2897, "license_type": "no_license", "max_line_length": 136, "num_lines": 32, "path": "/Server/data/test_data.sql", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "INSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (1, 'Dakota Meyers',-114,-2673);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (2, 'Amber White',-383,-4370);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (3, 'Hiram Tyson',-427,-4684);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (4, 'Eaton Greer',841,-2549);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (5, 'Sydney Cross',68,-4954);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (6, 'Murphy Terrell',1623,-2811);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (7, 'Hoyt Kinney',-444,-2401);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (8, 'Chantale Cash',657,-3756);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (9, 'Ralph Knight',-49,-2534);\nINSERT INTO 'members' ('member_id','name','balance','credit_limit') VALUES (10, 'James Fowkes',-4000,-5000);\n\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (1, '11');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (2, '22');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (3, '33');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (4, '44');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (5, '55');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (6, '66');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (7, '77');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (8, '88');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (9, '99');\nINSERT INTO 'rfid_tags' ('member_id', 'rfid_serial') VALUES (10, '1B7F2D2D');\n\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (101, '1', 'KitKat Chunky', 50);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (102, '2', 'Double Decker', 120);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (103, '3', 'Pringles Can', 120);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (104, '4', 'Pot Noodle', 120);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (105, '5', 'Mixed Nuts (1 Scoop)', 120);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (106, '6', 'Mixed Fruit and Nuts (1 Scoop)', 120);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (107, '7', 'Chocolate Bar', 120);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (108, '8', 'Seabrooks Crisps', 120);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (109, '9', 'Altoids', 120);\nINSERT INTO 'products' ('product_id', 'barcode', 'shortdesc', 'price') VALUES (110, '7613033126321', 'Yorkie (Raisin and Biscuit)', 50);\n" }, { "alpha_fraction": 0.6232727766036987, "alphanum_fraction": 0.6271541714668274, "avg_line_length": 40.4244384765625, "blob_id": "9042c96dbce0f1f73da76975d9dfbfb21645545b", "content_id": "1b6d8dfc8ad57d69ddb2287076e29e72f6da2893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12882, "license_type": "no_license", "max_line_length": 151, "num_lines": 311, "path": "/Client/screens/mainscreen_gui.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nmainscreen_gui.py\n\"\"\"\n\nfrom __future__ import division\n\nimport pygame #@UnresolvedImport\nimport logging\n\nfrom enum import Enum\nfrom const import Const\n\nfrom screens.productdisplay import ProductDisplayCollection\n\nfrom screens.displayconstants import Widths, Colours\n\nfrom LCARSGui import LCARSCappedBar, CapLocation\n\nfrom screens.border import Border\nfrom screens.screen_gui import ScreenGUI\n \nclass MainScreenLayout:\n\n \"\"\" Describes the graphical elements of the main screen and\n provides methods for setting introduction text \"\"\"\n\n def __init__(self, width, height, border):\n \n self.button_data = Const()\n self.button_data.width = 100\n self.button_data.large_width = self.button_data.width * 2\n self.button_data.height = 50\n\n ## Spread buttons out between sweep and edge\n self.button_data.done_x = border.inner_x() + Widths.BORDER\n self.button_data.cancel_x = width - Widths.BORDER - self.button_data.large_width\n self.button_data.pay_x = (self.button_data.done_x + self.button_data.cancel_x) / 2\n self.button_data.y = height - Widths.BORDER - self.button_data.height # Put buttons at bottom of screen\n\n ## Put the top bar below the sweep\n self.top_bar = Const()\n self.top_bar.x = border.inner_x() + Widths.BORDER\n self.top_bar.y = border.inner_y() + Widths.BORDER\n\n ## This allows caculation of the inner width of the useable screen area\n self.inner_width = width - self.top_bar.x - Widths.BORDER\n\n ## And then the small amount bar can be defined \n self.amount = Const()\n self.amount.y = self.top_bar.y\n self.amount.width = 2 * self.button_data.width\n self.amount.x = width - Widths.BORDER - self.amount.width\n\n ## And finally the top bar width can be defined\n self.top_bar.width = self.inner_width - self.amount.width - Widths.BORDER\n\n ## The first product entry starts below the top bar\n self.product_entries = Const()\n self.product_entries.top_y = self.top_bar.y + self.button_data.height + Widths.BORDER\n\n # The up/dn scroll buttons cover the whole height of the screen\n scroll_height = (self.button_data.y - self.product_entries.top_y) / 2\n scroll_height -= Widths.BORDER\n \n self.scroll = Const()\n self.scroll.height = scroll_height\n\n self.scroll.width = self.button_data.height\n self.scroll.x = width - Widths.BORDER - self.scroll.width\n self.scroll.up_y = self.product_entries.top_y\n self.scroll.dn_y = self.scroll.up_y + self.scroll.height + Widths.BORDER\n\n # Position constants for product objects\n \n self.product_entries.desc_x = self.top_bar.x\n self.product_entries.desc_w = self.button_data.large_width * 1.8\n self.product_entries.price_x = self.product_entries.desc_x + self.product_entries.desc_w + Widths.BORDER\n self.product_entries.price_w = self.button_data.large_width / 2\n self.product_entries.remove_x = self.product_entries.price_x + self.product_entries.price_w + Widths.BORDER\n self.product_entries.row_h = self.button_data.height + 20\n \n def get_done_rect(self):\n \"\"\" Return rectangle representing the Done button \"\"\"\n return pygame.Rect(self.button_data.done_x, self.button_data.y, self.button_data.large_width, self.button_data.height)\n\n def get_pay_rect(self):\n \"\"\" Return rectangle representing the Pay button \"\"\"\n return pygame.Rect(self.button_data.pay_x, self.button_data.y, self.button_data.large_width, self.button_data.height)\n\n def get_cancel_rect(self):\n \"\"\" Return rectangle representing the Cancel button \"\"\"\n return pygame.Rect(self.button_data.cancel_x, self.button_data.y, self.button_data.large_width, self.button_data.height)\n\n def get_top_bar_rect(self):\n \"\"\" Return rectangle representing the top information bar \"\"\"\n return pygame.Rect(self.top_bar.x, self.top_bar.y, self.top_bar.width, self.button_data.height)\n\n def get_amount_rect(self):\n \"\"\" Return rectangle representing the total amount bar \"\"\"\n return pygame.Rect(self.amount.x, self.amount.y, self.amount.width, self.button_data.height)\n\n def get_up_scroll_rect(self):\n \"\"\" Return rectangle representing the up scroll button \"\"\"\n return pygame.Rect(self.scroll.x, self.scroll.up_y, self.scroll.width, self.scroll.height)\n\n def get_down_scroll_rect(self):\n \"\"\" Return rectangle representing the down scroll button \"\"\"\n return pygame.Rect(self.scroll.x, self.scroll.dn_y, self.scroll.width, self.scroll.height)\n\n def get_description_rect(self, index):\n \"\"\" Returns a rectangle representing the description display for a product \"\"\"\n y_position = self.product_entries.top_y + (self.product_entries.row_h * index)\n return pygame.Rect(self.product_entries.desc_x, y_position, self.product_entries.desc_w, self.button_data.height)\n \n def get_price_rect(self, index):\n \"\"\" Returns a rectangle representing the price display for a product \"\"\"\n y_position = self.product_entries.top_y + (self.product_entries.row_h * index)\n return pygame.Rect(self.product_entries.price_x, y_position, self.product_entries.price_w, self.button_data.height)\n \n def get_remove_rect(self, index, width):\n \"\"\" Returns a rectangle representing the remove button for a product \"\"\"\n y_position = self.product_entries.top_y + (self.product_entries.row_h * index)\n return pygame.Rect(self.product_entries.remove_x, y_position, width, self.button_data.height)\n \nclass MainScreenGUI(ScreenGUI):\n\n \"\"\" Describes the graphical elements of the main screen and\n provides methods for adding and remove products \"\"\"\n \n def __init__(self, width, height, owner):\n \n ScreenGUI.__init__(self, width, height, owner)\n self.border = Border(width, height)\n\n # Object constant definitions\n # Reverse draw order - 0 drawn last\n self.ids = Enum(\"DONE\", \"CANCEL\", \"PAY\", \"TOPBAR\", \"AMOUNT\", \"UP\", \"DOWN\", \"PRODUCT\", \"REMOVE\")\n \n self.limits = Const()\n self.limits.screen_products = 5\n self.limits.objects_per_product_row = 3\n\n self.logger = logging.getLogger(\"MainScreen.GUI\")\n \n self.product_displays = ProductDisplayCollection(self.limits.screen_products)\n \n # #\n # # Fixed position objects\n # #\n self.layout = MainScreenLayout(width, height, self.border)\n\n self.objects = {\n self.ids.DONE: LCARSCappedBar(\n self.layout.get_done_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Done\", Colours.FG, Colours.BG, False),\n self.ids.PAY:LCARSCappedBar(\n self.layout.get_pay_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Pay debt\", Colours.FG, Colours.BG, False),\n self.ids.CANCEL:LCARSCappedBar(\n self.layout.get_cancel_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Cancel\", Colours.FG, Colours.BG, True),\n self.ids.TOPBAR:LCARSCappedBar(\n self.layout.get_top_bar_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"User: <No user scanned>\", Colours.FG, Colours.BG, True),\n self.ids.UP: LCARSCappedBar(\n self.layout.get_up_scroll_rect(), CapLocation.CAP_TOP, \"UP\", Colours.FG, Colours.BG, False),\n self.ids.DOWN: LCARSCappedBar(\n self.layout.get_down_scroll_rect(), CapLocation.CAP_BOTTOM, \"DN\", Colours.FG, Colours.BG, False),\n self.ids.AMOUNT:LCARSCappedBar(\n self.layout.get_amount_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Total Spend: \\xA30.00\", Colours.FG, Colours.BG, True)\n }\n\n # #\n # # Import standard objects\n # #\n self.objects.update(self.border.get_border())\n \n def add_to_product_display(self, product):\n \"\"\" Add a new product to the list \"\"\"\n self.product_displays.add(product)\n\n def update_total(self):\n \"\"\" Update the total spend value \"\"\"\n self.objects[self.ids.AMOUNT].setText(\"Total Spend: \\xA3%.2f\" % (self.owner.total_price() / 100))\n\n def _remove_button_width(self):\n \"\"\" The width of the remove button depends on whether the up/dn buttons are displayed \"\"\"\n removew = self.width - self.layout.product_entries.remove_x - Widths.BORDER\n\n if self._test_display_down_button() or self._test_display_up_button():\n removew -= (self.layout.scroll.width + Widths.BORDER)\n\n return removew\n\n def get_object_id(self, pos):\n \"\"\" Returns the ID of the object at the given position \"\"\"\n object_id = ScreenGUI.get_object_id(self, pos)\n\n if object_id == -1:\n # Try searching remove buttons\n if self.product_displays.collide_on_remove(pos) is not None:\n object_id = self.ids.REMOVE\n \n return object_id\n\n def set_unknown_user(self):\n \"\"\" Indicate that an unknown card was scanned \"\"\"\n self.objects[self.ids.TOPBAR].setText(\"User: <Unknown card>\")\n\n def set_user(self, name, balance, credit):\n \"\"\" Set the current username \"\"\"\n if balance >= 0:\n text = u\"%s (Balance: \\xA3%.2f\" % (name, balance / 100)\n else:\n text = u\"%s (Balance: -\\xA3%.2f\" % (name, -balance / 100)\n\n if credit > 0:\n text += u\", Pending Credit: \\xA3%.2f\" % (credit / 100)\n\n text += \")\"\n\n self.objects[self.ids.TOPBAR].setText(text)\n\n def _test_display_up_button(self):\n \"\"\" Returns TRUE if the up button should be displayed \"\"\"\n return (self.product_displays.top_index > 0)\n\n def _test_display_down_button(self):\n \"\"\" Returns TRUE if the down button should be displayed \"\"\"\n return (self.product_displays.top_index + self.limits.screen_products) < len(self.product_displays)\n\n def clear_products(self):\n \"\"\" Reset the products list to nothing \"\"\"\n self.product_displays.clear()\n\n def draw(self, window):\n \n \"\"\" Redraw the main screen \"\"\"\n window.fill(Colours.BG)\n\n self._set_show_hide_products()\n self._draw_products(window)\n self._draw_static_objects(window)\n\n pygame.display.flip()\n\n def _set_show_hide_products(self):\n\n \"\"\" Scan down the product list and set the visible\n state of the product objects \"\"\"\n \n visible_count = 0\n\n for (counter, product) in enumerate(self.product_displays):\n\n if (counter < self.product_displays.top_index):\n # Hide all the products above the list product top\n product.set_visible(False)\n elif visible_count < self.limits.screen_products:\n # Show screen products based on their quantity\n product.visible = True\n visible_count += 1\n else:\n # Hide products below list bottom\n product.set_visible(False)\n\n def _draw_products(self, window):\n\n \"\"\" Draw all visible product objects on the window \"\"\"\n \n # Iterate over all products in list\n index = 0\n for product in self.product_displays:\n if product.visible:\n product.draw(self.layout, index, self._remove_button_width(), window)\n index += 1\n\n def _draw_static_objects(self, window):\n\n \"\"\" Draw all the static objects on the window \"\"\"\n \n self.update_total()\n\n ## Draw border\n for draw_object in self.border.get_border().values():\n draw_object.draw(window)\n\n # Draw the fixed objects\n static_objs = [\n self.objects[self.ids.TOPBAR],\n self.objects[self.ids.PAY],\n self.objects[self.ids.CANCEL],\n self.objects[self.ids.DONE],\n self.objects[self.ids.AMOUNT],\n self.objects[self.ids.UP],\n self.objects[self.ids.DOWN]\n ]\n\n # Decide which objects should be shown\n if self.owner.user is not None:\n self.objects[self.ids.PAY].visible = self.owner.user.credit_allowed()\n self.objects[self.ids.DONE].visible = self.owner.user.has_added_credit() or (len(self.product_displays) > 0)\n \n self.objects[self.ids.UP].visible = self._test_display_up_button()\n self.objects[self.ids.DOWN].visible = self._test_display_down_button()\n\n for static_obj in static_objs:\n static_obj.draw(window)\n\n if self.banner is not None:\n self.banner.draw(window)\n\n def active(self):\n \"\"\" Abstraction for the active state of the screen \"\"\"\n return self.owner.active" }, { "alpha_fraction": 0.5894024968147278, "alphanum_fraction": 0.5941375494003296, "avg_line_length": 37.903507232666016, "blob_id": "071102bfac9b0b5958f748ad8d7aa8b21ee4e3e9", "content_id": "22bcf9805c0b074d3de26184794a8f172bf5d43a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4435, "license_type": "no_license", "max_line_length": 220, "num_lines": 114, "path": "/Client/screens/productentry_gui.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nproductentry_gui.py\n\"\"\"\n\nfrom __future__ import division\n\nimport pygame # @UnresolvedImport\n\nfrom enum import Enum\n\nfrom screens.displayconstants import Widths, Colours\n\nfrom LCARSGui import LCARSCappedBar, CapLocation\n\nfrom screens.border import Border\nfrom screens.screen_gui import ScreenGUI\n\n\nclass ProductEntryGUI(ScreenGUI):\n \n \"\"\" Describes the graphical elements of the product entry screen \"\"\"\n \n def __init__(self, width, height, owner):\n\n ScreenGUI.__init__(self, width, height, owner)\n\n border = Border(width, height)\n\n self.buttons = Enum(\"BARCODE\", \"DESCRIPTION\", \"PRICE\", \"DONE\", \"CANCEL\")\n\n # #\n # # Fixed position objects\n # #\n\n minx = border.inner_x() + 4 * Widths.BORDER\n maxx = width - Widths.BORDER\n miny = border.inner_y() + 4 * Widths.BORDER\n maxy = height - Widths.BORDER\n\n buttonh = 50\n buttonw = 100\n\n fullwidth = maxx - minx\n\n self.default_text = {\n self.buttons.BARCODE : \"1. Scan an item\",\n self.buttons.DESCRIPTION : \"2. Type a description\",\n self.buttons.PRICE : \"3. Set a price\",\n }\n\n self.objects = {\n self.buttons.BARCODE : LCARSCappedBar(pygame.Rect(minx, miny, fullwidth, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"1. Scan an item\", Colours.ENTRY, Colours.BG, True),\n self.buttons.DESCRIPTION : LCARSCappedBar(pygame.Rect(minx, miny + (2 * buttonh), fullwidth, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"2. Type a description\", Colours.ERR, Colours.BG, True),\n self.buttons.PRICE : LCARSCappedBar(pygame.Rect(minx, miny + (4 * buttonh), fullwidth, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"3. Set a price\", Colours.ERR, Colours.BG, True),\n self.buttons.DONE : LCARSCappedBar(pygame.Rect(minx, maxy - buttonh, buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Done\", Colours.FG, Colours.BG, True),\n self.buttons.CANCEL : LCARSCappedBar(pygame.Rect(maxx - buttonw, maxy - buttonh, buttonw, buttonh), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, \"Cancel\", Colours.FG, Colours.BG, True),\n }\n\n # #\n # # Import standard objects\n # #\n self.objects.update(border.get_border())\n\n def reset_entry(self, entry):\n \n \"\"\" Reset the text of the selected entry to the default \"\"\"\n if entry == self.buttons.BARCODE:\n self.objects[entry].fg = Colours.FG\n else:\n self.objects[entry].fg = Colours.ERR\n \n self.objects[entry].setText(self.default_text[entry])\n \n def set_active_entry(self, entry):\n\n \"\"\" Change the current entry textbox to one of barcode, description or price \"\"\"\n \n for key, gui_object in self.objects.iteritems():\n if key == entry:\n gui_object.fg = Colours.ENTRY\n gui_object.setText(\"\")\n else:\n if key in [self.buttons.BARCODE, self.buttons.DESCRIPTION, self.buttons.PRICE]:\n if (len(gui_object.getText()) == 0) or (gui_object.getText() == self.default_text[key]):\n # No entry in this box. Set error colour\n gui_object.fg = Colours.ERR\n gui_object.setText(self.default_text[key])\n else:\n gui_object.fg = Colours.FG\n gui_object.setText(gui_object.getText()) # Forces colour update\n\n def change_barcode(self, barcode):\n \"\"\" Set a new barocde for this product \"\"\"\n self.objects[self.buttons.BARCODE].setText(barcode)\n\n def change_description(self, description):\n \"\"\" Set a new description for this product \"\"\"\n self.objects[self.buttons.DESCRIPTION].setText(description)\n\n def change_price(self, priceinpence):\n \"\"\" Set a new price for this product \"\"\"\n self.objects[self.buttons.PRICE].setText(\"\\xA3%.2f\" % (priceinpence / 100))\n\n def draw(self, window):\n \"\"\" Redraw the product entry screen \"\"\"\n window.fill(Colours.BG)\n\n for gui_object in self.objects.values():\n gui_object.draw(window)\n\n if self.banner is not None:\n self.banner.draw(window)\n\n pygame.display.flip()\n" }, { "alpha_fraction": 0.6048421859741211, "alphanum_fraction": 0.609165608882904, "avg_line_length": 33.52238845825195, "blob_id": "ca4d140a3dacf8751df40b658ccb9cdea642c350", "content_id": "f4b42b626060ab2abc03d4675138bd042f4bd0bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2313, "license_type": "no_license", "max_line_length": 99, "num_lines": 67, "path": "/Client/user.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\" \nuser.py\n\nClass representing a snackspace user\n\"\"\"\n\nclass User:\n\n \"\"\" Definition of the user class \"\"\"\n \n def __init__(self, member_id, username, balance, credit_limit, options): #pylint: disable=R0913\n \"\"\" Initialise the user object \"\"\"\n self.name = username\n self.balance = int(balance)\n self.credit_limit = int(credit_limit)\n self.member_id = member_id\n self.limit_action = options.limit_action\n self.credit_action = options.credit_action\n\n ## Keep credit added recorded separately from balance.\n ## This way, balance will not be updated until payments have been processed,\n ## but the user can be prevented from adding too much credit (configuration dependent)\n self.credit = 0\n\n ## Transaction allowed return values\n XACTION_ALLOWED = 0\n XACTION_OVERLIMIT = 1\n XACTION_DENIED = 2\n\n def transaction_allowed(self, priceinpence):\n \"\"\" Determines if the user is allowed to debit their account by amount requested \"\"\"\n over_limit = (self.balance - priceinpence < self.credit_limit)\n transaction_state = self.XACTION_ALLOWED\n\n if over_limit:\n if self.limit_action == 'warn':\n transaction_state = self.XACTION_OVERLIMIT\n elif self.limit_action == 'deny':\n transaction_state = self.XACTION_DENIED\n else:\n transaction_state = self.XACTION_DENIED\n\n return transaction_state\n\n def credit_allowed(self):\n \"\"\" Determines if user is allowed to credit their account \"\"\"\n credit_allowed = False ## Assume that adding extra credit is not allowed\n\n if self.credit_action == 'always':\n credit_allowed = True\n elif self.credit_action == 'whenindebt':\n if (self.balance + self.credit) < 0:\n credit_allowed = True\n else:\n credit_allowed = False\n elif self.credit_action == 'disallow':\n credit_allowed = False\n\n return credit_allowed\n \n def has_added_credit(self):\n \"\"\" Returns true if the user has added some credit \"\"\"\n return (self.credit > 0)\n \n def add_credit(self, amount):\n \"\"\" Increases amount of added credit \"\"\"\n self.credit += int(amount)\n" }, { "alpha_fraction": 0.5367316603660583, "alphanum_fraction": 0.5457271337509155, "avg_line_length": 22.785715103149414, "blob_id": "c00a4ab053e0dd36f6d774897e6f722027fe3ed0", "content_id": "bc1366c6abb3a9339ad2127d1f528e25fb720929", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 59, "num_lines": 28, "path": "/Client/product.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "class Product:\n\n def __init__(self, barcode, description, priceinpence):\n self.valid = False\n self.description = ''\n self.price_in_pence = 0\n self.count = 0\n\n self.barcode = barcode\n self.description = description\n self.price_in_pence = int(priceinpence)\n self.count = 1\n self.valid = True\n\n def increment(self):\n if (self.valid):\n self.count += 1\n\n def decrement(self):\n if (self.valid):\n if self.count > 0:\n self.count -= 1\n\n return self.count\n\n @property\n def total_price(self):\n return self.count * self.price_in_pence\n\n" }, { "alpha_fraction": 0.8048780560493469, "alphanum_fraction": 0.8048780560493469, "avg_line_length": 29.5, "blob_id": "1a5fd125303726e4db85980fc9cbd8ddf4d81370", "content_id": "45c536c74e7e0de78fbb638a15c7903dc1a2e8ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 123, "license_type": "no_license", "max_line_length": 58, "num_lines": 4, "path": "/StartClient.sh", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nexport PYTHONPATH=$PYTHONPATH:Common:Client:Client/screens\npython Client/snackspace.py --file snackspace.cfg\n\n" }, { "alpha_fraction": 0.5791666507720947, "alphanum_fraction": 0.5839285850524902, "avg_line_length": 28.928571701049805, "blob_id": "8286f7ab0ae2e5b4eafba7151021965a28f36f48", "content_id": "d9d8ba4ff20c4c5bbeef873dc02b563550a6e5f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1680, "license_type": "no_license", "max_line_length": 64, "num_lines": 56, "path": "/Client/screens/screen.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nscreen.py\n\"\"\"\n\nclass Screen: #pylint: disable=R0921\n \n \"\"\" Defines a standard interface for a snackspace screen\n pylint R0921 disable - this class is referenced \"\"\"\n \n def __init__(self, manager, owner, screen_id):\n self.screen_manager = manager\n self.owner = owner\n self.last_gui_position = None\n self.last_keypress = ''\n self.screen_id = screen_id\n self.active = False\n \n def set_active(self, state):\n \"\"\"\n Active state can be changed by the screen manager\n \"\"\"\n if (not self.active) and state:\n #On transition from inactive->active, update the GUI\n self.active = state\n self._update_on_active()\n else:\n #Otherwise, just set new the active state\n self.active = state\n \n def _update_on_active(self):\n \"\"\" Called when active state changes \"\"\"\n raise NotImplementedError\n \n def on_gui_event(self, pos):\n \"\"\" Called when a GUI event is is triggered \"\"\"\n raise NotImplementedError\n \n def on_scan(self, product):\n \"\"\" Called when a product is scanned \"\"\"\n raise NotImplementedError\n \n def on_bad_scan(self, badcode):\n \"\"\" Called when an unknown product is scanned \"\"\"\n raise NotImplementedError\n \n def on_key_event(self, key):\n \"\"\" Called on keyboard press \"\"\"\n raise NotImplementedError\n\n def on_rfid(self):\n \"\"\" Called when a known RFID is scanned \"\"\"\n raise NotImplementedError\n \n def on_bad_rfid(self):\n \"\"\" Called when an unknown RFID is scanned \"\"\"\n raise NotImplementedError\n " }, { "alpha_fraction": 0.5843095779418945, "alphanum_fraction": 0.5857294797897339, "avg_line_length": 33.56441879272461, "blob_id": "f708ab1820738c7d5debe4db23cd8d804f5be01f", "content_id": "ca52e9d69a32a2ed89f450cc9da35d335d8d205c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5634, "license_type": "no_license", "max_line_length": 177, "num_lines": 163, "path": "/Server/dbserver.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\ndbase.py\n\nServer-side message and packet handling layer\n\n\"\"\"\n\nfrom messaging import Message, Packet, PacketTypes\n\nimport logging\n\nfrom db import Database\n\nclass DbServer(Database):\n \"\"\" Implementation of database server class \"\"\"\n def __init__(self, use_test_db):\n\n Database.__init__(self, use_test_db)\n \n self.packets = []\n \n logging.basicConfig(level=logging.DEBUG)\n \n self.logger = logging.getLogger(\"LocalDB\")\n \n def process_packets(self, packets):\n \"\"\" Process a list of packets \"\"\"\n \n reply = Message() ## The reply starts as an empty message\n\n for packet in packets:\n\n self.logger.info(\"Handling '%s' packet...\" % packet.type)\n\n if packet.type == PacketTypes.Ping:\n reply.add_packet( Packet(PacketTypes.PingReply) )\n elif packet.type == PacketTypes.GetProduct:\n reply.add_packet( self.get_product_from_data(packet.data) )\n elif packet.type == PacketTypes.GetUser:\n reply.add_packet( self.get_user_from_data(packet.data) )\n elif packet.type == PacketTypes.Transaction:\n reply.add_packet( self.apply_transaction_from_data(packet.data) )\n elif packet.type == PacketTypes.AddProduct:\n reply.add_packet ( self.add_product_from_data(packet.data) )\n elif packet.type == PacketTypes.AddCredit:\n reply.add_packet( self.add_credit_from_data(packet.data) )\n elif packet.type == PacketTypes.GetRandomProduct:\n reply.add_packet( self.get_random_product_packet() )\n elif packet.type == PacketTypes.PingReply:\n pass # No action required for ping reply\n else:\n self.logger.warning(\"Unknown packet '%s'\" % packet.type)\n\n return reply.get_xml()\n \n def get_random_product_packet(self):\n \"\"\" Get a random product and make packet \"\"\"\n result = self.get_random_product()\n \n datatype = PacketTypes.RandomProduct\n data = {'barcode': '0', 'description': '', 'priceinpence':'0'} \n data['barcode'] = result['barcode']\n data['description'] = result['shortdesc']\n data['priceinpence'] = result['price']\n \n packet = Packet(datatype, data)\n\n return packet\n \n def get_product_from_data(self, data):\n \"\"\" Get a product packet \"\"\"\n barcode = data['barcode']\n\n self.logger.info(\"Getting product %s\" % barcode)\n\n return self.product_from_barcode(barcode)\n\n def get_user_from_data(self, data):\n \"\"\" Get a user packet \"\"\"\n rfid = data['rfid']\n\n self.logger.info(\"Getting user %s\" % rfid)\n\n return self.user_from_rfid(rfid)\n\n def add_product_from_data(self, data):\n \"\"\" Add a product to the database \"\"\"\n _barcode = data['barcode']\n _desc = data['description']\n _priceinpence = data['price_in_pence']\n\n self.logger.info(\"Adding new product %s\" % _barcode)\n\n result = self.add_product(_barcode, _desc, _priceinpence)\n\n packet = Packet(PacketTypes.Result, {\"action\":PacketTypes.AddProduct, \"barcode\":_barcode, \"description\": _desc, \"result\": \"Success\" if result else \"Fail\"})\n\n return packet\n\n def add_credit_from_data(self, data):\n \"\"\" Add credit to a user \"\"\"\n memberid = data['memberid']\n amountinpence = int(data['amountinpence'])\n\n self.logger.info(\"Adding %s credit to member %s\" % (amountinpence, memberid))\n\n result = self.add_credit(memberid, amountinpence)\n\n packet = Packet(PacketTypes.Result, {\"action\":PacketTypes.AddCredit, \"credit\": amountinpence, \"result\": \"Success\" if result else \"Fail\", \"memberid\":memberid})\n\n return packet\n\n def apply_transaction_from_data(self, data):\n \"\"\" Add transaction to the database \"\"\"\n memberid = data['memberid']\n barcode = data['barcode']\n count = int(data['count'])\n\n result, total = self.transaction(memberid, barcode, count)\n\n packet = Packet(PacketTypes.Result, {\"action\":PacketTypes.Transaction, \"barcode\":barcode, \"total\":total, \"result\": \"Success\" if result else \"Fail\", \"memberid\":memberid})\n\n return packet\n\n def product_from_barcode(self, barcode):\n \"\"\" Build a product packet from the database \"\"\"\n result = self.get_product(barcode)\n\n if result is not None:\n datatype = PacketTypes.ProductData\n data = {'barcode': '0', 'description': '', 'priceinpence':'0'} \n data['barcode'] = result['barcode']\n data['description'] = result['shortdesc']\n data['priceinpence'] = result['price']\n else:\n datatype = PacketTypes.UnknownProduct\n data = {'barcode': '0'} \n data['barcode'] = barcode\n \n packet = Packet(datatype, data)\n\n return packet\n\n\n def user_from_rfid(self, rfid):\n \"\"\" Build a user packet from the database \"\"\"\n datatype = PacketTypes.UserData\n data = {'memberid': '0', 'username': '', 'balance':'0', 'limit':'0', 'rfid':rfid}\n\n result = self.get_user(rfid)\n\n if result is not None:\n data['rfid'] = result['rfid']\n data['memberid'] = result['memberid']\n data['username'] = result['username']\n data['balance'] = result['balance']\n data['limit'] = result['limit']\n else:\n datatype = PacketTypes.UnknownUser\n\n packet = Packet(datatype, data)\n\n return packet\n" }, { "alpha_fraction": 0.5719733238220215, "alphanum_fraction": 0.5802351236343384, "avg_line_length": 29.55339813232422, "blob_id": "90ff47a70d386d87d6e24c4013c082633865188f", "content_id": "73869a0967d57dab64d7e1178e6a38764626a78b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3147, "license_type": "no_license", "max_line_length": 87, "num_lines": 103, "path": "/Client/screens/numericentry.py", "repo_name": "jamesfowkes/Snackspace", "src_encoding": "UTF-8", "text": "\"\"\"\nnumericentry.py\n\"\"\"\n\nfrom __future__ import division\n\nfrom screenmanager import Screens\n\nfrom screens.numericentry_gui import NumericEntryGUI\nfrom screens.screen import Screen\n\nclass NumericEntry(Screen, NumericEntryGUI):\n\n \"\"\" Implements the numeric entry screen \"\"\"\n \n def __init__(self, width, height, manager, owner):\n \n Screen.__init__(self, manager, owner, Screens.NUMERICENTRY)\n NumericEntryGUI.__init__(self, width, height, self)\n self.amountinpence = 0\n self.preset_amount = False\n\n def on_gui_event(self, pos):\n\n button = self.get_object_id(pos)\n\n if button >= self.keys.KEY0 and button <= self.keys.KEY9:\n #Let button press decide whether to play sound or not\n self._new_button_press(button)\n else:\n #Play sound unconditionally for other buttons\n self.play_sound()\n if button == self.keys.FIVEPOUNDS:\n self.preset_amount = True\n self._set_amount(500)\n elif button == self.keys.TENPOUNDS:\n self.preset_amount = True\n self._set_amount(1000)\n elif button == self.keys.TWENTYPOUNDS:\n self.preset_amount = True\n self._set_amount(2000)\n elif button == self.keys.DONE:\n self._credit_and_exit()\n elif button == self.keys.CANCEL:\n self._exit()\n\n def _update_on_active(self):\n \"\"\" No action when active state changes \"\"\"\n pass\n\n def on_scan(self, product):\n \"\"\" No action when product scanned \"\"\"\n pass\n\n def on_bad_scan(self, badcode):\n \"\"\" No action when product scanned \"\"\"\n pass\n\n def on_key_event(self, key):\n \"\"\" No action when key pressed \"\"\"\n pass\n\n def on_rfid(self):\n \"\"\" No action when RFID scanned \"\"\"\n pass\n\n def on_bad_rfid(self):\n \"\"\" No action when bad RFID scanned \"\"\"\n pass\n\n def _set_amount(self, amount):\n \"\"\" Update the amount shown on the entry bar \"\"\"\n self.amountinpence = amount\n self.update_amount(self.amountinpence)\n self.screen_manager.req(Screens.NUMERICENTRY)\n\n def _new_button_press(self, key):\n \"\"\" One of the 0-9 button has been pressed, set a new amount \"\"\"\n \n if self.preset_amount:\n ## Clear the preset amount and assume starting from scratch\n self.preset_amount = False\n self.amountinpence = 0\n\n if ((self.amountinpence * 10) + key) <= 5000:\n\n self.play_sound()\n\n self.amountinpence *= 10\n self.amountinpence += key\n\n self.update_amount(self.amountinpence)\n self.screen_manager.req(Screens.NUMERICENTRY)\n\n def _credit_and_exit(self):\n \"\"\" Credit the user with the amount entered and then exit to the mainscreen \"\"\"\n self.owner.credit_user(self.amountinpence)\n self._exit()\n\n def _exit(self):\n \"\"\" Reset this screen and return to mainscreen \"\"\"\n self._set_amount(0)\n self.screen_manager.req(Screens.MAINSCREEN)\n" } ]
31
robustzurcher/analysis
https://github.com/robustzurcher/analysis
38fbbdb742204b63ff2b387709f358d6c2571157
86fdc91dff3ae1adef13c3196523c0f2d6398742
695320ae26dcfc2488090ce4aa161ded43c2f7ce
refs/heads/master
2021-12-23T16:16:28.467847
2021-11-08T13:29:44
2021-11-08T13:29:44
189,440,153
0
0
MIT
2019-05-30T15:41:21
2021-11-01T14:02:39
2021-11-08T13:29:44
Jupyter Notebook
[ { "alpha_fraction": 0.50448077917099, "alphanum_fraction": 0.542259693145752, "avg_line_length": 29.59677505493164, "blob_id": "dcf2c4e3af0439e5365e52addf4245a779ea13d9", "content_id": "96bb0e01d125365e3493fd0ffc32e638aa04707c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5691, "license_type": "permissive", "max_line_length": 94, "num_lines": 186, "path": "/python/scripts_figures/ex_post/transition_probabilities.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom config import DIR_FIGURES\nfrom scripts_figures.global_vals_funcs import BIN_SIZE\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import DICT_POLICIES_2223\nfrom scripts_figures.global_vals_funcs import DICT_POLICIES_4292\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\n\np_size = 3\nwidth = 0.8 * BIN_SIZE\np_raw = np.loadtxt(\"../pre_processed_data/parameters/rust_trans_raw.txt\")\nhesse_inv_raw = np.loadtxt(\"../pre_processed_data/parameters/rust_cov_raw.txt\")\nx = np.arange(1, p_size + 1) * BIN_SIZE\n\n\ndef get_probabilities(state):\n p_ml = DICT_POLICIES_4292[0.0][1][state, state : state + p_size]\n\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n\n ax.bar(\n x,\n p_ml,\n width,\n color=SPEC_DICT[color][\"colors\"][0],\n ls=SPEC_DICT[color][\"line\"][0],\n )\n\n ax.set_ylabel(r\"Transition probability\")\n ax.set_xlabel(r\"Mileage increase (in thousands)\")\n plt.xticks(x)\n ax.set_ylim([0.00, 0.80])\n ax.set_yticks(np.arange(0, 1, 0.2))\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-probabilities{SPEC_DICT[color]['file']}\"\n )\n\n\ndef get_probabilities_bar(state):\n\n p_ml = DICT_POLICIES_4292[0.0][1][state, state : state + p_size]\n std_err = _get_standard_errors(p_ml, p_raw, hesse_inv_raw)\n capsize = 15\n\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n\n ax.bar(\n x,\n p_ml,\n width,\n yerr=std_err,\n capsize=capsize,\n color=SPEC_DICT[color][\"colors\"][0],\n ls=SPEC_DICT[color][\"line\"][0],\n )\n\n ax.set_ylabel(r\"Transition probability\")\n ax.set_ylim([0.00, 0.80])\n ax.set_yticks(np.arange(0, 1, 0.2))\n\n ax.set_xlabel(r\"Mileage increase (in thousands)\")\n plt.xticks(x)\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-probabilities-bar{SPEC_DICT[color]['file']}\"\n )\n\n\ndef df_probability_shift(state):\n return pd.DataFrame(\n {\n \"0\": DICT_POLICIES_2223[0.0][1][state, state : state + p_size],\n \"4292_0.50\": DICT_POLICIES_4292[0.5][1][state, state : state + p_size],\n \"4292_0.95\": DICT_POLICIES_4292[0.95][1][state, state : state + p_size],\n \"2223_0.95\": DICT_POLICIES_2223[0.95][1][state, state : state + p_size],\n }\n )\n\n\ndef get_probability_shift(state):\n\n width = 0.25 * BIN_SIZE\n\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n\n ax.bar(\n x - width,\n DICT_POLICIES_4292[0.0][1][state, state : state + p_size],\n width,\n color=SPEC_DICT[color][\"colors\"][0],\n hatch=SPEC_DICT[color][\"hatch\"][0],\n label=\"reference\",\n )\n ax.bar(\n x,\n DICT_POLICIES_4292[0.50][1][state, state : state + p_size],\n width,\n color=SPEC_DICT[color][\"colors\"][1],\n hatch=SPEC_DICT[color][\"hatch\"][1],\n label=r\"$\\omega=0.50$\",\n )\n ax.bar(\n x + width,\n DICT_POLICIES_4292[0.95][1][state, state : state + p_size],\n width,\n color=SPEC_DICT[color][\"colors\"][2],\n hatch=SPEC_DICT[color][\"hatch\"][2],\n label=r\"$\\omega=0.95$\",\n )\n\n ax.set_ylabel(r\"Transition probability\")\n ax.set_xlabel(r\"Mileage increase (in thousands)\")\n ax.set_ylim([0.0, 0.8])\n ax.set_yticks(np.arange(0, 1, 0.2))\n plt.xticks(x)\n ax.legend()\n\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-probability-shift-omega{SPEC_DICT[color]['file']}\"\n )\n\n\ndef get_probability_shift_data(state):\n\n width = 0.25 * BIN_SIZE\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n\n ax.bar(\n x - width,\n DICT_POLICIES_4292[0.0][1][state, state : state + p_size],\n width,\n color=SPEC_DICT[color][\"colors\"][0],\n hatch=SPEC_DICT[color][\"hatch\"][0],\n label=\"reference\",\n )\n ax.bar(\n x,\n DICT_POLICIES_4292[0.95][1][state, state : state + p_size],\n width,\n color=SPEC_DICT[color][\"colors\"][1],\n hatch=SPEC_DICT[color][\"hatch\"][1],\n label=\"$N_x = 55$\",\n )\n ax.bar(\n x + width,\n DICT_POLICIES_2223[0.95][1][state, state : state + p_size],\n width,\n color=SPEC_DICT[color][\"colors\"][2],\n hatch=SPEC_DICT[color][\"hatch\"][2],\n label=\"$N_x = 29$\",\n )\n\n ax.set_ylabel(r\"Transition probability\")\n ax.set_xlabel(r\"Mileage increase (in thousands)\")\n plt.xticks(x)\n ax.set_ylim([0.0, 0.8])\n ax.set_yticks(np.arange(0, 1, 0.2))\n\n ax.legend()\n\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-probability-shift-data{SPEC_DICT[color]['file']}\"\n )\n\n\ndef _get_standard_errors(p, p_raw, hesse_inv_raw):\n runs = 1000\n draws = np.zeros((runs, len(p_raw)), dtype=np.float)\n for i in range(runs):\n draws[i, :] = draw_from_raw(p_raw, hesse_inv_raw)\n std_err = np.zeros((2, len(p_raw)), dtype=float)\n for i in range(len(p_raw)):\n std_err[0, i] = p[i] - np.percentile(draws[:, i], 2.5)\n std_err[1, i] = np.percentile(draws[:, i], 97.5) - p[i]\n return std_err\n\n\ndef draw_from_raw(p_raw, hesse_inv_raw):\n draw = np.random.multivariate_normal(p_raw, hesse_inv_raw)\n return np.exp(draw) / np.sum(np.exp(draw))\n" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.707317054271698, "avg_line_length": 23.600000381469727, "blob_id": "29fa0f57e63d69128b1317626d100ad0053225e8", "content_id": "a698088fc987266f87ed76398793ddf216b96583", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 123, "license_type": "permissive", "max_line_length": 39, "num_lines": 5, "path": "/python/config.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import os\n\nDIR_FIGURES = os.environ[\"DIR_FIGURES\"]\nROOT_DIR = os.environ[\"PROJECT_ROOT\"]\nDATA_DIR = os.environ[\"DATA_DIR\"]\n" }, { "alpha_fraction": 0.5268676280975342, "alphanum_fraction": 0.5819134712219238, "avg_line_length": 28.346153259277344, "blob_id": "280f0e461916c5f6258c3e8fa465e8ab364b55b9", "content_id": "7dd20fcc521ce13586bc16ccfeabf0b091850284", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1526, "license_type": "permissive", "max_line_length": 90, "num_lines": 52, "path": "/python/scripts_figures/introduction.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom config import DIR_FIGURES\nfrom matplotlib import pyplot as plt\nfrom scipy.interpolate import interp1d\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\n\ndef get_introduction_decision_making():\n\n for color in COLOR_OPTS:\n\n fig, ax = plt.subplots(1, 1)\n\n x_values = [0.00, 0.33, 0.66, 1.00]\n y_values = [0.95, 0.70, 0.40, 0.00]\n\n f = interp1d(x_values, y_values, kind=\"quadratic\")\n x_grid = np.linspace(0, 1, num=41, endpoint=True)\n\n cl = SPEC_DICT[color][\"colors\"][0]\n ls = SPEC_DICT[color][\"line\"][0]\n\n ax.plot(x_grid, f(x_grid), label=\"as-if\", color=cl, ls=ls)\n\n x_values = [0.00, 0.33, 0.66, 1.00]\n y_values = [0.80, 0.70, 0.50, 0.20]\n\n f = interp1d(x_values, y_values, kind=\"quadratic\")\n\n cl = SPEC_DICT[color][\"colors\"][1]\n ls = SPEC_DICT[color][\"line\"][1]\n\n x_grid = np.linspace(0, 1, num=41)\n\n ax.plot(x_grid, f(x_grid), label=\"robust\", color=cl, ls=ls)\n\n ax.set_xticks((0.0, 0.2, 0.5, 0.8, 1.0))\n ax.set_xticklabels([])\n\n ax.yaxis.get_major_ticks()[0].set_visible(False)\n ax.set_xlim(-0.1, 1.1)\n ax.set_ylim(-0.1, 1.0)\n ax.set_yticklabels([])\n\n ax.set_xlabel(\"Level of model misspecification\")\n ax.set_ylabel(\"Performance\")\n ax.legend()\n\n plt.savefig(\n f\"{DIR_FIGURES}/fig-introduction-robust-performance{SPEC_DICT[color]['file']}\"\n )\n" }, { "alpha_fraction": 0.5670879483222961, "alphanum_fraction": 0.5797257423400879, "avg_line_length": 34.75961685180664, "blob_id": "a21358e3319f178405f5d0fb4f8ed580c6a2c96b", "content_id": "a385abf67f04d12ff5d61773ed482c60a763b1e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3719, "license_type": "permissive", "max_line_length": 93, "num_lines": 104, "path": "/python/scripts_figures/ex_post/threshold_plot.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import glob\nimport pickle as pkl\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom config import DIR_FIGURES\nfrom scripts_figures.global_vals_funcs import BIN_SIZE\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import OMEGA_GRID\nfrom scripts_figures.global_vals_funcs import SIM_RESULTS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\nnum_keys = 100\n\n\ndef df_thresholds():\n means_discrete = _threshold_data()\n omega_range = np.linspace(0, 0.99, num_keys)\n return pd.DataFrame({\"omega\": omega_range, \"threshold\": means_discrete})\n\n\ndef get_replacement_thresholds():\n\n means_discrete = _threshold_data() * BIN_SIZE\n\n means_ml = np.full(len(OMEGA_GRID), np.round(means_discrete[0])).astype(int)\n\n omega_sections, state_sections = _create_sections(means_discrete, OMEGA_GRID)\n\n y_0 = state_sections[0][0] - 2 * BIN_SIZE\n y_1 = state_sections[-1][-1] + 2 * BIN_SIZE\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n ax.set_ylabel(r\"Mileage (in thousands)\")\n ax.set_xlabel(r\"$\\omega$\")\n ax.set_ylim([y_0, y_1])\n plt.xlim(left=-0.06, right=1)\n\n ax.plot(\n OMEGA_GRID,\n means_ml,\n color=SPEC_DICT[color][\"colors\"][0],\n ls=SPEC_DICT[color][\"line\"][0],\n label=\"as-if\",\n )\n if color == \"colored\":\n second_color = \"tab:orange\"\n else:\n second_color = SPEC_DICT[color][\"colors\"][0]\n for j, i in enumerate(omega_sections[:-1]):\n ax.plot(\n i, state_sections[j], color=second_color, ls=SPEC_DICT[color][\"line\"][1]\n )\n ax.plot(\n omega_sections[-1],\n state_sections[-1],\n color=second_color,\n ls=SPEC_DICT[color][\"line\"][1],\n label=\"robust\",\n )\n ax.legend()\n\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-replacement-thresholds{SPEC_DICT[color]['file']}\"\n )\n\n\ndef _threshold_data():\n file_list = sorted(glob.glob(SIM_RESULTS + \"result_ev_*_mat_0.0.pkl\"))\n if len(file_list) != 0:\n means_robust_strat = np.array([])\n for omega in OMEGA_GRID:\n mean = pkl.load(open(SIM_RESULTS + f\"result_ev_{omega}_mat_0.0.pkl\", \"rb\"))[\n 0\n ]\n means_robust_strat = np.append(means_robust_strat, mean)\n else:\n raise AssertionError(\"Need to unpack simulation files\")\n\n means_discrete = np.around(means_robust_strat).astype(int)\n return means_discrete\n\n\ndef _create_sections(mean_disc, om_range):\n omega_sections = []\n state_sections = []\n for j, i in enumerate(np.unique(mean_disc)):\n where = mean_disc == i\n max_ind = np.max(np.where(mean_disc == i))\n if j == 0:\n med_val = (np.max(om_range[where]) + np.min(om_range[~where])) / 2\n omega_sections += [np.append(om_range[where], med_val)]\n state_sections += [np.append(mean_disc[where], i)]\n elif j == (len(np.unique(mean_disc)) - 1):\n med_val = (np.min(om_range[where]) + np.max(om_range[~where])) / 2\n omega_sections += [np.array([med_val] + om_range[where].tolist())]\n state_sections += [np.array([i] + mean_disc[where].tolist())]\n else:\n low = (np.min(om_range[where]) + np.max(omega_sections[-1][:-1])) / 2\n high = (np.max(om_range[where]) + np.min(om_range[max_ind + 1])) / 2\n omega_sections += [np.array([low] + om_range[where].tolist() + [high])]\n state_sections += [np.array([i] + mean_disc[where].tolist() + [i])]\n return omega_sections, state_sections\n" }, { "alpha_fraction": 0.5616954565048218, "alphanum_fraction": 0.589011013507843, "avg_line_length": 32.88298034667969, "blob_id": "434c58840633b89137f3ff928b6a1277a338c73d", "content_id": "cf49f793a5ece6db14733fbe4edbd214397eb8bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3185, "license_type": "permissive", "max_line_length": 84, "num_lines": 94, "path": "/python/scripts_figures/ex_post/demonstration.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom config import DIR_FIGURES\nfrom ruspy.model_code.cost_functions import calc_obs_costs\nfrom ruspy.model_code.cost_functions import lin_cost\nfrom ruspy.simulation.simulation import simulate\nfrom scripts_figures.global_vals_funcs import BIN_SIZE\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import COST_SCALE\nfrom scripts_figures.global_vals_funcs import DICT_POLICIES_4292\nfrom scripts_figures.global_vals_funcs import PARAMS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\n\ndef get_demonstration_df(init_dict):\n states, periods = get_demonstration_data(init_dict)\n return pd.DataFrame(\n {\n \"months_ml\": periods[0],\n \"months_rob\": periods[1],\n \"opt_mileage\": states[0] * BIN_SIZE,\n \"rob_mileage\": states[1] * BIN_SIZE,\n }\n )\n\n\ndef get_demonstration(df, max_period):\n states = (df[\"opt_mileage\"], df[\"rob_mileage\"])\n periods = (df[\"months_ml\"], df[\"months_rob\"])\n labels = [\"as-if\", r\"robust ($\\omega = 0.95$)\"]\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n ax.set_xlabel(r\"Months\")\n ax.set_ylabel(r\"Mileage (in thousands)\")\n\n for i, state in enumerate(states):\n ax.plot(\n periods[i],\n state,\n color=SPEC_DICT[color][\"colors\"][i],\n ls=SPEC_DICT[color][\"line\"][i],\n label=labels[i],\n )\n if color == \"colored\":\n id = (states[1] == states[0]).idxmin()\n ax.plot(\n periods[1][:id],\n states[1][:id],\n color=SPEC_DICT[color][\"colors\"][0],\n ls=\"--\",\n )\n ax.legend(loc=\"upper left\")\n ax.set_ylim([0, 90])\n plt.xlim(left=-3, right=max_period)\n\n plt.xticks(range(0, max_period + 10, 10))\n\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-demonstration{SPEC_DICT[color]['file']}\"\n )\n\n\ndef get_demonstration_data(init_dict):\n\n ev_ml = np.dot(DICT_POLICIES_4292[0.0][1], DICT_POLICIES_4292[0.0][0])\n ev_95 = np.dot(DICT_POLICIES_4292[0.95][1], DICT_POLICIES_4292[0.95][0])\n trans_mat = DICT_POLICIES_4292[0.0][1]\n\n num_states = ev_ml.shape[0]\n\n costs = calc_obs_costs(num_states, lin_cost, PARAMS, COST_SCALE)\n\n df_ml = simulate(init_dict, ev_ml, costs, trans_mat)\n df_95 = simulate(init_dict, ev_95, costs, trans_mat)\n\n periods_ml = np.array(range(init_dict[\"periods\"]), dtype=int)\n periods_95 = np.array(range(init_dict[\"periods\"]), dtype=int)\n periods = [periods_ml, periods_95]\n states_ml = np.array(df_ml[\"state\"], dtype=int)\n states_95 = np.array(df_95[\"state\"], dtype=int)\n states = [states_ml, states_95]\n\n for i, df in enumerate([df_ml, df_95]):\n index = (\n np.array(\n df[df[\"decision\"] == 1].index.get_level_values(\"period\"), dtype=int\n )\n + 1\n )\n states[i] = np.insert(states[i], index, 0)\n periods[i] = np.insert(periods[i], index, index - 1)\n\n return states, periods\n" }, { "alpha_fraction": 0.6968085169792175, "alphanum_fraction": 0.6985815763473511, "avg_line_length": 28.6842098236084, "blob_id": "4590eba9ff09f5ee5e815995220eaf71392a6412", "content_id": "05a92dbca4895370529da7e2736f56a21aa970c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "permissive", "max_line_length": 91, "num_lines": 19, "path": "/python/execute_notebooks.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"This module executes all notebooks. It serves the main purpose to ensure that all can be\nexecuted and work proper independently.\"\"\"\nimport glob\nimport os\nimport subprocess as sp\n\nos.chdir(os.environ[\"PROJECT_ROOT\"] + \"/notebooks\")\n\nfor notebook in sorted(glob.glob(\"*.ipynb\")):\n cmd = (\n f\" jupyter nbconvert --to notebook --execute {notebook}\"\n f\" --ExecutePreprocessor.timeout=-1\"\n )\n sp.check_call(cmd, shell=True)\n\nfor convert_notebook in sorted(glob.glob(\"*nbconvert.ipynb\")):\n\n os.remove(convert_notebook)\n" }, { "alpha_fraction": 0.7985348105430603, "alphanum_fraction": 0.7997558116912842, "avg_line_length": 25.419355392456055, "blob_id": "82f26863b84a5a00e22b0269f14004951b989a00", "content_id": "325cc98e4215a493b462b697bd75707b9bfc01bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 819, "license_type": "permissive", "max_line_length": 62, "num_lines": 31, "path": "/configurations/ipython/profile_default/startup/start.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "from IPython import get_ipython\n\nipython = get_ipython()\n\nipython.magic(\"matplotlib inline\")\nipython.magic(\"load_ext autoreload\")\nipython.magic(\"autoreload 2\")\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfrom scripts_figures.ex_post.transition_probabilities import *\nfrom scripts_figures.global_vals_funcs import *\nfrom scripts_figures.ex_post.maintenace_probabilities import *\nfrom scripts_figures.ex_post.demonstration import *\nfrom scripts_figures.ex_post.threshold_plot import *\nfrom scripts_figures.ex_post.performance_plots import *\nfrom scripts_figures.ex_post.observations import *\nfrom scripts_figures.ex_ante import *\n\nfrom scripts_figures.introduction import *\nfrom scripts_figures.urn_illustrations import *\n\n\nextract_zips()\n\n\nDIR_FIGURES = os.environ[\"DIR_FIGURES\"]\n" }, { "alpha_fraction": 0.569088339805603, "alphanum_fraction": 0.5961538553237915, "avg_line_length": 31.65116310119629, "blob_id": "d1608514fb029c2ae7a2c400725d6ec7cdf1724a", "content_id": "de3e34d13caab8a03d53e78f1b4a01d4bf94cc35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2808, "license_type": "permissive", "max_line_length": 83, "num_lines": 86, "path": "/python/scripts_figures/ex_post/maintenace_probabilities.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom config import DIR_FIGURES\nfrom ruspy.model_code.choice_probabilities import choice_prob_gumbel\nfrom ruspy.model_code.cost_functions import calc_obs_costs\nfrom ruspy.model_code.cost_functions import lin_cost\nfrom scripts_figures.global_vals_funcs import BIN_SIZE\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import COST_SCALE\nfrom scripts_figures.global_vals_funcs import DICT_POLICIES_4292\nfrom scripts_figures.global_vals_funcs import DISC_FAC\nfrom scripts_figures.global_vals_funcs import PARAMS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\n\nkeys = [0.0, 0.5, 0.95]\nmax_state = 30\n\n\ndef df_maintenance_probabilties():\n choice_ml, choices = _create_repl_prob_plot(DICT_POLICIES_4292, keys)\n states = np.arange(choice_ml.shape[0]) * BIN_SIZE\n return pd.DataFrame(\n {\n \"milage_thousands\": states,\n 0.0: choice_ml[:, 0],\n keys[1]: choices[0][:, 0],\n keys[2]: choices[1][:, 0],\n }\n )\n\n\ndef get_maintenance_probabilities():\n\n choice_ml, choices = _create_repl_prob_plot(DICT_POLICIES_4292, keys)\n states = np.arange(max_state) * BIN_SIZE\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n\n ax.plot(\n states,\n choice_ml[:max_state, 0],\n color=SPEC_DICT[color][\"colors\"][0],\n ls=SPEC_DICT[color][\"line\"][0],\n label=\"as-if\",\n )\n for i, choice in enumerate(choices):\n ax.plot(\n states,\n choice[:max_state, 0],\n color=SPEC_DICT[color][\"colors\"][i + 1],\n ls=SPEC_DICT[color][\"line\"][i + 1],\n label=fr\"robust $(\\omega = {keys[i+1]:.2f})$\",\n )\n\n ax.set_ylabel(r\"Maintenance probability\")\n ax.set_xlabel(r\"Mileage (in thousands)\")\n ax.set_ylim([0, 1.02])\n\n end = states[::5][-1] + 25\n ax.set_xticks(np.append(states[::5], end))\n plt.xlim(right=end)\n ax.legend()\n\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-maintenance-probabilities\"\n f\"{SPEC_DICT[color]['file']}\"\n )\n\n\ndef _create_repl_prob_plot(file, keys):\n ev_ml = np.dot(DICT_POLICIES_4292[0.0][1], DICT_POLICIES_4292[0.0][0])\n num_states = ev_ml.shape[0]\n costs = calc_obs_costs(num_states, lin_cost, PARAMS, COST_SCALE)\n choice_ml = choice_prob_gumbel(ev_ml, costs, DISC_FAC)\n choices = []\n for omega in keys[1:]:\n choices += [\n choice_prob_gumbel(\n np.dot(DICT_POLICIES_4292[omega][1], DICT_POLICIES_4292[omega][0]),\n costs,\n DISC_FAC,\n )\n ]\n return choice_ml, choices\n" }, { "alpha_fraction": 0.49559858441352844, "alphanum_fraction": 0.5199823975563049, "avg_line_length": 29.374332427978516, "blob_id": "128a0029d12f3daee020b824846035692a9ed23c", "content_id": "51ecd2ab2c26d4830ac8db1e0294cf4660379d33", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11360, "license_type": "permissive", "max_line_length": 87, "num_lines": 374, "path": "/python/scripts_figures/urn_illustrations.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom config import DIR_FIGURES\nfrom scipy.stats import binom\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\n\ndef get_payoff(action, theta):\n \"Compute payoff based on theta and action theta'\"\n return 1 - (action - theta) ** 2\n\n\ndef take_action(r, n, rule, lambda_=None):\n \"action refers here to announce a theta estimate\"\n if lambda_ is None:\n lambda_ = np.sqrt(n) / (1 + np.sqrt(n))\n\n if rule == \"as-if\":\n theta_prime = r / n\n elif rule == \"robust\":\n theta_prime = lambda_ * r / n + (1 - lambda_) * 0.5\n elif rule == \"fixed\":\n theta_prime = np.tile(0.5, len(r))\n else:\n raise NotImplementedError\n\n return theta_prime\n\n\ndef risk_function(n, rule, theta=None, lambda_=None):\n if theta is None:\n theta_grid = np.linspace(0, 1, 100)\n\n else:\n theta_grid = np.array([theta])\n\n if lambda_ is None:\n lambda_ = np.sqrt(n) / (1 + np.sqrt(n))\n\n # rslt = np.tile(np.nan, len(p_grid))\n rslt = []\n for theta in theta_grid:\n r = np.array(range(n + 1))\n rv = binom(n, theta)\n rslt.append(\n np.sum(\n get_payoff(take_action(r, n, rule, lambda_=lambda_), theta) * rv.pmf(r)\n )\n )\n return np.array(rslt)\n\n\ndef create_payoff_func(theta):\n \"\"\"Plot expected payoff function.\n\n Focusing on a single point in the state space, we combine the information on\n the sampling distribution for our action with the payoff from each action to\n determine the **expected payoff**.\n \"\"\"\n matplotlib.rcParams[\"axes.spines.right\"] = True\n for color in COLOR_OPTS:\n # n = 50\n r = np.arange(0, 1, 0.01)\n\n fig, ax = plt.subplots(1, 1)\n ax.plot(\n r,\n get_payoff(r, theta),\n color=SPEC_DICT[color][\"colors\"][0],\n )\n ax.set_ylim([0.7, 1.01])\n # ax.set_yticks([0.97, 0.98, 0.99, 1])\n\n # ax.legend(loc=\"lower left\", bbox_to_anchor=(0, -0.32))\n # ax2.legend(ncol=2, loc=\"lower right\", bbox_to_anchor=(1, -0.32))\n\n # matplotlib.rc(\"axes\", edgecolor=\"k\")\n\n ax.set_ylabel(\"Payoff\")\n # ax.set_xlabel(r\"$\\hat{\\theta}$\")\n # ax.set_ylabel(\"Probability mass\")\n\n fname = f\"{DIR_FIGURES}/fig-example-urn-payoff{SPEC_DICT[color]['file']}\"\n\n fig.savefig(fname)\n matplotlib.rcParams[\"axes.spines.right\"] = False\n\n\ndef create_plot_expected_payoff_func(theta, lambda_robust):\n \"\"\"Plot expected payoff function.\n\n Focusing on a single point in the state space, we combine the information on\n the sampling distribution for our action with the payoff from each action to\n determine the **expected payoff**.\n \"\"\"\n matplotlib.rcParams[\"axes.spines.right\"] = True\n for color in COLOR_OPTS:\n n = 50\n rv = binom(n, theta)\n r = np.arange(binom.ppf(0.01, n, theta), binom.ppf(0.99, n, theta))\n\n fig, ax = plt.subplots(1, 1)\n ax2 = ax.twinx()\n series = pd.Series(rv.pmf(r), index=r)\n ax2.plot(\n r,\n get_payoff(take_action(r, n, \"as-if\"), theta),\n label=r\"ADF\",\n color=SPEC_DICT[color][\"colors\"][0],\n )\n ax2.plot(\n r,\n get_payoff(take_action(r, n, \"robust\", lambda_=lambda_robust), theta),\n label=\"RDF\",\n color=SPEC_DICT[color][\"colors\"][1],\n )\n ax.bar(\n series.index,\n series,\n alpha=0.2,\n label=\"PMF\",\n color=SPEC_DICT[color][\"colors\"][0],\n )\n ax.set_xticks(r)\n ax.set_ylim([0, 0.12])\n ax2.set_ylim([0.97, 1])\n ax.set_yticks([0, 0.04, 0.08, 0.12])\n ax2.set_yticks([0.97, 0.98, 0.99, 1])\n ax.set_xlabel(\"$r$\", labelpad=8)\n\n ax.legend(loc=\"lower left\", bbox_to_anchor=(0.1, -0.32))\n ax2.legend(ncol=2, loc=\"lower right\", bbox_to_anchor=(0.8, -0.32))\n\n matplotlib.rc(\"axes\", edgecolor=\"k\")\n\n ax2.set_ylabel(\"Payoff\")\n ax.set_ylabel(\"Probability mass\")\n\n fname = (\n f\"{DIR_FIGURES}/fig-example-urn-expected-payoff{SPEC_DICT[color]['file']}\"\n )\n\n fig.savefig(fname)\n matplotlib.rcParams[\"axes.spines.right\"] = False\n\n\ndef create_plot_risk_functions():\n \"\"\"Plot risk functions over state space.\n\n The **risk function** returns the expected payoff at each point\n in the state space.\n \"\"\"\n n = 50\n for color in COLOR_OPTS:\n\n fig, ax = plt.subplots(1, 1)\n\n ax.plot(\n np.linspace(0, 1, 100),\n risk_function(n, \"as-if\"),\n label=r\"ADF\",\n color=SPEC_DICT[color][\"colors\"][0],\n )\n ax.plot(\n np.linspace(0, 1, 100),\n risk_function(n, \"robust\", lambda_=0.9),\n label=r\"RDF\",\n color=SPEC_DICT[color][\"colors\"][1],\n )\n ax.set_ylabel(\"Expected payoff\")\n ax.set_xlabel(r\"$\\theta$\", labelpad=4)\n ax.set_ylim(0.994, 0.9999)\n plt.ticklabel_format(axis=\"y\", style=\"sci\", scilimits=(0, 0), useMathText=True)\n t = ax.yaxis.get_offset_text()\n t.set_x(-0.06)\n ax.legend(ncol=2, loc=\"lower center\", bbox_to_anchor=(0.5, -0.3))\n\n fname = (\n f\"{DIR_FIGURES}/fig-example-urn-payoff-functions{SPEC_DICT[color]['file']}\"\n )\n\n fig.savefig(fname)\n\n\ndef create_exp_payoff_plot_two_points(theta_1, theta_2, lambda_robust):\n \"\"\"Compare expected performance and expected regret at two values of theta.\"\"\"\n for color in COLOR_OPTS:\n\n n = 50\n df = pd.DataFrame(columns=[\"as-if\", \"robust\"], index=[\"theta1\", \"theta2\"])\n df.loc[\"theta2\", \"as-if\"] = risk_function(n, \"as-if\", theta=theta_2)[0]\n df.loc[\"theta2\", \"robust\"] = risk_function(\n n, \"robust\", theta=theta_2, lambda_=lambda_robust\n )[0]\n\n df.loc[\"theta1\", \"as-if\"] = risk_function(n, \"as-if\", theta=theta_1)[0]\n df.loc[\"theta1\", \"robust\"] = risk_function(\n n, \"robust\", theta=theta_1, lambda_=lambda_robust\n )[0]\n\n x = np.arange(2)\n width = 0.35\n fig, ax = plt.subplots()\n ax.bar(\n x - width / 2,\n df.loc[slice(None), \"as-if\"],\n width,\n label=r\"ADF\",\n color=SPEC_DICT[color][\"colors\"][0],\n )\n ax.bar(\n x + width / 2,\n df.loc[slice(None), \"robust\"],\n width,\n label=r\"RDF\",\n color=SPEC_DICT[color][\"colors\"][1],\n )\n ax.set_ylim([0.99, 0.999])\n ax.set_ylabel(\"Expected payoff\")\n ax.set_xticks([0, 1])\n ax.set_xticklabels([rf\"$\\theta = {theta_1}$\", rf\"$\\theta = {theta_2}$\"])\n ax.legend(ncol=2, loc=\"lower center\", bbox_to_anchor=(0.5, -0.3))\n plt.ticklabel_format(axis=\"y\", style=\"sci\", scilimits=(0, 0), useMathText=True)\n t = ax.yaxis.get_offset_text()\n t.set_x(-0.06)\n\n fname = (\n f\"{DIR_FIGURES}/fig-example-urn-exp-payoff\"\n f\"-two-points{SPEC_DICT[color]['file']}\"\n )\n\n fig.savefig(fname)\n\n\ndef create_rank_plot_urn():\n \"\"\"Create rank plot for urn example.\"\"\"\n # Insert correct values in data.\n df = pd.DataFrame(\n data=[\n [1, 0],\n [1, 0],\n [0, 1],\n ],\n index=[\n \"Maximin\",\n \"Minimax \\n regret\",\n \"Subjective \\n Bayes\",\n ],\n columns=[r\"ADF\", r\"RDF\"],\n )\n\n linestyle = [\"--\", \"-.\"]\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n\n ax.spines[\"bottom\"].set_color(\"white\")\n ax.spines[\"left\"].set_color(\"white\")\n ax.spines[\"right\"].set_color(\"white\")\n ax.spines[\"top\"].set_color(\"white\")\n\n for i, col in enumerate(df.columns):\n\n ax.plot(\n df[col].index,\n df[col].values,\n marker=\"o\",\n linestyle=linestyle[i],\n linewidth=6,\n markersize=30,\n color=SPEC_DICT[color][\"colors\"][i],\n label=df.columns[i],\n )\n\n # Flip y-axis.\n ax.axis([-0.1, 2.1, 1.2, -0.2])\n\n plt.yticks([0, 1], labels=[\"Rank 1\", \"Rank 2\"])\n plt.xticks(\n [0, 1, 2],\n labels=df.index.to_list(),\n )\n plt.xlabel(\"\")\n ax.tick_params(axis=\"both\", color=\"white\", pad=20)\n ax.legend(\n markerscale=0.3,\n labelspacing=0.8,\n handlelength=3,\n bbox_to_anchor=(0.45, 1.2),\n loc=\"upper center\",\n ncol=4,\n )\n\n fname = f\"{DIR_FIGURES}/fig-example-urn-ranks{SPEC_DICT[color]['file']}\"\n\n fig.savefig(fname)\n\n\ndef create_optimal_lambda_plot():\n \"\"\"Plot mean/max of risk function for range of lambda.\"\"\"\n\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n n = 50\n num_points = 20\n\n xmin, xmax = 0.6, 1\n ymin, ymax = 0.95, 1\n\n # Compute yvalues.\n xvals = np.linspace(xmin, xmax, num_points)\n yvals_bayes, yvals_maximin = [], []\n for lambda_ in xvals:\n yvals_bayes.append(risk_function(n, \"robust\", lambda_=lambda_).mean())\n yvals_maximin.append(risk_function(n, \"robust\", lambda_=lambda_).min())\n\n # Plot risk function for range of lambda.\n if color == \"colored\":\n color_id = 1\n else:\n color_id = 4\n ax.plot(\n xvals,\n yvals_bayes,\n label=\"Subjective Bayes\",\n color=SPEC_DICT[color][\"colors\"][color_id],\n )\n ax.plot(\n xvals,\n yvals_maximin,\n label=\"Maximin\",\n color=SPEC_DICT[color][\"colors\"][color_id],\n linestyle=\":\",\n )\n\n # Plot vertical lines for optimal lambda.\n lambda_bayes = pd.Series(yvals_bayes, index=xvals).idxmax()\n lambda_maximin = pd.Series(yvals_maximin, index=xvals).idxmax()\n plt.vlines(\n [lambda_bayes, lambda_maximin],\n ymin=ymin,\n ymax=[max(yvals_bayes), max(yvals_maximin)],\n linestyle=\"dashed\",\n color=\"k\",\n )\n\n # Set xticks and labels including optimal lambdas.\n ax.set_xticks([0.6, 0.7, 0.8, lambda_maximin, lambda_bayes, 1])\n ax.set_xticklabels(\n [\n 0.6,\n 0.7,\n 0.8,\n r\"$\\lambda^*_{\\mathrm{Maximin}}$\",\n r\"$\\lambda^*_{\\mathrm{Bayes}}$\",\n 1.0,\n ]\n )\n\n # Axis limits\n ax.set_xlabel(r\"$\\lambda$\")\n ax.set_xlim(xmin - 0.025, xmax)\n ax.set_ylim(ymin, ymax)\n ax.legend(ncol=2, loc=\"lower center\", bbox_to_anchor=(0.5, -0.4))\n ax.set_ylabel(\"Performance measure\")\n plt.ticklabel_format(axis=\"y\", style=\"sci\", scilimits=(0, 0), useMathText=True)\n\n fname = f\"{DIR_FIGURES}/fig-example-urn-optimal{SPEC_DICT[color]['file']}\"\n\n fig.savefig(fname)\n print(f\"Optimal lambda bayes: {lambda_bayes}\")\n print(f\"Optimal lambda maximin: {lambda_maximin}\")\n" }, { "alpha_fraction": 0.7730375528335571, "alphanum_fraction": 0.7798634767532349, "avg_line_length": 35.625, "blob_id": "b689f4fc3aeabcb61123ecbb1846ed67208e4de5", "content_id": "b3005b8d0ee9ba9f5c328d854f982f048cc4e13f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 586, "license_type": "permissive", "max_line_length": 127, "num_lines": 16, "path": "/README.md", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "# Robust bus replacement problem\n\nThis repository hosts our analysis of the robust bus replacement problem as documented in:\n\n> Blesch, M. & Eisenhauer, P. (2019). Robust investments under risk and ambiguity. *Unpublished Working Paper*, submitted.\n\n## Miscellaneous\n\nThere are several commands available to ease the workflow.\n\n* `execute-notebooks`, runs all notebooks in the repository\n\n* `update-repository`, updates the whole repository including all submodules\n\n\n[![Build Status](https://travis-ci.org/robustzurcher/analysis.svg?branch=master)](https://travis-ci.org/robustzurcher/analysis)\n" }, { "alpha_fraction": 0.48567771911621094, "alphanum_fraction": 0.5272843837738037, "avg_line_length": 30.2450008392334, "blob_id": "62e74945936134f8b65e651f5eac3b93e7af63c2", "content_id": "c1032ca1c61c2d5e14773ae4a1958dc0593b57d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6249, "license_type": "permissive", "max_line_length": 86, "num_lines": 200, "path": "/python/scripts_figures/ex_post/performance_plots.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import pickle as pkl\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom config import DIR_FIGURES\nfrom scipy.signal import savgol_filter\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import DICT_POLICIES_4292\nfrom scripts_figures.global_vals_funcs import NUM_PERIODS\nfrom scripts_figures.global_vals_funcs import OMEGA_GRID\nfrom scripts_figures.global_vals_funcs import SIM_RESULTS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\nGRIDSIZE = 1000\nNUM_POINTS = int(NUM_PERIODS / GRIDSIZE) + 1\n\n################################################################################\n# Convergence plot\n################################################################################\n\n\ndef get_decision_rule_df():\n v_exp_ml = np.full(\n NUM_POINTS, np.dot(DICT_POLICIES_4292[0.0][1], DICT_POLICIES_4292[0.0][0])[0]\n )\n\n v_disc_ml = pkl.load(open(SIM_RESULTS + \"result_ev_0.0_mat_0.95.pkl\", \"rb\"))[1]\n\n periods = np.arange(0, NUM_PERIODS + GRIDSIZE, GRIDSIZE)\n\n return pd.DataFrame(\n {\"months\": periods, \"disc_strategy\": v_disc_ml, \"exp_value\": v_exp_ml}\n )\n\n\ndef get_performance_decision_rules():\n print(\"The underlying transition matrix is the worst case given omega=0.95\")\n\n v_exp_ml = np.full(\n NUM_POINTS, np.dot(DICT_POLICIES_4292[0.0][1], DICT_POLICIES_4292[0.0][0])[0]\n )\n\n v_disc_ml = pkl.load(open(SIM_RESULTS + \"result_ev_0.0_mat_0.95.pkl\", \"rb\"))[1]\n\n periods = np.arange(0, NUM_PERIODS + GRIDSIZE, GRIDSIZE)\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n ax.set_ylabel(r\"Performance (in thousands)\")\n ax.set_xlabel(r\"Months (in thousands)\")\n\n # 'Discounted utility of otpimal strategy'\n ax.plot(\n periods,\n v_exp_ml,\n color=SPEC_DICT[color][\"colors\"][0],\n ls=SPEC_DICT[color][\"line\"][0],\n label=\"long-run expectation\",\n )\n ax.plot(\n periods,\n v_disc_ml,\n color=SPEC_DICT[color][\"colors\"][1],\n ls=SPEC_DICT[color][\"line\"][1],\n label=\"actual\",\n )\n ax.set_ylim([-60_000, 0])\n ax.set_yticks(np.arange(-60_000, 10_000, 10_000))\n ax.set_yticklabels(np.arange(-60, 10, 10))\n ax.set_xticks(np.arange(0, 120_000, 20_000))\n ax.set_xticklabels(np.arange(0, 120, 20))\n plt.xlim(right=100_000)\n ax.legend()\n fig.savefig(\n f\"{DIR_FIGURES}/\"\n f\"fig-application-performance-decision-rules{SPEC_DICT[color]['file']}\"\n )\n\n\n################################################################################\n# Performance plot\n################################################################################\n\n\ndef get_difference_df():\n\n nominal_costs = _performance_plot(0.0)\n robust_costs_50 = _performance_plot(0.5)\n robust_costs_95 = _performance_plot(0.95)\n\n diff_costs_95 = nominal_costs - robust_costs_95\n diff_costs_50 = nominal_costs - robust_costs_50\n\n print(\"The dataframe contains the difference for as-if - robust strategy.\")\n\n return pd.DataFrame(\n {\"omega\": OMEGA_GRID, \"robust_95\": diff_costs_95, \"robust_050\": diff_costs_50}\n )\n\n\ndef get_difference_plot():\n\n nominal_costs = _performance_plot(0.0)\n robust_costs_50 = _performance_plot(0.5)\n robust_costs_95 = _performance_plot(0.95)\n\n diff_costs_95 = nominal_costs - robust_costs_95\n diff_costs_50 = nominal_costs - robust_costs_50\n filter_95 = savgol_filter(diff_costs_95, 29, 3)\n filter_50 = savgol_filter(diff_costs_50, 29, 3)\n\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n\n ax.axhline(\n 0,\n 0.05,\n 1,\n color=SPEC_DICT[color][\"colors\"][0],\n ls=SPEC_DICT[color][\"line\"][2],\n label=\"as-if\",\n )\n\n ax.plot(\n OMEGA_GRID,\n filter_50,\n color=SPEC_DICT[color][\"colors\"][1],\n label=r\"robust $(\\omega = 0.50)$\",\n ls=SPEC_DICT[color][\"line\"][1],\n )\n\n ax.plot(\n OMEGA_GRID,\n filter_95,\n color=SPEC_DICT[color][\"colors\"][2],\n label=r\"robust $(\\omega = 0.95)$\",\n ls=SPEC_DICT[color][\"line\"][2],\n )\n\n ax.set_ylim([-400, 400])\n plt.xlim(left=-0.06, right=1)\n # ax.set_ylim([diff_costs_95[0], diff_costs_95[-1]])\n ax.set_ylabel(r\"$\\Delta$ Performance\")\n ax.set_xlabel(r\"$\\tilde{\\omega}$\")\n ax.legend()\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-difference{SPEC_DICT[color]['file']}\"\n )\n\n\n# def get_absolute_plot():\n#\n# nominal_costs = _performance_plot(0.0)\n# robust_costs_50 = _performance_plot(0.5)\n# robust_costs_95 = _performance_plot(0.95)\n#\n# for color in COLOR_OPTS:\n# fig, ax = plt.subplots(1, 1)\n#\n# ax.plot(\n# OMEGA_GRID,\n# nominal_costs,\n# color=SPEC_DICT[color][\"colors\"][0],\n# label=\"as-if\",\n# ls=SPEC_DICT[color][\"line\"][0],\n# )\n#\n# ax.plot(\n# OMEGA_GRID,\n# robust_costs_50,\n# color=SPEC_DICT[color][\"colors\"][1],\n# label=r\"robust $(\\omega = 0.50)$\",\n# ls=SPEC_DICT[color][\"line\"][1],\n# )\n#\n# ax.plot(\n# OMEGA_GRID,\n# robust_costs_95,\n# color=SPEC_DICT[color][\"colors\"][2],\n# label=r\"robust $(\\omega = 0.95)$\",\n# ls=SPEC_DICT[color][\"line\"][2],\n# )\n# ax.set_ylim([-54000, -47000])\n# # ax.set_ylim([diff_costs_95[0], diff_costs_95[-1]])\n# ax.set_ylabel(r\"$\\Delta$ Performance\")\n# ax.set_xlabel(r\"$\\omega$\")\n# ax.legend()\n# fig.savefig(\n# f\"{DIR_FIGURES}/fig-application-difference{SPEC_DICT[color]['file']}\"\n# )\n\n\ndef _performance_plot(sim_omega):\n\n costs = np.zeros(len(OMEGA_GRID))\n for j, omega in enumerate(OMEGA_GRID):\n file = SIM_RESULTS + f\"result_ev_{sim_omega}_mat_{omega}.pkl\"\n costs[j] = pkl.load(open(file, \"rb\"))[1][-1]\n\n return costs\n" }, { "alpha_fraction": 0.5679585933685303, "alphanum_fraction": 0.5853838920593262, "avg_line_length": 33.4327278137207, "blob_id": "27c8114d0de6e59d6f46756259bdb54cefdd2d0b", "content_id": "9bb613a2202e768ca126519961cf4f6e71b291ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9469, "license_type": "permissive", "max_line_length": 88, "num_lines": 275, "path": "/python/scripts_figures/ex_ante.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import pickle as pkl\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy.interpolate as interp\nfrom config import DATA_DIR\nfrom config import DIR_FIGURES\nfrom matplotlib import cm as CM\nfrom ruspy.estimation.estimation_transitions import create_transition_matrix\nfrom ruspy.model_code.cost_functions import calc_obs_costs\nfrom ruspy.model_code.cost_functions import lin_cost\nfrom ruspy.model_code.fix_point_alg import calc_fixp\nfrom scipy.signal import savgol_filter\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import COST_SCALE\nfrom scripts_figures.global_vals_funcs import DISC_FAC\nfrom scripts_figures.global_vals_funcs import NUM_STATES\nfrom scripts_figures.global_vals_funcs import PARAMS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\nfrom scripts_figures.global_vals_funcs import VAL_RESULTS\nfrom scripts_figures.global_vals_funcs import VAL_STRATS\n\n\nsamples = pkl.load(open(f\"{DATA_DIR}/samples.pkl\", \"rb\"))\nprob_grid = pkl.load(open(f\"{DATA_DIR}/grid.pkl\", \"rb\"))\nobs_costs = calc_obs_costs(NUM_STATES, lin_cost, PARAMS, COST_SCALE)\n\n# Settings for dataframe\nprob_colums = [\"p_0\", \"p_1\", \"p_2\"]\ntrue_prob_comuns = [\"p_0_true\", \"p_1_true\", \"p_2_true\"]\nstrat_cols = [0.0] + VAL_STRATS\n\n\ndef performance_dataframe():\n df = pd.DataFrame(\n data=None,\n index=pd.MultiIndex.from_product(\n [range(prob_grid.shape[0]), range(samples.shape[1])],\n names=[\"id_grid\", \"id_sample\"],\n ),\n columns=true_prob_comuns + prob_colums + list(VAL_STRATS) + [\"best\"],\n dtype=float,\n )\n\n for id_grid, gridpoint in enumerate(prob_grid):\n for id_sample, sample in enumerate(samples[id_grid, :, :]):\n for id_omega, omega in enumerate(VAL_STRATS):\n fname = f\"{VAL_RESULTS}grid_{id_grid}_sample_{id_sample}_{id_omega}.pkl\"\n df.loc[(id_grid, id_sample), omega] = pkl.load(open(fname, \"rb\"))\n\n df.loc[(id_grid, id_sample), prob_colums] = sample\n\n trans_mat_org = create_transition_matrix(NUM_STATES, gridpoint)\n\n ev_ml, _, _ = calc_fixp(trans_mat_org, obs_costs, DISC_FAC)\n\n df.loc[(id_grid, slice(None)), \"best\"] = ev_ml[0]\n\n df.loc[(id_grid, slice(None)), true_prob_comuns] = gridpoint\n return df\n\n\ndef print_generate_rankings(df_in, strategies, measures):\n df = df_in[strategies].mean(level=0)\n\n best_result = df_in.loc[(slice(None), 0), \"best\"].to_numpy()\n\n subjective_bayes_order = (\n df.mean(axis=0).sort_values(ascending=False).index.to_numpy()\n )\n print(df.mean(axis=0).sort_values(ascending=False))\n\n max_min_order = df.min().sort_values(ascending=False).index.to_numpy()\n print(df.min().sort_values(ascending=False))\n\n min_max_regret = (\n (df.subtract(best_result, axis=0) * -1)\n .max()\n .sort_values(ascending=True)\n .index.to_numpy()\n )\n print((df.subtract(best_result, axis=0) * -1).max().sort_values(ascending=True))\n\n print(\"The order of subjective belief is\", subjective_bayes_order)\n\n print(\"The order of max min is\", max_min_order)\n\n print(\"The order of min max regret is\", min_max_regret)\n\n df_rank = pd.DataFrame(data=None, index=measures, columns=strategies)\n\n for measure_name, measure_order in [\n (\"Subjective \\n Bayes\", subjective_bayes_order),\n (\"Minimax \\n \" \"regret\", min_max_regret),\n (\"Maximin\", max_min_order),\n ]:\n for pos, strat in enumerate(measure_order):\n df_rank.loc[measure_name, strat] = pos\n return df_rank\n\n\ndef create_ranking_graph(df):\n linestyle = [\"--\", \"-.\", \"-\", \":\"]\n\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(figsize=(8, 4))\n ax.spines[\"bottom\"].set_color(\"white\")\n ax.spines[\"left\"].set_color(\"white\")\n for i, col in enumerate(df.columns):\n if np.isclose(col, 0.0):\n label = \"as-if\"\n else:\n label = r\"robust ($\\omega$ = \" + f\"{col})\"\n\n ax.plot(\n df[col].index,\n df[col].values,\n marker=\"o\",\n linestyle=linestyle[i],\n linewidth=3,\n markersize=20,\n color=SPEC_DICT[color][\"colors\"][i],\n label=label,\n )\n\n # df[col].plot(**kwargs)\n # Flip y-axis.\n ax.set_xlim([-0.2, 2.1])\n ax.set_ylim([3.2, -0.8])\n\n plt.yticks(\n [0, 1, 2, 3],\n labels=[\"Rank 1\", \"Rank 2\", \"Rank 3\", \"Rank 4\"],\n )\n plt.xticks(\n [0, 1, 2],\n labels=df.index.to_list(),\n )\n plt.xlabel(\"\")\n ax.tick_params(axis=\"both\", color=\"white\", pad=20)\n ax.legend(\n markerscale=0.2,\n handlelength=1.5,\n # bbox_to_anchor=[-0.1, 1.1],\n loc=\"upper center\",\n ncol=4,\n )\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-validation-\"\n f\"ranking-plot{SPEC_DICT[color]['file']}.png\"\n )\n\n\ndef plot_performance_difference_matrix(df, val_strat, one_dim_interpol_grid):\n z = generate_plot_matrix(df, val_strat, one_dim_interpol_grid)\n max_scale = len(one_dim_interpol_grid)\n z_2 = np.where(z > 0, 1, z)\n z_2 = np.where(z_2 < 0, -1, z_2)\n z_2 = np.where(z_2 == 0, 2, z_2)\n fig, ax = plt.subplots()\n ax.set_ylim([-0.01, max_scale])\n ax.set_xlim([-0.01, max_scale])\n t1 = plt.Polygon(\n np.array([[0, max_scale], [max_scale, 0]]), closed=False, fill=False\n )\n plt.gca().add_patch(t1)\n ax.set_ylabel(r\"10,000 miles\")\n ax.set_xlabel(r\"5,000 miles\")\n # ax.spy(z, origin=\"lower\")\n ticks_space = max_scale / 5\n plt.xticks(\n np.arange(0, max_scale + ticks_space, ticks_space),\n np.arange(0, 1.2, 0.2).round(2),\n )\n plt.yticks(\n np.arange(0, max_scale + ticks_space, ticks_space),\n np.arange(0, 1.2, 0.2).round(2),\n )\n cmap = CM.get_cmap(\"Greys_r\", 3)\n # print(vars(cmap))\n\n plt.imshow(z_2, cmap=cmap, vmax=2.1, vmin=-1.1)\n # plt.colorbar()\n\n ax.yaxis.get_major_ticks()[0].label1.set_visible(False)\n\n fig.savefig(f\"{DIR_FIGURES}/fig-application-validation-contour-plot-sw\")\n\n\ndef generate_plot_matrix(df_in, val_strat, one_dim_interpol_grid):\n\n eval_omega = [0.0, val_strat]\n df = df_in.loc[:, eval_omega].mean(level=0)\n interpol_grid = create_prob_grid(one_dim_interpol_grid, 3)\n interpol_res = {}\n for omega in eval_omega:\n interpol_res[omega] = interp.griddata(\n prob_grid[:, :2], df.loc[:, omega], interpol_grid[:, :2], method=\"linear\"\n )\n z = np.zeros((len(one_dim_interpol_grid), len(one_dim_interpol_grid)), dtype=float)\n for id_prob, gridpoint in enumerate(interpol_grid):\n\n id_z_x = np.where(np.isclose(one_dim_interpol_grid, gridpoint[0]))[0][0]\n id_z_y = np.where(np.isclose(one_dim_interpol_grid, gridpoint[1]))[0][0]\n\n z[id_z_y, id_z_x] = (\n interpol_res[0.0][id_prob] - interpol_res[val_strat][id_prob]\n )\n return z\n\n\ndef create_prob_grid(one_dim_grid, num_dims):\n # The last column will be added in the end\n num_dims -= 1\n grid = np.array(np.meshgrid(*[one_dim_grid] * num_dims)).T.reshape(-1, num_dims)\n # Delete points which has probability larger than one\n grid = grid[np.sum(grid, axis=1) < 1]\n # Add last column\n grid = np.append(grid, (1 - np.sum(grid, axis=1)).reshape(len(grid), 1), axis=1)\n return grid\n\n\ndef filter_normalize(performance):\n filtered = savgol_filter(performance, 37, 3)\n moved = filtered - np.min(filtered)\n return moved / np.max(moved)\n\n\ndef get_optimal_omega_maximin(df):\n df_meaned = df[list(VAL_STRATS)].mean(level=0)\n omega_vals = df_meaned.loc[:, list(VAL_STRATS)].to_numpy()\n omega_eval_grid = np.arange(0, 1, 0.01)\n omega_interpol_vals = np.zeros((prob_grid.shape[0], len(omega_eval_grid)))\n for id_grid, _ in enumerate(prob_grid):\n omega_interpol_vals[id_grid, :] = interp.griddata(\n VAL_STRATS, omega_vals[id_grid, :], omega_eval_grid, method=\"linear\"\n )\n\n omegas_min = np.min(omega_interpol_vals, axis=0)\n normalized_min = filter_normalize(omegas_min)\n omega_max_min = omega_eval_grid[np.argmax(normalized_min)]\n for color in COLOR_OPTS:\n fig, ax = plt.subplots(1, 1)\n ax.plot(\n omega_eval_grid,\n normalized_min,\n color=SPEC_DICT[color][\"colors\"][0],\n label=\"minimum performance\",\n )\n plt.vlines(\n omega_max_min,\n ymin=0,\n ymax=np.max(normalized_min),\n linestyle=\"dashed\",\n color=\"k\",\n )\n\n ax.set_ylabel(r\"Normalized performance\")\n ax.set_xlabel(r\"$\\omega$\")\n # ax.legend()\n x = np.arange(0, 1.2, 0.2).round(1)\n x_labels = [str(num) for num in list(x)]\n x_labels[2] = r\"$\\omega^*$\"\n x[x == 0.4] = omega_max_min\n ax.set_xticks(x)\n ax.set_xticklabels(x_labels)\n ax.tick_params(axis=\"x\", which=\"major\", pad=5)\n ax.tick_params(axis=\"x\", which=\"minor\", pad=0.5)\n ax.set_ylim([0, 1.01])\n ax.set_xlim(right=1)\n fig.savefig(\n f\"{DIR_FIGURES}/fig-application-validation-optimal-omega\"\n f\"{SPEC_DICT[color]['file']}\"\n )\n" }, { "alpha_fraction": 0.5335170030593872, "alphanum_fraction": 0.5904499292373657, "avg_line_length": 23.75, "blob_id": "da17a8ccb49ffc9459ec988da3545e0baa13ac44", "content_id": "db67b1d049d85151fb9d64dcd6164d2b1f57fe23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2178, "license_type": "permissive", "max_line_length": 82, "num_lines": 88, "path": "/python/scripts_figures/global_vals_funcs.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import os\nimport pickle as pkl\nimport shutil\nfrom pathlib import Path\nfrom zipfile import ZipFile\n\nimport numpy as np\nfrom config import ROOT_DIR\n\n\nOMEGA_GRID = np.arange(0, 1, 0.01).round(2)\nVAL_STRATS = np.arange(0, 1.1, 0.1).round(2)\nVAL_STRATS[-1] -= 0.01\n\nNUM_STATES = 60\nDISC_FAC = 0.9999\nCOST_SCALE = 0.001\nPARAMS = np.array([50, 400])\nNUM_BUSES = 200\nBIN_SIZE = 5 # in thousand\nNUM_PERIODS = 100_000\nFIXP_DICT_4292 = f\"{ROOT_DIR}/pre_processed_data/fixp_results_4292.pkl\"\nFIXP_DICT_2223 = f\"{ROOT_DIR}/pre_processed_data/fixp_results_2223.pkl\"\nSIM_RESULTS = f\"{ROOT_DIR}/pre_processed_data/sim_results/\"\nVAL_RESULTS = f\"{ROOT_DIR}/pre_processed_data/val_results/\"\n\nCOLOR_OPTS = [\"colored\", \"black_white\"]\n\n# jet_color_map = [\n# \"#1f77b4\",\n# \"#ff7f0e\",\n# \"#2ca02c\",\n# \"#d62728\",\n# \"#9467bd\",\n# \"#8c564b\",\n# \"#e377c2\",\n# \"#7f7f7f\",\n# \"#bcbd22\",\n# \"#17becf\",\n# ]\n\nSPEC_DICT = {\n \"colored\": {\n \"colors\": [\"tab:blue\", \"tab:orange\", \"tab:green\", \"tab:red\"],\n \"line\": [\"-\"] * 3,\n \"hatch\": [\"\"] * 3,\n \"file\": \"\",\n },\n \"black_white\": {\n \"colors\": [\"#808080\", \"#d3d3d3\", \"#A9A9A9\", \"#C0C0C0\", \"k\"],\n \"line\": [\"-\", \"--\", \":\"],\n \"hatch\": [\"\", \"OOO\", \"///\"],\n \"file\": \"-sw\",\n },\n}\n\n\ndef extract_zips():\n if os.path.exists(SIM_RESULTS):\n shutil.rmtree(SIM_RESULTS)\n os.makedirs(f\"{ROOT_DIR}/pre_processed_data/sim_results\")\n ZipFile(f\"{ROOT_DIR}/pre_processed_data/simulation_results.zip\").extractall(\n SIM_RESULTS\n )\n\n if os.path.exists(VAL_RESULTS):\n shutil.rmtree(VAL_RESULTS)\n ZipFile(f\"{ROOT_DIR}/pre_processed_data/validation_results.zip\").extractall(\n VAL_RESULTS\n )\n\n\ndef get_file(fname):\n if not isinstance(fname, Path):\n fname = Path(fname)\n\n fname_pkl = Path(fname).with_suffix(\".pkl\")\n\n if not os.path.exists(fname_pkl):\n ZipFile(f\"{ROOT_DIR}/pre_processed_data/solution_results.zip\").extractall(\n f\"{ROOT_DIR}/pre_processed_data/\"\n )\n\n return pkl.load(open(fname_pkl, \"rb\"))\n\n\nDICT_POLICIES_4292 = get_file(FIXP_DICT_4292)\nDICT_POLICIES_2223 = get_file(FIXP_DICT_2223)\n" }, { "alpha_fraction": 0.6075494289398193, "alphanum_fraction": 0.6261234283447266, "avg_line_length": 33.77083206176758, "blob_id": "cf6ea3286a112436394ac339cdd7b0fa1cf1bbda", "content_id": "beac09112cbb26628b1dbff9557f8e0ea79020ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1669, "license_type": "permissive", "max_line_length": 92, "num_lines": 48, "path": "/python/scripts_figures/ex_post/observations.py", "repo_name": "robustzurcher/analysis", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom config import DIR_FIGURES\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\n\ndef df_num_obs(bin_size, init_dict, num_obs_per_state):\n max_state = num_obs_per_state.index.max()\n num_steps = int(bin_size / init_dict[\"binsize\"])\n num_bins = int(max_state / num_steps)\n hist_data = np.zeros(num_bins)\n for i in range(num_bins):\n hist_data[i] = np.sum(num_obs_per_state[i * num_steps : (i + 1) * num_steps])\n return pd.DataFrame(\n {\"Num_Obs\": hist_data}, index=np.arange(1, len(hist_data) + 1) * bin_size\n )\n\n\ndef get_number_observations(bin_size, init_dict, num_obs_per_state):\n\n max_state = num_obs_per_state.index.max()\n num_steps = int(bin_size / init_dict[\"binsize\"])\n num_bins = int(max_state / num_steps)\n hist_data = np.zeros(num_bins)\n for i in range(num_bins):\n hist_data[i] = np.sum(num_obs_per_state[i * num_steps : (i + 1) * num_steps])\n\n scale = 10\n mileage = np.arange(num_bins) * scale\n width = 0.75 * scale\n for color in COLOR_OPTS:\n\n fig, ax = plt.subplots(1, 1)\n ax.set_ylabel(r\"Number of observations\")\n ax.set_xlabel(r\"Milage (in thousands)\")\n\n cl = SPEC_DICT[color][\"colors\"][0]\n ax.bar(mileage, hist_data, width, align=\"edge\", color=cl)\n ax.set_xticks(range(0, 450, 50))\n ax.set_xticklabels(range(0, 450, 50))\n ax.set_ylim([0, 250])\n plt.xlim(right=400)\n\n plt.savefig(\n f\"{DIR_FIGURES}/fig-introduction-observations-mileage{SPEC_DICT[color]['file']}\"\n )\n" } ]
14
NotRithik/DoracakeDiscordBot
https://github.com/NotRithik/DoracakeDiscordBot
e91267926a314f6a6326f1a0346d1718da782d10
651f40ac37aa2a5e19471351a2489fa94c641f91
49e234d8460d67b649f20524f29b8a545c9aa2ee
refs/heads/main
2023-04-27T00:01:04.999307
2021-05-28T21:28:41
2021-05-28T21:28:41
370,700,650
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5445815920829773, "alphanum_fraction": 0.5497256517410278, "avg_line_length": 32.922157287597656, "blob_id": "1d39642d5d8eb1df844cfe3f27bcf7db155f1a03", "content_id": "e0dcb62ff7c09609653d54bff7077550381686f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5832, "license_type": "no_license", "max_line_length": 107, "num_lines": 167, "path": "/src/main.py", "repo_name": "NotRithik/DoracakeDiscordBot", "src_encoding": "UTF-8", "text": "import discord\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands.bot import Bot\r\nfrom discord.ext.commands.bot import when_mentioned_or\r\nimport random\r\n\r\napi_key = 'API key replaced :3'\r\nbot_prefixes = ['dora ', 'Dora ', 'dora', 'Dora']\r\ngreet_strings = ['Hello {0}!', 'Hey {0}!',\r\n 'o/ {0}', 'oi {0}', 'Yo {0}!', \"Hi {0}!\"]\r\n\r\ngaali_strings_hindi = ['string1', 'string2', 'string3']\r\n\r\nroast_strings = ['{0} is the role model of what not to be',\r\n 'Kids, study well if you dont want to end up like {0}!',\r\n 'Too bad, you can\\'t photoshop an ugly personality (like yours), {0}']\r\n\r\nuse_help_string = 'Type \\'dora help\\' to get a list of stuff I can do!'\r\n\r\nhelp_string = 'Say hi and I\\'ll reply to you!\\n' + \\\r\n '\\\"dora gaali de\\\" to see some Hindi gaalis\\n' + \\\r\n '\\\"dora roast <@user>\\\" to roast someone'\r\n\r\nreply_greet_strings = [greeting.replace('{0}', '').replace('!', '').strip().lower()\r\n for greeting in greet_strings]\r\n\r\nmuted = []\r\n\r\nowner_id = 'OWNER_ID_PLACEHOLDER'\r\n\r\nprint(\"Starting Doracake...\")\r\n\r\nbot = discord.ext.commands.Bot(command_prefix=(when_mentioned_or(*bot_prefixes)),\r\n description=use_help_string,\r\n help_command=None,\r\n case_insensitive=True)\r\n\r\n\r\[email protected]\r\nasync def on_ready():\r\n print('Logged in as user {0}'.format(bot.user))\r\n await bot.change_presence(status=discord.Status.online, activity=discord.Game(\"dora help\"))\r\n\r\n\r\[email protected]\r\nasync def on_message(message):\r\n\r\n # Check if the message was not sent by a bot\r\n # if(True):\r\n\r\n if(muted.__contains__(message.author.id)):\r\n await message.delete()\r\n\r\n if (not message.author.bot):\r\n\r\n message_first_word = message.content.split(' ')[0].lower()\r\n\r\n # Check if the first word of the input is a string from reply_greet_strings\r\n if (message_first_word.startswith(tuple(reply_greet_strings)) and\r\n len(message.content) > 1):\r\n\r\n # Check if there's a space, and hence more than one word\r\n if (message.content.count(' ') > 0):\r\n\r\n # Reply to the author of the message, only if the second word (the one immediately after hi\r\n # is the bot prefix)\r\n if (message.content.split(' ')[1].lower().startswith(tuple(bot_prefixes))):\r\n await message.channel.send(random.choice(greet_strings)\r\n .format('<@'+str(message.author.id)+'>'))\r\n else:\r\n await message.channel.send(random.choice(greet_strings)\r\n .format('<@'+str(message.author.id)+'>'))\r\n\r\n elif(message_first_word == 'f'):\r\n await message.channel.send('F')\r\n\r\n elif(message_first_word == 'oof'):\r\n await message.channel.send('big oof')\r\n\r\n elif(message_first_word == 'xd'):\r\n await message.channel.send('lmao')\r\n\r\n elif(message_first_word == 'lol'):\r\n await message.channel.send('LOL xD')\r\n\r\n elif(message_first_word == 'lmao'):\r\n await message.channel.send('looooooooool')\r\n\r\n await bot.process_commands(message)\r\n\r\n\r\[email protected](case_insensitive=True) # dora gaali de\r\nasync def gaali(ctx, *args):\r\n if(len(args) > 0 and args[0].lower() == 'de'):\r\n await ctx.message.channel.send(random.choice(gaali_strings_hindi))\r\n else:\r\n await ctx.message.channel.send('AHEM, gaali khayega tu <@{0}>'.\r\n format(ctx.message.author.id))\r\n\r\n\r\n@ bot.command(case_insensitve=True) # dora roast <@person>\r\nasync def roast(ctx, *args):\r\n if (not len(args) > 0):\r\n await ctx.message.channel.send(random.choice(roast_strings).\r\n format('<@'+str(ctx.message.author.id)+'>'))\r\n return\r\n\r\n if (args[0] == \"@here\" or args[0] == \"@everyone\"):\r\n await ctx.message.channel.send('Nope. you cannot tag everyone/here. Not happening today.')\r\n return\r\n\r\n try:\r\n await ctx.message.channel.send(random.choice(roast_strings).\r\n format('<@'+str(args[0].id)+'>'))\r\n except:\r\n await ctx.message.channel.send('Tag someone next time, bruh')\r\n\r\n\r\n@ bot.command(aliases=reply_greet_strings)\r\nasync def greet(ctx, *args):\r\n if(len(args) > 0):\r\n if(args[0] != \"@everyone\" and args[0] != \"@here\"):\r\n try:\r\n await ctx.message.channel.send(random.choice(greet_strings)\r\n .format(args[0]))\r\n except:\r\n await ctx.message.channel.send(random.choice(greet_strings)\r\n .format('<@'+str(ctx.message.author.id)+'>'))\r\n\r\n else:\r\n await ctx.message.channel.send(random.choice(greet_strings)\r\n .format('<@'+str(ctx.message.author.id)+'>'))\r\n\r\n\r\n@ bot.command()\r\nasync def command_not_found(ctx):\r\n await ctx.message.channel.send('Unknown command! Try \\'dora help\\'')\r\n\r\n\r\n@ bot.command()\r\nasync def mute(ctx, user: discord.User):\r\n print(muted)\r\n\r\n try:\r\n if (user.id == owner_id):\r\n return\r\n muted.append(user.id)\r\n except:\r\n await ctx.message.channel.send('Tag someone properly next time.')\r\n\r\n await ctx.message.delete()\r\n print(muted)\r\n\r\n\r\n@ bot.command()\r\nasync def fork(ctx, user: discord.User):\r\n try:\r\n if (user.id == owner_id):\r\n return\r\n muted.remove(user.id)\r\n except:\r\n await ctx.message.channel.send('Tag someone properly next time.')\r\n\r\n await ctx.message.delete()\r\n print(muted)\r\n\r\nbot.run(api_key)\r\n" }, { "alpha_fraction": 0.7960526347160339, "alphanum_fraction": 0.7960526347160339, "avg_line_length": 75, "blob_id": "95d44d46be030f530612930795ebcbb875f5c7fd", "content_id": "cd010a797dde78bc56850d91bb65bcca78c06d63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 152, "license_type": "no_license", "max_line_length": 130, "num_lines": 2, "path": "/README.md", "repo_name": "NotRithik/DoracakeDiscordBot", "src_encoding": "UTF-8", "text": "# DoracakeDiscordBot\nThis is a bot I made just to learn and practice some parts of python. It is very unreadable and doesn't use good coding practices.\n" } ]
2
saumikn/swiss-by-api
https://github.com/saumikn/swiss-by-api
aebd0de6d6b8f92f7936d98aa21cb74ed8009bf7
2a4ba67518cac3521c91ab28d670bd5500d8657c
dfa0c36e77bc96411225cbc32287c30c46b8576a
refs/heads/master
2022-10-07T06:10:31.881806
2020-06-10T01:28:53
2020-06-10T01:28:53
271,147,052
4
0
null
null
null
null
null
[ { "alpha_fraction": 0.5177948474884033, "alphanum_fraction": 0.5324494242668152, "avg_line_length": 28.04729652404785, "blob_id": "9db1ecee1b775d7313eb81c8a9319caffe3dfa4a", "content_id": "3c901da8bca127eff5cf4e85f083e42e68e4cc46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4299, "license_type": "no_license", "max_line_length": 115, "num_lines": 148, "path": "/arena.py", "repo_name": "saumikn/swiss-by-api", "src_encoding": "UTF-8", "text": "import requests\nimport logic\nimport json\nimport sys\n\nplayers = logic.read_player_key()\nuscf_key = logic.read_player_key(k=1,v=2)\nname_key = logic.read_player_key(k=1, v=3)\n\ndef get_game_winner(game_response):\n if 'winner' not in game_response:\n return '0.5-0.5'\n return '1-0' if game_response['winner'] == 'white' else '0-1'\n\ndef get_results(tournament_id):\n headers = {'Accept': 'application/x-ndjson'}\n response = requests.get(f'https://lichess.org/api/{tournament_id}/games', headers=headers)\n\n results = []\n for line in response.iter_lines():\n line = line.decode('utf-8')\n line = json.loads(line)\n\n white = line['players']['white']['user']['id']\n black = line['players']['black']['user']['id']\n\n if white in uscf_key and uscf_key[white].isnumeric() and black in uscf_key and uscf_key[black].isnumeric():\n result = get_game_winner(line)\n length = len(line['moves'].split())\n date = line['createdAt']\n if length > 1:\n results.append([white,black,result,date])\n if white not in uscf_key:\n print(white)\n if black not in uscf_key:\n print(black)\n \n results.sort(key=lambda x:x[3])\n results = [r[0:3] for r in results]\n return results\n\ndef get_players(results):\n players = set()\n for result in results:\n players.add(result[0])\n players.add(result[1])\n \n pruned_players = []\n for p in players:\n if p not in uscf_key:\n print(f'{p} is missing')\n continue\n if uscf_key[p].isnumeric():\n pruned_players.append(p)\n else:\n print(f'{p} is nonnumeric')\n return pruned_players\n\ndef get_xtable(players):\n xtable = []\n for p in players:\n xtable.append([p, [''] * 100])\n return xtable\n\ndef get_indexes(players, xtable):\n indexes = dict()\n for p in players:\n for i,x in enumerate(xtable):\n if p == x[0]:\n indexes[p]=i\n break\n return indexes\n\ndef add_result(xtable, result, indexes):\n w_i = indexes[result[0]]\n b_i = indexes[result[1]]\n if result[2] == '0.5-0.5':\n w_r = f'D{b_i+1}W'\n b_r = f'D{w_i+1}B'\n elif result[2] == '1-0':\n w_r = f'W{b_i+1}W'\n b_r = f'L{w_i+1}B'\n elif result[2] == '0-1':\n w_r = f'L{b_i+1}W'\n b_r = f'W{w_i+1}B'\n else:\n w_r = f'ERROR'\n b_r = f'ERROR'\n\n w = xtable[w_i][1]\n b = xtable[b_i][1]\n\n for i in range(len(xtable)): \n if w[i] == '' and b[i] == '':\n xtable[w_i][1][i] = w_r\n xtable[b_i][1][i] = b_r\n return xtable\n \n print(\"shouldn't get here\")\n return xtable\n\ndef add_results(xtable, results, indexes):\n for result in results:\n xtable = add_result(xtable, result, indexes)\n\n last = 0\n for _, games in xtable:\n for i,g in enumerate(games):\n if g != '':\n last = max(last,i)\n \n for i,(players, games) in enumerate(xtable):\n games = games[:last+1]\n for j,g in enumerate(games):\n if g == '':\n games[j] = 'U--'\n xtable[i] = [players,games]\n return xtable\n\ndef write_xtable(xtable, output_file='xtable.csv'):\n with open(output_file, 'w+') as f:\n header = 'Number,Rk,Fed,Title,Username,Name'\n for i in range(len(xtable[0][1])):\n header += f',RND{i+1}'\n header += ',Score,SB'\n print(header, file=f)\n for i,row in enumerate(xtable):\n # row = f'{row[0]},{name_key[row[0]]},{uscf_key[row[0]]},' + ','.join(row[1])\n row = f'{i+1},{i+1},,,{row[0]},{name_key[row[0]]},' + ','.join(row[1])\n print(row, file=f)\n\n\nif __name__ == '__main__':\n if (len(sys.argv) < 2):\n print('Missing URL')\n else:\n tournament_url = sys.argv[1].split('lichess.org/')[1]\n results = get_results(tournament_url)\n # results = get_results('swiss/wPodHVni')\n players = get_players(results)\n xtable = get_xtable(players)\n indexes = get_indexes(players, xtable)\n xtable = add_results(xtable, results, indexes)\n write_xtable(xtable)\n\n\n# player_key = logic.read_player_key()\n# print(player_key)\n" }, { "alpha_fraction": 0.5882724523544312, "alphanum_fraction": 0.5973713994026184, "avg_line_length": 34.0177001953125, "blob_id": "caf8cd36cdabee9ce08d1a44a9143c6bd8c22d96", "content_id": "05ffc5d45dbc784dfd9e560bce2b4c287d9c40d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7915, "license_type": "no_license", "max_line_length": 113, "num_lines": 226, "path": "/logic.py", "repo_name": "saumikn/swiss-by-api", "src_encoding": "UTF-8", "text": "import requests\nimport csv\nimport sheets\nimport json\nimport main\nimport time\n\nclass Pairing:\n def __init__(self, cell, white, black, gameId, status='created',result='',link=''):\n self.cell = cell\n self.white = white\n self.black = black\n # self.white = f'=hyperlink(\"https://lichess.org/{gameId}?color=white\", \"{white}\")'\n # self.black = f'=hyperlink(\"https://lichess.org/{gameId}?color=black\", \"{black}\")'\n self.gameId = gameId\n self.status = status\n self.result = result\n self.link = link\n\n def __str__(self):\n return ','.join([self.cell, self.white, self.black, self.gameId, self.status, self.result, self.link])\n\ndef setup_match_sheets(cell, white, black, gameId):\n token = main.token\n players = read_player_key()\n\n headers = {'Authorization': f'Bearer {token}'}\n if white not in players or black not in players:\n print(f'Error with {white} - {black}')\n\n return Pairing(cell, white, black, gameId)\n\ndef setup_pairings_sheets(cell, pairing_file, game_id_file):\n pairing_names = convert_swiss_sys(pairing_file)\n game_ids = read_game_ids(game_id_file)\n confirmation = input(f'Are you sure you want to start {len(pairing_names)} matches? Enter \"y\" to continue: ')\n if confirmation != 'y':\n return\n pairings = []\n\n for i in range(len(pairing_names)):\n white = pairing_names[i][0]\n black = pairing_names[i][1]\n gameid = game_ids[i].strip()\n cell = cell[0] + str(int(cell[1:])+1)\n if black == '1 ' or black == '½ ':\n pairings.append(Pairing(cell=cell, gameId='', white=white, result=black, black='BYE'))\n continue\n pairings.append(setup_match_sheets(cell, white, black, gameid))\n\n for p in pairings:\n if p:\n print(p.white)\n sheets.update_pairing(p)\n return pairings\n\ndef setup_match_lichess(cell, white, black, gameid):\n token = main.token\n players = read_player_key()\n headers = {'Authorization': f'Bearer {token}'}\n white = white.lower()\n black = black.lower()\n if white not in players or black not in players:\n print(f'Error with {white} - {black}')\n return Pairing(cell,white,black,'ERROR', status='ERROR',result='ERROR')\n whiteId = players[white]\n blackId = players[black]\n\n urlWhite = f'https://lichess.org/{gameid}?color=white'\n urlBlack = f'https://lichess.org/{gameid}?color=black'\n\n dataW = {'text':f'Please click on the link to start your game: {urlWhite}'}\n response = requests.post(f'https://lichess.org/inbox/{whiteId}', data=dataW, headers=headers)\n\n dataB = {'text':f'Please click on the link to start your game: {urlBlack}'}\n response = requests.post(f'https://lichess.org/inbox/{blackId}', data=dataB, headers=headers)\n return Pairing(cell, white, black, gameid) \n\ndef setup_pairings_lichess(cell, pairing_file, game_id_file):\n pairing_names = convert_swiss_sys(pairing_file)\n game_ids = read_game_ids(game_id_file)\n confirmation = input(f'Are you sure you want to start {len(pairing_names)} matches? Enter \"y\" to continue: ')\n if confirmation != 'y':\n return\n pairings = []\n\n for i in range(len(pairing_names)):\n white = pairing_names[i][0]\n black = pairing_names[i][1]\n gameid = game_ids[i].strip()\n cell = cell[0] + str(int(cell[1:])+1)\n if black == '1 ' or black == '½ ':\n pairings.append(Pairing(cell=cell, gameId='', white=white, result=black, black='BYE'))\n continue\n pairings.append(setup_match_lichess(cell, white, black, gameid))\n\n for p in pairings:\n if p:\n print(p.white)\n sheets.update_pairing(p)\n return pairings\n\n\ndef parse_event(event, pairing_objs='pairing_objs.csv'):\n players = read_player_key()\n\n event = event.decode('utf-8')\n if (event == ''):\n print('Empty Event')\n return\n event = json.loads(event)\n\n pairings = read_pairings(pairing_objs)\n gameId = event['id']\n status = event['status']\n white = event['players']['white']['userId']\n black = event['players']['black']['userId']\n for p in pairings:\n if p.white not in players or p.black not in players:\n # print(f'{p.white} vs {p.black} had an error')\n continue\n pWhite = players[p.white].lower()\n pBlack = players[p.black].lower()\n if gameId == p.gameId:\n p.result = get_result(gameId, status)\n p.link = get_link(gameId, status)\n sheets.update_pairing(p)\n if pWhite == white and pBlack == black and p.result in ['','0F-0F']:\n p.result = get_result(gameId, status)\n p.link = get_link(gameId, status)\n sheets.update_pairing(p)\n write_pairings(pairings, pairing_objs)\n\ndef get_result(gameId, status):\n if status in [10,20,60]:\n return ''\n if status in [25,37]:\n return '0F-0F'\n if status in [32,34]:\n return '0.5-0.5'\n if status in [30,31,33,35]:\n headers = {'Accept': 'application/json'}\n response = requests.get(f'https://lichess.org/game/export/{gameId}', headers=headers)\n if 'winner' not in response.json():\n return '0.5-0.5'\n return '1-0' if response.json()['winner'] == 'white' else '0-1'\n if status in [36]:\n headers = {'Accept': 'application/json'}\n response = requests.get(f'https://lichess.org/game/export/{gameId}', headers=headers)\n if 'winner' not in response.json():\n print(\"shouldn't get here...\")\n return '0.5-0.5'\n return '1F-0F' if response.json()['winner'] == 'white' else '0F-1F'\n\ndef get_link(gameId, status):\n if status == 10:\n return ''\n return f'https://lichess.org/{gameId}'\n\ndef convert_swiss_sys(pairing_file):\n pairings = []\n with open(pairing_file, encoding='utf-8-sig') as f:\n reader = csv.reader(f, delimiter='\\t')\n next(reader)\n next(reader)\n for bd,res1,white,res2,black in reader:\n if black.strip() == 'BYE':\n pairings.append([white,res1])\n else:\n pairings.append([white,black])\n return pairings\n\n\ndef read_game_ids(game_id_file):\n with open(game_id_file) as f:\n return f.readlines()\n\ndef start_stream():\n players = read_player_key()\n data = ','.join(set(players.values()))\n game_stream = requests.post(\"https://lichess.org/api/stream/games-by-users\", data=data, stream=True)\n return game_stream\n\n\n\n## Generic IO Funtions\n\ndef read_pairings(pairing_file):\n pairings = []\n with open(pairing_file, 'r') as f:\n reader = csv.reader(f)\n for (cell,white,black,gameId,status,result,link) in reader:\n pairings.append(Pairing(cell,white,black,gameId,status,result,link))\n return pairings\n\ndef write_pairings(pairings, file):\n ## Change this to 'a+' in order to append instead of overwrite!\n with open(file, 'w+') as f:\n for p in pairings:\n print(p, file=f)\n\ndef read_player_key(player_file='data.csv', k=0, v=3, output=False):\n players = dict()\n with open(player_file, 'r') as f:\n reader = csv.reader(f)\n for row in reader:\n if row[k] == '' or row[v] == '' or len(row) <= max(k,v):\n if output:\n print(f'Missing {row[0]}')\n continue\n players[row[k].lower()] = row[v]\n return players\n\ndef get_paired_players(pairings):\n player_key = read_player_key()\n paired_players = []\n for p in pairings:\n if p.white in player_key:\n paired_players.append(player_key[p.white])\n else:\n print(f'No username for {p.white}')\n if p.black in player_key:\n paired_players.append(player_key[p.black])\n else:\n print(f'No username for {p.black}')\n return paired_players" }, { "alpha_fraction": 0.7401685118675232, "alphanum_fraction": 0.7528089880943298, "avg_line_length": 46.488887786865234, "blob_id": "15287665a5e757712c4d9c547d8b6e27b54f0a8c", "content_id": "e9a15f0921d2fa58005b376b3e653aa50476c8a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2136, "license_type": "no_license", "max_line_length": 209, "num_lines": 45, "path": "/README.md", "repo_name": "saumikn/swiss-by-api", "src_encoding": "UTF-8", "text": "# Option 1\n**Converting Lichess Swiss/Arena to SwissSys Crosstable**\n\n1. Get the URL of the tournament: For example, an arena might have a URL https://lichess.org/tournament/vAT26cQv, and a swiss might have a URL https://lichess.org/swiss/E6PijXZ4\n\n2. Run `python arena.py {url}`\n\n3. After you have run this code, a file called xtable.csv will be created. Open the file in SwissSys 10.\n\n4. Edit the file data.csv to include the details of all the players in the tournament. You need their lichess username, USCF ID, and Name, but you don't need the timestamp.\n\n5. Import data.csv into SwissSys. If you need help with this, there is a video tutorial at https://new.uschess.org/rules/swisssys-feature-helping-chess-com-us-chess-rated-events/\n\n\n\n# Option 2\n**Running using SwissSys (Much more work required, but allows complete control over pairings, just like an OTB tournament)**\n\n## Do this once\n\n1. Follow Steps 1 and 2 here: https://developers.google.com/sheets/api/quickstart/python\n\n2. Run `python sheets.py` to save your Google Sheets credentials into `token.pickle`. You will only need to do this once\n\n3. Generate a personal lichess access token at https://lichess.org/account/oauth/token/create \n\n## Do this at the beginning of the tournament\n\n1. Create a new Google Sheet at https://sheets.google.com. Note the spreedsheet id, which you can find in the URL of your new Google Sheet at https://docs.google.com/spreadsheets/d/**spreadsheetId**/edit#gid=0\n\n2. make a `.env` file with the following contents:\n ```\n LICHESS_TOKEN=\"{lichess token}\"\n GOOGLE_SHEET_ID=\"{spreadsheet id}\"\n GOOGLE_SHEET_NAME=\"{sheet name}\"\n ```\n The Sheet Name will be the name of the tab you want to post pairings go.\n\n## Tournament Use\n\n2. For each section in the tournament, copy and paste the pairings from SwissSys into a seperate file.\n\n3. Run main.py with the section pairing paths as arguments. For example: `python main.py -start /pairings/section1 /pairings/section2 /pairings/section3`\n\n4. If your network disconnects during the middle of the round, and you want to pick up where you left off, run `python main.py -continue`." }, { "alpha_fraction": 0.6186059713363647, "alphanum_fraction": 0.6281619071960449, "avg_line_length": 34.56999969482422, "blob_id": "80057aa6d736c2ecd2834af5af399e534a1ea8f6", "content_id": "79b6fddbefcec3faa0ac0b7a435566fb15a469a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3558, "license_type": "no_license", "max_line_length": 212, "num_lines": 100, "path": "/main.py", "repo_name": "saumikn/swiss-by-api", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport requests\nimport sys\nimport json\nfrom dotenv import load_dotenv\nimport csv\nimport logic\nimport sheets\nimport time\n\nload_dotenv() \ntoken = os.getenv('LICHESS_TOKEN')\nsheet_id = os.getenv('GOOGLE_SHEET_ID')\npairing_sheet = os.getenv('GOOGLE_PAIRING_SHEET')\n\n## Use this at the beginning of the round\ndef start_round(pairing_files, output_file):\n game_stream = logic.start_stream()\n\n pairings = list()\n for section in pairing_files:\n cell = input(f'What cell should pairings for {section} start at? ')\n game_id_file = input(f'What game_id file should {section} use? ')\n pairings += logic.setup_pairings_lichess(cell=cell, pairing_file=section, game_id_file=game_id_file)\n logic.write_pairings(pairings, output_file)\n\n for line in game_stream.iter_lines():\n logic.parse_event(line, output_file)\n\n## Use this if watching games broke in the middle of the round\ndef continue_round(pairing_objs):\n game_stream = logic.start_stream()\n for line in game_stream.iter_lines():\n logic.parse_event(line, pairing_objs)\n\ndef message(player_file, message_body):\n players = logic.read_player_key().values()\n headers = {'Authorization': f'Bearer {token}'}\n data = {'text':message_body}\n\n for p in players:\n response = requests.post(f'https://lichess.org/inbox/{p}', data=data, headers=headers)\n print(f'{p},{response.text}')\n\ndef create_game_id_file(game_id_file, time_control):\n time_control = time_control.split('+')\n with open(game_id_file, 'w+') as f:\n for i in range(30):\n data = {'clock.limit':time_control[0], 'clock.increment':time_control[1]}\n response0 = requests.post('https://lichess.org/api/challenge/open', data=data)\n print(response0.json()['challenge']['id'], file=f)\n print(response0)\n\n\ndef print_missing():\n pairings = []\n pairings += logic.convert_swiss_sys('open.csv')\n pairings += logic.convert_swiss_sys('u1600.csv')\n pairings += logic.convert_swiss_sys('u1000.csv')\n pairings = [i.lower() for sublist in pairings for i in sublist]\n # print(pairings)\n player_key = logic.read_player_key()\n # print(player_key)\n for p in pairings:\n if p in player_key:\n headers = {'Accept': 'application/json'}\n response = requests.get(f'https://lichess.org/api/user/{player_key[p]}', headers=headers)\n if 'id' not in response.json():\n print(player_key[p])\n pass\n else:\n print(p)\n \ndef test():\n pass\n\nif __name__ == '__main__':\n if (len(sys.argv) < 2):\n print('Error: Not enough arguments')\n elif (sys.argv[1] in ['-start', '-S']):\n start_round(pairing_files=sys.argv[2:], output_file='pairing_objs.csv')\n elif (sys.argv[1] in ['-continue', '-C']):\n continue_round('pairing_objs.csv')\n elif (sys.argv[1] in ['-message', '-M']):\n welcome = \"All games done in Round 5, and Round 6 will start shortly. Round 6 is the last round of the tournament today. You can see the tournament pairings and standings at https://tinyurl.com/y77t9kox.\"\n message('players.csv', welcome)\n elif (sys.argv[1] in ['-create']):\n create_game_id_file(sys.argv[2], '900+5')\n elif (sys.argv[1] in ['-print-missing']):\n print_missing()\n elif (sys.argv[1] in ['-test', '-T']):\n test()\n else:\n print('Wrong arguments passed. Try running again with -s or -c flags')\n\n # set_up_stream()\n # sheets.get_players()\n \n pass\n\n" } ]
4
KWillak/Astonomical_Image_Processing
https://github.com/KWillak/Astonomical_Image_Processing
2e957e5487c1563dc1ecac7019f284f9d60434d2
f725bfdd43775da552593517e1cf16eec564ca9f
8d75a30b0c7715f6fe45dec672e4061a269f7118
refs/heads/master
2020-04-29T17:27:15.636971
2019-03-18T16:18:43
2019-03-18T16:18:43
176,297,425
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6033755540847778, "alphanum_fraction": 0.6362869143486023, "avg_line_length": 31.027027130126953, "blob_id": "6b49cbfef5d87b666d7e82c9fd73e1ec07b12b10", "content_id": "eed037113d32d53e3d1d3aba2e6d6400e49b2bd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1185, "license_type": "no_license", "max_line_length": 134, "num_lines": 37, "path": "/Creating_Histogram.py", "repo_name": "KWillak/Astonomical_Image_Processing", "src_encoding": "UTF-8", "text": "from astropy.io import fits\nimport numpy as np\nimport scipy\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as pl\nfrom scipy.stats import norm\nimport pickle\nimport Funtions as F\n\nhdulist = fits.open(r\"C:\\Users\\Kamil\\Documents\\Imperial\\3rd year lab\\Astronomical image processing\\Pictures\\A1_mosaic\\A1_mosaic.fits\")\nhdulist[0].header\ndata = hdulist[0].data\n# i = y, j = x , setting all dead pixels to zero\nfor i in range(4510, len(data)):\n for j in range(0, len(data[1])): #top side\n data[i, j] = 0\nfor i in range(0, len(data)): #right side\n for j in range(2470, len(data[1])):\n data[i, j] = 0\nfor i in range(0, len(data)): #left side\n for j in range(0, 100):\n data[i, j] = 0\nfor i in range(0, 100): #bottom side\n for j in range(0, len(data[1])):\n data[i, j] = 0\npickle.dump(data, open(\"data.p\", \"wb+\"))\n\nIntensity = []\n\n\nIntensity, mu, sigma = F.Gaussian(data)\n# the histogram of the data\nn, bins, patches = pl.hist(Intensity, 54, normed=1, facecolor='green', alpha=0.75)\n# add a 'best fit' line\ny = pl.mlab.normpdf( bins, mu, sigma)\nl = pl.plot(bins, y, 'r--', linewidth=2)\npl.show()\n" }, { "alpha_fraction": 0.6367265582084656, "alphanum_fraction": 0.6566866040229797, "avg_line_length": 21.772727966308594, "blob_id": "c92c928645efc487cc2ecf1173aa1ba86767e2fe", "content_id": "c535caa00a431b25ff2b2cf1ad6b423c47815687", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 501, "license_type": "no_license", "max_line_length": 54, "num_lines": 22, "path": "/Funtions.py", "repo_name": "KWillak/Astonomical_Image_Processing", "src_encoding": "UTF-8", "text": "from astropy.io import fits\nimport numpy as np\nimport scipy\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as pl\nfrom scipy.stats import norm\nimport pickle\n\n\n\ndef Gaussian(data):\n # creating a 1D array that stores all pixel values\n\n for i in range(len(data)):\n for j in range(len(data[1])):\n if 3390 < data[i, j] < 3445:\n Intensity.append(data[i, j])\n\n # best fit of data\n (mu, sigma) = norm.fit(Intensity)\n\n return Intensity, mu, sigma\n" }, { "alpha_fraction": 0.6728016138076782, "alphanum_fraction": 0.6809815764427185, "avg_line_length": 24.736841201782227, "blob_id": "0098e4e9fb3b3a999af340af37d8dc26e5319b01", "content_id": "af3685a9d01f4a2e8d4658bafb58f145e3891c37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 42, "num_lines": 19, "path": "/Counting_Stars.py", "repo_name": "KWillak/Astonomical_Image_Processing", "src_encoding": "UTF-8", "text": "from astropy.io import fits\nimport numpy as np\nimport scipy\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as pl\nfrom scipy.stats import norm\nimport pickle\nfrom Creating_Histogram import Gaussian\n\n\ndata = pickle.load(open(\"data.p\", \"rb\"))\nIntensity, mean, sigma = Gaussian(data)\n##j = x, i = y\nPositions = []\nfor i in range(0, len(data)):\n for j in range(0, len(data[1])):\n if (mean + 3*sigma) < data[i, j]:\n Positions.append([i, j])\nprint(Positions)\n" }, { "alpha_fraction": 0.8125, "alphanum_fraction": 0.8125, "avg_line_length": 15, "blob_id": "cdad32394d20a1394294a09363ef13cdae8d8055", "content_id": "324ba87ac574a9820a9da1a23a3522d00996e568", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 64, "license_type": "no_license", "max_line_length": 30, "num_lines": 4, "path": "/README.md", "repo_name": "KWillak/Astonomical_Image_Processing", "src_encoding": "UTF-8", "text": "# Astonomical_Image_Processing\n\n\nTo analyze deep space pictures\n" } ]
4
eric-tc/CmakeRef
https://github.com/eric-tc/CmakeRef
b9d46e39488a6f82c7ab7647305e95c0ca3c332b
adead79a9737dec4be35f73a9b2500b0b6ef43d5
3043bd13010ca95d0a9628ffad6169885ed81517
refs/heads/master
2023-03-19T08:47:40.151803
2021-03-18T13:51:27
2021-03-18T13:51:27
282,193,226
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7942583560943604, "alphanum_fraction": 0.8038277626037598, "avg_line_length": 28.85714340209961, "blob_id": "0261f729f026c956c59e9b268fedbe934b9bb2af", "content_id": "2fba915552039a73e9a7b52eeebaed798e0f28ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 209, "license_type": "no_license", "max_line_length": 126, "num_lines": 7, "path": "/Readme.md", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "# Esempio 1\n\nEsempio di come utilizzare il comando add-subdirectory() e target_sources() per compilare un progetto aggiungendo una libreria\n\n# Esempio 2\n\nCreazione di una libreria dinamica con classe astratta\n" }, { "alpha_fraction": 0.7674418687820435, "alphanum_fraction": 0.7790697813034058, "avg_line_length": 41.75, "blob_id": "cfb03c6fced20d870b6f01349c637c399f5273a9", "content_id": "d6929d1d75d5c27c10b815ec0f93433a8a60a8c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 172, "license_type": "no_license", "max_line_length": 68, "num_lines": 4, "path": "/Esempio1/lib1/CMakeLists.txt", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "\n\n#Definisco i file che devono essere compilati per creare la libreria\ntarget_sources(MyLib PRIVATE \n${CMAKE_CURRENT_LIST_DIR}/func1.h \n${CMAKE_CURRENT_LIST_DIR}/func1.cpp)" }, { "alpha_fraction": 0.7551020383834839, "alphanum_fraction": 0.7643784880638123, "avg_line_length": 21.29166603088379, "blob_id": "5bcdb33e5a9a48ee445c715fd836a5c6a1596f2f", "content_id": "775184affec0711b4efa0bc69b13cf3f41f1d03c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 539, "license_type": "no_license", "max_line_length": 64, "num_lines": 24, "path": "/Esempio3/CMakeLists.txt", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.12)\n\nproject(testlib)\n\nset (libshared_DIR ${CMAKE_CURRENT_SOURCE_DIR}/deps/testInstall)\n\nmessage(\"sharedLib dependecy ${sharedlib_DIR}\")\n\nset(CMAKE_CXX_STANDARD 11)\nset(CMAKE_CXX_STANDARD_REQUIRED)\n\nfind_package(libshared REQUIRED)\n\nmessage(\"include file ${LIBSHARED_INCLUDE_DIRS} \")\n\ninclude_directories(\"${LIBSHARED_INCLUDE_DIRS}\")\n\n#link_directories(deps/testinstall/lib)\n\nadd_executable(testlib main.cpp)\n\nmessage(\"sharedlib ${LIBSHARED_LIBS} \")\n\ntarget_link_libraries(testlib \"${LIBSHARED_LIBS}\")\n\n\n\n\n" }, { "alpha_fraction": 0.7642792463302612, "alphanum_fraction": 0.7724388241767883, "avg_line_length": 28.783782958984375, "blob_id": "b8ca447a18e51d8033c3dddfcd0f3836f919ec03", "content_id": "36fabb48f8ab1d9a6c71dd27710c626dd91438bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1103, "license_type": "no_license", "max_line_length": 94, "num_lines": 37, "path": "/Esempio5/library/CMakeLists.txt", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.12)\n\nproject(libshared)\n\n\nset(CMAKE_CXX_STANDARD 11)\nset(CMAKE_CXX_STANDARD_REQUIRED)\n\nadd_library(libshared SHARED test.cpp test.h)\n\nset_target_properties(\n libshared PROPERTIES\n SOVERSION 1\n VERSION 1.2.9\n)\n\n#aggiungere tutti gli header\n#set_target_properties(myproject PROPERTIES PUBLIC_HEADER \"${my_header_files}\")\nset_target_properties(libshared PROPERTIES PUBLIC_HEADER \"test.h\")\n\nset(INCLUDE \"include/test.h\")\n\n# senza @ONLY tutte le variabili di Cmake sono convertite nei valori statici\n# con @ONLY solo le variabili con @ VAR @ sono convertite con i loro valori\nconfigure_file(libsharedConfig.cmake.in \"${CMAKE_INSTALL_PREFIX}/libsharedConfig.cmake\" @ONLY)\n\n\n# copia i file nelle cartelle lib bin e include\ninstall(TARGETS libshared\n EXPORT libsharedTargets.cmake\n RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin\n LIBRARY DESTINATION ${CMAKE_INSTALL_PREFIX}/lib\n PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_PREFIX}/include\n)\n\n# Crea il file di configurazione\nexport ( TARGETS libshared FILE ${CMAKE_INSTALL_PREFIX}/libsharedTargets.cmake )\n\n" }, { "alpha_fraction": 0.7888563275337219, "alphanum_fraction": 0.803519070148468, "avg_line_length": 23.428571701049805, "blob_id": "94f81ae622240382154c07c9b8b90cc6dfdd2532", "content_id": "6360bf8936c9bc612337f73a9dbdabb11bfe82cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 341, "license_type": "no_license", "max_line_length": 93, "num_lines": 14, "path": "/JsonCpp/CMakeLists.txt", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.10)\n\nset (CMAKE_TOOLCHAIN_FILE \"${CMAKE_CURRENT_LIST_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake\")\n\nproject(jsondump)\n\nset(CMAKE_CXX_STANDARD 11)\nset(CMAKE_CXX_STANDARD_REQUIRED)\n\nfind_package(jsoncpp CONFIG REQUIRED)\n\nadd_executable(jsondump main.cpp)\n\ntarget_link_libraries(jsondump PRIVATE jsoncpp_static)" }, { "alpha_fraction": 0.7812080383300781, "alphanum_fraction": 0.7812080383300781, "avg_line_length": 40.33333206176758, "blob_id": "36b39c3932d7776c38ab755cc8bc8313fd67923e", "content_id": "3edd28c51343aa182e5fbedd8e01f06d7d046538", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 746, "license_type": "no_license", "max_line_length": 106, "num_lines": 18, "path": "/Esempio5/library/libsharedConfig.cmake.in", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "# config file for shared library\n\n# cartella corrente di installazione\nget_filename_component(LIBSHARED_CMAKE_DIR \"${CMAKE_CURRENT_LIST_FILE}\" PATH)\n\n#file(RELATIVE_PATH MYLIB_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_LIST_DIR}/include/)\n\n#set(LIBSHARED_INCLUDE_DIRS \"@INCLUDE@\")\n\nset(LIBSHARED_INCLUDE_DIRS ${CMAKE_CURRENT_LIST_DIR}/include/)\n\n#file(RELATIVE_PATH LIBSHARED_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_LIST_DIR}/include/)\n# questo file è generato dal comando export(TARGETS)\n# serve al posto di link_libraries nel file cmake principale\ninclude(\"${LIBSHARED_CMAKE_DIR}/libsharedTargets.cmake\")\n\n# sharedlib nome del target esportato presente nel comando export(TARGETS)\nset(LIBSHARED_LIBS libshared)\n\n" }, { "alpha_fraction": 0.6047120690345764, "alphanum_fraction": 0.6073298454284668, "avg_line_length": 19.13157844543457, "blob_id": "ae18b5f5d105f25f64248f9c8e5fd1d83f1480da", "content_id": "09212bf37e669d02b3b6a396217f24e6e84e937b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 764, "license_type": "no_license", "max_line_length": 77, "num_lines": 38, "path": "/JsonCpp/main.cpp", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <json/json.h>\n#include <fstream>\n\nusing namespace std;\n\nint main()\n{\n\n Json::Value root;\n Json::Value data;\n\n Json::Value content(Json::arrayValue);\n content.append(\"a\");\n// root[\"res\"]=content;\n// cout << root.toStyledString() <<endl;\n\n\n constexpr bool shouldUseOldWay = false;\n int i[4];\n \n root[\"action\"] = \"run\";\n data[\"number\"] = content;\n root[\"data\"] = data;\n\n Json::StreamWriterBuilder builder;\n const std::string json_file = Json::writeString(builder, root);\n std::cout << json_file << std::endl;\n\n\n ofstream myfile;\n myfile.open (\"example.txt\",std::ios::in | std::ios::out | std::ios::app);\n myfile<<json_file+ \"\\n\";\n myfile.close();\n\n cout<<\"test\"<<endl;\n return 0;\n}" }, { "alpha_fraction": 0.6288209557533264, "alphanum_fraction": 0.6462882161140442, "avg_line_length": 8.583333015441895, "blob_id": "cd79dac785272dff81aedf3997ee40155dbd5698", "content_id": "3e46e581a5a7283d9042e8eab51b797df1617bde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 229, "license_type": "no_license", "max_line_length": 33, "num_lines": 24, "path": "/Esempio2/src/classification.h", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include \"modelInterface.h\"\n\n\nnamespace classification{\n\n\nclass ResNet50 : modelInterface{\n\n public:\n\n ResNet50();\n void preprocessing(int data);\n void postprocessing();\n void runmodel();\n\n int model;\n\n};\n\n\n\n\n\n}" }, { "alpha_fraction": 0.7511110901832581, "alphanum_fraction": 0.7644444704055786, "avg_line_length": 14.066666603088379, "blob_id": "a4c725c2a57b7f6ee7a630a452966407efbb0796", "content_id": "4030ff4813497276f776d2f6da8258c8f984d336", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 225, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/Esempio2/src/modelInterface.h", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include <iostream>\n\n\n//classe interfaccia su come devono essere create le varie classi\nclass modelInterface{\n\npublic:\n\nvirtual void preprocessing(int data)=0;\n\nvirtual void runmodel()=0;\n\nvirtual void postprocessing()=0;\n\n};" }, { "alpha_fraction": 0.8116883039474487, "alphanum_fraction": 0.8116883039474487, "avg_line_length": 50.66666793823242, "blob_id": "9e87d2368c021b389f3c1c6f23b029581797f1e2", "content_id": "3511a2e3cace49eaa1b6218148b1f7c44a7c11ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 154, "license_type": "no_license", "max_line_length": 126, "num_lines": 3, "path": "/Esempio1/Readme.md", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "# CMake add_subdirectory()\n\nEsempio di come utilizzare il comando add-subdirectory() e target_sources() per compilare un progetto aggiungendo una libreria" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6413690447807312, "avg_line_length": 14.295454978942871, "blob_id": "9734758f6d01f2b103f51037e2dd2c78c866efe6", "content_id": "3166f0b7ff3bf6a20072a0a809780e4321c98150", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 672, "license_type": "no_license", "max_line_length": 81, "num_lines": 44, "path": "/Esempio2/main.cpp", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nusing namespace std;\n\n#include \"src/classification.h\"\n\nusing namespace classification;\n\n//classe Custom posso cambiare solo il preprocessing lasciando invariato il resto\n//Link lista funzioni che possono essere usate\nclass customResnet : ResNet50{\n\n public:\n\n customResnet(){\n\n cout<<\"costruttoreCustom\"<<endl;\n }\n \n \n void preprocessing(int data){\n\n ResNet50::model= data;\n\n }\n};\n\n\nint main(){\n \n ResNet50 *resnet; \n \n resnet = new ResNet50();\n\n resnet->preprocessing(1);\n cout<<resnet->model<<endl;\n cout<< \"test\"<< endl;\n\n customResnet cRes;\n\n cRes.preprocessing(1);\n\n return 0;\n}" }, { "alpha_fraction": 0.4270557165145874, "alphanum_fraction": 0.4721485376358032, "avg_line_length": 28.076923370361328, "blob_id": "f01dbf73b0935d465c8a0cb41c545e90651a79fa", "content_id": "5f9b8f4b2bfa70289b8b8d9fadf289004cd0be36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 377, "license_type": "no_license", "max_line_length": 53, "num_lines": 13, "path": "/JsonCpp/main.py", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "import json\n\nresults=[]\nresults_file = 'yolo/results_{}.json'.format(\"yolo\")\n\nfor i in range(0,10,1):\n\n results.append({'image_id': i,\n 'category_id': i+1,\n 'bbox': [12, 23, 23, 23],\n 'score': float(0.98)})\n with open(results_file, 'w+') as f:\n f.write(json.dumps(results, indent=4))" }, { "alpha_fraction": 0.5430711507797241, "alphanum_fraction": 0.5617977380752563, "avg_line_length": 9.720000267028809, "blob_id": "c43aed1b686f33ae525a587faf1beea8a8d52285", "content_id": "beb3a6a1d10334302dec63bbdd863fb529d961e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 267, "license_type": "no_license", "max_line_length": 33, "num_lines": 25, "path": "/Esempio1/main.cpp", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include \"lib1/func1.h\"\n\nusing namespace std;\n\nint main(){\n\n\n test *prova = new test();\n\n\n\n prova->add(10);\n\n cout<<prova->m_counter<<endl;\n\n cout <<prova->m_ip<<endl;\n\n cout<<\"test\"<<endl;\n\n cout<<\"test\"<<endl;\n\n\n return 0;\n}" }, { "alpha_fraction": 0.6170212626457214, "alphanum_fraction": 0.6489361524581909, "avg_line_length": 8.921052932739258, "blob_id": "ed960575eaec9c4e8a37d36b0c61c25d98f51494", "content_id": "8e8ab6d6bf1354124bf55995be2a1f67b26d27b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 376, "license_type": "no_license", "max_line_length": 39, "num_lines": 38, "path": "/Esempio2/src/classification.cpp", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include \"classification.h\"\nusing namespace std;\n\nnamespace classification{\n\n\nResNet50::ResNet50(){\n\n cout<<\"costruttore\"<<endl;\n \n}\n\nvoid ResNet50::postprocessing(){\n\n cout<<\"resnetPost\"<<endl;\n\n\n}\n\nvoid ResNet50::runmodel(){\n\n cout<<\"resnetRun\"<<endl;\n\n\n}\n\n\nvoid ResNet50::preprocessing(int data){\n\n ResNet50::model=data;\n\n cout<<\"resnetPre\"<<endl;\n\n}\n\n\n\n}" }, { "alpha_fraction": 0.5291005373001099, "alphanum_fraction": 0.5396825671195984, "avg_line_length": 10.176470756530762, "blob_id": "d128ab9a3d1ab56445fc17fffaa0ad0d759befb5", "content_id": "3a271ee18eb6407de266546380248c597acedc78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 189, "license_type": "no_license", "max_line_length": 25, "num_lines": 17, "path": "/Esempio3/main.cpp", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include \"test.h\"\n\nusing namespace std;\n\n\nint main(){\n\n test t;\n t.number=0;\n t.add();\n\n \n cout<< \"pipp<\"<<endl;\n cout<<t.number<<endl;\n return 0;\n}" }, { "alpha_fraction": 0.7824817299842834, "alphanum_fraction": 0.7941606044769287, "avg_line_length": 31.5238094329834, "blob_id": "56118371b4981f86cd58537d2c2a3c808aa9cd70", "content_id": "d21380da33d2c002d78e981e7d61bc942205dc42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 686, "license_type": "no_license", "max_line_length": 82, "num_lines": 21, "path": "/Esempio1/CMakeLists.txt", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.11)\n\n# progetto base per testare add_subdirectory\nproject(testfunction)\n\n\n# serve per compilare la libreria nella cartella lib1 aggiunta da add_subdirectory\n# il valore MyLib è passato a lib1/CMakeLists.txt\nadd_library(MyLib SHARED \"\")\n\n# Richiama il file lib1/CMakeLists.txt e crea la libreria statica definita\n# dal valore add_library(MyLib \"\") \n# i file da includere nella libreria sono definiti nel file lib1/CMakeLists.txt \n# con target_sources()\nadd_subdirectory(lib1)\n\n# genera eseguibile del progetto\nadd_executable(testfunction main.cpp)\n\n# Aggiungo la libreria creata da add_library all eseguibile\ntarget_link_libraries(testfunction MyLib)\n\n\n" }, { "alpha_fraction": 0.5252525210380554, "alphanum_fraction": 0.5353535413742065, "avg_line_length": 5.125, "blob_id": "c195dc72756b52c959f82926478e097c61637371", "content_id": "7261e65b1c33899ce9811a57705ffbf2be257717", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 99, "license_type": "no_license", "max_line_length": 27, "num_lines": 16, "path": "/Esempio1/lib1/func1.cpp", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include \"func1.h\"\n\n\n\n\n\ntest::test(){\n\n\n}\n\nvoid test::add(int i){\n\n m_counter= m_counter+i;\n\n}\n\n" }, { "alpha_fraction": 0.5142857432365417, "alphanum_fraction": 0.5142857432365417, "avg_line_length": 7.153846263885498, "blob_id": "2a2619408b063bf60b50ba28d2d5420428dd6789", "content_id": "5fe8da318fc6207a71e4ec8f0869fe5cba76013d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 105, "license_type": "no_license", "max_line_length": 19, "num_lines": 13, "path": "/Esempio3/deps/testInstall/include/test.h", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nclass test\n{\n\npublic:\n test();\n ~test();\n\n void add();\n\n int number; \n};" }, { "alpha_fraction": 0.4722222089767456, "alphanum_fraction": 0.48148149251937866, "avg_line_length": 4.736842155456543, "blob_id": "73a1b25130bbe0b6cc2b44302852921615e63141", "content_id": "e9ebc019ba95576ff3ef91775cac5b5a1e058530", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 108, "license_type": "no_license", "max_line_length": 22, "num_lines": 19, "path": "/Esempio5/library/test.cpp", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "#include \"test.h\"\n\n\ntest::test(){\n\n\n}\n\ntest::~test(){\n\n\n}\n\nvoid test::add(){\n\n \n number= number +1;\n\n}" }, { "alpha_fraction": 0.8068181872367859, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 17.578947067260742, "blob_id": "c64d443f34c6db90172e46a03eeb4c2b6a397285", "content_id": "296261ff0a257b97c95641de3f9355a95af2e3f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 352, "license_type": "no_license", "max_line_length": 78, "num_lines": 19, "path": "/Esempio2/CMakeLists.txt", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.5)\n\nproject(interface)\n\nset(CMAKE_CXX_STANDARD 11)\n\n#@add_library(modelInterface INTERFACE)\n\n\n\nadd_library(classification SHARED src/classification.cpp src/classification.h)\n\n\n#target_include_directories(modelInterface INTERFACE\n#src)\n\nadd_executable(interface main.cpp)\n\ntarget_link_libraries(interface classification)" }, { "alpha_fraction": 0.35606059432029724, "alphanum_fraction": 0.3636363744735718, "avg_line_length": 4.695652008056641, "blob_id": "bb5d89fa46533a70b715329374d80ea741e6407c", "content_id": "d252147a986ba21bd134d9186f3bb626a18e37d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 132, "license_type": "no_license", "max_line_length": 20, "num_lines": 23, "path": "/Esempio1/lib1/func1.h", "repo_name": "eric-tc/CmakeRef", "src_encoding": "UTF-8", "text": "\n\nclass test{\n\n \n \n \n \n public:\n\n int m_counter=0;\n\n int m_ip;\n\n test();\n\n \n\n void add(int i);\n\n\n\n\n\n};" } ]
21
leanhill/Zadania2
https://github.com/leanhill/Zadania2
884620606b45a3d045f02a24fd92a9ecc05218b4
034bcfccdae802fa36c9ca8bba55a7fc90bb6295
f378b4449d7ac70c80211a3389208d9ba76e2531
refs/heads/master
2022-11-23T12:55:51.120117
2020-07-15T21:44:55
2020-07-15T21:44:55
278,749,728
0
0
null
2020-07-10T23:06:22
2020-07-15T21:45:10
2020-07-17T21:06:13
Python
[ { "alpha_fraction": 0.5868613123893738, "alphanum_fraction": 0.5941605567932129, "avg_line_length": 35, "blob_id": "b8d799ad3e88907c1c4a67630fcd7c771c615593", "content_id": "84d6517ff8d72ecd448d46b6852682240e03e85f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "no_license", "max_line_length": 94, "num_lines": 19, "path": "/Zadanie2_2.py", "repo_name": "leanhill/Zadania2", "src_encoding": "UTF-8", "text": "\"\"\"2. Napisz funkcję która przyjmuje stringa i zwraca go ze wszystkimi parzystymi znakami,\n napisanymi wielką literą, a nieparzystymi znakami małą literą. Przyjmij indeksowanie od zera.\n\nto_weird_case('String') # => zwraca 'StRiNg'\nto_weird_case('Algorytmy i struktury danych') # => zwraca 'AlGoRyTmY I StRuKtUrY DaNyCh\"\"\"\ndef to_weird_case(word):\n weird_word = str()\n a = 1\n for character in word:\n if character == \" \":\n weird_word += character\n pass\n else:\n if a%2 == 0:\n weird_word += character.lower()\n else:\n weird_word += character.upper()\n a += 1\n return weird_word\n\n" }, { "alpha_fraction": 0.5889967679977417, "alphanum_fraction": 0.6488673090934753, "avg_line_length": 67.44444274902344, "blob_id": "c5b3bb20aa538b7d427054d9f42a80ce16fd3ae7", "content_id": "b789145b5b252aeeb3e80cd4db66e76e9a902227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 622, "license_type": "no_license", "max_line_length": 124, "num_lines": 9, "path": "/Zadanie2_1.py", "repo_name": "leanhill/Zadania2", "src_encoding": "UTF-8", "text": "\"\"\"1. Napisz funkcję, która przyjmuje listę 11 liczb całkowitych i zwraca stringa w formacie numeru telefonu.\n\ncreate_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) # => returns \"(+12) 345-678-901\"\"\"\n\ndef create_phone_number(phone_number_digits):\n phone_number = f\"(+{phone_number_digits[0]}{phone_number_digits[1]}) {phone_number_digits[2]}{phone_number_digits[2]}\" \\\n f\"{phone_number_digits[3]}-{phone_number_digits[5]}{phone_number_digits[6]}{phone_number_digits[7]}\" \\\n f\"-{phone_number_digits[8]}{phone_number_digits[9]}{phone_number_digits[10]}\"\n return phone_number\n\n\n" }, { "alpha_fraction": 0.734375, "alphanum_fraction": 0.74609375, "avg_line_length": 31, "blob_id": "df00a0a34fe9d934d9e4213f3ab57e939568444e", "content_id": "9aadc3dd2040cda0628b152dd9044fe5def59e4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 92, "num_lines": 8, "path": "/zadanie2_5.py", "repo_name": "leanhill/Zadania2", "src_encoding": "UTF-8", "text": "\"\"\"5. Zaimplementuj funkcję która bedzie przyjmować string i będzie zwracać wszystkie litery\n które leżą pod nieparzystymi indeksami:)\n\nteleturniej -> eeune\nkomputer -> optr\"\"\"\ndef get_odd_letters(word):\n odd_letters = word[1::2]\n return odd_letters\n" }, { "alpha_fraction": 0.30588236451148987, "alphanum_fraction": 0.31674209237098694, "avg_line_length": 44.95833206176758, "blob_id": "419c64f11c2b06c0bf7f48fce5d216280ef28ccc", "content_id": "ca46470df3de0fb363a78f0b008950f0c5e8290d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1168, "license_type": "no_license", "max_line_length": 119, "num_lines": 24, "path": "/Zadanie2_3.py", "repo_name": "leanhill/Zadania2", "src_encoding": "UTF-8", "text": "\"\"\"3. Napisz funkcję która przyjmie jako argument kod morse'a. Czyli ciąg kropek i kresek, np.:\n\nA = ‘·−‘\nQ = ‘−−·−‘\n1 = ‘·−−−−‘\nczyli w kodzie morse'a SOS wyglądałoby:\n\nSOS = ‘···−−−···’\nIii ta nowa funkcja powinna zwrócić zakodowany tekst, czyli np.:\n\ndecode_morse('... --- ...') # => 'S O S'\"\"\"\ndef decode_morse(txt_in_morse):\n\n morse_code = {\".-\":\"A\",\"-...\":\"B\",\"-.-.\":\"C\",\"-..\":\"D\",\".\":\"E\",\"..-.\":\"F\",\"--.\":\"G\",\"....\":\"H\",\"..\":\"I\",\".---\":\"J\",\n \"-.-\":\"K\",\".-..\":\"L\",\"--\":\"M\",\"-.\":\"N\",\"---\":\"O\",\".--.\":\"P\",\"--.-\":\"Q\",\".-.\":\"R\",\"...\":\"S\",\"-\":\"T\",\n \"..-\":\"U\",\"...-\":\"V\",\".--\":\"W\",\"-..-\":\"X\",\"-.--\":\"Y\",\"--..\":\"Z\",\"-----\":\"0\",\".----\":\"1\",\"..---\":\"2\",\n \"...--\":\"3\",\"....-\":\"4\",\".....\":\"5\",\"-....\":\"6\",\"--...\":\"7\",\"---..\":\"8\",\"----.\":\"9\",\".-.-\":\"Ą\",\n \"-.-..\":\"Ć\",\"..-..\":\"Ę\",\".-..-\":\"Ł\",\"--.--\":\"Ń\",\"---.\":\"Ó\",\"...-...\":\"Ś\",\"--..-.\":\"Ż\",\"--..-\":\"Ź\",\n }\n txt_decoded = txt_in_morse.split(\" \")\n txt_translated = \"\"\n for i in txt_decoded:\n txt_translated += morse_code[i]\n return txt_translated\n\n\n" }, { "alpha_fraction": 0.6809523701667786, "alphanum_fraction": 0.686904788017273, "avg_line_length": 54.79999923706055, "blob_id": "970911561d30e57db4ca8cd59f628b46988fee3c", "content_id": "7675c7fa19db793b1b10d8dec60125d996215b4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "no_license", "max_line_length": 112, "num_lines": 15, "path": "/Zadanie2_4.py", "repo_name": "leanhill/Zadania2", "src_encoding": "UTF-8", "text": "\n\"\"\"4. Zaimplementuj sortowanie bąbelkowe. W programowaniu problem sortowań jest jednym z ważniejszych problemów,\nponieważ każdą daną da się przedstawić jako cyfrę\n (zerknij sobie tak w ramach świadomości na tablekę na tej stronie:\n http://www.asciitable.com/ ) i zauważ że litery mają swoje odpowiedniki w liczbach :D)\nZałączam również link który opisuje jak ono działa:\n http://www.algorytm.edu.pl/algorytmy-maturalne/sortowanie-babelkowe.html\"\"\"\ndef bubble_sort(number_to_sort):\n number_bubbled = list(number_to_sort)\n for i in range (len(number_to_sort)):\n for i in range(len(number_to_sort) - 1):\n if number_bubbled[i] > number_bubbled[i + 1]:\n a = number_bubbled[i]\n number_bubbled[i] = number_bubbled[i + 1]\n number_bubbled[i + 1] = a\n return number_bubbled\n\n\n" } ]
5
Bradels/IoT-Application-Building-a-Smart-Library-master
https://github.com/Bradels/IoT-Application-Building-a-Smart-Library-master
388df1fec1d85389287419b29f1ed1e05b4bd407
28cdb11effdc53f5846ced371ad8c8892e9da142
26c62a8383d76830ee356fcf93760bc9d775d93c
refs/heads/master
2020-08-21T11:57:53.968382
2019-10-19T05:31:44
2019-10-19T05:31:44
216,154,693
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7058252692222595, "alphanum_fraction": 0.708737850189209, "avg_line_length": 43.69565200805664, "blob_id": "6239dfaa7c5ef7fcc1883f37ade30f1b12dcc78a", "content_id": "b5e2e858e622ff548c3deb2ef9bf09b96ff4a769", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 102, "num_lines": 23, "path": "/mp/webapp/app.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\nfrom flask import Flask, request, redirect, render_template, session, url_for\nfrom flask_bootstrap import Bootstrap\nfrom controller import RouteController\nfrom login_controller import login_controller\n\napp = Flask(__name__)\nbootstrap = Bootstrap(app)\n\napp.secret_key = \"lFgz7p1PZR6I63He3VvxtCmWdCPf\"\napp.add_url_rule('/', 'index', lambda: RouteController.index())\napp.add_url_rule('/booklist', 'booklist', lambda: RouteController.booklist(), methods=['GET', 'POST'])\napp.add_url_rule('/datavis', 'datavis', lambda: RouteController.data_vis())\napp.add_url_rule('/login', 'login', lambda: RouteController.login_post(), methods=['POST', 'GET'])\napp.add_url_rule('/logout', 'logout', lambda: RouteController.logout())\napp.add_url_rule('/delete', 'delete', lambda: RouteController.removeBook(), methods=['POST'])\napp.add_url_rule('/update', 'update', lambda: RouteController.updateBook(), methods=['POST'])\n\n\nif __name__ == \"__main__\":\n host = os.popen('hostname -I').read()\n app.run(host=host, port=80, debug=False)\n\n\n" }, { "alpha_fraction": 0.7218934893608093, "alphanum_fraction": 0.7278106212615967, "avg_line_length": 22, "blob_id": "0d21b9307d7ce75f345a96c1032daca061e5a47e", "content_id": "84eb2335bbfcae997737ff6eaf590d857e997e89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 169, "license_type": "no_license", "max_line_length": 60, "num_lines": 7, "path": "/rp/test_user.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# Reference: https://docs.python.org/2/library/unittest.html\nimport unittest\nfrom user import user\n\nclass TestUser(unittest.TestCase):\n\n def test_menu(self):\n " }, { "alpha_fraction": 0.5274843573570251, "alphanum_fraction": 0.5343824028968811, "avg_line_length": 34.38167953491211, "blob_id": "227e3e8c473f394819df9db1fb4caad067ce9175", "content_id": "c5e942e97829f0f1564b1b3466849dc46496a34b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4639, "license_type": "no_license", "max_line_length": 80, "num_lines": 131, "path": "/mp/webapp/controller.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "import os, requests, json\nfrom datetime import datetime\nfrom flask import Flask, render_template, request, redirect, session, url_for\nfrom flask_bootstrap import Bootstrap\nfrom wtforms import Form, StringField, HiddenField, validators\nfrom login_controller import login_controller\n\n# The base IP address of the API will be local machine IP at port 5001\n# For use at RMIT\n# API_IP = \"http://\"+os.popen('hostname -I').read().rstrip()+\":5001/\"\n# For use at home\nAPI_IP = \"http://127.0.0.1:5001/\"\n\nclass RouteController:\n @staticmethod\n def index():\n \"\"\"\n The Index Route\n Parameters:\n Returns: The index.html rendered template\n \"\"\"\n return render_template('index.html')\n\n @staticmethod\n def removeBook():\n \"\"\"\n The remove book route\n Parameters: Book ID (Gotten through the form)\n Returns: Redirects to the booklist\n \"\"\"\n id = request.form.get(\"id\")\n requests.delete(API_IP + \"book/\"+id)\n return redirect(\"/booklist\")\n \n @staticmethod\n def updateBook():\n \"\"\"\n The Update Book Route.\n Parameters: AddBookForm\n Returns: Redirects to the booklist\n \"\"\"\n id = request.form.get(\"id\")\n addBookForm = AddEditBookForm(request.form)\n newISBN = addBookForm.book_ISBN.data\n newTitle = addBookForm.book_title.data\n newAuthor = addBookForm.book_author.data\n requests.put(API_IP + \"book/\"+id,\n json={\"ISBN\": newISBN,\n \"Title\": newTitle,\n \"Author\": newAuthor})\n return redirect(\"/booklist\")\n\n @staticmethod\n def booklist():\n \"\"\"\n The book list route\n Parameters: (GET) Returns a book list. (POST) Inserts a book\n Returns: the book_list template populaed by the books in the system.\n \"\"\"\n addBookForm = AddEditBookForm(request.form)\n if 'logged_in' in session:\n if request.method == 'POST':\n if not addBookForm.validate():\n return redirect(url_for(\"booklist\"))\n ISBN = addBookForm.book_ISBN.data\n title = addBookForm.book_title.data\n author = addBookForm.book_author.data\n requests.post(API_IP + \"book\", None,\n {\"ISBN\": ISBN,\n \"Title\": title,\n \"Author\": author})\n return redirect(url_for(\"booklist\"))\n \n if request.method == 'GET':\n response = requests.get(API_IP+\"book\")\n books = json.loads(response.text)\n return render_template('booklist.html',\n books=books,\n addBookForm=addBookForm)\n else:\n return redirect('/')\n \n\n @staticmethod\n def login_post():\n \"\"\"\n The Login route\n Parameters: (GET) Returns the login form. (POST) attempts to login\n Returns: successful login or the login template with error\n \"\"\"\n if request.method == 'POST':\n if login_controller.validate_login(request):\n session[\"logged_in\"] = True\n return redirect(url_for(\"index\"))\n else:\n error = \"Invalid login information:\"\n return render_template(\"login.html\", error=error)\n if request.method == 'GET':\n return render_template('login.html')\n \n\n @staticmethod\n def data_vis():\n \"\"\"\n The data visualisation route\n Parameters: \n Returns: the data vis template links to the google studio\n \"\"\"\n if 'logged_in' in session:\n return render_template(\"data_vis.html\")\n else:\n return redirect(url_for(\"index\"))\n \n\n @staticmethod\n def logout():\n \"\"\"\n The logout route\n Parameters:\n Returns: If logged in, will log the user out\n \"\"\"\n if'logged_in' in session:\n session.pop(\"logged_in\", None)\n return redirect('/')\n else:\n return \"<h4>You must be logged in to log out<h4>\"\n\nclass AddEditBookForm(Form):\n book_ISBN = StringField('ISBN', [validators.Length(min=1, max=100)])\n book_title = StringField('Title', [validators.Length(min=1, max=100)])\n book_author = StringField('Author', [validators.Length(min=1, max=100)])\n " }, { "alpha_fraction": 0.5517241358757019, "alphanum_fraction": 0.5517241358757019, "avg_line_length": 23.33333396911621, "blob_id": "4dfab449ffde16af5b05ac71207b1e38b3351c3b", "content_id": "d67efcec6e26c0447dcd5974d574e5f129774ca1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 145, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/build/html/_sources/mp_voice_recognition.rst.txt", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Master Pi Voice Recognition\n============================\n .. module:: mp_voice_recognition\n\n .. autoclass:: voice_recognition\n :members:" }, { "alpha_fraction": 0.48695650696754456, "alphanum_fraction": 0.48695650696754456, "avg_line_length": 18.33333396911621, "blob_id": "eabcac0ecc5c2c3332a58f8800bf78ea4cbf43c8", "content_id": "91c2416e94f024b50cab2b0d2bf5270e7478286d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 115, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/source/rp_socket.rst", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Recieption Pi Socket\n========================\n .. module:: rp_socket\n\n .. autoclass:: rp_socket\n :members:" }, { "alpha_fraction": 0.6860024929046631, "alphanum_fraction": 0.6860024929046631, "avg_line_length": 28.38888931274414, "blob_id": "29f651378bc936092b76778b7aa80bc99aba58ed", "content_id": "1c96634b1568439f2dd9b733ca55cf2bc360ea8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1586, "license_type": "no_license", "max_line_length": 73, "num_lines": 54, "path": "/mp/webapp/test_webserver.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "import os\nimport pytest\nimport app\n\[email protected]\ndef client():\n app.app.config['TESTING'] = True\n client = app.app.test_client()\n\n yield client\n\ndef test_index(client):\n result = client.get('/')\n assert b'login' in result.data\n\ndef login(client, username, password):\n return client.post('/login', data=dict(\n username=username,\n password=password\n ), follow_redirects=True)\n\ndef logout(client):\n return client.get('/logout', follow_redirects=True)\n\ndef test_login_logout(client):\n incorrect_username = \"incorrect\"\n incorrect_password = \"incorrect\"\n correct_username = \"jaqen\"\n correct_password = \"hgar\"\n\n # Log in with correct details\n result = login(client,correct_username, correct_password)\n # If logged in, the logout option should appear\n assert b'logout' in result.data\n\n rv = logout(client)\n # When logged out, the log in option should appear\n assert b'login' in rv.data\n\n rv = login(client, incorrect_username, incorrect_password)\n # Login should fail with the message Invalid credentials\n assert b'Invalid' in rv.data\n\ndef test_test_no_access(client):\n rv = logout(client)\n # Logout incase logged in\n assert b'You must be logged in to log out' in rv.data\n rv = client.get('/booklist', follow_redirects=True)\n # The user should be taken back to the index, with login as an option\n assert b'login' in rv.data\n\n rv = client.get('/datavis', follow_redirects=True)\n # The user should be taken back to the index, with login as an option\n assert b'login' in rv.data" }, { "alpha_fraction": 0.4821428656578064, "alphanum_fraction": 0.4821428656578064, "avg_line_length": 17.83333396911621, "blob_id": "77430f1ac1a901e4225e47eefa5aae8e10cdfada", "content_id": "34c7c20feed2b8234287c0f6f5a12679bf36c17d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 112, "license_type": "no_license", "max_line_length": 26, "num_lines": 6, "path": "/build/html/_sources/rp_db.rst.txt", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Recieption Pi Database\n========================\n .. module:: rp_db\n\n .. autoclass:: database\n :members:" }, { "alpha_fraction": 0.5363160967826843, "alphanum_fraction": 0.5392214059829712, "avg_line_length": 36.434783935546875, "blob_id": "2f6b0d77b2370186febedad4fe45647fcbeaa1ca", "content_id": "d1d786ce9a3d8ba3c4e6651bd81a2db78ecdd0df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1721, "license_type": "no_license", "max_line_length": 86, "num_lines": 46, "path": "/source/rp_socket.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# # Reference: https://realpython.com/python-sockets/\n# # Documentation: https://docs.python.org/3/library/socket.html\n\n# import socket\n# import logging\n# import json\n\n# logging.basicConfig(filename=\"library.log\", level = logging.ERROR)\nclass rp_socket:\n\n # Call connection after successful login\n def connection(self, user=\"test\"): \n \"\"\"\n RP Socket is called when a user is logged in. By that, the socket searches\n for the server IP address/port to connect with. On connecting to the MP\n User needs to refer to the MP station and follow the attempts.\n When MP requests for logout, this message is passed to user class to logout. \n \"\"\" \n # try:\n # jsonData = self.readConfig()\n # HOST = jsonData[\"hostname\"]\n # PORT = jsonData[\"port\"] \n # ADDRESS = (HOST, PORT)\n # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n # s.connect(ADDRESS)\n # print(\"Connected to {}...\".format(ADDRESS))\n\n # while True: \n # s.sendall(user.encode())\n # # listen to message from server:\n # data = s.recv(4096)\n # message = data.decode()\n # print(\"Message from MP: \" + message)\n # if(message == \"logout\"):\n # return message\n # except Exception as e:\n # logging.error(\"RP Socket error: {}\".format(str(e)))\n # print(str(e))\n\n\n\n # # Read config.json\n # def readConfig(self):\n # with open('config.json') as jsonFile: \n # data = json.load(jsonFile)\n # return data" }, { "alpha_fraction": 0.686274528503418, "alphanum_fraction": 0.6941176652908325, "avg_line_length": 42.74285888671875, "blob_id": "27b9409ad18042f318165eb93a20a45462d2dc6d", "content_id": "8a5bc69746ecd9da7b2918bd2cd0192a6241ef5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1530, "license_type": "no_license", "max_line_length": 207, "num_lines": 35, "path": "/rp/test_db.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# Reference: https://docs.python.org/2/library/unittest.html\nimport unittest\nfrom db import database\n\n# Reference: https://docs.python.org/2/library/unittest.html\nimport unittest\nfrom db import database\nfrom passlib.hash import sha256_crypt\nclass db_test(unittest.TestCase):\n def setUp(self):\n self.c=database.connection().cursor()\n self.hashedPassword = sha256_crypt.hash(\"TestPassword\")\n database.insertData(\"TestUsername\",self.hashedPassword,\"TestFirstName\",\"TestLastName\",\"[email protected]\")\n def test_createTables(self):\n self.c=database.connection().cursor()\n self.c.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='account'\")\n name=self.c.fetchone()[0]\n self.assertEqual(name,\"account\")\n self.c.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='user'\")\n name=self.c.fetchone()[0]\n self.assertEqual(name,\"user\")\n \n def test_insertData(self):\n self.c.execute(\"SELECT count(*) from user where username='TestUsername' and password=%(password)s and firstname='TestFirstName' and lastname='TestLastName' and email='[email protected]'\",{\"password\":hashedPassword})\n result=self.c.fetchone()[0]\n self.assertEqual(int(result),1)\n \n def test_verifyPassword(self):\n self.assertTrue(database.veriftPassword(\"TestUsername\",self.hashedPassword))\n \n def test_checkUsernameExists(self):\n self.assertFalse(database.checkusernameexists(\"TestUsername\"))\n\nif __name__ == \"__main__\":\n unittest.main()" }, { "alpha_fraction": 0.5185629725456238, "alphanum_fraction": 0.5243238806724548, "avg_line_length": 38.27987289428711, "blob_id": "4b625381b993d422a6fd35ffc2d58f31079cfffb", "content_id": "214afed55fd3f0d74a0841df5f9471406c9b654e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12498, "license_type": "no_license", "max_line_length": 155, "num_lines": 318, "path": "/mp/library_menu.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# pip3 install PrettyTable\nfrom database_utils import DatabaseUtils\nimport logging\nfrom prettytable import PrettyTable\nimport re \nfrom bookevent import bookevent\nfrom voice_recognition import voice_recognition\nimport datetime\nfrom barcodescanner import barcodescanner\n\n\nlogging.basicConfig(filename=\"library.log\", level = logging.ERROR)\nclass library_menu:\n \n def runMenu(self, user):\n \"\"\"\n This method provides users with the search/borrow/return book(s) options\n Parameters:\n User name\n Returns:\n logout message if the user requests\n \"\"\"\n\n print(\"\\nWelcome \" + user + \"!\")\n while True:\n print()\n print(\"1. Search a book\")\n print(\"2. Borrow a book\")\n print(\"3. Return a book\")\n print(\"4. Logout\")\n selection = input(\"Select an option: \")\n print()\n\n try:\n if(selection == \"1\"):\n self.searchBook(user)\n elif(selection == \"2\"):\n self.borrowBook(user)\n elif(selection == \"3\"):\n self.returnBook(user)\n elif(selection == \"4\"):\n print(\"Goodbye!\")\n return \"logout\"\n else:\n print(\"Invalid input - please try again.\")\n except Exception as e:\n logging.error(\"Library menu error: {}\".format(str(e)))\n return \"login\"\n\n def insertUser(self, name):\n with DatabaseUtils() as db:\n if(db.insertUser(name)):\n # print(\"{} inserted successfully.\".format(name))\n pass\n else:\n print(\"{} failed to be inserted.\".format(name))\n \n # Search a book\n def searchBook(self, user):\n \"\"\"\n There are three methods to search for a book:\n 1- Search by book's title\n 2- Search by book's author\n 3. Search by ISBN\n By selecting any option LMS prompts user to enter title/author/ISBN and retrieves the result in a table\n Parameters:\n\n Returns:\n\n \"\"\"\n\n while True:\n print()\n print(\"1. Search by title\")\n print(\"2. Search by author\")\n print(\"3. Search by ISBN\")\n print(\"4. back\")\n selection = input(\"Select an option: \")\n print()\n\n try:\n if(selection == \"1\"):\n title = self.SearchByVoiceOrText(\"title\")\n title_result=self.listBooksByTitle(title)\n elif(selection == \"2\"):\n author = self.SearchByVoiceOrText(\"author\")\n author_result=self.listBooksByAuthor(author)\n elif(selection == \"3\"):\n isbn = self.SearchByVoiceOrText(\"ISBN\")\n isbn_result=self.listBooksByISBN(isbn)\n elif(selection == \"4\"):\n break\n else:\n print(\"Invalid input - please try again.\")\n if title_result==True or isbn_result==True or author_result==True:\n self.borrowBook(user)\n except Exception as e:\n logging.error(\"Search menu error: {}\".format(str(e)))\n\n def SearchByVoiceOrText(self, subject):\n \"\"\"\n We can search a book by typing on the command line or talking to google voice recognition.\n\n Parameters:\n\n Returns:\n\n \"\"\"\n while True:\n print()\n print(\"1. Search through command line\")\n print(\"2. Search through voice\")\n print(\"3. back\")\n selection = input(\"Select an option: \")\n print()\n\n try:\n if(selection == \"1\"):\n return input(\"Enter book's \"+subject+\": \")\n elif(selection == \"2\"):\n return voice_recognition.getTextFromVoice()\n elif(selection == \"3\"):\n break\n else:\n print(\"Invalid input - please try again.\")\n except Exception as e:\n logging.error(\"Search menu error: {}\".format(str(e)))\n\n # Borrow a book\n def borrowBook(self, user):\n\n \"\"\"\n this method allows the user to borrow a book from the library if it is avilabel.\n It also add event to Google calendar with user and book details\n \n Parameters: username\n \"\"\"\n\n print('Please Note that you only can borrow a book by its ISBN. If you do not know the ISBN, please go back to the menu and search the book first')\n # prompt the user for book's ISBN\n book_isbn = input('Please type the ISBN here or hit q to go back to menu: \\n')\n # exit if user hits q\n if book_isbn == 'q': exit\n # call DatabaseUtils class and create an object of it\n db_object = DatabaseUtils()\n # call library menu class and create an object of it\n lm_object = library_menu()\n # get today's date\n now = datetime.datetime.now()\n today_date = now.strftime(\"%Y-%m-%d\")\n # remove spaces\n book_isbn = book_isbn.strip()\n # check if the user typed the ISBN\n regex= r'978[\\d\\-]+\\d'\n pattern = re.match(regex, book_isbn)\n if bool(pattern)==True:\n # call the getBookByISBN function to check if the book exists at the library\n book_list = db_object.getBookByISBN(book_isbn)\n # convert to list\n book_list = list(book_list)\n # if the book doesn't exist, the apologize for the user\n if not book_list:\n print('We are sorry, we do not have the book at the moment')\n # if the book exists\n else:\n # boolean variable to check that the user only borrows one copy of a book at a time\n #bool_borroed = False\n # loop through all the copies of the same book and check which one is avilable to borrow\n for i in book_list:\n # check if the book is avilable to borrow\n return_value = db_object.getAvilableBook(i[0])\n #if return_value == True and bool_borroed == False:\n if return_value == True:\n # get book details from the library\n book_details = db_object.getBookByID(i[0])\n book_details = list(book_details)\n # add leading zeros to the book id to be able to add an event\n # since the id in google calendar must be at least 5 digits\n id_event = '00000' + str(book_details[0][0])\n # add an event to the calendar with the book details\n bookevent.insert(user, id_event, book_details[0][2], book_details[0][3])\n # check if the user exists in LmsUser table\n check_user_in_LmsUser = db_object.getUser(user)\n if check_user_in_LmsUser == False:\n # add the user the LmsUser table to keep track of users who borrowed book\n lm_object.insertUser(user)\n # insert book and user details to BookBorrowed table\n db_object.insertBookBorrowed(user, book_details[0][0], 'borrowed', today_date)\n # print success message\n print(\"You have successfully borrowed: \" + book_details[0][2])\n #bool_borroed = True\n return True\n # elif return_value == False and i == len(book_list)-1:\n # if the book is not avilable, the print a message to the user\n print('Sorry but the book is not avilable')\n return False\n else:\n print(\"Your Input does not match book's ISBN\")\n # Return a book\n def returnBook(self, user): \n \"\"\"\n allow the user to return a book\n\n Paramters: user\n \"\"\"\n\n # prompt the user to choose between entering the ISBN manually or scanning the QR code\n option=int(input('Please choose\\n 1.Manually Enter the detail\\n 2.Return the book using QR code \\n'))\n if option==1 :\n # prompt the user for the book ISBN\n user_input = input('Please type your book ISBN to continue with return process\\n')\n # if user choses to scan a QR code\n elif option==2:\n # call the barcodescanner file\n user_input = barcodescanner.scanQR()\n # strip the ISBN if it has spaces\n user_input = user_input.strip()\n # if the ISBN code does not match the format then exit\n if user_input == \"quitbyuser\":\n exit\n\n # call DatabaseUtils class and create an object of it\n db_object = DatabaseUtils()\n\n # get today's date\n now = datetime.datetime.now()\n today_date = now.strftime(\"%Y-%m-%d\")\n # check if the user typed the ISBN\n regex= r'978[\\d\\-]+\\d'\n pattern = re.match(regex, user_input)\n\n if bool(pattern)==True:\n # check if the book has been borrowed at the first place\n return_value, t_value = db_object.checkIfBookExistsInBookBorrowed(user_input, user)\n if isinstance(return_value, int) and t_value == True:\n id_event = '00000' + str(return_value)\n # remove the event from Google Calendar\n bookevent.removeEvent(id_event)\n # update the status of the book in BookBorrowed table\n db_object.updateBookBorrowed(user, return_value, 'returned', today_date)\n # print a message to the user\n print('We hope that you enjoyed your journey reading the book')\n return True\n # if the book doesn't exist in the BookBorrowed table, then it means the book has not been borrowed\n else:\n print('We apologize, the ISBN you entered has not been borrowed by you!')\n return False\n # if the user typed something else rather than book ISBN\n else:\n print('Your Input does not match books ISBN')\n return False\n\n # list books by title\n def listBooksByTitle(self, title):\n \"\"\"\n Search books by book name\n Parameters:\n Book title\n Returns:\n All books with the title name\n \"\"\"\n print(\"--- Books ---\")\n table = PrettyTable(['ISBN','Title', 'Author'])\n with DatabaseUtils() as db:\n books = db.getBookByTitle(title)\n if(len(books) > 0):\n for book in books:\n table.add_row([book[1], book[2], book[3]])\n print(table)\n return True\n else:\n print(\"Book not found! please try again.\")\n return False\n\n # list books by author \n def listBooksByAuthor(self, author):\n \"\"\"\n Search books by their author.\n Parameters:\n Author of a book\n Returns:\n All books which have been written by the author\n \"\"\"\n print(\"--- Books ---\")\n table = PrettyTable(['ISBN','Title', 'Author'])\n with DatabaseUtils() as db:\n books = db.getBookByAuthor(author)\n if(len(books) > 0):\n for book in books:\n table.add_row([book[1], book[2], book[3]])\n print(table)\n return True\n else:\n print(\"Book not found! please try again.\")\n return False\n\n # list books by ISBN\n def listBooksByISBN(self, isbn):\n \"\"\"\n Search Books by ISBN. \n Parameters:\n ISBN\n Returns:\n All books which have the ISBN\n \"\"\"\n\n print(\"--- Books ---\")\n table = PrettyTable(['ISBN','Title', 'Author'])\n with DatabaseUtils() as db:\n books = db.getBookByISBN(isbn)\n if(len(books) > 0):\n for book in books:\n table.add_row([book[1], book[2], book[3]])\n print(table)\n return True\n else:\n print(\"Book not found! please try again.\")\n return False\n\n\n \n\n\n" }, { "alpha_fraction": 0.6951501369476318, "alphanum_fraction": 0.7182447910308838, "avg_line_length": 27.866666793823242, "blob_id": "88cd966e892d159a7e325ffd1ba0bd5a97ae1358", "content_id": "7cee5fe0cb6f82e3125dcda0791b7c5f1e677538", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 433, "license_type": "no_license", "max_line_length": 69, "num_lines": 15, "path": "/mp/webapp/API/flask_site.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "from flask import Flask, Blueprint, request, jsonify, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\nimport os, requests, json\n\nsite = Blueprint(\"site\", __name__)\n\n# Client webpage.\[email protected](\"/\")\ndef index():\n # Use REST API.\n response = requests.get(\"http://127.0.0.1:5001/book\")\n data = json.loads(response.text)\n\n return render_template(\"index.html\", people=data)\n" }, { "alpha_fraction": 0.7278037667274475, "alphanum_fraction": 0.7348130941390991, "avg_line_length": 33.279998779296875, "blob_id": "e397449322b035b7fc587743d97fa2334e354720", "content_id": "fda9dce3e9eaf2787d2510fcd239132f6123d438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 856, "license_type": "no_license", "max_line_length": 92, "num_lines": 25, "path": "/mp/cloud_db_schema.sql", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "create table IF NOT EXISTS LmsUser (\n UserName nvarchar(256) not null,\n constraint PK_LmsUser primary key (UserName),\n constraint UN_UserName unique (UserName)\n);\n\ncreate table IF NOT EXISTS Book (\n\tBookID int not null auto_increment,\n ISBN text not null,\n Title text not null,\n Author text not null,\n constraint PK_Book primary key (BookID)\n);\n\ncreate table IF NOT EXISTS BookBorrowed (\n\tBookBorrowedID int not null auto_increment,\n UserName nvarchar(256) not null,\n BookID int not null,\n Status enum ('borrowed', 'returned'),\n BorrowedDate date not null,\n ReturnedDate date null,\n constraint PK_BookBorrowed primary key (BookBorrowedID),\n constraint FK_BookBorrowed_LmsUser foreign key (UserName) references LmsUser (UserName),\n constraint FK_BookBorrowed_Book foreign key (BookID) references Book (BookID)\n);" }, { "alpha_fraction": 0.722806990146637, "alphanum_fraction": 0.722806990146637, "avg_line_length": 30.55555534362793, "blob_id": "18951fe82c859bc5e72a7496f1fddfe33da61954", "content_id": "f626e2f053e78a7e7e8440222729f573de7ded6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 78, "num_lines": 9, "path": "/mp/webapp/API/get_installed.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "\n\"\"\"\n This file will print all the pythons currently running in the environment\n\n\"\"\"\nimport pip\ninstalled_packages = pip.get_installed_distributions()\ninstalled_packages_list = sorted([\"%s==%s\" % (i.key, i.version)\n for i in installed_packages])\nprint(installed_packages_list)\n" }, { "alpha_fraction": 0.5158730149269104, "alphanum_fraction": 0.5158730149269104, "avg_line_length": 20.16666603088379, "blob_id": "9a565c0a356575eb46de79d220c9ab63b5c947bc", "content_id": "3894b2927f15220391e2d0a15064a391ad791729", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 126, "license_type": "no_license", "max_line_length": 30, "num_lines": 6, "path": "/build/html/_sources/mp_library_menu.rst.txt", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Master Pi Library Menu\n========================\n .. module:: mp_library_menu\n\n .. autoclass:: library_menu\n :members:" }, { "alpha_fraction": 0.6452991366386414, "alphanum_fraction": 0.6452991366386414, "avg_line_length": 26.47058868408203, "blob_id": "cad75cbb23af0aa9a6a3ec19c62a5290024adec0", "content_id": "7defb638f3cb4050dbce51b34dceaeb469d565c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 46, "num_lines": 17, "path": "/mp/test_library_menu.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "from library_menu import library_menu\nimport unittest\n\nclass TestBorrowReturn(unittest.TestCase):\n def setUp(self):\n self.user=\"Brad\"\n self.menu=library_menu(self.user)\n def testBorrow(self):\n result=self.menu.borrowBook(self.user)\n self.assertTrue(result,True)\n \n def testReturn(self):\n result=self.menu.returnBook(self.user)\n self.assertTrue(result,True)\n \nif __name__ == \"__main__\":\n unittest.main()\n\n" }, { "alpha_fraction": 0.5961504578590393, "alphanum_fraction": 0.5982694625854492, "avg_line_length": 35.77922058105469, "blob_id": "c53ec957eeb3543c5d28be969b226c544ee4572f", "content_id": "859f5c64b257c413e6dace4a9264e70e65dd8158", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5663, "license_type": "no_license", "max_line_length": 166, "num_lines": 154, "path": "/rp/db.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# import packages\nfrom passlib.hash import sha256_crypt\nfrom datetime import date\nimport sqlite3\nimport time\n\n# database name\ndbname=\"Recepition_Pi.db\"\n\n# start of a class\nclass database:\n\n # connection method\n @staticmethod\n def connection(): \n \"\"\"\n This method connects to the local database and returns the connection\n\n Returns:\n connection object\n \"\"\"\n # connect to the database\n conn = sqlite3.connect(dbname)\n database.create_tables(conn)\n # return connection\n return conn\n\n # create tables method\n @staticmethod\n def create_tables(conn):\n \"\"\"\n This method creates two tables. user and account table\n \"\"\"\n # call the connection method which returns the connection object\n # conn = database.connection()\n with conn:\n # move the cursor to the top\n cur = conn.cursor()\n # drop table account if exists\n # cur.execute(\"DROP TABLE IF EXISTS account\")\n # create a table named account with the variables: username, and password\n cur.execute(\"CREATE TABLE IF NOT EXISTS account(username TEXT NOT NULL PRIMARY KEY,password TEXT)\")\n # drop table user if exists\n # cur.execute(\"DROP TABLE IF EXISTS user\")\n # create a table named user with the variables: firstname, lastname, username, and email\n cur.execute(\"CREATE TABLE IF NOT EXISTS user(firstname TEXT,lastname TEXT,username TEXT, email TEXT,FOREIGN KEY (username) REFERENCES ACCOUNT(username))\")\n\n # insert data method \n @staticmethod\n def insertData(username,password,firstname,lastname,email):\n\n \"\"\"\n This method inserts data to two tables. account table and user table\n\n Parameters:\n \n username: the username of the user\n password: password of the user after it's been hashed\n firstname: user's first name\n lastname: user's last name\n email: user's email address\n\n \"\"\"\n\n # call the connection method which returns the connection object\n conn=database.connection()\n with conn:\n # move the cursor to the top\n cur = conn.cursor()\n # try clause\n try:\n # insert username and password into account table \n cur.execute(\"INSERT INTO account values(?,?)\",(username,password))\n # insert firstname, lastname, username, email into user table\n cur.execute(\"INSERT INTO user values(?,?,?,?)\",(firstname,lastname,username,email))\n # except clause\n except:\n # since username is primary key, we can't add more than once.\n # So print the message below if trying to insert duplicate username\n print(\"Username already exists!\")\n\n # veriftPassword method\n @staticmethod\n def veriftPassword(username,password):\n \"\"\"\n This method verifies if the password that is associated with the username is right\n\n Parameters:\n \n username: user's username\n password: hashed value for the user's password\n\n Returns:\n \n True: check if the passed password equals the password that is associated with the username in account table\n False: if the passed password does not equal the password that is associated with the username in account table\n\n \"\"\"\n\n # call the connection method which returns the connection object\n conn=database.connection()\n with conn:\n # move the cursor to the top\n cur = conn.cursor()\n # assign the output of the sql code to a result variable after converting the sql object into a python list\n result = list(cur.execute(\"SELECT password FROM account WHERE USERNAME = ?\",(username,)))\n # check if the passed password equals the password that is associated with the username in account table\n if(sha256_crypt.verify(password, result[0][0])):\n return True\n # if result is empty which means username does exists in the account table, then return false\n else:\n return False\n \n\n # if password == result[0][0]:\n # print('True')\n # return True\n # # else return False\n # else: \n # print('False')\n # return False\n\n # check username exists method\n @staticmethod\n def checkusernameexists(username):\n \"\"\"\n This method checks if the username is already in the account table\n\n Parameters:\n \n username: user's username\n\n Returns:\n \n True: true if username does not exist\n False: false if username exists\n\n \"\"\"\n # call the connection method which returns the connection object\n try:\n conn=database.connection()\n with conn:\n # move the cursor to the top \n cur=conn.cursor()\n # assign the output of the sql code to a result variable after converting the sql object into a python list\n result = list(cur.execute(\"SELECT * FROM account WHERE USERNAME = ?\",(username,)))\n # if result is empty which means username does not exist, then return true\n if not result:\n return True\n # if result is empty which means username does exists in the account table, then return false\n else:\n return False\n except Exception as e:\n print(\"Error: \" + str(e))" }, { "alpha_fraction": 0.640406608581543, "alphanum_fraction": 0.664548933506012, "avg_line_length": 28.074073791503906, "blob_id": "c36b51a6b87afc9c347ea2fd10d80f3e5fae5d02", "content_id": "f775579809973b1021e3f2085206b7c924f257c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 75, "num_lines": 27, "path": "/mp/test_database_utils.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# Reference: https://docs.python.org/2/library/unittest.html\nimport unittest\nimport MySQLdb\nfrom database_utils import DatabaseUtils\n\nclass TestDatabaseUtils(unittest.TestCase):\n def setUp(self):\n self.db = DatabaseUtils()\n\n def test_getBookByISBN(self,):\n result = self.db.getBookByISBN('9781925483598')\n print(result)\n self.assertTrue(result[0][2],\"THE SUBTLE ART OF NOT GIVING A FUCK\")\n\n def test_getBookByTitle(self,):\n result = self.db.getBookByTitle('test')\n self.assertTrue(result.count,0)\n\n def test_getBookByAuthor(self,):\n result = self.db.getBookByAuthor('MARK MANSON')\n print(result)\n self.assertTrue(result[0][2],\"THE SUBTLE ART OF NOT GIVING A FUCK\")\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n" }, { "alpha_fraction": 0.6595988273620605, "alphanum_fraction": 0.6650429964065552, "avg_line_length": 33.2156867980957, "blob_id": "8fbf436d948f6523f1737506d97c4ae549252614", "content_id": "02ce0e0fbb92871c04fdfbced06ce57f859ab364", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3506, "license_type": "no_license", "max_line_length": 112, "num_lines": 102, "path": "/build/html/_sources/index.rst.txt", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": ".. Smart Library documentation master file, created by\n sphinx-quickstart on Sat May 18 09:47:21 2019.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nWelcome to Smart Library's documentation!\n=========================================\nConfiguration of Project Environment\n*************************************\n\nThis system is provided to the local council library to automate the Library Management\nSystem (LMS). This system will be used to borrow, return and maintain the backend information.\nThe application has two types of users: library user and library admin.\nThis system uses Google Calendar API to work with your Raspberry Pi using Google Cloud IoT Platform.\n\nApplication Components\n======================\n• Python documentation tools (Sphinx)\n• Unit testing in Python\n• Socket Programming\n• An API using Python’s microframework Flask\n• AI features (facial recognition, object detection and Voice detection)\n• Cloud databases\n\n\nOverview on How to Run this Application\n=======================================\n1. Download the app into two raspberry PIs, one is the master pi and the other is recieption pi\n2. Install necessary packages mentioned on top of each class\n\nSetup procedure\n================\n1. Master Pi\n On the MP Command line go to MP folder \n - Type the command below on the command line environment. ::\n\n python3 mp_socket.py\n\n2. Recieption Pi\n On the RP Command line go to RP folder \n - Type the command below on the command line environment. ::\n\n python3 user.py\n\nLMS features\n============\n A. For library users: \n The library user arrives at the reception. It is not manned by any person. The\n RECEPTION PI (RP) provides two options available for logging into the system:\n - using console-based system which allows them to type in the user credentials or,\n - using a facial recognition system\n The user registration is required for the first-time user. Upon registration the details are stored in a\n local database installed on RP.\n Upon logging in, a success message along with the username is sent from RP to the MASTER PI\n (MP) via sockets.\n The user is now presented with another console-based application:\n - search for book catalogues based on ISBN/Author name/Book name\n - option for borrowing a book/books\n - option for returning a book/books\n - logout\n Upon logging out a message is sent via sockets from MP to RP.\n\n B. For library admin: \n This is a separate website application that runs on MP. It can only be accessed\n by admin personnel.\n Admin website makes use of an API to\n - Add books to catalogue\n - Remove books and\n - Generate a data visualisation report for books borrowed (day wise).\n The book database is stored on a cloud environment namely the Google’s GCP IoT platform\n (Google Cloud Platform).\n\nDocumentation for the Code\n**************************\n.. toctree::\n :maxdepth: 2\n :caption: Contents:\n\n mp_socket\n mp_library_menu\n mp_database_utils\n mp_bookevent\n mp_barcodescanner\n mp_voice_recognition\n mp_controller\n mp_login_controller\n\n rp_user\n rp_socket\n rp_db\n rp_encode\n rp_capture\n rp_recognise\n\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n" }, { "alpha_fraction": 0.6346555352210999, "alphanum_fraction": 0.6388309001922607, "avg_line_length": 26.11320686340332, "blob_id": "623a645562f58cee3408ad4ddb4d67d77d8e5063", "content_id": "7733681b29a95e215bae516fb2270bf6af6bf4f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2874, "license_type": "no_license", "max_line_length": 98, "num_lines": 106, "path": "/mp/webapp/API/flask_api.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "from flask import Flask, Blueprint, request, jsonify, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\nimport os, requests, json\nfrom flask import current_app as app\n\napi = Blueprint(\"api\", __name__)\n\ndb = SQLAlchemy()\nma = Marshmallow()\n\n\n# Declaring the model.\nclass Book(db.Model):\n __tablename__ = \"Book\"\n BookID = db.Column(db.Integer, primary_key=True, autoincrement=True)\n ISBN = db.Column(db.Text, nullable=False)\n Title = db.Column(db.Text, nullable=False)\n Author = db.Column(db.Text, nullable=False)\n \n def __init__(self, ISBN, Title, Author, BookID=None):\n self.BookID = BookID\n self.ISBN = ISBN\n self.Title = Title\n self.Author = Author\n\nclass bookWithStatus():\n def __init__(self, ISBN, Title, Author, BookID=None):\n self.BookID = BookID\n self.ISBN = ISBN\n self.Title = Title\n self.Author = Author\n self.status = \"returned\"\n \n def toJSON(self):\n return {\"BookID\": self.BookID,\n \"ISBN\": self.ISBN,\n \"Title\": self.Title,\n \"Author\": self.Author,\n \"Status\": self.status}\n\nclass BookSchema(ma.Schema):\n # Reference: https://github.com/marshmallow-code/marshmallow/issues/377#issuecomment-261628415\n def __init__(self, strict=True, **kwargs):\n super().__init__(strict=strict, **kwargs)\n \n class Meta:\n # Fields to expose.\n fields = (\"BookID\", \"ISBN\", \"Title\", \"Author\")\n\nBooksSchema = BookSchema(many=True)\nBookSchema = BookSchema()\n\n# Endpoint to show all books\[email protected](\"/book\", methods=[\"GET\"])\ndef getBooks():\n books = Book.query.all()\n result = BooksSchema.dump(books)\n\n return jsonify(result.data)\n\n# Endpoint to get a book\[email protected](\"/book/<id>\", methods=[\"GET\"])\ndef getBook(id):\n person = Book.query.get(id)\n\n return BookSchema.jsonify(person)\n\n# Endpoint to create a new book\[email protected](\"/book\", methods=[\"POST\"])\ndef addBook():\n ISBN = request.json[\"ISBN\"]\n Title = request.json[\"Title\"]\n Author = request.json[\"Author\"]\n\n newBook = Book(ISBN=ISBN, Title=Title, Author=Author)\n\n db.session.add(newBook)\n db.session.commit()\n\n return BookSchema.jsonify(newBook)\n\n# Endpoint to update a book\[email protected](\"/book/<id>\", methods=[\"PUT\"])\ndef personUpdate(id):\n print(\"ISBN:\" + request.json[\"ISBN\"])\n book = Book.query.get(id)\n ISBN = request.json[\"ISBN\"]\n Title = request.json[\"Title\"]\n Author = request.json[\"Author\"]\n book.ISBN = ISBN\n book.Title = Title\n book.Author = Author\n\n db.session.commit()\n\n return BookSchema.jsonify(book)\n\n# Endpoint to delete a book\[email protected](\"/book/<id>\", methods=[\"DELETE\"])\ndef personDelete(id):\n book = Book.query.get(id)\n db.session.delete(book)\n db.session.commit()\n\n return BookSchema.jsonify(book)\n" }, { "alpha_fraction": 0.5989189147949219, "alphanum_fraction": 0.6010810732841492, "avg_line_length": 32.03571319580078, "blob_id": "e881c04ed02365fd2fa4177d41de17c26e1e6e4f", "content_id": "902638916a0351a257fc4cf91a54440d6c64b96c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 925, "license_type": "no_license", "max_line_length": 78, "num_lines": 28, "path": "/mp/socket_test.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# Reference: https://docs.python.org/2/library/unittest.html\nimport unittest\nfrom mp_socket import mp_socket\n\nclass mp_socket_test(unittest.TestCase):\n def test_setupServer(self):\n print(\"Test Setup Server\")\n self.assertEqual(mp_socket().connection(\"test_setupServer\"), True)\n\n def test_ConnectToServer(self):\n print(\"-------------------------\")\n print(\"Test Connect to Server\")\n self.assertEqual(mp_socket().connection(\"test_ConnectToServer\"), True)\n\n # def test_isupper(self):\n # self.assertTrue(\"FOO\".isupper())\n # self.assertFalse(\"Foo\".isupper())\n\n # def test_split(self):\n # s = \"hello world\"\n # self.assertEqual(s.split(), [\"hello\", \"world\"])\n \n # # Check that s.split fails when the separator is not a string.\n # with self.assertRaises(TypeError):\n # s.split(2)\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.5308454036712646, "alphanum_fraction": 0.5346534848213196, "avg_line_length": 31.850000381469727, "blob_id": "0975bec427d9a6b3b489aa85467cc0bc0deaf6a0", "content_id": "a5ef75cd3f24de6f72093a0a2de18d88dc6bfc59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1313, "license_type": "no_license", "max_line_length": 72, "num_lines": 40, "path": "/rp/rp_socket.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# Reference: https://realpython.com/python-sockets/\n# Documentation: https://docs.python.org/3/library/socket.html\n\nimport socket\nimport logging\nimport json\n\nlogging.basicConfig(filename=\"library.log\", level = logging.ERROR)\nclass rp_socket:\n\n # Call connection after successful login\n def connection(self, user=\"test\"): \n try:\n jsonData = self.readConfig()\n HOST = jsonData[\"hostname\"]\n PORT = jsonData[\"port\"] \n ADDRESS = (HOST, PORT)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect(ADDRESS)\n print(\"Connected to {}...\".format(ADDRESS))\n\n while True: \n s.sendall(user.encode())\n # listen to message from server:\n data = s.recv(4096)\n message = data.decode()\n print(\"Message from MP: \" + message)\n if(message == \"logout\"):\n return message\n except Exception as e:\n logging.error(\"RP Socket error: {}\".format(str(e)))\n print(str(e))\n\n\n\n # Read config.json\n def readConfig(self):\n with open('config.json') as jsonFile: \n data = json.load(jsonFile)\n return data" }, { "alpha_fraction": 0.4956521689891815, "alphanum_fraction": 0.4956521689891815, "avg_line_length": 18.33333396911621, "blob_id": "dcef316a610879afb90a2c2e2af0c62720e5fb52", "content_id": "29a31d2e812c245bc428223b328c58b73697e1ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 115, "license_type": "no_license", "max_line_length": 25, "num_lines": 6, "path": "/source/rp_capture.rst", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Recieption Pi Capture\n========================\n .. module:: rp_capture\n\n .. autoclass:: capture\n :members:" }, { "alpha_fraction": 0.4528301954269409, "alphanum_fraction": 0.4528301954269409, "avg_line_length": 16.83333396911621, "blob_id": "fe68f4920c5667e9abe25d8f25211f0cc0b6ba2b", "content_id": "1577e0c55d4af2cfa42c48c7a7457a9c467b91a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 106, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/source/rp_user.rst", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Recieption Pi User\n========================\n .. module:: rp_user\n\n .. autoclass:: user\n :members:" }, { "alpha_fraction": 0.5563910007476807, "alphanum_fraction": 0.5563910007476807, "avg_line_length": 21.33333396911621, "blob_id": "18530ff882eecbc15d67ee25dcbd9be4c58778a4", "content_id": "5c636eb4f47b98e5b13723eb1fcd4cc04cc0aa12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 133, "license_type": "no_license", "max_line_length": 32, "num_lines": 6, "path": "/source/mp_barcodescanner.rst", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Master Pi Barcode Scanner\n========================\n .. module:: mp_barcodescanner\n\n .. autoclass:: barcodescanner\n :members:" }, { "alpha_fraction": 0.5390625, "alphanum_fraction": 0.5390625, "avg_line_length": 20.5, "blob_id": "d2958317d72c7896e34e3a9b6213a16307bcb40c", "content_id": "ac8b479bb3fb12df8dc365703db1c98bddecc1ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 128, "license_type": "no_license", "max_line_length": 31, "num_lines": 6, "path": "/build/html/_sources/database_utils.rst.txt", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Master Pi Database Utils\n========================\n .. module:: database_utils\n\n .. autoclass:: DatabaseUtils\n :members:" }, { "alpha_fraction": 0.5301957726478577, "alphanum_fraction": 0.5506039261817932, "avg_line_length": 29.794872283935547, "blob_id": "861349bed9afe2e43bf86286d9bffa15ea994899", "content_id": "ca17938bbdfa7ac5457009c813d69e478dadf270", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2401, "license_type": "no_license", "max_line_length": 92, "num_lines": 78, "path": "/source/rp_capture.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# # USAGE\n# # With default parameter of user/id\n# # python3 01_capture.py -n default_user\n# # OR specifying the dataset and user/id\n# # python3 02_capture.py -i dataset -n default_user\n\n# ## Acknowledgement\n# ## This code is adapted from:\n# ## https://www.hackster.io/mjrobot/real-time-face-recognition-an-end-to-end-project-a10826\n\n\n# # references:\n# # Programming Internet of Things - Lab week 09\n\n# # import the necessary packages\n# # import the necessary packages\n# import cv2\n# import os\n# import argparse\n\n# class capture\nclass capture:\n\n # main method\n @staticmethod\n def main(username):\n\n \"\"\"\n main method, open the camera video and takes multiple pictures of the user face\n\n parameters: username - which create a folder for each user\n \"\"\"\n\n # # use name as folder name\n # name = username\n # folder = './dataset/{}'.format(name)\n\n # # Create a new folder for the new name\n # if not os.path.exists(folder):\n # os.makedirs(folder)\n\n # # Start the camera\n # cam = cv2.VideoCapture(0)\n # # Set video width\n # cam.set(3, 640)\n # # Set video height\n # cam.set(4, 480)\n # # Get the pre-built classifier that had been trained on 3 million faces\n # face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n # # Create a window\n # #cv2.namedWindow(\"Saving Images... (Press Escape to end)\")\n\n # img_counter = 0\n # while img_counter <= 10:\n # key = input(\"Press q to quit or ENTER to continue: \")\n # if key == 'q':\n # break\n\n # ret, frame = cam.read()\n # if not ret:\n # break\n \n # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # faces = face_detector.detectMultiScale(gray, 1.3, 5)\n\n # if(len(faces) == 0):\n # print(\"No face detected, please try again\")\n # continue\n\n # for (x,y,w,h) in faces:\n # cv2.rectangle(frame, (x,y), (x+w,y+h), (255,0,0), 2)\n # img_name = \"{}/{:04}.jpg\".format(folder,img_counter)\n # cv2.imwrite(img_name, frame[y:y+h,x:x+w])\n # print(\"{} written!\".format(img_name))\n # img_counter += 1\n\n # cam.release()\n # cv2.destroyAllWindows()" }, { "alpha_fraction": 0.6157804727554321, "alphanum_fraction": 0.6157804727554321, "avg_line_length": 28.200000762939453, "blob_id": "ab4f21bd984d969b7bb261740ffeff343304381c", "content_id": "d3e4ca63ed0e4f8e205054da730f48d8db272d3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 583, "license_type": "no_license", "max_line_length": 79, "num_lines": 20, "path": "/mp/webapp/login_controller.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "from flask import request\n\nUSERNAME = \"jaqen\"\nPASSWORD = \"hgar\"\n\nclass login_controller:\n\n @staticmethod\n def validate_login(request):\n \"\"\"\n This method validates login information\n Parameters: The request object\n Returns: True: Details were correct, False: Details were incorrect.\n \"\"\"\n sent_username = request.form.get('username')\n sent_password = request.form.get('password')\n if(sent_username == USERNAME and sent_password == PASSWORD):\n return True\n else:\n return False" }, { "alpha_fraction": 0.5673469305038452, "alphanum_fraction": 0.5868480801582336, "avg_line_length": 37.017242431640625, "blob_id": "f3959b40611854bbb7b5659b7537aae1bb52ddb3", "content_id": "55218db24e79458e99892fafc8f56278fa855dcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2205, "license_type": "no_license", "max_line_length": 166, "num_lines": 58, "path": "/mp/barcodescanner.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "## This code is adapted from:\n## https://www.pyimagesearch.com/2018/05/21/an-opencv-barcode-and-qr-code-scanner-with-zbar/\n## pip3 install pyzbar\n\n# Reference: COSC2674 - Programming Internet of Things - lab 10\n\n# import the necessary packages\nfrom imutils.video import VideoStream\nfrom pyzbar import pyzbar\nimport datetime\nimport imutils\nimport time\nimport cv2\nimport re\n\nclass barcodescanner:\n @staticmethod\n def scanQR():\n\n \"\"\"\n Scan a QR code and convert it to a string\n\n Returns: QR code string\n \"\"\"\n\n # initialize the video stream and allow the camera sensor to warm up\n #https://www.qr-code-generator.com/\n # loop over the frames from the video stream\n while True:\n user_input=input(\"Please go to this website https://www.qr-code-generator.com/ to generate QR code with TEXT format.\\nHit Enter to continue or q to quit\")\n if(user_input=='q'):\n return \"quitbyuser\"\n print(\"Put QR Code in front of the camera\")\n vs = VideoStream(src = 0).start()\n time.sleep(2.0)\n # grab the frame from the threaded video stream and resize it to\n # have a maximum width of 400 pixels\n frame = vs.read()\n frame = imutils.resize(frame, width = 400)\n # find the barcodes in the frame and decode each of the barcodes\n barcodes = pyzbar.decode(frame)\n # loop over the detected barcodes\n for barcode in barcodes:\n # the barcode data is a bytes object so we convert it to a string\n barcodeData = barcode.data.decode(\"utf-8\")\n barcodeType = barcode.type\n # check if the user typed the ISBN\n regex= r'978[\\d\\-]+\\d'\n pattern = re.match(regex, barcodeData)\n if bool(pattern)==True:\n vs.stop()\n return barcodeData \n else:\n print(\"QR does not follow the format.\\nMake sure the format is 978-0-00-000000-0\")\n vs.stop()\n # wait a little before scanning again\n time.sleep(1)\n vs.stop()\n" }, { "alpha_fraction": 0.5251798629760742, "alphanum_fraction": 0.5251798629760742, "avg_line_length": 19, "blob_id": "20997907abc9274491d159cd00cfb452431e20e7", "content_id": "370ecd6ac7de114d5613d18dee599b24fa32da70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 139, "license_type": "no_license", "max_line_length": 33, "num_lines": 7, "path": "/source/mp_controller.rst", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Master Pi Web App Controller\n=============================\n\n .. module:: mp_controller\n\n .. autoclass:: RouteController\n :members:" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5, "avg_line_length": 18.83333396911621, "blob_id": "47950cce69f60a6aab9f6989681d9ebc2c6bb6d1", "content_id": "a270a5cc8866387e494cc5ceb3a43e24152e8de7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 118, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/source/mp_bookevent.rst", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Master Pi Book Event\n========================\n .. module:: mp_bookevent\n\n .. autoclass:: bookevent\n :members:" }, { "alpha_fraction": 0.518482506275177, "alphanum_fraction": 0.5256161093711853, "avg_line_length": 43.69565200805664, "blob_id": "c6e0111da66e205aa1b48d1e81409786eef9a134", "content_id": "1f170712bc15bf8e9a0d24529c29ec047a897ded", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3084, "license_type": "no_license", "max_line_length": 128, "num_lines": 69, "path": "/mp/mp_socket.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Reference: https://realpython.com/python-sockets/\n# Documentation: https://docs.python.org/3/library/socket.html\n\nimport socket\nfrom library_menu import library_menu\nimport logging\n\nlogging.basicConfig(filename=\"library.log\", level = logging.ERROR)\nclass mp_socket:\n def connection(self, test = None):\n \"\"\"\n Server connetion is to start a TCP socket on the Master Pi (server) so that all reception PIs can connect to the server.\n On setting up the connection, server listens to the connection requests and the coming messages.\n This message will be the logged in user name which will be used for book borrowing purpose.\n When the user selects logout from the library menu, the server will send \"logout\" message to RP\n and RP is required to logout the user. The server stands by until another user logs in\n\n Parameters:\n\n Returns:\n\n \"\"\"\n testPassed = False\n HOST = \"\" # Empty string means to listen on all IP's on the machine, also works with IPv6.\n # Note \"0.0.0.0\" also works but only with IPv4.\n PORT = 65000 # Port to listen on (non-privileged ports are > 1023).\n ADDRESS = (HOST, PORT)\n try:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind(ADDRESS)\n s.listen()\n print(\"Listening on {}...\".format(ADDRESS))\n # Test server connection:\n if(test == \"test_setupServer\"):\n return True\n while True:\n print(\"The Smart Library is Ready be Accessed! Waiting for a User to Login . . .\")\n conn, addr = s.accept()\n with conn:\n print(\"Connected to {}\".format(addr))\n # test client connection\n if(test == \"test_ConnectToServer\"):\n testPassed = True\n else:\n data = conn.recv(4096)\n if(data):\n #Received message from RP \n user = data.decode() \n # print(\"Message from rp: \" + user)\n # Call library menu to search books/borrow books/return books\n logout_req = library_menu().runMenu(user)\n if(logout_req == \"logout\"):\n conn.sendall(logout_req.encode())\n\n print(\"Disconnecting from client.\")\n print(\"Closing listening socket.\")\n print(\"Done.\")\n except Exception as e:\n logging.error(\"MP Socket error: {}\".format(str(e)))\n print(str(e))\n #finally:\n # Clean up the connection\n # conn.close()\n return testPassed\n\nif __name__ == \"__main__\":\n mp_socket().connection()\n" }, { "alpha_fraction": 0.5206611752510071, "alphanum_fraction": 0.5206611752510071, "avg_line_length": 19.33333396911621, "blob_id": "995026c5e2f4ee174fe5d4b1c564c0225ff9db9e", "content_id": "bdffbc2e5bd089db20c5d98880fdb9fd6697d328", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 121, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/build/html/_sources/rp_recognise.rst.txt", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Recieption Pi Recognise\n========================\n .. module:: rp_recognise\n\n .. autoclass:: recognise\n :members:" }, { "alpha_fraction": 0.46846845746040344, "alphanum_fraction": 0.46846845746040344, "avg_line_length": 17.66666603088379, "blob_id": "7a9cade4c305f38b7f6fa0a417e0550c48eefe19", "content_id": "69cb9877c364bebd81032da5380f36d7cee1fd99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 111, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/source/mp_socket.rst", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Master Pi Socket\n========================\n .. module:: mp_socket\n\n .. autoclass:: mp_socket\n :members:" }, { "alpha_fraction": 0.5320512652397156, "alphanum_fraction": 0.5320512652397156, "avg_line_length": 25.16666603088379, "blob_id": "b1e097419663044dae70347705784a09a0e3ff9a", "content_id": "7174ba6e2201850cee97e813016b66974a31749d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 156, "license_type": "no_license", "max_line_length": 34, "num_lines": 6, "path": "/source/mp_login_controller.rst", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Master Pi Web App Login Controller\n==================================\n .. module:: mp_login_controller\n\n .. autoclass:: login_controller\n :members:" }, { "alpha_fraction": 0.746666669845581, "alphanum_fraction": 0.746666669845581, "avg_line_length": 36.5, "blob_id": "c684d64ae73a97045b911b1302a86de61d7682e3", "content_id": "6c2ff14d1857ca450a5b4d98747395346860b1c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 75, "license_type": "no_license", "max_line_length": 57, "num_lines": 2, "path": "/mp/webapp/.flaskenv", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# app.py should be the name of the script you want to run\nFLASK_APP=app.py\n" }, { "alpha_fraction": 0.7365269660949707, "alphanum_fraction": 0.7485029697418213, "avg_line_length": 17.08108139038086, "blob_id": "77edbff97e46fda16b918784a216b082841e1bc9", "content_id": "63262bb64cc933a757b32b4eea0f50b09e9d4093", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 668, "license_type": "no_license", "max_line_length": 86, "num_lines": 37, "path": "/mp/webapp/readme.md", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# Library Web App\n# Web App\n## Install\n\nYou must have a python3 environment with pip installed.\n```\npip install flask\npip install python-dotenv\npip3 install flask-bootstrap\npip install flask-session\npip3 install pytest\n\n```\n\n\n## Running the webapp\n\nTo run the webapp:\n\n```flask run```\n\n# The API\n\n## Install\n\nInstall:\n```\npip3 install flask flask_sqlalchemy flask_marshmallow marshmallow-sqlalchemy timedelta\n```\nYou may also use the Command - \"source venv/bin/activate\n## Running the API\n\n```flask run --port 5001```\nNote: Needs to run on a different port then the webapp\n\nYou must have a python environment with Pip installed.\nThe Cloud Database is set in the app.py" }, { "alpha_fraction": 0.7432666420936584, "alphanum_fraction": 0.7751420736312866, "avg_line_length": 56, "blob_id": "3730eb5d957ef78fe4ed508fceadb368d02382dc", "content_id": "695627e70ef06a1a3a8b30366052d84c1f13418c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4049, "license_type": "no_license", "max_line_length": 571, "num_lines": 71, "path": "/README.md", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# Smart Library - IoT application\n\nIn this project, we developed an application where we automated a Library Management\rSystem (LMS). This system will be used to borrow, return and maintain the backend information. \nThe library user arrives at the reception. It is not manned by any person. The\rRECEPTION PI (RP) provides two options available for logging into the system:\r- using console-based system which allows them to type in the user credentials or,\r- using a facial recognition system\rThe user registration is required for the first-time user. Upon registration the details are stored in a\rlocal database installed on RP. Upon logging in, a success message along with the username is sent from RP (Reception PI) to the MASTER PI (MP) via sockets. The user is now presented with another console-based application where the user can search for book catalogues based on ISBN/Author name/Book name (either by using console-based system or voice search feature) , option for borrowing a book/books, option for returning a book/books (either by typing the ISBN of a book or scanning the QR code), logout. Upon logging out a message is sent via sockets from MP to RP.\nFor library admin: This is a separate website application that runs on MP. It can only be accessed\rby admin personnel. Admin website makes use of an API to:\n- Add books to catalogue\n- Remove books\n- Generate a data visualisation report for books borrowed (day and week wise)\nThe book database is stored on a cloud environment namely the Google’s GCP IoT platform\r(Google Cloud Platform).\n\n## Getting Started\n\nThese instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.\n\n### Prerequisites\n\n\n```\nIn our implementation, we use two raspberry pis where one act like a reception and other one acts like a master. You can use you machine with two windows to get the application working. \n```\n\n### Installing\n\nA step by step series of examples that tell you how to get a development env running\n\nSay what the step will be\n\n```\nPlease find the installation.txt file where you will find all the necessary packages to install\n```\n\n## Running the tests\n\nExplain how to run the automated tests for this system\n\n```\nYou will need to run user.py file in one window and library_menu.py in another window\n```\n\n\n## Built With\n\n* [Python](https://www.python.org) - programming language\n* [SQLite](https://www.sqlite.org/index.html) - relational database management system\n* [MySQL](https://www.mysql.com) - open-source relational database management system\n* [Flask](http://flask.pocoo.org) - Python microframework\n* [Google Cloud Platform](https://cloud.google.com/gcp/?utm_source=google&utm_medium=cpc&utm_campaign=japac-AU-all-en-dr-bkws-all-super-trial-e-dr-1003987&utm_content=text-ad-none-none-DEV_c-CRE_248263937479-ADGP_Hybrid%20%7C%20AW%20SEM%20%7C%20BKWS%20~%20T1%20%7C%20EXA%20%7C%20General%20%7C%201:1%20%7C%20AU%20%7C%20en%20%7C%20google%20cloud%20platform-KWID_43700023244271242-kwd-296644789888&userloc_9071338&utm_term=KW_google%20cloud%20platform&gclid=CjwKCAjw8qjnBRA-EiwAaNvhwDdJuPzXpsVzy8bM4AsttOQ86iB5Cz29fB-LU5AqkuNp86ayj2igQBoCFsUQAvD_BwE) - Google Cloud Platform\n* [Google Calendar API](https://developers.google.com/calendar/) - Used to add, remove events on a user Google Calendar\n* [Google Assistant SDK](https://developers.google.com/assistant/sdk/) - Used to translate voice to text\n* [OpenCV](https://opencv.org) - Used to detect object via camera\n* [Google Data Studio](https://datastudio.google.com/u/0/navigation/reporting) - Used to Generate a data visualisation report\n\n## Authors\n\n* **Mohammed Alotaibi** - [MohammedAlosaimi](https://github.com/mohammedhalosaimi)\n* **Dawei Mao** - [maodawei](https://github.com/maodawei)\n* **Brad Hill** - [Bradels](https://github.com/Bradels)\n* **Farid Farzin** - [FaridFarzin](https://github.com/FaridFarzin)\n\n\n## Acknowledgments\n\n* Acknowledgments to COSC2674 - Programming Internet of Things code archives\n" }, { "alpha_fraction": 0.6006297469139099, "alphanum_fraction": 0.6079769134521484, "avg_line_length": 38.29896926879883, "blob_id": "9ee7b558c94899c41f97c3188192e8560adf5ed7", "content_id": "12ef0233e3d2e47eb461acce4223028ba7cbda5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3811, "license_type": "no_license", "max_line_length": 138, "num_lines": 97, "path": "/mp/bookevent.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# pip3 install google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client httplib2\n# python3 add_event.py --noauth_local_webserver\n\n# Reference: https://developers.google.com/calendar/quickstart/python\n# Documentation: https://developers.google.com/calendar/overview\n\n# Be sure to enable the Google Calendar API on your Google account by following the reference link above and\n# download the credentials.json file and place it in the same directory as this file.\n\n# Reference: COSC2674 - Programming Internet of Things - lab 8\n\nfrom __future__ import print_function\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\nimport time\nfrom pytz import timezone\n\nclass bookevent:\n\n @staticmethod\n def insert(username, id,title,author):\n \n \"\"\"\n Create an event on Google calendar if an event has not been created. OR delete an event if it exists\n\n Parameters:\n\n username, id 'Book ID', book title, author\n \"\"\"\n\n # If modifying these scopes, delete the file token.json.\n SCOPES = \"https://www.googleapis.com/auth/calendar\"\n store = file.Storage(\"token.json\")\n creds = store.get()\n if(not creds or creds.invalid):\n flow = client.flow_from_clientsecrets(\"credentials.json\", SCOPES)\n creds = tools.run_flow(flow, store)\n service = build(\"calendar\", \"v3\", http=creds.authorize(Http()))\n date = datetime.now(timezone('Australia/Melbourne'))\n curr_time=date.time()\n next_week = (date + timedelta(days = 7)).strftime(\"%Y-%m-%d\")\n time_start = \"{}T{}\".format(next_week,curr_time)\n time_end = \"{}T{}\".format(next_week,curr_time)\n event = {\n \"summary\": \"Return Book\",\n \"location\": \"IoT Smart Library\",\n \"description\": \"Username: {} has borrowed book details Book ID: {} Title: {} Author: {} \".format(username, id,title,author),\n \"start\": {\n \"dateTime\": time_start,\n \"timeZone\": \"Australia/Melbourne\",\n },\n \"end\": {\n \"dateTime\": time_end,\n \"timeZone\": \"Australia/Melbourne\",\n },\n \"id\": id,\n \"reminders\": {\n \"useDefault\": False,\n \"overrides\": [\n { \"method\": \"email\", \"minutes\": 5 },\n { \"method\": \"popup\", \"minutes\": 10 },\n ],\n }\n }\n\n # try to create an event if it doesn't exist with the id\n try:\n event = service.events().insert(calendarId = \"primary\", body = event).execute()\n print(\"Event created: {}\".format(event.get(\"htmlLink\")))\n # update an event with the specified id if it already exists\n except:\n event = service.events().update(calendarId='primary', eventId=id, body=event).execute()\n\n @staticmethod\n def removeEvent(id):\n\n \"\"\"\n remove an event from Google Calendar with the given bookID\n\n Parameters: id 'Book ID'\n \"\"\"\n\n SCOPES = \"https://www.googleapis.com/auth/calendar\"\n store = file.Storage(\"token.json\")\n creds = store.get()\n if(not creds or creds.invalid):\n flow = client.flow_from_clientsecrets(\"credentials.json\", SCOPES)\n creds = tools.run_flow(flow, store)\n service = build(\"calendar\", \"v3\", http=creds.authorize(Http()))\n # this function does not delete the event, rather it hides it and changes the status to 'cancell'\n service.events().delete(calendarId = \"primary\", eventId = id).execute()\n\n# bookevent.insert('LLLLL', '23456', 'Why Me', 'LLLLLL')\n# bookevent.removeEvent('23456')" }, { "alpha_fraction": 0.5390807390213013, "alphanum_fraction": 0.5400466918945312, "avg_line_length": 32.48517608642578, "blob_id": "7f00cf21bd477bd9021cb760d319c03fe696c883", "content_id": "d1867cb35f57c16e2d28542ce3de33e810b06881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12423, "license_type": "no_license", "max_line_length": 251, "num_lines": 371, "path": "/source/mp_database_utils.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "# #!/usr/bin/python3\n\n# import MySQLdb\n# # import pymysql\n# import json\n# import logging\n\n# logging.basicConfig(filename=\"library.log\", level = logging.ERROR)\nclass DatabaseUtils:\n\n # def __init__(self):\n # \"\"\"\n\n # Parameters:\n\n # Returns:\n\n # \"\"\"\n # try:\n # jsonData = self.readConfig()\n # HOST = jsonData[\"hostname\"]\n # USER = jsonData[\"user\"] \n # PASSWORD = jsonData[\"password\"] \n # DATABASE = jsonData[\"database\"] \n\n # self.connection = MySQLdb.connect(HOST, USER, PASSWORD, DATABASE)\n # # print(self.connection)\n # self.createTables()\n # except Exception as e:\n # print(\"DatabaseUtils error: {}\".format(str(e)))\n\n # def close(self):\n # self.connection.close()\n\n # def __enter__(self):\n # return self\n\n # def __exit__(self, type, value, traceback):\n # self.close()\n\n def createTables(self):\n \"\"\"\n Create tables into the databse as per cloud_db_schema.sql file if does not exist\n Parameters:\n\n Returns:\n\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(open(\"cloud_db_schema.sql\", \"r\").read())\n # self.connection.commit()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # User CRUD table\n # ****************************************\n # Insert user\n def insertUser(self, name):\n \"\"\"\n Insert loggedin user who borrows a book into the google cloud db\n Parameters:\n User name\n Returns:\n 1 if the user is added\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"insert into LmsUser (UserName) values (%s)\", (name,))\n # self.connection.commit()\n\n # return cursor.rowcount == 1\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Get user\n def getUser(self, name):\n \"\"\"\n Get the user name from the cloud if already borrowed a book\n Parameters:\n User name\n Returns:\n returns user if borrowed a book in the past\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select * from LmsUser Where UserName = %s\", (name,))\n # if cursor.rowcount > 0:\n # return True\n # else:\n # return False\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Get user\n def getUsers(self):\n \"\"\"\n Fetch all users from the cloud\n Parameters:\n\n Returns:\n List of all users\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select * from LmsUser\")\n # return cursor.fetchall()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Delete User\n def deleteUser(self, name):\n \"\"\"\n Delete a user from the cloud \n Parameters:\n LMS user ID\n Returns:\n\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"delete from LmsUser where UserName = %s\", (name,))\n # self.connection.commit()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n\n # Book CRUD table\n # ****************************************\n # Insert Book\n def insertBook(self, title, author, isbn):\n \"\"\"\n Insert a book into the cloud db\n Parameters:\n Book Name, Book author, ISBN\n Returns:\n Confirms if the book is registered\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"insert into Book (Title, Author, ISBN) values (%s, %s, %s)\", (title,author, isbn))\n # self.connection.commit()\n\n # return cursor.rowcount == 1\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Get Book by title\n def getBookByTitle(self, title):\n \"\"\"\n Fetch all the books containing the keyword in the title\n Parameters:\n Title of the book or part of the title\n Returns:\n All books contating the keyword\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select * from Book Where Title Like %s\", (\"%\" + title + \"%\",))\n # return cursor.fetchall()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Get Book by Author\n def getBookByAuthor(self, author):\n \"\"\"\n Fetch all the books containing the keyword in the author\n Parameters:\n author of the book or part of the author\n Returns:\n All books contating the keyword\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select * from Book Where Author Like %s\", (\"%\" + author + \"%\",))\n # return cursor.fetchall()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Get Book by ISBN\n def getBookByISBN(self, isbn):\n \"\"\"\n Fetch all the books containing the keyword in the isbn\n Parameters:\n isbn of the book or part of the isbn\n Returns:\n All books contating the keyword\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select * from Book Where ISBN Like %s\", (\"%\" + isbn + \"%\",))\n # return cursor.fetchall()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Get Book by book ID\n def getBookByID(self, bookID):\n \"\"\"\n Fetch all the books containing the keyword in the bookID\n Parameters:\n isbn of the book or part of the isbn\n Returns:\n All books contating the keyword\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select * from Book Where BookID Like %(BookID)s\", {\"BookID\":bookID})\n # return cursor.fetchall()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Get Book by ISBN\n def getBooks(self):\n \"\"\"\n Returns all the book in the cloud db\n Parameters:\n\n Returns:\n Returns all the book in the cloud db\n\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select * from Book\")\n # return cursor.fetchall()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Delete Book\n def deleteBook(self, bookID):\n \"\"\"\n Delete a book \n Parameters:\n Book ID\n Returns:\n\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"delete from Book where BookID = %s\", (bookID,))\n # self.connection.commit()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n\n # BookBorrowed CRUD table\n # ****************************************\n # Insert BookBorrowed record\n def insertBookBorrowed(self, name, bookID, status, borrowdDate):\n \"\"\"\n Allocate a book to a user who borrowed the book, mark the book as borrowed and insert the borrowed date \n Parameters:\n\n Returns:\n\n \"\"\"\n # try :\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"insert into BookBorrowed (UserName, BookID, Status, BorrowedDate) values (%s, %s, %s, %s)\", (name,bookID, status, borrowdDate))\n # # cursor.execute(\"insert into BookBorrowed (UserName, BookID, Status, BorrowedDate) values (%(UserName)s, %(BookID)s, %(Status)s, %(BorrowedDate)s)\", {'UserName':name,\"BookID\":'bookID', 'Status':status, 'BorrowedDate':borrowdDate})\n # # cursor.execute(\"insert into BookBorrowed Where BookID = %(BookID)s AND Status = %(Status)s\", {'BookID':bookID,\"Status\":'borrowed'})\n # self.connection.commit()\n # except:\n # print(\"ip address not authorised by google cloud\")\n # # return cursor.rowcount == 1\n\n\n # Insert BookBorrowed record\n def updateBookBorrowed(self, name, bookID, status, ReturnedDate):\n \"\"\"\n Update a book which the user returns to the library, change the status to returned and insert the return date \n Parameters:\n LMS user ID, Book ID, Status=returned, \n Returns:\n\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"UPDATE BookBorrowed SET Status = %s , ReturnedDate = %s WHERE UserName = %s AND BookID = %s\", (status, ReturnedDate, name,bookID))\n # self.connection.commit()\n\n # return cursor.rowcount == 1\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Get user\n def getBookBorrowed(self, name, bookID):\n \"\"\"\n Get the user's borrowed book status \n Parameters:\n LMS USER ID, BOOK ID\n Returns:\n user's borrowed book record \n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select * from BookBorrowed Where UserName = \"+ name +\" AND BookID = \"+ bookID)\n # return cursor.fetchall()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # The 2 methods below are new \n\n def getAvilableBook(self, bookID):\n \"\"\"\n This method checks if the book that is associated with the bookID is avilable to borrow or not\n\n Parameters:\n BookID\n Returns:\n Either the avilable bookID or a message stating that the book is not avilable to borrow\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select BookID from BookBorrowed Where BookID = %(BookID)s AND Status = %(Status)s\", {'BookID':bookID,\"Status\":'borrowed'})\n # if cursor.rowcount > 0:\n # return False\n # else:\n # return True\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n\n def checkIfBookExistsInBookBorrowed(self, isbn, name):\n \"\"\"\n Check if the book has been borrowed by a user\n\n Paramters: book ISBN, username\n\n Returns: book ID and True if the user has borrowed the book. None and False if the user did not borrow the book\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"select BookBorrowed.BookID from Book, BookBorrowed Where Book.ISBN = %(isbn)s AND Book.BookID = BookBorrowed.BookID AND BookBorrowed.Status = 'borrowed' AND BookBorrowed.UserName = %(name)s\",{\"isbn\":isbn,\"name\":name})\n # if cursor.rowcount > 0:\n # return list(cursor.fetchall())[0][0], True\n # else:\n # return None, False\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Delete User\n def deleteBookBorrowed(self, bookBorrowedID):\n \"\"\"\n Delete all borrowed books with the bookBorrowedID\n Parameters:\n Id of the borrowed book(s)\n Returns:\n\n \"\"\"\n # try:\n # with self.connection.cursor() as cursor:\n # cursor.execute(\"delete from BookBorrowed where BookBorrowedID != %s\", (bookBorrowedID,))\n # self.connection.commit()\n # except:\n # print(\"ip address not authorised by google cloud\")\n\n # Read config.json\n def readConfig(self):\n \"\"\"\n Fetch configuration data to connect to google cloud database\n Parameters:\n\n Returns:\n google cloud database parameters\n \"\"\"\n # with open('config.json') as jsonFile: \n # data = json.load(jsonFile)\n # return data\n\n# DatabaseUtils().getUsers()\n" }, { "alpha_fraction": 0.4821428656578064, "alphanum_fraction": 0.4821428656578064, "avg_line_length": 17.83333396911621, "blob_id": "624151c6ff0ac5eedc923332ecd63aca87600945", "content_id": "4d358325a4e02f431bce12a46f7d513da2a8a3bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 112, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/build/html/_sources/rp_encode.rst.txt", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "Recieption Pi Encode\n========================\n .. module:: rp_encode\n\n .. autoclass:: encode\n :members:" }, { "alpha_fraction": 0.568830668926239, "alphanum_fraction": 0.5740119814872742, "avg_line_length": 47.97512435913086, "blob_id": "63ed3980f4c5a53018b37d3b50468045b4c491ba", "content_id": "1a0e3cd673b13f93897909657a237bae805c6859", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9843, "license_type": "no_license", "max_line_length": 186, "num_lines": 201, "path": "/source/rp_user.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "\"\"\"\nReferences:\nhttps://stackoverflow.com/questions/9202224/getting-command-line-password-input-in-python\n\n\"\"\"\n\n# # import packages\n# from db import database\n# import re \n# from passlib.hash import sha256_crypt\n# import getpass\n# from rp_socket import rp_socket\n# from capture import capture\n# from encode import encode\n# from recognise import recognise\n# import time\n\n# start of class user\nclass user:\n\n # menu method to be displayed for users\n @staticmethod\n def menu():\n \"\"\"\n menu method does display the menu for the user\n \"\"\"\n # # keep looping\n # while True:\n # # print the menu and welcome message\n # print('Welcome to smart library\\n1- Register a new account \\n2- Login into your account')\n # # try clause\n # try:\n # # prompt user for input options either 1 or 2\n # user_input = int(input())\n # # if user types 1 --> call registration method\n # if user_input == 1:\n # # call registration method\n # user.registration()\n # # if user types 2 -- > call login method\n # elif user_input == 2:\n # # call login method\n # user.login()\n # else:\n # # if user types something else --> prompts them again\n # print('Please type either 1 or 2')\n # except:\n # # if user types something else --> prompts them again\n # print('Please type either 1 or 2')\n\n # registration method\n @staticmethod\n def registration():\n \"\"\"\n registration method does the register a new user into the library system\n \"\"\"\n # # print a message to the user\n # print('Welcome to registration page.\\n- Please note that username must contain letters only.\\n- Note that your two passwords must match.')\n\n # # prompt user for username\n # username = input('Please type your username ')\n # # using regular expression, check if the username contains letters only\n # while not bool(re.match(\"[a-zA-Z]\", username)): \n # # if username doesn't match the specification, then prompt the user again for thier username\n # username = input('Please type your username ')\n # # check if the username already exists in the database. if username does not exist, then exceed\n # # with registration process\n # if(database.checkusernameexists(username)):\n # # prompt user for password\n # password = getpass.getpass('Please type your password ')\n # # prompt user for password again\n # re_password = getpass.getpass('Please re-type your password again ')\n # # attempt variable to count the number of attempts the user tries to match their passwords\n # attempt = 0\n # # if the two passwords does not match and attempt times is less than two time then\n # # prompt user again \n # while password != re_password and attempt < 2:\n # # prompt user for password\n # password = getpass.getpass('Please type your password ')\n # # prompt user for password again\n # re_password = getpass.getpass('Please re-type your password again ')\n # # increment attempt times\n # attempt += 1\n # # if attempt is equal of greater than 2, then exist the registration page\n # if attempt >= 2: \n # print('You exceeded more than two attempts. Try and register again')\n # exit\n # # exceed with registration process\n # # hash the password and assign it to a variable named hashedPassword\n # hashedPassword = sha256_crypt.hash(password)\n # # prompt user for first name\n # first_name = input('Please type your first name ')\n # # check if first name contains letters only, if not then prompt user for first name again\n # while bool(re.match(\"[a-zA-Z]\", first_name)) == False: first_name = input('Please type your first name ')\n # # prompt user for last name\n # last_name = input('Please type your last name ')\n # # check if last name contains letters only, if not then prompt user for last name again\n # while bool(re.match(\"[a-zA-Z]\", last_name)) == False: last_name = input('Please type your last name ')\n # # prompt user for email address\n # email = input('Please type your email address ')\n # # check if email address does contain the proper format of an email, if not then prompt user for last name again\n # while bool(re.match(\"\\S+@\\S+\", email)) == False: email = input('Please type your email address ')\n \n # # insert the data into the databse calling database class\n # database.insertData(username, hashedPassword, first_name, last_name, email)\n\n # # prompt user to choose bwtween console-based/acial recognition authentication\n # option = int(input('Please choose one of the following options for your login process:\\n- 1 for console-based authentication\\n- 2 for facial recognition authentication\\n'))\n \n # # if user choses 1, the exit since the user doesn't want to do facial recognition authentication\n # if option == 1:\n # exit\n\n # # if user choses facial recognition authentication, then call facial recognition files\n # elif option == 2:\n # print('Please be ready as we will take some picture of your face')\n # time.sleep(5)\n # print('Taking pictures now')\n # # capture user face\n # capture.main(username)\n # print('Our system is encoding your pictures for learning purposes.')\n # # encode user face pictures\n # encode.main()\n \n # # else means that the username already exists in the database\n # else:\n # # print a message\n # print(\"Username already exists!\")\n # exit\n \n\n # login method\n @staticmethod\n def login():\n \"\"\"\n Login method, able the user to login in to the library system\n \"\"\"\n\n# # prompt user to choose bwtween console-based/acial recognition authentication for login option\n# option = int(input('Please choose one of the following options to login:\\n- 1 for console-based authentication\\n- 2 for facial recognition authentication\\n'))\n \n# # if user choses 1, it means the user want to login with console-based authentication\n# if option == 1:\n \n# # prompt user for username\n# username = input('Please type your username ')\n# # prompt user for password\n# password = getpass.getpass('Please type your password ')\n# # hash the password\n# if database.checkusernameexists(username) == True:\n# print('Either username or password is wrong, please re-enter')\n# # attempt variable to count the number of attempts the user tries to login\n# attempt = 0\n# # check if username and password aren't associated with each other and attempt is less than 4 times\n# checkPass = database.veriftPassword(username, password)\n# while checkPass == False and attempt < 4:\n# # print a meaningful message\n# print('Either username or password is wrong, please re-enter')\n# # prompt user for username\n# username = input('Please type your username ')\n# # prompt user for password\n# password = getpass.getpass('Please type your password ')\n# # hash the password\n# # hashedPassword = sha256_crypt.hash(password)\n# # increment attempt times\n# attempt += 1\n# checkPass = database.veriftPassword(username, password)\n# # if attempts is greater or equal tna 4, then print a message and exit\n# if attempt >= 4:\n# print('You exceeded more than 4 attempts to login. Try and login again')\n# exit\n \n# # check if username and password are matching for one user\n# if checkPass == True:\n# # send login message to Master Pi\n# print(username, ' welcome to the Smart Library')\n# # create an object from rp_socket\n# rp_socket_object = rp_socket()\n# rp_socket_object.connection(username)\n\n \n \n# # if user choses 2, it means the user wants to login with facial recognition authentication\n# elif option == 2: \n# # call the recognise file which returns two values, True if face has been recognized, and the user name\n# boolean, name = recognise.main()\n# # if the face has been recognized, welcome the user to the smaer library\n# if boolean == True and name != 'Unknown':\n# # send login message to Master Pi\n# print(name, ' welcome to the Smart Library')\n# # create an object from rp_socket\n# rp_socket_object = rp_socket()\n# rp_socket_object.connection(name)\n# else:\n# print('The System Could Not Recognize your Face')\n# # if login is not successful, then print a message saying login could not be done\n# else:\n# print('Please type either 1 or 2')\n \n\n# # call the user menu\n# user.menu()" }, { "alpha_fraction": 0.5423387289047241, "alphanum_fraction": 0.5625, "avg_line_length": 23.850000381469727, "blob_id": "4d6bbb1726c882ff9c7326e7719faba692ffe4dd", "content_id": "1df028a13f21e31e2abc216032f80486aa462e5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "no_license", "max_line_length": 73, "num_lines": 20, "path": "/mp/webapp/API/CreateDB/createDB.py", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "import MySQLdb\n\n\nclass CreateDB:\n\n def __init__(self):\n HOST = \"35.201.19.68\"\n USER = \"root\"\n PASSWORD = \"klLBK8BxKmNOfhkE\"\n DATABASE = \"Library_test\"\n self.connection = MySQLdb.connect(HOST, USER, PASSWORD, DATABASE)\n \n def createTables(self):\n with self.connection.cursor() as cursor:\n cursor.execute(open(\"sql1.2.sql\", \"r\").read())\n self.connection.commit()\n\nif __name__ == \"__main__\":\n db = CreateDB()\n db.createTables()" }, { "alpha_fraction": 0.6958763003349304, "alphanum_fraction": 0.6958763003349304, "avg_line_length": 26.85714340209961, "blob_id": "6d7e03db563c58a645a79c65150078fd1e357abf", "content_id": "53e4a1cb9e70069df7647c526ca1878c87bed408", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 194, "license_type": "no_license", "max_line_length": 43, "num_lines": 7, "path": "/mp/webapp/API/CreateDB/sql1.2.sql", "repo_name": "Bradels/IoT-Application-Building-a-Smart-Library-master", "src_encoding": "UTF-8", "text": "create table IF NOT EXISTS Book(\n BookID int not null auto_increment,\n ISBN text not null,\n Title text not null,\n Author text not null,\n constraint PK_Book primary key (BookID)\n);" } ]
43