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
Nyakinyua/instagram
https://github.com/Nyakinyua/instagram
433ebf5e5742a62fe7718f8095c5f02ac7a024eb
6c03c04f8324a2d0f687e8c87aafa366cf1fff92
e56e2798df64420cb06761d65b32522855f1080d
refs/heads/master
2022-12-21T15:20:10.686313
2020-01-06T05:55:47
2020-01-06T05:55:47
229,263,197
1
0
MIT
2019-12-20T12:43:38
2020-04-10T16:00:02
2022-04-22T22:55:27
Python
[ { "alpha_fraction": 0.6286849975585938, "alphanum_fraction": 0.6339847445487976, "avg_line_length": 26.20720672607422, "blob_id": "0f79d7ef28c7640acbbdb9e68cb71e1eae98b2cd", "content_id": "a85f781f0aaa8912968df21059c5ed763b377cf2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3019, "license_type": "permissive", "max_line_length": 78, "num_lines": 111, "path": "/gram/models.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "from django.db import models\nimport datetime as dt \nfrom django.contrib.auth.models import User\n\n\n# Create your models here.\nclass Profile(models.Model):\n user=models.OneToOneField(User, on_delete=models.CASCADE) \n userId = models.IntegerField(default=None)\n bio = models.TextField(max_length=200)\n profile_photo = models.ImageField(upload_to = 'profile/',blank=True)\n \n def __str__(self):\n return self.bio\n \n def save_profile(self):\n return self.save()\n \n def delete_profile(self):\n profile=Profile.objects.all().delete()\n return profile\n \n \nclass Like(models.Model):\n like = models.IntegerField(blank=True,default= 0)\n \n\n\nclass Images(models.Model):\n image = models.ImageField(upload_to = 'images/',blank=True)\n image_name = models.CharField(max_length=30)\n caption = models.CharField(max_length=100)\n userId=models.IntegerField(default=None)\n user=models.ForeignKey(User,on_delete=models.CASCADE,default=None)\n like = models.ForeignKey(Like,on_delete=models.CASCADE,default=0)\n posted_on = models.DateField(auto_now_add=True)\n \n def __str__(self):\n return self.image_name\n \n class Meta:\n ordering = ['posted_on']\n \n def save_image(self):\n return self.save()\n \n def delete_image(self):\n image=Image.objects.all().delete()\n return image\n \n def update_caption(self,caption):\n return self.update\n \n @classmethod\n def get_all_images(cls):\n images = cls.objects.all()\n return images\n \n @classmethod\n def get_one_image(cls,id):\n image=cls.objects.get(id=id)\n return image\n \n @classmethod\n def search_users(cls,term):\n result=cls.objects.filter(user__username__icontains=term)\n return result\n \n @classmethod\n def get_user_posts(cls,user_id):\n \"\"\"\n Function that gets all posts by a user\n \"\"\"\n posts = cls.objects.filter(posted_by__id__contains=user_id)\n return posts\n \n @classmethod\n def get_image_id(cls,imageId):\n '''\n function that gets an image id \n '''\n image_id=cls.objects.filter(id=imageId)\n return image_id\n \nclass Comment(models.Model):\n comment = models.TextField(max_length=45,blank=True)\n user=models.ForeignKey(User,on_delete=models.CASCADE,default=None)\n images=models.IntegerField(default=None)\n image_id = models.ForeignKey(Images,on_delete=models.CASCADE,default=None)\n \n def save_comment(self):\n return self.save()\n\n def delete_comment(self):\n return self.delete()\n \n\n def __str__(self):\n return self.comment\n \n @classmethod\n def get_comments(cls,id):\n comments = cls.objects.filter(image_id__in=id)\n return comments\n \nclass Followers(models.Model):\n user=models.CharField(max_length=30)\n insta=models.CharField(default='',max_length=50)\n \n def save_followers(self):\n self.save()" }, { "alpha_fraction": 0.6405109763145447, "alphanum_fraction": 0.6432482004165649, "avg_line_length": 24.511627197265625, "blob_id": "30a4dd761f9516b67185dbcbc5e3fcadcf9805b2", "content_id": "62af01165d3dee91f7fcd82c1bd32612fbdb6aa7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1096, "license_type": "permissive", "max_line_length": 96, "num_lines": 43, "path": "/gram/forms.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Images,Profile,Comment,Like,Followers\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\n\n\nclass UploadImage(forms.ModelForm):\n class Meta:\n model=Images\n exclude = ['']\n \nclass EditProfile(forms.ModelForm):\n class Meta:\n model=Profile\n exclude=['userId']\n\nclass UpdateProfile(forms.ModelForm):\n class Meta:\n model=Profile\n exclude=['user']\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model=Comment\n exclude=['user','images']\n\n \n\nclass Like(forms.ModelForm):\n class Meta:\n model=Images\n exclude=['likes','comments','pub_on','user','userId','profile','image','name','caption']\n\nclass Follow(forms.ModelForm):\n class Meta:\n model=Followers\n exclude=['user','insta']\n \nclass SignupForm(UserCreationForm):\n email = forms.EmailField(max_length=200, help_text='Required')\n class Meta:\n model = User\n fields = ('username', 'email', 'password1', 'password2')" }, { "alpha_fraction": 0.5553064346313477, "alphanum_fraction": 0.579970121383667, "avg_line_length": 29.409090042114258, "blob_id": "98362c3eb50202de746e7db85f4dcd3e478b9e57", "content_id": "25e58821b396323161d14dcc342afb2e841a2226", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1338, "license_type": "permissive", "max_line_length": 124, "num_lines": 44, "path": "/gram/migrations/0003_auto_20191231_1102.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2019-12-31 08:02\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 dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('gram', '0002_auto_20191230_1946'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='images',\n name='comment',\n ),\n migrations.RemoveField(\n model_name='images',\n name='profile',\n ),\n migrations.AddField(\n model_name='comment',\n name='user',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='images',\n name='user',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='images',\n name='userId',\n field=models.IntegerField(default=None),\n ),\n migrations.AlterField(\n model_name='followers',\n name='insta',\n field=models.CharField(default='', max_length=50),\n ),\n ]\n" }, { "alpha_fraction": 0.6984572410583496, "alphanum_fraction": 0.6984572410583496, "avg_line_length": 34.70000076293945, "blob_id": "5a07209ea9a8a54a77c7be8e1177d729929904fb", "content_id": "0917384b7426554cfb2fff8e94c90d6cec664fcd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 713, "license_type": "permissive", "max_line_length": 80, "num_lines": 20, "path": "/gram/urls.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom django.conf.urls import url\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom . import views\n\n\n\nurlpatterns = [\n url(r\"^$\",views.home,name=\"home\"),\n path(\"news_feed/\",views.news_feed,name=\"news_feed\"),\n path('profile/',views.profile,name='profile'),\n path('profile/edit/',views.edit,name='edit'),\n path('search/', views.search_results, name=\"search_results\"),\n path('one_post/<int:id>',views.one_post,name=\"one_post\"),\n url(r'upload$',views.uploads,name='uploads'),\n url(r'^logout/$',views.logout_user,name=\"logout_user\"),\n]\nif settings.DEBUG:\n urlpatterns+= static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)" }, { "alpha_fraction": 0.5939959287643433, "alphanum_fraction": 0.6009909510612488, "avg_line_length": 29.09649085998535, "blob_id": "db9f426804aef27621d6e4586590b278f006f6ee", "content_id": "fc90c28cd3cb03701d121fd4e6001a1a9a44803f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3431, "license_type": "permissive", "max_line_length": 120, "num_lines": 114, "path": "/gram/tests.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom .models import Profile, Like, Comment, Images\nfrom django.contrib.auth.models import User\n\n# Create your tests here.\n\n\nclass ProfileTestCase(TestCase):\n # setup method\n def setUp(self):\n \"\"\"\n class that creates new profile\n \"\"\"\n self.maya = User(username=\"Maya\", email=\"[email protected]\")\n self.maya = Profile(user=self.maya, user_id=1, bio=\"You're cute to think its about you\", profile_photo=\"my.jpg\")\n\n # Testing Instance\n def test_instance(self):\n self.assertTrue(isinstance(self.maya, Profile))\n\n # Testing save method\n\n def test_save_profile(self):\n self.save_profile()\n profiles = Profile.objects.all()\n self.assertTrue(len(profile) > 0)\n\n # Testing delete method\n def test_delete_profile(self):\n self.maya.delete_profile()\n profiles = Profile.objects.all()\n self.assertEqual(len(profiles), 0)\n\n\nclass ImagePostTestCase(TestCase):\n\n def setUp(self):\n \"\"\"\n creating new instances of the image\n \"\"\"\n self.new_image = Images(image=\"image.jpg\", image_name=\"roses\", caption=\"live\",\n user_id=1, user='Joy', likes=0, posted_on=\"111-2019\")\n\n def test_save_image(self):\n \"\"\"\n test case that saves the new image created\n \"\"\"\n self.roses.save_image()\n image = Images.objects.all()\n self.assertEqual(len(image), 1)\n\n def test_delete_image(self):\n self.roses.save_image()\n self.roses.delete_image()\n image=Images.objects.all()\n self.assertTrue(len(image)==0)\n \n def test_update_caption(self):\n '''\n testcase that tests on updating a post's caption\n '''\n self.roses.save_post()\n new_image=Images.update_caption(self.roses.id,'flowers bloom life and soul') \n self.assertTrue(result.caption,'flowers bloom life and soul')\n\n def get_all_images(self):\n \"\"\"\n Test case that gets all images in a post\n \"\"\"\n self.roses.save_image()\n all_images = Images.get_all_images()\n self.assertTrue(len(all_images)<1)\n \n def test_get_image_id(self):\n \"\"\"\n Test case that gets the id of one image\n \"\"\"\n self.roses.save_image()\n image_id=Images.get_image_id(self.roses.id)\n self.assertTrue(image_id.id==self.roses.id)\n \n def test_get_one_post(self):\n '''\n testcase that gets a single image\n '''\n self.bmw.save_post()\n one=Images.get_one_image(self.roses.id) \n self.assertTrue(one.image_name==self.roses.image_name)\n \n def test_search_user(self):\n \"\"\"\n testcase that tests the search user function\n \"\"\"\n self.maya.save_profile()\n user = Profile.search_users(self.maya.username)\n self.assertTrue(user.username==\"Maya\")\n \n\nclass CommentTestCase(TestCase):\n def setUp(self):\n self.comment=Comment(body=\"I like it\",image_id=self.bmw.id,posted_by=self.pyra,posted_on='09-12-2019') \n\n \n\n def test_instance(self):\n self.assertTrue(isinstance(self.comment,Comments))\n\n def test_instance_follow(self):\n self.assertTrue(isinstance(self.follow,Followers))\n\n def test_save(self):\n self.follow.save_followers()\n prof=Followers.objects.all()\n self.assertTrue(len(prof)>0)\n" }, { "alpha_fraction": 0.5491183996200562, "alphanum_fraction": 0.5609931349754333, "avg_line_length": 41.75384521484375, "blob_id": "50e37e740d8385d52584e9db560c58a392b1fbb9", "content_id": "17dc48161f8328f49443e7e7a316efb1afbaac51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2779, "license_type": "permissive", "max_line_length": 125, "num_lines": 65, "path": "/gram/migrations/0001_initial.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2019-12-30 13: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='Comment',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('comment', models.TextField(blank=True, max_length=45)),\n ],\n ),\n migrations.CreateModel(\n name='Followers',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('user', models.CharField(max_length=30)),\n ('insta', models.CharField(default='', max_length=30)),\n ],\n ),\n migrations.CreateModel(\n name='Like',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('like', models.IntegerField(blank=True, default=0)),\n ],\n ),\n migrations.CreateModel(\n name='Profile',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('email', models.EmailField(max_length=254)),\n ('bio', models.TextField(max_length=200)),\n ('profile_photo', models.ImageField(blank=True, upload_to='profile/')),\n ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Images',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('image', models.ImageField(blank=True, upload_to='images/')),\n ('image_name', models.CharField(max_length=30)),\n ('caption', models.CharField(max_length=100)),\n ('posted_on', models.DateField(auto_now_add=True)),\n ('comment', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='gram.Comment')),\n ('like', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='gram.Like')),\n ('profile', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='gram.Profile')),\n ],\n options={\n 'ordering': ['posted_on'],\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5527876615524292, "alphanum_fraction": 0.5907473564147949, "avg_line_length": 28.068965911865234, "blob_id": "174278e89585fc060c27398e71dfbb3d6980d8b4", "content_id": "4c322abd207ac7b33b3233a334c9309a6b8fb2fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 843, "license_type": "permissive", "max_line_length": 113, "num_lines": 29, "path": "/gram/migrations/0004_auto_20200102_0832.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-01-02 05:32\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('gram', '0003_auto_20191231_1102'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='comment',\n name='image_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='gram.Images'),\n ),\n migrations.AddField(\n model_name='comment',\n name='images',\n field=models.IntegerField(default=None),\n ),\n migrations.AlterField(\n model_name='images',\n name='like',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='gram.Like'),\n ),\n ]\n" }, { "alpha_fraction": 0.49056604504585266, "alphanum_fraction": 0.49782294034957886, "avg_line_length": 25.519229888916016, "blob_id": "c99c1b6b096625b18b95361489a2d993ac052349", "content_id": "c06289731f23aeee2bed22ccebfac95a35486b3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1378, "license_type": "permissive", "max_line_length": 142, "num_lines": 52, "path": "/gram/templates/registration/login.html", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "{%extends \"registration/base.html\"%}\n{% load static %}\n{% load bootstrap4 %}\n{% block content %}\n{{block.supper}}\n\n<div class=\"container\">\n <div class=\"row\">\n <!-- Empty div -->\n <div class=\"col-md-4\"></div>\n <div class=\"col-md-4\">\n {% if form.errors %}\n <p> Password or Username is incorrect </p>\n {% endif %}\n <div class=\"panel panel-default\">\n\n <div class=\"panel-heading\">\n <h3 class=\"text-center\">Sign In</h3>\n </div>\n <div class=\"panel-body\">\n\n <form action=\"/accounts/login/\" method=\"post\">\n <h1>Instagram</h1>\n {% csrf_token %}\n {% bootstrap_form form%}\n\n <div class=\"form-group\">\n <input type=\"submit\" class=\"btn btn-info sm\" value=\"Login\">\n </div>\n\n <h6 class=\"animated fadeIn\">OR</h6>\n <p style=\"text-align:center\"><a class=\"facebook\"href=\"www.facebook.com\"><i class='fab fa-facebook'></i>Login with Facebook</a></p>\n\n </form>\n\n </div>\n <div class=\"open\">\n <ul class=\"list-group\">\n <li class=\"list-group-item\">Dont have an account? <a href=\"/accounts/register/\">Sign up here</a></li>\n \n </ul>\n \n </div>\n\n </div>\n\n </div>\n <!-- empty div -->\n <div class=\"col-md-4\"></div>\n </div>\n</div>\n{% endblock %}" }, { "alpha_fraction": 0.5105041861534119, "alphanum_fraction": 0.5504201650619507, "avg_line_length": 20.636363983154297, "blob_id": "6af1ab7b4cd3fcd7d4b31663040017ca26496918", "content_id": "c95916439ea8c3361ce773576b200a67f0e590da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 476, "license_type": "permissive", "max_line_length": 52, "num_lines": 22, "path": "/gram/migrations/0002_auto_20191230_1946.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2019-12-30 16:46\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('gram', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='profile',\n name='email',\n ),\n migrations.AddField(\n model_name='profile',\n name='userId',\n field=models.IntegerField(default=None),\n ),\n ]\n" }, { "alpha_fraction": 0.7061529755592346, "alphanum_fraction": 0.7159286737442017, "avg_line_length": 32.46154022216797, "blob_id": "d99878aa1b7c439071d7de20b7cc71a015406361", "content_id": "4728d24ebffa93cadb173e8f0e670ea355f29068", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1739, "license_type": "permissive", "max_line_length": 356, "num_lines": 52, "path": "/README.md", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "# instapics\n#### This is a python web application that uses Django framework and Postgresql\n#### By **[Nyakinyua](https://github.com/Nyakinyua)**\n## Description\nInstapic is a social networking web application app made for sharing photos and videos. It is an instagram clone that allows users to post photos or videos. They are then displayed on the users profile. Other users who follow will see your posts in their own feed. Likewise, the user will be able to see posts from other users whom they choose to follow.\n\n## SetUp/Installation Requirements\n* python3.6\n* pip\n\n\n### Cloning\n* In your terminal:\n `$ git clone https://github.com/Nyakinyua/instagram.org`\n `$ cd instagram`\n\n## Running the Application\n* Creating the virtual environment and activating the the virtual environment\n\n `$ python3.6 -m venv virtual`\n `$ source virtual/bin/env`\n \n\n* Installing dependencies\n\n `$ pip install -r requirements.txt`\n\n* To run the application, in your terminal:\n\n `$ python3.6 manage.py runserver`\n\n## Testing the Application\n* To run the tests for the class files:\n\n `$ python3.6 manage.py test`\n\n\n\n## Technologies Used\n This project was generated with\n * [Python](https://www.python.org/) version 3.6.9.\n * [Django](https://www.fullstackpython.com/django.html)version2.2.4.\n * Django-Bootstrap4.\n * Psql database\n * CSS3\n * HTML5\n## Support and contact details\n In case You have any contributions and add ons to this application or any issues using this code please feel free to get in touch with me via [email]([email protected])\n## License \n#### This project is licensed by [Mit License](https://github.com/Nyakinyua/instagram/blob/master/LICENSE)\n \n #### (c) **[Nyakinyua](https://github.com/)**" }, { "alpha_fraction": 0.5208791494369507, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 17.200000762939453, "blob_id": "84e39649989c4ee93511b0fd65c392ae34d43493", "content_id": "3476339243dbd5d695826db590e91045c7747ba0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 455, "license_type": "permissive", "max_line_length": 28, "num_lines": 25, "path": "/requirements.txt", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "asgiref==3.2.3\nbeautifulsoup4==4.8.2\ncertifi==2019.11.28\nchardet==3.0.4\nconfig==0.4.2\nconfusable-homoglyphs==3.2.0\ndj-database-url==0.5.0\nDjango==2.2.4\ndjango-bootstrap4==1.1.1\ndjango-heroku==0.3.1\ndjango-registration==2.4.1\ngunicorn==20.0.4\nidna==2.8\nPillow==6.2.1\npsycopg2==2.8.4\npython-dateutil==2.8.1\npython-decouple==3.3\npytz==2019.3\npyuploadcare==2.6.0\nrequests==2.22.0\nsix==1.13.0\nsoupsieve==1.9.5\nsqlparse==0.3.0\nurllib3==1.25.7\nwhitenoise==5.0.1\n" }, { "alpha_fraction": 0.6979166865348816, "alphanum_fraction": 0.6979166865348816, "avg_line_length": 41.400001525878906, "blob_id": "7f2850352d6aa80ae9e05c6c654b4aaf2ae98262", "content_id": "0a3b4c3358a52da8de240650bb3d168ede724e8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "permissive", "max_line_length": 92, "num_lines": 15, "path": "/gram/email.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "from django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\n\n\ndef send_welcome_email(name,receiver):\n #creating message subject to the sender\n subject = \"Welcome to Nyakinyua Instapics, share photos and views photos from followers\"\n sender = \"[email protected]\"\n \n #passing in the context variables\n text_content = render_to_string('email/gramemail.txt',{\"name\":name})\n html_content = render_to_string('email/gramemail.html',{\"name\":name})\n msg = EmailMultiAlternatives(subject,text_content,sender,[receiver])\n msg.attach_alternative(html_content,'text/html')\n msg.send()\n " }, { "alpha_fraction": 0.6513379812240601, "alphanum_fraction": 0.6549058556556702, "avg_line_length": 32.5, "blob_id": "e741b86b239d39228bc7de7184fa330dc0de9e5f", "content_id": "6ca1597bf6008910ab2cdb6b4b332beeca50f935", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5045, "license_type": "permissive", "max_line_length": 112, "num_lines": 150, "path": "/gram/views.py", "repo_name": "Nyakinyua/instagram", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect\nfrom django.http import HttpResponse,Http404 \nfrom .models import Images,Profile,Comment,Followers,Like\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom .forms import UploadImage,EditProfile,UpdateProfile,CommentForm,Like,Follow\nfrom django.contrib.auth import logout\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import render_to_string\n\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom .forms import SignupForm\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.contrib.auth import login, authenticate\n\n\n# Create your views here.\ndef home(request):\n title = \"Nyakinyua Gram Photos\"\n \n return render(request,\"index.html\",{\"title\":title})\n\n@login_required(login_url=\"/accounts/login/\")\ndef news_feed(request):\n try:\n current_user = request.user.id\n images = Images.objects.all()\n prof_pic = Profile.objects.filter(userId=current_user)\n profile = prof_pic.reverse()[0:1]\n users = User.objects.all().exclude(id=request.user.id)\n comments = Comment.objects.all()\n except Exception as e:\n raise Http404\n return render(request,'all_pics.html',{\"images\":images,\"profile\":profile,\"users\":users,\"comments\":comments})\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef logout_user(request):\n '''\n view function renders home page once logout\n '''\n \n logout(request)\n return redirect('/')\n\n@login_required(login_url=\"/accounts/login/\")\ndef profile(request):\n try:\n current_user=request.user.id\n profile_photos=Images.objects.filter(userId=current_user)\n profile_image=Profile.objects.filter(userId=current_user).all()\n profile=profile_image.reverse()[0:1]\n\n except Exception as e:\n raise Http404()\n\n return render(request,\"profile.html\",{'profile':profile_photos,\"pic\":profile})\n\n@login_required(login_url='accounts/login/')\ndef uploads(request):\n title='NewPost'\n current_user = request.user\n current_user_id= request.user.id\n \n if request.method == 'POST':\n form = UploadImage(request.POST,request.FILES)\n if form.is_valid():\n image=form.save(commit=False) \n image.user=current_user\n image.userId=current_user_id\n image.profile=current_user_id\n image.save()\n \n return redirect('profile')\n else:\n form = UploadImage()\n \n return render(request,'upload.html',{'title':title,'form':form})\n \n@login_required(login_url='/accounts/login/')\ndef search_results(request):\n if 'user' in request.GET and request.GET['user']:\n term=request.GET.get(\"user\")\n found=Images.search_users(term)\n message=f'{term}'\n\n return render(request,'search.html',{'message':message,'founds':found,\"term\":term})\n else:\n message=\"You did not search any user please input a user name\"\n return render(request,\"search.html\",{\"message\":message}) \n\n\n@login_required(login_url='/accounts/login/')\ndef edit(request):\n current_user_id=request.user.id\n profile=Profile.objects.filter(userId=current_user_id)\n if len(profile)<1:\n\n if request.method=='POST':\n form=EditProfile(request.POST,request.FILES)\n if form.is_valid():\n profile=form.save(commit=False)\n profile.userId=current_user_id\n profile.save()\n return redirect(\"profile\")\n else:\n form=EditProfile()\n return render(request,\"edit.html\",{\"form\":form})\n else:\n if request.method=='POST':\n form=EditProfile(request.POST,request.FILES )\n if form.is_valid():\n profile=form.save(commit=False)\n bio=form.cleaned_data['bio']\n profile_photo=form.cleaned_data['profile_photo']\n update=Profile.objects.filter(userId=current_user_id).update(bio=bio,pic=profile_photo)\n profile.userId=current_user_id\n profile.save(update)\n return redirect(\"profile\")\n else:\n\n form=EditProfile()\n\n return render(request,\"edit.html\",{\"form\":form})\n\n\n \n@login_required(login_url=\"/accounts/login/\")\ndef one_post(request,id):\n '''\n view function that renders one post and has a comment section\n ''' \n if request.method=='POST':\n form=CommentForm(request.POST)\n if form.is_valid():\n comment=form.save(commit=False)\n comment.posted_by=request.user \n post=Images.get(id=id)\n comment.image_id=post\n comment.save()\n HttpResponseRedirect('one_pic')\n else:\n form=CommentForm()\n\n image=Images.get_one_image(id) \n image_Id=Images.get_image_id(id)\n comments=Comment.get_comments(image_Id)\n \n return render(request,'one_pic.html',{\"form\":form,\"comments\":comments,\"post\":image}) \n \n \n" } ]
13
Sholwa/mems-beadando
https://github.com/Sholwa/mems-beadando
4d552382a0e1cbf4818b95b1a12f402f8cee99ae
bc10ae83d215ce4fd618938b1b97f7e8e28f1f89
b8d0ece9df6cb3236b6d015653b269196349ea2a
refs/heads/master
2020-03-31T18:24:48.420855
2019-01-08T08:48:42
2019-01-08T08:48:42
152,458,226
0
0
null
2018-10-10T16:52:35
2018-11-18T18:56:57
2019-01-08T08:48:43
null
[ { "alpha_fraction": 0.47190672159194946, "alphanum_fraction": 0.4792441427707672, "avg_line_length": 31.834983825683594, "blob_id": "a788856b451fad4f73222980c279ec621436058e", "content_id": "afc00de295ee555af908f449d11b3fa8a9831f25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10109, "license_type": "no_license", "max_line_length": 124, "num_lines": 303, "path": "/rPI_music_box/main.py", "repo_name": "Sholwa/mems-beadando", "src_encoding": "UTF-8", "text": "# This Python file uses the following encoding: utf-8\n\n# Függvénykönyvtárak betöltése:\nfrom sense_hat import SenseHat # uncomment on rPI\nimport pygame #pygame eseménykezelés miatt\nfrom pygame.mixer import music as mp3 #zene lejátszáshoz\nimport os # mappa(ák) fájl(ok) kezelése\nimport time # log timestamp miatt\nimport datetime # log timestamp miatt\nfrom time import sleep\nimport random # shuffle funkció miatt\nimport sys # csript mappájának meghatározása, szolgáltatásként futattva (sys.path[0])\n\n# LOG FIle kezelés:\ntimestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H.%M.%S')\nlogpath=os.path.join(sys.path[0], \"log\", \"rPI_music_box_\")+timestamp+\".log\"\ndef newlogline(string):\n with open(logpath, \"a\") as log:\n log.write(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')+\" - \")\n log.write(string+\"\\n\")\n\n# Változók és konstansok definiálása:\nindex=0 # első zeneszám beállítása\nvol=0.5 # kezdeti nagerő érték\nplaying = \"\" # kezdeti lejtászás státusz\n\ng = (0, 100, 0) # Green\nb = (0, 0, 0) # Black\n\nmusicpath=os.path.join(sys.path[0], \"music\") # platform függtlen elérési út definiálása\nl = [] # számok listája\n\nSONG_END = pygame.USEREVENT + 1 # szám vége esemény definiálása\nmp3.set_endevent(SONG_END)\n\n# Fügvények:\ndef displayCL(): #conslo-ra és logba írás egyszerűsítése\n global l\n global index\n newlogline(\"Playing:\")\n newlogline(l[index])\n print(\"Playing:\")\n print(l[index]) \n print(\"Next:\")\n newlogline(\"Next:\")\n if index == lSize-1: # index határérték kezelése\n print(l[0])\n newlogline(l[0])\n elif index < 0:\n print(l[lSize-1])\n newlogline(l[lSize-1])\n else:\n print(l[index+1])\n newlogline(l[index+1])\n\ndef play_pause():\n global playing\n if playing == True:\n mp3.pause()\n playing = False\n print(\"Paused\")\n newlogline(\"Paused\")\n displayH(\"pause\")\n elif playing == False:\n mp3.unpause()\n playing = True\n displayCL()\n displayH(\"play\")\n else:\n mp3.load(l[index]) # az első szám betöltése\n mp3.play()\n playing = True\n displayH(\"play\")\n displayCL()\n\ndef next():\n global index\n global playing\n displayH(\"next\")\n mp3.load(l[index])\n mp3.play()\n playing = True\n displayCL()\n sleep(1)\n displayH(\"play\")\n\ndef previous():\n global index\n global playing\n displayH(\"previous\")\n mp3.load(l[index])\n mp3.play()\n playing = True\n displayCL()\n sleep(1)\n displayH(\"play\")\n\ndef shuffle(): #5 zene lista megkeverése\n global playing\n global index\n random.shuffle(l)\n index = 0\n mp3.load(l[index])\n mp3.play()\n playing = True\n displayH(\"shuffle\") # uncomment on rPI\n newlogline(\"rPI Shuffled\")\n print(\"rPI Shuffled\")\n displayCL()\n sleep(1)\n displayH(\"play\") # uncomment on rPI\n\ndef volup():\n global vol\n global playing\n vol += 0.02\n mp3.set_volume(vol)\n #cvol = mp3.get_volume()\n newlogline(\"Volume up\")\n print(mp3.get_volume())\n sense.show_letter(\"+\",text_colour=g,back_colour=b)\n sleep(0.3)\n if playing == False:\n displayH(\"pause\")\n elif playing == True:\n displayH(\"play\")\n else:\n displayH(\"smile\")\n\ndef voldown():\n global vol\n global playing\n vol -= 0.02\n mp3.set_volume(vol)\n #cvol = mp3.get_volume()\n newlogline(\"Volume down\")\n print(mp3.get_volume())\n sense.show_letter(\"-\",text_colour=g,back_colour=b)\n sleep(0.3)\n if playing == False:\n displayH(\"pause\")\n elif playing == True:\n displayH(\"play\")\n else:\n displayH(\"smile\")\n\ndef displayH(action): # logók mghivása\n sense.clear()\n if action == \"play\":\n pixels = [\n b, b, b, b, b, b, b, b,\n b, b, g, b, b, b, b, b,\n b, b, g, g, b, b, b, b,\n b, b, g, g, g, b, b, b,\n b, b, g, g, b, b, b, b,\n b, b, g, b, b, b, b, b,\n b, b, b, b, b, b, b, b,\n b, b, b, b, b, b, b, b\n ]\n elif action == \"pause\":\n pixels = [\n b, b, b, b, b, b, b, b,\n b, g, g, b, g, g, b, b,\n b, g, g, b, g, g, b, b,\n b, g, g, b, g, g, b, b,\n b, g, g, b, g, g, b, b,\n b, g, g, b, g, g, b, b,\n b, b, b, b, b, b, b, b,\n b, b, b, b, b, b, b, b\n ]\n elif action == \"next\":\n pixels = [\n b, b, b, b, b, b, b, b,\n b, b, b, b, b, g, b, b,\n b, g, b, b, b, g, g, b,\n b, g, g, b, b, g, g, g,\n b, g, g, g, b, g, g, b,\n b, g, g, b, b, g, b, b,\n b, g, b, b, b, b, b, b,\n b, b, b, b, b, b, b, b\n ]\n elif action == \"previous\":\n pixels = [\n b, b, b, b, b, b, b, b,\n b, b, g, b, b, b, b, b,\n b, g, g, b, b, b, g, b,\n g, g, g, b, b, g, g, b,\n b, g, g, b, g, g, g, b,\n b, b, g, b, b, g, g, b,\n b, b, b, b, b, b, g, b,\n b, b, b, b, b, b, b, b\n ]\n elif action == \"shuffle\":\n pixels = [\n b, b, b, b, b, b, g, b,\n b, b, b, b, g, g, g, g,\n g, g, b, g, b, b, g, b,\n b, b, g, b, b, b, b, b,\n b, b, g, b, b, b, b, b,\n g, g, b, g, b, b, g, b,\n b, b, b, b, g, g, g, g,\n b, b, b, b, b, b, g, b\n ]\n elif action == \"smile\":\n pixels = [\n b, b, b, b, b, b, b, b,\n b, b, b, b, b, b, b, b,\n b, b, g, b, g, b, b, b,\n b, b, b, b, b, b, b, b,\n b, g, b, b, b, g, b, b,\n b, b, g, g, g, b, b, b,\n b, b, b, b, b, b, b, b,\n b, b, b, b, b, b, b, b\n ]\n sense.set_pixels(pixels)\n\n# Zeneszámok betöltése, rendezése, lejátszó inicializálása\nif os.path.isdir(musicpath) == True: # zene könyvtár meglétének ellenőrzése\n print(\"==========================================\")\n print(\"The music folder exists\")\n print(\"==========================================\")\n newlogline((\"==========================================\"))\n newlogline(\"The music folder exists\")\n newlogline(\"==========================================\")\n os.chdir(musicpath) # könyvtár váltás, hogy ne kelljen elérési utat definiálni a zenék lejátszásakor\n for files in os.listdir(musicpath): # zene könyvtár listázása\n if files.endswith(\".mp3\"): # mp3 kiterejsztésű fájlokra szűrés\n l.append(files) # lejatászi lista létrehozása\n print(files)\n newlogline(files)\n l.sort() # számok sorba rendezése\n lSize=len(l) # számok darabszámának tárolása\n newlogline(\"\")\n newlogline(\"==========================================\")\n print(\"\")\n print(\"==========================================\")\n\n #START - SenseHat event handler\n sense = SenseHat() # semse Hat inicializálása\n # SYSTEMD BugFix\n import signal\n def handler(signum, frame):\n pass\n \n try:\n signal.signal(signal.SIGHUP, handler)\n except AttributeError:\n pass\n #_________________\n pygame.init() # pygame importált moduljaninak inicializálása\n mp3.set_volume(vol) # kezdeti hangerő beállítása\n sense.show_message(\"Welcome! Lets start listening...\", scroll_speed=0.08, text_colour=g, back_colour=b) # üdvözlő üzenet\n displayH(\"smile\") # smile jelzi, hogy betöltött a program\n while True:\n acceleration = sense.get_accelerometer_raw() # gyorsulámérő gyers adatok lekérése\n x = abs(acceleration['x'])\n y = abs(acceleration['y'])\n z = abs(acceleration['z'])\n if x > 2 or y > 2 or z > 2: # az eszköz \"rázásának\" érzékelése\n newlogline(\"==========================================\")\n print(\"==========================================\")\n newlogline(\"Accelerometer triggered shake\")\n shuffle()\n else:\n for event in sense.stick.get_events(): # senseHat események figyelése\n if event.action == \"pressed\":\n newlogline(\"==========================================\")\n print(\"==========================================\")\n if event.direction == \"up\":\n newlogline(\"Joystick up pressed\")\n volup()\n elif event.direction == \"down\":\n newlogline(\"Joystick down pressed\")\n voldown()\n elif event.direction == \"left\":\n newlogline(\"Joystick left pressed\")\n index -= 1\n if index < 0: # index határérték kezelése\n index = lSize-1\n previous()\n elif event.direction == \"right\":\n newlogline(\"Joystick right pressed\")\n index += 1\n if index == lSize: # index határérték kezelése\n index = 0\n next()\n elif event.direction == \"middle\":\n newlogline(\"Joystick middle pressed\")\n play_pause()\n for event in pygame.event.get(): # pygame események figyelése\n if event.type == SONG_END: # szám végének figyelése\n newlogline(\"==========================================\")\n newlogline(\"The song ended!\")\n print(\"==========================================\")\n print(\"The song ended!\")\n index += 1\n if index == lSize: # index határérték kezelése\n index = 0\n next()\n #END - SenseHat event handler\nelse:\n newlogline(\"The music folder is not exists\")\n print(\"The music folder is not exists\")\n" }, { "alpha_fraction": 0.7699530720710754, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 48.153846740722656, "blob_id": "957d43523092a967d7468aef38782aa914b1aaa4", "content_id": "0d9c478f4ac3acedfc49f06e742faea40dd0fae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 673, "license_type": "no_license", "max_line_length": 256, "num_lines": 13, "path": "/README.md", "repo_name": "Sholwa/mems-beadando", "src_encoding": "UTF-8", "text": "# mems-beadando\n\n*This project is a university course requirements.\nFrom now on, there will be hungarian descriptions. This applies to the whole project.\nThank you for understanding.*\n \n## rPI zene doboz\n\nAz eszköz egy Raspberry pi 3 mikroszámítógépből és egy SenseHat-ből áll. Az doboz vezérlése egy 5 gombos joystick által lehetséges (pl: lejátszás, szünet, következő / előző szám, hangerő szabályzása). Státusz kijelzése egy 8x8-as led mátrix-al valósul meg.\n\nBővebb információk a [wiki](https://github.com/Sholwa/mems-beadando/wiki)-ben.\n\n### Projeck státusz követése itt --> [MEMS](https://github.com/Sholwa/mems-beadando/projects/1)\n" } ]
2
microfinkit/microfinkitv0
https://github.com/microfinkit/microfinkitv0
4342dfd64518f6dadd1151fbdf419094693940e2
2be421754c5dccbaf00075c93bac2bf3ed05ba79
c82c692f5cff7823748612d66fd03e9cc85be8f4
refs/heads/master
2020-04-27T02:22:41.999225
2019-03-17T00:14:17
2019-03-17T00:14:17
173,991,992
1
1
MIT
2019-03-05T17:36:01
2019-03-14T13:15:31
2019-03-14T13:15:30
Python
[ { "alpha_fraction": 0.832402229309082, "alphanum_fraction": 0.8379888534545898, "avg_line_length": 43.75, "blob_id": "498ca839ba02c0e45b5f275b877262b88ed859bb", "content_id": "8366eb0816d75e09c7feadf94149d74be8ecb992", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 179, "license_type": "permissive", "max_line_length": 125, "num_lines": 4, "path": "/README.md", "repo_name": "microfinkit/microfinkitv0", "src_encoding": "UTF-8", "text": "# microfinkitv0\nMarket Microstructure Financial Kit\n\nThe idea behind this library is make some functions in python to apply market microstructure theory in financial time series.\n" }, { "alpha_fraction": 0.5406162738800049, "alphanum_fraction": 0.5516559481620789, "avg_line_length": 31.54143714904785, "blob_id": "70283e0c5570e08a8f772528199c13c7639fb9a4", "content_id": "c3974e5ccbca95d7b584b43e6dbb61c4c9c5d62b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6069, "license_type": "permissive", "max_line_length": 134, "num_lines": 181, "path": "/code/microfinkit.py", "repo_name": "microfinkit/microfinkitv0", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nMarket Microstructure Finance functions\r\nPython version: Python 3.7.1 \r\nversion 0.2\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\n \r\ndef bar(df, bar_column, treshold, flag):\r\n '''\r\n Compute index for bar's kind\r\n # args\r\n df: pandas dataframe with time, price, quantity, and dollars\r\n bar_column: Column name for bar's kind\r\n treshold: int(), Threshold value for bar's kind\r\n flag: 0 if is a tick bar\r\n 1 if is a volume bar \r\n 2 if is a dollar bar \r\n # returns\r\n idx: List of indices\r\n # reference:\r\n https://github.com/BlackArbsCEO/Adv_Fin_ML_Exercises/blob/master/notebooks/Tick%2C%20Volume%2C%20Dollar%20Volume%20Bars.ipynb \r\n '''\r\n t = df[bar_column]\r\n ts = 0\r\n idx = []\r\n if flag == 0:\r\n for i, x in enumerate(t):\r\n ts += 1\r\n if ts >= treshold:\r\n idx.append(i)\r\n ts = 0\r\n continue\r\n else:\r\n for i, x in enumerate(t):\r\n ts += x\r\n if ts >= treshold:\r\n idx.append(i)\r\n ts = 0\r\n continue \r\n # Ensures that the last index is included within the selected indexes\r\n #if idx[-1] != len(t)-1:\r\n # idx.append(len(t)-1)\r\n return idx\r\n\r\n\r\ndef vwap(df, vol_column,dollar_column,idx):\r\n '''\r\n Compute the Volume Weighted Average Price\r\n # args\r\n df: Pandas dataframe\r\n dollar_column: Transaction amount column (price x quantity)\r\n vol_column: Stock quantity transactions\r\n idx: list of indices \r\n # returns\r\n list with wwap computed\r\n '''\r\n vwap = []\r\n for i in range(0,len(idx)):\r\n if i == 0:\r\n inf = 0\r\n sup = idx[i]+1\r\n else:\r\n inf = idx[i-1]+1\r\n sup = idx[i]+1\r\n vwap.append(sum(df[dollar_column][inf:sup])/\r\n sum(df[vol_column][inf:sup]))\r\n return vwap\r\n\r\n\r\n\r\ndef attribute(df, att_column, idx, flag):\r\n '''\r\n Compute some values from tick bar range\r\n \r\n # args\r\n df: Pandas dataframe\r\n bar_column: Column price\r\n idx: Column with index location\r\n flag: 0 if bar range price is open\r\n 1 if bar range price is average\r\n 2 if bar range price is maximun\r\n 3 if bar range price is minimun\r\n 4 if volume bar range or dollar bar range is added\r\n # returns\r\n returns a new data frame column according to the attribute flag\r\n '''\r\n flag_p =[]\r\n for i in range(0,len(idx)):\r\n if i == 0:\r\n inf = 0\r\n sup = idx[i]+1\r\n else:\r\n inf = idx[i-1]+1\r\n sup = idx[i]+1 \r\n if flag == 0:\r\n flag_p.append(df[att_column][inf])\r\n if flag == 1:\r\n flag_p.append(df[att_column][inf:sup].mean())\r\n if flag == 2:\r\n flag_p.append(df[att_column][inf:sup].max())\r\n if flag == 3:\r\n flag_p.append(df[att_column][inf:sup].min())\r\n if flag == 4:\r\n flag_p.append(df[att_column][inf:sup].sum())\r\n continue\r\n return flag_p\r\n\r\n\r\n\r\ndef bar_df(df, price_column,vol_column, dollar_column, treshold, flag):\r\n '''\r\n Compute the bar's kind selected with open bar price, average bar price,\r\n maximum bar price,minimum bar price and vwap.\r\n \r\n # args\r\n df: Pandas dataframe\r\n idx: Tick bar index\r\n dfn: Pandas dataframe from tick bar index\r\n bar_column: Column name for bar's kind\r\n dollar_column: Transaction amount column (price x quantity)\r\n vol_column: Stock quantity transactions\r\n treshold: int(), Threshold value for bar's kind\r\n flag: 0 if is a tick bar\r\n 1 if is a volume bar o dollar bar \r\n # returns\r\n Return a pandas data frame with computed tick bars and:\r\n open_b: Price from the begining of range\r\n avg_b: Average price computed from the bar range\r\n max_b: Maximum price computed from the bar range\r\n close_b: Rename the price in order to get more consistent with others\r\n variable notations\r\n '''\r\n if flag ==0:\r\n bar_column = price_column\r\n elif flag == 1:\r\n bar_column = vol_column\r\n else:\r\n bar_column = dollar_column\r\n \r\n idx = bar(df, bar_column, treshold, flag)\r\n dfn = df.iloc[idx].copy() \r\n dfn['open_b'] = attribute(df,price_column,idx,0)\r\n dfn['avg_b'] = attribute(df,price_column,idx,1)\r\n dfn['max_b'] = attribute(df,price_column,idx,2)\r\n dfn['min_b'] = attribute(df,price_column,idx,3)\r\n dfn['vol_acum_b'] = attribute(df,vol_column,idx,4)\r\n dfn['dollar_acum_b'] = attribute(df,dollar_column,idx,4)\r\n dfn['vwap_b'] = vwap(df, vol_column,dollar_column,idx)\r\n dfn = dfn.drop([vol_column, dollar_column], axis = 1)\r\n dfn.rename(columns={'price': 'close_b'}, inplace=True)\r\n return dfn\r\n\r\n\r\ndef tick_rule(df,price_column):\r\n '''\r\n Compute the tick rule proposed by Lopez del Prado in AMLF\r\n # args\r\n df: Pandas dataframe\r\n price_column: price column name\r\n \r\n # returns \r\n Returns a panda dataframe column, with delta price sing\r\n bt = abs(dp)/dp\r\n if bt == 0 then bt = bt-1\r\n In order to get information at series begin, the bt takes bt+1 sing.\r\n \r\n '''\r\n # For some reaon panda gets a warning message. The next code\r\n # disable this message\r\n pd.options.mode.chained_assignment = None\r\n dfn = df.copy()\r\n dfn[price_column] = dfn[price_column] - dfn[price_column].shift(1)\r\n dfn[price_column] = dfn[price_column].apply(np.sign)\r\n dfn[price_column][dfn[price_column]==0] = np.nan\r\n dfn[price_column] = dfn[price_column].fillna(method='ffill')\r\n dfn[price_column] = dfn[price_column].fillna(method='bfill')\r\n dfn.rename(columns={price_column: 'tick_rule'},inplace=True)\r\n return dfn['tick_rule']\r\n return dfn" } ]
2
Tanvir18/coffe_shop
https://github.com/Tanvir18/coffe_shop
e77918b2683253c5cab846a75de80b85f598329e
3fc488909ee70148480d9d6a271a3c890b3827dc
5c080f4e0e1f7673a39500aee8b45b8cdd9f56b3
refs/heads/master
2020-07-23T18:57:34.649036
2019-09-10T22:36:52
2019-09-10T22:36:52
207,670,419
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6722689270973206, "alphanum_fraction": 0.7226890921592712, "avg_line_length": 58.5, "blob_id": "8f73b497f893b67fddea6a4a841fbdcb20bb452b", "content_id": "e64cb5ddb8b41437e4f5728b96d88e892085abbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 119, "license_type": "no_license", "max_line_length": 105, "num_lines": 2, "path": "/README.md", "repo_name": "Tanvir18/coffe_shop", "src_encoding": "UTF-8", "text": "# coffe_shop\n I am trying to make web app using Python 3.7.4, Django 2.2.5, PostgreSQL, ORM, HTMaL, CSS, Bootstrap etc\n" }, { "alpha_fraction": 0.723809540271759, "alphanum_fraction": 0.723809540271759, "avg_line_length": 20.100000381469727, "blob_id": "2ba3ffaa498253e694e341a25af63574a2a4120c", "content_id": "dd3e3a313d0e27aab785c7f46b93a81c82a56cf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/coffee/views.py", "repo_name": "Tanvir18/coffe_shop", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import coffee\n# Create your views here.\n\n\ndef index(request):\n\n coffees = coffee.objects.all()\n\n return render(request, \"index.html\", {'coffees': coffees})" } ]
2
HanYaodong/algorithm
https://github.com/HanYaodong/algorithm
0ca685eb8dda734c0d6310bafc9888de2c48a83d
28ffaccddf3f019127b022c7e9cdd86c05740e3a
ad04d98cfb9e59ccded0ce4568eccb77ee89ec27
refs/heads/master
2023-01-10T10:20:56.642028
2020-11-16T10:50:01
2020-11-16T10:50:01
258,149,291
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48890453577041626, "alphanum_fraction": 0.4938358664512634, "avg_line_length": 27.96938705444336, "blob_id": "69f770ec54c3867ad2d050e3f02e0859b48ba712", "content_id": "d74b0ca0538d3afe3565ce9871a195d98d9bbe0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2839, "license_type": "no_license", "max_line_length": 79, "num_lines": 98, "path": "/veb_tree.py", "repo_name": "HanYaodong/algorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nvan Emde Boas tree is a data structure for fast insertion, deletion\nor finding successor of a given number on {0, 1, ..., u}\nin O(log(log u)) time\n\"\"\"\n\nimport math\n\n\nclass VEBTree(object):\n __slots__ = ['size', 'sub_size', 'min', 'max', 'summary', 'clusters']\n\n def __init__(self, size: int):\n self.size = size\n self.sub_size = math.ceil(math.sqrt(size))\n self.min = None\n self.max = None\n if self.size > 2:\n self.summary = VEBTree(self.sub_size)\n self.clusters = [None for _ in range(self.sub_size)]\n\n def high(self, n: int) -> int:\n return n // self.sub_size\n\n def low(self, n: int) -> int:\n return n % self.sub_size\n\n def index(self, i: int, j: int) -> int:\n return i * self.sub_size + j\n\n def insert(self, x: int):\n if self.min is None:\n self.min = x\n self.max = x\n return\n if x < self.min:\n x, self.min = self.min, x\n if x > self.max:\n self.max = x\n i = self.high(x)\n if self.size <= 2:\n return\n if self.clusters[i] is None:\n self.summary.insert(i)\n self.clusters[i] = VEBTree(self.sub_size)\n self.clusters[i].insert(self.low(x))\n\n def delete(self, x: int):\n if self.size <= 2:\n if self.min == self.max:\n self.min = None\n self.max = None\n elif self.min == x:\n self.min = self.max\n else:\n self.max = self.min\n return\n if self.min == x:\n i = self.summary.min\n if i is None:\n self.min = None\n self.max = None\n return\n x = self.index(i, self.clusters[i].min)\n self.min = x\n self.clusters[self.high(x)].delete(self.low(x)) # recursive call\n if self.clusters[self.high(x)].min is None:\n self.summary.delete(self.high(x)) # recursive call\n if self.max == x:\n m = self.summary.max\n if m is None:\n self.max = None\n else:\n self.max = self.index(m, self.clusters[m].max)\n\n def successor(self, x: int) -> int:\n if self.min > x:\n return self.min\n if self.size <= 2 and self.max > x:\n return self.max\n i = self.high(x)\n if self.clusters[i] is not None and self.low(x) < self.clusters[i].max:\n j = self.clusters[i].successor(self.low(x))\n else:\n i = self.summary.successor(self.high(x))\n j = self.clusters[i].min\n return self.index(i, j)\n\n\nif __name__ == '__main__':\n r = VEBTree(16)\n r.insert(2)\n r.insert(3)\n r.insert(1)\n print(r.successor(0))\n r.delete(1)\n print(r.successor(0))\n pass\n" }, { "alpha_fraction": 0.610837459564209, "alphanum_fraction": 0.610837459564209, "avg_line_length": 20.36842155456543, "blob_id": "25ff21b85905aa9d7eb0495d51a3cfcaac7a8198", "content_id": "cfa06a5dc38a77b687d14e4794ca0e790fadd0d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 61, "num_lines": 19, "path": "/util.py", "repo_name": "HanYaodong/algorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nSome util functions\n\"\"\"\n\nimport functools\nimport time\n\n\ndef timeit(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n start_time = time.perf_counter()\n result = func(*args, **kwargs)\n end_time = time.perf_counter()\n elapse_time = end_time - start_time\n print(f'It took {elapse_time} seconds to run {func}')\n return result\n\n return wrapper\n" }, { "alpha_fraction": 0.7699680328369141, "alphanum_fraction": 0.7763578295707703, "avg_line_length": 38.125, "blob_id": "88aaed9cfa0fff6f0c368a0fbe93afa2c5410d4c", "content_id": "39df259ef8b90aad37662d070f708a25526acb96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 313, "license_type": "no_license", "max_line_length": 60, "num_lines": 8, "path": "/README.md", "repo_name": "HanYaodong/algorithm", "src_encoding": "UTF-8", "text": "# Algorithms\nSome interesting algorithms implemented in Python\n## Currently have:\n- von Emde Boas tree for fast lookup\n- Manacher algorithm for finding longest palidromic sequence\n- Skip list, a O(log(n)) time random access linked list\n- A puzzle solver by Raymond Hettinger shown in pyCon 19\n- A minimal Char RNN by Andrej\n" }, { "alpha_fraction": 0.3336809277534485, "alphanum_fraction": 0.34932219982147217, "avg_line_length": 21.83333396911621, "blob_id": "852315244f2361f4f59fcf154e5bb9fcaeb6d56f", "content_id": "7f87425a806bb3f04c5c4244ddf69504a161aa81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 959, "license_type": "no_license", "max_line_length": 60, "num_lines": 42, "path": "/manacher.py", "repo_name": "HanYaodong/algorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nManacher's algorithm is used to find the longest palindromic\nsubstring in a given string in O(n) time.\ne.g. 'eabcbadf' -> 'abcba'\n\"\"\"\n\n\ndef manacher_palindromic(s: str) -> str:\n s = '|' + '|'.join(s) + '|'\n p = [0] * len(s)\n r = 0\n c = 0\n i = 1\n for i in range(len(s)):\n j = 2 * c - i\n if i < c + p[c]:\n if j - p[j] > c - p[c]:\n # case 1\n p[i] = p[j]\n l = -1\n else:\n # case 2\n p[i] = c + p[c] - i\n l = 2 * i - r\n else:\n # case 3\n r = i\n l = i\n while l >= 0 and r < len(s) and s[r] == s[l]:\n p[i] += 1\n r += 1\n l -= 1\n if i + p[i] > c + p[c]:\n c = i\n m = max(p)\n c = p.index(m)\n return s[c - m + 1:c + m].replace('|', '')\n\n\nif __name__ == '__main__':\n a = manacher_palindromic('cabbaded')\n print(a)\n" }, { "alpha_fraction": 0.5179420709609985, "alphanum_fraction": 0.5251477360725403, "avg_line_length": 31.425233840942383, "blob_id": "ff4584a50fd1bea3fcb6707d6db47a6f9183e498", "content_id": "4d0cf1b513e56211ca62f61dcb2fccdf1e5c24ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6939, "license_type": "no_license", "max_line_length": 93, "num_lines": 214, "path": "/skip_list.py", "repo_name": "HanYaodong/algorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nA not so neat implementation of skip list data structure.\nSkip list can do search, insert and delete in O(lg n) time,\nin O(n) space, with high probability\n\"\"\"\nfrom __future__ import annotations\n\nfrom random import randrange\nfrom typing import List, Optional, Tuple\n\n\nclass SkipListNode:\n def __init__(self, value: int = -1):\n self.value: int = value\n self.next: Optional[SkipListNode] = None\n self.pre: Optional[SkipListNode] = None\n self.down: Optional[SkipListNode] = None\n self.up: Optional[SkipListNode] = None\n\n def search(self, x: int, path: List[SkipListNode]) \\\n -> Tuple[Optional[SkipListNode], List[SkipListNode]]:\n \"\"\"\n search and return the node with value x\n (node, path)\n \"\"\"\n if self.value == x:\n # item found, go to level 0 to find the position\n if self.down is None:\n # item found\n return self, path\n else:\n # go down\n path.append(self)\n return self.down.search(x, path)\n\n if self.down is None:\n # level 0, linear search\n if self.next is None or self.next.value > x:\n # hit list end or larger value at level 0, return None\n return None, path\n else:\n return self.next.search(x, path)\n\n if self.next is None or self.next.value > x:\n # hit list end or larger value, go down level\n path.append(self)\n return self.down.search(x, path)\n else:\n return self.next.search(x, path)\n\n def search_node_right_before(self, x: int, path: List[SkipListNode]) \\\n -> Tuple[SkipListNode, List[SkipListNode]]:\n \"\"\"\n search the node right before the value x should be inserted\n \"\"\"\n if self.value == x:\n return self.search(x, path)\n if self.down is None:\n # level 0, linear search\n if self.next is None or self.next.value > x:\n return self, path\n else:\n return self.next.search_node_right_before(x, path)\n if self.next is None or self.next.value > x:\n path.append(self)\n return self.down.search_node_right_before(x, path)\n return self.next.search_node_right_before(x, path)\n\n def insert_after(self, x: int) -> SkipListNode:\n \"\"\"\n insert a node as successor of current node\n \"\"\"\n new_node = SkipListNode(value=x)\n new_node.next = self.next\n new_node.pre = self\n self.next = new_node\n if new_node.next is not None:\n new_node.next.pre = new_node\n return new_node\n\n def insert_above(self) -> SkipListNode:\n new_node = SkipListNode(value=self.value)\n new_node.down = self\n self.up = new_node\n return new_node\n\n def delete(self) -> None:\n if self.up is not None:\n self.up.delete()\n self.pre.next = self.next\n if self.next is not None:\n self.next.pre = self.pre\n\n\nclass SkipList:\n def __init__(self) -> None:\n self.node_list: List[SkipListNode] = list()\n\n def is_empty(self) -> bool:\n return len(self.node_list) == 0\n\n def top_list_node(self) -> SkipListNode:\n return self.node_list[len(self.node_list) - 1]\n\n def search(self, x: int) -> bool:\n n, _ = self.top_list_node().search(x, [])\n return n is not None\n\n def insert(self, x: int) -> None:\n print(f\"inserting {x}\")\n if self.is_empty():\n # if the list is empty\n self.node_list.append(SkipListNode(value=x))\n return\n if self.node_list[0].value > x:\n # insert the first element\n new_node = SkipListNode(x)\n new_node.next = self.node_list[0]\n self.node_list[0].pre = new_node\n self.node_list[0].up = None\n self.node_list[0] = new_node\n if len(self.node_list) > 1:\n self.node_list[0].up = self.node_list[1]\n self.node_list[1].down = self.node_list[0]\n for node in self.node_list:\n node.value = x\n return\n\n node, path = self.top_list_node().search_node_right_before(x, [])\n last_node = node.insert_after(x)\n\n for path_node in path:\n if randrange(2) == 0:\n break\n new_node = path_node.insert_after(x)\n new_node.down = last_node\n last_node.up = new_node\n last_node = new_node\n else:\n while True:\n if randrange(2) == 0:\n break\n start_node = self.top_list_node().insert_above()\n new_node = last_node.insert_above()\n self.node_list.append(start_node)\n start_node.next = new_node\n new_node.pre = start_node\n last_node = new_node\n\n def delete(self, x: int) -> bool:\n print(f'deleting {x}')\n if self.node_list[0].value == x:\n # delete first element\n self.node_list[0] = self.node_list[0].next\n old_up = self.node_list[0].up\n if len(self.node_list) > 1:\n self.node_list[0].up = self.node_list[1]\n self.node_list[1].down = self.node_list[0]\n for node in self.node_list:\n node.value = self.node_list[0].value\n\n if old_up is not None:\n old_up.delete()\n return True\n\n node, path = self.top_list_node().search(x, [])\n if node is None:\n return False\n node.delete()\n return True\n\n def show(self):\n first_row: List[SkipListNode] = []\n process_node = self.node_list[0]\n while process_node is not None:\n first_row.append(process_node)\n process_node = process_node.next\n\n node_matrix: List[List[Optional[SkipListNode]]] = [[None for _ in first_row] for _ in\n self.node_list]\n node_matrix[0] = first_row\n for i, node in enumerate(first_row):\n node = node.up\n for j in range(1, len(self.node_list)):\n if node is None:\n break\n node_matrix[j][i] = node\n node = node.up\n value_matrix = '\\n'.join(\n [\"\\t\".join([str(n.value) if n is not None else \"\" for n in row]) for row in\n node_matrix]) + '\\n'\n return value_matrix\n\n\nif __name__ == '__main__':\n ll = SkipList()\n ll.insert(1)\n ll.insert(5)\n ll.insert(10)\n ll.insert(20)\n ll.insert(15)\n ll.insert(25)\n print(ll.show())\n\n ll.delete(15)\n print(ll.show())\n ll.delete(1)\n print(ll.show())\n\n ll.insert(1)\n print(ll.show())\n\n ll.insert(30)\n print(ll.show())\n" } ]
5
quochuyjava/Population-Census
https://github.com/quochuyjava/Population-Census
534c7fd4a775178ac9be2dc34df4e053898598c8
bd768ca10af44fbb54253730f857ea91231934b2
94479780d30a8012e6ff4b815013178d5b4cdf7a
refs/heads/master
2020-08-08T18:15:14.192060
2020-04-12T20:43:31
2020-04-12T20:43:31
213,885,989
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6639344096183777, "alphanum_fraction": 0.6639344096183777, "avg_line_length": 29.5, "blob_id": "d3880b958333a1c2dcf8f7371533cccce496aa7d", "content_id": "789a2e2698bc3c98ad47023b41fc23d9d470a522", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 89, "num_lines": 8, "path": "/Country.py", "repo_name": "quochuyjava/Population-Census", "src_encoding": "UTF-8", "text": "class Country:\n '''\n Describe a type country, which contains country name and country population in a year\n '''\n\n def __init__(self, name, populationInYear):\n self.name = name\n self.populationInYear = populationInYear\n" }, { "alpha_fraction": 0.6286654472351074, "alphanum_fraction": 0.6346731781959534, "avg_line_length": 32.1327018737793, "blob_id": "60795c97e7e30a6a00d00aa3d2c5759c9bf37dd3", "content_id": "4a773f02f9f9d74e9ab47ae27f0994d9edd0b87e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6991, "license_type": "no_license", "max_line_length": 136, "num_lines": 211, "path": "/StartUp.py", "repo_name": "quochuyjava/Population-Census", "src_encoding": "UTF-8", "text": "import copy\n\nimport pandas as pd\nfrom PyQt5 import QtWidgets as QtGui, QtWidgets\nfrom PyQt5.QtCore import QThread, QRect\nimport sys\n\nfrom PyQt5.QtWidgets import QApplication\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\n\nimport DataReader\nimport Graph\nimport design\nimport time\n\n# Declaration of global Variables\ncountriesData = pd.read_excel('population -countries.xls', sep=' ', encoding='utf-8') # Link to excel file\nworldData = pd.read_excel('population - world.xls', sep=' ', encoding='utf-8')\namountOfTopCountries = 20 # amount of top Countries per Year\nimageOutputFolder = '/Users/quochuy/Desktop/Github/Population-Census/Images'\nvideoOutputFolder = '/Users/quochuy/Desktop/Github/Population-Census/Images/Video.avi'\n\nFigureList = [] # List contains rendered Figures\nNumberOfFramesWouldBeRendered = 0\n\n\ndef init_years(dataReader):\n '''\n initialize a dictonary of years, which contains all Year Objects in the Data\n :param dataReader: Object from type Datareader, which analyze Excel data files\n :return: dictionary of years key: year (int) value: Year object\n '''\n import Year\n yearsDict = {}\n first_year = dataReader.getFirstYear()\n worldPopulationInYears = dataReader.getWorldPopulationInYearsDict()\n for x in range(dataReader.getCountOfYears()):\n this_year = first_year + x\n top_countries_in_this_year = dataReader.getTopCountries(this_year)\n yearsDict[first_year + x] = Year.Year(this_year, top_countries_in_this_year, worldPopulationInYears)\n return yearsDict\n\n\nclass DrawGraphThread(QThread):\n '''\n This Class's functions run in a new Thread to do functional tasks. For example: analyse Data, render Frames, export Images and Video\n '''\n def __init__(self):\n \"\"\"\n Make a new thread instance, prevent it to wait for the GUI\n \"\"\"\n QThread.__init__(self)\n\n def __del__(self):\n self.wait()\n\n def run(self):\n \"\"\"\n run in new thread\n \"\"\"\n import Graph\n import DataReader\n\n dataReader = DataReader.DataReader(countriesData, worldData, amountOfTopCountries)\n yearsDict = init_years(dataReader)\n graph = Graph.Graph(dataReader, yearsDict, imageOutputFolder, videoOutputFolder)\n\n global FigureList\n FigureList = graph.getFigureList()\n\n global NumberOfFramesWouldBeRendered\n NumberOfFramesWouldBeRendered = graph.getNumberofFramesWouldBeRendered()\n\n graph.render()\n\n\nclass MainWindow(QtGui.QMainWindow, design.Ui_MainWindow):\n \"\"\"\n This Class's functions draw figures on GUI and do tasks with GUI\n \"\"\"\n def __init__(self):\n super(self.__class__, self).__init__()\n self.setupUi(self)\n self.btn_start.clicked.connect(self.renderButtonClicked)\n self.btn_play_pause.clicked.connect(self.play)\n self.btn_stop.clicked.connect(self.stop)\n self.resize(1500, 1100)\n\n\n def renderButtonClicked(self):\n '''\n What do when Start Button is clicked\n '''\n # Change GUI Components\n QApplication.processEvents()\n self.btn_start.setEnabled(False)\n\n # FROM HIER: RUN IN NEW THREAD\n self.get_thread = DrawGraphThread()\n self.get_thread.start() # New Thread started\n self.drawFigure()\n\n def drawFigure(self):\n '''\n Draw first figure on GUI and wait the FigureList to be filled, so it could draw another Figure\n :return:\n '''\n global FigureList\n self.frameNumber = 0 # Start rendering with frame 0\n\n # Wait FigureList to fill the first Figure\n while len(FigureList) <= self.frameNumber:\n print('waiting for FigureList to init')\n time.sleep(.200)\n\n #First Figure Initialized\n thisFigure = FigureList[self.frameNumber]\n self.dynamic_canvas = FigureCanvas(thisFigure)\n self.view_layout.addWidget(self.dynamic_canvas)\n self.view_layout.removeWidget(self.dynamic_canvas)\n\n\n #Loop to update Figures\n self._timer = self.dynamic_canvas.new_timer(100,\n callbacks=[(self.updateFigure, [], {})])\n self._timer.start()\n\n\n\n def updateFigure(self):\n '''\n Update the Figure. When the a figure need to draw but still not in the FigureList, it wait with a for-loop\n :return:\n '''\n\n # Update Progess bar\n if self.progress_bar.value() != 100:\n self.progress_bar.setValue(float((len(FigureList) / NumberOfFramesWouldBeRendered)) * 100)\n\n # Add new Frame\n self.view_layout.addWidget(self.view_graph)\n self.dynamic_canvas.setParent(None)\n figure = copy.copy(FigureList[len(FigureList) -1]) # prevent figure to zoom in\n self.dynamic_canvas = FigureCanvas(figure)\n self.view_layout.addWidget(self.dynamic_canvas)\n self.view_layout.removeWidget(self.dynamic_canvas)\n self.label_status.setText(\"Rendering \"+ str(self.progress_bar.value()) + '% done')\n\n\n else: # All Frames are rendered\n self._timer.stop()\n self.btn_play_pause.setEnabled(True)\n self.btn_stop.setEnabled(True)\n self.progress_bar.hide()\n self.dynamic_canvas.setParent(None)\n self.label_status.setText(\"Rendering is finished.\")\n\n\n def play(self):\n '''\n Play rendered Frames\n '''\n # Update UI\n self.btn_play_pause.setEnabled(False)\n self.btn_stop.setEnabled(True)\n self.label_status.hide()\n\n self.frameNumber = 0\n self._timer2 = self.dynamic_canvas.new_timer(100, callbacks=[(self.updateFigurePlayback, [], {})])\n self._timer2.start()\n\n\n def stop(self):\n '''\n Stop playing\n '''\n self._timer2.stop()\n\n\n def updateFigurePlayback(self):\n '''\n Update the Figure. When the a figure need to draw but still not in the FigureList, it wait with a for-loop\n :return:\n '''\n # The Graph will stop at last Frame\n if self.frameNumber >= NumberOfFramesWouldBeRendered - 1:\n self._timer.stop()\n else: # Not at last Frame\n self.view_graph.setParent(None)\n self.view_layout.removeWidget(self.label_status)\n if self.frameNumber != 0:\n self.view_layout.removeWidget(self.dynamic_canvas)\n self.dynamic_canvas.deleteLater()\n self.frameNumber = self.frameNumber + 1\n figure = FigureList[self.frameNumber]\n self.dynamic_canvas = FigureCanvas(figure)\n self.view_layout.addWidget(self.dynamic_canvas)\n\n def closeEvent(self, event):\n sys.exit(app.exec_())\n\n\ndef main():\n global app\n app = QtGui.QApplication(sys.argv)\n form = MainWindow()\n form.show()\n app.exec_()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7312775254249573, "alphanum_fraction": 0.7356828451156616, "avg_line_length": 36.5, "blob_id": "50c169ddb8d253337534fb150af97d61daac8f80", "content_id": "dfe8d49a12642b15b4bc62ba336fad578a97eb6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 227, "license_type": "no_license", "max_line_length": 68, "num_lines": 6, "path": "/README.md", "repo_name": "quochuyjava/Population-Census", "src_encoding": "UTF-8", "text": "# Population-Census\nData visualization of the world and countries's population each year\n\n![alt text](https://i.imgur.com/nnjf9rS.png)\n![alt text](https://i.imgur.com/OcVxTDK.png)\n![alt text](https://i.imgur.com/OcVxTDK.png)\n\n\n" }, { "alpha_fraction": 0.6420355439186096, "alphanum_fraction": 0.6444754004478455, "avg_line_length": 33.130950927734375, "blob_id": "3e279f9cee0783431d933c1503a9ebbfed3e624c", "content_id": "c353947ddf22a3de1f4d190a64b03037ee1aa9dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2869, "license_type": "no_license", "max_line_length": 116, "num_lines": 84, "path": "/DataReader.py", "repo_name": "quochuyjava/Population-Census", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport glob\nimport cv2\nimport os\n\n\nclass DataReader:\n '''\n an Object of this Class could analyse data and give needed Information back\n '''\n def __init__(self, countriesData, worldData, amountOfTopCountries):\n self.countriesData = countriesData\n self.worldData = worldData\n\n self.deleteOtherCollums()\n self.amountOfTopCountries = amountOfTopCountries\n\n def deleteOtherCollums(self):\n '''\n Delete no needed Columns in the countries population table\n '''\n\n self.countriesData = self.countriesData.drop(columns=['Country Code', 'Indicator Name', 'Indicator Code'])\n\n def getCountOfCountries(self):\n '''\n Get the count of Countries back\n :return: count of Countries\n '''\n return len(self.countriesData)\n\n def getCountOfYears(self):\n '''\n Get the count of recorded years back\n :return: count of recorded years\n '''\n return len(self.worldData)\n\n def getTopCountries(self, year):\n '''\n Get a dictionary of Countries, which have most population\n :return: The Dictionary of the Names of Countries\n '''\n\n # remove all values from another years\n populationInYear = self.countriesData[['Country Name', str(year)]]\n # get top 20 countries\n populationInYear = populationInYear.nlargest(self.amountOfTopCountries, columns=str(year))\n # convert the top Dataframe to a dict\n topDict = populationInYear.set_index('Country Name').to_dict()\n return topDict.get(str(year))\n\n def getFirstYear(self):\n '''\n Get the earliest year in data\n :return: earliest year in type numpy.int64\n '''\n return self.worldData.iloc[0, 1]\n\n def getWorldPopulationInYearsDict(self):\n '''\n Get a Dictionary of world population, key = year, value = population\n :return: The Dictionary\n '''\n # delete fisrt column\n worldPopulation = self.worldData[['year', 'population']]\n # convert to dictionary\n worldPopulation = worldPopulation.set_index('year').to_dict()\n # print(worldPopulation.get('population'))\n return worldPopulation.get('population')\n\n def getHighestPopulationOfAllCountries(self):\n '''\n Get the highest population of all Countries in all years.\n :return: highest population. Type int\n '''\n countries = self.countriesData.melt(id_vars='Country Name')\n countries = countries.rename(columns={'Country Name': 'country', 'variable': 'year', 'value': 'population'})\n countries = countries[~ countries.population.isna()]\n countries = countries.astype({'population': int})\n return countries.population.max()\n\n\n" }, { "alpha_fraction": 0.5540562272071838, "alphanum_fraction": 0.5715193152427673, "avg_line_length": 45.31617736816406, "blob_id": "3daac00ad6c3fe74d6d2b00f50f4c671316a30e8", "content_id": "b422dd240696a43b07052e72f5be066865d10ae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6303, "license_type": "no_license", "max_line_length": 151, "num_lines": 136, "path": "/Graph.py", "repo_name": "quochuyjava/Population-Census", "src_encoding": "UTF-8", "text": "import sys\nimport threading\n\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport os\nimport cv2\nfrom PyQt5.QtWidgets import QApplication\n\n\n\nclass Graph:\n '''\n an Object of this Class could save Graphs into Images and render Video from saved Images\n '''\n def __init__(self, dataReader, yearsDict, imageOutputFolder, videoOutputFolder):\n self.dataReader = dataReader\n self.yearsDict = yearsDict\n self.NumberOfYears = dataReader.getCountOfYears()\n self.MaxPopulationPerCountry = dataReader.getHighestPopulationOfAllCountries()\n self.numberOfCountries = dataReader.amountOfTopCountries\n self.imageOutputFolder = imageOutputFolder\n self.videoOutputFolder = videoOutputFolder\n\n self.figureList = [] # A List to save all rendered Figures\n self.framePerYear = 3\n def render(self):\n for x in range(self.NumberOfYears): # Each loop for a year\n # Variable declaration for each year\n thisYearInt = self.dataReader.getFirstYear() + x\n thisYearObject = self.yearsDict.get(thisYearInt)\n if x < self.NumberOfYears - 1:\n nextYearObject = self.yearsDict.get(thisYearInt + 1)\n topPopulationNextYearList = nextYearObject.getTopPopulationList()\n topCountriesThisYearList = thisYearObject.getTopNameList()\n topPopulationThisYearList = thisYearObject.getTopPopulationList()\n\n for frame in range (self.framePerYear): # eachloop for a Frame in year\n #change Value of each Frame\n for index in range (len(topPopulationThisYearList)):\n if x < self.NumberOfYears: difference = topPopulationNextYearList[index] - topPopulationThisYearList[index]\n topPopulationThisYearList[index] = topPopulationThisYearList[index] + (difference * frame)/self.framePerYear\n\n # Size of the Image width x height in Inches\n self.pic = plt.figure(figsize=(15, 10))\n # set Style in Seabron\n sb.set_style('dark')\n # Draw the Graph\n sb.barplot(\n x=topPopulationThisYearList,\n y=topCountriesThisYearList,\n palette=sb.color_palette(\"YlOrRd_r\", self.numberOfCountries)) # Color for the bars\n # Set title\n title_obj = plt.title(\"Top \" +str(self.numberOfCountries)+ \" Countries with the Highest Population\".upper() + '\\n ' + str(thisYearInt))\n plt.setp(title_obj, color='orangered', fontsize=30)\n\n # Draw the Axes\n plt.tick_params(axis=\"y\",\n labelsize=self.getRelativeSize(14),\n labelrotation=15, labelcolor=\"g\")\n plt.tick_params(axis=\"x\", labelsize=17, labelrotation=0, labelcolor=\"g\",\n bottom=True, top=True, labeltop=True, labelbottom=True)\n plt.xlim(right=(1.2 * self.MaxPopulationPerCountry)) # Set Length for X-Axis\n plt.xlabel('\\nPopulation in Billions', fontsize=20, color=\"g\") # Label for X-Axis\n plt.ylabel('') # Label for Y-Axis\n\n for t in range(self.numberOfCountries): # Each loop for a country\n value = f'{int(topPopulationThisYearList[t]):,}'\n plt.text(topPopulationThisYearList[t] + 50000000, t, # gap between Bars\n value,\n color='deepskyblue', va=\"center\", fontsize=self.getRelativeSize(17))\n # Add rank to the graph\n plt.text(1000000, t,\n str(t + 1),\n color='lime', va=\"center\", fontsize=self.getRelativeSize(17))\n\n # Add World Population\n plt.text(610000000, self.numberOfCountries/3,\n 'TOTAL POPULATION OF THE WORLD',\n color='orangered', va=\"center\", fontsize=25)\n\n # Insert world's population in the center\n world_population = thisYearObject.getWorldPopulationThisYear()\n world_population = self.getFormattedStr(world_population)\n plt.text(560000000, self.numberOfCountries/2,\n world_population,\n color='orangered', va=\"center\", fontsize=80)\n\n # Signature\n plt.text(1000000000, self.numberOfCountries * 0.9,\n 'Võ Văn Thương - TP Hồ Chí Minh, Việt Nam, 09.2019'\n '\\nQuoc Huy Nguyen - Hamburg, Germany, 10.2019'\n '\\nData sources: https://data.worldbank.org',\n color='royalblue', va=\"center\", fontsize=13)\n\n #self.saveImages(thisYearInt, self.pic)\n self.addFiguretoList(self.pic)\n\n def saveImages(self, thisYear, pic): # Save image to png files (not in use)\n filename = 'population_' + str(thisYear) + '.png'\n plt.savefig('/Users/quochuy/Desktop/Github/Population-Census/Images/' + filename, dpi=50)\n plt.close()\n\n def addFiguretoList(self, pic):\n '''\n Add the rendered figure to List\n :param pic: The rendered Figure\n '''\n self.figureList.append(self.pic)\n plt.close()\n\n def getFigureList(self):\n '''\n Give the List of all RENDERED FIGURES\n :return:\n '''\n return self.figureList\n\n def getFormattedStr(self, population):\n '''\n Conver Int to a String in form: 1.000.000\n :param population: In Type Int\n :return: String in form 1.000.000\n '''\n return f'{int(population):,}'\n\n def getNumberofFramesWouldBeRendered(self):\n return self.NumberOfYears * self.framePerYear\n\n def getRelativeSize(self, size):\n '''\n Convert values of sizes, so the components could stay at their positions even when the size of Images was changed\n :param size: absolute size\n :return: relative size\n '''\n return size*20/self.numberOfCountries\n" }, { "alpha_fraction": 0.6232821345329285, "alphanum_fraction": 0.6281325817108154, "avg_line_length": 32.43243408203125, "blob_id": "d85b1e8ac53cd98cbfd592d732885ee2f1a09654", "content_id": "e8eb4cd2df9e85352053091f054764c88b66725f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1237, "license_type": "no_license", "max_line_length": 113, "num_lines": 37, "path": "/Year.py", "repo_name": "quochuyjava/Population-Census", "src_encoding": "UTF-8", "text": "import Country\nclass Year:\n '''\n Describe a type Year for each year, it contains world's population in this year and top countries Objects\n '''\n\n def __init__(self, year, topCountries, WorldPopulationInYear):\n self.year = year\n self.worldPopulationThisYear = WorldPopulationInYear.get(year)\n self.countries = []\n # self.top20Countries = top20Countries\n for key in topCountries:\n value = topCountries.get(str(key))\n self.countries.append(Country.Country(key, value))\n\n def getWorldPopulationThisYear(self):\n return self.worldPopulationThisYear\n\n def getTopPopulationList(self):\n '''\n Return a list with Population of top Countries. Index 0: Most\n :return: List population with type Float\n '''\n List = []\n for country in self.countries:\n List.append(country.populationInYear)\n return List\n\n def getTopNameList(self):\n '''\n Return a list with Name of top Countries. Index 0: Country has most population\n :return: List population with type Str\n '''\n List = []\n for country in self.countries:\n List.append(country.name)\n return List\n" }, { "alpha_fraction": 0.698051929473877, "alphanum_fraction": 0.7089728713035583, "avg_line_length": 48.82352828979492, "blob_id": "0e0831c825f280d83dc81a7d5610a4228fdedafb", "content_id": "f513ada847d9f769295090c7cd45c1843be105c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3388, "license_type": "no_license", "max_line_length": 114, "num_lines": 68, "path": "/design.py", "repo_name": "quochuyjava/Population-Census", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'designcopy.ui'\n#\n# Created by: PyQt5 UI code generator 5.13.1\n#\n# WARNING! All changes made in this file will be lost!\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(1432, 819)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.view_layout = QtWidgets.QVBoxLayout()\n self.view_layout.setObjectName(\"view_layout\")\n self.view_graph = QtWidgets.QGraphicsView(self.centralwidget)\n self.view_graph.setObjectName(\"view_graph\")\n self.view_layout.addWidget(self.view_graph)\n self.verticalLayout.addLayout(self.view_layout)\n self.status_layout = QtWidgets.QVBoxLayout()\n self.status_layout.setObjectName(\"status_layout\")\n self.progress_bar = QtWidgets.QProgressBar(self.centralwidget)\n self.progress_bar.setProperty(\"value\", 0)\n self.progress_bar.setObjectName(\"progress_bar\")\n self.status_layout.addWidget(self.progress_bar)\n self.label_status = QtWidgets.QLabel(self.centralwidget)\n self.label_status.setObjectName(\"label_status\")\n self.status_layout.addWidget(self.label_status)\n self.verticalLayout.addLayout(self.status_layout)\n self.buttons_layout = QtWidgets.QHBoxLayout()\n self.buttons_layout.setObjectName(\"buttons_layout\")\n self.btn_start = QtWidgets.QPushButton(self.centralwidget)\n self.btn_start.setObjectName(\"btn_start\")\n self.buttons_layout.addWidget(self.btn_start)\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.buttons_layout.addItem(spacerItem)\n self.btn_play_pause = QtWidgets.QPushButton(self.centralwidget)\n self.btn_play_pause.setEnabled(False)\n self.btn_play_pause.setMinimumSize(QtCore.QSize(100, 0))\n self.btn_play_pause.setMaximumSize(QtCore.QSize(100, 50))\n self.btn_play_pause.setObjectName(\"btn_play_pause\")\n self.buttons_layout.addWidget(self.btn_play_pause)\n self.btn_stop = QtWidgets.QPushButton(self.centralwidget)\n self.btn_stop.setEnabled(False)\n self.btn_stop.setMinimumSize(QtCore.QSize(100, 0))\n self.btn_stop.setMaximumSize(QtCore.QSize(100, 50))\n self.btn_stop.setObjectName(\"btn_stop\")\n self.buttons_layout.addWidget(self.btn_stop)\n self.verticalLayout.addLayout(self.buttons_layout)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Population Census\"))\n self.label_status.setText(_translate(\"MainWindow\", \"Status: No frame has been rendered\"))\n self.btn_start.setText(_translate(\"MainWindow\", \"Render\"))\n self.btn_play_pause.setText(_translate(\"MainWindow\", \"Play\"))\n self.btn_stop.setText(_translate(\"MainWindow\", \"Stop\"))\n" } ]
7
alexchang0229/passboard
https://github.com/alexchang0229/passboard
5232effaa01d7af0a666a0ef87b801e113dcd0f3
6740e21adf3d8c857403f8589348d6408d75a0cf
5e54142b42b4b09bb6528f5b440c691db56142ff
refs/heads/main
2023-07-18T09:15:43.833415
2021-09-08T20:00:52
2021-09-08T20:00:52
404,149,534
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.41769230365753174, "alphanum_fraction": 0.4300000071525574, "avg_line_length": 35.11111068725586, "blob_id": "c16f09d4a60a1830d0f837486c8ab9602036cde1", "content_id": "1bc86edad8b589e26aa3f4a3379f3f4c77eed964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1300, "license_type": "no_license", "max_line_length": 108, "num_lines": 36, "path": "/frontend/src/pages/AboutPage.js", "repo_name": "alexchang0229/passboard", "src_encoding": "UTF-8", "text": "import React from 'react'\nimport { Grid, Paper } from '@material-ui/core';\nimport LinkedInButton from '../assets/LinkedIn-Button.png'\nimport Instructions_picture from '../assets/instructions.png'\nimport Divider from '@material-ui/core/Divider';\n\nexport default function AboutPage() {\n\n return (\n <div className=\"App-header\">\n <Grid\n container\n direction=\"row\"\n justify=\"center\"\n style={{\n marginTop: '5%',\n marginBottom: '5%',\n width: '100%',\n }}>\n <Grid item md={7} sm={12} >\n <Paper>\n <h1>About</h1>\n <img src={Instructions_picture} alt=\"Instructions\" style={{\n maxWidth: '100%',\n height: 'auto'\n }} />\n <p>This app was built by Alex Chang</p>\n <a href=\"https://www.linkedin.com/in/alexyuchang/\" target=\"_blank\" rel=\"noreferrer\">\n <img src={LinkedInButton} alt=\"LinkedIn Icon\" height={100} />\n </a>\n </Paper>\n </Grid>\n </Grid>\n </div >\n )\n}\n" }, { "alpha_fraction": 0.4053540825843811, "alphanum_fraction": 0.41307276487350464, "avg_line_length": 47.01176452636719, "blob_id": "ea11df923ac19b8cb09666ac708ce3ae91f9341d", "content_id": "45b5e946414a39fa893d257bba31517133ee605d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 16324, "license_type": "no_license", "max_line_length": 142, "num_lines": 340, "path": "/frontend/src/pages/PassTimeTable.js", "repo_name": "alexchang0229/passboard", "src_encoding": "UTF-8", "text": "import React, { useState, useRef, useCallback, useEffect } from 'react';\nimport { makeStyles } from '@material-ui/core/styles';\nimport Table from '@material-ui/core/Table';\nimport TableBody from '@material-ui/core/TableBody';\nimport TableCell from '@material-ui/core/TableCell';\nimport TableContainer from '@material-ui/core/TableContainer';\nimport TableSortLabel from '@material-ui/core/TableSortLabel';\nimport TableHead from '@material-ui/core/TableHead';\nimport Grid from '@material-ui/core/Grid';\nimport TableRow from '@material-ui/core/TableRow';\nimport Paper from '@material-ui/core/Paper';\nimport Clock from 'react-live-clock';\nimport Collapse from '@material-ui/core/Collapse';\nimport IconButton from '@material-ui/core/IconButton';\nimport KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';\nimport KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';\nimport Countdown from 'react-countdown';\nimport Link from '@material-ui/core/Link';\nimport { CSVLink } from \"react-csv\";\nimport OrbitMap from \"../functions/OrbitMap.js\";\nimport LinearProgress from '@material-ui/core/LinearProgress';\n\n\n\nconst useStyles = makeStyles({\n grid: {\n paddingBottom: \"10vh\",\n paddingTop: \"3vh\",\n width: '100%',\n overflowX: 'auto',\n }\n});\n\nfunction descendingComparator(a, b, orderBy) {\n if (b[orderBy] < a[orderBy]) {\n return -1;\n }\n if (b[orderBy] > a[orderBy]) {\n return 1;\n }\n return 0;\n}\n\nfunction getComparator(order, orderBy) {\n return order === 'desc'\n ? (a, b) => descendingComparator(a, b, orderBy)\n : (a, b) => -descendingComparator(a, b, orderBy);\n}\n\nfunction stableSort(array, comparator) {\n const stabilizedThis = array.map((el, index) => [el, index]);\n stabilizedThis.sort((a, b) => {\n const order = comparator(a[0], b[0]);\n if (order !== 0) return order;\n return a[1] - b[1];\n });\n return stabilizedThis.map((el) => el[0]);\n}\n\nconst headCells = [\n { id: 'satName', alignDirection: 'left', label: 'Satellite name' },\n { id: 'orbitnum', alignDirection: 'left', label: 'Orbit' },\n { id: 'start', alignDirection: 'center', label: 'AOS' },\n { id: 'end', alignDirection: 'center', label: 'LOS' },\n { id: 'duration', alignDirection: 'right', label: 'Duration' },\n];\n\n\nconst AOSLOSTime = _time => {\n const passEpoch = new Date(0)\n passEpoch.setUTCSeconds(_time);\n return (`${dayOfYear(passEpoch)}-${(\"0\" + passEpoch.getHours()).slice(-2)}`\n + `:${(\"0\" + passEpoch.getMinutes()).slice(-2)}`\n + `:${(\"0\" + passEpoch.getSeconds()).slice(-2)}`)\n}\n\nconst dayOfYear = _date => {\n const passTime = _date\n return Math.floor((passTime - new Date(passTime.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);\n}\n\nconst passDuration = (_duration) => {\n var minutes = Math.floor(_duration / 60);\n var seconds = Math.round(_duration - minutes * 60);\n return `${(\"0\" + minutes).slice(-2)}:${(\"0\" + seconds).slice(-2)}`\n}\n\n\nconst TableRowFunc = (props) => {\n const rowdata = props.rowdata;\n const [open, setOpen] = useState(false);\n const [csvData, setcsvData] = useState('');\n const csvLink = useRef();\n const disableStyle = { color: 'dimgray' };\n const AOSEpoch = new Date(0);\n const LOSEpoch = new Date(0);\n\n const countDownRenderer = ({ hours, minutes, seconds, completed }) => {\n return `${completed ? (\"+\") : (\"-\")}${(\"0\" + hours).slice(-2)}:${(\"0\" + minutes).slice(-2)}:${(\"0\" + seconds).slice(-2)}`;\n };\n const csvHeaders = ['Unix time (s)', 'Elevation (deg)', 'Azimuth (deg)']\n const handleCSVDownload = async () => {\n await fetch('/api/get_path_csv', {\n method: \"POST\",\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(rowdata.start)\n })\n .then(response => response.json())\n .then(data => setcsvData(data))\n csvLink.current.link.click()\n }\n return (\n <React.Fragment>\n <TableRow style={!rowdata.take\n ? { background: '#333333' }\n : null}>\n <TableCell align=\"left\" style={rowdata.take ? null : disableStyle}>\n <IconButton aria-label=\"expand row\" size=\"small\" onClick={() => setOpen(!open)}>\n {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}\n </IconButton>\n </TableCell>\n <TableCell component=\"th\" scope=\"row\" align=\"left\" style={rowdata.take ? null : disableStyle}>\n {rowdata.satName}\n </TableCell>\n <TableCell align=\"left\" style={rowdata.take ? null : disableStyle}>{rowdata.orbitnum}</TableCell>\n <TableCell align=\"center\" style={rowdata.take ? null : disableStyle}>{AOSLOSTime(rowdata.start)}</TableCell>\n <TableCell align=\"center\" style={rowdata.take ? null : disableStyle}>{AOSLOSTime(rowdata.end)}</TableCell>\n <TableCell align=\"right\" style={rowdata.take ? null : disableStyle}>{passDuration(rowdata.duration)}</TableCell>\n </TableRow>\n {props.nearestAOS / 1000 === rowdata.start && props.passState === true\n ? (<TableRow>\n <TableCell colSpan={6}>\n <LinearProgress variant=\"determinate\" value={props.passProgress} />\n </TableCell>\n </TableRow>)\n : null}\n <TableRow style={rowdata.take ? null : { background: '#333333' }}>\n <TableCell style={{ padding: 0 }} colSpan={6}>\n <Collapse in={open} timeout=\"auto\" unmountOnExit>\n <Table>\n <TableBody>\n <TableRow >\n <TableCell align=\"center\" colSpan={3} width=\"45%\">\n <Link\n style={{ color: '#abdbe3' }}\n onClick={handleCSVDownload}>\n Download path csv\n </Link>\n <CSVLink\n data={csvData}\n filename={`${rowdata.satName}-${rowdata.orbitnum}.csv`}\n className='hidden'\n ref={csvLink}\n target='_blank'\n headers={csvHeaders}\n />\n </TableCell>\n <TableCell align=\"center\" style={rowdata.take ? null : disableStyle}>\n {props.settings.predictionType === \"custom\"\n ? (<Countdown\n date={AOSEpoch.setUTCSeconds(rowdata.start)}\n overtime={true}\n autoStart={false}\n daysInHours={true}\n now={() => Date.parse(props.settings.customStartTime)}\n renderer={countDownRenderer} />)\n : (<Countdown\n date={AOSEpoch.setUTCSeconds(rowdata.start)}\n overtime={true}\n daysInHours={true}\n renderer={countDownRenderer} />)}\n </TableCell>\n <TableCell align=\"center\" style={rowdata.take ? null : disableStyle}>\n {props.settings.predictionType === \"custom\"\n ? (<Countdown\n date={AOSEpoch.setUTCSeconds(rowdata.start)}\n overtime={true}\n autoStart={false}\n daysInHours={true}\n now={() => Date.parse(props.settings.customStartTime)}\n renderer={countDownRenderer} />)\n : (<Countdown\n date={LOSEpoch.setUTCSeconds(rowdata.end)}\n overtime={true}\n daysInHours={true}\n renderer={countDownRenderer}\n onComplete={props.passFinished} />)}\n </TableCell>\n <TableCell colSpan={3} width=\"17%\"></TableCell>\n </TableRow>\n <TableRow>\n <TableCell align=\"center\" colSpan={6}\n >\n <div style={{\n position: 'relative',\n height: '120px',\n width: '100%',\n paddingBottom: '10%',\n marginTop: '-2%',\n marginBottom: '-2%'\n }}>\n <div style={{\n position: 'absolute',\n inset: '0%',\n width: '100%'\n }}>\n <OrbitMap aostime={rowdata.start} />\n </div>\n </div>\n </TableCell>\n </TableRow>\n </TableBody>\n </Table>\n </Collapse>\n </TableCell>\n </TableRow>\n\n </React.Fragment>\n )\n}\n\nexport default function PassTimeTable(props) {\n const [order, setOrder] = useState('asc');\n const [orderBy, setOrderBy] = useState('start');\n const [passState, setPassState] = useState(false);\n const [passProgress, setPassProgress] = useState(0);\n const handleRequestSort = (event, property) => {\n const isAsc = orderBy === property && order === 'asc';\n setOrder(isAsc ? 'desc' : 'asc');\n setOrderBy(property);\n };\n\n const passFinished = useCallback(() => {\n setTimeout(() => {\n fetch('/api/passData').then(res => res.json()).then(data => {\n props.setPassData(data);\n }).catch(() => alert('Error fetching data from flask server.'));\n }, 30000)\n }, [props])\n const classes = useStyles();\n const [nearestLOS, setNearestLOS] = useState(0);\n const [nearestAOS, setNearestAOS] = useState(0);\n useEffect(() => {\n let progressInterval\n let AOStimer\n let LOStimer\n if (props.passData !== false && props.settings.predictionType !== \"custom\") {\n for (var i = 0; i < props.passData.length; i++) {\n if (props.passData[i].take === true) {\n setNearestAOS(props.passData[i].start * 1000)\n setNearestLOS(props.passData[i].end * 1000)\n break\n }\n }\n AOStimer = setTimeout(() => {\n setPassState(true)\n progressInterval = setInterval(() => {\n setPassProgress((Date.now() - nearestAOS) / (nearestLOS - nearestAOS) * 100)\n }, 1000);\n }, nearestAOS - Date.now());\n LOStimer = setTimeout(() => {\n setPassState(false)\n passFinished()\n }, nearestLOS - Date.now());\n return () => {\n clearTimeout(AOStimer)\n clearTimeout(LOStimer)\n clearInterval(progressInterval)\n }\n }\n }, [props, nearestLOS, nearestAOS, passFinished])\n\n return (\n <header className=\"App-header\">\n <Grid\n container\n direction=\"row\"\n justify=\"center\"\n style={{\n margin: 0,\n width: '100%',\n }}\n >\n <Grid item md={7} sm={12} className={classes.grid}>\n {props.passData === false ? (<div>Waiting for passData from FlaskAPI...</div>) : (\n <TableContainer component={Paper}>\n <Table aria-label=\"simple table\">\n <TableHead>\n <TableRow>\n <TableCell colSpan={6} align=\"center\" style={{ fontSize: \"180%\" }}>\n {props.settings.predictionType === \"custom\"\n ? (<Clock format=\"YYYY-DDD-HH:mm:ss\" ticking={false} date={props.settings.customStartTime} />)\n : (<Clock format=\"YYYY-DDD-HH:mm:ss\" ticking={true} />)\n }\n </TableCell>\n </TableRow>\n <TableRow >\n <TableCell />\n {headCells.map((headCell) => (\n <TableCell\n key={headCell.id}\n align={headCell.alignDirection}\n sortDirection={orderBy === headCell.id ? order : false}\n >\n <TableSortLabel\n active={orderBy === headCell.id}\n direction={orderBy === headCell.id ? order : 'asc'}\n onClick={(event) => handleRequestSort(event, headCell.id)}\n >\n {headCell.label}\n </TableSortLabel>\n </TableCell>\n ))}\n </TableRow>\n </TableHead>\n <TableBody>\n {stableSort(Object.values(props.passData), getComparator(order, orderBy))\n .map((rowdata, index) => (\n <TableRowFunc\n rowdata={rowdata}\n key={rowdata.start}\n passFinished={passFinished}\n settings={props.settings}\n passState={passState}\n nearestAOS={nearestAOS}\n passProgress={passProgress} />\n ))}\n </TableBody>\n </Table>\n </TableContainer>\n )\n }\n </Grid>\n </Grid>\n </header>\n );\n}\n" }, { "alpha_fraction": 0.7580071091651917, "alphanum_fraction": 0.7580071091651917, "avg_line_length": 38.42856979370117, "blob_id": "5e7a4636e9f2394b1c75ce8a94610d7a037ecdfa", "content_id": "f1f5229f9dff26955a5c5d91c62488b6e471b9b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "no_license", "max_line_length": 67, "num_lines": 7, "path": "/configfile.py", "repo_name": "alexchang0229/passboard", "src_encoding": "UTF-8", "text": "import os\r\n\r\nGOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID')\r\nGOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET')\r\nSQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI')\r\nSECRET_KEY = os.environ.get('SECRET_KEY')\r\nSQLALCHEMY_TRACK_MODIFICATIONS = False" }, { "alpha_fraction": 0.38053739070892334, "alphanum_fraction": 0.4001452326774597, "avg_line_length": 35.216217041015625, "blob_id": "7356f0d61a533eb6c6320c9eb682e80e8a908a71", "content_id": "b66f53d06875b13ce6020541c4522d53d23f6862", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2754, "license_type": "no_license", "max_line_length": 107, "num_lines": 74, "path": "/frontend/src/functions/OrbitMap.js", "repo_name": "alexchang0229/passboard", "src_encoding": "UTF-8", "text": "import React, { useState, useEffect } from 'react'\r\nimport {\r\n ComposableMap,\r\n Geographies,\r\n Geography,\r\n Marker,\r\n Line,\r\n Graticule\r\n} from \"react-simple-maps\";\r\nimport mapJson from \"../assets/geos.json\"\r\n\r\nconst geoUrl = mapJson\r\n//\"https://raw.githubusercontent.com/zcreativelabs/react-simple-maps/master/topojson-maps/world-110m.json\";\r\n\r\nexport default function OrbitMap(props) {\r\n const [mapCoords, setMapCoords] = useState(false)\r\n useEffect(() => {\r\n fetch('/api/mapviewInfo', {\r\n method: \"POST\",\r\n headers: {\r\n 'Accept': 'application/json',\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify(props.aostime)\r\n })\r\n .then(response => response.json())\r\n .then(data => setMapCoords(data))\r\n }, [props.aostime])\r\n return (\r\n <React.Fragment>\r\n {mapCoords === false\r\n ? (<div>loading</div>)\r\n : (<ComposableMap\r\n projection=\"geoEqualEarth\"\r\n projectionConfig={{\r\n scale: 150,\r\n center: [0, 0]//mapCoords[2]\r\n }}\r\n width={800} height={400} style={{ width: \"100%\", height: \"100%\" }}>\r\n <Graticule stroke=\"#969696\" />\r\n <Geographies geography={geoUrl}>\r\n {({ geographies }) =>\r\n geographies.map(geo => (\r\n <Geography key={geo.rsmKey} geography={geo} />\r\n ))\r\n }\r\n </Geographies>\r\n <Marker coordinates={mapCoords[2]}>\r\n <circle r={4} fill=\"#F53\" />\r\n </Marker>\r\n <Marker coordinates={mapCoords[0]}>\r\n <circle r={4} fill=\"#F53\" />\r\n <text textAnchor=\"middle\" x=\"-20\" fill=\"#F53\">\r\n AOS\r\n </text>\r\n </Marker>\r\n <Marker coordinates={mapCoords[1]}>\r\n <circle r={4} fill=\"#F53\" />\r\n <text textAnchor=\"middle\" x=\"-20\" fill=\"#F53\">\r\n LOS\r\n </text>\r\n </Marker>\r\n <Line\r\n from={mapCoords[0]}\r\n to={mapCoords[1]}\r\n stroke=\"#FF5533\"\r\n strokeWidth={4}\r\n strokeLinecap=\"round\"\r\n />\r\n </ComposableMap>)\r\n }\r\n </React.Fragment >\r\n )\r\n}\r\n" }, { "alpha_fraction": 0.5907753109931946, "alphanum_fraction": 0.5996033549308777, "avg_line_length": 34.36651611328125, "blob_id": "81f80cd7cadc2409cc332ddbb8576dfbe9f03557", "content_id": "e97c372a68167fb5e01d4e366768d637221bab97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15632, "license_type": "no_license", "max_line_length": 94, "num_lines": 442, "path": "/FlaskAPI.py", "repo_name": "alexchang0229/passboard", "src_encoding": "UTF-8", "text": "from skyfield.api import load, wgs84, utc\nfrom datetime import date, datetime, timedelta\nfrom flask import Flask, request, session, render_template, send_from_directory, make_response\nfrom flask import url_for, redirect, jsonify\nfrom flask_cors import CORS\nfrom authlib.integrations.flask_client import OAuth\nimport json\nimport numpy as np\nimport pytz\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__, static_folder='frontend/build', static_url_path='')\nCORS(app)\napp.config.from_object('configfile')\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n id = db.Column(db.String(255), primary_key=True)\n userSettings = db.Column(db.PickleType, nullable=False)\n\n def __repr__(self):\n return '<%r>' % self.id\n\n\nCONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'\noauth = OAuth(app)\noauth.register(name='google',\n server_metadata_url=CONF_URL,\n client_kwargs={'scope': 'openid email profile'})\n\n\ndef make_sat_from_id(idList):\n satellites = []\n makeSatError = False\n for SatID in idList:\n try:\n url = 'https://celestrak.com/satcat/tle.php?CATNR={}'.format(SatID)\n filename = './TLEs/tle-{}.txt'.format(SatID)\n satellite = load.tle_file(url, filename=filename)\n days = load.timescale().now() - satellite[0].epoch\n if abs(days) > 5: # if TLEs > 2 days old, get new ones\n satellite = load.tle_file(url, filename=filename, reload=True)\n satellites.append(satellite)\n except Exception as e:\n makeSatError = SatID\n print(e)\n return satellites, makeSatError\n\n\ndef calc_path(passesSorted, passIndex):\n if session.get('useSessionSettings') == True:\n settings = session['settings']\n else:\n settings = get_settings_from_file()\n stationLong = float(settings['stationLong'])\n stationLat = float(settings['stationLat'])\n stationLocation = wgs84.latlon(stationLat, stationLong)\n selected_pass = passesSorted[passIndex]\n satellite, _ = make_sat_from_id([selected_pass['NORADid']])\n passTimeArray = np.arange(selected_pass['start'], selected_pass['end'], 1)\n difference = satellite[0][0] - stationLocation\n ELAZ = []\n ts = load.timescale()\n for t in passTimeArray:\n timeStep = datetime.utcfromtimestamp(t).replace(tzinfo=pytz.utc)\n _el, _az, _ = difference.at(ts.from_datetime(timeStep)).altaz()\n _eldeg = _el.degrees\n ELAZ.append([t, _eldeg, _az.degrees])\n return ELAZ\n\n\ndef calc_map_coords(passesSorted, passIndex):\n if session.get('useSessionSettings') == True:\n settings = session['settings']\n else:\n settings = get_settings_from_file()\n stationCoord = [\n float(settings['stationLong']),\n float(settings['stationLat'])\n ]\n selected_pass = passesSorted[passIndex]\n satellite, _ = make_sat_from_id([selected_pass['NORADid']])\n ts = load.timescale()\n AOStime = ts.from_datetime(\n datetime.utcfromtimestamp(\n selected_pass['start']).replace(tzinfo=pytz.timezone('UTC')))\n LOStime = ts.from_datetime(\n datetime.utcfromtimestamp(\n selected_pass['end']).replace(tzinfo=pytz.timezone('UTC')))\n AOSpos = wgs84.subpoint(satellite[0][0].at(AOStime))\n LOSpos = wgs84.subpoint(satellite[0][0].at(LOStime))\n AOScoord = [\n round(AOSpos.longitude.degrees, 2),\n round(AOSpos.latitude.degrees, 2)\n ]\n LOScoord = [\n round(LOSpos.longitude.degrees, 2),\n round(LOSpos.latitude.degrees, 2)\n ]\n return AOScoord, LOScoord, stationCoord\n\n\n# This function loads and returns the settings for list of satellites to track,\n# station location ...\ndef get_settings_from_file():\n if session.get('user') != None:\n userdata = User.query.filter_by(\n id=session.get('user')['email']).first()\n settings = userdata.userSettings\n else:\n # Default settings if custom settings file doesn't exist\n stationLong = -73.43\n stationLat = +45.51\n predHours = 24.0\n predictionType = 'realtime'\n customStartTime = datetime.strftime(datetime.now(),\n \"%Y-%m-%dT%H:%M:%S.%fZ\")\n minAltitudeDegrees = 5.0\n idList = [25338, 28654, 33591, 38771, 43689, 37214, 25544]\n satellites, _ = make_sat_from_id(idList)\n satList = {}\n for i in range(idList.__len__()):\n satList[i] = {\n 'name': satellites[i][0].name,\n 'NORADid': idList[i],\n 'priority': i\n }\n\n settings = {\n 'satList': satList,\n 'stationLong': stationLong,\n 'stationLat': stationLat,\n 'predHours': predHours,\n 'minElevation': minAltitudeDegrees,\n 'predictionType': predictionType,\n 'customStartTime': customStartTime\n }\n\n return (settings)\n\n\n# This function predicts the upcoming passes for the list of satellites in the\n# specified time period\ndef predict(settings):\n\n satList = settings['satList']\n stationLong = float(settings['stationLong'])\n stationLat = float(settings['stationLat'])\n predHours = float(settings['predHours'])\n minAltitudeDegrees = float(settings['minElevation'])\n stationLocation = wgs84.latlon(stationLat, stationLong)\n predictionType = settings['predictionType']\n customStartTime = datetime.strptime(settings['customStartTime'],\n \"%Y-%m-%dT%H:%M:%S.%fZ\")\n # Get TLEs from celestrak and save in file\n idList = [satList[ind]['NORADid'] for ind in satList]\n satellites, _ = make_sat_from_id(idList)\n\n # Timescale range for predicting satellite passes\n ts = load.timescale()\n if predictionType == 'realtime':\n t0 = ts.utc(ts.now().utc_datetime() -\n timedelta(seconds=30)) # Time range starts 30s before now\n else:\n t0 = ts.utc(customStartTime.replace(tzinfo=pytz.utc))\n t1 = ts.utc(t0.utc_datetime() + timedelta(hours=predHours))\n passes = {}\n\n # This for loop goes through each satellite and finds passes over the\n # station, passe information for all satellites are stored in the 'passes' array\n passIndex = 0\n\n for i, satloop in enumerate(satList):\n t_temp, events_temp = satellites[i][0].find_events(\n stationLocation, t0, t1, altitude_degrees=minAltitudeDegrees)\n # find event returns [0: AOS, 1: PEAK, 2: LOS, 0: AOS ... ]\n t_AOSLOS = np.delete(t_temp, np.where(events_temp == 1))\n\n # If we call find_events() during a pass, it's going to return an array\n # starting with event 1 or 2 (PEAK/LOS) instead of 0 (AOS). To find the\n # AOS time in the past, this if statement goes back one day and finds the\n # closest AOS time to the current time and puts that as the first element\n # of the t_AOSLOS array\n if events_temp[0] != 0:\n t_temp1, events_temp1 = satellites[i][0].find_events(\n stationLocation,\n ts.utc(t0.utc_datetime() - timedelta(hours=24)),\n t0,\n altitude_degrees=minAltitudeDegrees)\n aosArray = np.delete(\n t_temp1,\n np.append(np.where(events_temp1 == 1),\n np.where(events_temp1 == 2)))\n passAOS = min(aosArray, key=lambda x: abs(x - t0))\n t_AOSLOS = [passAOS] + t_AOSLOS.tolist()\n\n t_AOS = t_AOSLOS[0:][::2]\n t_LOS = t_AOSLOS[1:][::2]\n orbitatEpoch = satellites[i][0].model.revnum\n angVel = satellites[i][0].model.no_kozai\n for j, _ in enumerate(t_LOS):\n minSinceEpoch = (\n datetime.timestamp(t_AOS[j].utc_datetime()) -\n datetime.timestamp(satellites[i][0].epoch.utc_datetime())) / 60\n orbitsSinceEpoch = np.floor(minSinceEpoch * angVel / (2 * np.pi))\n orbitnum = orbitatEpoch + orbitsSinceEpoch\n\n passes[passIndex] = {\n 'start':\n datetime.timestamp(t_AOS[j].utc_datetime()),\n 'end':\n datetime.timestamp(t_LOS[j].utc_datetime()),\n 'duration': (t_LOS[j].utc_datetime() -\n t_AOS[j].utc_datetime()).total_seconds(),\n 'satName':\n satellites[i][0].name,\n 'NORADid':\n satList[satloop]['NORADid'],\n 'priority':\n satList[satloop]['priority'],\n 'satIND':\n i,\n 'orbitnum':\n orbitnum,\n 'take':\n True\n }\n passIndex = passIndex + 1\n\n minSecBetweenPass = 0\n # Sort passes by AOS time\n passSortKeys = sorted(passes, key=lambda x: passes.get(x).get('start'))\n passesSorted = []\n for i in passSortKeys:\n passesSorted.append(passes[i])\n # Handles conflicts based on priority\n for i in range(0, len(passesSorted)):\n if passesSorted[i]['take'] == True:\n for j in range(i + 1, len(passesSorted)):\n if passesSorted[i]['end'] + minSecBetweenPass > passesSorted[\n j]['start']:\n if passesSorted[i]['priority'] < passesSorted[j][\n 'priority']:\n passesSorted[i]['take'] = True\n passesSorted[j]['take'] = False\n else:\n passesSorted[i]['take'] = False\n passesSorted[j]['take'] = True\n break\n else:\n passesSorted[i]['take'] = True\n break\n\n return passesSorted\n\n\[email protected]('/api/mapviewInfo', methods=['POST'])\ndef map_coord_to_react():\n passAOS = request.json\n passsorted = np.array(session['passesSorted'])\n aosList = [aos['start'] for aos in passsorted]\n passIndex = aosList.index(passAOS)\n aosCoord, losCoord, stationCoord = calc_map_coords(passsorted, passIndex)\n mapinfo = [aosCoord, losCoord, stationCoord]\n return jsonify(mapinfo)\n\n\[email protected]('/api/passData')\ndef passData_to_react():\n if session.get('useSessionSettings') == True:\n settings = session['settings']\n else:\n settings = get_settings_from_file()\n passesSorted = predict(settings)\n session['passesSorted'] = passesSorted\n return json.dumps(passesSorted)\n\n\[email protected]('/api/settings', methods=['GET'])\ndef pass_settings_to_react():\n if session.get('useSessionSettings') == True:\n settings = session['settings']\n else:\n settings = get_settings_from_file()\n return settings\n\n\[email protected]('/api/changeSettings', methods=['POST'])\ndef get_settings_from_react():\n session['useSessionSettings'] = False\n data = request.json\n idList = [data['satList'][sats]['NORADid'] for sats in data['satList']]\n stationLong = data['stationLong']\n stationLat = data['stationLat']\n predHours = data['predHours']\n minAltitudeDegrees = data['minElevation']\n customStartTime = data['customStartTime']\n predictionType = data['predictionType']\n satellites, makeSatError = make_sat_from_id(idList)\n\n if makeSatError is False:\n satList = {}\n for i in range(satellites.__len__()):\n satList[i] = {\n 'name': satellites[i][0].name,\n 'NORADid': idList[i],\n 'priority': i\n }\n settings = {\n 'satList': satList,\n 'stationLong': stationLong,\n 'stationLat': stationLat,\n 'predHours': predHours,\n 'minElevation': minAltitudeDegrees,\n 'customStartTime': customStartTime,\n 'predictionType': predictionType\n }\n userEmail = session.get('user')['email']\n userData = User.query.filter_by(id=userEmail).first()\n if userData == None:\n newSettings = User(id=userEmail, userSettings=settings)\n db.session.add(newSettings)\n else:\n userData.userSettings = settings\n db.session.commit()\n\n return jsonify('Settings saved!')\n else:\n errorString = 'NORAD ID: {ErrorID} caused an error, settings not saved.'\n return jsonify(errorString.format(ErrorID=makeSatError))\n\n\[email protected]('/api/get_path_csv', methods=['POST'])\ndef path_CSV_to_react():\n passAOS = request.json\n passesSorted = np.array(session['passesSorted'])\n aosList = [aos['start'] for aos in passesSorted]\n passIndex = aosList.index(passAOS)\n path = calc_path(session['passesSorted'], passIndex)\n return jsonify(path)\n\n\[email protected]('/api/next_pass_path', methods=['POST'])\ndef next_pass_path():\n userEmail = request.get_json()['Email address']\n try:\n userdata = User.query.filter_by(id=userEmail).first()\n settings = userdata.userSettings\n except:\n return \"Email not found in database\", 400\n passesSorted = predict(settings)\n for passes in passesSorted:\n if passes['take'] == True and passes['start'] > datetime.now(\n ).timestamp():\n nextPass = passes\n break\n aosList = [aos['start'] for aos in passesSorted]\n passIndex = aosList.index(nextPass['start'])\n path = calc_path(passesSorted, passIndex)\n return jsonify(path)\n\n\[email protected]('/api/save_to_session', methods=['POST'])\ndef save_settings_to_session():\n data = request.json\n idList = [data['satList'][sats]['NORADid'] for sats in data['satList']]\n stationLong = data['stationLong']\n stationLat = data['stationLat']\n predHours = data['predHours']\n minAltitudeDegrees = data['minElevation']\n customStartTime = data['customStartTime']\n predictionType = data['predictionType']\n satellites, makeSatError = make_sat_from_id(idList)\n\n if makeSatError is False:\n satList = {}\n for i in range(satellites.__len__()):\n satList[i] = {\n 'name': satellites[i][0].name,\n 'NORADid': idList[i],\n 'priority': i\n }\n settings = {\n 'satList': satList,\n 'stationLong': stationLong,\n 'stationLat': stationLat,\n 'predHours': predHours,\n 'minElevation': minAltitudeDegrees,\n 'customStartTime': customStartTime,\n 'predictionType': predictionType\n }\n else:\n errorString = 'NORAD ID: {ErrorID} caused an error, settings not saved.'\n return jsonify(errorString.format(ErrorID=makeSatError))\n\n session['settings'] = settings\n session['useSessionSettings'] = True\n\n return jsonify('Settings saved!')\n\n\[email protected]('/api/popSession')\ndef popSession():\n session['settings'] = False\n session['useSessionSettings'] = False\n return jsonify('Session poped!')\n\n\[email protected]('/api/session')\ndef apiSession():\n sessionUser = session.get('user')\n return jsonify(sessionUser)\n\n\[email protected]('/api/login')\ndef login():\n redirect_uri = url_for('auth', _external=True)\n return oauth.google.authorize_redirect(redirect_uri)\n\n\[email protected]('/auth')\ndef auth():\n token = oauth.google.authorize_access_token()\n user = oauth.google.parse_id_token(token)\n session['user'] = user\n return redirect('/SettingsPage')\n\n\[email protected]('/api/logout')\ndef logout():\n session.pop('user', None)\n return redirect('/SettingsPage')\n\n\[email protected](404)\ndef catch_all(path):\n return send_from_directory(app.static_folder, 'index.html')\n\n\nif __name__ == '__main__':\n app.run(host='localhost', port=5000)\n" }, { "alpha_fraction": 0.3898274600505829, "alphanum_fraction": 0.39396119117736816, "avg_line_length": 43.158729553222656, "blob_id": "1e52628f2f57a0d22e3150e53494e6b7d6d38a35", "content_id": "b5d6975296324009b74f588465b080f9d84dc718", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5564, "license_type": "no_license", "max_line_length": 116, "num_lines": 126, "path": "/frontend/src/functions/table.js", "repo_name": "alexchang0229/passboard", "src_encoding": "UTF-8", "text": "import React, { useEffect, useState } from \"react\";\nimport { DragDropContext, Droppable, Draggable } from \"react-beautiful-dnd\";\nimport TextField from '@material-ui/core/TextField';\nimport Card from '@material-ui/core/Card'\nimport { Box } from '@material-ui/core';\nimport Tooltip from '@material-ui/core/Tooltip';\nimport DeleteIcon from '@material-ui/icons/Delete';\nimport IconButton from '@material-ui/core/IconButton';\n// a little function to help us with reordering the result\nconst reorder = (list, startIndex, endIndex) => {\n const result = Array.from(list);\n const [removed] = result.splice(startIndex, 1);\n result.splice(endIndex, 0, removed);\n result.forEach((data, index) => data.priority = index)\n return result;\n};\n\nconst grid = 6;\n\nconst getItemStyle = (isDragging, draggableStyle) => ({\n // some basic styles to make the items look a bit nicer\n userSelect: \"none\",\n padding: 3,\n margin: `0 0 ${grid}px 0`,\n // change background colour if dragging\n background: isDragging ? \"gray \" : \"#525252\",\n // styles we need to apply on draggables\n ...draggableStyle\n});\n\nconst getListStyle = isDraggingOver => ({\n //background: isDraggingOver ? \"lightblue\" : \"lightgrey\",\n padding: grid,\n width: 250\n});\n\nexport default function Table(props) {\n const [list, setlist] = useState(Object.values(props.settingIn.satList));\n\n useEffect(() => {\n setlist(Object.values(props.settingIn.satList))\n }, [props.settingIn])\n\n function onDragEnd(result) {\n // dropped outside the list\n if (!result.destination) {\n return;\n }\n const newlist = reorder(\n list,\n result.source.index,\n result.destination.index\n );\n newlist.forEach((data, ind) => props.setSettings(\n (prevSetting) => ({\n ...prevSetting, satList: {\n ...prevSetting.satList, [ind]: data\n }\n })\n ));\n setlist(newlist);\n }\n return (\n <DragDropContext onDragEnd={onDragEnd}>\n <Droppable droppableId=\"droppable\">\n {(provided, snapshot1) => (\n <div\n {...provided.droppableProps}\n ref={provided.innerRef}\n style={getListStyle(snapshot1.isDraggingOver)}\n >\n {Object.values(list).map((satellite, index) => (\n <Draggable key={satellite.name} draggableId={satellite.name} index={index}>\n {(provided, snapshot) => (\n <Card\n ref={provided.innerRef}\n {...provided.draggableProps}\n {...provided.dragHandleProps}\n style={getItemStyle(\n snapshot.isDragging,\n provided.draggableProps.style,\n )}\n >\n <Box m={1}>\n <b style={{ textAlign: 'left' }}>\n {satellite.name}\n </b>\n <Tooltip title=\"Priority\">\n <span style={{ float: 'left', fontSize: 12 }}>\n {satellite.priority}\n </span>\n </Tooltip>\n <span style={{ float: 'right' }}>\n <IconButton size='small' onClick={(e) => props.deleteSat(e, index)}>\n <DeleteIcon fontSize='small' />\n </IconButton>\n </span>\n </Box>\n <TextField\n id={\"NORAD-tracking-number\" + index}\n label=\"NORAD tracking number\"\n value={list[index]['NORADid']}\n type=\"number\"\n InputLabelProps={{ shrink: true }}\n onInput={(e) => {\n e.target.value = e.target.value.toString().slice(0, 5)\n }}\n onChange={(e) => {\n var newlist = list\n newlist[index]['NORADid'] = e.target.value\n return setlist([...newlist])\n }}\n variant=\"outlined\"\n />\n </Card>\n )}\n </Draggable>\n ))}\n {provided.placeholder}\n </div>\n )}\n </Droppable>\n </DragDropContext >\n );\n\n}\n" }, { "alpha_fraction": 0.5309168696403503, "alphanum_fraction": 0.5343283414840698, "avg_line_length": 29.454545974731445, "blob_id": "5cec0902a9596897e20ce63df48e68dffcf82753", "content_id": "a6db6c48315c3f00c99ab6b60a1c35e69dc4b37d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2345, "license_type": "no_license", "max_line_length": 80, "num_lines": 77, "path": "/frontend/src/App.js", "repo_name": "alexchang0229/passboard", "src_encoding": "UTF-8", "text": "import React, { useState, useEffect } from 'react';\nimport './App.css';\nimport PassTimeTable from './pages/PassTimeTable.js';\nimport SettingsPage from './pages/SettingsPage.js';\nimport AboutPage from './pages/AboutPage.js';\nimport { BrowserRouter as Router, Switch, Route, Link } from \"react-router-dom\";\nimport { createMuiTheme } from \"@material-ui/core/styles\";\nimport { ThemeProvider } from \"@material-ui/styles\";\n\n\nconst theme = createMuiTheme({\n palette: {\n type: \"dark\"\n }\n});\n\nfunction App() {\n const [passData, setPassData] = useState(false);\n const [userSession, setuserSession] = useState(null);\n const [refetchData, setrefetchData] = useState(false);\n const [settings, setSettings] = useState(false);\n useEffect(() => {\n fetch('/api/passData').then(res => res.json()).then(data => {\n setPassData(data);\n }).catch(() => alert('Error fetching data from flask server.'));\n }, [refetchData]);\n useEffect(() => {\n fetch('/api/session').then(res => res.json()).then(data => {\n setuserSession(data);\n }).catch((e) => console.log(e));\n }, []);\n useEffect(() => {\n fetch('/api/settings').then(res => res.json()).then(data => {\n setSettings(data);\n });\n }, [refetchData]);\n\n return (\n <div style={{ minHeight: \"100vh\", backgroundColor: \"#282c34\" }}>\n <Router>\n <ThemeProvider theme={theme}>\n <div className=\"App\">\n &emsp;\n <Link to='/SettingsPage'>\n Settings\n </Link>&emsp;\n <Link to=\"\" style={{ textAlign: \"left\" }}>\n Pass Board\n </Link>&emsp;\n <Link to=\"/About\">\n About\n </Link>\n <Switch>\n <Route path=\"/SettingsPage\">\n <SettingsPage\n userSession={userSession}\n setrefetchData={setrefetchData}\n refetchData={refetchData} />\n </Route>\n <Route path=\"/About\">\n <AboutPage />\n </Route>\n <Route path=\"/\">\n <PassTimeTable\n passData={passData}\n setPassData={setPassData}\n settings={settings} />\n </Route>\n </Switch>\n </div>\n </ThemeProvider>\n </Router>\n </div>\n );\n}\n\nexport default App;\n" } ]
7
zhakguder/FoodProject
https://github.com/zhakguder/FoodProject
8b628583fb2f0ee3537f5340301b78c926401968
7ab881d9884d366efffa7a4c84c27c02fbe7a467
a087b6fbd9bc4f3ec1d7f48268e733e106369fcd
refs/heads/main
2023-03-05T18:30:16.939582
2021-02-14T19:50:04
2021-02-14T19:50:04
327,974,533
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5811659097671509, "alphanum_fraction": 0.5829596519470215, "avg_line_length": 23.77777862548828, "blob_id": "106db7d67f0a5e1ca43edafef21d6f51dd507aa6", "content_id": "e7d6469682d632c634cabf83c8cd5cfcc945602a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1115, "license_type": "no_license", "max_line_length": 87, "num_lines": 45, "path": "/food_project/image_classification/models.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport json\nimport os\n\nimport requests\n\n\nclass ImageClassificationModel:\n def _init__(self):\n self.uri = None\n self._ready = False\n\n @property\n def ready(self):\n return self._ready\n\n @ready.setter\n def ready(self, ready_or_not):\n self._ready = ready_or_not\n\n def get_ingredients(self, img_path, with_probs=False):\n with open(img_path, \"rb\") as img:\n img_name = os.path.basename(img_path)\n files = {\"image\": (img_name, img, \"multipart/form-data\", {\"Expires\": \"0\"})}\n with requests.Session() as s:\n r = s.post(self.uri, files=files)\n\n if with_probs:\n data = json.loads(r.text)\n return data\n return [x.strip() for x in r.text.split(\",\")]\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass ImageClassificationModelInitiator:\n def __init__(self, uri, port, route):\n self.uri = f\"{uri}:{port}/{route}\"\n\n def visit(self, element):\n element.uri = self.uri\n\n\nimage_classification_model = ImageClassificationModel()\n" }, { "alpha_fraction": 0.5627871155738831, "alphanum_fraction": 0.5635528564453125, "avg_line_length": 34.297298431396484, "blob_id": "7af675107ebeabbd9135d995f6de026647d9de15", "content_id": "351b77fd86691ecd48ffbb29ea605d284f91125f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 79, "num_lines": 37, "path": "/food_project/recipe/__init__.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\n\nimport pandas as pd\n\nfrom food_project.recipe.db_to_local import (get_processed_ingredients_from_db,\n get_recipe_from_db,\n get_recipe_ids_from_db)\nfrom food_project.recipe.flat_to_db import (populate_db_images,\n populate_db_processed,\n populate_db_recipes)\nfrom food_project.recipe.models import (RawRecipeGroup, RecipeDBInitiator,\n RecipeFilePathSetter,\n get_recipe_cluster_model,\n raw_recipe_model)\nfrom food_project.recipe.similarity.controller import (\n SimilarityController, SimilarityControllerVisitor)\n\n\ndef connect_to_database(uri, uname, pwd):\n rdi = RecipeDBInitiator(uri, uname, pwd)\n raw_recipe_model.accept(rdi)\n\n\ndef save_cluster_df(path):\n if not os.path.exists(path):\n rcm = get_recipe_cluster_model()\n rcm.export_cluster_df(path)\n else:\n print(\"File already exists!\")\n\n\ndef load_cluster_df(path):\n if not os.path.exists(path):\n raise Except(\"Cluster file doesn't exist!\")\n else:\n return pd.read_pickle(path)\n" }, { "alpha_fraction": 0.6013100147247314, "alphanum_fraction": 0.6187772750854492, "avg_line_length": 29.53333282470703, "blob_id": "78ca2f90be36f1864cc2a53215436252ae5ca3cc", "content_id": "10fe420493b4cedecd2f911ef89b964b1a30d794", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2290, "license_type": "no_license", "max_line_length": 79, "num_lines": 75, "path": "/ingredient_prediction_server.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n#!/usr/bin/env python\nimport json\nimport pickle\nfrom functools import wraps\nfrom tempfile import NamedTemporaryFile\nfrom urllib import parse\n\nimport numpy as np\nimport tensorflow as tf\nfrom flask import Flask, Response, request\nfrom PIL import Image\n\nfrom food_project.image_classification import (calculate_clique_potentials,\n predict_image)\nfrom food_project.image_classification.crf.crf_model import CRF\n\napp = Flask(__name__)\n\n\nclass Classifier:\n def __init__(self):\n prefix = \"/FoodProject/data/image_classification/model/\"\n self.model = tf.keras.models.load_model(prefix + \"hyvee.best.hdf5\")\n with open(prefix + \"hyvee_label.dict\", \"rb\") as f:\n mapping = pickle.load(f)\n self.reverse_map = {v: k for k, v in mapping.items()}\n self.ready = True\n\n def get_ingredients(self, np_arr, with_probs):\n shp = np_arr.shape\n image = np_arr.reshape(1, *shp) / 255\n probs = tf.nn.softmax(self.model.predict(image)).numpy().reshape(-1)\n pred_probs = {}\n for i in range(probs.shape[0]):\n cls = self.reverse_map[i]\n cls = parse.unquote_plus(cls)\n pred_probs[cls] = probs[i]\n return pred_probs\n\n\ndef limit_content_length(max_length):\n def decorator(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n cl = request.content_length\n if cl is not None and cl > max_length:\n abort(413)\n return f(*args, **kwargs)\n\n return wrapper\n\n return decorator\n\n\n# TODO: return with location information!!!\[email protected](\"/predict-label/\", methods=[\"POST\"])\n@limit_content_length(1000 * 1024 * 1024)\ndef predict():\n calculate_clique_potentials()\n image = request.files[\"image\"]\n image = np.array(Image.open(image), dtype=float)\n\n predictions = predict_image(image, image_classification_model=Classifier())\n crf = CRF(9, 5)\n for i in range(3):\n for j in range(3):\n crf.add_node(predictions[i][j])\n prbs, bst = crf.get_best_config(threshold=0.9)\n resp = json.dumps({\"prbs\": prbs, \"best\": bst})\n return Response(resp, status=200)\n\n\nif __name__ == \"__main__\":\n app.run(debug=False, host=\"0.0.0.0\", port=\"8888\")\n" }, { "alpha_fraction": 0.6731107234954834, "alphanum_fraction": 0.6748681664466858, "avg_line_length": 24.863636016845703, "blob_id": "0e6fcd30249975daa1c2b3b0e9046043e9e8191b", "content_id": "49efec49a9f0b0cb0b92a4eeaa02d4ac3daf274b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 569, "license_type": "no_license", "max_line_length": 67, "num_lines": 22, "path": "/main_clusterdf.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\n\nfrom dotenv import load_dotenv\n\nfrom food_project.recipe import (connect_to_database,\n get_processed_ingredients_from_db,\n save_cluster_df)\nfrom food_project.recipe.similarity import entropy_update\n\nload_dotenv()\nuri = os.getenv(\"MONGODB_URI\")\nuname = os.getenv(\"MONGODB_USERNAME\")\npwd = os.getenv(\"MONGODB_PWD\")\n\nconnect_to_database(uri, uname, pwd)\n\nres = get_processed_ingredients_from_db()\nentropy_update(res)\n\nsave_cluster_df(\"data/recipes/cluster_ingredients.df\")\n" }, { "alpha_fraction": 0.7148093581199646, "alphanum_fraction": 0.7155424952507019, "avg_line_length": 28.65217399597168, "blob_id": "f01525fb4c07c5632649dab4a85237b5d99abe6f", "content_id": "feb0281014d703885089459acb842f7431ad3f6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1364, "license_type": "no_license", "max_line_length": 170, "num_lines": 46, "path": "/food_project/recipe/similarity/__init__.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom food_project.recipe.similarity.entropy import (EntropyClusterVisitor,\n EntropyVisitor, __entropy)\n\n# from food_project.recipe.similarity.importance import ImportanceCalculator\n\n\ndef calculate_entropies(collection: list) -> dict:\n \"\"\"Calculates entropies for all the items in the collection. Entropy definition is taken from paper Complexity and Similarity of Recipes based on Entropy Measurement.\n Returns a dictionary of entries where each key is taken from collection.\n \"\"\"\n visitor = EntropyVisitor(collection)\n __entropy.accept(visitor)\n return __entropy.calculate()\n\n\ndef get_entropy_mask(df, n):\n \"\"\"Returns the n highest entropies in every recipe\"\"\"\n return __entropy.entropy_mask(df, n)\n\n\ndef get_item_entropy(item_name: str) -> float:\n return __entropy.get_item_entropy(item_name)\n\n\n# entropies = None\n\n\ndef entropy_update(collection):\n # global entropies\n entropies = calculate_entropies(collection)\n\n\ndef cluster_entropy_update(cluster_entropies):\n ecv = EntropyClusterVisitor(cluster_entropies)\n __entropy.accept(ecv)\n\n\ndef get_cluster_entropies():\n return __entropy.cluster_entropies\n\n\n# def calculate_importance(mask, mask_type='db_recipes'):\n# ic = ImportanceCalculator()\n# return ic.calculate_importances(mask, mask_type)\n" }, { "alpha_fraction": 0.7557603716850281, "alphanum_fraction": 0.7580645084381104, "avg_line_length": 32.38461685180664, "blob_id": "0c6edc3feb61c728cab6cf1a2ba6e9a6d197e014", "content_id": "43928d21e3ee87a8ae2b46dc190215111be830fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 434, "license_type": "no_license", "max_line_length": 63, "num_lines": 13, "path": "/food_project/recipe/cluster.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom food_project.util import read_json\n\nclusters = read_json(\"data/recipes/ingr_clusters.json\")\ncluster_ids = read_json(\"data/recipes/ingr_id_clusters.json\")\n\n# clusters has been consolidated for plural cluster names\n# base words are removed from cluster_ids\n# intersection of both is clean\n\ncluster_keys = clusters.keys() & cluster_ids.keys()\ningredient_clusters = {x: cluster_ids[x] for x in cluster_keys}\n" }, { "alpha_fraction": 0.5769230723381042, "alphanum_fraction": 0.5821678042411804, "avg_line_length": 26.238094329833984, "blob_id": "c76d26aebdf9e85ef2dff5355f23fc2283607743", "content_id": "6b7bf30bfa9257e787338014b0155bfa835a0b28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3432, "license_type": "no_license", "max_line_length": 81, "num_lines": 126, "path": "/food_project/image_classification/crf/test.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\n\nimport cv2\nimport numpy as np\n\n\nclass TestImageCompiler:\n def __init__(self, n):\n \"\"\"Args:\n n: number of grids in nxn placements of image\n \"\"\"\n self.n = n\n self.single_image_width = 28\n self.single_image_height = 28\n self.single_image_size = lambda: (\n self.single_image_width,\n self.single_image_height,\n )\n self.n_color = 3 # for RGB\n self.img_empty_grid = lambda height, width: np.zeros(\n (height * self.n, width * self.n, self.n_color), np.uint8\n )\n\n def compile_test_image(self, *image_paths):\n width, height = self.single_image_size()\n canvas = self.img_empty_grid(height, width).copy()\n\n n_images = len(image_paths)\n\n for i in range(self.n):\n for j in range(self.n):\n image_idx = i * self.n + j\n\n if image_idx < n_images:\n image_path = image_paths[image_idx]\n image = GridImage(image_path, *self.single_image_size())\n y = i * height\n x = j * width\n canvas[y : y + height, x : x + width, :] = image.image\n return canvas\n\n @staticmethod\n def write(path, canvas):\n cv2.imwrite(path, canvas)\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass GridImage:\n def __init__(self, path, width=28, height=28):\n self.path = path\n self._image = cv2.imread(path)\n self.size = (width, height)\n self._image = cv2.resize(self.image, self.size)\n\n @property\n def image(self):\n if self._image is None:\n raise Exception(\"Image not read yet\")\n return self._image\n\n def resize(self, size):\n if self.size == size:\n return self\n return GridImage(self.path, size)\n\n\nclass ImageSizeSetter:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n def visit(self, element):\n element.single_image_width = self.width\n element.single_image_height = self.height\n\n\ndef make_test_image(\n test_image_dir: str,\n n: int,\n image_ext: str = \".jpeg\",\n write: bool = False,\n size: int = 200,\n **kwargs\n) -> np.array:\n \"\"\"Creates a nxn image grid consisting of images in the folder. If folder\n contains more than nxn images randomly places nxn of the images in the\n grid.\n\n Individual images are resized to sizexsize before placing in the grid.\n\n Args:\n\n n: number of grids in nxn placements of images. k: number of\n images to use test_image_dir: relative folder from which to get test\n images from\n\n Kwargs:\n path: path to write the compiled image if write is True\n\n Returns:\n\n canvas: an nxn image grid\n\n \"\"\"\n\n path = kwargs[\"path\"] if \"path\" in kwargs else None\n\n tic = TestImageCompiler(n)\n _set_canvas_grid_size(tic, size)\n\n get_absolute = lambda x: os.path.join(test_image_dir, x)\n image_paths = os.listdir(test_image_dir)\n\n image_paths = [get_absolute(x) for x in image_paths if x.endswith(image_ext)]\n canvas = tic.compile_test_image(*image_paths)\n if write:\n tic.write(path, canvas)\n return canvas\n\n\ndef _set_canvas_grid_size(comp: TestImageCompiler, size: int) -> None:\n iss = ImageSizeSetter(size, size)\n iss.visit(comp)\n" }, { "alpha_fraction": 0.6151121854782104, "alphanum_fraction": 0.6210153698921204, "avg_line_length": 30.762500762939453, "blob_id": "6d28d3c222dbd43901981814346b08b9fb139913", "content_id": "8899437640d8af4fed219ebe6bc41f8cf39f5e1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2541, "license_type": "no_license", "max_line_length": 90, "num_lines": 80, "path": "/food_project/recipe/similarity/entropy.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "import math\n\nimport numpy as np\nimport pandas as pd\n\n\nclass Entropy:\n def __init__(self):\n self.collection = []\n self.freqs = {}\n self.ingredient_entropies = None\n self.cluster_entropies = None\n self.ranked_cluster_entropies = None\n self.ranked_ingredient_entropies = None\n\n def get_item_entropy(self, item_name: str) -> float:\n if not self.freqs:\n raise NameError(\"Frequencies not calculated.\")\n return abs(\n -math.log10(self.freqs.get(item_name, 1))\n ) # abs to fix log10(1) = -0\n\n def calculate(self):\n if not self.freqs:\n collection = pd.Series(self.collection)\n counts = collection.value_counts()\n freqs = counts / self.n_collection\n\n self.ingredient_entropies = -np.log10(freqs)\n self.freqs = freqs.to_dict()\n return self.freqs\n\n def _rank_ingredient_entropies(self):\n self.ranked_ingredient_entropies = self.ingredient_entropies.rank(\n method=\"max\", ascending=False\n )\n\n def _rank_cluster_entropies(self, df):\n df[df != 0] = 1\n df = df * self.cluster_entropies\n if self.cluster_entropies is not None:\n self.ranked_cluster_entropies = df.rank(axis=1, ascending=False)\n else:\n raise Exception(\"Cluster entropies are not calculated.\")\n\n def entropy_mask(self, df, n):\n \"\"\"Only keeps the ingredients with n highest entropies in each recipe\"\"\"\n # if self.ranked_ingredient_entropies is None:\n # self._rank_ingredient_entropies()\n if self.ranked_cluster_entropies is None:\n self._rank_cluster_entropies(df.copy())\n # res = self.ranked_cluster_entropies[self.ranked_cluster_entropies < n].fillna(0)\n # res[res != 0] = 1\n # return res\n return self.cluster_entropies\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass EntropyVisitor:\n def __init__(self, collection: list) -> None:\n self.n_collection = len(collection)\n collection = [item for sublist in collection for item in sublist]\n self.collection = collection\n\n def visit(self, element):\n element.collection = self.collection\n element.n_collection = self.n_collection\n\n\nclass EntropyClusterVisitor:\n def __init__(self, clusters_entropy_df):\n self.cluster_entropies = clusters_entropy_df\n\n def visit(self, element):\n element.cluster_entropies = self.cluster_entropies\n\n\n__entropy = Entropy()\n" }, { "alpha_fraction": 0.7167019248008728, "alphanum_fraction": 0.7177590131759644, "avg_line_length": 27.66666603088379, "blob_id": "1dfb76a9d266166ea53bd2365db96a265795c8da", "content_id": "541f5f2f55b65d84797a8d8d7bf3b5eb52c7d2a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 946, "license_type": "no_license", "max_line_length": 76, "num_lines": 33, "path": "/food_project/recipe/models/recipe_models.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom abc import ABC, abstractmethod\n\nfrom food_project.recipe.models.volume_models import (RecipeClusterModel,\n RecipeIngredientModel)\nfrom food_project.recipe.models.weight_models import (\n RecipeWeightClusterModel, RecipeWeightIngredientModel)\n\n\nclass RecipeModelAbstractFactory(ABC):\n @abstractmethod\n def create_ingredient_model(self):\n pass\n\n @abstractmethod\n def create_cluster_model(self):\n pass\n\n\nclass RecipeModelVolumeFactory(RecipeModelAbstractFactory):\n def create_ingredient_model(self):\n return RecipeIngredientModel()\n\n def create_cluster_model(self):\n return RecipeClusterModel()\n\n\nclass RecipeModelWeightFactory(RecipeModelAbstractFactory):\n def create_ingredient_model(self):\n return RecipeWeightIngredientModel()\n\n def create_cluster_model(self):\n return RecipeWeightClusterModel()\n" }, { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.800000011920929, "avg_line_length": 30.66666603088379, "blob_id": "c4957d7d834462d256c67fb63a913968edda10c8", "content_id": "e97e7fdb98021a240be577abd6729bc9251648ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "no_license", "max_line_length": 70, "num_lines": 3, "path": "/food_project/image_classification/crf/__init__.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom food_project.image_classification.crf.test import make_test_image\n" }, { "alpha_fraction": 0.6323108673095703, "alphanum_fraction": 0.6347648501396179, "avg_line_length": 19.040983200073242, "blob_id": "2c7845e77f6bf1a0fc39f3db168cf2f64f1a2b72", "content_id": "c57c3dec6cb1dfdf25d60285b4abfd2bf0118b24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2445, "license_type": "no_license", "max_line_length": 75, "num_lines": 122, "path": "/food_project/util.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport json\nimport os\nimport pickle\nimport re\nfrom difflib import SequenceMatcher\nfrom functools import partial\n\nimport pandas as pd\n\n\ndef read_json(path):\n with open(path, \"r\") as f:\n content = json.load(f)\n return content\n\n\ndef read_pickle(path, encoding=None):\n with open(path, \"rb\") as f:\n if encoding:\n content = pickle.load(f, encoding=encoding)\n else:\n content = pickle.load(f)\n return content\n\n\ndef column_name(df, i):\n return df.columns[i]\n\n\ndef column_value(df, i):\n return df.iloc[:, i]\n\n\ndef dataframe_from_dict(mydict):\n return pd.DataFrame(mydict)\n\n\ndef dataframe_from_list(lst, columns):\n return pd.DataFrame(lst, columns=columns)\n\n\ndef save_dataframe(df, path):\n try:\n df.to_pickle(path)\n except:\n raise Exception(\"Couldn't save dataframe!\")\n\n\ndef series_from_dict(mydict):\n return pd.Series(mydict)\n\n\ndef matching_columns(df, text):\n return df.columns.str.contains(text)\n\n\ndef _content_matches(path, match_cond):\n return match_cond.match(path)\n\n\ndef list_content_with_matches(path, match_cond):\n contents = os.listdir(path)\n\n def abs_path(x):\n return os.path.join(path, x)\n\n return [abs_path(x) for x in contents if match_cond.match(abs_path(x))]\n\n\ndef clean_word(inp, word, sep=\"_\"):\n \"\"\"Removes word from inp and returns modified inp\"\"\"\n inp = _change_plus(inp)\n if word in inp:\n words = inp.split(sep)\n words = [x for x in words if x != word]\n return sep.join(words)\n else:\n return inp\n\n\ndef _change_plus(word, sep=\"_\", unwanted_sep=\"+\"):\n words = word.split(unwanted_sep)\n return sep.join(words)\n\n\nclass FilesystemMatch:\n def __init__(self, fn, *args):\n self.fn = fn\n self.args = args\n\n def match(self, dir_content):\n return self.fn(dir_content, *self.args)\n\n\ndef comparison(fn, *args):\n return FilesystemMatch(fn, *args)\n\n\ndef match_score(text, query):\n\n match = re.search(query, text)\n\n if not match:\n return 0\n\n start, end = match.span()\n return (end - start) / len(text)\n\n\ndef uniform_score(text, query):\n\n return 1\n\n\ndef matchsubstring(m, n, verbose=0):\n seqMatch = SequenceMatcher(None, m, n)\n match = seqMatch.find_longest_match(0, len(m), 0, len(n))\n if verbose and match.size:\n print(\"Common Substring ::>\", m[match.a : match.a + match.size])\n return match.size\n" }, { "alpha_fraction": 0.6386701464653015, "alphanum_fraction": 0.6391075849533081, "avg_line_length": 29.078947067260742, "blob_id": "a1e88ba3cc04a3e5c909cde0fcb065f08ebc67c3", "content_id": "bcd7c0ed4b65890abea72b6f78110de82e13a895", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2286, "license_type": "no_license", "max_line_length": 79, "num_lines": 76, "path": "/food_project/recipe/flat_to_db.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\nfrom functools import partial\n\nfrom food_project.recipe.models import (ProcessedRecipeGroup,\n ProcessedRecipeReader, RawImageGroup,\n RawRecipeGroup, RawRecipeImageGroup,\n RecipeFilePathSetter, raw_recipe_model,\n raw_recipe_reader)\n\n\ndef set_recipe_filename(path, obj):\n rfps = RecipeFilePathSetter(path)\n obj.accept(rfps)\n\n\nset_recipe_reader_fname = partial(set_recipe_filename, obj=raw_recipe_reader)\nset_group_dirname = set_recipe_filename\n\n\ndef recipe_ids():\n if not raw_recipe_reader.ready:\n raw_recipe_reader.read()\n return raw_recipe_reader.recipe_ids\n\n\ndef list_group_files(group_obj):\n return group_obj.process()\n\n\ndef save_recipe_by_id(recipe_id):\n try:\n data = raw_recipe_reader.recipe_by_id(recipe_id)\n except Exception as e:\n raise e\n raw_recipe_model.save(data)\n\n\ndef save_recipe_image_paths(recipe_image_folder):\n # recipe_id = os.path.basename(recipe_id)\n rig = RawImageGroup()\n set_group_dirname(recipe_image_folder, rig)\n recipe_id = os.path.basename(recipe_image_folder)\n images = list_group_files(rig)\n raw_recipe_model.update(recipe_id, {\"images\": images})\n\n\ndef populate_db_recipes(path):\n rcg = RawRecipeGroup()\n set_group_dirname(path, rcg)\n for recipe_file in list_group_files(rcg):\n set_recipe_reader_fname(recipe_file)\n ids = recipe_ids()\n for id_ in ids:\n save_recipe_by_id(id_)\n\n\ndef populate_db_images(path):\n rcig = RawRecipeImageGroup()\n set_group_dirname(path, rcig)\n for recipe_group in list_group_files(rcig):\n save_recipe_image_paths(recipe_group)\n\n\ndef populate_db_processed(path):\n prg = ProcessedRecipeGroup()\n set_group_dirname(path, prg)\n for recipe in list_group_files(prg):\n prr = ProcessedRecipeReader()\n set_recipe_filename(recipe, prr)\n data = prr.read()\n raw_recipe_model.update(prr.recipe_id, {\"processed_ingredients\": data})\n\n # recipe_id = os.path.basename(recipe_image_folder)\n # images = list_group_files(rig)\n # raw_recipe_model.update(recipe_id, {'images': images})\n" }, { "alpha_fraction": 0.6461538672447205, "alphanum_fraction": 0.6492307782173157, "avg_line_length": 26.85714340209961, "blob_id": "2933a6e266abf008bae8bf580b4f1fa861691348", "content_id": "8957980563047995b27462b08ef5df5c1742e328", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 975, "license_type": "no_license", "max_line_length": 102, "num_lines": 35, "path": "/food_project/recipe/similarity/importance.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Currently, these classes are not used. Importance is calculated using recipe.recipe.Recipe class\"\"\"\nfrom abc import ABC, abstractmethod\n\n\nclass ImportanceCalculator:\n def _create_ranker(self, mask_type):\n \"\"\"Return an importance ranker\"\"\"\n if mask_type == \"db_recipes\":\n return DBRecipesRanker()\n else:\n return QueryRecipeRanker()\n\n def calculate_importances(self, mask, mask_type):\n ranker = self._create_ranker(mask_type)\n return ranker.get_ranks(mask)\n\n\nclass Ranker(ABC):\n @abstractmethod\n def get_ranks(self, values):\n pass\n\n\nclass QueryRecipeRanker(Ranker):\n def get_ranks(self, values):\n ranks = values.rank(ascending=False, method=\"dense\")\n tmp = ranks[values != 0]\n return tmp\n\n\nclass DBRecipesRanker(Ranker):\n def get_ranks(self, values):\n # TODO: GO FROM HERE!\n tmp = values.rank(ascending=False, method=\"dense\", axis=1)\n" }, { "alpha_fraction": 0.6108857989311218, "alphanum_fraction": 0.6119530200958252, "avg_line_length": 37.40163803100586, "blob_id": "84cf24611228cb74bb408aa55b576877a39c2819", "content_id": "2178fa9880b0cf9e420f9b55f8893ff7216f0895", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4685, "license_type": "no_license", "max_line_length": 96, "num_lines": 122, "path": "/food_project/recipe/models/weight_models.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom functools import partial\n\nfrom food_project.recipe.cluster import ingredient_clusters\nfrom food_project.recipe.ingredient import Ingredient, IngredientCluster\nfrom food_project.recipe.similarity import get_item_entropy\nfrom food_project.util import (column_name, column_value, dataframe_from_dict,\n dataframe_from_list, read_json, read_pickle,\n save_dataframe, series_from_dict)\n\n\nclass RecipeModel:\n def __init__(self):\n self.filename = None\n self.scaled_ingredients = None\n\n # def _read_data(self):\n # self.scaled_ingredients = read_pickle(self.filename)\n\n def _recipe_percentage_normalize(self, df):\n row_totals = df.sum(axis=1)\n return df.div(row_totals, axis=0)\n\n def _get_ingredient_name(self, i):\n self._read_data()\n try: # TODO: remove after abstract factory is implemented\n return partial(column_name, self.scaled_ingredients)(i)\n except:\n raise Exception(\"Not existent\")\n\n def _get_ingredient_quantity(self, i):\n self._read_data()\n return partial(column_value, self.scaled_ingredients)(i)\n\n def _get_ingredient_entropy(self, ingredient_name: str) -> float:\n return get_item_entropy(ingredient_name)\n\n\nclass RecipeWeightIngredientModel(RecipeModel):\n def __init__(self):\n super().__init__()\n print(\"INIT WEIGHT INGREDIENT MODEL\")\n # self.conversion_file = \"data/recipes/all_weight_cup.json\"\n self.conversion_file = \"data/recipes/unit_conversion/new_corrected_meta.json\"\n\n def _read_data(self):\n if self.scaled_ingredients is None:\n gram_data = read_json(self.conversion_file)\n columns = [\"id\", \"name\", \"qty\", \"unit\", \"tag\"] # TODO\n tmp_df = dataframe_from_list(gram_data[\"data\"], columns)\n # tmp_df = tmp_df[tmp_df[\"unit\"] != \"cup\"]\n tmp_df = tmp_df.drop(columns=\"tag\")\n tmp_df = tmp_df.astype({\"qty\": \"float\", \"id\": \"float\"})\n tmp_df = tmp_df.drop_duplicates(subset=[\"id\", \"name\"])\n tmp_df = tmp_df.pivot(index=\"id\", columns=\"name\", values=\"qty\")\n tmp_df[tmp_df.isna()] = 0\n\n self.scaled_ingredients = self._fix_missing_and_extra_columns(tmp_df)\n\n def get_data(self):\n self._read_data()\n\n def _fix_missing_and_extra_columns(self, tmp_df):\n tmp = read_pickle(\"data/recipes/recipe_ingredients_scaled_units_wide_df.pkl\")\n diff_no_want = set(tmp_df.columns) - set(tmp.columns)\n missing_columns = set(tmp.columns) - set(tmp_df.columns)\n missing_col_dict = {k: 0 for k in missing_columns}\n tmp_df = tmp_df.assign(**missing_col_dict)\n return tmp_df[tmp.columns]\n\n\nclass RecipeWeightClusterModel(RecipeWeightIngredientModel):\n \"\"\"Data after parsing raw recipes. Consolidated into clusters.\"\"\"\n\n # TODO: Model should only load/save data, extract logic in this to a controller helper class\n def __init__(self):\n print(\"INIT WEIGHT CLUSTER MODEL\")\n super().__init__()\n self.clusters = None\n self.is_clusters_formed = lambda: self.clusters is not None\n\n def _consolidate_clusters(self):\n clusters = []\n for k, v in ingredient_clusters.items():\n ingredients = []\n for i in v:\n try: # TODO: remove after you have abstract factory class\n\n name = self._get_ingredient_name(i)\n\n except:\n print(\"name not found\")\n continue\n quantity = self._get_ingredient_quantity(i)\n entropy = self._get_ingredient_entropy(name)\n ingredients.append(Ingredient(name, i, quantity, entropy))\n\n ic = IngredientCluster(k, *ingredients)\n clusters.append(ic)\n return clusters\n\n def get_data(self):\n if not self.is_clusters_formed():\n clusters = self._consolidate_clusters()\n df = dataframe_from_dict(\n {x.name: x.get_quantity() for x in clusters}\n ) # TODO: This shouldn't depend on the availability of entropies\n return self._recipe_percentage_normalize(df)\n\n def export_cluster_df(self, path):\n df = self.get_data()\n save_dataframe(df, path)\n\n def get_entropy(self):\n if not self.is_clusters_formed():\n clusters = self._consolidate_clusters()\n return series_from_dict({x.name: x.get_entropy() for x in clusters})\n\n def get_amount_of_cluster_in_recipe(self, cluster_name, recipe_id):\n\n data = self.get_data()\n return data.loc[recipe_id, cluster_name]\n" }, { "alpha_fraction": 0.6852791905403137, "alphanum_fraction": 0.6903553009033203, "avg_line_length": 18.700000762939453, "blob_id": "5573510ac6e784259d6e93642ab97110c61c40fa", "content_id": "aa543ed0108488448d8149058cb8661794bb4025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 197, "license_type": "no_license", "max_line_length": 57, "num_lines": 10, "path": "/food_project/image_classification/crf/prediction_classes.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport pickle\n\nclass_file = \"data/image_classification/hyvee_label.dict\"\n\n\nwith open(class_file, \"rb\") as f:\n classes = pickle.load(f)\n classes = list(classes.keys())\n" }, { "alpha_fraction": 0.6041079163551331, "alphanum_fraction": 0.6105517745018005, "avg_line_length": 24.080808639526367, "blob_id": "29fc2ce6232ac1335cf7c63ea3a976972c01a115", "content_id": "d2608fff421a90e549f0d42191516169c3941365", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2483, "license_type": "no_license", "max_line_length": 79, "num_lines": 99, "path": "/food_project/image_classification/crf/prediction_class_clusters.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom food_project.image_classification.crf.prediction_classes import classes\nfrom food_project.image_classification.crf.recipe_cluster_names import \\\n cluster_names\nfrom food_project.util import clean_word, matchsubstring\n\nword_separator = \"_\"\n\n\ndef get_cluster_names():\n return cluster_names\n\n\ndef get_ingredient_name_separator():\n return word_separator\n\n\ndef get_prediction_class_list():\n\n classes = _get_prediction_class_list()\n unwanted_words = _get_unwanted_words()\n\n for i, cls in enumerate(classes):\n cls_original = cls\n for word in unwanted_words:\n cls = clean_word(cls, word)\n if cls != cls_original:\n classes[i] = cls\n return classes\n\n\ndef _get_prediction_class_list():\n return classes\n\n\ndef _get_unwanted_words():\n return [\"fruit\", \"fresh\"]\n\n\ndef get_cluster_of_ingredient(ingredient):\n cluster_names = get_cluster_names()\n clusters = []\n words = ingredient.split(word_separator)\n max_score = 0\n cluster = \"\"\n for cluster_name in cluster_names:\n score = matchsubstring(cluster_name, ingredient)\n\n if score > max_score:\n max_score = score\n cluster = cluster_name\n\n return cluster\n\n\ndef get_class_clusters():\n prediction_classes = get_prediction_class_list()\n class_clusters = {}\n\n for cls in prediction_classes:\n cluster = get_cluster_of_ingredient(cls)\n class_clusters[cls] = cluster\n return class_clusters\n\n\nclass ClassCandidates:\n def __init__(self, probs: dict):\n self.probs = probs\n self._classes = probs.keys()\n\n @staticmethod\n def class_to_cluster(pred_class):\n return get_cluster_of_ingredient(pred_class)\n\n @property\n def classes(self):\n return self._classes\n\n def _sorted_classes(self):\n\n return sorted(self.probs.items(), key=lambda x: x[1], reverse=True)\n\n def top_n_clusters(self, n):\n data = self._sorted_classes()\n # 0: name, 1: cluster name, 2: prob\n data = [\n (x[0], self.class_to_cluster(x[0]), x[1]) for x in data if x[1] > 0\n ] # don't consider 0 probability classes\n i = 0\n selected = set()\n selected_list = []\n for point in data:\n if i >= n:\n break\n if point[0] not in selected:\n selected.add(point[1])\n selected_list.append(point)\n i += 1\n return selected_list\n" }, { "alpha_fraction": 0.732758641242981, "alphanum_fraction": 0.7356321811676025, "avg_line_length": 22.200000762939453, "blob_id": "ea6e5ff553d2c1e39d10409bc82facfd233bccf6", "content_id": "694e80c4f90ab43ce40ecb9e9fc433f4203c7ebb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 348, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/food_project/recipe/db_to_local.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom food_project.recipe.models import raw_recipe_model\n\n\ndef get_recipe_from_db(id_):\n return raw_recipe_model.load(id_)\n\n\ndef get_recipe_ids_from_db():\n return raw_recipe_model.retrieve_field(\"recipe_ID\")\n\n\ndef get_processed_ingredients_from_db():\n return raw_recipe_model.retrieve_field(\"processed_ingredients\")\n" }, { "alpha_fraction": 0.6254295706748962, "alphanum_fraction": 0.6277204751968384, "avg_line_length": 31.943395614624023, "blob_id": "3514ec92ed02abcbee5fee7ae8ee2db6b9582ad4", "content_id": "7e888e99153f0a4be95aaba923d7f84a712d1aff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1746, "license_type": "no_license", "max_line_length": 88, "num_lines": 53, "path": "/food_project/recipe/ingredient.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nclass Ingredient:\n def __init__(self, name, id, quantity, entropy):\n self.name = name\n self.id = id # column number in recipe ingredients dataframe\n self.quantity = quantity\n self.entropy = entropy\n\n\n# clusters = {}\ningredients_to_clusters = {} # TODO: put this into mongo\n# TODO: separate populating this into an independent task, do it upfront once\n# not with every run of the program\n\n\nclass IngredientCluster:\n def __init__(self, name, *ingredients):\n self.name = name\n self.ingredients = ingredients\n # self.quantity = 0\n # clusters[name] = self\n self.save_ingredients() # TODO: functions shouldn't have side-effects!!!\n\n def save_ingredients(self):\n # TODO: not written well\n for ingredient in self.ingredients:\n ingredients_to_clusters[ingredient.name] = self.name\n\n def add_ingredient(self, ingredient):\n self.ingredients += (ingredient,)\n\n def get_quantity(self):\n # self.quantity = sum([x.quantity for x in self.ingredients])\n # return self.quantity\n return sum([x.quantity for x in self.ingredients])\n\n def get_entropy(self):\n # self.entropy = sum([x.entropy for x in self.ingredients])\n # return self.entropy\n try:\n n_ingredients = len([x for x in self.ingredients if x.entropy != 0])\n return sum([x.entropy for x in self.ingredients]) / n_ingredients\n except:\n return 0\n\n @staticmethod\n def ingredient_in_cluster(ing_name):\n # return [\n # cluster.name for _, cluster in clusters if ing_name in cluster.ingredients\n # ]\n return ingredients_to_clusters.get(ing_name, None)\n" }, { "alpha_fraction": 0.5617760419845581, "alphanum_fraction": 0.5670160055160522, "avg_line_length": 32.88785171508789, "blob_id": "2c99b3a8861b0e269ff41a8da5acad94657d8654", "content_id": "9f6a79822ad4a6ed248203f6826de81d48b05d46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3626, "license_type": "no_license", "max_line_length": 126, "num_lines": 107, "path": "/food_project/image_classification/crf/crf_model.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport itertools\nimport math\n\nimport numpy as np\n\nfrom food_project.image_classification.crf.potentials import (\n NodePotential, get_clique_potential)\nfrom food_project.image_classification.crf.prediction_class_clusters import \\\n ClassCandidates\n\n\nclass CRF:\n def __init__(self, n: int, k: int) -> None:\n \"\"\"Args:\n\n n: Number of nodes in CRF\n k: Number of variable values to consider for\n each node. Top k values for each node is considered.\n \"\"\"\n self.n = n\n self.k = k\n self.nodes = []\n self.edges = {}\n self.all_possible_configs = None\n\n def add_node(self, node: ClassCandidates):\n clusters_probs = node.top_n_clusters(self.k)\n node = [NodePotential(x[0], x[1], x[2]) for x in clusters_probs]\n self.nodes.append(node)\n\n def make_full(self):\n # while len(self.nodes) < self.n:\n # self.nodes.append([NodePotential(\"empty\", 'empty', 1)])\n self.nodes = [\n x for x in self.nodes if x[0].name != \"empty\"\n ] # this is hardcoded but is correct, when the image is empty in the grid, classifier returns {'empty':1} as response\n\n self.all_possible_configs = itertools.product(*self.nodes)\n\n def get_clique_potential(self, *nodes):\n return get_clique_potential(*nodes)\n\n def calc_setting_prob(self, setting):\n\n edge_probs = []\n node_probs = []\n n = len(setting)\n\n for clique in self.cliques(setting):\n node_names = [x.name for x in clique]\n # TODO: problem might be here??\n\n if len(set(node_names)) == len(clique):\n edge_probs.append(self.get_clique_potential(*node_names))\n node_probs.extend([x.potential for x in setting])\n # for i in range(n):\n # node1 = setting[i]\n # node_probs.append(node1.potential)\n # for j in range(i + 1, n):\n # node2 = setting[j]\n # if node1.name != node2.name:\n # edge_probs.append(self.get_edge_potential(node1.name, node2.name))\n return np.sum(np.log(edge_probs)) + np.sum(np.log(node_probs))\n\n def cliques(self, selected_nodes):\n return itertools.chain(\n itertools.combinations(selected_nodes, 2),\n itertools.combinations(selected_nodes, 3),\n )\n\n def get_node_config(self):\n # for nt in self.all_possible_configs:\n # for prd in itertools.product(*nt):\n # yield prd\n\n return next(self.all_possible_configs)\n\n def filter_at_threshold(self, threshold):\n for i in range(len(self.nodes)):\n node = self.nodes[i]\n if node[0].potential >= threshold:\n self.nodes[i] = [node[0]]\n\n def get_best_config(self, threshold):\n self.make_full()\n self.filter_at_threshold(threshold)\n max_prob = -math.inf\n best_setting = None\n # config_gen = self.get_node_config()\n for setting in self.all_possible_configs:\n res = self.calc_setting_prob(setting)\n if res > max_prob:\n max_prob = res\n best_setting = setting\n\n # while True:\n # try:\n # setting = self.get_node_config()\n # except StopIteration:\n # break\n # res = self.calc_setting_prob(setting)\n # if res > max_prob:\n # max_prob = res\n # best_setting = setting\n best_setting = [x.name for x in best_setting if x.name != \"empty\"]\n return max_prob, best_setting\n" }, { "alpha_fraction": 0.5853185653686523, "alphanum_fraction": 0.5875346064567566, "avg_line_length": 32.738319396972656, "blob_id": "477f2d339803a8ed3116c15a849d3630f37e6e8a", "content_id": "d5b09b7069baa5d3c8e03657e70b60b4b22d18b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3610, "license_type": "no_license", "max_line_length": 82, "num_lines": 107, "path": "/food_project/image_classification/crf/potentials.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\nimport pickle\n\nfrom food_project.image_classification.crf.prediction_class_clusters import \\\n get_class_clusters\nfrom food_project.recipe.crf import (get_number_of_recipes,\n get_recipe_counts_containing_ingredients)\n\n# All names are in terms of clusters\n\nclass_clusters = get_class_clusters()\nclusters = class_clusters.values()\nn_clusters = clusters\nid_clusters = {x[0]: x[1] for x in zip(range(len(n_clusters)), clusters)}\nclusters_ids = {v: k for k, v in id_clusters.items()}\n\n\ndef name_potential(*nodes):\n classes = [class_clusters[x] for x in nodes]\n node_ids = [str(clusters_ids[x]) for x in classes]\n return \"+\".join(sorted(node_ids))\n\n\nclass NodePotential:\n def __init__(self, name, cluster, potential):\n self.name = name\n self.cluster = cluster\n self._potential = potential\n\n @property\n def potential(self):\n return self._potential\n\n\nclass CliquePotentials:\n def __init__(self, path):\n class_clusters = get_class_clusters()\n self.clusters = list(class_clusters.values())\n self.n_total_recipes = get_number_of_recipes()\n self.clique_potentials = {}\n self.path = path # This is ugly\n\n self.bi_freq = None\n self.tri_freq = None\n\n def _calculate_bi_frequencies(self):\n \"\"\"Calculates cliques of size 2 and 3.\"\"\"\n clusters = self.clusters\n for ci in clusters:\n for cj in clusters:\n name = name_potential(ci, cj)\n if ci == cj:\n continue\n if name not in self.clique_potentials:\n cnt = get_recipe_counts_containing_ingredients(ci, cj)\n freq = cnt / self.n_total_recipes\n self.clique_potentials[name] = freq\n return self.clique_potentials\n\n def _calculate_tri_frequencies(self):\n clusters = self.clusters\n for ci in clusters:\n for cj in clusters:\n for ck in clusters:\n if len(set([ci, cj, ck])) != 3:\n continue\n name = name_potential(ci, cj, ck)\n if name not in self.clique_potentials:\n cnt = get_recipe_counts_containing_ingredients(ci, cj, ck)\n freq = cnt / self.n_total_recipes\n self.clique_potentials[name] = freq\n return self.clique_potentials\n\n def _save_frequencies(self, frequencies):\n if not os.path.exists(self.path):\n with open(self.path, \"wb\") as f:\n pickle.dump(frequencies, f)\n\n def get_frequencies(self):\n if not os.path.exists(self.path):\n self._calculate_bi_frequencies()\n self._calculate_tri_frequencies()\n self._save_frequencies(self.clique_potentials)\n else:\n if not self.clique_potentials:\n with open(self.path, \"rb\") as f:\n self.clique_potentials = pickle.load(f)\n return self.clique_potentials\n\n def clique_potential(self, *nodes):\n if not self.clique_potentials:\n self.get_frequencies()\n\n # TODO: is it good to keep this 1? This might be useful when we have\n # empty nodes to make it ineffective\n try:\n return self.clique_potentials[name_potential(*nodes)]\n except:\n return 1\n\n\n_clique_potentials = CliquePotentials(\"data/crf/clique_potentials_dict.pkl\")\n\n\ndef get_clique_potential(*nodes):\n return _clique_potentials.clique_potential(*nodes)\n" }, { "alpha_fraction": 0.6471354365348816, "alphanum_fraction": 0.6536458134651184, "avg_line_length": 20.33333396911621, "blob_id": "2e5baafb4cd23a080c1475865c656725f2c251a3", "content_id": "a1a2762a14226b1d53a083392b9906807cd946e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 768, "license_type": "no_license", "max_line_length": 76, "num_lines": 36, "path": "/food_project/recipe/unit_conversion/util.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport json\nfrom collections import defaultdict\n\n\ndef read_json(path):\n with open(path, \"rb\") as f:\n content = json.load(f)\n return content\n\n\n# needs_conversion = 'data/recipes/unit_conversion/corrected_meta.json'\nneeds_conversion = \"data/recipes/unit_conversion/cup_ingr.json\"\nto_convert_json = read_json(needs_conversion)\n\ndata = defaultdict(list)\nfor entry in to_convert_json[\"data\"]:\n data[entry[3]].append(entry[1])\n\n\ntmp = {}\ntotal = 0\ntotal_uniq = 0\nfor k, v in data.items():\n total += len(v)\n try:\n tmp[k] = list(set(v))\n total_uniq += len(tmp[k])\n except:\n breakpoint()\n\nwith open(\n \"data/recipes/unit_conversion/cup_units_ingredients_no_repeat.json\", \"w\"\n) as f:\n json.dump(tmp, f)\n" }, { "alpha_fraction": 0.607295572757721, "alphanum_fraction": 0.6079636812210083, "avg_line_length": 26.018051147460938, "blob_id": "a12c7f4ff17ea9c2b3d33f5a98aa58cdcb8e768c", "content_id": "cb76ab2d8271df3803a84a7bcc57f5ac100ed3c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7484, "license_type": "no_license", "max_line_length": 99, "num_lines": 277, "path": "/food_project/recipe/models/__init__.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\nfrom functools import partial\n\nfrom pymongo import MongoClient\n\nfrom food_project.recipe.cluster import ingredient_clusters\nfrom food_project.recipe.ingredient import Ingredient, IngredientCluster\nfrom food_project.recipe.models.recipe_models import (RecipeModelVolumeFactory,\n RecipeModelWeightFactory)\nfrom food_project.recipe.similarity import get_item_entropy\nfrom food_project.util import (column_name, column_value, comparison,\n dataframe_from_dict, list_content_with_matches,\n read_json, read_pickle, save_dataframe,\n series_from_dict)\n\nmodel_type = None\nmodel_factory = None\nrecipe_ingredient_model = None\nrecipe_cluster_model = None\n\n\ndef set_recipe_model(modeltype=\"volume\"):\n global model_type\n model_type = modeltype\n _set_recipe_model_factory()\n _set_recipe_ingredient_model()\n _set_recipe_cluster_model()\n\n\ndef _set_recipe_model_factory():\n global model_factory\n if model_type == \"volume\":\n model_factory = RecipeModelVolumeFactory()\n elif model_type == \"weight\":\n model_factory = RecipeModelWeightFactory()\n\n\ndef _set_recipe_ingredient_model():\n global recipe_ingredient_model\n recipe_ingredient_model = model_factory.create_ingredient_model()\n\n\ndef _set_recipe_cluster_model():\n global recipe_cluster_model\n recipe_cluster_model = model_factory.create_cluster_model()\n\n\ndef get_recipe_ingredient_model():\n return recipe_ingredient_model\n\n\ndef get_recipe_cluster_model():\n return recipe_cluster_model\n\n\nclass QueryModel:\n def _set_data(self, ingredients):\n self.ingredients = ingredients\n\n def get_data(self, *ingredients):\n self._set_data(ingredients)\n return self.ingredients\n\n\n# TODO: Change name to reflect that this is not a db model\n#\n#\n\n# def _calculate_ingredient_entropies(self):\n# if self.scaled_ingredients is None:\n# self._read_data()\n# self.entropies = self.scaled_ingredients.copy()\n# ingredients = self.scaled_ingredients.columns\n# entropies = {}\n# for ingredient in ingredients:\n# entropies[ingredient] = get_item_entropy(ingredient)\n# return entropies\n\n# def calculate_recipe_ingredient_entropies(self):\n# entropies = self._calculate_ingredient_entropies()\n\n# for colname in self.entropies.columns:\n# values = self.entropies[colname]\n# self.entropies[colname] = values.apply(lambda x: entropies[colname] if x > 0 else 0)\n# return self.entropies\n\n\nclass RecipeDBInitiator:\n def __init__(self, uri, uname, pwd):\n self.db_uri = uri\n self.uname = uname\n self.pwd = pwd\n\n def visit(self, element):\n \"\"\"Sets username and password for recipe database and establishes connection to database\"\"\"\n element.username = self.uname\n element.password = self.pwd\n element.uri = f\"mongodb://{self.uname}:{self.pwd}@{self.db_uri}\"\n element._connect()\n\n\nclass RawRecipeModel:\n def __init__(self):\n self.username = None\n self.password = None\n self.uri = None\n self.path = None\n self.key_field = \"recipe_ID\"\n\n def _connect(self):\n client = MongoClient(self.uri)\n db = client[\"food\"]\n self.collection = db[\"recipe\"]\n\n def load(self, id_):\n id_ = str(id_)\n return self.collection.find_one({self.key_field: id_})\n\n def save(self, data):\n id = data[\"_id\"] # TODO: fix according to recipe class\n try:\n self.collection.insert_one(data)\n # print(f\"Inserted recipe id {id}\")\n except:\n # print(f\"Couldn't insert recipe id {id}\")\n pass\n\n def update(self, id_, data):\n \"\"\"data: key value pair\"\"\"\n id_ = str(id_)\n try:\n updated = self.collection.find_one_and_update(\n {self.key_field: id_}, {\"$set\": data}, upsert=True\n )\n # print(f\"Updated recipe id {id_}\")\n\n except:\n # print(f\"Couldn't update {id_}\")\n pass\n return updated\n\n def _retrieve_all(self):\n return self.collection.find()\n\n def retrieve_field(self, field_name):\n coll = self._retrieve_all()\n field_val = lambda x: x.get(field_name, [])\n return [field_val(x) for x in coll]\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass RawRecipeReader:\n # TODO: factor out a recipe class with _id, etc\n def __init__(self):\n self._reset()\n\n def _reset(self):\n self.path = None\n self.data = None\n self._recipe_ids = None\n\n def read(self):\n \"\"\"Returns recipe data in json format\"\"\"\n self.data = read_json(self.path)\n\n @property\n def ready(self):\n return self.data is not None\n\n @property\n def recipe_ids(self):\n if not self._recipe_ids:\n self._recipe_ids = [x[\"recipe_ID\"] for x in self.data]\n return self._recipe_ids\n\n def _filter_by_id(self, recipe_id):\n return [x for x in self.data if x[\"recipe_ID\"] == recipe_id][0]\n\n def recipe_by_id(self, recipe_id):\n x = self._filter_by_id(recipe_id)\n x[\"_id\"] = x[\"recipe_ID\"]\n return x\n\n def accept(self, visitor):\n self._reset()\n visitor.visit(self)\n\n\nclass ProcessedRecipeReader:\n def __init__(self):\n self._reset()\n\n def _reset(self):\n self.path = None\n self.data = None\n self._recipe_id = None\n\n @property\n def ready(self):\n return self.data is not None\n\n def read(self):\n with open(self.path, \"r\") as f:\n self.data = [x.strip() for x in f.readlines()]\n return self.data\n\n @property\n def recipe_id(self):\n if not self._recipe_id:\n self._recipe_id = os.path.basename(self.path).split(\".\")[0]\n return self._recipe_id\n\n def accept(self, visitor):\n self._reset()\n visitor.visit(self)\n\n\nclass RawDataGroup:\n def __init__(self):\n self.path = None\n self.inner_dir = None\n\n def content_path(self):\n if self.inner_dir is not None:\n return os.path.join(self.path, self.inner_dir)\n else:\n return self.path\n\n def process(self):\n return list_content_with_matches(self.content_path(), self.match_cond)\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass RawRecipeGroup(RawDataGroup):\n def __init__(self):\n super().__init__()\n self.inner_dir = \"original_recipes_info\"\n self.suffix = \"json\"\n self.match_cond = comparison(str.endswith, self.suffix)\n\n\nclass ProcessedRecipeGroup(RawDataGroup):\n def __init__(self):\n super().__init__()\n self.suffix = \"out\"\n self.match_cond = comparison(str.endswith, self.suffix)\n\n\nclass RawRecipeImageGroup(RawDataGroup):\n def __init__(self):\n super().__init__()\n self.inner_dir = \"imgs\"\n self.match_cond = comparison(os.path.isdir)\n\n\nclass RawImageGroup(RawDataGroup):\n def __init__(self):\n super().__init__()\n self.suffix = \"jpg\"\n self.match_cond = comparison(str.endswith, self.suffix)\n\n\nclass RecipeFilePathSetter:\n def __init__(self, path):\n self.path = path\n\n def visit(self, element):\n element.path = self.path\n\n\nraw_recipe_model = RawRecipeModel()\nraw_recipe_reader = RawRecipeReader()\n" }, { "alpha_fraction": 0.6348167657852173, "alphanum_fraction": 0.6374345421791077, "avg_line_length": 38.17948532104492, "blob_id": "0eaa2f2c564f5e2fb229c9f5679b2342117eca65", "content_id": "659decf8254d520c9e1c3826198ae1419b5d952a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1528, "license_type": "no_license", "max_line_length": 82, "num_lines": 39, "path": "/food_project/recipe/recipe.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom food_project.recipe.ingredient import IngredientCluster\nfrom food_project.recipe.models import get_recipe_cluster_model\nfrom food_project.recipe.similarity import get_cluster_entropies\n\n\nclass Recipe:\n def __init__(self, id_, *ingredients):\n self.id_ = id_\n self.ingredients = ingredients\n self.cluster_entropies = get_cluster_entropies()\n self.clusters = [self._cluster_of_ingredient(x) for x in self.ingredients]\n self.cluster_amounts_model = get_recipe_cluster_model()\n\n def _cluster_of_ingredient(self, ingredient):\n return IngredientCluster.ingredient_in_cluster(ingredient)\n\n def _amount_of_cluster_of_ingredient(self, ingredient):\n cluster = self._cluster_of_ingredient(ingredient)\n return self.cluster_amounts_model.get_amount_of_cluster_in_recipe(\n cluster, float(self.id_)\n )\n\n def importance_ranked_ingredients(self, use_entropy=True):\n ingredient_ranks = []\n for ing, cluster in zip(self.ingredients, self.clusters):\n try:\n amount = self._amount_of_cluster_of_ingredient(ing)\n if use_entropy:\n entropy = self.cluster_entropies[cluster]\n else:\n entropy = 1\n\n ingredient_ranks.append((ing, amount * entropy))\n except:\n continue\n\n sorted_ingrs = sorted(ingredient_ranks, key=lambda x: x[1], reverse=True)\n return [x[0] for x in sorted_ingrs]\n" }, { "alpha_fraction": 0.8620689511299133, "alphanum_fraction": 0.8620689511299133, "avg_line_length": 13.5, "blob_id": "9c469d65e9cfa967c0b54d0f2b0babd5b989326d", "content_id": "ff37c077607136736591dce659e6f0630d5bc253", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/tmp.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "import collections\nimport os\n" }, { "alpha_fraction": 0.6678743958473206, "alphanum_fraction": 0.7028985619544983, "avg_line_length": 27.55172348022461, "blob_id": "2ebc00190821cb7859180798d2a66621e2c78309", "content_id": "2bec6cbb95af085ea0c4eba996629ad6de3e2d42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 828, "license_type": "no_license", "max_line_length": 85, "num_lines": 29, "path": "/test_crf.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom food_project.image_classification.crf.crf_model import CRF\nfrom food_project.image_classification.crf.prediction_class_clusters import \\\n ClassCandidates\nfrom food_project.image_classification.crf.preprocess import (\n get_individual_image, read_image, split_image)\n\n# crf = CRF(5, 10)\n\n# node1 = ClassCandidates({\"apple\": 0.5, \"orange\": 0.3, \"cheese\": 0.1})\n# node2 = ClassCandidates({\"cheese\": 0.1, \"lemon\": 0.3, \"bread\": 0.4, \"pepper\": 0.1})\n# crf.add_node(node1)\n# crf.add_node(node2)\n# crf.make_full()\n# res, best = crf.get_best_config()\n\n# 3x3 image grid\nv_n = 3\nh_n = 3\nimage = read_image(\"data/crf/test_images/compiled/1.jpeg\")\nsplitted_image = split_image(image, v_n, h_n)\nres = get_individual_image(splitted_image, 0, 1)\n\n\nfrom PIL import Image\n\nimg = Image.fromarray(res)\nimg.show()\n" }, { "alpha_fraction": 0.6392069458961487, "alphanum_fraction": 0.641720175743103, "avg_line_length": 39.23595428466797, "blob_id": "3db7d3e3dea235d49bf5e52fd609ede1c89cd04c", "content_id": "432161b77261ffe9fe8b962c2f523c831c5866e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3581, "license_type": "no_license", "max_line_length": 103, "num_lines": 89, "path": "/food_project/recipe/similarity/controller.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom food_project.recipe.ingredient import IngredientCluster\nfrom food_project.recipe.matcher import (IngredientMatcher, IngredientQuery,\n match_score)\nfrom food_project.recipe.models import (QueryModel, get_recipe_cluster_model,\n get_recipe_ingredient_model)\nfrom food_project.recipe.similarity import ( # update cluster entropies in main this is not good\n cluster_entropy_update, get_entropy_mask)\n\n\nclass SimilarityController:\n def __init__(self):\n self.query_model = QueryModel()\n self.recipe_cluster_model = get_recipe_cluster_model()\n self.recipe_ingredient_model = get_recipe_ingredient_model()\n self.scoring_strategy = match_score\n self.scaled_cluster_ingredients = None\n self.scaled_ingredients = None\n self.n_clusters_in_recipe = 0\n self.loaded = (\n lambda: self.scaled_cluster_ingredients is not None\n and self.scaled_ingredients is not None\n )\n\n def handle(self, request, n):\n \"\"\"Calculates similarities using mask and the scaled_cluster_ingredients df.\n Returns ids and similarity scores of the top n most similar recipes.\n \"\"\"\n if not self.loaded():\n self.load_data()\n\n cluster_entropy_update(self.recipe_cluster_entropies) # this is not good here\n mask = self._get_mask(request)\n similarity_scores = self._get_similarity_scores(mask, self.n_clusters_in_recipe)\n return self._get_n_most_similar(similarity_scores, n)\n\n def load_data(self):\n self.scaled_cluster_ingredients = self.recipe_cluster_model.get_data()\n self.scaled_ingredients = self.recipe_ingredient_model.get_data()\n self.recipe_cluster_entropies = self.recipe_cluster_model.get_entropy()\n self.loaded_flag = True\n\n def _get_mask(self, request):\n matcher = IngredientMatcher(\n self.scaled_cluster_ingredients, self.scoring_strategy\n )\n query_ingredients = self.query_model.get_data(*request)\n # TODO use IngredientCluster.ingredient_in_cluster to get relevant clusters for all ingredients\n # TODO you have to run this on pandas to get access to images\n clusters = []\n for ingredient in query_ingredients:\n cluster = IngredientCluster.ingredient_in_cluster(\n \"_\".join(ingredient.split(\" \"))\n )\n if cluster:\n clusters.append(cluster)\n\n self.n_clusters_in_recipe = len(set(clusters))\n entropy_mask = get_entropy_mask(\n self.scaled_cluster_ingredients, self.n_clusters_in_recipe\n )\n test = IngredientQuery(*query_ingredients)\n mask = matcher.query_mask(test)\n mask = mask * entropy_mask\n # TODO add importance ranking\n return mask\n\n def _get_similarity_scores(self, mask, n):\n ingredient_similarity_scores = mask * self.scaled_cluster_ingredients\n non_0_cnts = ingredient_similarity_scores.apply(\n lambda x: len(x[x != 0]), axis=1\n )\n rng = non_0_cnts.between(n - 2, n + 2)\n return ingredient_similarity_scores[rng].sum(axis=1)\n\n def _get_n_most_similar(self, arr, n):\n\n return arr.sort_values(ascending=False).iloc[:n]\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass SimilarityControllerVisitor:\n def __init__(self, scoring):\n self.scoring = scoring\n\n def visit(self, element):\n element.scoring_strategy = self.scoring\n" }, { "alpha_fraction": 0.5891910791397095, "alphanum_fraction": 0.5897209644317627, "avg_line_length": 24.736364364624023, "blob_id": "6bf58ffcf0886474007ef0517478f351c4d658b8", "content_id": "2ca055cfd5fdc540b5886559d312f6f3e9a46afd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5662, "license_type": "no_license", "max_line_length": 156, "num_lines": 220, "path": "/food_project/recipe/models/raw_data_models.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\nfrom functools import partial\n\nfrom pymongo import MongoClient\n\nfrom food_project.util import ( # read_pickle,; column_name,; column_value,; dataframe_from_dict,; dataframe_from_list,; series_from_dict,; save_dataframe,\n comparison,\n list_content_with_matches,\n read_json,\n)\n\n# from food_project.recipe.cluster import ingredient_clusters\n# from food_project.recipe.ingredient import Ingredient , IngredientCluster\n# from food_project.recipe.similarity import get_item_entropy\n\n\nclass QueryModel:\n def _set_data(self, ingredients):\n self.ingredients = ingredients\n\n def get_data(self, *ingredients):\n self._set_data(ingredients)\n return self.ingredients\n\n\n# TODO: Change name to reflect that this is not a db model\n#\n#\n\n\nclass RecipeDBInitiator:\n def __init__(self, uri, uname, pwd):\n self.db_uri = uri\n self.uname = uname\n self.pwd = pwd\n\n def visit(self, element):\n \"\"\"Sets username and password for recipe database and establishes connection to database\"\"\"\n element.username = self.uname\n element.password = self.pwd\n element.uri = f\"mongodb://{self.uname}:{self.pwd}@{self.db_uri}\"\n element._connect()\n\n\nclass RawRecipeModel:\n def __init__(self):\n self.username = None\n self.password = None\n self.uri = None\n self.path = None\n self.key_field = \"recipe_ID\"\n\n def _connect(self):\n client = MongoClient(self.uri)\n db = client[\"food\"]\n self.collection = db[\"recipe\"]\n\n def load(self, id_):\n id_ = str(id_)\n return self.collection.find_one({self.key_field: id_})\n\n def save(self, data):\n id = data[\"_id\"] # TODO: fix according to recipe class\n try:\n self.collection.insert_one(data)\n # print(f\"Inserted recipe id {id}\")\n except:\n # print(f\"Couldn't insert recipe id {id}\")\n pass\n\n def update(self, id_, data):\n \"\"\"data: key value pair\"\"\"\n id_ = str(id_)\n try:\n updated = self.collection.find_one_and_update(\n {self.key_field: id_}, {\"$set\": data}, upsert=True\n )\n # print(f\"Updated recipe id {id_}\")\n\n except:\n # print(f\"Couldn't update {id_}\")\n pass\n return updated\n\n def _retrieve_all(self):\n return self.collection.find()\n\n def retrieve_field(self, field_name):\n coll = self._retrieve_all()\n field_val = lambda x: x.get(field_name, [])\n return [field_val(x) for x in coll]\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass RawRecipeReader:\n # TODO: factor out a recipe class with _id, etc\n def __init__(self):\n self._reset()\n\n def _reset(self):\n self.path = None\n self.data = None\n self._recipe_ids = None\n\n def read(self):\n \"\"\"Returns recipe data in json format\"\"\"\n self.data = read_json(self.path)\n\n @property\n def ready(self):\n return self.data is not None\n\n @property\n def recipe_ids(self):\n if not self._recipe_ids:\n self._recipe_ids = [x[\"recipe_ID\"] for x in self.data]\n return self._recipe_ids\n\n def _filter_by_id(self, recipe_id):\n return [x for x in self.data if x[\"recipe_ID\"] == recipe_id][0]\n\n def recipe_by_id(self, recipe_id):\n x = self._filter_by_id(recipe_id)\n x[\"_id\"] = x[\"recipe_ID\"]\n return x\n\n def accept(self, visitor):\n self._reset()\n visitor.visit(self)\n\n\nclass ProcessedRecipeReader:\n def __init__(self):\n self._reset()\n\n def _reset(self):\n self.path = None\n self.data = None\n self._recipe_id = None\n\n @property\n def ready(self):\n return self.data is not None\n\n def read(self):\n with open(self.path, \"r\") as f:\n self.data = [x.strip() for x in f.readlines()]\n return self.data\n\n @property\n def recipe_id(self):\n if not self._recipe_id:\n self._recipe_id = os.path.basename(self.path).split(\".\")[0]\n return self._recipe_id\n\n def accept(self, visitor):\n self._reset()\n visitor.visit(self)\n\n\nclass RawDataGroup:\n def __init__(self):\n self.path = None\n self.inner_dir = None\n\n def content_path(self):\n if self.inner_dir is not None:\n return os.path.join(self.path, self.inner_dir)\n else:\n return self.path\n\n def process(self):\n return list_content_with_matches(self.content_path(), self.match_cond)\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass RawRecipeGroup(RawDataGroup):\n def __init__(self):\n super().__init__()\n self.inner_dir = \"original_recipes_info\"\n self.suffix = \"json\"\n self.match_cond = comparison(str.endswith, self.suffix)\n\n\nclass ProcessedRecipeGroup(RawDataGroup):\n def __init__(self):\n super().__init__()\n self.suffix = \"out\"\n self.match_cond = comparison(str.endswith, self.suffix)\n\n\nclass RawRecipeImageGroup(RawDataGroup):\n def __init__(self):\n super().__init__()\n self.inner_dir = \"imgs\"\n self.match_cond = comparison(os.path.isdir)\n\n\nclass RawImageGroup(RawDataGroup):\n def __init__(self):\n super().__init__()\n self.suffix = \"jpg\"\n self.match_cond = comparison(str.endswith, self.suffix)\n\n\nclass RecipeFilePathSetter:\n def __init__(self, path):\n self.path = path\n\n def visit(self, element):\n element.path = self.path\n\n\nraw_recipe_model = RawRecipeModel()\nraw_recipe_reader = RawRecipeReader()\n" }, { "alpha_fraction": 0.7539622783660889, "alphanum_fraction": 0.7547169923782349, "avg_line_length": 34.81081008911133, "blob_id": "8b1ff7d05446afc9ea7fc08391d58fb2546c4e3f", "content_id": "686ee20e95853574d8794a64cf2453a986dce78e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1325, "license_type": "no_license", "max_line_length": 81, "num_lines": 37, "path": "/food_project/image_classification/__init__.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom food_project.image_classification.crf.potentials import _clique_potentials\nfrom food_project.image_classification.crf.preprocess import (\n GridImagePredictionCollector, read_image)\nfrom food_project.image_classification.models import (\n ImageClassificationModelInitiator, image_classification_model)\n\n\ndef set_image_predictor(uri, port, route):\n icmi = ImageClassificationModelInitiator(uri, port, route)\n image_classification_model.accept(icmi)\n image_classification_model.ready = True\n return image_classification_model\n\n\ndef predict_image(\n image,\n prediction_format=\"INGR_SERVER\",\n image_classification_model=image_classification_model,\n):\n if not image_classification_model.ready:\n raise Exception(\"Set the image predictor first!\")\n elif prediction_format == \"INGR_SERVER\":\n gipc = GridImagePredictionCollector(image_classification_model)\n return gipc.predict_grid_image(image)\n elif prediction_format == \"INGR\":\n return image_classification_model.get_ingredients(image, with_probs=True)\n\n else:\n return image_classification_model.get_ingredients(image)\n\n\ndef calculate_clique_potentials():\n print(\"Calculating clique potentials\")\n _clique_potentials.get_frequencies()\n print(\"Clique potentials calculated\")\n" }, { "alpha_fraction": 0.5967641472816467, "alphanum_fraction": 0.6023646593093872, "avg_line_length": 25.561983108520508, "blob_id": "8203105f80032b581053b5b8b8b78181cd271b03", "content_id": "ed2e417fbd8d9c633bfc166f4a62b4c771a2af3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3214, "license_type": "no_license", "max_line_length": 86, "num_lines": 121, "path": "/food_project/image_classification/crf/preprocess.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport json\nimport os\nfrom tempfile import NamedTemporaryFile\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\nfrom food_project.image_classification.crf.prediction_class_clusters import \\\n ClassCandidates\n\n\nclass ImageSplitter:\n def __init__(self, n, m):\n\n \"\"\"Args:\n\n n: number of desired images along height\n m: number of desired images along width\n \"\"\"\n\n self.n = n\n self.m = m\n\n def split_image_grid(self, image):\n vertical_splitted = np.split(image, self.n, axis=0)\n horizontal_splitted = [np.split(x, self.m, axis=1) for x in vertical_splitted]\n return horizontal_splitted\n\n def get_image_at_index(self, image, v_index, h_index):\n return image[v_index][h_index]\n\n def set_grid_no(self, v_n, h_n):\n self.n = v_n\n self.m = h_n\n\n\ndef is_image_empty(image):\n return len(np.unique(image)) == 1\n\n\ndef read_image(path):\n return cv2.imread(path)\n\n\ndef arr_to_jpeg(arr, path):\n im = Image.fromarray(arr)\n im.save(path)\n\n\ndef split_image(image, v_n, h_n):\n image_splitter = ImageSplitter(v_n, h_n)\n return image_splitter.split_image_grid(image)\n\n\ndef get_individual_image(splitted_image, v_index, h_index):\n v_n = len(splitted_image)\n h_n = len(splitted_image[0])\n image_splitter = ImageSplitter(v_n, h_n)\n return image_splitter.get_image_at_index(splitted_image, v_index, h_index)\n\n\nclass GridImageCollector:\n def __init__(self, grid_image, v_n, h_n):\n self.grid_image = grid_image\n self._v_n = v_n\n self._h_n = h_n\n\n @property\n def splitted(self):\n return split_image(self.grid_image, self.n_vertical, self.n_horizontal)\n\n def __getitem__(self, idx):\n return get_individual_image(self.splitted, idx[0], idx[1])\n\n @property\n def n_vertical(self):\n return self._v_n\n\n @property\n def n_horizontal(self):\n return self._h_n\n\n\nclass GridImagePredictionCollector:\n def __init__(self, classifier_client):\n self.classifier_client = classifier_client\n self.predictions = None\n self.ready = False\n\n def __getitem__(self, idx):\n if not self.ready:\n raise Exception(\"Individual image predictions not performed yet!\")\n return self.predictions[idx[0]][idx[1]]\n\n def __setitem__(self, idx, value):\n self.predictions[idx[0]][idx[1]] = value\n\n def predict_grid_image(self, grid_image):\n preds = []\n # TODO: don't hardcode 3x3\n grid_image = GridImageCollector(grid_image, 3, 3)\n for i in range(grid_image.n_vertical):\n preds_row = []\n for j in range(grid_image.n_horizontal):\n image = grid_image[i, j]\n if not is_image_empty(image):\n pred = self.classifier_client.get_ingredients(\n image, with_probs=True\n )\n else:\n pred = {\"empty\": 1}\n preds_row.append(ClassCandidates(pred))\n preds.append(preds_row)\n self.predictions = preds\n self.ready = True\n return self.predictions\n\n\n# TODO: Pictures are shifted in the grid!!!\n" }, { "alpha_fraction": 0.7982456088066101, "alphanum_fraction": 0.8070175647735596, "avg_line_length": 21.799999237060547, "blob_id": "e302de4211aeef2a4b321ff06fedd1dda40b7e08", "content_id": "5366e6677c1e635ef74019c7b553a41e05b5e856", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "no_license", "max_line_length": 76, "num_lines": 5, "path": "/food_project/image_classification/crf/recipe_cluster_names.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport json\n\nfrom food_project.recipe.cluster import ingredient_clusters as cluster_names\n" }, { "alpha_fraction": 0.6276299357414246, "alphanum_fraction": 0.6347274780273438, "avg_line_length": 34.8636360168457, "blob_id": "acb78236a723ef3fcec1cabe1ccf91e190db9331", "content_id": "41e3c1905a9bacba5ddf84f6ce97ef9087a9da52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3945, "license_type": "no_license", "max_line_length": 87, "num_lines": 110, "path": "/__main__.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nfrom random import choices\nfrom sys import argv\n\nfrom dotenv import load_dotenv\n\nfrom food_project.image_classification import (image_classification_model,\n set_image_predictor)\nfrom food_project.recipe import (SimilarityController,\n SimilarityControllerVisitor,\n connect_to_database,\n get_processed_ingredients_from_db,\n get_recipe_from_db, get_recipe_ids_from_db,\n populate_db_images, populate_db_processed,\n populate_db_recipes)\nfrom food_project.recipe.matcher import match_score, uniform_score\nfrom food_project.recipe.models import set_recipe_model\nfrom food_project.recipe.recipe import Recipe\nfrom food_project.recipe.similarity import entropy_update\n\nload_dotenv()\n\n\nclassification_type = \"DISH\" # or INGR\n\nuri = os.getenv(\"MONGODB_URI\")\nuname = os.getenv(\"MONGODB_USERNAME\")\npwd = os.getenv(\"MONGODB_PWD\")\nclassification_uri = os.getenv(\"SERVER_URI\")\n\nprefix = classification_type + \"_CLASS_\"\nclassification_port = os.getenv(prefix + \"PORT\")\nclassification_route = os.getenv(prefix + \"ROUTE\")\n\nn_most_similar_recipes = int(os.getenv(\"N_SIMILAR\"))\n\nconnect_to_database(uri, uname, pwd)\n\nset_image_predictor(classification_uri, classification_port, classification_route)\n\nunit_type = argv[1] # can be volume or weight\nset_recipe_model(unit_type)\nsim_ctrl = SimilarityController()\nres = get_processed_ingredients_from_db()\nentropy_update(res)\nsim_ctrl.load_data()\nsim_ctrl_vis = SimilarityControllerVisitor(match_score)\nsim_ctrl_vis.visit(sim_ctrl)\n\nraw_data_dir = \"data/recipes/raw\"\nprocessed_data_dir = \"data/recipes/processed\"\n\n# for directory in os.listdir(raw_data_dir):\n# populate_db_recipes(os.path.join(raw_data_dir, directory))\n# populate_db_images(os.path.join(raw_data_dir, directory))\n# populate_db_processed(os.path.join(processed_data_dir, directory))\n\nall_recipe_ids = get_recipe_ids_from_db()\nhits = []\nrandom_ids = choices(all_recipe_ids, k=10)\nfor recipe_id in random_ids:\n hit = []\n recipe = get_recipe_from_db(int(recipe_id))\n recipe_ingredients = recipe.get(\"processed_ingredients\", \"\")\n print(\"*\" * 10)\n print(recipe_ingredients)\n print(\"*\" * 10)\n for image in recipe[\"images\"]:\n preds = image_classification_model.get_ingredients(image)\n print(\"-\" * 10)\n print(preds)\n print(\"-\" * 10)\n res = sim_ctrl.handle(preds, n_most_similar_recipes)\n recipe_ids = [int(x) for x in res.index.values]\n for i, id_ in enumerate(recipe_ids):\n print(f\"Most similar recipe {i}\")\n ingrs = get_recipe_from_db(id_).get(\"processed_ingredients\", [])\n\n recipe = Recipe(id_, *ingrs)\n\n res = recipe.importance_ranked_ingredients(use_entropy=False)\n print(\"*\" * 20, unit_type.capitalize(), \"only importance\", \"*\" * 20)\n print(res)\n res = recipe.importance_ranked_ingredients()\n print(\"*\" * 20, unit_type.capitalize(), \"and entropy importance\", \"*\" * 20)\n print(res)\n hit.append(int(recipe_id) in recipe_ids)\n print(\"=\" * 20)\n\n\n# hits.append(hit)\n# print(hits)\n# recipe = get_recipe_from_db(277888)\n# print(recipe['name'])\n# print(recipe['processed_ingredients'])\n# print(\"PREDICTIONS\")\n# for image in recipe['images']:\n# preds = image_classification_model.get_ingredients(image)\n# preds = [x.strip() for x in preds.split(',')]\n# res = sim_ctrl.handle(preds, n_most_similar_recipes)\n# recipe_ids = [int(x) for x in res.index.values]\n# for recipe_id in recipe_ids:\n# try:\n# recipe = get_recipe_from_db(recipe_id)\n# print(recipe['name'])\n# print(recipe['processed_ingredients'])\n# except:\n# pass\n" }, { "alpha_fraction": 0.7224669456481934, "alphanum_fraction": 0.7312775254249573, "avg_line_length": 35.953487396240234, "blob_id": "99cf6ebe402ece86d823ea890a655a1f7d0a50cb", "content_id": "545e9f33be076793ab355102db2697a5dd760d55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1589, "license_type": "no_license", "max_line_length": 114, "num_lines": 43, "path": "/main_crf.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# from food_project.recipe.crf import get_recipe_counts_with_both\n# from food_project.image_classification.crf import get_class_clusters\n\n# class_clusters = get_class_clusters()\n# clusters = list(class_clusters.values())\n# get_recipe_counts_with_both(clusters[0], clusters[1])\n\nimport os\n\nfrom dotenv import load_dotenv\n\n# from food_project.image_classification.crf import edge_potentials_dict, make_test_image\nfrom food_project.image_classification import (predict_image,\n set_image_predictor)\nfrom food_project.image_classification.crf.crf_model import CRF\nfrom food_project.image_classification.crf.preprocess import read_image\n\n# print(edge_potentials_dict)\n\n# canvas = make_test_image('data/crf/test_images/raw', 3, write=True, path='data/crf/test_images/compiled/1.jpeg')\nload_dotenv()\nclassification_type = \"INGR\" # or DISH\n\nclassification_uri = os.getenv(\"SERVER_URI\")\nprefix = classification_type + \"_CLASS_\"\nclassification_port = os.getenv(prefix + \"PORT\")\nclassification_route = os.getenv(prefix + \"ROUTE\")\n\n\nset_image_predictor(classification_uri, classification_port, classification_route)\ngrid_image_path = \"data/crf/test_images/compiled/1.jpeg\"\n\n# grid_image = read_image(grid_image_path)\nres = predict_image(grid_image_path, classification_type)\nbreakpoint()\n# consider CRF for cases where only the model is less than 90% confident about its prediction\n# crf = CRF(9, 5)\n# for i in range(3):\n# for j in range(3):\n# crf.add_node(preds[i][j])\n# prbs, bst = crf.get_best_config(threshold=0.9)\n" }, { "alpha_fraction": 0.6288659572601318, "alphanum_fraction": 0.6318114995956421, "avg_line_length": 28.521739959716797, "blob_id": "a916f0e46f1d5ae5add9f1d45a3962db2adea69f", "content_id": "952da66a6374316302c2793c645ee8a906b211f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1358, "license_type": "no_license", "max_line_length": 81, "num_lines": 46, "path": "/food_project/recipe/matcher.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport numpy as np\nimport pandas as pd\n\nfrom food_project.util import match_score, matching_columns, uniform_score\n\n\nclass IngredientQuery:\n def __init__(self, *ingredients):\n self.ingredients = ingredients\n\n def add_ingredient(self, ingredient):\n self.ingredients += ingredient\n\n @property\n def query(self):\n return \"|\".join(self.ingredients)\n\n\nclass IngredientMatcher:\n def __init__(self, recipe_collection, scoring_strategy):\n self.recipe_collection = recipe_collection\n self.match_scoring_strategy = scoring_strategy\n\n def _find_matching_cols(self, query):\n matched_cols = matching_columns(self.recipe_collection, query)\n return matched_cols\n\n def query_mask(self, ingredient_query):\n matched_cols = self._find_matching_cols(ingredient_query.query)\n mask = pd.Series(0, index=self.recipe_collection.columns, dtype=np.float)\n\n matched_cols_ = np.argwhere(matched_cols > 0).reshape(-1)\n n = len(matched_cols_)\n match_scores = list(\n map(\n self.match_scoring_strategy,\n self.recipe_collection.columns[matched_cols],\n [ingredient_query.query] * n,\n )\n )\n\n for i in range(n):\n mask[matched_cols_[i]] = match_scores[i]\n return mask\n" }, { "alpha_fraction": 0.7190082669258118, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 26.923076629638672, "blob_id": "321ecdd795446aaeeaaf19f642b3aaf4c21a9e50", "content_id": "80b17d6ad45d9e729876bfe89a8ecdddb0830727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "no_license", "max_line_length": 76, "num_lines": 13, "path": "/food_project/recipe/crf/__init__.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom food_project.recipe.crf.cluster_bi_occurrences import cluster_df\n\n\ndef get_recipe_counts_containing_ingredients(*ings):\n \"\"\"Returns the number of recipes that contain all ingredients in ings\"\"\"\n ingrs_df = cluster_df[list(ings)]\n return sum(ingrs_df.all(axis=1))\n\n\ndef get_number_of_recipes():\n return cluster_df.shape[0]\n" }, { "alpha_fraction": 0.7801932096481323, "alphanum_fraction": 0.7874395847320557, "avg_line_length": 40.400001525878906, "blob_id": "c6911e071b897af048ae4de9c7f07a80c2b36015", "content_id": "32f4f1cb354fe4192ca1b6ba7f58d0393bf169a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 414, "license_type": "no_license", "max_line_length": 80, "num_lines": 10, "path": "/food_project/recipe/crf/cluster_bi_occurrences.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\"\"\"This module implements functions and classes to calculate pairwise ingredient\nco-occurrences. Ingredients are represented by the cluster names they belong to.\nOnly the classes that will be used in image classification will be counted.\"\"\"\n\nfrom food_project.recipe import load_cluster_df\n\ncluster_df = load_cluster_df(\"data/recipes/cluster_ingredients.df\")\ncluster_df[cluster_df > 0] = 1\n" }, { "alpha_fraction": 0.6538461446762085, "alphanum_fraction": 0.692307710647583, "avg_line_length": 12, "blob_id": "e12b39de67df3887c189252140a4fdde19d3481b", "content_id": "1d6c7fcd2e46f406322daf3658b73d5246b46e33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/food_project/recipe/flat_to_local.py", "repo_name": "zhakguder/FoodProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nre\n" } ]
36
sriveros95/hello_world
https://github.com/sriveros95/hello_world
670a15afcac647cbf7204b069d1699eca61ceaa3
02397004710dace505b09e43d8ca6956b8c882c0
ecf5738506b5db5252e1e7218d3140507667a11d
refs/heads/master
2021-01-01T04:13:12.793399
2016-04-26T16:39:33
2016-04-26T16:39:33
57,054,184
0
0
null
2016-04-25T15:39:37
2016-04-25T15:39:37
2016-04-25T15:56:55
null
[ { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 17, "blob_id": "ad04abfce69b12238bfd4706a363bb9347c620b0", "content_id": "3a39d0f6baec880807b7ec37126d011753cf9a35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 110, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/README.md", "repo_name": "sriveros95/hello_world", "src_encoding": "UTF-8", "text": "# hello_world\nhello_world repository\n\nRepositorio de presentación\nAutor: Santiago Riveros García\nOrigen: Bogotá, Colombia\n" }, { "alpha_fraction": 0.42119088768959045, "alphanum_fraction": 0.441039115190506, "avg_line_length": 24.765625, "blob_id": "2c10a04895ea263b56e55d043dbb630e3e2be1e2", "content_id": "5a97f7f27f06fff1c07366e9b16d4c4d2d85032f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3426, "license_type": "no_license", "max_line_length": 65, "num_lines": 128, "path": "/hankDaBot.py", "repo_name": "sriveros95/hello_world", "src_encoding": "UTF-8", "text": "import xlrd\r\nimport time\r\nimport sys\r\n\r\n## hankDaBot.py \"decimalList.xls\" 0 dec-hex\r\n## xls file column conversion\r\n\r\nfile = sys.argv[1]\r\ncolumn = int(sys.argv[2])\r\nop = sys.argv[3]\r\n\r\n\r\nif sys.argv[1] == \"dec-hex\":\r\n print(\"Convertire Decimales a Hexadecimal\")\r\n \r\ndef dec_to_hex(decimalNum):\r\n try:\r\n prueba = decimalNum + 1\r\n except ValueError:\r\n print(\"Not a Decimal!!!\")\r\n return -1\r\n hexa = []\r\n stop = 0\r\n n = 0\r\n while stop == 0:\r\n if(int(decimalNum)>=(16**n)):\r\n n = n + 1\r\n else:\r\n stop = 1\r\n n = n - 1\r\n actual = decimalNum\r\n while n >= 0:\r\n hex_element = actual//(16**n)\r\n if((hex_element >= 0) and (hex_element <= 9)):\r\n hexa.append(actual//(16**n)) \r\n elif hex_element == 10:\r\n hexa.append('A')\r\n elif hex_element == 11:\r\n hexa.append('B')\r\n elif hex_element == 12:\r\n hexa.append('C')\r\n elif hex_element == 13:\r\n hexa.append('D')\r\n elif hex_element == 14:\r\n hexa.append('E')\r\n elif hex_element == 15:\r\n hexa.append('F')\r\n else:\r\n return -1\r\n actual = actual % (16**n)\r\n n = n - 1\r\n hex_string = ''.join(str(v) for v in hexa)\r\n\r\n print(\" hexadecimal es : \", hex_string)\r\n\r\ndef dec_to_oct(decimalNum):\r\n try:\r\n prueba = decimalNum + 1\r\n except ValueError:\r\n print(\"Not a Decimal!!!\")\r\n return -1\r\n octal = []\r\n stop = 0\r\n n = 0\r\n while stop == 0:\r\n if(int(decimalNum)>=(8**n)):\r\n n = n + 1\r\n else:\r\n stop = 1\r\n n = n - 1\r\n actual = decimalNum\r\n while n >= 0:\r\n octal_element = actual//(8**n)\r\n if((octal_element >= 0) and (octal_element <= 8)):\r\n octal.append(actual//(8**n)) \r\n else:\r\n return -1\r\n actual = actual % (8**n)\r\n n = n - 1\r\n octal_string = ''.join(str(v) for v in octal)\r\n\r\n print(\" octal es : \", octal_string)\r\n\r\n\r\nworkbook = xlrd.open_workbook(file)\r\nworksheet = workbook.sheet_by_index(0)\r\ni = 0\r\nstop = 0\r\nif op == \"dec-hex\":\r\n while(stop == 0):\r\n try:\r\n current_cell = int(worksheet.cell(i, column).value)\r\n if current_cell == xlrd.empty_cell.value:\r\n stop = 1\r\n else:\r\n print(current_cell, end = \"\")\r\n dec_to_hex(current_cell)\r\n i = i + 1\r\n \r\n except IndexError:\r\n stop = 1\r\n except ValueError:\r\n print(\"! \", worksheet.cell(i, column).value, end='')\r\n print(\" is not a Decimal!!!\")\r\n i = i + 1\r\n \r\n print(\"Bye bye!\")\r\n\r\nelif op == \"dec-oct\":\r\n while(stop == 0):\r\n try:\r\n current_cell = int(worksheet.cell(i, column).value)\r\n if current_cell == xlrd.empty_cell.value:\r\n stop = 1\r\n else:\r\n print(current_cell, end = \"\")\r\n dec_to_oct(current_cell)\r\n i = i + 1\r\n \r\n except IndexError:\r\n stop = 1\r\n except ValueError:\r\n print(\"! \", worksheet.cell(i, column).value, end='')\r\n print(\" is not a Decimal!!!\")\r\n i = i + 1\r\n \r\n print(\"Bye bye!\")\r\n pass\r\n" } ]
2
Rongpeng-Lin/A-DA-GAN-architecture
https://github.com/Rongpeng-Lin/A-DA-GAN-architecture
54e68cd3f386ac039bf157fce3f68629e7a3ea41
e8669a6a6fabe29860fab96d8559084065fdd82f
20cc44836ed7f841255648fab3d7683a924195d8
refs/heads/master
2020-03-31T02:00:45.082537
2018-10-06T05:19:00
2018-10-06T05:19:00
151,804,350
16
6
null
null
null
null
null
[ { "alpha_fraction": 0.49664804339408875, "alphanum_fraction": 0.5280447006225586, "avg_line_length": 44.43147277832031, "blob_id": "7af2b63498a457f32040710a035eed9f27ccb6c0", "content_id": "29efa25fc7b8d6fcf7e137cb9db7c76081337b7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8968, "license_type": "no_license", "max_line_length": 150, "num_lines": 197, "path": "/model.py", "repo_name": "Rongpeng-Lin/A-DA-GAN-architecture", "src_encoding": "UTF-8", "text": "from utlis import *\nfrom ops import *\nimport tensorflow as tf\nimport numpy as np\nimport cv2 as cv\nimport math,os,h5py\n\nclass DAE_GAN:\n def __init__(self,batch,epoch,im_size,hw_size,k,alpa,beta,im_dir,save_dir,saveS_dir,saveT_dir):\n self.batch = batch\n self.epoch = epoch\n self.im_size = im_size\n self.hw_size = hw_size\n self.positive_dir = [im_dir+'positive/'+name for name in os.listdir(im_dir+'positive')]\n self.negtive_dir = [im_dir+'negtive/'+name for name in os.listdir(im_dir+'negtive')]\n self.svhnMat = h5py.File(im_dir+'digitStruct.mat', mode='r')\n self.first = 64\n self.k = k\n self.alpa = alpa\n self.beta = beta\n self.one_ep_iter = One_ep_Iter(im_dir,batch)\n self.S = tf.placeholder(tf.float32,[None,im_size,im_size,3],'S')\n self.T = tf.placeholder(tf.float32,[None,im_size,im_size,3],'T')\n self.S_label = tf.placeholder(tf.float32,[None,10],'S_label')\n self.T_label = tf.placeholder(tf.float32,[None,10],'T_label')\n self.save_dir = save_dir\n self.saveS = saveS_dir\n self.saveT = saveT_dir\n\n def Encoder(self,x,reuse):\n with tf.variable_scope('encoder',reuse=reuse): \n conv1 = conv('conv1',x,3*3,2,self.first,True)\n bn1 = BN('bn1',conv1)\n relu1 = lrelu('relu1',bn1)\n \n conv2 = conv('conv2',relu1,3*3,2,int(2*self.first),True)\n bn2 = BN('bn2',conv2)\n relu2 = lrelu('relu2',bn2)\n \n conv3 = conv('conv3',relu2,3*3,2,int(4*self.first),True)\n bn3 = BN('bn3',conv3)\n relu3 = lrelu('relu3',bn3)\n \n conv4 = conv('conv4',relu3,3*3,2,int(8*self.first),True)\n bn4 = BN('bn4',conv4)\n relu4 = lrelu('relu4',bn4)\n return relu4\n \n def F(self,features,k):\n with tf.variable_scope('f_location'):\n cha = [i.value for i in features.get_shape()][-1]\n \n conv1 = conv('conv1',features,3*3,2,int(2*cha),True)\n bn1 = BN('bn1',conv1)\n relu1 = lrelu('relu1',bn1)\n \n conv2 = conv('conv2',relu1,3*3,2,int(4*cha),True)\n bn2 = BN('bn2',conv2)\n relu2 = lrelu('relu2',bn2)\n \n out_xy = FC_location('fc1',relu2,2,self.im_size,self.hw_size)\n mask = get_mask(out_xy,self.hw_size,self.hw_size,self.im_size,k,self.batch)\n return mask\n \n def GAN_G(self,x,reuse):\n with tf.variable_scope('G_net',reuse=reuse): \n\n conv_trans1 = conv_trans('conv_trans1',x,5*5,1,256,True) \n Lrelu1 = lrelu('Lrelu1',conv_trans1)\n \n conv_trans2 = conv_trans('conv_trans2',Lrelu1,5*5,1,128,True)\n bn2 = BN('bn2',conv_trans2)\n Lrelu2 = lrelu('Lrelu2',bn2)\n \n conv_trans3 = conv_trans('conv_trans3',Lrelu2,5*5,1,64,True)\n bn3 = BN('bn3',conv_trans3)\n Lrelu3 = lrelu('Lrelu3',bn3)\n \n conv_trans4 = conv_trans('conv_trans4',Lrelu3,5*5,1,3,True)\n Lrelu4 = tanh('Lrelu4',conv_trans4)\n return Lrelu4\n\n def GAN_D(self,name,x,reuse):\n with tf.variable_scope(name,reuse=reuse):\n conv1 = conv('conv1',x,3*3,2,64,True)\n bn1 = BN('bn1',conv1)\n relu1 = lrelu('relu1',bn1)\n \n conv2 = conv('conv2',relu1,3*3,2,128,True)\n bn2 = BN('bn2',conv2)\n relu2 = lrelu('relu2',bn2)\n \n conv3 = conv('conv3',relu2,3*3,2,256,True)\n bn3 = BN('bn3',conv3)\n relu3 = lrelu('relu3',bn3)\n \n conv4 = conv('conv4',relu3,3*3,2,512,True)\n bn4 = BN('bn4',conv4)\n relu4 = lrelu('relu4',bn4)\n \n D_out = FC('fc1',relu4,1)\n return D_out\n \n def DAE(self,x,reuse):\n with tf.variable_scope('DAE',reuse=reuse):\n encode_x = self.Encoder(x,reuse)\n mask = self.F(encode_x,self.k)\n x_mask = x*mask\n encode_mask_x = self.Encoder(x_mask,True)\n \n probs = resnet_classifer('classsifer',encode_mask_x)\n return encode_mask_x,probs\n\n def forward(self):\n self.s_DAE,self.s_out_label = self.DAE(self.S,False)\n self.t_DAE,self.t_out_label = self.DAE(self.T,True)\n self.s_pie = self.GAN_G(self.s_DAE,False)\n self.t_pie = self.GAN_G(self.t_DAE,True)\n \n self.t_D1 = self.GAN_D('D2',self.T,False)\n self.t_pie_D = self.GAN_D('D2',self.t_pie,True)\n \n self.t_D2 = self.GAN_D('D1',self.T,False)\n self.s_pie_D = self.GAN_D('D1',self.s_pie,True)\n \n self.s_pie_DAE,_ = self.DAE(self.s_pie,True)\n self.t_pie_DAE,_ = self.DAE(self.t_pie,True)\n \n def train(self):\n self.forward()\n# Loss for G and DAE:\n# 1、 Loss of s_DAE and s_pie_DAE:\n Lcst = tf.reduce_mean(tf.abs(self.s_DAE-self.s_pie_DAE)) # L1范数\n# 2、 Loss of t_DAE and t_pie_DAE:\n Lsym = tf.reduce_mean(tf.abs(self.t_DAE-self.t_pie_DAE)) # L1范数\n# 3、Make D2 judge t_pie as true: \n loss_G_DAE1 = tf.reduce_mean(-1*tf.log(self.t_pie_D))\n# 4、Make D1 judge s_pie as true:\n loss_G_DAE2 = tf.reduce_mean(-1*tf.log(self.s_pie_D))\n# 5、Loss caused by classification: cross entropy, this alone corresponds to DAE: \n cross_entroy = tf.reduce_mean(tf.reduce_mean((-1)*tf.log(self.s_out_label)*self.S_label + (-1)*tf.log(1-self.s_out_label)*(1-self.S_label),1))\n \n self.DAE_G_loss = self.alpa*Lcst + self.beta*Lsym + loss_G_DAE1 + loss_G_DAE2 + cross_entroy\n \n self.D1_loss = tf.reduce_mean((-1)*tf.log(self.t_D2) + (-1)*tf.log(1-self.s_pie_D))\n self.D2_loss = tf.reduce_mean((-1)*tf.log(self.t_D2) + (-1)*tf.log(1-self.t_pie_D))\n DAE_G_vars = [var for var in tf.trainable_variables() if 'DAE' in var.name or 'G_net' in var.name]\n D1_vars = [var for var in tf.trainable_variables() if 'D1' in var.name]\n D2_vars = [var for var in tf.trainable_variables() if 'D2' in var.name]\n optim_DAE_G = tf.train.AdamOptimizer().minimize(self.DAE_G_loss,var_list=DAE_G_vars) \n optim_D1 = tf.train.AdamOptimizer().minimize(self.D1_loss,var_list=D1_vars) \n optim_D2 = tf.train.AdamOptimizer().minimize(self.D2_loss,var_list=D2_vars) \n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n graph = tf.summary.FileWriter(self.save_dir,graph=sess.graph)\n Saver = tf.train.Saver(max_to_keep=20)\n \n savedir = self.save_dir+'model.ckpt'\n for i in range(self.epoch):\n for j in range(self.one_ep_iter):\n ims_po,labels_po = get_im_label(j, self.batch, self.positive_dir, self.svhnMat)\n ims_neg,labels_neg = get_im_label(j, self.batch, self.negtive_dir, self.svhnMat)\n \n fed_dict={self.S:ims_po,self.S_label:labels_po,self.T:ims_neg,self.T_label:labels_neg}\n \n _,LossD1 = sess.run([optim_D1,self.D1_loss],feed_dict=fed_dict)\n print('LossD1: ',LossD1)\n \n _,LossD2 = sess.run([optim_D2,self.D2_loss],feed_dict=fed_dict)\n print('LossD2: ',LossD2)\n \n _,S_sample,T_sample,LossDAE_G = sess.run([optim_DAE_G,self.s_pie,self.t_pie,self.DAE_G_loss],feed_dict=fed_dict)\n print('LossDAE_G: ',LossDAE_G)\n \n save_im(S_sample, self.saveS, i, j, self.batch)\n save_im(T_sample, self.saveT, i, j, self.batch)\n \n step = int(i*self.epoch + j)\n Saver.save(sess,savedir,global_step=step)\n print('save_success at: ',step)\n \n def load(self,load_dir,raw_im_dir,save_im_dir):\n self.forward()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n graph = tf.summary.FileWriter(self.save_dir,graph=sess.graph)\n Saver = tf.train.Saver()\n Saver.restore(sess,load_dir)\n for i,im_name in enumerate(os.listdir(raw_im_dir)):\n im_bgr = cv.resize(cv.imread(raw_im_dir+im_name),(64,64),interpolation=cv.INTER_CUBIC)\n im_rgb_unpro = im_bgr[:,:,::-1]\n im_rgb = np.expand_dims(((im_rgb_unpro/255)-0.5)*2,0)\n# fed_dict={self.S:ims_po,self.S_label:labels_po}\n fed_dict={self.S:im_rgb}\n s_tar = sess.run(self.s_pie,feed_dict=fed_dict)\n Save_load(s_tar,i,save_im_dir)\n print('save at: ',i)\n" }, { "alpha_fraction": 0.6883116960525513, "alphanum_fraction": 0.6910946369171143, "avg_line_length": 43.91666793823242, "blob_id": "5b576e37a13935e37389886a54a7cb4f0cd44905", "content_id": "267646fa777b7e6867f52f4360adf4adecacafb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 169, "num_lines": 24, "path": "/Data.py", "repo_name": "Rongpeng-Lin/A-DA-GAN-architecture", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport cv2 as cv\nimport math,os,h5py,argparse,sys\nfrom Create_data import clear_and_create\n\ndef main(args):\n if args.op_type=='clear':\n clear_and_create.clear_data(args.im_dir)\n return True\n else:\n clear_and_create.create_data(args.raw_dir,args.if_clip)\n return True \n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--op_type', type=str, help='Choose to clear data or create positive and negative samples,clear or create.', default=\"clear\")\n parser.add_argument('--im_dir', type=str, help='Path to the image folder.', default=\"D:/SVHN_dataset/train/\")\n parser.add_argument('--raw_dir', type=str, help='The path that has been cleared.', default=\"D:/SVHN_dataset/train/\")\n parser.add_argument('--if_clip', type=bool,help='Whether to divide the picture into two parts (the training set will be reduced after segmentation).', default=False)\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n" }, { "alpha_fraction": 0.5985815525054932, "alphanum_fraction": 0.7186761498451233, "avg_line_length": 140, "blob_id": "6e25957d394b7ae9fe95b041b54810c638e2519b", "content_id": "fe7ba6e45fe231716bf255404635bd855b7638b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2115, "license_type": "no_license", "max_line_length": 438, "num_lines": 15, "path": "/README.md", "repo_name": "Rongpeng-Lin/A-DA-GAN-architecture", "src_encoding": "UTF-8", "text": "# A-DA-GAN-architecture\n## A basic architecture of \"DA-GAN: Instance-level Image Translation by Deep Attention Generative Adversarial Networks\"<br>\n&#8195;This is a basic architecture implementation, and the structure of the article is outlined below:<br>&#8195;&#8195;1.&#8195;The image is encoded using an encoder (convolutional architecture).<br>\n&#8195;&#8195;2.&#8195;Use another set of convolutions combined with a full join to generate an attention area (similar to the border of the target detection) and perform a masking operation on the original image.<br>\n&#8195;&#8195;3.&#8195;The mask operation does not use the 01 mask, but instead uses sigmoid instead of direction propagation, making the change more 'soft'.<br>\n## how to use<br>\n&#8195;1.&#8195;There are some samples marked incorrectly in the svhn data set, first clean the sample:<br>\n&#8195;&#8195;python&#8195;D:\\SVHN_dataset\\train\\DAE_GAN\\Data.py&#8195;--op_type=\"clear\"&#8195;--im_dir=\"D:/SVHN_dataset/train/forcmd/\"&#8195;--raw_dir=\"D:/SVHN_dataset/train/forcmd/\"&#8195;--if_clip=False<br>\n&#8195;2.&#8195;Create positive and negative sample data:<br>\n&#8195;&#8195;python&#8195;D:\\SVHN_dataset\\train\\DAE_GAN\\Data.py&#8195;--op_type=\"create\"&#8195;--im_dir=\"D:/SVHN_dataset/train/forcmd/\"&#8195;--raw_dir=\"D:/SVHN_dataset/train/forcmd/\"&#8195;--if_clip=False<br>\n&#8195;3.&#8195;Perform training or loading:<br>\n&#8195;&#8195;Train:<br>\n&#8195;&#8195;&#8195;python&#8195;D:\\SVHN_dataset\\train\\DAE_GAN\\train.py&#8195;--is_train=\"train\"&#8195;--im_size=64&#8195;--batch=2&#8195;--epoch=100&#8195;--hw_size=30&#8195;--k=2e5&#8195;--alpa=0.9&#8195;--beta=0.5&#8195;--im_dir=\"D:/SVHN_dataset/train/forcmd/\"&#8195;--save_dir=\"D:/SVHN_dataset/train/forcmd/ckpt/\"&#8195;--saveS_dir=\"D:/SVHN_dataset/train/forcmd/SampleS/\"&#8195;--saveT_dir=\"D:/SVHN_dataset/train/forcmd/SampleT/\"<br>\n&#8195;&#8195;Test:<br>\n&#8195;&#8195;&#8195;python&#8195;D:\\SVHN_dataset\\train\\DAE_GAN\\train.py&#8195;--is_train=\"test\"&#8195;--load_dir=\"D:/SVHN_dataset/train/ckpt/\"&#8195;--raw_im_dir=\"D:/SVHN_dataset/test\"&#8195;--save_im_dir=\"D:/SVHN_dataset/test_save/\"<br>\n" }, { "alpha_fraction": 0.5632287263870239, "alphanum_fraction": 0.5991031527519226, "avg_line_length": 34.935482025146484, "blob_id": "851d81112e4bd3fb0eaf2c69f76edf4f4305ff08", "content_id": "9212bf28407c7be396f859270f4f8f7b7b9775ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1115, "license_type": "no_license", "max_line_length": 126, "num_lines": 31, "path": "/utlis.py", "repo_name": "Rongpeng-Lin/A-DA-GAN-architecture", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport cv2 as cv\nimport math,os,h5py,argparse,sys\n\ndef get_im_label(idx,batch,Dir,svhnMat):\n im_zeros = np.zeros([batch,64,64,3],np.float32)\n label_zeros = np.zeros([batch,10],np.float32)\n start = int(idx*batch)\n end = start+batch\n dirs = Dir[start:end]\n print('dirs: ',dirs)\n for i,Dir in enumerate(dirs):\n im_bgr = cv.resize(cv.imread(Dir),(64,64),interpolation=cv.INTER_CUBIC)\n im_rgb_unpro = im_bgr[:,:,::-1]\n im_rgb = ((im_rgb_unpro/255)-0.5)*2\n im_zeros[i,:,:,:] = im_rgb\n label_zeros[i,:] = im_dir2label(Dir,svhnMat)\n return im_zeros,label_zeros\n \ndef im_dir2label(a_dir,svhnMat):\n label = np.zeros([10,],np.float32)\n im_name = a_dir.split('/')[-1]\n im_num = int(im_name.split('.')[0])\n \n item = svhnMat['digitStruct']['bbox'][im_num-1].item()\n attr = svhnMat[item]['label']\n values = [svhnMat[attr.value[i].item()].value[0][0] for i in range(len(attr))] if len(attr) > 1 else [attr.value[0][0]] \n for value in values:\n label[int(value)] = 1.0\n return label\n\n" }, { "alpha_fraction": 0.56333988904953, "alphanum_fraction": 0.5889625549316406, "avg_line_length": 39.15107727050781, "blob_id": "e334add755c8a67847546de0ec8fac6de4eaf141", "content_id": "e9b7c01c8b154ebdbb52d12da3ab8cd773da11c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5583, "license_type": "no_license", "max_line_length": 108, "num_lines": 139, "path": "/ops.py", "repo_name": "Rongpeng-Lin/A-DA-GAN-architecture", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport cv2 as cv\nimport math,os,h5py,argparse,sys\n\ndef conv(name,x,kers,s,outs,pad):\n with tf.variable_scope(name):\n ker = int(math.sqrt(kers))\n shape = [i.value for i in x.get_shape()]\n w = tf.get_variable('w',\n [ker,ker,shape[-1],outs],\n tf.float32,\n tf.contrib.layers.xavier_initializer_conv2d())\n b = tf.get_variable('b',[outs],tf.float32,tf.constant_initializer(0.))\n padd = \"SAME\" if pad else \"VALID\"\n x_conv = tf.nn.conv2d(x,w,[1,s,s,1],padd) + b\n return x_conv\n\ndef res_block(name,x):\n with tf.variable_scope(name):\n shape = [i.value for i in x.get_shape()]\n conv1 = conv(name+'_conv1',x,3*3,shape[-1],1,True)\n bn1 = tf.nn.relu(tf.contrib.layers.batch_norm(conv1,scale=True,updates_collections=None)) \n conv2 = conv(name+'_conv2',bn1,3*3,shape[-1],1,True)\n bn2 = tf.contrib.layers.batch_norm(conv2,scale=True,updates_collections=None)\n return tf.nn.relu(bn2+x) \n \ndef conv_trans(name,x,sizes,s,outs,ifpad):\n with tf.variable_scope(name):\n ker = int(math.sqrt(sizes))\n shape = [i.value for i in x.get_shape()]\n ins = shape[-1]//4\n w = tf.get_variable('w',[ker,ker,ins,outs],tf.float32,tf.contrib.layers.xavier_initializer_conv2d())\n b = tf.get_variable('b',[outs],tf.float32,tf.constant_initializer(0.))\n pad = \"SAME\" if ifpad else \"VALID\"\n x_conv = tf.nn.conv2d(tf.depth_to_space(x,2),w,[1,s,s,1],pad)+b\n return x_conv\n \ndef lrelu(name,x):\n with tf.variable_scope(name):\n return tf.nn.relu(x)\n\ndef tanh(name,x):\n with tf.variable_scope(name):\n return tf.nn.tanh(x)\n \ndef BN(name,x):\n with tf.variable_scope(name):\n return tf.contrib.layers.batch_norm(x,scale=True,updates_collections=None)\n \ndef FC_location(name,x,outs,im_size,hw_size):\n with tf.variable_scope(name):\n raw_shape = [i.value for i in x.get_shape()]\n new_shape = int(raw_shape[1]*raw_shape[2]*raw_shape[3])\n x_resh = tf.reshape(x,[-1,new_shape])\n w = tf.get_variable('w',[new_shape,outs],tf.float32,tf.contrib.layers.xavier_initializer())\n b = tf.get_variable('b',[1,outs],tf.float32,tf.constant_initializer(0.))\n fc_ = tf.matmul(x_resh,w)+b\n # Add a range limit to the position coordinates while making the gradient softer.\n xy_constraint = tf.nn.sigmoid(fc_)*(im_size-hw_size)\n return tf.cast(tf.round(xy_constraint),tf.int32)\n\ndef get_constant(im_size):\n zero_x = np.zeros([im_size,im_size],np.float32)\n zero_y = np.zeros([im_size,im_size],np.float32)\n for i in range(im_size):\n zero_x[:,i] = i+1 \n zero_y[i,:] = i+1\n return zero_x,zero_y\n\ndef sigmoid_mask(x,k):\n k = int(k)\n X = tf.cast(x,tf.float32)\n return 1/(1+tf.exp(-1*k*X))\n \ndef get_mask(xy,reigon_w,reigon_h,im_size,k,B): \n # xy: [batch, 2]: coordinates\n # reigon_w, reigon_h: size of the area\n # im_size: Image size for generating the original X\n # k: The growth factor of the sigmoid function\n with tf.variable_scope('Mask'):\n x_left = tf.expand_dims(tf.expand_dims(tf.expand_dims(xy[:,0],1),2),3)\n x_right = tf.expand_dims(tf.expand_dims(tf.expand_dims(xy[:,0]+reigon_w,1),2),3)\n y_top = tf.expand_dims(tf.expand_dims(tf.expand_dims(xy[:,1],1),2),3)\n y_bottom = tf.expand_dims(tf.expand_dims(tf.expand_dims(xy[:,1]+reigon_h,1),2),3)\n x_value,y_value = get_constant(im_size)\n x_constant = np.tile(np.expand_dims(np.expand_dims(x_value,0),3),[B,1,1,1])\n y_constant = np.tile(np.expand_dims(np.expand_dims(y_value,0),3),[B,1,1,1])\n A = sigmoid_mask(x_constant-x_left,k)\n C = sigmoid_mask(x_constant-x_right,k)\n D = sigmoid_mask(y_constant-y_top,k)\n E = sigmoid_mask(y_constant-y_bottom,k)\n return (A-C)*(D-E)\n\ndef FC(name,x,outs):\n with tf.variable_scope(name):\n shape = [i.value for i in x.get_shape()]\n size = int(shape[1]*shape[2]*shape[3])\n x_reshape = tf.reshape(x,[-1,size])\n w = tf.get_variable('w',[size,outs],tf.float32,tf.contrib.layers.xavier_initializer())\n b = tf.get_variable('b',[1,outs],tf.float32,tf.constant_initializer(0.))\n return tf.nn.sigmoid(tf.matmul(x_reshape,w)+b)\n \ndef resnet_classifer(name,x): # x: batch,4,4,512\n with tf.variable_scope(name):\n res1 = res_block('res1',x)\n res2 = res_block('res2',res1)\n res3 = res_block('res3',res2)\n res4 = res_block('res4',res3)\n res5 = res_block('res5',res4)\n res6 = res_block('res6',res5)\n res7 = res_block('res7',res6)\n probs = FC('probs',res7,10)\n return probs\n\ndef One_ep_Iter(im_dir,batch):\n num_ims = min(len(os.listdir(im_dir+'positive')),len(os.listdir(im_dir+'negtive')))\n return num_ims//batch\n\ndef get_shape(x):\n L = [i.value for i in x.get_shape()]\n return L\n\ndef save_im(sample_im,save_dir,cur_ep,cur_batch,batch):\n for i in range(batch):\n im_S = sample_im[i,:,:,:]\n im_s = (im_S[:,:,::-1]+1)*127.5\n s_name = 'ep'+str(cur_ep)+'_sample'+str(cur_batch)+'_batch'+str(i)+'.png'\n cv.imwrite(save_dir+s_name,im_s)\n return True\n\ndef Save_load(ims,num,save_dir):\n b = np.shape(ims)[0]\n for i in range(b):\n im_S = ims[i,:,:,:]\n im_s = (im_S[:,:,::-1]+1)*127.5\n name = 'num_'+str(num)+'.png'\n cv.imwrite(save_dir+name,im_s)\n return True\n" }, { "alpha_fraction": 0.5002949833869934, "alphanum_fraction": 0.5115044116973877, "avg_line_length": 37.522727966308594, "blob_id": "6a316d4bf0a1f030ae9ec6ae5682fec58e8cacb9", "content_id": "19dd3b692c8a5d864ced292c273b24b78305b3c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1695, "license_type": "no_license", "max_line_length": 130, "num_lines": 44, "path": "/Create_data/clear_and_create.py", "repo_name": "Rongpeng-Lin/A-DA-GAN-architecture", "src_encoding": "UTF-8", "text": "import os,h5py\nimport numpy as np\nimport cv2 as cv\n\ndef clear_data(im_dir):\n name = im_dir+'digitStruct.mat'\n svhnMat = h5py.File(name=name, mode='r')\n im_names = [Im_name for Im_name in os.listdir(im_dir) if Im_name.split('.')[-1]=='png'] \n for im_name in im_names:\n im_num = int(im_name.split('.')[0])\n item = svhnMat['digitStruct']['bbox'][im_num-1].item()\n attr = svhnMat[item]['label']\n values = [svhnMat[attr.value[i].item()].value[0][0] for i in range(len(attr))] if len(attr) > 1 else [attr.value[0][0]] \n for value in values:\n if value>=10.0:\n os.remove(im_dir+im_name)\n print('im is: ',im_name)\n print('value is: ',value)\n break\n return True\n\ndef create_data(raw_dir,if_clip):\n positive = raw_dir+'positive'\n negtive = raw_dir+'negtive'\n for new_dir in [positive,negtive]:\n os.makedirs(new_dir) \n for im_name in os.listdir(raw_dir):\n if im_name.split('.')[-1]=='png':\n im = cv.imread(raw_dir+im_name)\n if if_clip:\n if_flip = np.random.uniform()\n if if_flip>0.5:\n im_flip = cv.flip(im,1,dst=None)\n cv.imwrite(negtive+'/'+im_name,im_flip)\n os.remove(raw_dir+im_name)\n else:\n cv.imwrite(positive+'/'+im_name,im)\n os.remove(raw_dir+im_name)\n else:\n cv.imwrite(positive+'/'+im_name,im)\n im_flip = cv.flip(im,1,dst=None)\n cv.imwrite(negtive+'/'+im_name,im_flip)\n os.remove(raw_dir+im_name)\n return True\n" }, { "alpha_fraction": 0.6699774265289307, "alphanum_fraction": 0.6790067553520203, "avg_line_length": 60.52777862548828, "blob_id": "c6af7e98d5fd4349e46b8273dd03961cda9ee2ef", "content_id": "79f9442f1db3b684d2b3dc4c2b8d15a19fc83690", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2215, "license_type": "no_license", "max_line_length": 163, "num_lines": 36, "path": "/train.py", "repo_name": "Rongpeng-Lin/A-DA-GAN-architecture", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport cv2 as cv\nimport math,os,h5py,argparse,sys\nfrom model import *\n\ndef main(args):\n dae_gan = DAE_GAN(args.batch, args.epoch, args.im_size, args.hw_size, args.k, args.alpa, args.beta, args.im_dir, args.save_dir, args.saveS_dir, args.saveT_dir)\n if args.is_train=='train':\n dae_gan.train()\n else:\n dae_gan.load(args.load_dir, args.raw_im_dir, args.save_im_dir)\n return True \n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--is_train', type=str, help='Training or loading.', default=\"train\") \n parser.add_argument('--load_dir', type=str, help='Load model checkpoint.', default=\"D:/SVHN_dataset/train/ckpt/\")\n parser.add_argument('--raw_im_dir', type=str, help='Image to test.', default=\"D:/SVHN_dataset/test\")\n parser.add_argument('--save_im_dir', type=str, help='Save sample images dir.', default=\"D:/SVHN_dataset/test_save/\")\n\n parser.add_argument('--im_size', type=int, help='Image size (height, width) in pixels.', default=64)\n parser.add_argument('--batch', type=int, help='batch size.', default=64)\n parser.add_argument('--epoch', type=int, help='Number of training cyclese.', default=100)\n parser.add_argument('--hw_size', type=int, help='The size of the attention area removed.', default=30)\n parser.add_argument('--k', type=float, help='Gain coefficient of sigmoid when generating mask.', default=int(2e2))\n parser.add_argument('--alpa', type=float, help='Error weight_1.', default=0.4)\n parser.add_argument('--beta', type=float, help='Error weight_2.', default=0.6)\n parser.add_argument('--im_dir', type=str, help='Path to the image folder.', default=\"D:/SVHN_dataset/train/\")\n parser.add_argument('--save_dir', type=str, help='Model save path.', default=\"D:/SVHN_dataset/train/ckpt/\")\n parser.add_argument('--saveS_dir', type=str, help='The path that has been cleared.', default=\"D:/SVHN_dataset/train/SampleS/\")\n parser.add_argument('--saveT_dir', type=str, help='Source image save path.', default=\"D:/SVHN_dataset/train/SampleT/\")\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n" } ]
7
jero98772/Jane_assist
https://github.com/jero98772/Jane_assist
e39f12367b9d11ba54ea232114796db1358e00a0
521dd67c125a35e9ac93b0d65904194d15372363
cea8f857233e131ace960b157c0a068b5d9433ee
refs/heads/main
2023-01-30T14:57:26.359643
2020-12-12T01:34:55
2020-12-12T01:34:55
320,164,183
1
0
null
2020-12-10T04:58:31
2020-12-10T03:05:44
2020-12-10T03:05:42
null
[ { "alpha_fraction": 0.7459016442298889, "alphanum_fraction": 0.7475410103797913, "avg_line_length": 25.39130401611328, "blob_id": "eaa724757f4d1f458755649e74e917697685fafb", "content_id": "e4c0d5a3159377a18d80fcc3f147b28646a29544", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 610, "license_type": "no_license", "max_line_length": 154, "num_lines": 23, "path": "/README.md", "repo_name": "jero98772/Jane_assist", "src_encoding": "UTF-8", "text": "# Jane_assist\nBased on jarves for python and modified to send text messages through kdeconnect-cli\n### run and talk\n python3 Jane.py\n### dependencies\nPyAudio\n\n\tpip install PyAudio\n\nor\nthis work for me\n\n conda install PyAudio\ngtts\n\n pip install gtts\nSpeechRecognition\n\n\tpip install SpeechRecognition\n### settings\nyou can change your username and Jane name you can see the current name in config.txt if you dont see config.txt the name is \"jane\" and your name is \"tim\"\n\nyou can customize speaking say name+\" configuration\" or changes the parameters in the text file called \"config.txt\" \n\n\n" }, { "alpha_fraction": 0.5670223236083984, "alphanum_fraction": 0.5740246772766113, "avg_line_length": 29.602041244506836, "blob_id": "d858880602a4341ac8686d6d1e222abd06ef8112", "content_id": "3ecc8c53cd24fe13a8be9b6827f8eb253231e49c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5998, "license_type": "no_license", "max_line_length": 106, "num_lines": 196, "path": "/Jane.py", "repo_name": "jero98772/Jane_assist", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# Requires PyAudio and PySpeech.\n# Requires a contacts.txt file with each line containing a name and phone number seperated by a space\nimport speech_recognition as sr\nimport time\nimport os\nfrom gtts import gTTS\nimport webbrowser\ndef readtxt(name):\n\tcontent = []\n\twith open(name+\".txt\", 'r') as file:\n\t\tfor i in file.readlines():\n\t\t\tcontent.append(str(i).replace(\"\\n\",\"\"))\t\n\treturn content\t\ndef writetxt(name,content):\n\twith open(name+\".txt\", 'w') as file:\n\t\tfor i in content:\n\t\t\tfile.write(i+\"\\n\")\n\t\tfile.close()\ndef loadConfigurations():\n\tfilename = \"config\"\n\tfristconfigurations= [\"tim\",\"jane\"]\n\ttry:\n\t\tconfigurations = readtxt(filename)\n\t\tvale = configurations\n\texcept:\t\n\t\twritetxt(filename,fristconfigurations)\n\t\tvale = fristconfigurations\n\treturn vale\ndef speak(audioString):\n print(audioString)\n tts = gTTS(text=audioString, lang='en')\n tts.save(\"audio.mp3\")\n os.system(\"mpg123 audio.mp3\")\n\ndef recordAudio():\n # Record Audio\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Say something!\")\n audio = r.listen(source)\n \n # Speech recognition using Google Speech Recognition\n data = \"\"\n try:\n # Uses the default API key\n # To use another API key: `r.recognize_google(audio, key=\"GOOGLE_SPEECH_RECOGNITION_API_KEY\")`\n data = r.recognize_google(audio)\n print(\"You said: \" + data)\n except sr.UnknownValueError:\n print(\"Google Speech Recognition could not understand audio\")\n speak(\"I couldn't understand you\")\n except sr.RequestError as e:\n print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))\n data = data.lower()\n return data\n \ndef sendSMS():\n numbers = []\n names = []\n my_file = \"contacts.txt\"\n # open file in read mode\n with open(my_file, 'r') as file_handle:\n # convert file contents into a list\n lines = file_handle.read().splitlines()\n for i, val in enumerate(lines): \n #split each line and appends name and number to respective list \n person = val.split(\" \", 1)\n names.append(person[0])\n numbers.append(person[1])\n print(i, names[i], numbers[i])\n if(i + 1 >= len(lines)):\n break\n speak(\"Select acontact by number: \")\n data = recordAudio() \n i = data\n i = int(i)\n dest = numbers[i]\n speak(\"Record your message\")\n data = recordAudio()\n message = data\n speak(\"Would you like to send \" + message + \" to \" + names[i] + \"?\")\n data = recordAudio()\n if \"yes\" in data:\n os.system(\"kdeconnect-cli --send-sms '%s' -n s20 --destination %s\" % (message, dest))\n speak(\"Message sent to \" + names[i])\n\ndef jane(name,data):\n name = str(name)+\" \"\n if name+\"how are you\" in data:\n speak(\"I am fine, thanks\")\n if name+\"see you later\" in data or \"bye \"+name in data or name+\"bye\" in data:\n exit()\n if name+\"what time is it\" in data:\n print(time.ctime())\n speak(time.ctime())\n\n if name+\"where is\" in data:\n data = data.split(\" \", 2)\n location = data[2]\n speak(\"Hold on Tim, I will show you where \" + location + \" is.\")\n webbrowser.open_new_tab(\"https://www.google.com/maps/place/\" + location + \"/&amp;\")\n \n if name+\"search for\" in data:\n data = data.split(\" \", 2)\n search = data[2]\n speak(\"Hold on Tim, I will search for \" + search)\n webbrowser.open_new_tab('http://www.google.com/search?btnG=1&q=' + search)\n \n if name+\"start\" in data:\n data = data.split(\" \", 1)\n start = data[1]\n start = start.lower()\n speak(\"Starting \" + start)\n os.system(start + \"&\")\n \n if name+\"signal\" in data:\n os.system(\"signal-desktop &\")\n \n if \"hey \"+name in data:\n speak(\"Hey Tim, what's up?\")\n \n if name+\"send text\" in data:\n sendSMS()\n \n if name+\"open Instagram\" in data:\n instagram = 'istekram'\n os.system(istekram + \"&\")\n if name+\"configuration\" in data:\n configMenu()\n else:\n pass\t\ndef configMenu():\n\ti = 0\n\toptionsAvibles= \"\"\"\n\t1) change your username\n\t2) what do you want to call me\n\t3) going back\n\t\"\"\"\n\tfilename = \"config\"\n\tattempts = 3\n\tspeak(optionsAvibles)\n\tconfigurations = loadConfigurations()\n\ttmpConfigurations = configurations\t\n\twhile i < attempts:\n\t\toption = recordAudio()\n\t\tif option == \"change your username\" or \"1\":\n\t\t\tspeak(\"how is you new username?\")\n\t\t\tconfigurations[0] = recordAudio()\n\t\t\tspeak(\"ok ,\"+configurations[0]+\" is right?\"+\"\"\"\n\t\t\t1) yes\t\t\t\n\t\t\t\"\"\")\n\t\t\tverification = recordAudio()\n\t\t\tif verification == \"yes\" or verification == \"1\":\n\t\t\t\tspeak(\"ok ,\"+configurations[0]+\" Nice to meet you again \")\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tpass\n\t\telif option == \"what do you want to call me\" or \"2\":\n\t\t\tspeak(\"how you want to call me?\")\n\t\t\tspeak(\"ok ,\"+configurations[1]+\" is right?\"+\"\"\"\n\t\t\t1) yes\n\n\t\t\t\"\"\")\n\t\t\tconfigurations[1] = recordAudio()\n\t\t\tif verification == \"yes\" or verification == \"1\":\n\t\t\t\tspeak(configurations[1]+\" ? i like that name \")\n\t\t\t\tbreak\n\t\telif option == \"going back\" or \"3\":\n\t\t\tspeak(\"as you wish it could be another time\")\n\t\t\tconfigurations = tmpConfigurations \n\t\t\tbreak\n\t\telse:\n\t\t\tpass\n\twritetxt(filename,configurations)\n#def configJane(option):\ndef banner():\n\tprint(\"\"\"\n _ Virtual\n | | __ _ _ __ ___ _ __ _ _ Assistant\n _ | |/ _` | '_ \\ / _ \\ | '_ \\| | | |\n| |_| | (_| | | | | __/_| |_) | |_| |\n \\___/ \\__,_|_| |_|\\___(_) .__/ \\__, |\n |_| |___/ \n\t\"\"\")\n# initialization\ndef main():\n\tbanner()\n\tconfigurations = loadConfigurations()\n\tspeak(\"Hi \"+configurations[0]+\",I am \"+configurations[1]+\", how can I help?\")\n\twhile True:\n \t\ttime.sleep(0.5)\n \t\tdata = recordAudio()\n \t\tjane(configurations[1],data)\nif __name__ == \"__main__\":\n\tmain()\n" } ]
2
soran-ghaderi/iowa_gambling_task
https://github.com/soran-ghaderi/iowa_gambling_task
8a11302f7cb8204d0f99ac7ea1e6461b72a511b7
b9a3e1dcaea72dbce3a36f02d6fb9f488c16e571
8a22849f8799214bae042338249d02544b126b6e
refs/heads/master
2023-06-19T09:33:58.274961
2023-05-30T16:49:44
2023-05-30T16:49:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7196261882781982, "alphanum_fraction": 0.7196261882781982, "avg_line_length": 25.75, "blob_id": "3a26778d521dcc4d57f7da30f674ff200c3eec82", "content_id": "eb6e5347a54621db74f53b7c082c11c2db49f465", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 107, "license_type": "permissive", "max_line_length": 52, "num_lines": 4, "path": "/docs/source/transformerx.layers.positionwise_ffn.rst", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": ".. automodule:: transformerx.layers.positionwise_ffn\n :members:\n :undoc-members:\n :show-inheritance:\n" }, { "alpha_fraction": 0.6418367624282837, "alphanum_fraction": 0.6704081892967224, "avg_line_length": 28.696969985961914, "blob_id": "52d0bd2c4f401ec7b0362716a904f3a24abce9d9", "content_id": "ff5ce03b96561b37ead5b034ebb8ac1b9e6d9dec", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 980, "license_type": "permissive", "max_line_length": 112, "num_lines": 33, "path": "/examples/eng2fr_translation.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "# **NOTE**: This example will be heavily edited, hence, this is not an official part of the library at this time\n\nfrom transformerx.data_loader import BaseDataset\nfrom transformerx.training.base import Transformer, Trainer\nfrom transformerx.layers import TransformerEncoder, TransformerDecoder\n\ndepth, n_blocks, dropout = 256, 2, 0.2\nffn_num_hiddens, num_heads = 64, 4\nkey_size, query_size, value_size = 256, 256, 256\n\ndata = BaseDataset(batch_size=128)\nnorm_shape = [2]\nencoder = TransformerEncoder(\n len(data.src_vocab),\n depth,\n norm_shape,\n ffn_num_hiddens,\n num_heads,\n n_blocks,\n dropout,\n)\ndecoder = TransformerDecoder(\n len(data.tgt_vocab),\n depth,\n norm_shape,\n ffn_num_hiddens,\n num_heads,\n n_blocks,\n dropout,\n)\nmodel = Transformer(encoder, decoder, tgt_pad=data.tgt_vocab[\"<pad>\"], lr=0.001)\ntrainer = Trainer(max_epochs=2, gradient_clip_val=1)\ntrainer.fit(model, data)\n" }, { "alpha_fraction": 0.837837815284729, "alphanum_fraction": 0.837837815284729, "avg_line_length": 74, "blob_id": "173a3c2d022469ba165ffedbb767f7be773afcb2", "content_id": "9b1421e69ba0c3afe5c9fbaa5c9b2ef6f4cde808", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "permissive", "max_line_length": 74, "num_lines": 1, "path": "/transformerx/training/__init__.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "from .base import Module, Trainer, Transformer, Classifier, EncoderDecoder" }, { "alpha_fraction": 0.5439441800117493, "alphanum_fraction": 0.6029240489006042, "avg_line_length": 33.99418640136719, "blob_id": "06f3b8698ce988be9d352976f76ed324109799bf", "content_id": "0f68bda9a9cc50daa13713412b8f1226d306156d", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6021, "license_type": "permissive", "max_line_length": 120, "num_lines": 172, "path": "/transformerx/layers/dot_product_attention.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\nfrom transformerx.layers.masks.global_attention_mask import GlobalAttentionMask\nfrom transformerx.utils import masked_softmax\nfrom transformerx.layers.masks import LookAheadMask\n\n\nclass DotProductAttention(tf.keras.layers.Layer):\n \"\"\"Compute (scaled) dot-product attention [1]_\n\n Implement multiplicative (dot-product) and scaled multiplicative attention for the input queries, keyes, and values.\n\n Parameters\n ----------\n dropout_rate : float\n Fraction of the input units to drop. A float between 0 and 1.\n scaled : bool\n Indicate whether to scale the dot-product\n\n Returns\n -------\n output : tf.Tensor with the same shape of Query, Key, and value\n (Scaled) dot-product of the keys, queries, and values\n\n Notes\n -----\n Dot-product attention formulation is as following:\n\n .. math::\n Attention(Q, K, V) = softmax(Q K^T) V\n\n And scaled dot-product attention [1]_ is formulated as:\n\n .. math::\n Attention(Q, K, V) = softmax(\\\\frac{QK^T}{\\\\sqrt{d_k}}) V\n\n\n Examples\n --------\n Scaled dot-product (scaled multiplicative) self-attention of tensor `x` (we feed `x` to queries, keys, and\n values).\n >>> tf.random.set_seed(1)\n >>> x = tf.cast(tf.random.uniform([2, 3, 2]), dtype=tf.float32)\n >>> print(x)\n tf.Tensor(\n [[[0.16513085 0.9014813 ]\n [0.6309742 0.4345461 ]\n [0.29193902 0.64250207]]\n <BLANKLINE>\n [[0.9757855 0.43509948]\n [0.6601019 0.60489583]\n [0.6366315 0.6144488 ]]], shape=(2, 3, 2), dtype=float32)\n\n >>> dot_product = DotProductAttention(0.2)\n >>> queries, keys, values = x, x, x\n >>> output, attn_weights = dot_product(queries, keys, values)\n >>> print(output)\n tf.Tensor(\n [[[0.34450796 0.6787753 ]\n [0.36907017 0.65472305]\n [0.35440704 0.66882825]]\n <BLANKLINE>\n [[0.77042043 0.5446019 ]\n [0.7632908 0.5484005 ]\n [0.7627964 0.5486638 ]]], shape=(2, 3, 2), dtype=float32)\n\n The next example shows the dot-product (multiplicative) self-attention of tensor `x`.\n\n >>> dot_product = DotProductAttention(dropout_rate=0.1, scaled=False)\n >>> output, attn_weights = dot_product(queries, keys, values)\n >>> print(output)\n tf.Tensor(\n [[[0.33704066 0.6868143 ]\n [0.37176722 0.6526886 ]\n [0.35094902 0.6727435 ]]\n <BLANKLINE>\n [[0.7759446 0.54165894]\n [0.7657266 0.54710305]\n [0.7650213 0.5474789 ]]], shape=(2, 3, 2), dtype=float32)\n\n References\n ----------\n .. [1] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, I. Polosukhin, Attention\n is all you need, in: NIPS, pp. 5998–6008.\n \"\"\"\n\n def __init__(\n self,\n dropout_rate: float = 0,\n scaled: bool = True,\n kernel_initializer: str = \"ones\",\n kernel_regularizer: str = None,\n causal_mask: bool = None,\n mask_type=\"dilated\",\n mask_prob=0.0,\n dilation_rate=1,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.dropout_rate = dropout_rate\n self.dropout = tf.keras.layers.Dropout(self.dropout_rate)\n self.scaled = scaled\n self.attention_weights = None\n self.kernel_initializer = kernel_initializer\n self.kernel_regularizer = kernel_regularizer\n self.causal_mask = causal_mask\n\n self.mask_type = mask_type\n self.mask_prob = mask_prob\n self.dilation_rate = dilation_rate\n self.global_mask = GlobalAttentionMask(\n mask_type=self.mask_type,\n mask_prob=self.mask_prob,\n dilation_rate=self.dilation_rate,\n )\n\n def build(self, input_shape):\n super().build(input_shape)\n\n # Shape of queries: (batch_size, no. of queries, d)\n # Shape of keys: (batch_size, no. of key-value pairs, d)\n # Shape of values: (batch_size, no. of key-value pairs, value dimension)\n # Shape of attention_mask: (batch_size,) or (batch_size, no. of queries)\n def call(\n self,\n queries: tf.Tensor,\n keys: tf.Tensor,\n values: tf.Tensor,\n attention_mask: tf.Tensor = None,\n training=None,\n **kwargs,\n ) -> tf.Tensor:\n scores = tf.matmul(queries, keys, transpose_b=True)\n if self.scaled:\n depth = queries.shape[-1]\n\n scores = scores / tf.math.sqrt(tf.cast(depth, dtype=queries.dtype))\n\n # apply causal mask\n if self.causal_mask:\n # Obsolete version of masking. To be removed in the upcomming updates\n # seq_len = tf.shape(queries)[2]\n # heads = tf.shape(queries)[1]\n # batch_size, num_heads, seq_len, _ = tf.unstack(tf.shape(queries))\n # causal_mask = tf.ones((num_heads, seq_len)) * -1e9\n # causal_mask = tf.linalg.LinearOperatorLowerTriangular(\n # causal_mask\n # ).to_dense()\n # causal_mask = tf.expand_dims(causal_mask, axis=0) # add batch dimension\n # causal_mask = tf.broadcast_to(\n # tf.expand_dims(causal_mask, -1), tf.shape(scores)\n # ) # broadcast across batch dimension\n\n # New version of masking\n look_ahead_mask = LookAheadMask()\n scores = look_ahead_mask(scores)\n\n # to be uncommented later\n # apply global mask\n # gmask = self.global_mask.get_mask(keys.shape)\n # masked_attention_scores = tf.math.multiply(scores, gmask)\n # attention_probs = tf.nn.softmax(masked_attention_scores, axis=-1)\n # uncomment until here\n\n self.attention_weights = masked_softmax(scores, attention_mask)\n # self.attention_weights = tf.nn.softmax(scores, axis=-1, mask=attention_mask)\n # scores = tf.matmul(self.dropout(self.attention_weights, **kwargs), values)\n attention_output = tf.matmul(self.dropout(self.attention_weights), values)\n return attention_output, self.attention_weights\n\n def get_attention_weights(self):\n return self.attention_weights\n" }, { "alpha_fraction": 0.6317335963249207, "alphanum_fraction": 0.6707709431648254, "avg_line_length": 42.57926940917969, "blob_id": "5930be1a57726a1a13201763072f976df7da97f1", "content_id": "76be49a32a3f4b29c44671c76e26e6a6648aec73", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7147, "license_type": "permissive", "max_line_length": 88, "num_lines": 164, "path": "/tests/layers/test_transformer_encoder_block.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport pytest\n\nfrom transformerx.layers import TransformerEncoderBlock\n\n\nclass TestTransformerEncoderBlock:\n @pytest.fixture\n def transformer_encoder_block(self):\n return TransformerEncoderBlock()\n\n def test_transformer_encoder_block_output_shape(self, transformer_encoder_block):\n x = tf.random.uniform((32, 10, 512))\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_attention_mask(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n attention_mask = tf.ones((32, 10))\n output_tensor, attn_weights = transformer_encoder_block(\n x, attention_mask=attention_mask\n )\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_residual_connections(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.residual_connections = (True, True)\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_clip_norm(self, transformer_encoder_block):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.clip_norm = 1.0\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert tf.math.reduce_max(tf.norm(output_tensor, axis=-1)) <= 1.0\n\n def test_transformer_encoder_block_with_layer_norm(self, transformer_encoder_block):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.use_norm = True\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_without_layer_norm(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.use_norm = False\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_bias(self, transformer_encoder_block):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.use_bias = True\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_without_bias(self, transformer_encoder_block):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.use_bias = False\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_mixed_precision(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n tf.keras.mixed_precision.set_global_policy(\"float32\")\n transformer_encoder_block.mixed_precision = True\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.dtype == tf.float32\n\n def test_transformer_encoder_block_with_learning_rate_schedule(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.learning_rate_schedule = lambda x: 1e-4 * x\n output_tensor, attn_weights = transformer_encoder_block(x, global_step=10)\n assert transformer_encoder_block.learning_rate == 1e-3\n\n def test_transformer_encoder_block_with_kernel_regularizer(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.kernel_regularizer = tf.keras.regularizers.l2(1e-4)\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_bias_regularizer(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.bias_regularizer = tf.keras.regularizers.l2(1e-4)\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_non_linear_proj(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.non_linear_proj = tf.keras.layers.Dense(256)\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_contextualized_embeddings(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n transformer_encoder_block.contextualized_embeddings = tf.keras.layers.Dense(768)\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n\nclass TestTransformerEncoderBlockIntegration:\n @pytest.fixture\n def transformer_encoder_block(self):\n return TransformerEncoderBlock()\n\n def test_transformer_encoder_block_with_embedding_layer(\n self, transformer_encoder_block\n ):\n input_data = tf.random.uniform((32, 10), minval=0, maxval=100, dtype=tf.int32)\n embedding_layer = tf.keras.layers.Embedding(input_dim=100, output_dim=512)\n x = embedding_layer(input_data)\n output_tensor, attn_weights = transformer_encoder_block(x)\n assert output_tensor.shape == (32, 10, 512)\n\n def test_transformer_encoder_block_with_dense_layer(\n self, transformer_encoder_block\n ):\n x = tf.random.uniform((32, 10, 512))\n output_tensor, attn_weights = transformer_encoder_block(x)\n dense_layer = tf.keras.layers.Dense(units=256, activation=\"relu\")\n output_tensor = dense_layer(output_tensor)\n assert output_tensor.shape == (32, 10, 256)\n\n def test_transformer_encoder_block_training(self, transformer_encoder_block):\n input_data = tf.random.uniform((32, 10), minval=0, maxval=100, dtype=tf.int32)\n target_data = tf.random.uniform((32, 10), minval=0, maxval=100, dtype=tf.int32)\n\n input_layer = tf.keras.layers.Input(shape=(10,), dtype=tf.int32)\n embedding_layer = tf.keras.layers.Embedding(input_dim=100, output_dim=512)\n x = embedding_layer(input_layer)\n output_tensor, attn_weights = transformer_encoder_block(x)\n dense_layer = tf.keras.layers.Dense(units=100)\n output_tensor = dense_layer(output_tensor)\n\n model = tf.keras.Model(inputs=input_layer, outputs=output_tensor)\n\n loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n optimizer = tf.keras.optimizers.Adam()\n\n with tf.GradientTape() as tape:\n predictions = model(input_data)\n loss = loss_object(target_data, predictions)\n\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n assert loss is not None\n assert gradients is not None\n" }, { "alpha_fraction": 0.5909661054611206, "alphanum_fraction": 0.6065802574157715, "avg_line_length": 35.78461456298828, "blob_id": "945edcf5a6709f77977ae5eceece73e2ee13e7ad", "content_id": "daae09f812f2dba0d0c48bdae69ab4f5432ded95", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7173, "license_type": "permissive", "max_line_length": 319, "num_lines": 195, "path": "/transformerx/layers/addnorm.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nfrom typing import Optional\n\n\nclass AddNorm(tf.keras.layers.Layer):\n \"\"\"Residual connection addition with dropout and normalization.\n\n This layer implements a residual connection with dropout followed by a normalization layer. The normalization can be of type 'batch', 'instance', or 'layer'. The layer also supports different activation functions and regularization techniques.\n\n Parameters\n ----------\n norm_type : str, optional\n Type of normalization to apply. Can be 'batch', 'instance', or 'layer'. Defaults to 'layer'.\n norm_eps : float, optional\n Epsilon value for numerical stability in the normalization layer. Defaults to 1e-6.\n dropout_rate : float, optional\n Fraction of the input units to drop. Should be between 0 and 1. Defaults to 0.1.\n activation : str, optional\n Activation function to apply after the normalization layer. Defaults to None.\n kernel_regularizer : Optional[tf.keras.regularizers.Regularizer], optional\n Regularizer function applied to the kernel weights. Defaults to None.\n bias_regularizer : Optional[tf.keras.regularizers.Regularizer], optional\n Regularizer function applied to the bias weights. Defaults to None.\n\n Returns\n -------\n tf.Tensor\n Added and normalized tensor.\n\n Raises\n ------\n ValueError\n If the value of dropout_rate is not between 0 and 1, or if the value of norm_type is not one of ['batch', 'instance', 'layer'].\n TypeError\n If the value of norm_shape is not an int or a list/tuple of ints.\n\n Notes\n -----\n Batch normalization (BatchNorm) normalizes across the batch dimension, instance normalization (InstanceNorm) normalizes across the channel dimension, and layer normalization (LayerNorm) normalizes across the feature dimension.\n\n This layer applies dropout to the residual connection before adding it to the input tensor, which helps to prevent overfitting. It then applies the specified normalization technique to the output tensor, followed by an optional activation function. Regularization can also be applied to the kernel and bias weights.\n\n Normalization techniques can help to stabilize the training process and improve the performance of deep neural networks.\n\n Examples\n --------\n >>> x = tf.constant(np.arange(10).reshape(5, 2) * 10, dtype=tf.float32)\n >>> y = tf.constant(np.arange(10).reshape(5, 2) * 11, dtype=tf.float32)\n >>> print(x)\n tf.Tensor(\n [[ 0. 10.]\n [20. 30.]\n [40. 50.]\n [60. 70.]\n [80. 90.]], shape=(5, 2), dtype=float32)\n\n >>> addnorm = AddNorm(norm_type='layer', norm_eps=1e-6, dropout_rate=0.2, activation='relu')\n >>> output = addnorm(x, y)\n >>> print(output)\n tf.Tensor(\n [[0. 1.]\n [0. 1.]\n [0. 1.]\n [0. 1.]\n [0. 1.]], shape=(5, 2), dtype=float32)\n\n References\n ----------\n Ba, J., Kiros, J. R., & Hinton, G. E. (2016). Layer normalization. arXiv preprint arXiv:1607.06450.\n \"\"\"\n\n def __init__(\n self,\n norm_type: str = \"layer\",\n norm_eps: float = 1e-6,\n dropout_rate: float = 0.1,\n activation: Optional[str] = None,\n kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,\n bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,\n **kwargs,\n ):\n super(AddNorm, self).__init__(**kwargs)\n if not isinstance(dropout_rate, (int, float)) or not 0 <= dropout_rate <= 1:\n raise ValueError(\n f\"Invalid value {dropout_rate} received for \"\n \"`dropout_rate`, expected a value between 0 and 1.\"\n )\n # Check normalization type\n if norm_type not in [\"batch\", \"instance\", \"layer\"]:\n raise TypeError(\n f\"Invalid type {norm_type} received for 'norm_type', expected one of ['batch', 'instance', 'layer'].\"\n )\n\n self.norm_type = norm_type\n self.norm_eps = norm_eps\n self.dropout_rate = dropout_rate\n self.activation = activation\n\n if dropout_rate >= 1:\n raise ValueError(\"Dropout rate must be less than 1\")\n self.dropout = tf.keras.layers.Dropout(self.dropout_rate)\n # Regularizers\n self.kernel_regularizer = kernel_regularizer\n self.bias_regularizer = bias_regularizer\n\n # Layers\n self.dropout = tf.keras.layers.Dropout(dropout_rate)\n self.norm_layer = None\n\n def build(self, input_shape):\n if self.norm_type == \"batch\":\n self.norm_layer = tf.keras.layers.BatchNormalization(epsilon=self.norm_eps)\n elif self.norm_type == \"instance\":\n self.norm_layer = tf.keras.layers.LayerNormalization(\n epsilon=self.norm_eps, axis=-1\n )\n elif self.norm_type == \"layer\":\n self.norm_layer = tf.keras.layers.LayerNormalization(\n epsilon=self.norm_eps, axis=-1\n )\n\n # Build activation layer if specified\n if self.activation is not None:\n self.activation_layer = tf.keras.layers.Activation(self.activation)\n\n super(AddNorm, self).build(input_shape)\n\n # self.ln = tf.keras.layers.LayerNormalization(norm_shape)\n\n def call(self, x: tf.Tensor, residual: tf.Tensor, **kwargs):\n \"\"\"Call AddNorm layer.\n\n Parameters\n ----------\n x :\n Input tensor\n residual :\n Residual input tensor\n\n Returns\n -------\n output :\n Added and normalized tensor\n \"\"\"\n if not isinstance(x, tf.Tensor):\n raise TypeError(\n f\"Expected a tensor for the \" f\"argument 'x', but received: {x}\"\n )\n if not isinstance(residual, tf.Tensor):\n raise TypeError(\n f\"Expected a tensor for the \"\n f\"argument 'residual', but received: {residual}\"\n )\n\n # Apply dropout\n # residual = self.dropout(residual)\n\n # Add residual connection\n x = tf.add(x, residual)\n\n # Apply normalization\n x = self.norm_layer(x)\n\n # Apply activation if specified\n if self.activation is not None:\n x = self.activation_layer(x)\n\n # return self.ln(self.dropout(residual, **kwargs) + x)\n return x\n\n def get_config(self):\n config = super(AddNorm, self).get_config()\n config.update(\n {\n \"norm_type\": self.norm_type,\n \"norm_eps\": self.norm_eps,\n \"dropout_rate\": self.dropout_rate,\n \"activation\": self.activation,\n \"kernel_regularizer\": self.kernel_regularizer,\n \"bias_regularizer\": self.bias_regularizer,\n }\n )\n return config\n\n\n# if __name__ == \"__main__\":\n# x = tf.constant(np.arange(10).reshape(5, 2) * 10, dtype=tf.float32)\n# y = tf.constant(np.arange(10, 20).reshape(5, 2) * 13, dtype=tf.float32)\n#\n# addnorm = AddNorm(\n# norm_type=\"layer\", norm_eps=1e-6, dropout_rate=0.2, activation=\"relu\"\n# )\n# output = addnorm(x, y)\n# print(output)\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 25, "blob_id": "1b9d735bbd14f82573294bc7cce9d202cd80cfc0", "content_id": "791948a6a1a9385f5aa4a156cb50ef9c6191db05", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26, "license_type": "permissive", "max_line_length": 25, "num_lines": 1, "path": "/transformerx/txplot/__init__.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "from .plot_pe import Plot\n" }, { "alpha_fraction": 0.7014555931091309, "alphanum_fraction": 0.7224162817001343, "avg_line_length": 40.137725830078125, "blob_id": "bbb8b711b40da5c60a811bb5c40d2abee06de5d6", "content_id": "706124b5fdbcd261fe25b03530b81228858ace58", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6877, "license_type": "permissive", "max_line_length": 462, "num_lines": 167, "path": "/README.md", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "<div align=\"center\">\n<h1><b>TransformerX</b></h1>\n<hr>\n<div>\n<img src=\"logo.jpeg\" height=\"400\" width=\"400\">\n</div>\n<p><b>TransformerX</b> is a Python library for building transformer-based models.</p>\n</div>\n\n<div align=\"center\">\n<img alt=\"PyPI - Python Version\" src=\"https://img.shields.io/pypi/pyversions/emgraph\">\n<img alt=\"PyPI - Implementation\" src=\"https://img.shields.io/pypi/implementation/transformerx\">\n<img alt=\"GitHub last commit\" src=\"https://img.shields.io/github/last-commit/tensorops/transformerx\">\n<img alt=\"PyPI - Maintenance\" src=\"https://img.shields.io/badge/Maintained%3F-yes-green.svg\">\n<img alt=\"PyPI - License\" src=\"https://img.shields.io/pypi/l/transformerx.svg\">\n<img alt=\"PyPI - Format\" src=\"https://img.shields.io/pypi/format/transformerx.svg\">\n<img alt=\"Status\" src=\"https://img.shields.io/pypi/status/transformerx.svg\">\n<img alt=\"Commits\" src=\"https://badgen.net/github/commits/tensorops/transformerx\">\n<img alt=\"Commits\" src=\"https://img.shields.io/badge/TensorFlow 2-FF6F00?style=flat&logo=tensorflow&logoColor=white\">\n</div>\n\n<div align=\"center\">\n<p>It comes with multiple building blocks and layers you need for creating your model.</p>\n<hr>\n</div>\n\n<div align=\"center\">\n <p>Join <a href=\"https://discord.gg/WGdPS5NJ\"><b>TensorOps</b> community on Discord</a></p>\n <p>Follow <a target=\"_blank\" href=\"https://twitter.com/tensorops\"><b>TensorOps</b> Twitter</a></p>\n</div>\n\n<b>Here's why:</b>\n\n- Your time should be focused on creating more advanced and complex tasks\n- You shouldn't be doing the same tasks over and over\n\n<div>\n <h2>Installation</h2>\n <p>Install the latest version of <b>TransformerX</b>:</p>\n <pre>$ pip install transformerx</pre>\n</div>\n\n<div>\n<h2>Getting Started</h2>\n<p>This example implements a French to English translation model.</p>\n\n<p>Check out these blog posts on Medium:\n\n- <a href=\"https://towardsdatascience.com/the-map-of-transformers-e14952226398\">The Map Of Transformers</a></p>\n- <a href=\"https://towardsdatascience.com/transformers-in-action-attention-is-all-you-need-ac10338a023a\">Transformers in\n Action: Attention Is All You Need</a></p>\n- <a href=\"https://towardsdatascience.com/rethinking-thinking-how-do-attention-mechanisms-actually-work-a6f67d313f99\">\n Rethinking Thinking: How Do Attention Mechanisms Actually Work?</a></p>\n\n<b>Note</b>: The <code>data_loader</code> and <code>training</code> modules are still under development and you may\nwant to use your own training and input pipeline. However,\nthe <code>layers</code> package is the core component and will remain the same (you can integrate it with Tensorflow\nalready 🔜 Pytorch and JAX).\n\n```python\nfrom transformerx.data_loader import BaseDataset\nfrom transformerx.training import Transformer, Trainer\nfrom transformerx.layers import TransformerEncoder, TransformerDecoder\n\ndepth, n_blocks, dropout = 256, 2, 0.2\nffn_num_hiddens, num_heads = 64, 4\nkey_size, query_size, value_size = 256, 256, 256\n\ndata = BaseDataset(batch_size=128)\nnorm_shape = [2]\nencoder = TransformerEncoder(\n len(data.src_vocab),\n depth,\n norm_shape,\n ffn_num_hiddens,\n num_heads,\n n_blocks,\n dropout,\n)\ndecoder = TransformerDecoder(\n len(data.tgt_vocab),\n depth,\n norm_shape,\n ffn_num_hiddens,\n num_heads,\n n_blocks,\n dropout,\n)\nmodel = Transformer(encoder, decoder, tgt_pad=data.tgt_vocab[\"<pad>\"], lr=0.001)\ntrainer = Trainer(max_epochs=2, gradient_clip_val=1)\ntrainer.fit(model, data)\n```\n\n</div>\n\n<div>\n<h2>Features</h2>\n\n- [x] Support CPU/GPU\n- [x] Vectorized operations\n- [x] Standard API\n\n</div>\n\n<div>\n<h2>Roadmap</h2>\n\n- [x] Support Tensorflow\n- [ ] Extensive documentation\n - <a href=\"https://github.com/tensorops/TransformerX/issues/30\">Documentation</a>\n - Examples (Colab, etc.)\n - Add more contents to the <a href=\"https://github.com/tensorops/TransformerX/blob/master/README.md\">README.md</a>\n- [ ] Support Pytorch and JAX\n- [ ] More layers\n - <a href=\"https://github.com/tensorops/TransformerX/issues/44\">Attention layers</a>\n - <a href=\"https://github.com/tensorops/TransformerX/issues/42\">Residual and residual gate layers</a>\n - <a href=\"https://github.com/tensorops/TransformerX/issues/41\">Embedding layers</a>\n\n</div>\n<div>\n<h2>Contribution</h2>\n\nContributions are what make the open source community such an amazing place to learn, inspire, and create. Any\ncontributions you make are <b>greatly appreciated</b>.\n\nIn case you want to get ideas or just work on a ready-to-solve issue, please check out issues with the\nlabel `issue list`.\nHere is a <a href=\"https://github.com/tensorops/TransformerX/issues?q=is%3Aissue+is%3Aopen+label%3A%22issue+list%22\">\nlist of issue lists</a>\n\nIf you have a suggestion that would make this better, please fork the repo and create a pull request. You can also\nsimply open an issue with the tag \"enhancement\" or \"bug\".\n\n<ol>\n<li>Fork the Project</li>\n<li>Create your Feature Branch (git checkout -b feature/AmazingFeature)</li>\n<li>Commit your Changes (git commit -m 'Add some AmazingFeature')</li>\n<li>Push to the Branch (git push origin feature/AmazingFeature)</li>\n<li>Open a Pull Request</li>\n</ol>\n\n<h3>If you find this project helpful or valuable, please consider giving it a star ⭐️</h3> Your support helps us to\nreach\na wider audience and improve the project for everyone. <b>Thank you for your support!</b>\n</div>\n\n<div>\n<h2>Contributors</h2>\n<a href = \"https://github.com/Tanu-N-Prabhu/Python/graphs/contributors\">\n <img src = \"https://contrib.rocks/image?repo=tensorops/transformerx\"/>\n</a>\n</div>\n\n<div>\n<h2>License</h2>\n<p>Released under the Apache 2.0 license -> To be changed to MIT license after the first stable release</p>\n</div>\n\n<h2>Contact</h2>\n<div class=\"footer\"><pre>Copyright &copy; 2021-2023 <b>TensorOps</b> Developers\n<a href=\"https://soran-ghaderi.github.io/\"><b>Soran Ghaderi</b></a> ([email protected])\nfollow me on <a href=\"https://github.com/soran-ghaderi\"><img alt=\"Github\" src=\"https://img.shields.io/badge/GitHub-100000?&logo=github&logoColor=white\"></a> <a href=\"https://twitter.com/soranghadri\"><img alt=\"Twitter\" src=\"https://img.shields.io/badge/Twitter-1DA1F2?&logo=twitter&logoColor=white\"></a> <a href=\"https://www.linkedin.com/in/soran-ghaderi/\"><img alt=\"Linkedin\" src=\"https://img.shields.io/badge/LinkedIn-0077B5?&logo=linkedin&logoColor=white\"></a>\n<br>\n<a href=\"https://uk.linkedin.com/in/taleb-zarhesh\"><b>Taleb Zarhesh</b></a> ([email protected])\nfollow me on <a href=\"https://github.com/sigma1326\"><img alt=\"Github\" src=\"https://img.shields.io/badge/GitHub-100000?&logo=github&logoColor=white\"></a> <a href=\"https://twitter.com/taleb__z\"><img alt=\"Twitter\" src=\"https://img.shields.io/badge/Twitter-1DA1F2?&logo=twitter&logoColor=white\"></a> <a href=\"https://www.linkedin.com/in/taleb-zarhesh/\"><img alt=\"Linkedin\" src=\"https://img.shields.io/badge/LinkedIn-0077B5?&logo=linkedin&logoColor=white\"></a>\n</pre>\n</div>\n" }, { "alpha_fraction": 0.5551839470863342, "alphanum_fraction": 0.5819398164749146, "avg_line_length": 28.899999618530273, "blob_id": "0f82282663bdf393921b207c898655b60fe59371", "content_id": "2068d333c8008c76428f3000be5d1aa9c6a84d22", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "permissive", "max_line_length": 65, "num_lines": 10, "path": "/transformerx/__version__.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "VERSION = (1, 0, 0, \"beta\", 3)\n\nif len(VERSION) < 3:\n raise ValueError(\"VERSION must have at least three elements\")\n\n__version__ = \".\".join(str(v) for v in VERSION[:3])\nif len(VERSION) > 3:\n __version__ += \"-\" + \".\".join(str(v) for v in VERSION[3:])\n# version_str += \"-dev\"\nprint(__version__)\n" }, { "alpha_fraction": 0.572576105594635, "alphanum_fraction": 0.6056933403015137, "avg_line_length": 38.20441818237305, "blob_id": "e35ed97a3771afc3890a9daf16bd97e7a65634b4", "content_id": "6c3d5da0aa0dbe6ef9b2c74a6541552841ee8f60", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7096, "license_type": "permissive", "max_line_length": 89, "num_lines": 181, "path": "/tests/layers/test_transformer_decoder_block.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import pytest\nimport tensorflow as tf\n\nfrom transformerx.layers import TransformerDecoderBlock\n\n\ndef test_transformer_decoder_block():\n batch_size = 2\n seq_length = 10\n queries = tf.random.uniform((batch_size, seq_length, 64))\n keys = tf.random.uniform((batch_size, seq_length, 64))\n values = tf.random.uniform((batch_size, seq_length, 64))\n valid_lens = tf.ones((batch_size, seq_length))\n\n decoder_block = TransformerDecoderBlock(d_model=64)\n output, attn1_weights, attn2_weights = decoder_block(\n queries, keys, values, valid_lens\n )\n\n assert output.shape == (batch_size, seq_length, 64)\n assert attn1_weights.shape == (batch_size, 8, seq_length, seq_length)\n assert attn2_weights.shape == (batch_size, 8, seq_length, seq_length)\n\n\nclass TestTransformerDecoderBlock:\n def test_basic_functionality(self):\n batch_size = 2\n seq_length = 10\n queries = tf.random.uniform((batch_size, seq_length, 512))\n keys = tf.random.uniform((batch_size, seq_length, 512))\n values = tf.random.uniform((batch_size, seq_length, 512))\n valid_lens = tf.ones((batch_size, seq_length))\n\n decoder_block = TransformerDecoderBlock()\n output, attn1_weights, attn2_weights = decoder_block(\n queries, keys, values, valid_lens\n )\n\n assert output.shape == (batch_size, seq_length, 512)\n assert attn1_weights.shape == (batch_size, 8, seq_length, seq_length)\n assert attn2_weights.shape == (batch_size, 8, seq_length, seq_length)\n\n @pytest.fixture\n def transformer_block(self):\n return TransformerDecoderBlock()\n\n def test_call(self, transformer_block):\n # Generate inputs for testing\n queries = tf.ones(shape=(2, 5, 512))\n keys = tf.ones(shape=(2, 10, 512))\n values = tf.ones(shape=(2, 10, 512))\n valid_lens = tf.constant([5, 7])\n\n # Test the call method\n output, _, _ = transformer_block(queries, keys, values, valid_lens)\n assert output.shape == (2, 5, 512)\n\n def test_call2(self):\n batch_size = 2\n seq_length = 5\n hidden_size = 4\n num_heads = 2\n dropout_rate = 0.2\n epsilon = 1e-6\n\n decoder_block = TransformerDecoderBlock(hidden_size, num_heads, dropout_rate)\n\n input_tensor = tf.random.uniform(\n shape=(batch_size, seq_length, hidden_size), dtype=tf.float32\n )\n look_ahead_mask = 1 - tf.linalg.band_part(\n tf.ones((seq_length, seq_length)), -1, 0\n )\n look_ahead_mask = tf.tile(\n tf.expand_dims(look_ahead_mask, 0), [batch_size, 1, 1]\n )\n\n output_tensor, _, attention_weights = decoder_block(\n input_tensor, input_tensor, input_tensor, look_ahead_mask\n )\n\n # Check the shape of output_tensor\n assert output_tensor.shape == (batch_size, seq_length, hidden_size)\n\n # Check the shape of attention_weights\n assert attention_weights.shape == (\n batch_size,\n num_heads,\n seq_length,\n seq_length,\n )\n\n # Check that the output tensor is not all zeros\n assert not tf.reduce_all(tf.abs(output_tensor) < epsilon)\n\n # Check that the attention weights sum to 1 along the last axis\n assert tf.reduce_all(\n tf.abs(tf.reduce_sum(attention_weights, axis=-1) - 1) < epsilon\n )\n\n tf.debugging.assert_near(\n tf.reduce_sum(attention_weights, axis=-1),\n tf.ones((batch_size, num_heads, seq_length)),\n atol=epsilon,\n )\n\n def test_shape(self, transformer_block):\n # Test that the output shape is correct\n queries = tf.ones(shape=(2, 5, 512))\n keys = tf.ones(shape=(2, 10, 512))\n values = tf.ones(shape=(2, 10, 512))\n valid_lens = tf.constant([5, 7])\n output, _, _ = transformer_block(queries, keys, values, valid_lens)\n assert output.shape == (2, 5, 512)\n\n def test_addnorm(self, transformer_block):\n # Test that the output of the addnorm layer is correct\n queries = tf.ones(shape=(2, 5, 512))\n keys = tf.ones(shape=(2, 10, 512))\n values = tf.ones(shape=(2, 10, 512))\n valid_lens = tf.constant([5, 7])\n output, _, _ = transformer_block(queries, keys, values, valid_lens)\n assert transformer_block.addnorm1(output, queries).shape == (2, 5, 512)\n\n def test_multihead_attention(self, transformer_block):\n # Test that the output of the multi-head attention layer is correct\n queries = tf.ones(shape=(2, 5, 512))\n keys = tf.ones(shape=(2, 10, 512))\n values = tf.ones(shape=(2, 10, 512))\n valid_lens = tf.constant([5, 7])\n output, attn_weights = transformer_block.attention1(queries, queries, queries)\n assert output.shape == (2, 5, 512)\n assert attn_weights.shape == (2, 8, 5, 5)\n\n def test_positionwise_ffn(self, transformer_block):\n # Test that the output of the position-wise feedforward network is correct\n queries = tf.ones(shape=(2, 5, 512))\n keys = tf.ones(shape=(2, 10, 512))\n values = tf.ones(shape=(2, 10, 512))\n valid_lens = tf.constant([5, 7])\n output = transformer_block.ffn(queries)\n assert output.shape == (2, 5, 512)\n\n def test_clip_norm(self, transformer_block):\n block = TransformerDecoderBlock(\n d_model=512, num_heads=8, input_hidden_units_ffn=2048\n )\n block.clip_norm = 1.0\n queries = tf.ones(shape=(2, 5, 512))\n keys = tf.ones(shape=(2, 10, 512))\n values = tf.ones(shape=(2, 10, 512))\n valid_lens = tf.constant([5, 7])\n with tf.GradientTape(persistent=True) as tape:\n tape.watch([queries, keys, values])\n output, _, attn_weights = block(\n queries, keys, values, attention_mask=valid_lens\n )\n loss = tf.reduce_mean(output)\n grads = tape.gradient(loss, [queries, keys, values])\n clipped_grads, _ = tf.clip_by_global_norm(grads, clip_norm=block.clip_norm)\n # Check that the norm of the clipped gradients is less than or equal to clip_norm\n for clipped_grad in clipped_grads:\n assert tf.math.reduce_euclidean_norm(clipped_grad) <= block.clip_norm\n\n def htest_mixed_precision(self, transformer_block):\n # Test that the layer can run with mixed precision\n # tf.config.experimental.set_memory_growth(\n # tf.config.list_physical_devices(\"GPU\")[0], True\n # )\n tf.keras.mixed_precision.set_global_policy(\"mixed_float16\")\n\n # Create test inputs and labels\n input_tensor = tf.ones(shape=(2, 5, 512), dtype=tf.float16)\n output_tensor, _, _ = transformer_block(\n input_tensor, input_tensor, input_tensor\n )\n\n # Check that the output tensor is of the correct shape and dtype\n assert output_tensor.shape == (2, 5, 512)\n assert output_tensor.dtype == tf.float16\n # tf.keras.mixed_precision.set_global_policy(\"float32\")\n" }, { "alpha_fraction": 0.5481213331222534, "alphanum_fraction": 0.6109099984169006, "avg_line_length": 36.610328674316406, "blob_id": "5de9a8faace3e49ba090e416455c07b6f20e1170", "content_id": "2d960d3d54064c3c83bc8d4ef0718e2dc9784a52", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8011, "license_type": "permissive", "max_line_length": 225, "num_lines": 213, "path": "/transformerx/layers/positionwise_ffn.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import os\n\nimport tensorflow as tf\n\n\n# todo: remove commented old implementation after writing tests\n# class PositionWiseFFN(tf.keras.layers.Layer):\n# \"\"\"Compute position-wise feed-forward network [1]_.\n#\n# Consists of two dense layers with ReLU activation.\n#\n# See Also\n# --------\n# transformerx.layers.transformer_encoder_block\n# transformerx.layers.transformer_decoder_block\n#\n# Notes\n# -----\n# Position-Wise Feed-Forward Layer is a type of feedforward layer consisting of two dense layers that applies to the\n# last dimension, which means the same dense layers are used for each position item in the sequence, so called\n# position-wise.\n#\n# Parameters\n# ----------\n# input_hidden_units :\n# Number of input hidden units\n# output_hidden_units :\n# Number of output hidden units\n#\n# Returns\n# -------\n# Output :\n# A tensor of shape (batch size, number of time steps or sequence length in tokens, number of hidden units or\n# feature dimension)\n#\n# Examples\n# --------\n# >>> tf.random.set_seed(1)\n# >>> ffn = PositionWiseFFN(6, 4)\n# >>> x = tf.ones((2, 3, 6))\n# >>> print(ffn(x))\n# tf.Tensor(\n# [[[ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]\n# [ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]\n# [ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]]\n# [[ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]\n# [ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]\n# [ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]]], shape=(2, 3, 4), dtype=float32)\n#\n# References\n# ----------\n# .. [1] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I.\n# (2017). Attention Is All You Need. arXiv. https://doi.org/10.48550/arXiv.1706.03762\n# \"\"\"\n#\n# def __init__(self, input_hidden_units, output_hidden_units):\n# super().__init__()\n# self.dense1 = tf.keras.layers.Dense(input_hidden_units)\n# self.relu = tf.keras.layers.ReLU()\n# self.dense2 = tf.keras.layers.Dense(output_hidden_units)\n#\n# def call(self, x):\n# # x.shape: (batch size, number of time steps or sequence length in tokens, number of hidden units or\n# # feature dimension)\n# return self.dense2(self.relu(self.dense1(x)))\n#\n#\n\n\nclass PositionwiseFFN(tf.keras.layers.Layer):\n \"\"\"\n Position-wise feed-forward network layer.\n\n Consists of two dense layers with customizable activation functions, weight initialization, non-linear projection,\n and contextualized embeddings.\n\n Parameters\n ----------\n input_hidden_units : int\n Number of input hidden units.\n output_hidden_units : int\n Number of output hidden units.\n activation : str or callable, optional\n Activation function to use in the dense layers. Default is 'relu'.\n kernel_initializer : str or callable, optional\n Weight initialization strategy to use in the dense layers. Default is 'glorot_uniform'.\n non_linear_proj : str, optional\n Non-linear projection layer to use. Default is None, but you can also use 'glu' for a Gated Linear Unit or\n 'selu' for a Scaled Exponential Linear Unit. If non_linear_proj is not None, the output dimension will be twice\n the input dimension.\n contextualized_embeddings : `transformers.TFPreTrainedModel`, optional\n Contextualized embedding model to use, such as BERT or ELMo. If provided, the input tensor will be passed through\n the contextualized embedding model before being processed by the PositionWiseFFN layer.\n\n Returns\n -------\n output : `tf.Tensor`\n A tensor of shape `(batch size, number of time steps or sequence length in tokens, number of hidden units or\n feature dimension)`.\n\n Notes\n -----\n The Position-Wise Feed-Forward Layer is a type of feedforward layer consisting of two dense layers that apply to the\n last dimension, which means the same dense layers are used for each position item in the sequence, so called\n position-wise.\n\n Examples\n --------\n >>> tf.random.set_seed(1)\n >>> ffn = PositionwiseFFN(input_hidden_units=6, output_hidden_units=4, activation='tanh', kernel_initializer='he_uniform', non_linear_proj='glu', contextualized_embeddings=TFBertModel.from_pretrained('bert-base-uncased'))\n >>> x = tf.ones((2, 3, 6))\n >>> print(ffn(x))\n tf.Tensor(\n [[[ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]\n [ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]\n [ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]]\n [[ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]\n [ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]\n [ 0.51875997 -0.2624486 -0.79755557 1.5191057 ]]], shape=(2, 3, 4), dtype=float32)\n\n References\n ----------\n Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I.\n (2017). Attention Is All You Need. arXiv. https://doi.org/10.48550/arXiv.1706.03762\n \"\"\"\n\n def __init__(\n self,\n input_hidden_units=2048,\n # output_hidden_units=512,\n activation=\"relu\",\n dropout_rate=0.0,\n kernel_initializer=\"glorot_uniform\",\n bias_initializer=None,\n non_linear_proj=None,\n contextualized_embeddings=None,\n **kwargs\n ):\n super(PositionwiseFFN, self).__init__(**kwargs)\n self.input_hidden_units = input_hidden_units\n # self.output_hidden_units = output_hidden_units\n\n self.activation = activation\n self.kernel_initializer = kernel_initializer\n self.bias_initializer = bias_initializer\n\n self.non_linear_proj = non_linear_proj\n\n self.contextualized_embeddings = contextualized_embeddings\n self.dropout = tf.keras.layers.Dropout(rate=dropout_rate)\n\n def build(self, input_shape):\n super().build(input_shape)\n output_hidden_units = input_shape[-1]\n self.dense1 = tf.keras.layers.Dense(\n self.input_hidden_units,\n activation=self.activation,\n kernel_initializer=self.kernel_initializer,\n bias_initializer=self.bias_initializer,\n )\n\n if self.non_linear_proj == \"glu\":\n self.glu = tf.keras.layers.Dense(\n output_hidden_units,\n activation=\"sigmoid\",\n kernel_initializer=self.kernel_initializer,\n )\n elif self.non_linear_proj == \"selu\":\n self.selu = tf.keras.layers.Dense(\n output_hidden_units,\n activation=\"selu\",\n kernel_initializer=self.kernel_initializer,\n )\n else:\n self.dense2 = tf.keras.layers.Dense(\n output_hidden_units,\n activation=self.activation,\n kernel_initializer=self.kernel_initializer,\n )\n\n def call(self, x, **kwargs):\n # x.shape: (batch size, number of time steps or sequence length in tokens, number of hidden units or\n # feature dimension)\n if self.contextualized_embeddings is not None:\n bert_output = self.contextualized_embeddings(x)\n x = bert_output[0]\n\n if self.non_linear_proj is None:\n x = self.dropout(x)\n return self.dense2(self.dense1(x))\n else:\n x = self.dense1(x)\n x = self.dropout(x)\n if self.non_linear_proj == \"glu\":\n gate = tf.keras.activations.sigmoid(self.glu(x))\n return x * gate\n elif self.non_linear_proj == \"selu\":\n gate = tf.keras.activations.sigmoid(self.selu(x))\n return x * gate\n\n\nif __name__ == \"__main__\":\n tf.random.set_seed(1)\n # ffn = PositionWiseFFN(6, 4)\n ffn = PositionwiseFFN(\n input_hidden_units=32,\n output_hidden_units=64,\n activation=\"tanh\",\n kernel_initializer=\"he_uniform\",\n non_linear_proj=\"glu\",\n )\n x = tf.ones((2, 3, 32))\n print(ffn(x))\n" }, { "alpha_fraction": 0.5804597735404968, "alphanum_fraction": 0.5971786975860596, "avg_line_length": 33.17856979370117, "blob_id": "0491a55d54addb71d7ffe7af5e089ac280b630fb", "content_id": "68d0149f4bdb6e025c67048892ccf22ae6f93791", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1914, "license_type": "permissive", "max_line_length": 87, "num_lines": 56, "path": "/tests/layers/test_positional_encoding.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport pytest\n\n\nfrom transformerx.layers import SinePositionalEncoding\n\n\nclass TestAbsolutePositionalEncoding:\n @pytest.fixture\n def layer(self):\n depth = 16\n max_len = 20\n return SinePositionalEncoding(d_model=depth, maximum_position_encoding=max_len)\n\n def test_output_shape(self):\n depth = 64\n max_len = 100\n layer = SinePositionalEncoding(depth, maximum_position_encoding=max_len)\n input_shape = (5, max_len, depth)\n input_tensor = tf.ones(input_shape)\n output_tensor = layer(input_tensor)\n assert output_tensor.shape == input_shape\n\n def test_call_batch_size_1(self, layer):\n input_shape = (1, 10, layer.d_model)\n X = tf.ones(input_shape)\n output = layer(X)\n assert output.shape == input_shape\n assert not np.allclose(output.numpy(), X.numpy())\n assert np.allclose(\n output.numpy()[:, :5, :], X.numpy()[:, :5, :] + layer.P.numpy()[:, :5, :]\n )\n\n def test_call_batch_size_3(self, layer):\n input_shape = (3, 15, layer.d_model)\n X = tf.ones(input_shape)\n output = layer(X)\n assert output.shape == input_shape\n assert not np.allclose(output.numpy(), X.numpy())\n assert np.allclose(\n output.numpy()[:, :7, :], X.numpy()[:, :7, :] + layer.P.numpy()[:, :7, :]\n )\n\n def test_dropout(self):\n depth = 64\n max_len = 100\n dropout_rate = 0.5\n layer = SinePositionalEncoding(\n depth, dropout_rate=dropout_rate, maximum_position_encoding=max_len\n )\n input_shape = (5, max_len, depth)\n input_tensor = tf.ones(input_shape)\n output_tensor = layer(input_tensor)\n # Check that some values have been zeroed out due to dropout\n assert np.count_nonzero(output_tensor.numpy()) != np.prod(input_shape)\n" }, { "alpha_fraction": 0.5268672704696655, "alphanum_fraction": 0.5345692038536072, "avg_line_length": 30.36516761779785, "blob_id": "4c8aa2907457b32f8a6d305d364ab9fc53f18c25", "content_id": "59e4a45807b57ca484ca050c3ba120308741b0ac", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11166, "license_type": "permissive", "max_line_length": 101, "num_lines": 356, "path": "/transformerx/data_loader.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import collections\nimport hashlib\nimport os\nimport tarfile\nimport zipfile\nfrom typing import Optional, Tuple, List\n\nimport requests\nimport tensorflow as tf\n\n\nclass DataModule:\n \"\"\"Base class for data loaders\"\"\"\n\n def __init__(self, data_directory=\"./data\"):\n self.data_directory = data_directory\n\n def get_dataloader(self, train):\n raise NotImplementedError\n\n def train_dataloader(self):\n return self.get_dataloader(train=True)\n\n def val_dataloader(self):\n return self.get_dataloader(train=False)\n\n def get_tensorloader(\n self, tensors: List[tf.Tensor], train: bool, indices: int = slice(0, None)\n ):\n \"\"\"Prepare tensors for training\n\n Slice tensors, shuffle them if it is in training mode and then generate batches.\n\n Parameters\n ----------\n tensors : A list of tensors.\n train : Flag representing the training mode; True if it is in training mode, False otherwise.\n indices : Indices of slices to be processed in the downstream tasks.\n\n Returns\n -------\n Shuffled and batched dataset\n \"\"\"\n tensors = tuple(a[indices] for a in tensors)\n shuffle_buffer = tensors[0].shape[0] if train else 1\n return (\n tf.data.Dataset.from_tensor_slices(tensors)\n .shuffle(buffer_size=shuffle_buffer)\n .batch(self.batch_size)\n )\n\n\nclass Vocab:\n \"\"\"Vocabulary for text\"\"\"\n\n def __init__(\n self, tokens: list = [], min_freq: int = 0, reserved_tokens: Optional[list] = []\n ):\n \"\"\"Initialize the Vocab class\n\n Parameters\n ----------\n tokens : Tokens to be included in the vocab\n min_freq : Minimum frequency accepted while adding to the vocabulary\n reserved_tokens : Reserved tokens\n \"\"\"\n # Flatten a 2D list if needed\n if tokens and isinstance(tokens[0], list):\n tokens = [token for line in tokens for token in line]\n # Count token frequencies\n counter = collections.Counter(tokens)\n self.token_freqs = sorted(counter.items(), key=lambda x: x[1], reverse=True)\n # The list of unique tokens\n self.idx_to_token = list(\n sorted(\n set(\n [\"<unk>\"]\n + reserved_tokens\n + [token for token, freq in self.token_freqs if freq >= min_freq]\n )\n )\n )\n self.token_to_idx = {token: idx for idx, token in enumerate(self.idx_to_token)}\n\n def __len__(self):\n return len(self.idx_to_token)\n\n def __getitem__(self, tokens):\n if not isinstance(tokens, (list, tuple)):\n return self.token_to_idx.get(tokens, self.unk)\n return [self.__getitem__(token) for token in tokens]\n\n def to_tokens(self, indices: Tuple[int, list]) -> Tuple[int, list]:\n \"\"\"Get tokens for the specified indices\n\n Parameters\n ----------\n indices : Indices to return tokens for\n\n Returns\n -------\n Tokens for the specified indices\n \"\"\"\n if hasattr(indices, \"__len__\") and len(indices) > 1:\n return [self.idx_to_token[int(index)] for index in indices]\n return self.idx_to_token[indices]\n\n @property\n def unk(self):\n \"\"\"Special token unknown property\n\n Returns\n -------\n Index for the unknown token\n \"\"\"\n return self.token_to_idx[\"<unk>\"]\n\n\nclass BaseDataset(DataModule):\n \"\"\"Base dataset class for downloading and processing.\"\"\"\n\n def __init__(\n self,\n batch_size,\n num_steps=9,\n num_train=512,\n num_val=128,\n url=\"http://d2l-data.s3-accelerate.amazonaws.com/\",\n ):\n \"\"\"Initialize the class\n\n Parameters\n ----------\n batch_size : Size of the batches\n num_steps : Number of steps\n num_train : Number of training items\n num_val : Number of validation items\n \"\"\"\n super(BaseDataset, self).__init__()\n self.batch_size = batch_size\n self.num_steps = num_steps\n self.num_train = num_train\n self.num_val = num_val\n # self.save_hyperparameters()\n self.url = url\n self.arrays, self.src_vocab, self.tgt_vocab = self._build_arrays(\n self._download()\n )\n\n @staticmethod\n def download(url, folder: str = \"../data\", sha1_hash: str = None) -> str:\n \"\"\"Download a file to folder and return the local filepath.\n\n Parameters\n ----------\n folder : Directory to place the downloaded data into\n sha1_hash : SHA hash of the file\n\n Returns\n -------\n Path to the downloaded file\n \"\"\"\n os.makedirs(folder, exist_ok=True)\n fname = os.path.join(folder, url.split(\"/\")[-1])\n # Check if hit cache\n if os.path.exists(fname) and sha1_hash:\n sha1 = hashlib.sha1()\n with open(fname, \"rb\") as f:\n while True:\n data = f.read(1048576)\n if not data:\n break\n sha1.update(data)\n if sha1.hexdigest() == sha1_hash:\n return fname\n\n # Download\n print(f\"Downloading {fname} from {url}...\")\n r = requests.get(url, stream=True, verify=True)\n with open(fname, \"wb\") as f:\n f.write(r.content)\n return fname\n\n @staticmethod\n def extract(filename, folder: Optional[str] = None):\n \"\"\"Extract zip/tar file into the folder\n\n Parameters\n ----------\n filename : File name to be extracted\n folder : the path to locate the extracted files\n \"\"\"\n base_dir = os.path.dirname(filename)\n _, ext = os.path.splitext(filename)\n assert ext in (\".zip\", \".tar\", \".gz\"), \"Only support zip/tar files.\"\n\n if ext == \".zip\":\n fp = zipfile.ZipFile(filename, \"r\")\n else:\n fp = tarfile.open(filename, \"r\")\n\n if folder is None:\n folder = base_dir\n fp.extractall(folder)\n\n def _download(self):\n self.extract(\n self.download(\n self.url + \"fra-eng.zip\",\n self.data_directory,\n \"94646ad1522d915e7b0f9296181140edcf86a4f5\",\n )\n )\n with open(self.data_directory + \"/fra-eng/fra.txt\", encoding=\"utf-8\") as f:\n return f.read()\n\n @staticmethod\n def _preprocess(text: str) -> str:\n \"\"\"Preprocess input text by replacing breaking space with space.\n\n Parameters\n ----------\n text : Text to be preprocessed\n\n Returns\n -------\n Preprocessed text\n \"\"\"\n # Replace non-breaking space with space\n text = text.replace(\"\\u202f\", \" \").replace(\"\\xa0\", \" \")\n # Insert space between words and punctuation marks\n no_space = lambda char, prev_char: char in \",.!?\" and prev_char != \" \"\n out = [\n \" \" + char if i > 0 and no_space(char, text[i - 1]) else char\n for i, char in enumerate(text.lower())\n ]\n return \"\".join(out)\n\n @staticmethod\n def _tokenize(text: str, max_examples: int = None):\n \"\"\"Tokenize the input text\n\n Parameters\n ----------\n text : Text to be tokenized\n max_examples : Maximum number of lines of the input to be tokenized\n\n Returns\n -------\n Source and target lists of tokens\n \"\"\"\n src, tgt = [], []\n for i, line in enumerate(text.split(\"\\n\")):\n if max_examples and i > max_examples:\n break\n parts = line.split(\"\\t\")\n if len(parts) == 2:\n # Skip empty tokens\n src.append([t for t in f\"{parts[0]} <eos>\".split(\" \") if t])\n tgt.append([t for t in f\"{parts[1]} <eos>\".split(\" \") if t])\n return src, tgt\n\n def _build_arrays(self, raw_text, src_vocab=None, tgt_vocab=None):\n \"\"\"Build vocabs from the input text\n\n Parameters\n ----------\n raw_text : Input text to generate source and target vocabs from\n src_vocab : Source vocabulary\n tgt_vocab : Target vocabulary\n\n Returns\n -------\n Generated source and target vocabularies along with valid lens, src and tgt arrays\n \"\"\"\n\n def _build_array(sentences, vocab, is_tgt=False):\n pad_or_trim = lambda seq, t: (\n seq[:t] if len(seq) > t else seq + [\"<pad>\"] * (t - len(seq))\n )\n sentences = [pad_or_trim(s, self.num_steps) for s in sentences]\n if is_tgt:\n sentences = [[\"<bos>\"] + s for s in sentences]\n if vocab is None:\n vocab = Vocab(sentences, min_freq=2)\n array = tf.constant([vocab[s] for s in sentences])\n valid_len = tf.reduce_sum(tf.cast(array != vocab[\"<pad>\"], tf.int32), 1)\n return array, vocab, valid_len\n\n src, tgt = self._tokenize(\n self._preprocess(raw_text), self.num_train + self.num_val\n )\n src_array, src_vocab, src_valid_len = _build_array(src, src_vocab)\n tgt_array, tgt_vocab, _ = _build_array(tgt, tgt_vocab, True)\n\n return (\n (src_array, tgt_array[:, :-1], src_valid_len, tgt_array[:, 1:]),\n src_vocab,\n tgt_vocab,\n )\n\n def get_dataloader(self, train: bool):\n \"\"\"\n\n Parameters\n ----------\n train : Training mode indicator flag\n\n Returns\n -------\n\n \"\"\"\n idx = slice(0, self.num_train) if train else slice(self.num_train, None)\n return self.get_tensorloader(self.arrays, train, idx)\n\n def build(self, src_sentences, tgt_sentences):\n \"\"\"Build arrays\n\n Parameters\n ----------\n src_sentences : Source sentences\n tgt_sentences : Target sentences\n\n Returns\n -------\n arrays : source and target arrays\n \"\"\"\n raw_text = \"\\n\".join(\n [src + \"\\t\" + tgt for src, tgt in zip(src_sentences, tgt_sentences)]\n )\n arrays, _, _ = self._build_arrays(raw_text, self.src_vocab, self.tgt_vocab)\n return arrays\n\n\nclass EngFrDatasets(BaseDataset):\n \"\"\"Download data and preprocess\"\"\"\n\n def __init__(self, batch_size, num_steps=9, num_train=512, num_val=128):\n \"\"\"Initialize the class\n\n Parameters\n ----------\n batch_size : Size of the batches\n num_steps : Number of steps\n num_train : Number of training items\n num_val : Number of validation items\n \"\"\"\n super(EngFrDatasets, self).__init__()\n self.batch_size = batch_size\n self.num_steps = num_steps\n self.num_train = num_train\n self.num_val = num_val\n # self.save_hyperparameters()\n self.arrays, self.src_vocab, self.tgt_vocab = self._build_arrays(\n self._download()\n )\n" }, { "alpha_fraction": 0.6247190833091736, "alphanum_fraction": 0.6247190833091736, "avg_line_length": 23.72222137451172, "blob_id": "297b528dae5654e48b231c5ea374d0b18cc403dd", "content_id": "5e616ec015e65c786236b00b10006a6f8b17297a", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "permissive", "max_line_length": 74, "num_lines": 18, "path": "/transformerx/__backends__.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import sys\nimport numpy\n\nbackends_list = [\"tensorflow\", \"pytorch\", \"jax\", \"numpy\"]\n\n\n\ndef set_backend(backends_list: list = None, backend_instance: str = None):\n if not backend_instance == None:\n backend = backend_instance\n else:\n for backend_item in backends_list:\n if backend_item in sys.modules:\n backend = backend_item\n break\n return backend\n\nprint(set_backend(backends_list))\n" }, { "alpha_fraction": 0.5622283816337585, "alphanum_fraction": 0.5728960633277893, "avg_line_length": 37.93846130371094, "blob_id": "56c708cff31c1c80a0b8ddf0b34b3148ee42a6b7", "content_id": "0779ee51a215c34d5739e22791935ecb32249c51", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2531, "license_type": "permissive", "max_line_length": 105, "num_lines": 65, "path": "/transformerx/layers/masks/global_attention_mask.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\n\nclass GlobalAttentionMask:\n \"\"\"Global attention mask class.\n\n This class creates a global attention mask for the input.\n It is created by applying a random mask to the input.\n The mask is applied by randomly selecting a number of tokens from the input.\n The number of tokens selected is determined by the mask probability.\"\"\"\n\n def __init__(self, mask_type=\"none\", mask_prob=0.0, dilation_rate=1):\n self.mask_type = mask_type\n self.mask_prob = mask_prob\n self.dilation_rate = dilation_rate\n\n def get_mask(self, input_shape):\n if len(input_shape) == 4:\n # Assumes the input shape is 4-d ('b', 'h', 'l', 'd')\n input_shape = input_shape[1:]\n batch_size, seq_len = input_shape[0], input_shape[2]\n elif len(input_shape) == 3:\n # Assumes the input shape is 3-d ('b', 'l', 'd')\n batch_size, seq_len = input_shape[0], input_shape[1]\n elif len(input_shape) == 2:\n # Assumes the input shape is 2-d ('b', 'd')\n batch_size, seq_len = input_shape[0], input_shape[1]\n else:\n raise ValueError(\n \"The input shape must be 2-d ('b', 'd'), 3-d ('b', 'l', 'd') or 4-d ('b', 'h', 'l', 'd')\"\n )\n\n mask = tf.ones((batch_size, seq_len, seq_len), dtype=tf.float32)\n\n if self.mask_type == \"none\":\n pass\n\n elif self.mask_type == \"random\":\n mask = tf.where(\n tf.random.uniform((batch_size, seq_len, seq_len)) < self.mask_prob,\n tf.zeros((batch_size, seq_len, seq_len)),\n mask,\n )\n elif self.mask_type == \"dilated\":\n mask = self.create_dilated_mask(mask, self.dilation_rate)\n\n return mask\n\n # create a dilated mask method\n def create_dilated_mask(self, mask, dilation_rate):\n batch_size, seq_len = mask.shape[0], mask.shape[1]\n\n # Create a boolean mask where True indicates positions that need to be masked\n mask_bool = tf.math.logical_and(\n tf.math.abs(tf.range(seq_len) - tf.range(seq_len)[:, tf.newaxis])\n <= dilation_rate,\n tf.math.not_equal(tf.range(seq_len)[:, tf.newaxis], tf.range(seq_len)),\n )\n\n # Convert the boolean mask to float32\n mask_float = tf.cast(mask_bool, dtype=tf.float32)\n\n # Multiply the original mask with the dilated mask to apply the dilation\n dilated_mask = mask * mask_float\n return dilated_mask\n" }, { "alpha_fraction": 0.7172619104385376, "alphanum_fraction": 0.7202380895614624, "avg_line_length": 20.677419662475586, "blob_id": "ab96be991270e67d918cf82ad5078aaa6cae3c41", "content_id": "c259fbd7ac059c537390f3c5b6448cd2de409157", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 672, "license_type": "permissive", "max_line_length": 48, "num_lines": 31, "path": "/docs/source/transformerx.layers.rst", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "transformerx.layers package\n===========================\n\n.. automodule:: transformerx.layers\n :members:\n :undoc-members:\n :show-inheritance:\n\nSubpackages\n-----------\n\n.. toctree::\n :maxdepth: 4\n\n transformerx.layers.masks\n\nSubmodules\n----------\n\n.. toctree::\n :maxdepth: 4\n\n transformerx.layers.addnorm\n transformerx.layers.dot_product_attention\n transformerx.layers.multihead_attention\n transformerx.layers.positional_encoding\n transformerx.layers.positionwise_ffn\n transformerx.layers.transformer_decoder\n transformerx.layers.transformer_decoder_block\n transformerx.layers.transformer_encoder\n transformerx.layers.transformer_encoder_block\n" }, { "alpha_fraction": 0.5679012537002563, "alphanum_fraction": 0.604938268661499, "avg_line_length": 31.90625, "blob_id": "12db7119bf96a19057322adac3a222737231641c", "content_id": "f2664b56e49472a0563aedeabfdceb812100615e", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2106, "license_type": "permissive", "max_line_length": 64, "num_lines": 64, "path": "/tests/layers/test_positionwise_ffn.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import pytest\nimport tensorflow as tf\n\nfrom transformerx.layers import PositionwiseFFN\n\n\nclass TestPositionwiseFFN:\n @pytest.fixture\n def layer(self):\n return PositionwiseFFN(\n input_hidden_units=128,\n activation=\"relu\",\n kernel_initializer=\"glorot_uniform\",\n non_linear_proj=\"glu\",\n contextualized_embeddings=None,\n dropout_rate=0.1,\n )\n\n @pytest.fixture\n def layer_selu(self):\n return PositionwiseFFN(\n input_hidden_units=128,\n activation=\"relu\",\n kernel_initializer=\"glorot_uniform\",\n non_linear_proj=\"selu\",\n contextualized_embeddings=None,\n dropout_rate=0.1,\n )\n\n @pytest.fixture\n def layer_no_nonlinear(self):\n return PositionwiseFFN(\n input_hidden_units=128,\n activation=\"relu\",\n kernel_initializer=\"glorot_uniform\",\n non_linear_proj=None,\n contextualized_embeddings=None,\n dropout_rate=0.1,\n )\n\n def test_layer_output_shape(self, layer):\n input_tensor = tf.random.normal([32, 20, 128])\n output_tensor = layer(input_tensor)\n assert output_tensor.shape == (32, 20, 128)\n\n def test_layer_output_type(self, layer):\n input_tensor = tf.random.normal([32, 20, 128])\n output_tensor = layer(input_tensor)\n assert isinstance(output_tensor, tf.Tensor)\n\n def test_layer_glu_non_linear_proj(self, layer):\n input_tensor = tf.random.normal([32, 20, 128])\n output_tensor = layer(input_tensor)\n assert output_tensor.shape == (32, 20, 128)\n\n def test_layer_selu_non_linear_proj(self, layer_selu):\n input_tensor = tf.random.normal([32, 20, 128])\n output_tensor = layer_selu(input_tensor)\n assert output_tensor.shape == (32, 20, 128)\n\n def test_layer_no_non_linear_proj(self, layer_no_nonlinear):\n input_tensor = tf.random.normal([32, 20, 128])\n output_tensor = layer_no_nonlinear(input_tensor)\n assert output_tensor.shape == (32, 20, 128)\n" }, { "alpha_fraction": 0.6117630004882812, "alphanum_fraction": 0.6472572684288025, "avg_line_length": 36.05434799194336, "blob_id": "6933b28483413e74892d3644e217068cfe4ab2e5", "content_id": "2a3440a481b938570cf5e4d7460cef0beb3c9e45", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6818, "license_type": "permissive", "max_line_length": 91, "num_lines": 184, "path": "/tests/layers/test_multihead_attention.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import pytest\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom transformerx.layers import MultiHeadAttention\n\n\n# def test_multihead_attention():\n# # Create an instance of the MultiHeadAttention class with 4 attention heads\n# multihead = MultiHeadAttention(d_model=8, num_heads=4)\n#\n# # Define some input tensor with shape [batch_size, sequence_length, d_model]\n# x = tf.constant(np.random.random([2, 3, 8]), dtype=tf.float32)\n#\n# # Apply the multi-head attention to the input tensor\n# output = multihead(x, x, x)\n#\n# # Check that the output has the expected shape [batch_size, sequence_length, d_model]\n# assert output.shape == (2, 3, 8)\n#\n# # Create a test case for the MultiHeadAttention class\n# @pytest.fixture\n# def multihead_attention():\n# return MultiHeadAttention(d_model=8, num_heads=3, dropout_rate=0.0, bias=False)\n#\n# # Test the initialization of the MultiHeadAttention class\n# def test_multihead_attention_init(multihead_attention):\n# assert multihead_attention.d_model == 8\n# assert multihead_attention.num_heads == 3\n# assert multihead_attention.dropout_rate == 0.0\n# assert multihead_attention.bias == False\n#\n# def test_split_heads():\n# # Create a random tensor with 3 dimensions\n# x = tf.random.uniform((2, 3, 24))\n#\n# # Create a MultiHeadAttention layer with 4 attention heads\n# multihead = MultiHeadAttention(num_heads=8)\n#\n# # Test the split_heads method with x as input\n# assert multihead.split_heads(x).shape == (2, 8, 3, 3)\n#\n# def test_inverse_transpose_qkv(multihead_attention):\n# # Test 1\n# x = tf.random.uniform(shape=(2, 4, 3, 6))\n# expected_output_shape = (2, 3, 24)\n# output = multihead_attention.inverse_transpose_qkv(x)\n# assert output.shape == expected_output_shape\n#\n# # Test 2\n# x = tf.random.uniform(shape=(2, 1, 3, 6))\n# expected_output_shape = (2, 3, 6)\n# output = multihead_attention.inverse_transpose_qkv(x)\n# assert output.shape == expected_output_shape\n#\n# # Test 3\n# x = tf.random.uniform(shape=(2, 4, 1, 6))\n# expected_output_shape = (2, 1, 24)\n# output = multihead_attention.inverse_transpose_qkv(x)\n# assert output.shape == expected_output_shape\n#\n# # Set the random seed for reproducibility\n# np.random.seed(42)\n#\n# # Define the dimensions of the input tensor and the number of heads\n# d_model = 8\n# num_heads = 4\n#\n# # Create a random tensor as input\n# x = tf.constant(np.random.random([2, 3, d_model]), dtype=tf.float32)\n#\n# # Create a MultiHeadAttention object with the specified dimensions\n# multihead = MultiHeadAttention(d_model=d_model, num_heads=num_heads)\n#\n# # Test the call method\n# def test_call():\n# # The call method should return a tensor with the concatenated attention heads\n# output = multihead(x, x, x)\n# assert output.shape == (2, 3, d_model)\n#\n# # Test that the output has the expected number of attention heads\n# num_heads_output = output.shape[-1] / d_model\n# assert num_heads_output == num_heads\n#\n#\n\n\nclass TestMultiHeadAttention:\n @pytest.fixture\n def attention(self):\n return MultiHeadAttention(d_model=32, num_heads=4, dropout_rate=0.1)\n\n @pytest.fixture\n def attention_causal_mask(self):\n return MultiHeadAttention(\n d_model=32, num_heads=4, dropout_rate=0.1, causal_mask=True\n )\n\n @pytest.fixture\n def inputs(self):\n # Create some dummy input tensors for testing\n x = tf.constant(np.random.random([2, 3, 2]), dtype=tf.float32)\n y = tf.constant(np.random.random([2, 3, 2]), dtype=tf.float32)\n z = tf.constant(np.random.random([2, 3, 2]), dtype=tf.float32)\n return x, y, z\n\n def test_split_heads(self, attention):\n queries = tf.random.normal((3, 10, 16))\n queries_split = attention.split_heads(queries)\n assert queries_split.shape == (3, 4, 10, 4)\n\n def test_multihead_attention_init(self):\n # Test the initialization of the MultiHeadAttention class\n multihead = MultiHeadAttention(d_model=8)\n assert isinstance(multihead, MultiHeadAttention)\n\n def test_multihead_attention_call(self, inputs):\n # Test the call method of the MultiHeadAttention class\n x, y, z = inputs\n multihead = MultiHeadAttention(d_model=8)\n output, _ = multihead(x, y, z)\n assert output.shape == (2, 3, 8)\n\n def test_inverse_transpose_qkv(self, attention):\n queries_split = tf.random.normal((3, 4, 10, 4))\n queries = attention.inverse_transpose_qkv(queries_split)\n assert queries.shape == (3, 10, 16)\n\n def test_multihead_attention_with_mask(self):\n attention = MultiHeadAttention(d_model=64, num_heads=8)\n # create a batch of inputs and a mask\n inputs = tf.random.normal((32, 64, 128), dtype=tf.float32)\n\n attention_mask = tf.random.uniform((32, 1, 1, 64), maxval=2, dtype=tf.float32)\n # call the layer with the inputs and mask\n outputs, _ = attention(inputs, inputs, inputs, attention_mask=attention_mask)\n\n # check that the output shape is correct\n assert outputs.shape == (32, 64, 64)\n\n # check that the output values are not all zero\n assert not tf.reduce_all(tf.math.equal(outputs, 0.0))\n\n def test_call_with_causal_mask(self, attention_causal_mask):\n queries = tf.random.normal((4, 10, 32))\n values = tf.random.normal((4, 20, 32))\n keys = tf.random.normal((4, 20, 32))\n\n output, _ = attention_causal_mask(queries, values, keys)\n\n assert output.shape == (4, 10, 32)\n\n def test_call_with_both_masks(self, attention_causal_mask):\n queries = tf.random.normal((4, 10, 32))\n values = tf.random.normal((4, 10, 64))\n keys = tf.random.normal((4, 10, 32))\n attention_mask = tf.random.uniform((4, 10), maxval=2, dtype=tf.int32)\n\n output, _ = attention_causal_mask(\n queries, keys, values, attention_mask=attention_mask\n )\n\n assert output.shape == (4, 10, 32)\n\n def test_call_with_zero_mask(self, attention):\n queries = tf.random.normal((4, 10, 32))\n values = tf.random.normal((4, 10, 64))\n keys = tf.random.normal((4, 10, 32))\n attention_mask = tf.zeros((4, 10), dtype=tf.int32)\n\n output, _ = attention(queries, keys, values, attention_mask=attention_mask)\n\n assert output.shape == (4, 10, 32)\n\n def test_call_with_ones_mask(self, attention):\n queries = tf.random.normal((4, 10, 32))\n values = tf.random.normal((4, 10, 64))\n keys = tf.random.normal((4, 10, 32))\n attention_mask = tf.ones((4, 10), dtype=tf.int32)\n\n output, _ = attention(queries, keys, values, attention_mask=attention_mask)\n\n assert output.shape == (4, 10, 32)\n" }, { "alpha_fraction": 0.5699442625045776, "alphanum_fraction": 0.5914850234985352, "avg_line_length": 30.56800079345703, "blob_id": "e8434b75b50b86f967562a7bbbf5aea2c678d36c", "content_id": "a2c597dca067a8933376118103ee0488c2e944dd", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3946, "license_type": "permissive", "max_line_length": 103, "num_lines": 125, "path": "/transformerx/layers/masks/base.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\n\nclass BaseMask(tf.keras.layers.Layer):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def build_mask(self, inputs):\n raise NotImplementedError(\"Subclasses must implement build_mask method\")\n\n def call(self, inputs, *args, **kwargs):\n if tf.shape(inputs).shape == 4:\n pass\n elif tf.shape(inputs).shape == 3:\n inputs = tf.expand_dims(inputs, axis=1)\n else:\n raise f\"Invalid input shape. Expected 3D or 4D tensors, but received {len(inputs.shape)}D.\"\n mask = self.build_mask(inputs)\n return tf.add(inputs, mask * -1e9)\n\n\nclass LookAheadMask(BaseMask):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def build_mask(self, inputs):\n input_shape = tf.shape(inputs)\n if input_shape.shape == 4:\n print(\"input shape: \", input_shape)\n k_seq_len = input_shape[3]\n q_seq_len = input_shape[2]\n\n # mask = 1 - tf.linalg.band_part(tf.ones((q_seq_len, k_seq_len)), -1, 0)\n mask = (\n 1\n - tf.linalg.LinearOperatorLowerTriangular(\n tf.ones((q_seq_len, k_seq_len)), -1, 0\n ).to_dense()\n )\n return mask\n\n\nclass PaddingMask(BaseMask):\n def __init__(self, padding_value=0, multi_head=True, **kwargs):\n super().__init__(**kwargs)\n self.padding_value = padding_value\n self.multi_head = multi_head\n\n def build_mask(self, inputs):\n mask = tf.cast(tf.math.equal(inputs, self.padding_value), tf.float32)\n return mask\n\n\nclass PaddingMaskNew(tf.keras.layers.Layer):\n def __init__(self, multi_head=True, padding_value=0, **kwargs):\n super(PaddingMask, self).__init__(**kwargs)\n self.multi_head = multi_head\n self.padding_value = padding_value\n\n def build(self, input_shape):\n pass\n\n def call(self, inputs):\n seq = tf.cast(tf.math.equal(inputs, self.padding_value), tf.float32)\n seq = tf.expand_dims(seq, axis=1)\n if self.multi_head:\n seq = tf.expand_dims(seq, axis=1)\n return seq\n\n def get_config(self):\n config = super(PaddingMask, self).get_config()\n config.update({\"multi_head\": self.multi_head})\n return config\n\n\nif __name__ == \"__main__\":\n from transformerx.layers import DotProductAttention, MultiHeadAttention\n\n input_tensor = tf.random.uniform((2, 4, 6))\n q_input_tensor = tf.random.uniform((2, 4, 6))\n attn_o, attn_w = DotProductAttention()(q_input_tensor, q_input_tensor, input_tensor)\n\n print(\"attn_w.shape: \", attn_w.shape)\n la_mask = LookAheadMask()\n output_tensor = la_mask(attn_w)\n print(output_tensor.shape, output_tensor)\n\n multihead_attn = MultiHeadAttention(d_model=32, num_heads=4, dropout_rate=0.1)\n output, attn_w = multihead_attn(q_input_tensor, input_tensor, input_tensor)\n\n sample_input = tf.random.uniform((1, 1, 4, 2))\n # output_tensor = la_mask(attn_w)\n output_tensor = la_mask(sample_input)\n print(output_tensor.shape, output_tensor)\n\n data = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]\n # Create a 2D tensor\n data = tf.constant([[1, 2, 3], [4, 5, 6]])\n\n # Convert the dataset to a tensor\n # data_tensor = tf.constant(data, dtype=tf.float32)\n\n # Create a SequencePadding layer\n # sequence_padding_layer = PaddingLayer(0, 4)\n\n # padded_data = sequence_padding_layer(data)\n\n # Test input\n input_tensor = tf.constant(\n [\n [[1, 2, 0], [4, 5, 6], [7, 8, 9], [0, 0, 0]],\n [[1, 2, 3], [4, 5, 0], [0, 0, 0], [0, 0, 0]],\n ],\n dtype=tf.float32,\n )\n\n # Create a PaddingMask layer\n padding_mask_layer = PaddingMask()\n\n # Generate the padding mask\n # padding_mask = padding_mask_layer(input_tensor)\n # print(padding_mask.shape, padding_mask)\n\n lad_mask = la_mask(input_tensor)\n # print(lad_mask.shape, lad_mask)\n" }, { "alpha_fraction": 0.6056439280509949, "alphanum_fraction": 0.6393635869026184, "avg_line_length": 43.26956558227539, "blob_id": "30a4ab68681789c69fb285f629f58072c1b12a1c", "content_id": "b7cf77a8dc75778323b9901f4ec3b0ec208e9e97", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15275, "license_type": "permissive", "max_line_length": 240, "num_lines": 345, "path": "/transformerx/layers/multihead_attention.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom einops import rearrange\n\nfrom transformerx.layers.dot_product_attention import DotProductAttention\n\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n \"\"\"Compute Multi-Head [1]_ (masked) self- or cross- attention layer.\n\n An attention class that runs through an attention mechanism (i.e. most commonly scaled dot-product) several\n times in parallel. The independent attention outputs are then concatenated and linearly transformed into the\n expected dimension.\n\n This class implements a multi-head attention layer to be used in a Transformer model. The layer\n computes self-attention using dot-product attention, and applies linear transformations\n to the queries, keys, and values to project them into different subspaces. The resulting\n attention scores are then combined and transformed to produce the final output.\n\n The multi-head attention layer allows the model to attend to different positions and contexts\n in the input sequence, and to combine and weight these contexts in different ways to produce\n the final output. This can help the model to better capture long-range dependencies and\n complex patterns in the input data.\n\n The multi-head attention layer is composed of several attention heads, each of which\n computes an attention score for a subset of the queries, keys, and values. The attention\n scores are then combined and weighted to produce the final output for each attention head,\n and the outputs of the attention heads are concatenated and transformed to produce the\n final output of the layer.\n\n The layer can optionally use a window mask to prevent attention between elements that are\n too far apart in the input sequence. This can help the model to focus on local contexts and\n avoid attending to irrelevant positions in the input.\n\n See Also\n --------\n layers.dot_product_attention : The class for the dot-product attention mechanism.\n call : The method for computing the multi-head attention.\n\n Notes\n -----\n Intuitively, multiple attention heads allows for attending to parts of the sequence differently\n (e.g. longer-term dependencies versus shorter-term dependencies).\n\n For more please see [2]\n\n Mathematical equations\n ---------------------\n\n The multi-head attention mechanism computes the attention scores between the queries and key-value pairs using the dot product of their representations. The attention scores are then combined and transformed to produce the final output:\n\n .. math::\n Attention(Q, K, V) = softmax(\\\\frac{QK^T}{\\\\sqrt{d_k}})V\n\n Where:\n\n - :math:`Q` is the queries tensor, with shape (batch_size, no. of queries, depth)\n - :math:`K` is the keys tensor, with shape (batch_size, no. of key-value pairs, depth)\n - :math:`V` is the values tensor, with shape (batch_size, no. of key-value pairs, depth)\n - :math:`d_k` is the depth of the queries and keys\n - :math:`softmax` is the softmax function\n\n The final output of the multi-head attention is computed as a weighted sum of the transformed queries, keys, and values, with the attention scores as the weights:\n\n .. math::\n Output = Concat(head_1, \\\\dots, head_n)W^O\n\n Where:\n\n - :math:`head_i` is the output of the $i$-th attention head, with shape (batch_size, no. of queries, depth / num_heads)\n .. math::\n head_i = Attention(Q W^Q_i, K W^K_i, V W^V_i)\n - :math:`Concat` is the concatenation operation\n - :math:`W^O` is the linear transformation matrix, with shape (num_heads * depth, depth)\n\n The attention weights tensor is optional and can be used to visualize and analyze the attention mechanisms in the model. The attention weights tensor has shape (batch_size, no. of queries, no. of key-value pairs).\n\n Parameters\n ----------\n d_model : int\n The dimension of the model, i.e., the depth of the input and output tensors.\n num_heads : int\n Number of the heads in the multi-head attention\n dropout_rate : float\n The dropout rate to use for regularization. Float between 0 and 1.\n use_bias : bool, optional\n Whether to use bias terms in the linear transformations i.e. W_q, W_k, W_v, and W_o, by default False.\n\n Returns\n -------\n output:\n Concatenated tensors. Same shape as the queries.\n attention_weights:\n Optional tensor of attention weights.\n\n Methods\n -------\n split_heads(X)\n Transpose tensors for parallel computation of attention heads.\n inverse_transpose_qkv(X)\n Reverse the operation of split_heads.\n call(queries, keys, values, valid_lens, window_mask=None, **kwargs)\n Compute the multi-head attention for the given queries, keys, and values.\n\n Examples\n --------\n >>> import tensorflow as tf\n >>> import random\n >>> tf.random.set_seed(1)\n >>> random.seed(42)\n\n\n >>> x = tf.constant(tf.random.uniform([2, 3, 2]), dtype=tf.float32)\n >>> multihead = MultiHeadAttention(d_model=8, dropout_rate=0)\n >>> print(type(multihead))\n <class 'multihead_attention.MultiHeadAttention'>\n\n >>> output, attn_weights = multihead(x, x, x)\n >>> print(output)\n tf.Tensor(\n [[[ 0.27276292 -0.2744614 -0.06085328 -0.03441356 -0.1577001\n 0.33375 -0.7894692 -0.33158925]\n [ 0.2792416 -0.27180034 -0.06341933 -0.02869054 -0.15612581\n 0.33674437 -0.7850623 -0.3237151 ]\n [ 0.274466 -0.27393326 -0.06170867 -0.03307929 -0.15757665\n 0.33440444 -0.78846383 -0.3293347 ]]\n <BLANKLINE>\n [[ 0.44330204 -0.14170787 -0.1372787 0.3109271 -0.30478996\n 0.47728932 -0.8789958 -0.3304574 ]\n [ 0.44153026 -0.14282975 -0.13679348 0.30881953 -0.30498797\n 0.476456 -0.8804113 -0.33254212]\n [ 0.44139963 -0.14291355 -0.13675913 0.30866385 -0.3050046\n 0.4763937 -0.88051784 -0.3326969 ]]], shape=(2, 3, 8), dtype=float32)\n\n\n\n\n\n >>> tf.random.set_seed(1)\n >>> attention = MultiHeadAttention(d_model=16, num_heads=4, dropout_rate=0.1)\n >>> queries = tf.random.normal((3, 20, 16))\n >>> keys = tf.random.normal((3, 20, 16))\n >>> values = tf.random.normal((3, 20, 16))\n >>> valid_lens = tf.constant([3, 20])\n >>> output, _ = attention(queries, keys, values)\n >>> print(output.shape)\n (3, 20, 16)\n\n >>> window_mask = tf.ones((3, 10))\n >>> output, _ = attention(queries, keys, values, attention_mask=window_mask)\n >>> output.shape\n (3, 10, 16)\n\n\n References\n ----------\n .. [1] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, I. Polosukhin, Attention\n is all you need, in: NIPS, pp. 5998–6008.\n\n .. [2] Transformers in Action: Attention Is All You Need\n https://towardsdatascience.com/transformers-in-action-attention-is-all-you-need-ac10338a023a#d417\n \"\"\"\n\n def __init__(\n self,\n d_model: int = 512,\n num_heads: int = 8,\n dropout_rate: float = 0,\n use_bias: bool = False,\n attention: str = \"scaled_dotproduct\",\n causal_mask: bool = False,\n **kwargs,\n ):\n super(MultiHeadAttention, self).__init__(**kwargs)\n self.d_model = d_model\n self.num_heads = num_heads\n self.dropout_rate = dropout_rate\n self.use_bias = use_bias\n self.causal_mask = causal_mask\n if attention == \"scaled_dotproduct\" or attention == None:\n self.attention = DotProductAttention(\n self.dropout_rate, scaled=True, causal_mask=self.causal_mask\n )\n elif attention == \"dotproduct\":\n self.attention = DotProductAttention(\n self.dropout_rate, scaled=False, causal_mask=self.causal_mask\n )\n self.W_q = tf.keras.layers.Dense(self.d_model, use_bias=self.use_bias)\n self.W_k = tf.keras.layers.Dense(self.d_model, use_bias=self.use_bias)\n self.W_v = tf.keras.layers.Dense(self.d_model, use_bias=self.use_bias)\n self.W_o = tf.keras.layers.Dense(self.d_model, use_bias=self.use_bias)\n\n def split_heads(self, X: tf.Tensor) -> tf.Tensor:\n \"\"\"Transpose tensors for parallel computation of attention heads.\n\n First transposition produces a tensor of shape x: (batch_size, num_heads, no. of queries or key-value pairs,\n depth / num_heads).\n Next it is rearranged to a new order (batch_size * num_heads, no. of queries or key-value pairs,\n depth / num_heads) which is then passed to the last rearrangement and returned.\n\n Parameters\n ----------\n X : tf.Tensor\n Shape (batch_size, no. of queries or key-value pairs, depth).\n The tensor to be transposed and prepared for the multi-head attention layer (i.e. queries, keys, and values)\n Returns\n -------\n x : tf.Tensor\n Transposed tensor of shape ((batch_size * num_heads, no. of queries or key-value pairs, depth / num_heads)\n \"\"\"\n\n # x = tf.reshape(x, shape=(x.shape[0], x.shape[1], self.num_heads, -1))\n X = rearrange(X, \"b l (h dk) -> b l h dk\", h=self.num_heads)\n # x = tf.transpose(x, perm=(0, 2, 1, 3))\n X = rearrange(X, \"b l h dk -> b h l dk\")\n # return tf.reshape(x, shape=(-1, x.shape[2], x.shape[3]))\n # X = rearrange(X, \"b h l dk -> (b h) l dk\")\n return X\n\n def inverse_transpose_qkv(self, X: tf.Tensor) -> tf.Tensor:\n \"\"\"Reverses the operation of split_heads for the input array X.\n\n Parameters\n ----------\n X : tf.Tensor\n A tensor of shape (batch_size, num_heads, seq_len, head_dim).\n\n Returns\n -------\n tf.Tensor\n A tensor of shape (batch_size, seq_len, hidden_dim), where hidden_dim is the\n original hidden dimension of the input to split_heads.\n \"\"\"\n\n # transpose back to original shape: (batch_size, seq_len, num_heads, head_dim)\n X = rearrange(X, \"b h l d -> b l h d\")\n\n # concatenate num_heads dimension with head_dim dimension:\n X = rearrange(X, \"b l h d -> b l (h d)\")\n return X\n\n def call(\n self,\n queries: tf.Tensor,\n keys: tf.Tensor,\n values: tf.Tensor,\n attention_mask: tf.Tensor = None,\n **kwargs,\n ) -> tf.Tensor:\n \"\"\"Compute the multi-head attention for the given queries, keys, and values.\n\n This method computes the multi-head attention for the given queries, keys, and values,\n using the dot-product attention mechanism and the linear transformations defined\n in the constructor. The attention scores are then combined and transformed to produce\n the final output of the layer.\n\n The method optionally accepts a window mask, which is used to prevent attention\n between elements that are too far apart in the input sequence. This can help the model\n to focus on local contexts and avoid attending to irrelevant positions in the input.\n\n The method returns the final output tensor and an optional tensor containing the\n attention weights. The attention weights can be used for visualization and analysis\n of the attention mechanisms in the model.\n\n Parameters\n ----------\n queries : tf.Tensor\n The queries tensor. This tensor has shape (batch_size, no. of queries, depth).\n keys : tf.Tensor\n The keys tensor. This tensor has shape (batch_size, no. of key-value pairs, depth).\n values : tf.Tensor\n The values tensor. This tensor has shape (batch_size, no. of key-value pairs, depth).\n valid_lens : Union[tf.Tensor, tf.Tensor]\n The valid sequence lengths for the queries and keys. This tensor has shape\n (batch_size,) or (batch_size, no. of queries).\n window_mask : Optional[tf.Tensor], optional\n The window mask tensor, by default None. This tensor has shape\n (batch_size, no. of queries, no. of key-value pairs) and contains zeros\n for positions that should not attend to each other.\n\n Returns\n -------\n Tuple[tf.Tensor, Optional[tf.Tensor]]\n The final output tensor and the attention weights tensor. The output tensor has\n shape (batch_size, no. of queries, depth), and the attention weights tensor has\n shape (batch_size, no. of queries, no. of key-value pairs).\n\n Raises\n ------\n ValueError\n If the dimensions of the queries, keys, and values tensors are incompatible.\n\n Examples\n --------\n >>> import tensorflow as tf\n\n >>> queries = tf.random.normal([batch_size, no_of_queries, depth])\n >>> keys = tf.random.normal([batch_size, no_of_key_value_pairs, depth])\n >>> values = tf.random.normal([batch_size, no_of_key_value_pairs, depth])\n >>> valid_lens = tf.random.uniform([batch_size], minval=0, maxval=no_of_queries, dtype=tf.int32)\n\n >>> multihead_attn = MultiHeadAttention(d_model=depth, num_heads=num_heads, dropout_rate=dropout)\n >>> output, attention_weights = multihead_attn(queries, keys, values, valid_lens)\n\n Here is an example of how to use the call method with a window mask:\n\n >>> import tensorflow as tf\n\n >>> queries = tf.random.normal([batch_size, no_of_queries, depth])\n >>> keys = tf.random.normal([batch_size, no_of_key_value_pairs, depth])\n >>> values = tf.random.normal([batch_size, no_of_key_value_pairs, depth])\n >>> valid_lens = tf.random.uniform([batch_size], minval=0, maxval=no_of_queries, dtype=tf.int32)\n >>> window_mask = tf.random.uniform([batch_size, no_of_queries, no_of_key_value_pairs], 0, 2, dtype=tf.int32)\n\n >>> multihead_attn = MultiHeadAttention(d_model=depth, num_heads=num_heads, dropout_rate=dropout)\n >>> output, attention_weights = multihead_attn(queries, keys, values, valid_lens, window_mask)\n \"\"\"\n\n # Shape of queries, keys, or values:\n # (batch_size, no. of queries or key-value pairs, depth)\n # Shape of attention_mask: (batch_size,) or (batch_size, no. of queries)\n # After transposing, shape of output queries, keys, or values:\n # (batch_size * num_heads, no. of queries or key-value pairs,\n # depth / num_heads)\n\n queries = self.split_heads(self.W_q(queries))\n keys = self.split_heads(self.W_k(keys))\n values = self.split_heads(self.W_v(values))\n\n if attention_mask is not None:\n # On axis 0, copy the first item (scalar or vector) for num_heads\n # times, then copy the next item, and so on\n attention_mask = tf.repeat(attention_mask, repeats=self.num_heads, axis=0)\n\n # Shape of output: (batch_size * num_heads, no. of queries,\n # depth / num_heads)\n print(\"multihead q: \", queries.shape)\n attention_output, attention_weights = self.attention(\n queries, keys, values, attention_mask, **kwargs\n )\n\n # Shape of output_concat: (batch_size, no. of queries, depth)\n output_concat = self.inverse_transpose_qkv(attention_output)\n final_output = self.W_o(output_concat)\n\n return final_output, attention_weights\n" }, { "alpha_fraction": 0.6274877190589905, "alphanum_fraction": 0.6347459554672241, "avg_line_length": 27.844594955444336, "blob_id": "5edde79e0d5b0c0096d00c0851a6ad14c08d6fe3", "content_id": "af3b80b4c19537a9756a7c301c489fe188e57bf3", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4279, "license_type": "permissive", "max_line_length": 113, "num_lines": 148, "path": "/setup.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import io\nimport os\nimport sys\nfrom shutil import rmtree\n\nfrom setuptools import setup, find_packages, Command\n\nwith open(\"README.md\", \"r\") as readme_file:\n readme = readme_file.read()\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nNAME = \"TransformerX\"\nDESCRIPTION = \"TransformerX is a python library for building transformer-based models using ready-to-use layers.\"\n\nPLATFORMS = [\"Linux\", \"Mac OSX\", \"Windows\", \"Unix\"]\nVERSION = None\nAUTHORS = {\n \"Soran\": (\"Soran Ghaderi\", \"[email protected]\"),\n \"Taleb\": (\"Taleb Zarhesh\", \"[email protected]\"),\n}\n\nMAINTAINER = \"TensorOps Developers\"\nMAINTAINER_EMAIL = \"[email protected]\"\n\nKEYWORDS = [\n \"transformer\",\n \"deep-learning\",\n \"machine-learning\",\n \"NLP\",\n \"natural-language-processing\",\n \"computer-vision\",\n \"cv\",\n \"vision\",\n \"speech-recognition\",\n]\n\nCLASSIFIERS = [\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n \"Intended Audience :: Science/Research\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Education\",\n \"Topic :: Scientific/Engineering :: Mathematics\",\n \"Topic :: Scientific/Engineering :: Physics\",\n]\n\n# Import the README and use it as the long-description.\n# Note: this will only work if 'README.md' is present in your MANIFEST.in file!\ntry:\n with io.open(os.path.join(here, \"README.md\"), encoding=\"utf-8\") as f:\n long_description = \"\\n\" + f.read()\nexcept FileNotFoundError:\n long_description = readme\n\n# Load the package's __version__.py module as a dictionary.\nabout = {}\nif not VERSION:\n project_slug = NAME.lower().replace(\"-\", \"_\").replace(\" \", \"_\")\n with open(os.path.join(here, project_slug, \"__version__.py\")) as f:\n exec(f.read(), about)\nelse:\n about[\"__version__\"] = VERSION\n\n\ndef parse_requirements_file(filename):\n with open(filename) as fid:\n requires = [l.strip() for l in fid.readlines() if not l.startswith(\"#\")]\n\n return requires\n\n\n# extras_require = {\n# dep: parse_requirements_file(\"requirements/\" + dep + \".txt\")\n# for dep in [\"developer\", \"doc\", \"extra\", \"test\"]\n# }\n# requirements = parse_requirements_file(\"requirements/default.txt\")\n# requirements = ['networkx']\n\nclass UploadCommand(Command):\n \"\"\"Support setup.py upload.\"\"\"\n\n user_options = []\n\n @staticmethod\n def status(s):\n \"\"\"Prints things in bold.\"\"\"\n print(\"\\033[1m{0}\\033[0m\".format(s))\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n try:\n self.status(\"Removing previous builds…\")\n rmtree(os.path.join(here, \"dist\"))\n except OSError:\n pass\n\n self.status(\"Building Source and Wheel (universal) distribution…\")\n os.system(\"{0} setup.py sdist bdist_wheel --universal\".format(sys.executable))\n\n self.status(\"Uploading the package to PyPI via Twine…\")\n os.system(\"twine upload dist/*\")\n\n self.status(\"Pushing git tags…\")\n os.system(\"git tag v{0}\".format(about[\"__version__\"]))\n os.system(\"git push --tags\")\n\n sys.exit()\n\nsetup(\n name=NAME,\n version=about[\"__version__\"],\n maintainer=MAINTAINER,\n maintainer_email=MAINTAINER_EMAIL,\n author=AUTHORS[\"Soran\"][0],\n author_email=AUTHORS[\"Soran\"][1],\n description=DESCRIPTION,\n long_description=readme,\n keywords=KEYWORDS,\n platforms=PLATFORMS,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/tensorops/TransformerX\",\n packages=find_packages(exclude=(\"tests\", \"docs\", \"html\", \"requirements\")),\n # install_requires=requirements,\n # extras_require=extras_require,\n classifiers=CLASSIFIERS,\n python_requires=\">=3.6\",\n zip_safe=False,\n license=\"Apache-2.0\",\n cmdclass={\n 'upload': UploadCommand,\n },\n)\n\n\n" }, { "alpha_fraction": 0.7325227856636047, "alphanum_fraction": 0.7325227856636047, "avg_line_length": 20.933332443237305, "blob_id": "2b4b32471f8ebda74746d652d21d8633feb5aa84", "content_id": "c0c1660b446a1cd062a8c1dc3cf8ee76c2d32ab3", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 329, "license_type": "permissive", "max_line_length": 60, "num_lines": 15, "path": "/.github/ISSUE_TEMPLATE/subtask-template.md", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "---\nname: Subtask template\nabout: Create a subtask issue to reference in a pull request\ntitle: \"[Issue name] [#Issue_number]\"\nlabels: Subtask\nassignees: ''\n\n---\n\n**Naming convention**\n[issue name in the subtasks] [#main_issue_number]\n\n**Describe the issue in more details**\n\n**Provide other additional information if available**\n" }, { "alpha_fraction": 0.5858984589576721, "alphanum_fraction": 0.6126019358634949, "avg_line_length": 40.09189224243164, "blob_id": "7687eedf295425b4431dacddca70441fdbe95c75", "content_id": "d8fb743bc5ed64e90fbf82b62b908c75fc396884", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7602, "license_type": "permissive", "max_line_length": 91, "num_lines": 185, "path": "/tests/layers/test_transformer_decoder.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pytest\nimport tensorflow as tf\nfrom transformerx.layers import TransformerDecoder, TransformerEncoder\n\n\nclass TestTransformerDecoder:\n @pytest.fixture\n def decoder(self):\n return TransformerDecoder(vocab_size=1000)\n\n @pytest.fixture\n def inputs(self):\n queries = tf.zeros(\n (2, 3)\n ) # this is the target sequence and will go through the embedding layer before the\n # decoder -> converted to shape (2, 3, 512)\n keys = tf.zeros((2, 3, 512))\n values = tf.zeros((2, 3, 512))\n return queries, keys, values\n\n def test_transformer_decoder_creation(self, decoder):\n assert isinstance(decoder, TransformerDecoder)\n assert decoder is not None\n\n def test_initialization(self, decoder):\n assert decoder.vocab_size == 1000\n assert decoder.d_model == 512\n assert decoder.num_heads == 8\n assert decoder.n_blocks == 6\n assert decoder.maxlen_position_encoding == 10000\n assert decoder.attention_dropout == 0.0\n assert decoder.norm_type == \"layer\"\n assert decoder.norm_eps == 1e-6\n assert decoder.use_norm == True\n assert decoder.rescale_embedding == False\n assert decoder.dropout_rate == 0.1\n assert decoder.attention_mechanism == \"scaled_dotproduct\"\n assert decoder.input_hidden_units_ffn == 64\n assert decoder.residual_connections == (True, True)\n assert decoder.activation_fn == tf.nn.relu\n assert decoder.non_linear_proj == None\n assert decoder.clip_norm == 1.0\n assert isinstance(\n decoder.kernel_initializer, tf.keras.initializers.GlorotUniform\n )\n assert isinstance(decoder.bias_initializer, tf.keras.initializers.Zeros)\n assert isinstance(decoder.kernel_regularizer, tf.keras.regularizers.l2)\n assert decoder.bias_regularizer == None\n assert decoder.mixed_precision == False\n assert decoder.learning_rate_schedule == None\n assert decoder.use_bias == True\n assert decoder.contextualized_embeddings == None\n\n def test_apply_positional_embedding(self, decoder):\n inputs = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n embedded_inputs = decoder.apply_positional_embedding(inputs)\n assert embedded_inputs.shape == (2, 3, 512)\n\n def test_positional_encoding_output_shape(self, decoder):\n input_data = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n embedded_data = decoder.embedding(input_data)\n pos_encoded_data = decoder.pos_encoding(embedded_data)\n assert pos_encoded_data.shape == (2, 3, 512)\n\n def test_call(self, decoder):\n queries = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n keys = tf.random.uniform((2, 3, 512))\n values = tf.random.uniform((2, 3, 512))\n output, attn_weights = decoder(queries, keys, values)\n assert output.shape == (2, 3, 512)\n assert len(attn_weights) == 6\n for attn_weights in attn_weights:\n assert attn_weights.shape == (2, 8, 3, 3)\n\n def test_decoder_output_shape(self, decoder, inputs):\n queries, keys, values = inputs\n output, attn_weights = decoder(queries, keys, values)\n assert output.shape == (2, 3, 512)\n assert len(attn_weights) == decoder.n_blocks\n\n def test_decoder_block_output_shape(self, decoder, inputs):\n queries, keys, values = inputs\n queries = tf.keras.layers.Embedding(1000, 512)(queries)\n output, attn_weights, attn_weights2 = decoder.blocks[0](queries, keys, values)\n assert output.shape == (2, 3, 512)\n\n def test_decoder_output_values(self, decoder, inputs):\n queries, keys, values = inputs\n valid_lens = tf.constant([3, 2], dtype=tf.float32)\n output, attn_weights = decoder(queries, keys, values)\n assert not np.allclose(output.numpy(), np.zeros((2, 3, 512)))\n\n def test_decoder_attention_weights_shape(self, decoder, inputs):\n queries, keys, values = inputs\n valid_lens = tf.constant([3, 2], dtype=tf.float32)\n ouputs, attn_weights = decoder(queries, keys, values)\n for attention_weights in attn_weights:\n assert attention_weights.shape == (2, 8, 3, 3)\n\n def test_decoder_attention_weights_values(self, decoder, inputs):\n queries, keys, values = inputs\n valid_lens = tf.constant([3, 2], dtype=tf.float32)\n ouputs, attn_weights = decoder(queries, keys, values)\n for attention_weights in attn_weights:\n assert not np.allclose(attention_weights.numpy(), np.zeros((2, 8, 3, 3)))\n\n\nclass TestTransformerDecoderIntegration:\n seq_length = 5\n vocab_size = 8\n\n @staticmethod\n def create_toy_dataset(\n num_samples=1000, seq_length=10, vocab_size=64, num_classes=2\n ):\n # x = np.random.randint(0, vocab_size, size=(num_samples, seq_length))\n # x = np.random.normal(\n # (vocab_size // 2), (vocab_size // 2 - 1), size=(num_samples, seq_length)\n # )\n x = tf.random.normal(\n shape=(num_samples, seq_length),\n mean=vocab_size // 2,\n stddev=vocab_size / 2 - 3,\n )\n # y = np.random.randint(0, 2, size=(num_samples, 1))\n # y = np.random.normal(1, 1, size=(num_samples, seq_length))\n y = tf.cast(tf.math.greater(x, vocab_size / 2), tf.int32)\n print(\"x: \", x.shape)\n print(\"y: \", y.shape)\n print(\"vocab: \", vocab_size, vocab_size / 2, vocab_size // 2)\n print(\"x: \", x[:5, :5])\n print(\"y: \", y[:5, :5])\n\n # x_train = tf.random.normal(\n # shape=(num_samples, seq_length), mean=vocab_size, dtype=tf.int32\n # )\n # y_train = tf.random.normal(\n # shape=(num_samples, 1), maxval=num_classes, dtype=tf.int32\n # )\n return x, y\n\n @pytest.fixture(scope=\"class\")\n def model(self):\n num_classes = 2\n num_samples = 128\n num_head = 1\n encoder = TransformerEncoder(\n vocab_size=self.vocab_size,\n maxlen_position_encoding=self.seq_length,\n num_heads=num_head,\n d_model=16,\n n_blocks=1,\n )\n decoder = TransformerDecoder(\n vocab_size=self.vocab_size,\n num_heads=num_head,\n maxlen_position_encoding=self.seq_length,\n d_model=64,\n n_blocks=1,\n )\n assert isinstance(encoder, TransformerEncoder)\n assert isinstance(decoder, TransformerDecoder)\n print(\"cheked enc dec: \", encoder, decoder)\n inputs = tf.keras.layers.Input(shape=[self.seq_length])\n tgt_inputs = tf.keras.layers.Input(shape=(self.seq_length,))\n enc_output, attn_weights = encoder(inputs)\n print(\"enc_ouput: \", enc_output.shape)\n dec_output, attn_weights_dec = decoder(tgt_inputs, enc_output, enc_output)\n predictions = tf.keras.layers.Dense(1, activation=\"sigmoid\")(dec_output)\n\n model = tf.keras.Model(inputs=[inputs, tgt_inputs], outputs=predictions)\n model.compile(\n optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"]\n )\n print(model.summary())\n return model\n\n def test_model_creation(self, model):\n x, y = self.create_toy_dataset(\n num_samples=100, vocab_size=self.vocab_size, seq_length=self.seq_length\n )\n history = model.fit([x, x], y, epochs=100, batch_size=32, validation_split=0.2)\n assert isinstance(model, tf.keras.Model)\n assert model is not None\n" }, { "alpha_fraction": 0.6509822010993958, "alphanum_fraction": 0.6582914590835571, "avg_line_length": 26.708860397338867, "blob_id": "6eb8e4e48d8124fa3890fce827554b1de0cd9251", "content_id": "7533edaa47434ffa225ad3695220e5ff3b81db64", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2189, "license_type": "permissive", "max_line_length": 87, "num_lines": 79, "path": "/docs/source/conf.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\nimport os\nimport sys\n\n# sys.path.insert(0, os.path.abspath(\"../../transformerx/\"))\nfrom datetime import datetime\nfrom pygments.styles import get_style_by_name\n\nPYTHONPATH = \"../../transformerx/\"\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = \"TransformerX\"\ncopyright = \"2023, TensorOps\"\nauthor = \"TensorOps\"\nrelease = \"v1.0.0-rc\"\n\n# style = get_style_by_name(\"friendly\")\n# style.background_color = \"#f3f2f1\"\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n # \"sphinx_rtd_theme\",\n \"furo\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosummary\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.mathjax\",\n \"sphinx_markdown_builder\",\n]\n\ntemplates_path = [\"_templates\"]\n\nnapoleon_use_rtype = False\n\nnapoleon_include_init_with_doc = True\nnapoleon_google_docstring = True\nnapoleon_use_param = True\nnapoleon_use_ivar = True\n\n# pygments_style = \"friendly\"\n\nlanguage = \"english\"\n\n\nexclude_patterns = []\n\n\n# html_theme = \"sphinx_rtd_theme\"\nhtml_theme = \"furo\"\nhtml_title = \"TransformerX Documentation\"\nhtml_show_sourcelink = False\nhtml_baseurl = \"https://github.com/tensorops/transformerx\"\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\n# html_theme = \"alabaster\"\nhtml_static_path = [\"_static\"]\n\nhtml_theme_options = {\n \"enable_search_shortcuts\": True,\n \"globaltoc_collapse\": True,\n \"prev_next_buttons_location\": \"both\",\n # \"style_nav_header_background\": \"#F5A603\",\n \"navigation_depth\": 2,\n \"collapse_navigation\": True,\n \"sticky_navigation\": False,\n \"logo_only\": False,\n \"display_version\": True,\n \"style_external_links\": True,\n \"titles_only\": True,\n}\n\nnapoleon_use_param = False\n" }, { "alpha_fraction": 0.5858110189437866, "alphanum_fraction": 0.5921401381492615, "avg_line_length": 34.757896423339844, "blob_id": "a91a9aa811429ac558b1ff464eaed26bc62c693b", "content_id": "25b730750c54c61fc9f221f1884fe7144eceedcd", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6794, "license_type": "permissive", "max_line_length": 101, "num_lines": 190, "path": "/transformerx/training/base.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\n\n# import examples.eng2fr_translation\n\n\nclass Module(tf.keras.Model):\n \"\"\"Base class for models\"\"\"\n\n def __init__(self, plot_train_per_epoch=2, plot_valid_per_epoch=1):\n super().__init__()\n # self.save_hyperparameters()\n self.training = None\n self.plot_train_per_epoch = plot_train_per_epoch\n self.plot_valid_per_epoch = plot_valid_per_epoch\n\n def loss(self, y_hat, y):\n raise NotImplementedError\n\n def forward(self, X):\n assert hasattr(self, \"net\"), \"Neural network is defined\"\n return self.net(X)\n\n def call(self, X, *args, **kwargs):\n if kwargs and \"training\" in kwargs:\n self.training = kwargs[\"training\"]\n return self.forward(X, *args)\n\n def training_step(self, batch):\n l = self.loss(self(*batch[:-1]), batch[-1])\n # self.plot(\"loss\", l, train=True)\n return l\n\n def validation_step(self, batch):\n l = self.loss(self(*batch[:-1]), batch[-1])\n self.plot(\"loss\", l, train=False)\n\n def configure_optimizers(self):\n \"\"\"Return optimizer\"\"\"\n return tf.keras.optimizers.SGD(self.lr)\n\n\nclass Classifier(Module):\n \"\"\"Classifier class\"\"\"\n\n def validation_step(self, batch):\n Y_hat = self(*batch[:-1])\n self.plot(\"loss\", self.loss(Y_hat, batch[-1]), train=False)\n self.plot(\"acc\", self.accuracy(Y_hat, batch[-1]), train=False)\n\n @staticmethod\n def accuracy(Y_hat, Y, averaged=True):\n \"\"\"Compute the number of correct predictions\"\"\"\n Y_hat = tf.reshape(Y_hat, (-1, Y_hat.shape[-1]))\n preds = tf.astype(tf.argmax(Y_hat, axis=1), Y.dtype)\n compare = tf.astype(preds == tf.reshape(Y, -1), tf.float32)\n return tf.reduce_mean(compare) if averaged else compare\n\n @staticmethod\n def loss(Y_hat, Y, averaged=True):\n \"\"\"Compute loss\"\"\"\n Y_hat = tf.reshape(Y_hat, (-1, Y_hat.shape[-1]))\n Y = tf.reshape(Y, (-1,))\n fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n return fn(Y, Y_hat)\n\n def layer_summary(self, X_shape):\n \"\"\"Layer summary\"\"\"\n X = tf.random.normal(X_shape)\n for layer in self.net.layers:\n X = layer(X)\n print(layer.__class__.__name__, \"output shape:\\t\", X.shape)\n\n\nclass EncoderDecoder(Classifier):\n \"\"\"Encoder-decoder architecture base class\"\"\"\n\n def __init__(self, encoder, decoder):\n super().__init__()\n self.encoder = encoder\n self.decoder = decoder\n\n def call(self, enc_X, dec_X, *args):\n enc_outputs = self.encoder(enc_X, *args, training=True)\n dec_state = self.decoder.init_state(enc_outputs, *args)\n # Return decoder output only\n return self.decoder(dec_X, dec_state, training=True)[0]\n\n def predict_step(self, batch, num_steps, save_attention_weights=False):\n src, tgt, src_valid_len, _ = batch\n enc_outputs = self.encoder(src, src_valid_len, training=False)\n dec_state = self.decoder.init_state(enc_outputs, src_valid_len)\n outputs, attention_weights = [\n tf.expand_dims(tgt[:, 0], 1),\n ], []\n for _ in range(num_steps):\n Y, dec_state = self.decoder(outputs[-1], dec_state, training=False)\n outputs.append(tf.argmax(Y, 2))\n # Save attention weights (to be covered later)\n if save_attention_weights:\n attention_weights.append(self.decoder.attention_weights)\n return tf.concat(outputs[1:], 1), attention_weights\n\n\nclass Transformer(EncoderDecoder):\n def __init__(self, encoder, decoder, tgt_pad, lr):\n super().__init__(encoder, decoder)\n # self.save_hyperparameters()\n self.tgt_pad = tgt_pad\n self.lr = lr\n\n def validation_step(self, batch):\n Y_hat = self(*batch[:-1])\n # self.plot(\"loss\", self.loss(Y_hat, batch[-1]), train=False)\n\n def configure_optimizers(self):\n # Adam optimizer is used here\n return tf.keras.optimizers.Adam(learning_rate=self.lr)\n\n\nclass Trainer:\n def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):\n # self.save_hyperparameters()\n self.val_batch_idx = None\n self.train_batch_idx = None\n self.epoch = None\n self.optim = None\n assert num_gpus == 0, \"No GPU support yet\"\n self.max_epochs = max_epochs\n self.gradient_clip_val = gradient_clip_val\n\n def prepare_data(self, data):\n self.train_dataloader = data.train_dataloader()\n self.val_dataloader = data.val_dataloader()\n # self.num_train_batches = len(self.train_dataloader)\n # self.num_val_batches = (len(self.val_dataloader) if self.val_dataloader is not None else 0)\n\n def prepare_model(self, model):\n # examples.eng2fr_translation.trainer = self\n # model.board.xlim = [0, self.max_epochs]\n self.model = model\n\n def fit(self, model, data):\n self.prepare_data(data)\n self.prepare_model(model)\n self.optim = model.configure_optimizers()\n self.epoch = 0\n self.train_batch_idx = 0\n self.val_batch_idx = 0\n for self.epoch in range(self.max_epochs):\n self.fit_epoch()\n\n @staticmethod\n def prepare_batch(batch):\n \"\"\"Prepare batch\"\"\"\n return batch\n\n def fit_epoch(self):\n \"\"\"Train the model\"\"\"\n self.model.training = True\n for batch in self.train_dataloader:\n with tf.GradientTape() as tape:\n loss = self.model.training_step(self.prepare_batch(batch))\n grads = tape.gradient(loss, self.model.trainable_variables)\n if self.gradient_clip_val > 0:\n grads = self.clip_gradients(self.gradient_clip_val, grads)\n self.optim.apply_gradients(zip(grads, self.model.trainable_variables))\n self.train_batch_idx += 1\n\n if self.val_dataloader is None:\n return\n self.model.training = False\n for batch in self.val_dataloader:\n self.model.validation_step(self.prepare_batch(batch))\n self.val_batch_idx += 1\n\n @staticmethod\n def clip_gradients(grad_clip_val, grads):\n \"\"\"Clip the gradients\"\"\"\n grad_clip_val = tf.constant(grad_clip_val, dtype=tf.float32)\n new_grads = [\n tf.convert_to_tensor(grad) if isinstance(grad, tf.IndexedSlices) else grad\n for grad in grads\n ]\n norm = tf.math.sqrt(sum((tf.reduce_sum(grad ** 2)) for grad in new_grads))\n if tf.greater(norm, grad_clip_val):\n for i, grad in enumerate(new_grads):\n new_grads[i] = grad * grad_clip_val / norm\n return new_grads\n return grads\n" }, { "alpha_fraction": 0.84375, "alphanum_fraction": 0.84375, "avg_line_length": 31, "blob_id": "6c12ab866d2992c5582e30700b1fc4d80e6ce079", "content_id": "80c100df292b35d4eec36f6dff71a27b7dca084d", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32, "license_type": "permissive", "max_line_length": 31, "num_lines": 1, "path": "/transformerx/layers/masks/__init__.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "from .base import LookAheadMask\n" }, { "alpha_fraction": 0.6030288934707642, "alphanum_fraction": 0.6195502281188965, "avg_line_length": 37.56637191772461, "blob_id": "50b9344ef1e757d7d67f4347f30d1a805e29efa3", "content_id": "11634428fd4e88f5d45f202beb91375cadcb7763", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4358, "license_type": "permissive", "max_line_length": 117, "num_lines": 113, "path": "/tests/layers/test_dot_product_attention.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom transformerx.layers import DotProductAttention\n\n\nclass TestDotProductAttention:\n \"this class tests the dot-product attention class\"\n\n # Set up the test class with some test data\n @pytest.fixture(autouse=True)\n def setup(self):\n self.x = tf.cast(np.random.random([2, 3, 2]), dtype=tf.float32)\n self.dot_product_scaled = DotProductAttention(0.2)\n self.dot_product_unscaled = DotProductAttention(dropout_rate=0.1, scaled=False)\n\n # Test that the output shape of the `call` method is the same as the input shape of the queries, keys, and values\n def test_output_shape(self):\n queries, keys, values = self.x, self.x, self.x\n output_scaled, _ = self.dot_product_scaled(queries, keys, values)\n output_unscaled, _ = self.dot_product_unscaled(queries, keys, values)\n assert output_scaled.shape == (2, 3, 2)\n assert output_unscaled.shape == (2, 3, 2)\n\n # Test that the `call` method computes the correct dot-product attention\n def test_dot_product_attention(self):\n dot_product = DotProductAttention()\n x = self.x\n # Feed the input tensor to queries, keys, and values\n queries, keys, values = x, x, x\n\n # Compute the dot-product attention\n attention, _ = dot_product(queries, keys, values)\n\n # Check that the attention tensor has the same shape as the input tensor\n assert attention.shape == x.shape\n\n def test_call(self):\n head_nums = [1, 2, 4, 8]\n x = self.x\n # Feed the input tensor to queries, keys, and values\n queries, keys, values = x, x, x\n for num in head_nums:\n dot_product = DotProductAttention()\n\n # Compute the dot-product attention\n attention, _ = dot_product(queries, keys, values)\n\n # Check that the attention tensor has the same shape as the input tensor\n assert attention.shape == queries.shape\n\n def test_call_with_different_input_tensor_shapes(self):\n # Create an instance of the DotProductAttention class\n dot_product = DotProductAttention()\n\n # Test the call method with 2D input tensors\n queries = tf.random.uniform([2, 2])\n keys = tf.random.uniform([2, 2])\n values = tf.random.uniform([2, 2])\n output, _ = dot_product(queries, keys, values)\n assert output.shape == queries.shape\n\n # Test the call method with 3D input tensors\n queries = tf.random.uniform([2, 3, 2])\n keys = tf.random.uniform([2, 3, 2])\n values = tf.random.uniform([2, 3, 2])\n output, _ = dot_product(queries, keys, values)\n assert output.shape == queries.shape\n\n @pytest.mark.parametrize(\n \"queries, keys, values, expected_output_shape, expected_output_values\",\n [\n (\n tf.zeros((2, 3, 4)),\n tf.zeros((2, 3, 4)),\n tf.zeros((2, 3, 4)),\n (2, 3, 4),\n 0,\n ),\n (tf.ones((2, 3, 4)), tf.ones((2, 3, 4)), tf.ones((2, 3, 4)), (2, 3, 4), 1),\n ],\n )\n def test_call_with_different_values(\n self, queries, keys, values, expected_output_shape, expected_output_values\n ):\n attention = DotProductAttention()\n output, _ = attention(queries, keys, values)\n\n assert output.shape == expected_output_shape\n assert tf.reduce_all(output == expected_output_values)\n\n @pytest.fixture\n def attention_layer(self):\n return DotProductAttention(dropout_rate=0.2, scaled=True)\n\n def test_from_config(self, attention_layer):\n config = attention_layer.get_config()\n new_layer = DotProductAttention.from_config(config)\n assert attention_layer.dropout.rate == new_layer.dropout.rate\n assert attention_layer.scaled == new_layer.scaled\n\n def test_get_attention_weights(self, attention_layer):\n attention_layer.attention_weights = np.random.rand(5, 10)\n weights = attention_layer.get_attention_weights()\n assert weights.shape == (5, 10)\n\n def test_get_config(self, attention_layer):\n config = attention_layer.get_config()\n print(config)\n assert isinstance(config, dict)\n assert config[\"dropout_rate\"] == 0.2\n assert config[\"scaled\"] == True\n" }, { "alpha_fraction": 0.6004273295402527, "alphanum_fraction": 0.6260683536529541, "avg_line_length": 21.285715103149414, "blob_id": "ba9a1ac5c76916eff542921ed4a570dc38db3684", "content_id": "ebda9f1d049b9b3534f0f0e83250607c0762e6f2", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 468, "license_type": "permissive", "max_line_length": 76, "num_lines": 21, "path": "/docs/source/index.rst", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": ".. TransformerX documentation master file, created by\n sphinx-quickstart on Mon May 1 19:41:56 2023.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nWelcome to TransformerX's documentation!\n========================================\n\n.. toctree::\n :maxdepth: 4\n :caption: Contents:\n\n transformerx\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n" }, { "alpha_fraction": 0.8803418874740601, "alphanum_fraction": 0.8803418874740601, "avg_line_length": 51, "blob_id": "a6935df564b141632e07bd4eed790b39b65715a0", "content_id": "55b3cd7cd1f92d84e99f579525022e3d3e24f835", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "permissive", "max_line_length": 62, "num_lines": 9, "path": "/transformerx/layers/__init__.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "from .addnorm import AddNorm\nfrom .dot_product_attention import DotProductAttention\nfrom .multihead_attention import MultiHeadAttention\nfrom .positional_encoding import SinePositionalEncoding\nfrom .positionwise_ffn import PositionwiseFFN\nfrom .transformer_decoder import TransformerDecoder\nfrom .transformer_decoder_block import TransformerDecoderBlock\nfrom .transformer_encoder import TransformerEncoder\nfrom .transformer_encoder_block import TransformerEncoderBlock\n" }, { "alpha_fraction": 0.6274222731590271, "alphanum_fraction": 0.635911226272583, "avg_line_length": 43.366233825683594, "blob_id": "b95c7eb75a28f1f62148829929c373ac5dba6a2d", "content_id": "448ddd887ad5724a96a87c746a5b1d3a3a872a25", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17081, "license_type": "permissive", "max_line_length": 122, "num_lines": 385, "path": "/transformerx/layers/transformer_decoder_block.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "from typing import Optional, Tuple, Callable\n\nimport tensorflow as tf\n\nfrom transformerx.layers.addnorm import AddNorm\nfrom transformerx.layers.multihead_attention import MultiHeadAttention\nfrom transformerx.layers.positionwise_ffn import PositionwiseFFN\n\n\nclass TransformerDecoderBlockOld(tf.keras.layers.Layer):\n \"\"\"Transformer decoder block [1]_.\n\n Include a stack of layers used in the transformer decoder block.\n\n Parameters\n ----------\n num_hiddens :\n Dimensions of the queries, keys, and values\n norm_shape :\n Arbitrary. Shape of the input.\n ffn_num_hiddens :\n Number of input hidden units\n num_heads :\n Number of the heads in the multi-head attention\n dropout_rate :\n Float between 0 and 1. Fraction of the input units to drop.\n i :\n Index of the block\n \"\"\"\n\n def __init__(\n self,\n num_hiddens,\n norm_shape,\n ffn_num_hiddens,\n num_heads,\n dropout_rate,\n i,\n ):\n super().__init__()\n self.i = i\n self.attention1 = MultiHeadAttention(num_hiddens, num_heads, dropout_rate)\n self.addnorm1 = AddNorm(norm_shape, dropout_rate)\n self.attention2 = MultiHeadAttention(num_hiddens, num_heads, dropout_rate)\n self.addnorm2 = AddNorm(norm_shape, dropout_rate)\n self.ffn = PositionwiseFFN(ffn_num_hiddens, num_hiddens)\n self.addnorm3 = AddNorm(norm_shape, dropout_rate)\n\n def call(self, X, state, **kwargs):\n \"\"\"Forward propagation of the decoder block.\n\n During training, all the tokens of any output sequence are processed at the same time, so state[2][self.i]\n is None as initialized. When decoding any output sequence token by token during prediction, state[2][self.i]\n contains representations of the decoded output at the i-th block up to the current time step\n \"\"\"\n enc_outputs, enc_valid_lens = state[0], state[1]\n if state[2][self.i] is None:\n key_values = X\n else:\n key_values = tf.concat((state[2][self.i], X), axis=1)\n state[2][self.i] = key_values\n if kwargs[\"training\"]:\n batch_size, num_steps, _ = X.shape\n # Shape of dec_valid_lens: (batch_size, num_steps), where every\n # row is [1, 2, ..., num_steps]\n dec_valid_lens = tf.repeat(\n tf.reshape(tf.range(1, num_steps + 1), shape=(-1, num_steps)),\n repeats=batch_size,\n axis=0,\n )\n else:\n dec_valid_lens = None\n # Self-attention\n X2 = self.attention1(X, key_values, key_values, dec_valid_lens, **kwargs)\n Y = self.addnorm1(X, X2, **kwargs)\n # Encoder-decoder attention. Shape of enc_outputs:\n # (batch_size, num_steps, depth)\n Y2 = self.attention2(Y, enc_outputs, enc_outputs, enc_valid_lens, **kwargs)\n Z = self.addnorm2(Y, Y2, **kwargs)\n return self.addnorm3(Z, self.ffn(Z), **kwargs), state\n\n\nclass TransformerDecoderBlock(tf.keras.layers.Layer):\n \"\"\"Transformer decoder block [1]_.\n\n The TransformerDecoderBlock is a custom layer in TensorFlow Keras that implements a single block of the Transformer\n decoder architecture [1]_, which is a key component of the Transformer model for natural language processing tasks\n such as machine translation, text summarization, and language generation. The layer includes multi-head attention\n mechanism, feedforward networks, and residual connections with optional normalization and other customization options.\n\n Parameters\n ----------\n d_model: int (default=512)\n Dimensionality of the input and output tensors.\n num_heads: int (default=8)\n Number of attention heads.\n dropout_rate: float (default=0.0)\n Dropout rate for the attention and feedforward networks.\n norm_type: str (default=\"layer\")\n Type of normalization to be applied to the output of the feedforward networks. Can be either \"layer\", \"batch\",\n or \"instance\".\n norm_eps: float (default=1e-6)\n Epsilon value for numerical stability in normalization.\n attention_mechanism: str (default=\"scaled_dotproduct\")\n Type of attention mechanism to be used in the self-attention layer. Currently supports \"scaled_dotproduct\" and\n other custom attention mechanisms.\n input_hidden_units_ffn: int (default=32)\n Number of hidden units in the input layer of the feedforward networks.\n output_hidden_units_ffn: int (default=64)\n Number of hidden units in the output layer of the feedforward networks.\n use_norm: bool (default=True)\n Whether to apply normalization to the output of the feedforward networks.\n residual_connections: Optional[Tuple[bool, bool]] (default=None)\n Tuple indicating whether to apply residual connections before and after the self-attention and feedforward\n networks. If None, residual connections will be used by default.\n activation_fn: Optional[Callable] (default=None)\n Activation function to be used in the feedforward networks. If None, ReLU activation will be used by default.\n non_linear_proj: Optional (default=None)\n Non-linear projection function to be applied after the self-attention layer. If None, no non-linear projection\n will be applied.\n clip_norm: Optional[float] (default=None)\n Maximum norm for gradient clipping during training.\n kernel_initializer: Optional[Callable] (default=None)\n Initializer for the kernel weights of the self-attention and feedforward networks.\n bias_initializer: Optional[Callable] (default=None)\n Initializer for the bias weights of the self-attention and feedforward networks.\n mixed_precision: bool (default=False)\n Whether to use mixed precision training, which combines float16 and float32 data types for faster training.\n learning_rate_schedule: Optional[Callable] (default=None)\n Learning rate schedule function to be applied during training. If None, no learning rate schedule will be used.\n use_bias: bool (default=False)\n Whether to include bias terms in the computation of the self-attention weights.\n kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] (default=None)\n Regularizer for the kernel weights of the AddNorm layer.\n bias_regularizer: Optional[tf.keras.regularizers.Regularizer] (default=None)\n Regularizer for the bias weights of the AddNorm layer.\n contextualized_embeddings: None (default=None)\n Pre-trained language model embeddings to be incorporated into the feedforward networks for contextualization of\n input embeddings.\n casual_mask: bool (default=True)\n Weather to use a casual mask. Allows information from the past to be used when computing the attention weights.\n name: str (default=None)\n The name of the layer.\n i: int (default=0)\n Index of the block.\n **kwargs:\n Additional keyword arguments for the parent class tf.keras.layers.Layer.\n\n Methods\n -------\n call(X, state, **kwargs) :\n Performs the forward propagation of the decoder block\n\n Examples\n --------\n >>> # Example 1: Initialize a custom transformer layer with default parameters\n >>> decoder_block = TransformerDecoderBlock()\n\n >>> # Example 2: Initialize a custom transformer layer with custom parameters\n >>> decoder_block = TransformerDecoderBlock(\n ... d_model=256,\n ... num_heads=4,\n ... dropout_rate=0.1,\n ... norm_type=\"batch\",\n ... norm_eps=1e-5,\n ... attention_mechanism=\"scaled_dotproduct\",\n ... input_hidden_units_ffn=64,\n ... output_hidden_units_ffn=128,\n ... use_norm=True,\n ... residual_connections=(True, True),\n ... activation_fn=tf.nn.relu,\n ... non_linear_proj=None,\n ... clip_norm=1.0,\n ... kernel_initializer=tf.keras.initializers.GlorotUniform(),\n ... bias_initializer=tf.keras.initializers.Zeros(),\n ... mixed_precision=False,\n ... learning_rate_schedule=None,\n ... use_bias=True,\n ... kernel_regularizer=tf.keras.regularizers.l2(0.01),\n ... bias_regularizer=None,\n ... contextualized_embeddings=None,\n ... casual_mask=True,\n ... name=None,\n ... i=0\n ... )\n\n References\n ----------\n .. [1] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L.,\n & Polosukhin, I. (2017). Attention is all you need. In Advances in neural information\n processing systems (pp. 5998-6008).\n\n Notes\n -----\n - This implementation follows the original Transformer model proposed by Vaswani et al. [1]_.\n - The `attention_mechanism` parameter allows the user to specify the type of attention\n mechanism to use in the multi-head self-attention layer. Possible values are \"scaled_dot_product\"\n and \"masked\". If not specified, \"scaled_dot_product\" is used by default.\n - The `use_norm` parameter controls whether to apply layer normalization after the multi-head\n self-attention and FFN layers. If set to False, no layer normalization is applied.\n - The `contextualized_embeddings` parameter allows the user to specify pre-trained contextualized\n embeddings, such as BERT or ELMo embeddings, to be used in the FFN layer. If not specified,\n standard embeddings are used by default.\n - The `mixed_precision` parameter enables mixed precision training using TensorFlow's\n experimental `mixed_float16` policy.\n - The `learning_rate_schedule` parameter allows the user to specify a custom learning rate\n schedule for the optimizer. The learning rate schedule should be a callable object that takes\n the current training step as input and returns the learning rate for that step.\n - The `casual_mask` parameter is useful for tasks where the output at time step t should only depend\n on the inputs up to time step t-1, such as language modeling or sequence prediction.\n \"\"\"\n\n def __init__(\n self,\n d_model: int = 512, # Dimensionality of the input and output tensors\n num_heads: int = 8, # Number of attention heads\n dropout_rate: float = 0.1, # Dropout rate for the attention and feedforward networks\n norm_type: str = \"layer\", # Type of normalization (layer or batch) (feedforward networks)\n norm_eps: float = 1e-6,\n attention_mechanism: str = \"scaled_dotproduct\",\n input_hidden_units_ffn: int = 2048, # Number of input hidden units in the feedforward network\n # output_hidden_units_ffn: int = 512, # Number of output hidden units in the feedforward network\n use_norm: bool = True, # Whether to use normalization (layer or batch)\n residual_connections: Optional[\n Tuple[bool, bool]\n ] = None, # Whether to use residual connections\n activation_fn: Optional[\n Tuple[Callable, str]\n ] = \"relu\", # Activation function for the feedforward network,\n non_linear_proj=None, # Non-linear projection for poistionwise feedforward network\n clip_norm: Optional[float] = None, # Maximum norm for gradient clipping\n kernel_initializer: Optional[\n Callable\n ] = None, # Initializer for the kernel weights\n bias_initializer: Optional[Callable] = None, # Initializer for the bias weights\n kernel_regularizer: Optional[\n tf.keras.regularizers.Regularizer\n ] = None, # kernel regularizer for AddNorm\n bias_regularizer: Optional[\n tf.keras.regularizers.Regularizer\n ] = None, # bias regularizer for AddNorm\n mixed_precision: bool = False, # Whether to use mixed precision training\n learning_rate_schedule: Optional[\n Callable\n ] = None, # Learning rate schedule function\n use_bias: bool = False, # Whether to include bias terms in the attention computation\n contextualized_embeddings=None, # incorporate pre-trained language models such as BERT or GPT-2 into the\n # model (feedforward networks)\n causal_mask: bool = True, # Whether to use a causal mask\n name=None, # Name of the layer\n i: int = 0, # Index of the block\n **kwargs,\n ):\n super().__init__(name=name)\n self.d_model = d_model\n self.num_heads = num_heads\n self.i = i\n self.dropout_rate = dropout_rate\n self.norm_type = norm_type\n self.use_bias = use_bias\n self.attention_mechanism = attention_mechanism\n\n # Multi-head attention 1\n self.attention1 = MultiHeadAttention(\n d_model=self.d_model,\n num_heads=self.num_heads,\n dropout_rate=self.dropout_rate,\n use_bias=self.use_bias,\n attention=self.attention_mechanism,\n causal_mask=causal_mask,\n **kwargs,\n )\n self.addnorm1 = (\n AddNorm(\n norm_type=norm_type,\n norm_eps=norm_eps,\n dropout_rate=dropout_rate,\n activation=activation_fn,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n **kwargs,\n )\n if use_norm\n else None\n )\n\n # Multi-head attention 2\n self.attention2 = MultiHeadAttention(\n d_model=self.d_model,\n num_heads=self.num_heads,\n dropout_rate=self.dropout_rate,\n use_bias=self.use_bias,\n attention=self.attention_mechanism,\n causal_mask=causal_mask,\n **kwargs,\n )\n self.addnorm2 = (\n AddNorm(\n norm_type=norm_type,\n norm_eps=norm_eps,\n dropout_rate=dropout_rate,\n activation=activation_fn,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n **kwargs,\n )\n if use_norm\n else None\n )\n\n # Position-wise feedforward network\n self.ffn = PositionwiseFFN(\n input_hidden_units=input_hidden_units_ffn,\n # output_hidden_units=output_hidden_units_ffn,\n activation=activation_fn,\n dropout_rate=dropout_rate,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n non_linear_proj=non_linear_proj,\n contextualized_embeddings=contextualized_embeddings,\n **kwargs,\n )\n self.addnorm3 = (\n AddNorm(\n norm_type=norm_type,\n norm_eps=norm_eps,\n dropout_rate=dropout_rate,\n activation=activation_fn,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n **kwargs,\n )\n if use_norm\n else None\n )\n\n self.residual_connections = residual_connections\n self.clip_norm = clip_norm\n self.mixed_precision = mixed_precision\n self.learning_rate_schedule = learning_rate_schedule\n\n if self.mixed_precision:\n policy = mixed_precision.Policy(\"mixed_float16\")\n mixed_precision.set_global_policy(policy)\n\n # the call method of the transformer decoder block\n def call(self, queries, keys, values, attention_mask=None, **kwargs):\n # Multi-head attention 1 (self-attention)\n attn_output1, attn1_weights = self.attention1(\n queries, queries, queries, **kwargs\n )\n if self.addnorm1 is not None:\n attn_output1 = self.addnorm1(queries, attn_output1, **kwargs)\n else:\n attn_output1 = queries + attn_output1\n\n # Multi-head attention 2 (encoder-decoder --cross-- attention)\n attn2_output, attn2_weights = self.attention2(\n attn_output1, keys, values, **kwargs\n )\n if self.addnorm2 is not None:\n attn2_output = self.addnorm2(attn_output1, attn2_output, **kwargs)\n else:\n attn2_output = attn_output1 + attn2_output\n\n # Position-wise feedforward network\n ffn_output = self.ffn(attn2_output)\n if self.addnorm3 is not None:\n ffn_output = self.addnorm3(attn2_output, ffn_output, **kwargs)\n else:\n ffn_output = attn2_output + ffn_output\n\n if self.clip_norm is not None:\n ffn_output = tf.clip_by_norm(ffn_output, self.clip_norm)\n\n if self.learning_rate_schedule is not None:\n global_step = kwargs.get(\"global_step\", None)\n if global_step is None:\n raise ValueError(\n \"global_step must be provided if learning_rate_schedule is not None\"\n )\n learning_rate = self.learning_rate_schedule(global_step)\n self.add_metric(learning_rate, name=\"learning_rate\")\n\n return ffn_output, attn1_weights, attn2_weights\n" }, { "alpha_fraction": 0.45414847135543823, "alphanum_fraction": 0.4661571979522705, "avg_line_length": 23.756755828857422, "blob_id": "5957c86183a00bddfca01a9de2a38564a982022e", "content_id": "09c30a4e5577971392a869f7c5dede3a9d0dae72", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 916, "license_type": "permissive", "max_line_length": 51, "num_lines": 37, "path": "/transformerx/txplot/plot_pe.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "from itertools import cycle\nfrom typing import Tuple\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nclass Plot:\n def plot_pe(\n self,\n cols: Tuple[int, list, np.ndarray],\n pos_encodings,\n num_steps,\n show_grid=True,\n ):\n ax = plt.figure(figsize=(6, 2.5), dpi=1000)\n\n lines = [\"-\", \"--\", \"-.\", \":\"]\n self.line_cycler = cycle(lines)\n\n def plot_line(col):\n plt.plot(\n np.arange(num_steps),\n pos_encodings[0, :, col].T,\n next(self.line_cycler),\n label=f\"col {col}\",\n )\n\n if isinstance(cols, (list, np.ndarray)):\n for col in cols:\n plot_line(col)\n else:\n plot_line(cols)\n ax.legend()\n plt.title(\"Columns 7-10\")\n plt.grid(show_grid)\n plt.show()\n" }, { "alpha_fraction": 0.7010309100151062, "alphanum_fraction": 0.7010309100151062, "avg_line_length": 23.25, "blob_id": "81546286fd88f80beef4690f1dede9120cd2c4cd", "content_id": "e319c1b45e21f3ab9c0ddc914e7cc8d89d8b41c7", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 97, "license_type": "permissive", "max_line_length": 42, "num_lines": 4, "path": "/docs/source/transformerx.training.base.rst", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": ".. automodule:: transformerx.training.base\n :members:\n :undoc-members:\n :show-inheritance:\n" }, { "alpha_fraction": 0.6002501249313354, "alphanum_fraction": 0.6245657801628113, "avg_line_length": 36.290157318115234, "blob_id": "d16db5172669bbb3ea9376c66a4f54886663dae1", "content_id": "cf62db04be63c72d0b277ebeeb1013289c7a4982", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7199, "license_type": "permissive", "max_line_length": 119, "num_lines": 193, "path": "/transformerx/layers/positional_encoding.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\n\nfrom transformerx.utils import exists\n\n\nclass SinePositionalEncoding(tf.keras.layers.Layer):\n \"\"\"Compute absolute positional encoding object [1]_.\n\n Generate a sinusoid for each dimension of the positional encoding where wavelengths form a geometric progression\n from :math:`2π` to :math:`(10000)2π`.\n\n Notes\n -----\n Absolute Position Encodings are a type of position embeddings for [Transformer-based models] where positional\n encodings are added to the input embeddings at the bottoms of the encoder and decoder stacks. The positional\n encodings have the same dimension :math:`d_model` as the embeddings, so that the two can be summed. In the original\n implementation, sine and cosine functions of different frequencies are used:\n\n .. math::\n PE(pos, 2i) = \\sin(pos^{2i/d_{model}})\n\n PE(pos, 2i+1) = \\cos(pos^{2i/d_{model}})\n\n where is the position and is the dimension.\n\n\n Parameters\n ----------\n d_model :\n Embedding Size; Length of the positional encoding's hidden units, the same as the length of Embedding.\n dropout_rate :\n Float between 0 and 1. Fraction of the input units to drop.\n maximum_position_encoding :\n Maximum length of the steps to calculate sinusoid\n\n Returns\n -------\n output:\n Tensor of the same shape of the input tensor with positinoal encodings added\n\n Examples\n --------\n >>> depth, num_steps = 32, 50\n >>> pos_encoding = SinePositionalEncoding(depth, dropout_rate=0.2)\n >>> x = tf.zeros((1, num_steps, depth))\n >>> print(x.shape)\n (1, 50, 32)\n >>> x = pos_encoding(x, training=False)\n >>> P = pos_encoding.P[:, : x.shape[1], :]\n >>> print(x.shape)\n (1, 50, 32)\n >>> print(P.shape)\n (1, 50, 32)\n\n References\n ----------\n .. [1] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I.\n (2017). Attention Is All You Need. arXiv. https://doi.org/10.48550/arXiv.1706.03762\n \"\"\"\n\n def __init__(\n self, d_model, dropout_rate=0, maximum_position_encoding=10000, **kwargs\n ):\n super().__init__(**kwargs)\n self.d_model = d_model\n self.dropout = tf.keras.layers.Dropout(dropout_rate)\n # Create a long enough P\n positions = tf.range(maximum_position_encoding, dtype=tf.float32)\n even_indices = tf.range(0, self.d_model, 2, dtype=tf.float32)\n odd_indices = tf.range(1, self.d_model, 2, dtype=tf.float32)\n denominator = tf.pow(10000.0, tf.math.floor(even_indices / 2) / self.d_model)\n even_encoding = tf.sin(positions[:, tf.newaxis] / denominator)\n odd_encoding = tf.cos(positions[:, tf.newaxis] / denominator)\n self.P = tf.concat([even_encoding, odd_encoding], axis=-1)[tf.newaxis, :, :]\n\n def call(self, x, **kwargs):\n assert len(tf.shape(x)) == 3, f\"Input must be a 3D tensor. Got {tf.shape(x)}\"\n if self.P.dtype != x.dtype:\n self.P = tf.cast(self.P, dtype=x.dtype)\n # self.P = tf.cast(self.P, dtype=X.dtype)\n x = x + self.P[:, : tf.shape(x)[1], :]\n x = self.dropout(x, **kwargs)\n return x\n\n\nclass RelativePositionEmbedding(tf.keras.layers.Layer):\n \"\"\"Create a relative positional embedding as in [2]_.\n\n\n References\n ----------\n .. [1] Peter Shaw, Jakob Uszkoreit, Ashish Vaswani (2018), Self-Attention with Relative Position\n Representations, https://doi.org/10.48550/arXiv.1803.02155\n\n .. [2] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I.\n (2017). Attention Is All You Need. arXiv. https://doi.org/10.48550/arXiv.1706.03762\n \"\"\"\n\n def __init__(self, scale, causal=False, num_buckets=32, max_distance=128, heads=8):\n super().__init__()\n self.scale = scale\n self.causal = causal\n self.num_buckets = num_buckets\n self.max_distance = max_distance\n self.relative_attention_bias = tf.keras.layers.Embedding(num_buckets, heads)\n\n # def call(self, q, k):\n # # Compute the pairwise-distance between each position\n # q_indices = tf.range(tf.shape(q)[1], dtype=tf.float32)\n # k_indices = tf.range(tf.shape(k)[1], dtype=tf.float32)\n # distance = k_indices[None, :, None] - q_indices[:, None, None]\n #\n # # Clip the distance values to the range [-max_distance, max_distance]\n # distance = tf.clip_by_value(distance, -self.max_distance, self.max_distance)\n #\n # # Shift the distance values by max_distance to ensure they are all non-negative integers\n # distance += self.max_distance\n #\n # # Compute the bucket index for each distance value\n # buckets = tf.cast(distance / self.max_distance * self.num_buckets, dtype=tf.int32)\n #\n # # Lookup the relative attention bias for each bucket index\n # bias = self.relative_attention_bias(buckets)\n #\n # # Reshape the bias tensor to have the same shape as the query tensor\n # bias = tf.transpose(bias, [2, 0, 1])\n # bias = tf.expand_dims(bias, axis=0)\n #\n # # Apply the bias to the dot product of q and k\n # dot_product = tf.matmul(q, k, transpose_b=True)\n # attention_weights = dot_product + bias\n #\n # # Scale the attention weights and apply the causal mask if necessary\n # attention_weights /= tf.math.sqrt(tf.cast(tf.shape(k)[-1], tf.float32))\n # if self.causal:\n # mask = tf.ones_like(attention_weights[0, :, :])\n # mask = tf.linalg.LinearOperatorLowerTriangular(mask).to_dense()\n # attention_weights = tf.where(tf.equal(mask, 0), -1e9, attention_weights)\n #\n # # Apply the softmax function to get the attention weights and compute the context vectors\n # attention_weights = tf.nn.softmax(attention_weights, axis=-1)\n # context_vectors = tf.matmul(attention_weights, k)\n #\n # # Return the scaled context vectors\n # return context_vectors * self.scale\n\n\ndef main():\n # Define the input shape\n input_shape = (10, 64)\n\n # Define the inputs\n inputs = tf.keras.layers.Input(shape=input_shape)\n\n # Add the SinePositionalEncoding layer\n encoded = SinePositionalEncoding(d_model=64)(inputs)\n\n print(tf.shape(inputs))\n print(tf.shape(encoded))\n # Add a convolutional layer\n conv1 = tf.keras.layers.Conv1D(filters=32, kernel_size=3, activation=\"relu\")(\n encoded\n )\n print(tf.shape(conv1))\n # Add a pooling layer\n pool1 = tf.keras.layers.MaxPooling1D(pool_size=2)(conv1)\n\n # Flatten the output\n flatten = tf.keras.layers.Flatten()(pool1)\n\n # Add a dense layer\n dense = tf.keras.layers.Dense(units=16, activation=\"relu\")(flatten)\n\n # Add the output layer\n outputs = tf.keras.layers.Dense(units=1, activation=\"sigmoid\")(dense)\n\n # Create the model\n model = tf.keras.models.Model(inputs=inputs, outputs=outputs)\n\n # Compile the model\n model.compile(\n optimizer=tf.keras.optimizers.Adam(),\n loss=tf.keras.losses.BinaryCrossentropy(),\n metrics=[tf.keras.metrics.BinaryAccuracy()],\n )\n\n # Print the model summary\n model.summary()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6195643544197083, "alphanum_fraction": 0.6263269782066345, "avg_line_length": 43.15625, "blob_id": "027f35f24599588971e9c731f995bcdd06f740aa", "content_id": "1277bd2ba2abea0a8677b422dbbbd3c5c73d677f", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12717, "license_type": "permissive", "max_line_length": 119, "num_lines": 288, "path": "/transformerx/layers/transformer_decoder.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "from typing import Optional, Callable, Tuple\n\nimport tensorflow as tf\n\nfrom transformerx.layers.positional_encoding import SinePositionalEncoding\nfrom transformerx.layers.transformer_decoder_block import TransformerDecoderBlock\n\n\nclass TransformerDecoderOld(tf.keras.layers.Layer):\n \"\"\"Transformer decoder that encompasses one or more TransformerDecoderBlock blocks.\n\n Transformer decoder that encompasses one or more TransformerDecoderBlock blocks.\n\n The TransformerDecoder processes the input sequences and produces the output sequences.\n It also generates attention weights for each of the two attention layers in each of the\n TransformerDecoderBlock blocks.\n\n Parameters\n ----------\n vocab_size : int\n Vocabulary size. The size of the vocabulary used by the Transformer decoder. This is used to determine the\n size of the input tensor and the output tensor of the call method.\n depth : int\n Dimension of each input sequence. The depth of the input tensor and the output tensor of the call method.\n This is also the size of the hidden states of the Transformer decoder blocks.\n norm_shape : str\n Shape of the normalization layers in the Transformer decoder blocks. This is a tuple of three integers,\n specifying the number of dimensions to normalize over for the first, second, and third normalization layers,\n respectively.\n ffn_num_hiddens : int\n Number of hidden units in the feed-forward neural network layers of the Transformer decoder blocks.\n num_heads : int\n Number of attention heads of the Transformer decoder blocks.\n n_blocks : int\n Number of encoder blocks in the Transformer decoder.\n dropout : float\n The dropout rate to use for the dropout layers in the Transformer decoder blocks. This value is used to\n determine the strength of regularization. A higher dropout rate means that more nodes are dropped out during\n training, which can help prevent overfitting.\n\n Attributes\n ----------\n depth : int\n The depth (i.e., number of channels) of the input and output representations.\n n_blocks : int\n The number of TransformerDecoderBlock blocks in the decoder.\n embedding : tf.keras.layers.Embedding\n The embedding layer that maps the input sequences to their input representations.\n pos_encoding : SinePositionalEncoding\n The absolute positional encoding layer that adds position information to the input\n representations.\n blocks : List[TransformerDecoderBlock]\n The list of TransformerDecoderBlock blocks that process the input sequences.\n dense : tf.keras.layers.Dense\n The dense layer that maps the output representations to the output sequences.\n \"\"\"\n\n def __init__(\n self,\n vocab_size,\n depth,\n norm_shape,\n ffn_num_hiddens,\n num_heads,\n n_blocks,\n dropout,\n ):\n super().__init__()\n self.depth = depth\n self.n_blocks = n_blocks\n self.embedding = tf.keras.layers.Embedding(vocab_size, depth)\n self.pos_encoding = SinePositionalEncoding(depth, dropout)\n self.blocks = [\n TransformerDecoderBlock(\n depth,\n norm_shape,\n ffn_num_hiddens,\n num_heads,\n dropout,\n i,\n )\n for i in range(n_blocks)\n ]\n self.dense = tf.keras.layers.Dense(vocab_size)\n\n def init_state(self, enc_outputs, enc_valid_lens):\n return [enc_outputs, enc_valid_lens, [None] * self.n_blocks]\n\n def call(self, X, state, **kwargs):\n \"\"\"Forward call of the Transformer decoder.\n\n Parameters\n ----------\n X : tf.Tensor\n Input tensor with shape (batch_size, no. of queries or key-value pairs, depth). This tensor is used to\n compute the output of the Transformer decoder.\n state : List\n List of decoder state tensors. This is a list of three elements:\n - enc_outputs: The outputs of the Transformer encoder, of shape (batch_size, max_seq_len, depth).\n This tensor is used to compute the attention weights for the encoder-decoder attention layer in the\n Transformer decoder blocks.\n - enc_valid_lens: The valid lengths of the input sequence to the Transformer encoder, of shape\n (batch_size,) or (batch_size, max_seq_len). This tensor is used to mask the outputs of the Transformer\n encoder so that only the valid parts of the sequence are used in the attention computations.\n - state: A list of length n_blocks, where each element is the state of the corresponding Transformer\n decoder block. This state is used to carry over information from previous time steps when computing the\n output of the Transformer decoder blocks.\n **kwargs\n Additional keyword arguments that can be passed to the Transformer decoder blocks. This can include\n arguments such as the attention mask and the mask for the masked language model.\n\n Returns\n -------\n output : tf.Tensor\n Output tensor with shape (batch_size, no. of queries or key-value pairs, depth).\n state : List\n Updated list of decoder state tensors.\n\n Examples\n --------\n >>> # Initialize a TransformerDecoder with a vocabulary size of 1000 and a depth of 512\n >>> decoder = TransformerDecoder(\n ... vocab_size=1000,\n ... depth=512,\n ... norm_shape=(512,),\n ... n_blocks=6,\n ... dropout=0.2\n >>> )\n\n >>> # Define the input sequence, with batch size of 2 and sequence length of 10\n >>> inputs = tf.random.uniform((2, 10), minval=0, maxval=1000, dtype=tf.int32)\n\n >>> # Define the initial state of the decoder, which should be the output from the encoder\n >>> # and the valid sequence lengths from the encoder\n >>> enc_outputs = tf.random.normal((2, 10, 512))\n >>> enc_valid_lens = tf.constant([10, 5], dtype=tf.int32)\n >>> initial_state = decoder.init_state(enc_outputs, enc_valid_lens)\n\n >>> # Call the decoder to get the output and the updated state\n >>> output, state = decoder(inputs, initial_state)\n\n >>> # The output will be a tensor of shape (2, 10, 1000) containing the predicted\n >>> # probabilities for each of the input tokens at each timestep\n >>> # The state will be a tuple containing the encoder outputs, the encoder valid lengths,\n >>> # and a list of attention weights for each block in the decoder\n \"\"\"\n\n X = self.pos_encoding(\n self.embedding(X) * tf.math.sqrt(tf.cast(self.depth, dtype=tf.float32)),\n **kwargs,\n )\n # 2 attention layers in decoder\n self._attention_weights = [[None] * len(self.blocks) for _ in range(2)]\n for i, blk in enumerate(self.blocks):\n X, state = blk(X, state, **kwargs)\n # Decoder self-attention weights\n self._attention_weights[0][i] = blk.attention1.attention.attention_weights\n # Encoder-decoder attention weights\n self._attention_weights[1][i] = blk.attention2.attention.attention_weights\n return self.dense(X), state\n\n @property\n def attention_weights(self):\n return self._attention_weights\n\n\nclass TransformerDecoder(tf.keras.layers.Layer):\n def __init__(\n self,\n vocab_size: int,\n d_model: int = 512,\n num_heads: int = 8,\n n_blocks: int = 6,\n maxlen_position_encoding: int = 10000,\n attention_dropout: float = 0.0,\n norm_type: str = \"layer\",\n norm_eps: float = 1e-6,\n use_norm: bool = True,\n rescale_embedding: bool = False,\n dropout_rate: float = 0.1,\n attention_mechanism: str = \"scaled_dotproduct\",\n input_hidden_units_ffn: int = 64,\n residual_connections: Optional[Tuple[bool, bool]] = (True, True),\n activation_fn: Optional[Callable] = tf.nn.relu,\n non_linear_proj=None,\n clip_norm: Optional[float] = 1.0,\n kernel_initializer: Optional[Callable] = tf.keras.initializers.GlorotUniform(),\n bias_initializer: Optional[Callable] = tf.keras.initializers.Zeros(),\n kernel_regularizer: Optional[\n tf.keras.regularizers.Regularizer\n ] = tf.keras.regularizers.l2(0.01),\n bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,\n mixed_precision: bool = False,\n learning_rate_schedule: Optional[Callable] = None,\n use_bias: bool = True,\n contextualized_embeddings=None,\n name: str = \"TransformerDecoder\",\n dtype: Optional[tf.dtypes.DType] = None,\n **kwargs,\n ):\n super(TransformerDecoder, self).__init__(name=name, dtype=dtype, **kwargs)\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.num_heads = num_heads\n self.n_blocks = n_blocks\n self.maxlen_position_encoding = maxlen_position_encoding\n self.attention_dropout = attention_dropout\n self.norm_type = norm_type\n self.norm_eps = norm_eps\n self.use_norm = use_norm\n self.rescale_embedding = rescale_embedding\n self.dropout_rate = dropout_rate\n self.attention_mechanism = attention_mechanism\n self.input_hidden_units_ffn = input_hidden_units_ffn\n self.residual_connections = residual_connections\n self.activation_fn = activation_fn\n self.non_linear_proj = non_linear_proj\n self.clip_norm = clip_norm\n self.kernel_initializer = kernel_initializer\n self.bias_initializer = bias_initializer\n self.kernel_regularizer = kernel_regularizer\n self.bias_regularizer = bias_regularizer\n self.mixed_precision = mixed_precision\n self.learning_rate_schedule = learning_rate_schedule\n self.use_bias = use_bias\n self.contextualized_embeddings = contextualized_embeddings\n\n self.pos_encoding = SinePositionalEncoding(\n d_model=d_model,\n dropout_rate=dropout_rate,\n maximum_position_encoding=maxlen_position_encoding,\n **kwargs,\n )\n self.embedding = tf.keras.layers.Embedding(vocab_size, d_model)\n self.blocks = [\n TransformerDecoderBlock(\n d_model=d_model,\n num_heads=num_heads,\n dropout_rate=dropout_rate,\n norm_type=norm_type,\n norm_eps=norm_eps,\n use_norm=use_norm,\n attention_mechanism=attention_mechanism,\n input_hidden_units_ffn=input_hidden_units_ffn,\n residual_connections=residual_connections,\n activation_fn=activation_fn,\n non_linear_proj=non_linear_proj,\n clip_norm=clip_norm,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n mixed_precision=mixed_precision,\n learning_rate_schedule=learning_rate_schedule,\n use_bias=use_bias,\n contextualized_embeddings=contextualized_embeddings,\n dtype=dtype,\n i=i,\n **kwargs,\n )\n for i in range(self.n_blocks)\n ]\n\n def apply_positional_embedding(self, inputs=None, **kwargs):\n embedded_inputs = self.embedding(inputs)\n return self.pos_encoding(\n embedded_inputs\n * tf.math.sqrt(tf.cast(self.d_model, dtype=embedded_inputs.dtype)),\n **kwargs,\n )\n\n def call(self, queries, keys, values, attention_mask=None, **kwargs):\n blk_outputs = self.apply_positional_embedding(queries, **kwargs)\n # keys = self.apply_positional_embedding(keys, **kwargs)\n # values = self.apply_positional_embedding(values, **kwargs)\n # self.attention_weights = [None] * len(self.blocks)\n self.attention_weights = []\n for i, blk in enumerate(self.blocks):\n blk_outputs, attn_weights, attn_weights2 = blk(\n blk_outputs,\n keys,\n values,\n attention_mask=attention_mask,\n **kwargs,\n )\n # self.attention_weights[i] = attn_weights2\n self.attention_weights.append(attn_weights2)\n return blk_outputs, self.attention_weights\n" }, { "alpha_fraction": 0.6287795901298523, "alphanum_fraction": 0.6396175026893616, "avg_line_length": 41.55813980102539, "blob_id": "7af8b410a91b0cb45b5face48c4ec0a3dd4c0ac5", "content_id": "fca0611ec866260d697678ccc70799e189e4a0e0", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10980, "license_type": "permissive", "max_line_length": 105, "num_lines": 258, "path": "/transformerx/layers/transformer_encoder.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import os\nfrom typing import Optional, Callable, Tuple\n\nimport tensorflow as tf\n\nfrom transformerx.layers.positional_encoding import SinePositionalEncoding\nfrom transformerx.layers.transformer_encoder_block import TransformerEncoderBlock\n\n\nclass TransformerEncoder(tf.keras.layers.Layer):\n \"\"\"Transformer encoder that encompasses one or more TransformerEncoderBlock blocks.\n\n The TransformerEncoder class provides a Keras layer for the encoder part of the Transformer\n architecture. It consists of an embedding layer, a positional encoding layer, and one or more\n TransformerEncoderBlock blocks. The input sequence is first embedded and then passed through\n the positional encoding layer to obtain the final input representation. The input representation\n is then passed through the TransformerEncoderBlock blocks in a sequential manner to compute\n the final output representation.\n\n Parameters\n ----------\n vocab_size : int\n The size of the input vocabulary.\n d_model : int\n The d_model of the input and output representations.\n norm_shape : int\n The shape of the normalization layer.\n ffn_num_hiddens : int\n The number of hidden units in the feed-forward network of the TransformerEncoderBlock.\n num_heads : int\n The number of attention heads in the TransformerEncoderBlock.\n n_blocks : int\n The number of TransformerEncoderBlock blocks.\n dropout : float\n The dropout rate.\n use_bias : bool\n Whether to use bias in the linear transformations of the TransformerEncoderBlock.\n Default is False.\n\n Attributes\n ----------\n embedding : tf.keras.layers.Embedding\n The embedding layer for the input sequence.\n pos_encoding : SinePositionalEncoding\n The positional encoding layer for the input sequence.\n blocks : List[TransformerEncoderBlock]\n The list of TransformerEncoderBlock blocks.\n attention_weights : List[tf.Tensor]\n The list of attention weights tensors computed by each Transformer\n\n\n Examples\n --------\n >>> # Create a TransformerEncoder instance with a vocabulary size of 1000, a d_model of 128,\n >>> # a normalization shape of 4, 64 hidden units in the feed-forward network, 8 attention heads,\n >>> # 2 TransformerEncoderBlock blocks, and a dropout rate of 0.1\n >>> transformer_encoder = TransformerEncoder(\n ... vocab_size=1000,\n ... d_model=128,\n ... norm_shape=4,\n ... ffn_num_hiddens=64,\n ... num_heads=8,\n ... n_blocks=2,\n ... dropout=0.1\n ... )\n\n >>> # Compute the output representation for a batch of input sequences\n >>> input_sequences = tf.random.uniform((batch_size, seq_length))\n >>> valid_lens = tf.random.uniform((batch_size,))\n >>> output_representation = transformer_encoder(input_sequences, valid_lens)\n\n >>> # Get the attention weights of the TransformerEncoderBlock blocks\n >>> attention_weights = transformer_encoder.attention_weights\n \"\"\"\n\n def __init__(\n self,\n vocab_size: int,\n d_model: int = 512,\n num_heads: int = 8,\n n_blocks: int = 6,\n maxlen_position_encoding: int = 10000,\n attention_dropout: float = 0.0,\n norm_type: str = \"layer\",\n norm_eps: float = 1e-6,\n use_norm: bool = True,\n rescale_embedding: bool = False,\n dropout_rate: float = 0.1,\n attention_mechanism: str = \"scaled_dotproduct\",\n input_hidden_units_ffn: int = 64,\n residual_connections: Optional[Tuple[bool, bool]] = (True, True),\n activation_fn: Optional[Callable] = tf.nn.relu,\n non_linear_proj=None,\n clip_norm: Optional[float] = 1.0,\n kernel_initializer: Optional[Callable] = tf.keras.initializers.GlorotUniform(),\n bias_initializer: Optional[Callable] = tf.keras.initializers.Zeros(),\n kernel_regularizer: Optional[\n tf.keras.regularizers.Regularizer\n ] = tf.keras.regularizers.l2(0.01),\n bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,\n mixed_precision: bool = False,\n learning_rate_schedule: Optional[Callable] = None,\n use_bias: bool = True,\n contextualized_embeddings=None,\n name: str = \"TransformerEncoder\",\n dtype: Optional[tf.dtypes.DType] = None,\n **kwargs,\n ):\n super(TransformerEncoder, self).__init__(name=name, dtype=dtype, **kwargs)\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.num_heads = num_heads\n self.n_blocks = n_blocks\n self.maxlen_position_encoding = maxlen_position_encoding\n self.attention_dropout = attention_dropout\n self.norm_type = norm_type\n self.norm_eps = norm_eps\n self.use_norm = use_norm\n self.rescale_embedding = rescale_embedding\n self.dropout_rate = dropout_rate\n self.attention_mechanism = attention_mechanism\n self.input_hidden_units_ffn = input_hidden_units_ffn\n self.residual_connections = residual_connections\n self.activation_fn = activation_fn\n self.non_linear_proj = non_linear_proj\n self.clip_norm = clip_norm\n self.kernel_initializer = kernel_initializer\n self.bias_initializer = bias_initializer\n self.kernel_regularizer = kernel_regularizer\n self.bias_regularizer = bias_regularizer\n self.mixed_precision = mixed_precision\n self.learning_rate_schedule = learning_rate_schedule\n self.use_bias = use_bias\n self.contextualized_embeddings = contextualized_embeddings\n\n self.pos_encoding = SinePositionalEncoding(\n d_model=self.d_model,\n dropout_rate=self.dropout_rate,\n maximum_position_encoding=self.maxlen_position_encoding,\n **kwargs,\n )\n self.embedding = tf.keras.layers.Embedding(self.vocab_size, self.d_model)\n self.blocks = [\n TransformerEncoderBlock(\n d_model=self.d_model,\n num_heads=self.num_heads,\n dropout_rate=self.dropout_rate,\n norm_type=self.norm_type,\n norm_eps=self.norm_eps,\n use_norm=self.use_norm,\n attention_mechanism=self.attention_mechanism,\n input_hidden_units_ffn=self.input_hidden_units_ffn,\n residual_connections=self.residual_connections,\n activation_fn=self.activation_fn,\n non_linear_proj=self.non_linear_proj,\n clip_norm=self.clip_norm,\n kernel_initializer=self.kernel_initializer,\n bias_initializer=self.bias_initializer,\n kernel_regularizer=self.kernel_regularizer,\n bias_regularizer=self.bias_regularizer,\n mixed_precision=self.mixed_precision,\n learning_rate_schedule=self.learning_rate_schedule,\n use_bias=self.use_bias,\n contextualized_embeddings=self.contextualized_embeddings,\n dtype=self.dtype,\n **kwargs,\n )\n for _ in range(self.n_blocks)\n ]\n\n def apply_positional_embedding(self, inputs=None, **kwargs):\n # if tf.shape(inputs)\n embedded_inputs = self.embedding(inputs)\n return self.pos_encoding(\n embedded_inputs\n * tf.math.sqrt(tf.cast(self.d_model, dtype=embedded_inputs.dtype)),\n # **kwargs,\n )\n\n def call(self, queries, attention_mask=None, **kwargs):\n \"\"\"Compute the output representation for the input sequence.\n\n This method computes the output representation for the input sequence by first passing it\n through the embedding layer and the positional encoding layer, and then passing the resulting\n input representation through the TransformerEncoderBlock blocks in a sequential manner.\n\n Parameters\n ----------\n queries : tf.Tensor\n The input sequence tensor of shape (batch_size, seq_length).\n attention_mask : tf.Tensor\n The tensor of valid sequence lengths of shape (batch_size,) or (batch_size, seq_length).\n **kwargs : dict\n Additional keyword arguments to be passed to the TransformerEncoderBlock blocks.\n\n Returns\n -------\n output_representation : tf.Tensor\n The output representation tensor of shape (batch_size, seq_length, d_model).\n\n Examples\n --------\n >>> # Create a TransformerEncoder instance with a vocabulary size of 1000, a d_model of 128,\n >>> # a normalization shape of 4, 64 hidden units in the feed-forward network, 8 attention heads,\n >>> # 2 TransformerEncoderBlock blocks, and a dropout rate of 0.1\n >>> transformer_encoder = TransformerEncoder(\n ... vocab_size=1000,\n ... d_model=128,\n ... norm_shape=4,\n ... ffn_num_hiddens=64,\n ... num_heads=8,\n ... n_blocks=2,\n ... dropout=0.1\n ... )\n >>>\n >>> # Compute the output representation for a batch of input sequences\n >>> input_sequences = tf.random.uniform((batch_size, seq_length))\n >>> valid_lens = tf.random.uniform((batch_size,))\n >>> output_representation = transformer_encoder(input_sequences, attention_mask)\n >>>\n >>> # Get the attention weights of the TransformerEncoderBlock blocks\n >>> attention_weights = transformer_encoder.attention_weights\n \"\"\"\n # Since positional encoding values are between -1 and 1, the embedding\n # values are multiplied by the square root of the embedding dimension\n # to rescale before they are summed up\n embeddings = self.apply_positional_embedding(queries, **kwargs)\n self.attention_weights = [None] * len(self.blocks)\n for i, blk in enumerate(self.blocks):\n embeddings, attn_weights = blk(\n embeddings, attention_mask=attention_mask, **kwargs\n )\n self.attention_weights[i] = attn_weights\n return embeddings, self.attention_weights\n\n\ndef main():\n # define the model\n inputs = tf.keras.layers.Input(shape=[10])\n x, _ = TransformerEncoder(vocab_size=64, d_model=512, num_heads=8, n_blocks=6)(\n inputs\n )\n x = tf.keras.layers.GlobalAveragePooling1D()(x)\n outputs = tf.keras.layers.Dense(1, activation=\"sigmoid\")(x)\n model = tf.keras.models.Model(inputs=inputs, outputs=outputs)\n\n # compile the model\n optimizer = tf.keras.optimizers.Adam(lr=0.001)\n model.compile(loss=\"binary_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\"])\n\n # train the model\n x_train = tf.random.uniform(shape=(1000, 10), maxval=64, dtype=tf.int32)\n y_train = tf.random.uniform(shape=(1000, 1), maxval=2, dtype=tf.int32)\n model.fit(x_train, y_train, epochs=10, batch_size=32)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5693531632423401, "alphanum_fraction": 0.6035973429679871, "avg_line_length": 38.33333206176758, "blob_id": "a2d12b72a0adf4d8ab29fde77f67b1104e72faa2", "content_id": "d62779ce14260c77306784a5dfcee047bff883ef", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5782, "license_type": "permissive", "max_line_length": 85, "num_lines": 147, "path": "/tests/layers/test_transformer_encoder.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import os\n\nimport pytest\nimport tensorflow as tf\nimport numpy as np\nfrom keras import regularizers\n\nfrom transformerx.layers import TransformerEncoder\n\n\nclass TestTransformerEncoder:\n @pytest.fixture(scope=\"class\")\n def encoder(self):\n return TransformerEncoder(\n vocab_size=1000,\n maxlen_position_encoding=50,\n d_model=128,\n num_heads=4,\n n_blocks=2,\n )\n\n def test_embedding_output_shape(self, encoder):\n input_data = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n embedded_data = encoder.embedding(input_data)\n assert embedded_data.shape == (2, 3, 128)\n\n def test_positional_encoding_output_shape(self, encoder):\n input_data = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n embedded_data = encoder.embedding(input_data)\n pos_encoded_data = encoder.pos_encoding(embedded_data)\n assert pos_encoded_data.shape == (2, 3, 128)\n\n def test_encoder_block_output_shape(self, encoder):\n input_data = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n valid_lens = tf.constant([3, 2], dtype=tf.float32)\n embedded_data = encoder.embedding(input_data)\n pos_encoded_data = encoder.pos_encoding(embedded_data)\n block_output, block_attn_weights = encoder.blocks[0](pos_encoded_data)\n assert block_output.shape == (2, 3, 128)\n\n def test_encoder_output_shape(self, encoder):\n input_data = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n valid_lens = tf.constant([3, 2], dtype=tf.float32)\n output, attn_weights = encoder(input_data)\n assert output.shape == (2, 3, 128)\n\n def test_encoder_output_values(self, encoder):\n input_data = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n valid_lens = tf.constant([3, 2], dtype=tf.float32)\n output, attn_weights = encoder(input_data)\n assert not np.allclose(output.numpy(), np.zeros((2, 3, 128)))\n\n def test_encoder_attention_weights_shape(self, encoder):\n input_data = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n valid_lens = tf.constant([3, 2], dtype=tf.float32)\n _ = encoder(input_data)\n for attention_weights in encoder.attention_weights:\n assert attention_weights.shape == (2, 4, 3, 3)\n\n def test_encoder_attention_weights_values(self, encoder):\n input_data = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)\n valid_lens = tf.constant([3, 2], dtype=tf.float32)\n _ = encoder(input_data)\n for attention_weights in encoder.attention_weights:\n assert not np.allclose(attention_weights.numpy(), np.zeros((2, 4, 3, 3)))\n\n\nclass TestTransformerEncoderIntegration:\n seq_length = 10\n vocab_size = 32\n\n @staticmethod\n def create_toy_dataset(\n num_samples=1000, seq_length=10, vocab_size=64, num_classes=2\n ):\n # x = np.random.randint(0, vocab_size, size=(num_samples, seq_length))\n x = np.random.normal(\n vocab_size / 2, vocab_size / 2 - 1, size=(num_samples, seq_length)\n )\n y = np.random.randint(0, 2, size=(num_samples, 1))\n y = np.random.normal(1, 1, size=(num_samples, seq_length))\n\n x_train = tf.random.uniform(\n shape=(num_samples, seq_length), maxval=vocab_size, dtype=tf.int32\n )\n y_train = tf.random.uniform(\n shape=(num_samples, 1), maxval=num_classes, dtype=tf.int32\n )\n return x_train, y_train\n\n @pytest.fixture\n def model(self):\n kernel_regularizer = regularizers.L1L2(l1=1e-5, l2=1e-4)\n inputs = tf.keras.layers.Input(shape=[self.seq_length])\n valid_lens = tf.keras.layers.Input(shape=())\n encoder = TransformerEncoder(\n vocab_size=self.vocab_size,\n maxlen_position_encoding=self.seq_length,\n d_model=64,\n num_heads=1,\n n_blocks=1,\n )\n learning_rate_schedule = lambda x: 1e-4 * x\n outputs, attn_weights = encoder(\n inputs,\n learning_rate_schedule=learning_rate_schedule,\n kernel_regularizer=kernel_regularizer,\n )\n # outputs = tf.keras.layers.Dense(10, activation=\"relu\")(inputs)\n outputs = tf.keras.layers.Conv1D(\n filters=16,\n kernel_size=2,\n padding=\"same\",\n activation=\"relu\",\n kernel_regularizer=kernel_regularizer,\n )(outputs)\n pooled_output = tf.keras.layers.GlobalAveragePooling1D()(outputs)\n predictions = tf.keras.layers.Dense(\n 1, activation=\"sigmoid\", kernel_regularizer=kernel_regularizer\n )(pooled_output)\n model = tf.keras.Model(inputs=[inputs], outputs=predictions)\n optimizer = tf.keras.optimizers.Adam(1e-4)\n model.compile(\n optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"]\n )\n print(model.summary())\n return model\n\n def test_training(self, model):\n x_train, y_train = self.create_toy_dataset(\n vocab_size=self.vocab_size, seq_length=self.seq_length, num_samples=100\n )\n history = model.fit(\n x_train, y_train, epochs=50, batch_size=16, validation_split=0.2\n )\n # tf.keras.mixed_precision.set_global_policy(\"mixed_float16\")\n assert (\n history.history[\"accuracy\"][-1] > 0.5\n ), \"Training accuracy should be greater than 0.5\"\n loss, accuracy = model.evaluate(x_train, y_train)\n\n assert accuracy > 0.5, \"Evaluation accuracy should be greater than 0.5\"\n\n prediction = model.predict(x_train)\n assert (\n 0 <= prediction[0][0] <= 1\n ), \"Prediction should be a probability value between 0 and 1\"\n" }, { "alpha_fraction": 0.593589723110199, "alphanum_fraction": 0.6132478713989258, "avg_line_length": 35, "blob_id": "47299c114b34db42c7e4f4cdf2f4bd42c2abc96d", "content_id": "50e35bef6c9f6ef5296499cfa73c21e5019d2261", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2340, "license_type": "permissive", "max_line_length": 84, "num_lines": 65, "path": "/transformerx/utils.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import os\n\nimport tensorflow as tf\n\n\ndef sequence_mask(X, attention_mask, value=-1e9):\n if not isinstance(X, tf.Tensor):\n raise TypeError(\"X must be a Tensor\")\n if not isinstance(attention_mask, tf.Tensor):\n raise TypeError(\"attention_mask must be a Tensor\")\n if len(X.shape) not in (2, 3, 4):\n raise ValueError(\"X must be a 2D, 3D, or 4D tensor\")\n if len(attention_mask.shape) not in (1, 2):\n raise ValueError(\"attention_mask must be a 1D or 2D tensor\")\n\n if len(attention_mask.shape) == 2:\n maxlen = X.shape[1]\n mask = tf.range(start=0, limit=maxlen, dtype=tf.float32)[None, :] < tf.cast(\n attention_mask, dtype=tf.float32\n )\n print(\"mask.shape: \", mask.shape, attention_mask.shape, X.shape)\n else:\n maxlen = X.shape[0]\n print(\"attention_mask.shape: \", attention_mask.shape, X.shape)\n mask = tf.range(start=0, limit=maxlen, dtype=tf.float32) < tf.cast(\n attention_mask, dtype=tf.float32\n )\n mask = tf.expand_dims(mask, axis=-1)\n if len(X.shape) > 3:\n X = tf.reshape(X, shape=(-1, X.shape[-1]))\n mask = tf.broadcast_to(mask, X.shape)\n return tf.where(mask, X, value)\n\n\ndef masked_softmax(X, attention_mask, temperature=1.0):\n \"\"\"Perform softmax operation by masking elements on the last axis.\"\"\"\n\n # x: 3D tensor, attention_mask: 1D or 2D tensor\n if attention_mask is None:\n return tf.nn.softmax(X / temperature, axis=-1)\n else:\n shape = X.shape\n if isinstance(attention_mask, tf.SparseTensor):\n attention_mask = tf.sparse.reshape(attention_mask, shape=(-1,))\n elif len(attention_mask.shape) == 1:\n attention_mask = tf.repeat(attention_mask, repeats=shape[1])\n else:\n attention_mask = tf.reshape(attention_mask, shape=-1)\n # On the last axis, replace masked elements with a very large negative\n # value, whose exponentiation outputs 0\n X = sequence_mask(\n tf.reshape(X, shape=(-1, shape[-1])), attention_mask, value=1e-7\n )\n return tf.nn.softmax(tf.reshape(X, shape=shape) / temperature, axis=-1)\n\n\ndef use_device(device):\n if device == \"cpu\":\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n else:\n pass\n\n\ndef exists(val):\n return val is not None\n" }, { "alpha_fraction": 0.5090726017951965, "alphanum_fraction": 0.5685483813285828, "avg_line_length": 32.62711715698242, "blob_id": "1b0e4fd2b886fe36bb17f8e86fe081702d15d5f5", "content_id": "680b58e96fd1a733b730a9b73bdfb766dd5b4e59", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1984, "license_type": "permissive", "max_line_length": 85, "num_lines": 59, "path": "/tests/layers/test_addnorm.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom transformerx.layers import AddNorm\n\n\nclass TestAddNorm:\n def test_init(self):\n # Test that the layer initializes correctly\n norm_type = \"layer\"\n dropout_rate = 0.2\n addnorm = AddNorm(norm_type=norm_type, dropout_rate=dropout_rate)\n\n assert addnorm.dropout_rate == dropout_rate\n\n # Test for invalid input for dropout_rate\n norm_type = \"batch\"\n dropout_rate = 1.2\n with pytest.raises(ValueError):\n addnorm = AddNorm(norm_type=norm_type, dropout_rate=dropout_rate)\n\n # Test for invalid input type for norm_shape\n norm_type = \"instance2\"\n dropout_rate = 0.2\n with pytest.raises(TypeError):\n addnorm = AddNorm(norm_type, dropout_rate)\n\n def test_call(self):\n def test_call():\n norm_shape = [0, 1]\n dropout_rate = 0.2\n addnorm = AddNorm(norm_shape, dropout_rate)\n\n x = tf.constant(np.arange(10).reshape(5, 2) * 10, dtype=tf.float32)\n y = tf.constant(np.arange(10).reshape(5, 2) * 10, dtype=tf.float32)\n\n # Test the shape of the output tensor\n assert addnorm(x, y).shape == (5, 2)\n\n # Test the output tensor values\n expected_output = np.array(\n [\n [-1.5666986, -1.2185433],\n [-0.8703881, -0.52223283],\n [-0.17407762, 0.17407762],\n [0.52223283, 0.8703881],\n [1.2185433, 1.5666986],\n ]\n )\n\n np.testing.assert_almost_equal(addnorm(x, y), expected_output, decimal=4)\n\n def test_invalid_dropout_rate(self):\n # Test that a ValueError is raised if an invalid dropout rate is provided\n dropout_rate = -0.2 # This should be between 0 and 1\n\n with pytest.raises(ValueError):\n addnorm = AddNorm(\"layer\", dropout_rate=dropout_rate)\n" }, { "alpha_fraction": 0.6346388459205627, "alphanum_fraction": 0.6428003311157227, "avg_line_length": 44.03341293334961, "blob_id": "ea00325e93e61d1038d3141ad74b47f9738395b4", "content_id": "de7ebe0adf65552193b1b723aa9ec1dd485a3761", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18869, "license_type": "permissive", "max_line_length": 150, "num_lines": 419, "path": "/transformerx/layers/transformer_encoder_block.py", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "from typing import Optional, Tuple, Callable\n\nimport tensorflow as tf\n\nfrom transformerx.layers.addnorm import AddNorm\nfrom transformerx.layers.multihead_attention import MultiHeadAttention\nfrom transformerx.layers.positionwise_ffn import PositionwiseFFN\n\n\nclass TransformerEncoderBlock1(tf.keras.layers.Layer):\n \"\"\"Transformer encoder block [1]_.\n\n Include a stack of layers used in the transformer encoder block.\n\n Parameters\n ----------\n d_model : int\n Dimensions of the queries, keys, and values\n norm_type :\n Arbitrary. Shape of the input.\n ffn_num_hiddens :\n Number of input hidden units\n num_heads : int\n Number of the heads in the multi-head attention\n dropout_rate :\n Float between 0 and 1. Fraction of the input units to drop.\n bias : bool - default = False\n Indicates the usage of bias in the dense layers (i.e. W_q, W_k, W_v, and W_o)\n \"\"\"\n\n def __init__(\n self,\n d_model,\n ffn_num_hiddens,\n num_heads,\n dropout_rate,\n norm_type=\"layer\",\n bias=False,\n ):\n super().__init__()\n self.attention = MultiHeadAttention(d_model, num_heads, dropout_rate, bias)\n self.addnorm1 = AddNorm(norm_type, dropout_rate)\n self.ffn = PositionwiseFFN(ffn_num_hiddens, d_model)\n self.addnorm2 = AddNorm(norm_type, dropout_rate)\n\n def call(self, X, attention_mask, **kwargs):\n Y = self.addnorm1(\n X, self.attention(X, X, X, attention_mask, **kwargs), **kwargs\n )\n return self.addnorm2(Y, self.ffn(Y), **kwargs)\n\n\nclass TransformerEncoderBlock(tf.keras.layers.Layer):\n \"\"\"Transformer Encoder Block\n\n The TransformerEncoderBlock is a custom layer in TensorFlow Keras that implements a single block of the Transformer\n encoder architecture [1]_, which is a key component of the Transformer model for natural language processing tasks such\n as machine translation, text classification, and language generation. The layer includes self-attention mechanism,\n feedforward networks, and residual connections with optional normalization and other customization options.\n\n Parameters\n ----------\n d_model: int (default=512)\n Dimensionality of the input and output tensors.\n num_heads: int (default=8)\n Number of attention heads.\n dropout_rate: float (default=0.0)\n Dropout rate for the attention and feedforward networks.\n norm_type: str (default=\"layer\")\n Type of normalization to be applied to the output of the feedforward networks. Can be either \"layer\", \"batch\",\n or \"instance\".\n norm_eps: float (default=1e-6)\n Epsilon value for numerical stability in normalization.\n attention_mechanism: str (default=\"scaled_dotproduct\")\n Type of attention mechanism to be used in the self-attention layer. Currently supports \"scaled_dotproduct\" and\n other custom attention mechanisms.\n input_hidden_units_ffn: int (default=32)\n Number of hidden units in the input layer of the feedforward networks.\n output_hidden_units_ffn: int (default=64)\n Number of hidden units in the output layer of the feedforward networks.\n use_norm: bool (default=True)\n Whether to apply normalization to the output of the feedforward networks.\n residual_connections: Optional[Tuple[bool, bool]] (default=None)\n Tuple indicating whether to apply residual connections before and after the self-attention and feedforward\n networks. If None, residual connections will be used by default.\n activation_fn: Optional[Callable] (default=None)\n Activation function to be used in the feedforward networks. If None, ReLU activation will be used by default.\n non_linear_proj: Optional (default=None)\n Non-linear projection function to be applied after the self-attention layer. If None, no non-linear projection\n will be applied.\n clip_norm: Optional[float] (default=None)\n Maximum norm for gradient clipping during training.\n kernel_initializer: Optional[Callable] (default=None)\n Initializer for the kernel weights of the self-attention and feedforward networks.\n bias_initializer: Optional[Callable] (default=None)\n Initializer for the bias weights of the self-attention and feedforward networks.\n mixed_precision: bool (default=False)\n Whether to use mixed precision training, which combines float16 and float32 data types for faster training.\n learning_rate_schedule: Optional[Callable] (default=None)\n Learning rate schedule function to be applied during training. If None, no learning rate schedule will be used.\n use_bias: bool (default=False)\n Whether to include bias terms in the computation of the self-attention weights.\n kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] (default=None)\n Regularizer for the kernel weights of the AddNorm layer.\n bias_regularizer: Optional[tf.keras.regularizers.Regularizer] (default=None)\n Regularizer for the bias weights of the AddNorm layer.\n contextualized_embeddings: None (default=None)\n Pre-trained language model embeddings to be incorporated into the feedforward networks for contextualization of\n input embeddings.\n **kwargs:\n Additional keyword arguments for the parent class tf.keras.layers.Layer.\n\n Raises\n ------\n ValueError\n If any of the input arguments are invalid:\n - d_model is not a positive integer.\n - input_hidden_units_ffn is not a positive integer.\n - num_heads is not a positive integer or not divisible by d_model.\n - dropout_rate is not a float between 0 and 1.\n - norm_type is not one of \"layer\", \"batch\", or \"instance\".\n - residual_connections is not None and not a tuple of two boolean values.\n - activation_fn is not callable.\n - clip_norm is not None and not a positive float.\n - kernel_initializer is not callable.\n - bias_initializer is not callable.\n - learning_rate_schedule is not callable.\n - mixed_precision is True but TensorFlow is not configured for mixed precision training.\n - bias is not a boolean.\n\n Examples\n --------\n >>> # Example 1: Initialize a custom transformer layer with default parameters\n >>> encoder_block = TransformerEncoderBlock()\n\n\n >>> # Example 2: Initialize a custom transformer layer with custom parameters\n >>> encoder_block = TransformerEncoderBlock(\n ... d_model=256,\n ... num_heads=4,\n ... dropout_rate=0.1,\n ... norm_type=\"batch\",\n ... norm_eps=1e-5,\n ... attention_mechanism=\"scaled_dotproduct\",\n ... input_hidden_units_ffn=64,\n ... output_hidden_units_ffn=128,\n ... use_norm=True,\n ... residual_connections=(True, True),\n ... activation_fn=tf.nn.relu,\n ... non_linear_proj=None,\n ... clip_norm=1.0,\n ... kernel_initializer=tf.keras.initializers.GlorotUniform(),\n ... bias_initializer=tf.keras.initializers.Zeros(),\n ... mixed_precision=False,\n ... learning_rate_schedule=None,\n ... use_bias=True,\n ... kernel_regularizer=tf.keras.regularizers.l2(0.01),\n ... bias_regularizer=None,\n ... contextualized_embeddings=None\n ... )\n\n See Also\n --------\n :func:`MultiHeadAttention` : The multi-head self-attention layer used in the TransformerEncoderBlock.\n :func:`PositionwiseFFN` : The position-wise feed-forward network used in the TransformerEncoderBlock.\n :func:`AddNorm` : The residual connection with layer normalization used in the TransformerEncoderBlock.\n\n References\n ----------\n .. [1] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L.,\n & Polosukhin, I. (2017). Attention is all you need. In Advances in neural information\n processing systems (pp. 5998-6008).\n\n Notes\n -----\n - This implementation follows the original Transformer model proposed by Vaswani et al. [1]_.\n - The `attention_mechanism` parameter allows the user to specify the type of attention\n mechanism to use in the multi-head self-attention layer. Possible values are \"scaled_dot_product\"\n and \"masked\". If not specified, \"scaled_dot_product\" is used by default.\n - The `use_norm` parameter controls whether to apply layer normalization after the multi-head\n self-attention and FFN layers. If set to False, no layer normalization is applied.\n - The `contextualized_embeddings` parameter allows the user to specify pre-trained contextualized\n embeddings, such as BERT or ELMo embeddings, to be used in the FFN layer. If not specified,\n standard embeddings are used by default.\n - The `mixed_precision` parameter enables mixed precision training using TensorFlow's\n experimental `mixed_float16` policy.\n - The `learning_rate_schedule` parameter allows the user to specify a custom learning rate\n schedule for the optimizer. The learning rate schedule should be a callable object that takes\n the current training step as input and returns the learning rate for that step.\n \"\"\"\n\n def __init__(\n self,\n d_model: int = 512, # Dimensionality of the input and output tensors\n num_heads: int = 8, # Number of attention heads\n dropout_rate: float = 0.0, # Dropout rate for the attention and feedforward networks\n norm_type: str = \"layer\", # Type of normalization (layer or batch) (feedforward networks)\n norm_eps: float = 1e-6,\n attention_mechanism: str = \"scaled_dotproduct\",\n input_hidden_units_ffn: int = 2048, # Number of input hidden units in the feedforward network\n use_norm: bool = True, # Whether to use normalization (layer or batch)\n residual_connections: Optional[\n Tuple[bool, bool]\n ] = None, # Whether to use residual connections\n activation_fn: Optional[\n Callable\n ] = None, # Activation function for the feedforward network\n non_linear_proj=None, # Non-linear projection for poistionwise feedforward network\n clip_norm: Optional[float] = None, # Maximum norm for gradient clipping\n kernel_initializer: Optional[\n Callable\n ] = None, # Initializer for the kernel weights\n bias_initializer: Optional[Callable] = None, # Initializer for the bias weights\n kernel_regularizer: Optional[\n tf.keras.regularizers.Regularizer\n ] = None, # kernel regularizer for AddNorm\n bias_regularizer: Optional[\n tf.keras.regularizers.Regularizer\n ] = None, # bias regularizer for AddNorm\n mixed_precision: bool = False, # Whether to use mixed precision training\n learning_rate_schedule: Optional[\n Callable\n ] = None, # Learning rate schedule function\n use_bias: bool = False, # Whether to include bias terms in the attention computation\n contextualized_embeddings: bool = None, # incorporate pre-trained language models such as BERT or GPT-2 into the model (feedforward networks)\n name: str = \"transformer_encoder_block\",\n dtype: Optional[tf.dtypes.DType] = None,\n **kwargs,\n ):\n super(TransformerEncoderBlock, self).__init__(name=name, dtype=dtype, **kwargs)\n assert isinstance(d_model, int) and d_model > 0, \"Invalid d_model: {}\".format(\n d_model\n )\n assert (\n isinstance(input_hidden_units_ffn, int) and input_hidden_units_ffn > 0\n ), \"Invalid ffn_num_hiddens: {}\".format(input_hidden_units_ffn)\n assert (\n isinstance(num_heads, int) and num_heads > 0 and d_model % num_heads == 0\n ), \"Invalid num_heads: {}\".format(num_heads)\n assert (\n isinstance(dropout_rate, float) and 0.0 <= dropout_rate <= 1.0\n ), \"Invalid dropout rate: {}\".format(dropout_rate)\n assert norm_type in [\n \"layer\",\n \"batch\",\n \"instance\",\n ], \"Invalid norm_type: {}\".format(norm_type)\n assert isinstance(use_bias, bool), \"Invalid bias: {}\".format(use_bias)\n if residual_connections is not None:\n assert (\n len(residual_connections) == 2\n ), \"residual_connections should be a tuple of two boolean values\"\n if activation_fn is not None:\n assert callable(activation_fn), \"activation_fn should be a callable object\"\n if clip_norm is not None:\n assert (\n isinstance(clip_norm, float) and clip_norm > 0.0\n ), \"Invalid clip_norm: {}\".format(clip_norm)\n if kernel_initializer is not None:\n assert callable(\n kernel_initializer\n ), \"kernel_initializer should be a callable object\"\n if bias_initializer is not None:\n assert callable(\n bias_initializer\n ), \"bias_initializer should be a callable object\"\n\n if learning_rate_schedule is not None:\n assert callable(\n learning_rate_schedule\n ), \"learning_rate_schedule should be a callable object\"\n\n self.d_model = d_model\n self.attention = MultiHeadAttention(\n d_model, num_heads, dropout_rate, use_bias, attention_mechanism, **kwargs\n )\n self.addnorm1 = (\n AddNorm(\n norm_type=norm_type,\n norm_eps=norm_eps,\n dropout_rate=dropout_rate,\n activation=activation_fn,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n **kwargs,\n )\n if use_norm\n else None\n )\n self.ffn = PositionwiseFFN(\n input_hidden_units=input_hidden_units_ffn,\n # output_hidden_units=output_hidden_units_ffn,\n activation=activation_fn,\n dropout_rate=dropout_rate,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n non_linear_proj=non_linear_proj,\n contextualized_embeddings=contextualized_embeddings,\n **kwargs,\n )\n self.addnorm2 = (\n AddNorm(\n norm_type=norm_type,\n norm_eps=norm_eps,\n dropout_rate=dropout_rate,\n activation=activation_fn,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n **kwargs,\n )\n if use_norm\n else None\n )\n self.residual_connections = residual_connections\n self.clip_norm = clip_norm\n self.mixed_precision = mixed_precision\n self.learning_rate_schedule = learning_rate_schedule\n\n if self.mixed_precision:\n policy = mixed_precision.Policy(\"mixed_float16\")\n mixed_precision.set_global_policy(policy)\n\n def call(self, queries, attention_mask=None, **kwargs):\n assert (\n len(queries.shape) == 3\n ), f\"Input tensor should have rank 3, got {len(queries.shape)}, {queries.shape}\"\n assert (\n queries.shape[-1] == self.d_model\n ), \"Last dimension of input tensor should be equal to d_model\"\n # if attention_mask is not None:\n # attention_mask = tf.cast(attention_mask, tf.int32)\n # assert (\n # len(attention_mask.shape) == 1\n # ), \"attention_mask should be a 1D tensor\"\n # assert isinstance(attention_mask[0].numpy(), int), 'Elements of attention_mask should be integers'\n if self.learning_rate_schedule is not None:\n global_step = kwargs.get(\"global_step\", None)\n if global_step is None:\n raise ValueError(\n \"global_step must be provided if learning_rate_schedule is not None\"\n )\n self.learning_rate = self.learning_rate_schedule(global_step)\n self.add_metric(self.learning_rate, name=\"learning_rate\")\n\n attn_output, attn_weights = self.attention(\n queries, queries, queries, attention_mask, **kwargs\n )\n if self.addnorm1:\n attn_output = self.addnorm1(queries, attn_output, **kwargs)\n ffn_output = self.ffn(attn_output, **kwargs)\n if self.addnorm2:\n ffn_output = self.addnorm2(attn_output, ffn_output, **kwargs)\n if self.residual_connections is None:\n output = ffn_output\n else:\n output = ffn_output if self.residual_connections[1] else attn_output\n output = queries + output if self.residual_connections[0] else output\n if self.clip_norm is not None:\n output = tf.clip_by_norm(output, self.clip_norm)\n\n return output, attn_weights\n\n\ndef main():\n # Set up a dummy batch of inputs and attention_mask\n batch_size = 4\n seq_length = 32\n d_model = 512\n inputs = tf.random.normal((batch_size, seq_length, d_model))\n # attention_mask = tf.constant([10, 8, 6, 10], dtype=tf.int32)\n # attention_mask = tf.cast(attention_mask, tf.int32)\n # attention_mask = tf.random.uniform((32, 1, 1, 64), maxval=2, dtype=tf.float32)\n # attention_mask = tf.zeros((seq_length), dtype=tf.int32)\n attention_mask = tf.ones((batch_size, seq_length, seq_length), dtype=tf.bool)\n p = 0.5\n attention_mask = tf.random.uniform((batch_size, seq_length, seq_length)) < p\n attention_mask = tf.cast(attention_mask, dtype=tf.bool)\n # Initialize a TransformerEncoderBlock object\n encoder_block = TransformerEncoderBlock(\n d_model=512,\n num_heads=4,\n dropout_rate=0.1,\n norm_type=\"batch\",\n norm_eps=1e-5,\n use_norm=True,\n attention_mechanism=\"scaled_dotproduct\",\n input_hidden_units_ffn=64,\n residual_connections=(True, True),\n activation_fn=tf.nn.relu,\n non_linear_proj=None,\n clip_norm=1.0,\n kernel_initializer=tf.keras.initializers.GlorotUniform(),\n bias_initializer=tf.keras.initializers.Zeros(),\n mixed_precision=False,\n learning_rate_schedule=None,\n use_bias=True,\n kernel_regularizer=tf.keras.regularizers.l2(0.01),\n bias_regularizer=None,\n contextualized_embeddings=None,\n )\n encoder_block2 = TransformerEncoderBlock(\n d_model=d_model, num_heads=d_model // seq_length, dropout_rate=0.1\n )\n\n # Pass the inputs through the encoder block\n outputs = encoder_block(inputs, attention_mask=attention_mask)\n\n # Check that the output tensor has the correct shape\n assert outputs.shape == (\n batch_size,\n seq_length,\n d_model,\n ), f\"{outputs.shape}, ({batch_size}, {seq_length})\"\n\n print(\"Test passed.\")\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7422463297843933, "alphanum_fraction": 0.745859682559967, "avg_line_length": 27.384614944458008, "blob_id": "a958ba740223087fa9d88616a03a017718e4316f", "content_id": "9393636f1e98cdd9b4b524fda058f7267207f281", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3321, "license_type": "permissive", "max_line_length": 181, "num_lines": 117, "path": "/CONTRIBUTING.md", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "# Contributing to the TransformerX\n\nWe want to make contributing to this project as easy and transparent as\npossible.\n\n## Our Development Process\n\nMinor changes and improvements will be released on an ongoing basis. Larger\nchanges (e.g., changesets implementing a new paper) will be released on a\nmore periodic basis.\n\n## Pull Requests\n\nWe actively welcome your pull requests.\n\n1. Fork the repo and create your branch from `master`.\n2. If you've added code that should be tested, add tests.\n3. If you've changed APIs, update the documentation.\n4. Ensure the test suite passes.\n5. Make sure your code lints (we recomend using Black plugin on Pycharm).\n\n## Issues\n\nWe use GitHub issues to track public bugs. Please ensure your description is\nclear and has sufficient instructions to be able to reproduce the issue.\n\n## Environment setup\n\nWe recommend using Pycharm which handles all these stuff for you with minimal interaction. Also, there are other good IDEs you can use.\n\notherwise:\n\n```bash\nname@user:~$ cd path/to/transformerX\nname@user:path/to/transformerX~$ python3 -m venv myenv\nname@user:path/to/transformerX~$ source myenv/bin/activate\n(myenv) name@user:path/to/transformerX~$ pip3 install -r requirements-test.txt\n```\n\n## Coding Style\n\nTwo options to make sure that the code is formatted and linted properly:\n* either you run black, mypy and isort before opening up your PR.\n\n```bash\nblack .\nisort . --profile black\nflake8 --config .flake8\nmypy --ignore-missing-imports --scripts-are-modules --pretty --exclude build/ --exclude stubs/ .\n```\n\n* or you can just install black plugin on Pycharm which will make sure that all of the above is run automatically anytime you commit.\n\nAfter these steps each of your commits will run the same linting and formatting routines as the TransformerX continuous integration, which greatly helps getting your PRs all green !\n\n## Testing\n\n### Static analysis\n\n```bash\nmypy --ignore-missing-imports --scripts-are-modules --pretty --exclude stubs/ .\n```\n\n### Unit tests\n\n```bash\npytest\n```\n\nor\n\n``` bash\npython -m pytest\n```\n\n### Check test coverage\n\n``` bash\npython -m pytest --cov-report term --cov=template tests\n```\n\n## Commit Guidelines\n\nWe follow the same guidelines as AngularJS. Each commit message consists of a **header**,\na **body** and a **footer**. The header has a special format that includes a **type**,\nand a **subject**:\n\n```bash\n[<type>] <subject>\n<BLANK LINE>\n<body>\n<BLANK LINE>\n<footer>\n```\n\nAny line of the commit message cannot be longer 100 characters! This allows the message to be easier\nto read on github as well as in various git tools.\n\n### Type\n\nMust be one of the following:\n\n* **feat**: A new feature\n* **fix**: A bug fix\n* **cleanup**: Changes that do not affect the meaning of the code (white-space, formatting, missing\n semi-colons, dead code removal etc.)\n* **refactor**: A code change that neither fixes a bug or adds a feature\n* **perf**: A code change that improves performance\n* **test**: Adding missing tests or fixing them\n* **chore**: Changes to the build process or auxiliary tools and libraries such as documentation\ngeneration\n* **docs**: Documentation only changes\n\n## License\n\nBy contributing to *TransformerX*, you agree that your contributions will be licensed\nunder the LICENSE file in the root directory of this source tree.\n" }, { "alpha_fraction": 0.6224753856658936, "alphanum_fraction": 0.6478508710861206, "avg_line_length": 30.145160675048828, "blob_id": "dba7fe09abe61107f1ec9028cf25d5103c9ed936", "content_id": "ff485a7cf9496590d093735fa2415f910a5e67cb", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 1931, "license_type": "permissive", "max_line_length": 110, "num_lines": 62, "path": "/pyproject.toml", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "[tool.poetry]\nname = \"TransformerX\"\nversion = \"1.0.0.beta.4\"\ndescription = \"TransformerX is a python library for building transformer-based models using pre-built layers.\"\nhomepage = \"https://github.com/tensorops/TransformerX\"\nrepository = \"https://github.com/tensorops/TransformerX\"\nauthors = [\"Soran Ghaderi <[email protected]>\", \"sigma1326 <[email protected]>\"]\nmaintainers = [\"Soran Ghaderi <[email protected]>\", \"sigma1326 <[email protected]>\"]\nreadme = \"README.md\"\nlicense = \"Apache-2.0\"\ninclude = [\n \"License\",\n]\npackages = [\n { include = \"transformerx\" }\n]\nclassifiers = [\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: 3.11\",\n \"Topic :: Software Development\",\n \"Topic :: Software Development :: Libraries\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Scientific/Engineering\",\n \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n \"Topic :: Scientific/Engineering :: Mathematics\",\n \"Intended Audience :: Science/Research\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Education\",\n]\nkeywords = [\n \"transformer\",\n \"deep-learning\",\n \"machine-learning\",\n \"NLP\",\n \"natural-language-processing\",\n \"computer-vision\",\n \"cv\",\n \"vision\",\n \"speech-recognition\",\n]\n\n[tool.poetry.dependencies]\nnumpy = \">=1.18.5\"\nmatplotlib = {version = \"^3.5.3\", optional = true }\ntensorflow = \">=2.2.0\"\neinops = \"^0.4.1\"\n\n[tool.poetry.dev-dependencies]\npytest = \"^7.1.2\"\n\n[build-system]\nrequires = [\"poetry-core>=1.0.0\"]\nbuild-backend = \"poetry.core.masonry.api\"\n" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.6246498823165894, "avg_line_length": 12.730769157409668, "blob_id": "ba41f3077c902e879c2b55aefb46c7826d2d6e5e", "content_id": "e59b212f4f456586ee4d3b3a8dc1c0b82a295b7d", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 357, "license_type": "permissive", "max_line_length": 28, "num_lines": 26, "path": "/docs/source/transformerx.rst", "repo_name": "soran-ghaderi/iowa_gambling_task", "src_encoding": "UTF-8", "text": "transformerx package\n====================\n\n.. automodule:: transformerx\n :members:\n :undoc-members:\n :show-inheritance:\n\nSubpackages\n-----------\n\n.. toctree::\n :maxdepth: 4\n\n transformerx.layers\n transformerx.training\n transformerx.txplot\n\nSubmodules\n----------\n\n.. toctree::\n :maxdepth: 4\n\n transformerx.data_loader\n transformerx.utils\n" } ]
42
Saumyaa27/Disease-prediction-and-patient-management-webapp
https://github.com/Saumyaa27/Disease-prediction-and-patient-management-webapp
fb0fa5f9f77f968092c1df06d5abfcbaccadcff9
ec08ece69a6d085a801316a9ec220a472aef02fb
50272366e3d57aeb0cfc91a69dbd080b234647bd
refs/heads/master
2023-01-03T07:48:28.244851
2020-10-27T12:23:31
2020-10-27T12:23:31
307,931,319
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.663755476474762, "alphanum_fraction": 0.6703056693077087, "avg_line_length": 37.20833206176758, "blob_id": "71036b3b6e483c195402d42302b4dc0d0b75f806", "content_id": "f6dbd436fe81cc5390c6cf9382b8d9c853ec77a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 916, "license_type": "no_license", "max_line_length": 125, "num_lines": 24, "path": "/Users/utils.py", "repo_name": "Saumyaa27/Disease-prediction-and-patient-management-webapp", "src_encoding": "UTF-8", "text": "from django.utils.encoding import force_bytes, force_text\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.template.loader import render_to_string\nfrom .token import account_activation_token\nfrom django.core.mail import EmailMessage\n\ndef send_email(current_site,user,name=None,mess=\"confirm your registration\",link=\"activate\",subj = \"Activate your account.\"):\n mail_subject = subj\n if name is None:\n name=user.email\n message = render_to_string('Users/acc_active_email.html', {\n 'message' : mess,\n 'link' : link,\n 'user': user,\n 'name': name, \n 'domain': current_site.domain,\n 'uid':urlsafe_base64_encode(force_bytes(user.pk)),\n 'token':account_activation_token.make_token(user),\n })\n to_email = user.email\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()" }, { "alpha_fraction": 0.7228520512580872, "alphanum_fraction": 0.732100248336792, "avg_line_length": 38.89285659790039, "blob_id": "190d767a823731fc40622d5b5c80edb59e282a2d", "content_id": "e04ef775f81498ba36a23126fbc5727d033ea84a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3352, "license_type": "no_license", "max_line_length": 103, "num_lines": 84, "path": "/Users/models.py", "repo_name": "Saumyaa27/Disease-prediction-and-patient-management-webapp", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import AbstractBaseUser\nfrom django.contrib.auth.models import PermissionsMixin\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils import timezone\n\nfrom .managers import CustomUserManager\n\nclass User(AbstractBaseUser, PermissionsMixin):\n email = models.EmailField(_('email address'), unique=True)\n\n is_doctor = models.BooleanField(default=False)\n is_patient = models.BooleanField(default=False)\n is_staff = models.BooleanField(default=False)\n is_active = models.BooleanField(default=True)\n date_joined = models.DateTimeField(default=timezone.now)\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = []\n\n objects = CustomUserManager()\n\n def __str__(self):\n return self.email\n\nclass Patient(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE,related_name=\"Patient\")\n Name = models.CharField(max_length=80,default = None,null=True)\n Age = models.IntegerField(default = None,null=True)\n Address = models.TextField(max_length=300,null=True)\n Gender = models.CharField(max_length=30,null=True)\n\n def __str__(self):\n return self.Name\n\n\nclass Specialization(models.Model):\n Name = models.CharField(max_length=100,null=True,blank=True,default = None)\n\n def __str__(self):\n return self.Name\n\nclass Doctor(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE,related_name=\"Doctor\")\n Name = models.CharField(max_length=80,default = None,null=True)\n Age = models.IntegerField(default = None,null=True)\n Address = models.TextField(max_length=300,null=True)\n Gender = models.CharField(max_length=30,null=True)\n Specialization = models.ForeignKey(Specialization,on_delete=models.PROTECT,related_name=\"Doctors\")\n contact = models.IntegerField(null=True)\n Qualification = models.CharField(max_length=30,null=True)\n\n def __str__(self):\n return self.Name\n\n\nfrom django.db import models\n\nclass Reports(models.Model):\n name= models.CharField(max_length=100)\n Description = models.CharField(max_length=500)\n Patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name=\"Reports\")\n filepath= models.FileField(upload_to='files/', null=True, verbose_name=\"\")\n Doctors = models.ManyToManyField(Doctor,related_name=\"Reports\",null=True,blank=True)\n \n def __str__(self):\n return self.name + \": \" + str(self.filepath)\n\nclass Disease(models.Model):\n Name = models.CharField(max_length=100,null=True,blank=True,default = None)\n Specialization = models.ForeignKey(Specialization,on_delete=models.CASCADE,related_name=\"Diseases\")\n\n def __str__(self):\n return self.Name\n\nclass Treatment(models.Model):\n Patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name=\"Treatments\")\n Doctor = models.ForeignKey(Doctor,related_name=\"Treatments\",null=True,on_delete=models.CASCADE)\n is_active = models.BooleanField(default=False)\n is_new = models.BooleanField(default=False)\n is_completed = models.BooleanField(default=False)\n Disease = models.ForeignKey(Disease,on_delete=models.PROTECT,related_name=\"Patients\")\n Prescription = models.TextField(max_length=800,null=True,default = None,blank=True)\n Appointment = models.DateField(null=True,default = None,blank=True)\n\n" }, { "alpha_fraction": 0.6587197780609131, "alphanum_fraction": 0.6613324880599976, "avg_line_length": 30.255102157592773, "blob_id": "8a18b15082ae7d6fa65edf3ca074ee5a1ccdefc1", "content_id": "d19cd24fa80477d59a1d321cf7f530aeea6d87e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3062, "license_type": "no_license", "max_line_length": 136, "num_lines": 98, "path": "/Users/forms.py", "repo_name": "Saumyaa27/Disease-prediction-and-patient-management-webapp", "src_encoding": "UTF-8", "text": "from django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom django import forms\nfrom .models import User,Reports,Treatment,Doctor,Patient\nfrom bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin\nfrom django.contrib.auth.password_validation import validate_password\nfrom django.core import validators\n\n\nclass CustomUserCreationForm(UserCreationForm):\n\n class Meta(UserCreationForm):\n model = User\n fields = ['email',]\n\n\nclass CustomUserChangeForm(UserChangeForm):\n\n class Meta:\n model = User\n fields = ['email']\n\nclass LoginUserForm(forms.ModelForm):\n password = forms.CharField(widget=forms.PasswordInput())\n class Meta:\n model = User\n fields = ['email','password'] \n\nclass RegisterUserForm(forms.ModelForm):\n # password1 = forms.CharField(widget=forms.PasswordInput(),validators=[validate_password]) #uncomment when using password validation\n password1 = forms.CharField(widget=forms.PasswordInput())\n password2 = forms.CharField(widget=forms.PasswordInput())\n class Meta:\n model = User\n fields = ['email','password1','password2']\n\nclass Forgot_email_form(forms.ModelForm):\n class Meta:\n model = User\n fields = ['email']\n\nclass Forgot_Password_Form(forms.ModelForm):\n # password1 = forms.CharField(widget=forms.PasswordInput(),validators=[validate_password]) # to use django validation\n password1 = forms.CharField(widget=forms.PasswordInput())\n password2 = forms.CharField(widget=forms.PasswordInput())\n class Meta:\n model = User\n fields = ['password1','password2']\n \n\nclass FileForm(forms.ModelForm):\n class Meta:\n model= Reports\n fields= [\"name\", \"filepath\",\"Description\"]\n \n def save(self,user):\n data = self.cleaned_data\n report = Reports(name=data['name'], filepath=data['filepath'],\n Description=data['Description'], Patient=user.Patient)\n report.save()\n\nclass send_to_doc_Form(forms.ModelForm):\n class Meta:\n model= Reports\n fields = [\"Doctors\"]\n \n def __init__ (self,Patient, *args, **kwargs):\n super(send_to_doc_Form, self).__init__(*args, **kwargs)\n self.fields[\"Doctors\"].widget = forms.widgets.CheckboxSelectMultiple()\n choices = []\n # choices = [(d.Doctor.id,d.Doctor.Name) for d in Patient.Treatments.all()]\n for treat in Patient.Treatments.all():\n if treat.is_active:\n choices.append((treat.Doctor.id,treat.Doctor.Name))\n self.fields[\"Doctors\"].choices = choices\n\n \n\n# class Treatment_Form(forms.ModelForm):\n# class Meta:\n# model= Treatment\n# fields = [\"Doctor\",\"Disease\"]\n \n\nclass Register_Doc(forms.ModelForm):\n class Meta:\n model=Doctor\n exclude = ['user']\n\n\nclass Register_Patient(forms.ModelForm):\n class Meta:\n model=Patient\n exclude = ['user']\n\nclass Prescription(forms.ModelForm):\n class Meta:\n model = Treatment\n fields = ['Prescription']" }, { "alpha_fraction": 0.6485956907272339, "alphanum_fraction": 0.6668843626976013, "avg_line_length": 53.71428680419922, "blob_id": "e6ab9446ea50f08beaf36173b1cd69818ae6a3db", "content_id": "5dafb79d49918d8cae56c3b50409469ab270ce28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1531, "license_type": "no_license", "max_line_length": 131, "num_lines": 28, "path": "/Users/urls.py", "repo_name": "Saumyaa27/Disease-prediction-and-patient-management-webapp", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\",views.login_view,name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"rform/<int:num>\",views.rform,name=\"rform\"),\n path(\"reg\", views.reg, name=\"reg\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"registerD\", views.register_Doctor, name=\"registerDoctor\"),\n path(\"reports\", views.showfile, name=\"reports\"),\n path(\"View_Treatment\",views.View_Treatment, name = \"View_Treatment\"),\n url(r'^activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'),\n path(\"send/<int:nums>\",views.send,name=\"send\"),\n path(\"NewTreat\",views.view_new_treatments,name=\"NewTreat\"),\n path(\"ActiveTreat\",views.view_active_treatments,name=\"ActiveTreat\"),\n path(\"Treat/<int:nums>\",views.Treats,name=\"Treat\"),\n path(\"Email_Forget\",views.email_forgot,name=\"Email_Forget\"),\n url(r'^Forgot/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.Forgot,name=\"Forgot\"),\n path(\"Edit_profile\",views.Edit_profile,name=\"Edit_profile\"),\n path(\"Change_Password\",views.Change_Password,name=\"Change_Password\"),\n path(\"delete_Treatment/<int:nums>\",views.delete_Treat,name=\"Delete_Treatment\"),\n path(\"Complete_Treatment/<int:nums>\",views.Complete_Treat,name=\"Complete_Treatment\"),\n path(\"not_new/<int:nums>\",views.not_new,name=\"not_new\"),\n]" }, { "alpha_fraction": 0.8088235259056091, "alphanum_fraction": 0.8088235259056091, "avg_line_length": 30.733333587646484, "blob_id": "4bbf578106a1dd9e09165ab5b6e97ced91a962de", "content_id": "a08a59479a6e18b4ed412e27c52a3cb1893367fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 476, "license_type": "no_license", "max_line_length": 120, "num_lines": 15, "path": "/README.md", "repo_name": "Saumyaa27/Disease-prediction-and-patient-management-webapp", "src_encoding": "UTF-8", "text": "# Software Engineering\n\nlogin/ register user\nForgot password\n\nif user is patient:\nthey can upload reports, Send the reports to Doctors( with whom they have treatment) [Treatments are added via database]\nPatient can view Treatments.\nEdit their profile\n\nif User id Doctor\nThey can view treatmenst ( Active and new )\nActive treatment details can be viewed [by clicking on hyperlink above them]\nTreatments details contain detailed treatment info, Shared reports\nEdit user profile\n" }, { "alpha_fraction": 0.5641618967056274, "alphanum_fraction": 0.5658512115478516, "avg_line_length": 31.602041244506836, "blob_id": "e131f4ceced2b0d9f4007477785d44916f46a583", "content_id": "7946a226eaf36c74bd1a8c9562b8712a89a42dba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15983, "license_type": "no_license", "max_line_length": 163, "num_lines": 490, "path": "/Users/views.py", "repo_name": "Saumyaa27/Disease-prediction-and-patient-management-webapp", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.db import IntegrityError\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import User,Patient,Doctor,Reports,Treatment\nfrom .forms import FileForm , send_to_doc_Form,Register_Doc,Register_Patient, LoginUserForm, RegisterUserForm, Forgot_email_form,Forgot_Password_Form, Prescription\nfrom .utils import send_email\nfrom django.contrib.sites.shortcuts import get_current_site\n\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom .token import account_activation_token\n\nfrom .decorators import patient_required, doctor_required\nfrom django.views.decorators.http import require_http_methods\n\n# Create your views here.\n\ndef Change_Password(request):\n if request.method == \"POST\":\n form = Forgot_Password_Form(request.POST)\n if not form.is_valid() or form.data.get('password1') != form.data.get('password2'):\n return render(request, \"Users/forgot.html\",{\n \"message\" : \"Change Passsword\",\n \"form\" : form,\n \"name\" : \"Change Password\",\n \"error\" : \"Passwords Should Match\"\n })\n else:\n request.user.set_password(form.data.get('password1'))\n request.user.save()\n # return HttpResponseRedirect(reverse(\"login\"))\n return render(request, \"Users/confirmation.html\",{\n \"message\" : \"Password Changed Succesfully. Now you can login your account.\" \n })\n\n form = Forgot_Password_Form()\n return render(request, \"Users/forgot.html\",{\n \"message\" : \"Change Passsword\",\n \"form\" : form,\n \"name\" : \"Change Password\",\n })\n\n@login_required\ndef Edit_profile(request):\n message = None\n if request.method == \"POST\":\n if request.user.is_patient:\n form = Register_Patient(data=request.POST,instance=request.user.Patient)\n form.save()\n \n else: \n form = Register_Doc(data=request.POST,instance=request.user.Doctor)\n form.save()\n \n message = \"Profile Updated Succesfully\"\n \n if request.user.is_patient:\n form = Register_Patient(instance=request.user.Patient)\n else: \n form = Register_Doc(instance=request.user.Doctor)\n\n return render(request,\"Users/Edit.html\",{\n \"form\" : form,\n \"message\" : message\n })\n\n\n@login_required\n@doctor_required\ndef view_active_treatments(request):\n Treatments = Treatment.objects.filter(Doctor=request.user.Doctor)\n t = []\n for tr in Treatments:\n if tr.is_active:\n t.append(tr)\n\n return render(request, 'Users/ActiveTreat.html',{\n 'Treatments' : t,\n })\n\n@login_required\n@doctor_required\ndef view_new_treatments(request):\n Treatments = Treatment.objects.filter(Doctor=request.user.Doctor)\n t = []\n for tr in Treatments:\n if tr.is_new:\n t.append(tr)\n\n return render(request, 'Users/NewTreat.html',{\n 'Treatments' : t\n })\n\n@login_required\ndef Treats(request,nums):\n Treat = Treatment.objects.get(pk=nums)\n if request.user.is_doctor:\n reports = request.user.Doctor.Reports.all()\n if Treat.Doctor != request.user.Doctor or Treat.is_completed or Treat.is_new:\n return HttpResponseRedirect(reverse(\"index\"))\n\n form = Prescription(instance=Treat)\n return render(request, 'Users/Treatment.html',{\n 'Treatment' : Treat,\n 'files' : reports,\n 'presc' : form\n })\n else:\n reports = Reports.objects.filter(Patient=request.user.Patient)\n if Treat.Patient != request.user.Patient or Treat.is_new:\n return HttpResponseRedirect(reverse(\"index\"))\n\n return render(request, 'Users/Treatment.html',{\n 'Treatment' : Treat,\n 'files' : reports\n })\n\n@login_required()\ndef delete_Treat(request,nums):\n t = Treatment.objects.get(pk=nums)\n print(nums)\n if t.Patient != request.user.Patient:\n return HttpResponseRedirect(reverse(\"View_Treatment\"))\n \n t.delete()\n return HttpResponseRedirect(reverse(\"View_Treatment\"))\n\n@login_required()\ndef Complete_Treat(request,nums):\n if request.method == \"POST\":\n t = Treatment.objects.get(pk=nums)\n print(nums)\n if t.Doctor != request.user.Doctor:\n pass\n else:\n t.is_completed = True\n t.is_active = False\n t.save()\n\n return HttpResponseRedirect(reverse(\"ActiveTreat\"))\n\n@login_required()\ndef not_new(request,nums):\n if request.method == \"POST\":\n t = Treatment.objects.get(pk=nums)\n print(nums)\n if t.Doctor != request.user.Doctor:\n pass\n else:\n t.is_new = False\n if \"Accept\" in request.POST:\n t.is_active = True\n t.save()\n\n return HttpResponseRedirect(reverse(\"NewTreat\"))\n\n@login_required()\n@patient_required\ndef View_Treatment(request):\n Treatments = Treatment.objects.filter(Patient=request.user.Patient)\n \n active = []\n new= []\n rejected = []\n completed = []\n\n for t in Treatments:\n if t.is_active:\n active.append(t)\n elif t.is_new:\n new.append(t)\n elif t.is_completed:\n completed.append(t)\n else:\n rejected.append(t)\n return render(request, 'Users/Treat.html',{\n 'active' : active,\n 'new' : new,\n 'rejected' : rejected,\n \"completed\" : completed\n }) \n\n\n\n@login_required()\n@patient_required\n@require_http_methods([\"POST\"])\ndef send(request,nums):\n if request.method == \"POST\":\n files = Reports.objects.get(pk=nums)\n if files.Patient != request.user.Patient:\n return HttpResponseRedirect(reverse(\"index\"))\n docs = request.POST.getlist(f'file_{nums}')\n \n for id in docs:\n if all(int(id) != doc.id for doc in files.Doctors.all()):\n d = Doctor.objects.get(pk=id)\n files.Doctors.add(d)\n\n for doc in files.Doctors.all():\n if str(doc.id) not in docs:\n d = Doctor.objects.get(pk=doc.id)\n files.Doctors.remove(d)\n \n \n return HttpResponseRedirect(reverse(\"reports\")) \n\n\n@login_required()\n@patient_required\ndef showfile(request):\n # lastfile = request.user.Patient.Reports\n form = FileForm(request.POST or None, request.FILES or None)\n if form.is_valid():\n form.save(request.user) #replace by patient\n\n lastfile= Reports.objects.filter(Patient=request.user.Patient)\n\n send_form = send_to_doc_Form(request.user.Patient)\n # treat = Treatment.objects.filter(Patient=request.user.Patient)\n # send_form.fields['Doctors'].queryset = (doc.Doctor for doc in treat )\n\n context = None\n if lastfile:\n context= {\n 'form': form,\n 'lastfile' : lastfile,\n 'Send' : send_form\n }\n\n if not context:\n context = {\n 'form': form,\n 'Send' : send_form\n }\n\n return render(request, 'Users/files.html', context)\n\n\ndef rform(request,num):\n if(num == 1):\n form = Register_Patient()\n else:\n form = Register_Doc()\n \n return render(request, 'Users/form.html', {\n \"form\" : form\n })\n\n\ndef index(request):\n return render(request, \"Users/index.html\",)\n\ndef email_forgot(request):\n if request.method == \"POST\":\n form = Forgot_email_form(request.POST)\n email = form.data.get(\"email\")\n print(email)\n u = User.objects.filter(email=email).first()\n \n print(\"here\",u)\n if u is not None :\n current_site = get_current_site(request)\n send_email(current_site,u,mess=\"reset your Password\",link=\"Forgot\",subj = \"Reset Password\")\n logout(request)\n return render(request, \"Users/confirmation.html\",{\n \"message\" : \"Change you password by email sent \",\n \"u\" : u,\n })\n else:\n return render(request, \"Users/forgot.html\",{\n \"message\" : \"Forgot Password\",\n \"form\" : form,\n \"name\" : \"Send Email\",\n \"error\" : \"Email Doesnot Exists\"\n })\n \n \n form = Forgot_email_form()\n return render(request, \"Users/forgot.html\",{\n \"message\" : \"Forgot Password\",\n \"form\" : form,\n \"name\" : \"Send Email\"\n })\n\ndef Forgot(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, user.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n if request.method == \"POST\":\n form = Forgot_Password_Form(request.POST)\n if not form.is_valid() or form.data.get('password1') != form.data.get('password2'):\n return render(request, \"Users/forgot.html\",{\n \"message\" : \"Change Passsword\",\n \"form\" : form,\n \"name\" : \"Change Password\",\n \"error\" : \"Password Should Match\"\n })\n else:\n user.set_password(form.data.get('password1'))\n user.save()\n return HttpResponseRedirect(reverse(\"login\"))\n\n else:\n form = Forgot_Password_Form()\n return render(request, \"Users/forgot.html\",{\n \"message\" : \"Change Passsword\",\n \"form\" : form,\n \"name\" : \"Change Password\",\n })\n else:\n return render(request, \"Users/confirmation.html\",{\n \"message\" : \"Link is invalid!\" \n })\n\ndef login_view(request):\n if request.method == \"POST\":\n # Attempt to sign user in\n log = LoginUserForm(request.POST)\n email = log.data.get(\"email\")\n password = log.data.get(\"password\")\n user = authenticate(request, email=email, password=password)\n\n # Check if authentication successful\n if user is not None:\n if not user.is_active:\n return HttpResponse(f'Please confirm your email address to complete the registration')\n login(request, user)\n link = request.POST[\"next\"]\n if link != \"None\":\n return HttpResponseRedirect(link)\n \n return HttpResponseRedirect(reverse(\"index\"))\n else: \n return render(request, \"Users/login.html\", {\n \"message\": \"Invalid username and/or password.\",\n \"next\" : request.POST[\"next\"],\n \"login\" : log\n })\n else:\n log = LoginUserForm()\n if \"next\" in request.GET:\n url = request.GET[\"next\"]\n else:\n url = None \n return render(request, \"Users/login.html\",{\n \"next\" : url,\n \"login\" : log,\n })\n \n\n\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect(reverse(\"index\"))\n\ndef reg(request):\n reg = RegisterUserForm()\n form = Register_Patient()\n return render(request, \"Users/registerDoctor.html\",{\n \"register\" : reg,\n \"form\" : form,\n })\n\n\ndef register(request):\n if request.method == \"POST\":\n reg = RegisterUserForm(request.POST)\n email = reg.data.get(\"email\")\n form = Register_Patient(request.POST)\n # Ensure password matches confirmation\n password = reg.data.get(\"password1\")\n confirmation = reg.data.get(\"password2\")\n if not reg.is_valid() or password != confirmation:\n return render(request, \"Users/registerDoctor.html\", {\n \"message\": \"Passwords must match.\",\n \"form\" : form,\n \"register\" : reg\n })\n if not form.is_valid():\n return render(request, \"Users/registerDoctor.html\",{\n \"form\" : form,\n \"register\" : reg,\n })\n\n # Attempt to create new user\n try:\n user = User.objects.create_user(email, password,is_active = True,is_patient = True) ### change is active to false\n user.save()\n p = form.save(commit=False)\n p.user = user\n p.save()\n current_site = get_current_site(request)\n send_email(current_site,user,p.Name)\n return render(request, \"Users/confirmation.html\",{\n \"message\" : \"Confirm your email\",\n \"u\" : user,\n })\n except IntegrityError:\n return render(request, \"Users/registerDoctor.html\", {\n \"message\": \"Username already taken.\",\n \"form\" : form,\n \"register\" : reg\n })\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return HttpResponseRedirect(reverse(\"index\"))\n\n\ndef register_Doctor(request):\n if request.method == \"POST\":\n form = Register_Doc(request.POST)\n reg = RegisterUserForm(request.POST)\n if not reg.is_valid():\n return render(request,\"Users/registerDoctor.html\",{\n \"form\" : form,\n \"d\" : True,\n \"register\" : reg\n })\n email = reg.data.get(\"email\")\n # Ensure password matches confirmation\n password = reg.data.get(\"password1\")\n confirmation = reg.data.get(\"password2\")\n if password != confirmation:\n return render(request, \"Users/registerDoctor.html\", {\n \"message\": \"Passwords must match.\",\n \"form\" : form,\n \"d\" : True,\n \"register\" : reg\n })\n if not form.is_valid():\n return render(request,\"Users/registerDoctor.html\",{\n \"form\" : form,\n \"d\" : True,\n \"register\" : reg\n })\n\n # Attempt to create new user\n try:\n user = User.objects.create_user(email, password,is_active = True,is_doctor = True) ### change is active to false\n user.save()\n d = form.save(commit=False)\n d.user = user\n d.save()\n current_site = get_current_site(request)\n send_email(current_site,user,d.Name)\n return render(request, \"Users/confirmation.html\",{\n \"message\" : \"Confirm your email\",\n \"u\" : user,\n })\n except IntegrityError:\n return render(request, \"Users/registerDoctor.html\", {\n \"message\": \"Username already taken.\",\n \"form\" : form,\n \"d\" : True,\n \"register\" : reg\n })\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n\n\n return HttpResponseRedirect(reverse(\"index\"))\n\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, user.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user)\n # return redirect('home')\n return render(request, \"Users/confirmation.html\",{\n \"message\" : \"Thank you for your email confirmation. Now you can login your account.\" \n })\n else:\n return render(request, \"Users/confirmation.html\",{\n \"message\" : \"Activation link is invalid!\" \n })\n " } ]
6
Manish-SmartEnovations/CRM_BACKEND
https://github.com/Manish-SmartEnovations/CRM_BACKEND
d47459d736767daa19d6bd4922081a7adf9dc036
1d174dbaebe1870c420e552e8c98eb0b0be9b3de
02706749ae51579d70fdcb81284bfdca91c5cb71
refs/heads/main
2023-03-21T02:38:59.718546
2021-03-08T11:39:18
2021-03-08T11:39:18
345,631,336
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6030324101448059, "alphanum_fraction": 0.6078566312789917, "avg_line_length": 29.536842346191406, "blob_id": "8cfcb3bcc0a5947651eaa7366654e54dddb49ab4", "content_id": "862f072144de79940fe1a4196001e4dc3f07e545", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2902, "license_type": "no_license", "max_line_length": 90, "num_lines": 95, "path": "/crm_apps/admin.py", "repo_name": "Manish-SmartEnovations/CRM_BACKEND", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.http import HttpResponse\nfrom django.contrib import admin\nfrom django.contrib.admin import AdminSite\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom .models import User\nfrom django.core.exceptions import ValidationError\n\n\n# try:\n# #loading site config\n# site_config = SiteConfig.load()\n \n# #change in admin interface values\n# AdminSite.site_header = site_config.company_name\n# AdminSite.site_title = site_config.compay_name\n \n# except:\n# pass\n\n\nclass UserCreationForm(forms.ModelForm):\n \"\"\"Custom User creation form\"\"\"\n password1 = forms.CharField(label='Password', widget=forms.PasswordInput)\n password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)\n\n class Meta:\n model = User\n fields = ('name', 'email', 'designation',\n 'role', 'manager', 'department')\n \n def clean_password2(self):\n # Check that the two password entries match\n password1 = self.cleaned_data.get(\"password1\")\n password2 = self.cleaned_data.get(\"password2\")\n if password1 and password2 and password1 != password2:\n raise ValidationError(\"Passwords don't match\")\n return password2\n \n def save(self, commit=True):\n # Save the provided password in hashed format\n user = super().save(commit=False)\n user.set_password(self.cleaned_data[\"password1\"])\n if commit:\n user.save()\n return user\n \nclass UserChangeForm(forms.ModelForm):\n \"\"\"Custom form for updating user information\"\"\"\n \n class Meta:\n model = User\n fields = ('name', 'email', 'password',\n 'role', 'manager', 'department','is_active', 'is_admin')\n \n def clean_password(self):\n return self.initial[\"password\"]\n \n \n\nclass UserAdmin(BaseUserAdmin):\n \"\"\"Custom admin for users\"\"\"\n \n add_form = UserCreationForm\n form = UserChangeForm\n model = User\n \n list_display = ('email', 'is_admin')\n list_filter = ('is_admin',)\n fieldsets = (\n (None, {'fields': ('email', 'password')}),\n ('Personal info', {\n 'fields': ('name','department')}),\n ('Manager', {'fields': ('role', 'designation' , 'manager')}),\n ('Permissions', {'fields': ('is_admin',)}),\n )\n \n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': ('name', 'email', 'designation', \n 'role', 'manager', 'department' ,'password1', 'password2'),\n }),\n )\n search_fields = ('email',)\n ordering = ('email',)\n filter_horizontal = ()\n \n \n \n\n# Register your models here.\nadmin.site.register(User, UserAdmin)\n\n" }, { "alpha_fraction": 0.5775535702705383, "alphanum_fraction": 0.5977301597595215, "avg_line_length": 44.31428527832031, "blob_id": "62933f6600ec9ae962fa60313d88cf576f0c7555", "content_id": "03aeb6b841b22820f0ef731145032efd4aeeb462", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1586, "license_type": "no_license", "max_line_length": 192, "num_lines": 35, "path": "/crm_apps/migrations/0001_initial.py", "repo_name": "Manish-SmartEnovations/CRM_BACKEND", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2021-03-08 07:30\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 ]\n\n operations = [\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('password', models.CharField(max_length=128, verbose_name='password')),\n ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),\n ('name', models.CharField(max_length=100)),\n ('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),\n ('designation', models.CharField(max_length=50, null=True, verbose_name='Designation')),\n ('role', models.PositiveSmallIntegerField(blank=True, choices=[(1, 'CEO'), (2, 'Manager'), (3, 'BDE')], null=True)),\n ('department', models.CharField(max_length=50, null=True, verbose_name='Department')),\n ('is_active', models.BooleanField(default=True)),\n ('is_admin', models.BooleanField(default=False)),\n ('manager', models.ForeignKey(blank=True, default=None, limit_choices_to={'role': 2}, null=True, on_delete=django.db.models.deletion.SET_DEFAULT, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5660635232925415, "alphanum_fraction": 0.5715261101722717, "avg_line_length": 24.478260040283203, "blob_id": "6e7c4621baf986150bec9db0b6a8e13aeb845b4f", "content_id": "63e0a0e6096b1dbc6181911152762ba64140841e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2929, "license_type": "no_license", "max_line_length": 76, "num_lines": 115, "path": "/crm_apps/models.py", "repo_name": "Manish-SmartEnovations/CRM_BACKEND", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import BaseUserManager, AbstractBaseUser\n\n\n\n# Create your models here.\n# class SiteConfig(singletonModel):\n# company_name = models.CharField(\n# default=\"Your company name\", max_length=225)\n# company_email = models.EmailField(default=\"[email protected]\")\n \nclass UserManager(BaseUserManager):\n \"\"\"Custom auth model\"\"\"\n \n def create_user(self, name, email, role=None, password=None):\n \n if not email:\n raise ValueError('User must have an email address')\n \n user = self.model(\n name=name,\n email=self.normalize_email(email),\n role=role\n )\n \n user.set_password(password)\n user.save(using=self._db)\n return user\n \n \n def create_superuser(self, name, email, password):\n user = self.create_user(\n name=name,\n email=email,\n password=password\n )\n \n user.is_admin = True\n user.save(using=self._db)\n return user\n\nclass User(AbstractBaseUser):\n \"\"\"Custom User for additional field\"\"\"\n \n \n name = models.CharField(max_length=100)\n \n email = models.EmailField(\n verbose_name='email address',\n max_length=255,\n unique=True\n )\n \n designation = models.CharField(\n (\"Designation\"), max_length=50, blank=False, null=True)\n \n \n # employee_image = models.ImageField(\n # upload_to=User_directory_path, blank=True, null=True)\n \n #choice for role\n CEO = 1\n MANAGER = 2\n BDE = 3\n \n ROLE_CHOICES = (\n (CEO, 'CEO'),\n (MANAGER, 'Manager'),\n (BDE, 'BDE')\n )\n \n role = models.PositiveSmallIntegerField(\n choices=ROLE_CHOICES, blank=True, null=True)\n \n @property\n def is_ceo(self):\n return self.role == self.CEO\n \n @property\n def is_manager(self):\n return self.role == self.MANAGER\n \n @property\n def is_bde(self):\n return self.role == self.BDE\n \n manager = models.ForeignKey('User', default=None, null=True, blank=True,\n limit_choices_to={'role':MANAGER},\n on_delete=models.SET_DEFAULT)\n \n department = models.CharField(\n (\"Department\"), max_length=50, blank=False, null=True)\n \n is_active = models.BooleanField(default=True)\n is_admin = models.BooleanField(default=False)\n \n objects = UserManager()\n \n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['name']\n \n def __str__(self):\n return self.email\n \n def has_perm(self, perm, obj=None):\n return True\n \n def has_module_perms(self, app_lable):\n return True\n \n @property\n def is_staff(self):\n \"Is the user a member of staff?\"\n # Simplest possible answer: All admins are staff\n return self.is_admin" } ]
3
alexlines8/CAM-ON-ENGERLAND
https://github.com/alexlines8/CAM-ON-ENGERLAND
5fbe86257eb0daab58aae4c73df52ecc6d42c3ca
e003a71cbcda5bb9150811172ec221a065c78862
ce83680e45e1e3a455c8cf0bf48ca7d786ed51ca
refs/heads/main
2023-06-19T02:14:06.243639
2021-07-09T20:46:57
2021-07-09T20:46:57
384,547,276
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5468137264251709, "alphanum_fraction": 0.5754901766777039, "avg_line_length": 29.399999618530273, "blob_id": "533b3bb8ae9a73376489d64973f97e65ad3e2474", "content_id": "e79fcaab2268fa6aa8869fba5fa427b4e92da6ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4080, "license_type": "no_license", "max_line_length": 143, "num_lines": 130, "path": "/COME ON ENGERLAND!/Come on England.py", "repo_name": "alexlines8/CAM-ON-ENGERLAND", "src_encoding": "UTF-8", "text": "import pygame, sys\r\nimport time\r\npygame.font.init()\r\npygame.mixer.init()\r\nclock = pygame.time.Clock()\r\n\r\nWIDTH = 900\r\nHEIGHT = 500\r\nWIN = pygame.display.set_mode((WIDTH,HEIGHT))\r\npygame.display.set_caption(\"iCoach\")\r\nPITCH = pygame.transform.scale(pygame.image.load('C://Users/alexl/Documents/Coding/Python/COME ON ENGERLAND!/Assets/pitch.jpg'),(WIDTH,HEIGHT))\r\nENGERLAND_SOUND = pygame.mixer.Sound('C://Users/alexl/Documents/Coding/Python/COME ON ENGERLAND!/Assets/CAM ON INGERLAND.mp3')\r\n\r\nWHITE = (255,255,255)\r\nRED = (255,0,0)\r\nFPS = 60\r\n\r\nSCORE_FONT = pygame.font.SysFont('comicsans', 150)\r\nNAME_FONT = pygame.font.SysFont('comicsans', 70)\r\nCOUNTDOWN_FONT = pygame.font.SysFont('comicsans', 200)\r\n\r\n\r\n\r\ndef sound_check(leftScore,rightScore):\r\n if leftScore%50 == 0 and leftScore!=0 and leftScore%100 !=0:\r\n output = True\r\n elif rightScore%100 == 0 and rightScore!= 0:\r\n output = True\r\n else:\r\n output = False\r\n \r\n return output\r\n\r\n\r\ndef start_count():\r\n current_time = 0\r\n startTime = 0\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n\r\n current_time = pygame.time.get_ticks()\r\n\r\n if current_time - startTime < 1000:\r\n WIN.blit(PITCH, (0,0))\r\n timerText = COUNTDOWN_FONT.render(str(3), False, WHITE)\r\n tLength = timerText.get_width()\r\n tHeight = timerText.get_height()\r\n WIN.blit(timerText, (WIDTH/2 - tLength/2, HEIGHT/2 - tHeight/2))\r\n\r\n elif current_time - startTime < 2000:\r\n WIN.blit(PITCH, (0,0))\r\n timerText = COUNTDOWN_FONT.render(str(2), False, WHITE)\r\n tLength = timerText.get_width()\r\n tHeight = timerText.get_height()\r\n WIN.blit(timerText, (WIDTH/2 - tLength/2, HEIGHT/2- tHeight/2))\r\n \r\n elif current_time - startTime < 3000:\r\n WIN.blit(PITCH, (0,0))\r\n timerText = COUNTDOWN_FONT.render(str(1), False, WHITE)\r\n tLength = timerText.get_width()\r\n tHeight = timerText.get_height()\r\n \r\n WIN.blit(timerText, (WIDTH/2 - tLength/2, HEIGHT/2- tHeight/2))\r\n \r\n elif current_time - startTime < 4000:\r\n break\r\n\r\n pygame.display.flip()\r\n clock.tick(60)\r\n\r\n \r\n\r\n\r\ndef draw_window_play(leftScore, rightScore, leftPlayer, rightPlayer):\r\n WIN.blit(PITCH, (0,0))\r\n \r\n if sound_check(leftScore, rightScore) == True:\r\n ENGERLAND_SOUND.play()\r\n\r\n leftPlayerText = NAME_FONT.render(str(leftPlayer),False,WHITE)\r\n lNameLength = leftPlayerText.get_width()\r\n rightPlayerText = NAME_FONT.render(str(rightPlayer),False,WHITE)\r\n rNameLength = rightPlayerText.get_width()\r\n leftText = SCORE_FONT.render(str(leftScore),False,WHITE)\r\n rightText = SCORE_FONT.render(str(rightScore),False,WHITE)\r\n lLength = leftText.get_width()\r\n rLength = rightText.get_width()\r\n WIN.blit(leftText, (300 - lLength/2,210))\r\n WIN.blit(rightText, (600 - rLength/2,210))\r\n WIN.blit(leftPlayerText,(300 - lNameLength/2, 50) )\r\n WIN.blit(rightPlayerText, (600 - rNameLength/2, 50))\r\n pygame.display.update()\r\n\r\n\r\ndef play(leftPlayer,rightPlayer):\r\n start_count()\r\n leftScore = 0\r\n rightScore = 0\r\n run = True\r\n while run:\r\n clock.tick(FPS)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n pygame.quit()\r\n sys.exit()\r\n \r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_RCTRL:\r\n rightScore += 1\r\n \r\n if event.key == pygame.K_LCTRL:\r\n leftScore += 1\r\n \r\n \r\n draw_window_play(leftScore, rightScore,leftPlayer, rightPlayer)\r\n\r\ndef main():\r\n leftPlayer = 'a'\r\n rightPlayer = 'b'\r\n play(leftPlayer, rightPlayer)\r\n \r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()" } ]
1
Covid-Analytics/covidanalytics.org
https://github.com/Covid-Analytics/covidanalytics.org
6c768bfd3566506f40d09fa7993570a153d2b7e5
8c76113a0f6cfabb033aee3de83c6ae12d8872ba
5cb9bd3cf99b9af3213ee905145718e8d1c70e7a
refs/heads/master
2023-07-21T17:47:31.938737
2021-04-01T08:24:03
2021-04-01T08:24:03
250,098,085
0
2
null
2020-03-25T21:43:33
2021-04-01T08:24:09
2023-07-06T22:37:42
JavaScript
[ { "alpha_fraction": 0.6352128982543945, "alphanum_fraction": 0.6444188952445984, "avg_line_length": 23.828571319580078, "blob_id": "9f3397dbcd708037564711d7d9af9b330816c625", "content_id": "923bcfa8fc3417134679d1c36027d2649a0e4b81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 869, "license_type": "no_license", "max_line_length": 64, "num_lines": 35, "path": "/website/frontend/src/data/NotebookViewer.js", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "import React from \"react\";\n\nimport GridItem from \"../components/Grid/GridItem\";\nimport GridContainer from \"../components/Grid/GridContainer\";\n\nimport {dashRoutes, getActiveRoute} from \"../routes\";\nimport {makeStyles} from \"@material-ui/core/styles\";\n\nconst useStyles = makeStyles({\n iframe: {\n width: '100%',\n height: '82vh',\n border: 'none',\n borderBottom: '1px solid #CCC',\n },\n});\n\nexport default function NotebookViewer() {\n const classes = useStyles();\n\n // find the HREF to the notebook\n const route = getActiveRoute(dashRoutes);\n if (!route || !route.hasOwnProperty('nb_href')) return <div/>;\n let nb_src = route['nb_href'];\n if (!nb_src.startsWith('/'))\n nb_src = '/' + nb_src;\n\n return (\n <GridContainer>\n <GridItem xs={12}>\n <iframe src={nb_src} className={classes.iframe}/>\n </GridItem>\n </GridContainer>\n )\n}\n" }, { "alpha_fraction": 0.5943496227264404, "alphanum_fraction": 0.5989221930503845, "avg_line_length": 35.233726501464844, "blob_id": "49603f683dc8ed1883c5eb417f12c7a761c0dbd5", "content_id": "676afefb2ed5790410da67fb4d551565f8a6995e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12247, "license_type": "no_license", "max_line_length": 122, "num_lines": 338, "path": "/website/backend-converter/convert-ipynb.py", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "# This script pre-processes a bunch of notebooks generating all of the figures, and then creates\n# a bundle of pics and html ready for frontend compiling into our react UI.\n\nimport glob\nimport json\nimport os\nimport nbformat\nimport pandas\nimport random\nfrom datetime import datetime, timedelta, timezone\nfrom jinja2 import DictLoader\nfrom nbconvert import HTMLExporter\nfrom nbconvert.preprocessors import ExecutePreprocessor, ClearOutputPreprocessor\nfrom traitlets.config import Config\n\n# Configuration (shall have a command line, one day)\nNOTEBOOK_PATHS = ['.', './input', '../../analysis']\nOUTPUT_FOLDER = 'output'\nFRONTEND_GLUE_FILE = 'DataGlue.js'\nFIGURES_META_FILE = 'meta-figures.csv'\nNOTEBOOKS_META_FILE = 'meta-notebooks.csv'\nPYTHON_EXTRA_PATHS = ['/app/input', '../../../../analysis']\n\n# This is the inline'd template\nstand_alone_tpl = \"\"\"\n{%- extends 'full.tpl' -%}\n\n{% block input_group %}\n {%- if cell.metadata.get('nbconvert', {}).get('show_code', False) -%}\n{{ super() }}\n {%- endif -%}\n{% endblock input_group %}\n\n{% block html_head %}\n{{ super() }}\n<!-- customize looks -->\n<style type=\"text/css\">\n body {\n background: transparent;\n padding: 0\n }\n div#notebook-container{\n padding: 2ex 4ex 2ex 4ex;\n }\n div.output_subarea {\n max-width: initial;\n }\n .rendered_html table {\n width: 100%;\n }\n</style>\n{% endblock html_head %}\n\"\"\"\nreact_glue_tpl = \"\"\"\n{%- extends 'basic.tpl' -%}\n\n{%- block header -%}\nmodule.exports = function(props) {\n return (\n{%- endblock header -%}\n\n{% block body %}\n {{ super() }}\n{%- endblock body %}\n\n{% block footer %}\n );\n};\n{% endblock footer %}\n\"\"\"\n\n\ndef current_utc_time():\n # whether to compensate for the build time - so that the UTC refresh date is now + X minutes\n compensate_build_time = 2\n return (datetime.now(timezone.utc) + timedelta(minutes=compensate_build_time)).strftime('%Y-%m-%dT%H:%M:%SZ')\n\n\ndef input_file_to_folder(basename):\n return basename.lower().replace(' ', '_').replace('.', '_')\n\n\ndef scan_for_notebooks(paths_list):\n print(\"Finding notebooks in: \" + str(paths_list))\n nb_list = []\n for probe_dir in paths_list:\n for nb_file_name in glob.glob(probe_dir + '/*.ipynb'):\n file_path = os.path.normpath(nb_file_name)\n file_basename = os.path.splitext(os.path.basename(file_path))[0]\n nb_list.append({\n 'input': file_path,\n 'basename': input_file_to_folder(file_basename),\n })\n print(\" - found \" + str(len(nb_list)) + \" notebooks:\" + str(nb_list))\n return nb_list\n\n\ndef convert_notebook_to_assets(notebook_file_name, base_name, output_prefix):\n # define and create output folder\n output_folder = output_prefix + '/' + base_name\n os.makedirs(output_folder, exist_ok=True)\n\n # open file\n print('Converting Notebook: ' + notebook_file_name + ' ...')\n nb_file = open(notebook_file_name, 'r').read()\n nb = nbformat.reads(nb_file, as_version=4)\n\n # 1. clear output\n print(\" - clearing output\")\n ep = ClearOutputPreprocessor()\n ep.preprocess(nb, {})\n\n # 2. generate fresh charts by running the notebook\n print(\" - executing\")\n ep = ExecutePreprocessor(timeout=600, kernel_name='python3', allow_errors=False)\n try:\n ep.preprocess(nb, {'metadata': {'path': output_folder}})\n except Exception as e:\n print('ERROR: Execution of the notebook ' + notebook_file_name + ' stopped, likely for missing some py libs.')\n print(' Please check the output/exception and add those to the requirements.')\n print(e)\n exit(1)\n\n # 3. export HTML\n print(\" - generating html\")\n cleaner_config = Config({\n \"HTMLExporter\": {\n \"exclude_input\": True,\n \"exclude_input_prompt\": True,\n \"exclude_output_prompt\": True,\n \"preprocessors\": ['nbconvert.preprocessors.ExtractOutputPreprocessor']\n },\n })\n local_templates = DictLoader({\n 'our-html.tpl': stand_alone_tpl,\n 'react-glue.tpl': react_glue_tpl,\n })\n exporter = HTMLExporter(config=cleaner_config, extra_loaders=[local_templates])\n exporter.template_file = 'our-html.tpl'\n (html_body, html_resources) = exporter.from_notebook_node(nb)\n notebook_convert_time = current_utc_time()\n\n # save html output file, with local reference to the pictures\n local_html = []\n output_html_file_name = output_folder + '/' + \"index.html\"\n print(\" - saving html: \" + output_html_file_name)\n with open(output_html_file_name, 'wt') as the_file:\n the_file.write(html_body)\n local_html.append({\n 'notebook': base_name,\n 'notebook_html': output_html_file_name,\n 'convert_time': notebook_convert_time,\n })\n\n # save js file for react inclusion (local ref to the pictures)\n # exporter.template_file = 'react-glue.tpl'\n # (react_body, react_resources) = exporter.from_notebook_node(nb)\n # output_react_file_name = output_folder + '/' + \"index.js\"\n # print(\" - saving react js: \" + output_react_file_name)\n # with open(output_react_file_name, 'wt') as the_file:\n # the_file.write(react_body)\n\n # save all the figures\n local_figures = []\n figures = html_resources['outputs']\n figures_count = len(figures)\n figure_index = 1\n for figure_file in figures:\n output_figure_file_name = output_folder + '/' + figure_file\n print(\" - saving png \" + str(figure_index) + \" of \" + str(figures_count) + \": \" + output_figure_file_name)\n if not figure_file.endswith('.png'):\n print(\"WARNING: figure is not a PNG file\")\n continue\n with open(output_figure_file_name, 'wb') as the_file:\n the_file.write(figures[figure_file])\n local_figures.append({\n 'figure': figure_file,\n 'file': output_figure_file_name,\n 'notebook': base_name,\n 'notebook_html': output_html_file_name,\n 'convert_time': notebook_convert_time,\n })\n\n # create an empty 'custom.css'\n custom_css_file_name = output_folder + '/' + 'custom.css'\n with open(custom_css_file_name, 'wt') as the_file:\n the_file.write(\"\")\n\n # return a recap of all assets\n return local_html, local_figures\n\n\nglue_frontend_template = \"\"\"// MACHINE GENERATED CODE, by convert-ipynb.py\nimport React from \"react\";\nimport {EmbeddedChart} from \"./EmbeddedChart\";\n\n// List the EmbeddedChart(s)\nexport const ChartsGlue = [\n%COMPONENTS%\n];\n\n// List the Notebooks\nexport const NotebooksGlue = [\n%NOTEBOOKS%\n];\n\n// Metadata\nexport const MetaDataGlue = {\n%METADATA%\n};\n\"\"\"\n\n\ndef write_assets_loader(pages, figures, output_prefix, frontend_glue_file_name):\n fig_count = len(figures)\n print('Generating Fronted Glue JS for ' + str(fig_count) + ' Figures ...')\n\n # begin loading Meta info about the figures - this is to compensate for the lack of information transfer between\n # the notebooks and the Glue. To compensate, manual editing is needed, and we use a simple CSV file here\n df_figures = pandas.read_csv(FIGURES_META_FILE, sep=',').fillna('')\n\n # Figures: generate JS statements for every figure\n frontend_components = []\n fig_index = 0\n df_warning_silencer = False\n for figure in figures:\n fig_index = fig_index + 1\n\n # figure: conversion parameters\n fig_id = figure['figure']\n fig_file = figure['file']\n notebook_id = figure['notebook']\n fig_updated = figure['convert_time']\n\n # figure: relative URL of the PNG (/public folder referencing in React) - example: '/covid19_world/output_5_0.png'\n fig_img_src = \"/\" + fig_file.replace(output_prefix + '/', '')\n\n # figure: metadata: default values - to NEVER show(!)\n fig_title = fig_id\n fig_short = \"short commentary\"\n fig_scopes = \",\".join([scope for scope in ['global', 'us', 'italy'] if random.random() < 0.3])\n fig_tags = \",\".join([scope for scope in ['mortality', 'cases', 'trends'] if random.random() < 0.3])\n fig_priority = fig_index\n fig_highlight = 1 if random.random() < 0.3 else ''\n fig_hide = random.random() < 0.9\n\n # figure: metadata: replace with editorial values from the local 'CSV' database\n df = df_figures\n df = df[df['notebook_id'] == notebook_id]\n df = df[df['figure_id'] == fig_id]\n if len(df) != 1:\n if not df_warning_silencer:\n print(\" WARNING: the following are missing metadata in \" + FIGURES_META_FILE)\n df_warning_silencer = True\n print(notebook_id + \",\" + fig_id + \",,,,,,,\")\n else:\n fig_title = str(df['title'].iloc[0])\n fig_short = df['commentary'].iloc[0]\n fig_scopes = df['scopes'].iloc[0]\n fig_tags = df['tags'].iloc[0]\n fig_priority = int(df['priority'].iloc[0]) if df['priority'].iloc[0] else 99\n fig_highlight = df['highlight'].iloc[0]\n fig_hide = df['hide'].iloc[0]\n\n # append one component (only if not hidden)\n if not fig_hide:\n frontend_components.append(\n '{src: \"' + fig_img_src + '\"' +\n ', title: \"' + fig_title + '\"' +\n ', short: \"' + fig_short + '\"' +\n ', notebook_id: \"' + notebook_id + '\"' +\n ', scopes: ' + json.dumps(fig_scopes.split(',') if fig_scopes else []) + '' +\n ', tags: ' + json.dumps(fig_tags.split(',') if fig_tags else []) + '' +\n ', priority: ' + str(int(fig_priority)) + '' +\n ', highlight: ' + ('true' if fig_highlight else 'false') + '' +\n ', updated: \"' + fig_updated + '\"' +\n '},')\n\n # Notebooks\n df_notebooks = pandas.read_csv(NOTEBOOKS_META_FILE, sep=',').fillna('')\n page_data = []\n for page in pages:\n page_name = page['notebook']\n page_title = page_name.replace('_', ' ').title()\n page_file = page['notebook_html'].replace(output_prefix + '/', '')\n page_updated = page['convert_time']\n\n # default meta options\n page_priority = len(page_data)\n\n # get extra options from the Meta\n df = df_notebooks\n df = df[df['notebook_id'] == page_name]\n if len(df) != 1:\n print(\" WARNING: the following are missing metadata in \" + FIGURES_META_FILE)\n print(page_name + \",\")\n else:\n page_priority = int(df['priority'].iloc[0]) if df['priority'].iloc[0] else 99\n\n # append one JSON descriptor\n page_def = '{id: \"' + page_name + '\"' + \\\n ', title: \"' + page_title + '\"' + \\\n ', href: \"/' + page_file + '\"' + \\\n ', priority: ' + str(int(page_priority)) + '' + \\\n ', updated: \"' + page_updated + '\"' + \\\n '},'\n page_data.append(page_def)\n\n # Metadata\n meta_strings = [\"convert_iso8601: '\" + current_utc_time() + \"',\"]\n\n # write the JS file\n glue_string = glue_frontend_template \\\n .replace('%COMPONENTS%', \"\\n\".join([\" \" + fc for fc in frontend_components])) \\\n .replace('%NOTEBOOKS%', \"\\n\".join([\" \" + pd for pd in page_data])) \\\n .replace('%METADATA%', \"\\n\".join([\" \" + ms for ms in meta_strings]))\n\n output_frontend_glue_name = output_prefix + '/' + frontend_glue_file_name\n print(\" - saving frontend glue JS: \" + output_frontend_glue_name)\n with open(output_frontend_glue_name, 'wt') as the_file:\n the_file.write(glue_string)\n\n\n# Main\nos.makedirs(OUTPUT_FOLDER, exist_ok=True)\n# make sure the modules loaded by the notebook can be found in a relative-to-the-notebook search path\nif 'PYTHONPATH' not in os.environ: os.environ['PYTHONPATH'] = ''\nos.environ[\"PYTHONPATH\"] += (os.pathsep if os.environ['PYTHONPATH'] else '') + os.pathsep.join(PYTHON_EXTRA_PATHS)\nnotebooks = scan_for_notebooks(NOTEBOOK_PATHS)\nall_pages = []\nall_figures = []\nfor task in notebooks:\n nb_html, nb_figures = convert_notebook_to_assets(task['input'], task['basename'], OUTPUT_FOLDER)\n all_pages.extend(nb_html)\n all_figures.extend(nb_figures)\nwrite_assets_loader(all_pages, all_figures, OUTPUT_FOLDER, FRONTEND_GLUE_FILE)\n\nprint(\"done.\")\n" }, { "alpha_fraction": 0.6439473628997803, "alphanum_fraction": 0.6489473581314087, "avg_line_length": 29.89430809020996, "blob_id": "230e77e4c3335cb1051b3af8478e0c1b96c0682f", "content_id": "2d412671b29bcbeebd5013c41480b8cffd569bd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3800, "license_type": "no_license", "max_line_length": 90, "num_lines": 123, "path": "/website/frontend/src/layouts/SimpleLayout.js", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "import React from \"react\";\n\nimport {Switch, Redirect, useLocation} from \"react-router-dom\";\nimport cx from \"classnames\";\n\nimport GoogleAnalytics from \"react-ga\";\n\n// import PerfectScrollbar from \"perfect-scrollbar\";\n// import \"perfect-scrollbar/css/perfect-scrollbar.css\";\n\n// @material-ui/core components\nimport {makeStyles} from \"@material-ui/core/styles\";\n\nimport SimpleNavbar from \"components/Navbars/SimpleNavbar.js\";\nimport Footer from \"components/Footer/Footer.js\";\nimport SimpleSidebar from \"components/Sidebar/SimpleSidebar.js\";\n\nimport {dashRoutes, getRoutesForLayout, getActiveRouteTitle} from \"routes.js\";\n\nimport styles from \"assets/jss/material-dashboard-pro-react/layouts/adminStyle.js\";\n\n// style={{ backgroundImage: \"url(\" + getBgImage() + \")\" }}\n\n// let ps; // perfect scrollbar\n\n// Analytics\nGoogleAnalytics.initialize('UA-65634159-7', {debug: false});\n\nfunction Analytics() {\n const location = useLocation();\n React.useEffect(() => {\n GoogleAnalytics.pageview(window.location.pathname + window.location.search);\n }, [location]);\n return <React.Fragment/>\n}\n\nconst useStyles = makeStyles(styles);\n\nexport default function SimpleLayout(props) {\n const {...rest} = props;\n // states and functions\n // noinspection JSUnusedLocalSymbols\n const location = useLocation();\n const [mobileOpen, setMobileOpen] = React.useState(false);\n const [miniActive, setMiniActive] = React.useState(false);\n const [image] = React.useState(undefined /*require(\"assets/img/sidebar-image-2.jpg\")*/);\n const [color] = React.useState(\"rose\");\n const [bgColor] = React.useState(\"white\");\n // styles\n const classes = useStyles();\n const mainPanelClasses =\n classes.mainPanel +\n \" \" +\n cx({\n [classes.mainPanelSidebarMini]: miniActive,\n // [classes.mainPanelWithPerfectScrollbar]:\n // navigator.platform.indexOf(\"Win\") > -1\n });\n\n // ref for main panel div\n const mainPanel = React.createRef();\n\n React.useEffect(() => {\n const resizeFunction = () => {\n if (window.innerWidth >= 960)\n setMobileOpen(false);\n };\n /*if (navigator.platform.indexOf(\"Win\") > -1) {\n ps = new PerfectScrollbar(mainPanel.current, {\n suppressScrollX: true,\n suppressScrollY: false\n });\n document.body.style.overflow = \"hidden\";\n }*/\n window.addEventListener(\"resize\", resizeFunction);\n\n // Specify how to clean up after this effect:\n return function cleanup() {\n /*if (navigator.platform.indexOf(\"Win\") > -1) {\n ps.destroy();\n }*/\n window.removeEventListener(\"resize\", resizeFunction);\n };\n }, []);\n // functions for changing the states from components\n const handleDrawerToggle = () => setMobileOpen(!mobileOpen);\n const handleSidebarMinimize = () => setMiniActive(!miniActive);\n return (\n <div className={classes.wrapper}>\n <Analytics/>\n <SimpleSidebar\n routes={dashRoutes}\n logoText={\"Covid-19 Live\"}\n // logo={logo}\n image={image}\n handleDrawerToggle={handleDrawerToggle}\n open={mobileOpen}\n color={color}\n bgColor={bgColor}\n miniActive={miniActive}\n {...rest}\n />\n <div className={mainPanelClasses} ref={mainPanel}>\n <SimpleNavbar\n sidebarMinimize={handleSidebarMinimize.bind(this)}\n miniActive={miniActive}\n brandText={getActiveRouteTitle(dashRoutes)}\n handleDrawerToggle={handleDrawerToggle}\n {...rest}\n />\n <div className={classes.content}>\n <div className={classes.container}>\n <Switch>\n {getRoutesForLayout(dashRoutes, '')}\n <Redirect from=\"/\" to={dashRoutes[0].path}/>\n </Switch>\n </div>\n </div>\n <Footer fluid/>\n </div>\n </div>\n );\n}\n" }, { "alpha_fraction": 0.6440466046333313, "alphanum_fraction": 0.6469608545303345, "avg_line_length": 39.71186447143555, "blob_id": "84e1361122f3f73b6cd492c702c0ecb8b591ed2a", "content_id": "e7270a92d3a2b33a2df5fd88af332f29bb9d723a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2450, "license_type": "no_license", "max_line_length": 119, "num_lines": 59, "path": "/website/frontend/src/data/DataUtils.js", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "import React from \"react\";\n\n// const us_flag = require(\"assets/img/flags/US.png\");\n// const it_flag = require(\"assets/img/flags/IT.png\");\n// const kr_flag = require(\"assets/img/flags/KR.png\");\n// const cn_flag = require(\"assets/img/flags/CN.png\");\n// const in_flag = require(\"assets/img/flags/IN.png\");\n// const br_flag = require(\"assets/img/flags/BR.png\");\n\nexport function notebookIdToTitle(notebookId) {\n if (notebookId === \"covid19_world\") return \"World Analysis\";\n if (notebookId === \"us_data\") return \"United States Analysis\";\n if (notebookId === \"italy_analysis\") return \"Italy Analysis\";\n if (notebookId === \"predictions\") return \"Modeling\";\n return \"Others\";\n}\n\nexport function notebookIdToShort(notebookId) {\n if (notebookId === \"covid19_world\") return \"World\";\n if (notebookId === \"us_data\") return \"United States\";\n if (notebookId === \"italy_analysis\") return \"Italy\";\n if (notebookId === \"predictions\") return \"Modeling\";\n return \"Others\";\n}\n\nexport function notebookIdGateMessage(notebookId) {\n if (notebookId === \"predictions\") return \"I understand the following are simple fits of the Confirmed Cases and \" +\n \"Deaths to logistic curves. Multiple factors make reality more complex, but this is a first order approximation \" +\n \"that offers a common ground for idiosyncratic behaviors.\";\n return \"\";\n}\n\n/*export function scope2flag(scopeId) {\n if (scopeId === \"us\") return <img src={us_flag} alt=\"USA\" key={scopeId}/>;\n if (scopeId === \"it\") return <img src={it_flag} alt=\"Italy\" key={scopeId}/>;\n if (scopeId === \"kr\") return <img src={kr_flag} alt=\"South Korea\" key={scopeId}/>;\n if (scopeId === \"cn\") return <img src={cn_flag} alt=\"China\" key={scopeId}/>;\n if (scopeId === \"in\") return <img src={in_flag} alt=\"India\" key={scopeId}/>;\n if (scopeId === \"br\") return <img src={br_flag} alt=\"Brazil\" key={scopeId}/>;\n return scopeId;\n}*/\n\nexport function scope2emoji(scopeId) {\n if (scopeId === \"us\") return \"🇺🇸\";\n if (scopeId === \"it\") return \"🇮🇹\";\n if (scopeId === \"kr\") return \"🇰🇷\";\n if (scopeId === \"cn\") return \"🇨🇳\";\n if (scopeId === \"in\") return \"🇮🇳\";\n if (scopeId === \"br\") return \"🇧🇷\";\n return scopeId;\n}\n\nexport function tag2emoji(tagId, skipName = false) {\n if (tagId === 'cases') return '🌡';\n if (tagId === 'deaths') return '💀';\n if (tagId === 'forecast') return '📈';\n if (tagId === 'hospital') return '🏥';\n return skipName ? '' : tagId;\n}\n" }, { "alpha_fraction": 0.571865439414978, "alphanum_fraction": 0.7094801068305969, "avg_line_length": 18.235294342041016, "blob_id": "2d49bd7295345fdf97d9026bfe2e06d41c4c5db6", "content_id": "3861e1902fe54519e01bc1ff19c65ff1770dd78c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 327, "license_type": "no_license", "max_line_length": 31, "num_lines": 17, "path": "/website/backend-converter/requirements.txt", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "# for the script\nnbformat==5.1.2\nnbconvert==5.6.1\njinja2==2.11.3\n# for execution of the notebook\njupyter_client==6.1.12\nipykernel==5.5.3\n# used inside the notebooks\nmatplotlib==3.4.1\npandas==1.1.5\nnumpy==1.20.2\n# forward looking\nscipy==1.6.2\n#scikit-learn==0.22.2.post1\n#Pillow==\n#scikit-image==0.16.2\n#opencv-python==4.2.0.32\n" }, { "alpha_fraction": 0.5657364130020142, "alphanum_fraction": 0.574447512626648, "avg_line_length": 33.248619079589844, "blob_id": "64b32fdeb64645aeb0717b8b8f31480c8dfdf79d", "content_id": "d2c49e9ecedb2ea00e38c10e56048a5a66144bbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6199, "license_type": "no_license", "max_line_length": 112, "num_lines": 181, "path": "/website/frontend/src/data/EmbeddedChartContainer.js", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport Checkbox from \"@material-ui/core/Checkbox\";\nimport FormControlLabel from \"@material-ui/core/FormControlLabel\";\nimport MuiLink from \"@material-ui/core/Link\";\nimport Button from \"components/CustomButtons/Button\";\nimport GridContainer from \"components/Grid/GridContainer\";\nimport GridItem from \"components/Grid/GridItem\";\n\nimport {ChartsGlue} from \"./DataGlue\"\nimport {EmbeddedChart} from \"./EmbeddedChart\";\nimport {notebookIdGateMessage, notebookIdToShort, notebookIdToTitle, scope2emoji, tag2emoji} from \"./DataUtils\";\n\n/**\n * This component is here to provide Gating (checkbox) capability.\n */\nfunction ChartGroup({name, notebookId, charts, onViewImage}) {\n const [gateChecked, setGateChecked] = React.useState(false);\n const gatingMessage = notebookIdGateMessage(notebookId);\n const isGated = gatingMessage.length > 0;\n const showCharts = !isGated || gateChecked;\n return (\n <React.Fragment>\n {isGated && <GridItem xs={12}>\n <h5>Click on the following to see the logistic charts.</h5>\n <FormControlLabel\n control={\n <Checkbox\n checked={gateChecked}\n disabled={false}\n color=\"primary\"\n onChange={e => setGateChecked(e.target.checked)}/>}\n label={gatingMessage}\n style={{color: '#888'}}/>\n </GridItem>}\n {showCharts && charts.map(chart => (\n <GridItem xs={12} sm={12} md={6} lg={4} xl={3} key={chart.src}>\n <EmbeddedChart chart={chart} onViewImage={onViewImage}/>\n </GridItem>\n ))}\n </React.Fragment>\n )\n}\n\n\nexport function EmbeddedChartContainer(props) {\n const {onViewImage} = props;\n const [activeScope, setActiveScope] = React.useState('global');\n const [activeTags, setActiveTags] = React.useState([]);\n const toggleTag = (tagId) => {\n if (activeTags.includes(tagId))\n setActiveTags(activeTags.filter(tag => tag !== tagId));\n else\n setActiveTags(activeTags.concat(tagId));\n };\n const smoothScrollTo = (event, selector) => {\n event.preventDefault();\n document.querySelector(selector).scrollIntoView({behavior: 'smooth'});\n };\n\n // find all scopes\n const allScopes = ['global'].concat(ChartsGlue.reduce((acc, chart) => {\n chart.scopes.forEach(tag => {\n if (!acc.includes(tag)) acc.push(tag);\n });\n return acc;\n }, []).sort());\n const showScopes = false;\n\n // find all tags\n const allTags = ChartsGlue.reduce((acc, chart) => {\n chart.tags.forEach(tag => {\n if (!acc.includes(tag)) acc.push(tag);\n });\n return acc;\n }, []).sort();\n\n // charts to display\n let charts = ChartsGlue;\n\n // sort by chart priority\n charts = charts.sort((a, b) => a.priority - b.priority);\n\n // limit scope, if not 'global'\n if (activeScope !== 'global')\n charts = charts.filter(chart => chart.scopes.includes(activeScope));\n\n // limit tags, if not empty\n if (activeTags.length)\n charts = charts.filter(chart => {\n for (const chartTag of chart.tags)\n if (activeTags.includes(chartTag))\n return true;\n return false;\n });\n\n // group by Notebook\n const chartGroups = [];\n charts.forEach(chart => {\n const notebookId = chart.notebook_id;\n let group = chartGroups.find(g => g.notebookId === notebookId);\n if (!group) {\n group = {\n name: notebookIdToTitle(notebookId),\n short: notebookIdToShort(notebookId),\n notebookId: notebookId,\n charts: [],\n };\n chartGroups.push(group);\n }\n group.charts.push(chart);\n });\n\n return (\n <React.Fragment>\n {/* Header: section selector, ...filters */}\n <GridContainer id=\"charts-top\">\n <GridItem xs={12} sm={6} style={{marginTop: 'auto', marginBottom: 'auto'}}>\n <h6 style={{display: 'inline', marginRight: '1.1em'}}>Section:&nbsp;</h6>\n {chartGroups.map((group, idx) =>\n <span key={group.notebookId}>\n <MuiLink href={'#' + group.notebookId}\n onClick={(e) => smoothScrollTo(e, '#' + group.notebookId)}>\n {group.short}\n </MuiLink>\n {idx === chartGroups.length - 1 ? '.' : ', '}\n </span>)}\n </GridItem>\n\n {/* Scopes: exclusive selector */}\n {showScopes && <GridItem xs={12} sm={6}>\n <h6 style={{display: 'inline', marginRight: '1em'}}>Scope:</h6>\n {allScopes.map(scopeId =>\n <Button color={activeScope === scopeId ? \"rose\" : undefined}\n onClick={() => setActiveScope(scopeId)}\n size=\"sm\" round\n key={scopeId}>\n {scope2emoji(scopeId)}\n </Button>)}\n </GridItem>}\n {/* Tags: any can be active */}\n <GridItem xs={12} sm={6}>\n <h6 style={{display: 'inline', marginRight: '1.1em'}}>Filter:&nbsp;&nbsp;&nbsp;&nbsp;</h6>\n {allTags.map(tagId =>\n <Button color={activeTags.includes(tagId) ? \"primary\" : undefined}\n onClick={() => toggleTag(tagId)}\n size=\"sm\" round key={tagId}>\n {tag2emoji(tagId)}\n </Button>)}\n </GridItem>\n {/* Spacer for Desktop versions */}\n <GridItem xs={12}>\n &nbsp;\n </GridItem>\n </GridContainer>\n\n {/* Chart Groups (by Notebook basically) */}\n {chartGroups.map((chartGroup, groupIdx) =>\n <GridContainer key={chartGroup.notebookId} id={chartGroup.notebookId}>\n <GridItem xs={12}>\n <h3>\n {chartGroup.name}\n {groupIdx > 0 && <MuiLink href={'#'} style={{float: 'right'}}\n onClick={e => smoothScrollTo(e, '#charts-top')}>\n &#94;\n </MuiLink>}\n </h3>\n </GridItem>\n <ChartGroup {...chartGroup} onViewImage={onViewImage}/>\n </GridContainer>)}\n\n {/* Missing Charts */}\n {charts.length === 0 && <GridContainer>\n <GridItem sm={12}>\n <h4 style={{textAlign: 'center'}}>\n There are no charts matching the filter criteria.\n </h4>\n </GridItem>\n </GridContainer>}\n </React.Fragment>\n );\n}\n" }, { "alpha_fraction": 0.631309449672699, "alphanum_fraction": 0.631309449672699, "avg_line_length": 31.164705276489258, "blob_id": "3316bb8213727df3ce6462192836c4c0452c3980", "content_id": "eef446f4aa99f6d8d213bea41df9d3013f0456e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2734, "license_type": "no_license", "max_line_length": 92, "num_lines": 85, "path": "/website/frontend/src/components/Navbars/SimpleNavbar.js", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "import React from \"react\";\n// nodejs library to set properties for components\nimport PropTypes from \"prop-types\";\nimport cx from \"classnames\";\n\n// @material-ui/core components\nimport {makeStyles} from \"@material-ui/core/styles\";\nimport AppBar from \"@material-ui/core/AppBar\";\nimport Toolbar from \"@material-ui/core/Toolbar\";\nimport Hidden from \"@material-ui/core/Hidden\";\n\n// material-ui icons\nimport Menu from \"@material-ui/icons/Menu\";\nimport MoreVert from \"@material-ui/icons/MoreVert\";\nimport ViewList from \"@material-ui/icons/ViewList\";\n\n// core components\n// import SimpleNavbarLinks from \"./SimpleNavbarLinks\";\nimport Button from \"components/CustomButtons/Button.js\";\n\nimport styles from \"assets/jss/material-dashboard-pro-react/components/adminNavbarStyle.js\";\nimport SimpleNavbarLinks from \"./SimpleNavbarLinks\";\n\nconst useStyles = makeStyles(styles);\n\nexport default function SimpleNavbar(props) {\n const classes = useStyles();\n const {color, brandText, miniActive} = props;\n const appBarClasses = cx({\n [\" \" + classes[color]]: color\n });\n return (\n <AppBar className={classes.appBar + appBarClasses}>\n <Toolbar className={classes.container}>\n {/* Toggle to minimize the side bar */}\n <Hidden smDown implementation=\"css\">\n <div className={classes.sidebarMinimize}>\n {miniActive ? (\n <Button justIcon round color=\"white\" onClick={props.sidebarMinimize}>\n <ViewList className={classes.sidebarMiniIcon}/>\n </Button>\n ) : (\n <Button justIcon round color=\"white\" onClick={props.sidebarMinimize}>\n <MoreVert className={classes.sidebarMiniIcon}/>\n </Button>\n )}\n </div>\n </Hidden>\n\n {/* Brand text*/}\n <div className={classes.flex}>\n <Button href=\"#\" className={classes.title} color=\"transparent\">\n {brandText}\n </Button>\n </div>\n\n {/* Links (none here) */}\n <Hidden smDown implementation=\"css\">\n <SimpleNavbarLinks/>\n </Hidden>\n\n {/* Mobile: Drawer toggle on the right side */}\n <Hidden mdUp implementation=\"css\">\n <Button\n className={classes.appResponsive}\n color=\"transparent\"\n justIcon\n aria-label=\"open drawer\"\n onClick={props.handleDrawerToggle}\n >\n <Menu/>\n </Button>\n </Hidden>\n </Toolbar>\n </AppBar>\n );\n}\n\nSimpleNavbar.propTypes = {\n color: PropTypes.oneOf([\"primary\", \"info\", \"success\", \"warning\", \"danger\"]),\n brandText: PropTypes.string,\n miniActive: PropTypes.bool,\n handleDrawerToggle: PropTypes.func,\n sidebarMinimize: PropTypes.func\n};\n" }, { "alpha_fraction": 0.7478813529014587, "alphanum_fraction": 0.75, "avg_line_length": 38.33333206176758, "blob_id": "4db2c0598130b2f79af64aa82be282382d95e6cc", "content_id": "3e281a02a34e45fcc05754aa0e9afef0a5e8d54c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 472, "license_type": "no_license", "max_line_length": 101, "num_lines": 12, "path": "/website/conf-nginx/install-nginx-site.sh", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# First manual setup: generation of the SSH keys for the domain.\n# The following has been executed manually.\n# certbot certonly --nginx --expand -d www.covidanalytics.org -d covidanalytics.org\n\n# copy the frontend configuration (note: this requires the SSH certs to be present, as per the above)\nSCRIPT_DIR=`dirname \"$(readlink -f \"$0\")\"`\nln -nsf \"$SCRIPT_DIR/nginx-site-covidanalytics.conf\" /etc/nginx/sites-enabled/\n\n# restart nginx\nservice nginx restart\n" }, { "alpha_fraction": 0.7247087955474854, "alphanum_fraction": 0.7277743816375732, "avg_line_length": 41.3636360168457, "blob_id": "dfefc002c46026de51bc248d0d55bf4a052e33df", "content_id": "627215f6bd9e424a060a6e6b8d983267e6e0ae1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3262, "license_type": "no_license", "max_line_length": 133, "num_lines": 77, "path": "/website/build-website.sh", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# change this to specify where this application will be served from\n# it not in a parameter yet for risk management\nINSTALL_DIR=\"/srv/org.covidanalytics/static\"\nLOCAL_CONVERTER_OUTPUT=\"out_converter\"\nLOCAL_CONVERTER_LOG=\"$LOCAL_CONVERTER_OUTPUT\"/coverter.out.html\nLOCAL_FRONTEND_OUTPUT=\"out_frontend\"\n\n# == CONVERTER ==\n\n# build the container to statically compile the notebooks to html\ndocker build . -f Dockerfile.converter --tag=covana-converter\n\n# perform the conversion (instanciate the container, copy files, excute script, copy back output) - 1 minute\n# NOTE: to inspect the image at any state: docker exec -it $CONV_CONTAINER /bin/bash\necho \"> Start Notebooks Converter container\"\nCONV_CONTAINER=$(docker run --rm -d -t covana-converter:latest /bin/bash)\n\necho \"> Copying notebooks and helpers from '../analysis' to the container 'input/' folder\"\nfor NOTEBOOK in ../analysis/*.ipynb; do docker cp \"$NOTEBOOK\" \"$CONV_CONTAINER\":/app/input/; done\nfor HELPER in ../analysis/*.py; do docker cp \"$HELPER\" \"$CONV_CONTAINER\":/app/input/; done\n\necho \"> Converting Notebooks (and copying the output to $LOCAL_CONVERTER_OUTPUT)...\"\nrm -fr \"$LOCAL_CONVERTER_OUTPUT\"\nmkdir -p \"$LOCAL_CONVERTER_OUTPUT\"\necho \"<html><body><pre>\" >> \"$LOCAL_CONVERTER_LOG\"\ntime docker exec -t \"$CONV_CONTAINER\" python3 /app/convert-ipynb.py |& tee \"$LOCAL_CONVERTER_LOG\"\ndocker cp \"$CONV_CONTAINER\":/app/output/. \"$LOCAL_CONVERTER_OUTPUT\"\necho -n Optimizing images...\nfind \"$LOCAL_CONVERTER_OUTPUT\" -name '*.png' -exec optipng {} \\; > /dev/null 2> /dev/null\necho done.\necho \"</pre></body></html>\" >> \"$LOCAL_CONVERTER_LOG\"\n\necho -n \"> Removing container... \"\ndocker kill \"$CONV_CONTAINER\" > /dev/null\necho \"done.\"\n\n# Check if the build was successful before continuing\n[ ! -f \"$LOCAL_CONVERTER_OUTPUT/DataGlue.js\" ] && echo \"Build ERROR: $LOCAL_CONVERTER_OUTPUT/DataGlue.js missing. Exiting.\" && exit 1\n\n# == Frontend ==\n\n# build the container\ndocker build . -f Dockerfile.frontend --tag=covana-frontend\n\n# perform the frontend compilation - 2 minutes\necho \"> Start Frontend compiler container\"\nFRONTEND_CONTAINER=$(docker run --rm -d -t covana-frontend:latest /bin/bash)\n\necho \"> Copying GLUE files (site already in the image)...\"\n# copy to the public wesbite, for serving the Notebook folders (index.html + pictures)\ndocker cp \"$LOCAL_CONVERTER_OUTPUT/.\" \"$FRONTEND_CONTAINER\":/app/public/\n# copy to the data folder, for glueing up with the Frontend (by replacing this single file)\ndocker cp \"$LOCAL_CONVERTER_OUTPUT/DataGlue.js\" \"$FRONTEND_CONTAINER\":/app/src/data/\n\necho \"> Compiling Frontend (and copying the output to $LOCAL_FRONTEND_OUTPUT)...\"\nrm -fr \"$LOCAL_FRONTEND_OUTPUT\"\ntime docker exec -t \"$FRONTEND_CONTAINER\" npm run build\ndocker cp \"$FRONTEND_CONTAINER\":/app/build/. \"$LOCAL_FRONTEND_OUTPUT\"\n\necho -n \"> Removing container... \"\ndocker kill \"$FRONTEND_CONTAINER\" > /dev/null\necho \"done.\"\n\n# Install the new contents\nrm -fr \"$INSTALL_DIR\"/precache* \"$INSTALL_DIR\"/static/\ncp -a \"$LOCAL_FRONTEND_OUTPUT\"/* \"$INSTALL_DIR\"\nrm -f \"$INSTALL_DIR\"/DataGlue.js \"$INSTALL_DIR\"/service-worker.js\n\n\n# == Cleanup ==\necho -n \"> Cleaning up docker images... \"\n# shellcheck disable=SC2046\ndocker rmi $(docker image ls -f dangling=true -q) 2> /dev/null\necho \"done.\"\necho\n" }, { "alpha_fraction": 0.747086226940155, "alphanum_fraction": 0.748251736164093, "avg_line_length": 34.75, "blob_id": "dd57cf3d036c0f3c1ff6fbc5d9b76ff9ca712838", "content_id": "55f645722773cdfd2f818a4c2ee62b72d71f9007", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 858, "license_type": "no_license", "max_line_length": 103, "num_lines": 24, "path": "/website/Readme.md", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "## /website folder\nThis folder contains the frontend of the website, as well as the backend machinery\nand server-side configuation.\n\nMore TBA later.\n\n## Building the backend\nUsing a Docker container to encapsulate the \"static building\" of notebooks into HMTL files.\n\nThe command we'll run need to have the full repo as build context, so we'll converge to something like:\n\n ```docker build ../../ -f Dockerfile --tag=covana-backend-compiler```\n\nTo test the container:\n\n ```docker run --rm -it covana-backend-compiler /bin/bash```\n\n## Continuous update of the Analyses\nUse this simple script that operates ever 2 minutes and:\n* pulls the latest repo from github\n* compiles the notebooks to html\n* (not done yet) updates the frontend - for now it only replaces /index.html with the last notebook\n\nRun ```continuous-update-loop.sh``` on a ```tmux``` instance.\n" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6319444179534912, "avg_line_length": 13.399999618530273, "blob_id": "40db9181ca5f84f74a3b2fc24cb3f34afdee2afc", "content_id": "779063c2c3ae99d1905e43b483a2c29679ddfa6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 144, "license_type": "no_license", "max_line_length": 46, "num_lines": 10, "path": "/website/build-continuous-loop.sh", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nwhile /bin/true; do\n echo \"[$(date)] Running - Next update in 2h\"\n git pull\n echo\n ./build-website.sh\n sleep 30m;\n echo\ndone\n" }, { "alpha_fraction": 0.6494076251983643, "alphanum_fraction": 0.6516015529632568, "avg_line_length": 24.606740951538086, "blob_id": "4696e07e9222edffb1e3af0c85f8c965b41a319d", "content_id": "7d1abc16f11e919af1db1247bdfb34078628ddbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2279, "license_type": "no_license", "max_line_length": 82, "num_lines": 89, "path": "/website/frontend/src/routes.js", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport {Route} from \"react-router-dom\";\n\nimport SimpleDashboard from \"views/SimpleDashboard.js\";\n\n\n// @material-ui/icons\nimport DashboardIcon from \"@material-ui/icons/Dashboard\";\nimport NotesIcon from '@material-ui/icons/Notes';\n\n// Other\nimport NotebookViewer from \"data/NotebookViewer\";\nimport {NotebooksGlue} from \"data/DataGlue\";\n\nconst dashRoutes = [\n // Enrico mod\n {\n path: '/charts',\n name: \"Live Charts\",\n icon: DashboardIcon,\n component: SimpleDashboard,\n layout: \"\"\n },\n {\n is_notebooks_container: true,\n collapse: true,\n name: \"Analyses\",\n icon: NotesIcon,\n state: \"analysesCollapse\",\n views: [],\n layout: \"\",\n },\n];\n\nfunction addNotebooksRoutes(notebooksRoutes, notebooksGlue) {\n notebooksGlue.forEach(notebook => {\n const id = notebook.id;\n const href = notebook.href;\n const title = notebook.title;\n const mini = title.split(' ').map(s => s[0] || \"\").join('').slice(0, 2);\n notebooksRoutes.views.push({\n path: \"/notebook/\" + id,\n name: title,\n mini: mini,\n component: NotebookViewer,\n layout: \"\",\n // notebook-specific route data\n nb_id: id,\n nb_href: href,\n })\n })\n}\n\n// add the Notebooks from the Glue data\naddNotebooksRoutes(dashRoutes.find(r => r.is_notebooks_container), NotebooksGlue);\n\n\nfunction getRoutesForLayout(routes, base_layout = '') {\n return routes.map((r, idx) => {\n if (r.collapse)\n return getRoutesForLayout(r.views, base_layout);\n if (r.layout === base_layout)\n return <Route path={r.layout + r.path} component={r.component} key={idx}/>;\n else\n return null;\n });\n}\n\nfunction getActiveRoute(routes) {\n for (let i = 0; i < routes.length; i++) {\n if (routes[i].collapse) {\n const collapseActiveRoute = getActiveRoute(routes[i].views);\n if (collapseActiveRoute !== null)\n return collapseActiveRoute;\n } else {\n if (window.location.href.indexOf(routes[i].layout + routes[i].path) !== -1)\n return routes[i];\n }\n }\n return null;\n}\n\nfunction getActiveRouteTitle(routes) {\n const route = getActiveRoute(routes);\n if (route) return route.name;\n return \"Route Title Not Set\";\n}\n\nexport {dashRoutes, getRoutesForLayout, getActiveRouteTitle, getActiveRoute};\n" }, { "alpha_fraction": 0.6100829839706421, "alphanum_fraction": 0.6209317445755005, "avg_line_length": 32.10563278198242, "blob_id": "d4819862bfda127cf00f7563ab67f60d69d527e4", "content_id": "b4316410300fc208da8f36b09b320d888f3e49d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4701, "license_type": "no_license", "max_line_length": 116, "num_lines": 142, "path": "/website/frontend/src/data/EmbeddedChart.js", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport Card from \"../components/Card/Card\";\nimport CardHeader from \"../components/Card/CardHeader\";\nimport CardBody from \"../components/Card/CardBody\";\nimport CardFooter from \"../components/Card/CardFooter\";\nimport Hidden from \"@material-ui/core/Hidden\";\nimport AccessTime from \"@material-ui/icons/AccessTime\";\nimport LibraryBooksIcon from '@material-ui/icons/LibraryBooks';\nimport TimelineIcon from '@material-ui/icons/Timeline';\nimport Tooltip from \"@material-ui/core/Tooltip\";\nimport {makeStyles} from \"@material-ui/core/styles\";\n\nimport TimeAgo from 'react-timeago'\n\nimport {cardTitle, tooltip, successColor} from \"assets/jss/material-dashboard-pro-react\";\nimport dashboardStyle from \"assets/jss/material-dashboard-pro-react/views/dashboardStyle.js\";\nimport hoverCardStyle from \"assets/jss/material-dashboard-pro-react/hoverCardStyle.js\";\nimport GridContainer from \"../components/Grid/GridContainer\";\nimport GridItem from \"../components/Grid/GridItem\";\nimport Button from \"../components/CustomButtons/Button\";\n\nimport {scope2emoji, tag2emoji} from \"./DataUtils\";\n\nconst embeddedChartStyles = {\n ...hoverCardStyle,\n tooltip,\n cardTitle: {\n ...cardTitle,\n marginTop: \"0px\",\n marginBottom: \"3px\"\n },\n cardHover: {\n \"&:hover\": {\n \"& $cardHeaderHover\": {\n transform: \"translate3d(0, -40px, 0)\"\n }\n }\n },\n cardHeaderHover: {\n ...hoverCardStyle.cardHeaderHover,\n zIndex: 5, // make sure the header covers the buttons underneath\n },\n cardHoverUnder: {\n ...hoverCardStyle.cardHoverUnder,\n top: '-40px',\n },\n underButton: {\n padding: '6px 30px',\n },\n cardImagePreview: {\n width: '100%',\n },\n successText: {\n color: successColor[0]\n },\n cardCategory: {\n ...dashboardStyle.cardCategory,\n },\n // cardCategoryArrow: {\n // width: 14,\n // height: 14\n // },\n cardStats: {\n ...dashboardStyle.stats,\n },\n};\nconst useStyles = makeStyles(embeddedChartStyles);\n\n// Example from DataGlue.js\n// const chart = {\n// src: \"/placeholder.png\",\n// title: \"Chart\",\n// short: \"short comment\",\n// notebook_id: \"covid19_world\",\n// scopes: [\"us\", \"it\"],\n// tags: [\"deaths\"],\n// highlight: false,\n// priority: 2,\n// updated: \"2020-04-01T17:52:13Z\"\n// };\n\nexport function EmbeddedChart(props) {\n const {chart, onViewImage} = props;\n const classes = useStyles();\n\n // unpack chart attributes\n const {src, title, short, notebook_id, scopes, tags, /*highlight,*/ /*priority,*/ updated} = chart;\n const img_src = process.env.PUBLIC_URL + src;\n const route_notebook = \"/notebook/\" + notebook_id;\n\n const handleImageClick = (e) => {\n e.preventDefault();\n onViewImage(img_src);\n };\n return (\n <Card chart className={classes.cardHover}>\n <CardHeader color=\"rose\" className={classes.cardHeaderHover} style={{padding: 6, background: 'white'}}>\n <a href={route_notebook} onClick={e => handleImageClick(e)}>\n <img src={img_src} alt={title} className={classes.cardImagePreview}/>\n </a>\n </CardHeader>\n <CardBody>\n <Hidden smDown implementation=\"css\">\n <div className={classes.cardHoverUnder}>\n <Tooltip id=\"tooltip-top\" title=\"View Chart\" placement=\"bottom\" classes={{tooltip: classes.tooltip}}>\n <Button color=\"rose\" simple onClick={e => handleImageClick(e)} className={classes.underButton}>\n <TimelineIcon/>\n </Button>\n </Tooltip>\n <Tooltip id=\"tooltip-top\" title=\"View Notebook\" placement=\"bottom\" classes={{tooltip: classes.tooltip}}>\n <Button color=\"rose\" simple href={route_notebook} className={classes.underButton}>\n <LibraryBooksIcon/>\n </Button>\n </Tooltip>\n </div>\n </Hidden>\n <GridContainer>\n <GridItem xs={9}>\n <h4 className={classes.cardTitle}>\n <a href={route_notebook}>{title}</a>\n </h4>\n </GridItem>\n <GridItem xs={3} style={{textAlign: 'right'}}>\n {tags.map(tagId => <span key={tagId}>{tag2emoji(tagId, true)}</span>)}\n {scopes.map(scope => scope2emoji(scope))}\n </GridItem>\n <GridItem xs={12}>\n <p className={classes.cardCategory}>\n {/*<span className={classes.successText}>*/}\n {/* <ArrowUpward className={classes.cardCategoryArrow}/> 55%*/}\n {/*</span>{\" \"}*/}\n {short}\n </p>\n </GridItem>\n </GridContainer>\n </CardBody>\n <CardFooter chart>\n <div className={classes.cardStats}><AccessTime/> {<TimeAgo date={updated}/>}.</div>\n </CardFooter>\n </Card>\n );\n}\n" }, { "alpha_fraction": 0.7917675375938416, "alphanum_fraction": 0.7917675375938416, "avg_line_length": 40.29999923706055, "blob_id": "b8454aee26035235dc36d829d1a1417c47f19787", "content_id": "ed0030ba8aa4ac005ebc7df23db3b7048990f40d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 413, "license_type": "no_license", "max_line_length": 82, "num_lines": 10, "path": "/analysis/Readme.md", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "## Analysis folder\nIn this folder we will structure the editorial and analytical part of the website.\n\nThe proposal is to have python notebooks that can analyze live data.\n\nEvery notebook should produce one Chart, and the chart will then be mapped and\nblended with the rest of the UI of the website.\n\nUpon change of the underlying data, or of a notebook, or of the UI, the whole\nwebsite is rebuilt and redeployed\n" }, { "alpha_fraction": 0.5548062920570374, "alphanum_fraction": 0.5669219493865967, "avg_line_length": 47.07143020629883, "blob_id": "a70b9e4d41c06029dd6be8d2e093e6a7b18a8c94", "content_id": "de93bbd1a63804d4870a2da1265162b8be8fb93f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8749, "license_type": "no_license", "max_line_length": 124, "num_lines": 182, "path": "/analysis/eplotter.py", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "# Utility functions to plot data frames\nfrom datetime import datetime\n\nfrom matplotlib.dates import WeekdayLocator, FR\nfrom matplotlib.ticker import MultipleLocator, ScalarFormatter\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# noinspection PyDefaultArgument\ndef scatter_plot_by_series(_df,\n x_key, y_key, # [data] keys (column names for X's and Y's)\n series_key, # [series] the series key (column) in the df\n series_names=None, # [series] the ranked names to use; defaults to col.unique()\n series_is_secondary=None, # [series] function: True -> gray line\n series_secondary_width=None, # [series] the width of the line, if secondary\n shift_x_to_intersect_y=None, # [transform] translate Series to intersect a point\n y_filter=None, # [transform] filter the y values. valid: 'expo'\n y_log=False, # [axis] make the Y axis logarithmic\n bounds=[None, None, None, None], # [axis] x_min, x_max, y_min, y_max\n legend_off=False, # [legend] disable if True\n legend_decimals=0, # [legend] how many decimals\n legend_suffix=None, # [legend] whether to append a suffix (e.g. '%')\n data_labels=None, # [data labels] text: legend, series, value\n data_labels_align=\"center\", # [data labels] align to: left, right, center\n line_style_non_first_series=None, # [style] line style: solid, dashed, dashdot, dotted, ' '\n title=None, title_align='left', label_x=None, label_y=None, stamp_1=None, stamp_2=None):\n # label the plot\n plt.rc('font', size=14)\n fig = plt.figure(figsize=(14, 10))\n fig.patch.set_facecolor('white')\n plt.title(title if title else \"'\" + y_key + \"' over '\" + x_key + \"', by '\" + series_key + \"'\", loc=title_align)\n if not label_x:\n label_x = x_key\n if shift_x_to_intersect_y:\n label_x = label_x + \" since crossing \" + str(shift_x_to_intersect_y)\n plt.xlabel(label_x)\n if label_y: plt.ylabel(label_y)\n # if not stamp_1: stamp_1 = \"\"\n if not stamp_2: stamp_2 = \"\" + datetime.now().strftime(\"%Y-%m-%d (%H:%M UTC)\")\n\n # if the series values are missing, enumerate them all\n if series_names is None:\n series_names = _df[series_key].unique()\n\n # add the lines for all the 'countries to chart'\n all_x = []\n all_y = []\n is_first_series = True\n for series_name in series_names:\n # [select rows] get the data of a single series (e.g. a country)\n df = _df[_df[series_key] == series_name]\n\n # [cleanup] remove metric <= 0 , as they don't play well with log\n if y_log: df = df[df[y_key] > 0]\n\n # [cleanup] remove NaNs\n df = df[df[y_key].notna()]\n\n # skip empty series\n if df.empty: continue\n\n # if requested, compute a per-series X translation to a set 'y' level\n x_translation = 0\n if shift_x_to_intersect_y:\n exceeding = df[df[y_key] >= shift_x_to_intersect_y]\n if len(exceeding) == 0:\n continue\n x_translation = -exceeding.iloc[0][x_key]\n\n # checks if this element should be grayed out\n secondary = series_is_secondary(df) if series_is_secondary else False\n\n # text of the label (and shorten 'USA')\n series_name = series_name if series_name != \"United States of America\" else \"USA\"\n metric_label = round(df[y_key].iloc[-1], legend_decimals)\n if legend_decimals == 0: metric_label = metric_label.astype(int)\n legend_label = series_name + \" \" + str(format(metric_label, ',')) + (legend_suffix if legend_suffix else \"\")\n if secondary: legend_label = None\n\n # format the color and size\n line_color = (0.5, 0.5, 0.5, 0.2) if secondary else None\n line_style = 'solid' if ((not line_style_non_first_series) or is_first_series) else line_style_non_first_series\n line_width = 2.4\n if secondary and series_secondary_width: line_width = series_secondary_width\n\n # add the series data\n x = (df[x_key] + x_translation).tolist()\n y = df[y_key].tolist()\n y_plotted = y\n if y_filter == 'expo': y_plotted = df[y_key].rolling(window=(7, 20), win_type='exponential').mean(tau=20)\n if y_filter == 'sma3': y_plotted = df[y_key].rolling(window=3).mean()\n if y_filter == 'sma7': y_plotted = df[y_key].rolling(window=7).mean()\n if y_filter == 'sma30': y_plotted = df[y_key].rolling(window=30).mean()\n plt.plot(x, y_plotted, label=legend_label, color=line_color, linewidth=line_width, linestyle=line_style)\n # plt.plot(x, y, color=(0.8, 0.8, 0.8, 0.4), linewidth=1)\n # plt.scatter(x, y, color=line_color, linewidth=1, alpha=1)\n\n # add the data label on the endpoint\n if data_labels and not secondary:\n point_label = None\n if data_labels == \"series\":\n point_label = series_name\n elif data_labels == \"value\":\n point_label = str(metric_label)\n if data_labels == \"legend\":\n point_label = legend_label\n # PATCH: remove the label for China in the second chart, or it will be scaled down\n if shift_x_to_intersect_y and series_name == \"China\": point_label = None\n if point_label:\n plt.annotate(point_label,\n (x[-1], y[-1]), # this is the point to label\n textcoords=\"offset points\", # how to position the text\n xytext=(0, 2), # distance from text to points (x,y)\n annotation_clip=False, # draw over the chart, to spot issues\n ha=data_labels_align) # horizontal alignment can be left, right or center\n # for auto bounds\n all_x.extend(x)\n all_y.extend(y)\n # not the first series anymore\n is_first_series = False\n\n # X/Y axes: set-up ranges and scale type\n # boundaries = [left, right, min_y, max_y] <- automatic if any is set to None\n if not bounds: bounds = [None, None, None, None]\n auto_bounds = [min(all_x), max(all_x), np.floor(min(all_y)), np.ceil(max(all_y))]\n bounds = list(map(lambda pair: pair[0] if pair[0] is not None else pair[1], zip(bounds, auto_bounds)))\n if shift_x_to_intersect_y:\n bounds[0] = 0\n bounds[1] = bounds[1] - 10 # magic number, shall remove\n bounds[2] = shift_x_to_intersect_y\n if y_log:\n plt.yscale('log')\n formatter = ScalarFormatter(useOffset=False)\n formatter.set_powerlimits((-3, 10))\n plt.gca().yaxis.set_major_formatter(formatter)\n bounds[3] = 2 * bounds[3]\n plt.xlim(bounds[0], bounds[1])\n plt.ylim(bounds[2], bounds[3])\n\n # add grid\n plt.gca().grid(axis='both', color=(0.4, 0.4, 0.4), alpha=0.2)\n\n # set x grid to 'weekly'\n if shift_x_to_intersect_y:\n x_locator = MultipleLocator(base=7.0)\n else:\n x_locator = WeekdayLocator(byweekday=FR)\n plt.gca().xaxis.set_major_locator(x_locator)\n\n # add legend\n if not legend_off:\n plt.legend()\n\n # add any decorative text boxes\n if stamp_1:\n plt.text(1, 1, stamp_1, transform=plt.gca().transAxes, alpha=0.5,\n horizontalalignment='right', verticalalignment='bottom')\n if stamp_2:\n plt.text(1, -0.046, stamp_2, transform=plt.gca().transAxes, alpha=0.5,\n horizontalalignment='right', verticalalignment='top')\n\n # display it\n plt.show()\n\n\ndef rank_data_by_metric(df, metric, unique_key, unique_pick='last', df_filter=None, rank_highest=True, max_results=None):\n # [pick latest] for data set with exploded unique keys (for days, for example), select the most relevant frame\n df = df.drop_duplicates(unique_key, keep=unique_pick)\n\n # [select rows] remove empty data on the metric itself\n df = df[df[metric].notna()]\n\n # [select rows] .. more filtering?\n if df_filter: df = df_filter(df) # e.g. (lambda df: df[df['Population'] > 1E+06])\n\n # [sort] by the metric, descending\n df = df.sort_values(metric, ascending=(False if rank_highest else True))\n\n # [reduce] keep the top N results\n if max_results: df = df.head(max_results)\n return df\n" }, { "alpha_fraction": 0.6325399279594421, "alphanum_fraction": 0.647458553314209, "avg_line_length": 58.870452880859375, "blob_id": "9b148ba0c5a3a18e790ad6b8b5317979bce071c1", "content_id": "1769a38ccffb6f9175d4b76282c30aa5da94bca5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26343, "license_type": "no_license", "max_line_length": 643, "num_lines": 440, "path": "/analysis/eloader.py", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "# Utility functions to load the latest Covid-19 data sets\n# - see the main function for how to use this\n#\nfrom datetime import datetime, timedelta, timezone\nimport dateutil.parser as du_parser\nimport pandas as pd\nimport numpy as np\n\nCANONICAL_COLS = ['Date', 'X', 'CountryCode', 'CountryName', 'RegionCode', 'RegionName', 'Confirmed', 'Negative', 'Infectious', 'Deaths', 'Recovered', 'Hospitalized', 'Tampons', 'PeopleTested', 'Population', 'dConfirmed', 'dNegative', 'dInfectious', 'dDeaths', 'dRecovered', 'dHospitalized', 'dTampons', 'dPeopleTested', 'Death_rate', 'dateChecked']\nDATE_FORMAT = '%Y-%m-%d'\n\n# MISC functions\nreference_day = datetime(2020, 1, 1)\n\n\ndef current_day_of_year():\n return date_to_day_of_year(datetime.now())\n\n\ndef date_to_day_of_year(date):\n return (date - reference_day).days + 1\n\n\ndef day_of_year_to_date(day_of_year):\n return reference_day + timedelta(days=(day_of_year - 1))\n\n\ndef filter_rows_remove_equals(df, column_name, column_value, reason):\n print('Removing data where ', column_name, ' is ', column_value, ' because:', reason)\n return df[df[column_name] != column_value]\n\n\ndef cleanup_canonical(df, warning_prefix='', drop_na_columns=True):\n # check if some columns are not in the canonical list\n extra_canonical_cols = list(set(df.columns) - set(CANONICAL_COLS))\n extra_canonical_cols.sort()\n if extra_canonical_cols:\n print(warning_prefix + ': non-canonical cols: ' + ', '.join(extra_canonical_cols) + '. (Dropped)')\n\n # select canonical cols: excess columns are discarded, missing columns are NaN\n df = df.reindex(columns=CANONICAL_COLS)\n\n # remove empty columns\n if drop_na_columns:\n df = df.dropna(axis=1, how='all')\n\n # use integers where appropriate\n df = df.astype({'X': int})\n return df\n\n\n# def split_column_into_posneg(df, col_name, pos_neg_names=['Positives', 'Negatives']):\n# df_col = df[col_name]\n# # columns: create 2 extra columns with the values\n# df_pos_neg = pd.concat([df_col[df_col >= 0], df_col[df_col < 0]], axis=1)\n# df_pos_neg.columns = pos_neg_names\n# return pd.concat([df, df_pos_neg], axis=1)\n\n\n# def label_by_value(df, value_col, label_col, label_fn):\n# df[label_col] = df[value_col].apply(label_fn)\n\n\ndef load_csv(filename: str, keep_cols_map: list or dict, drop_cols: list):\n df = pd.read_csv(filename)\n original_cols = set(df.columns)\n\n # check if: 1. the data has something extra, 2. the data is missing something we expect\n keep_cols = keep_cols_map if type(keep_cols_map) is list else list(keep_cols_map)\n new_data = original_cols - set(keep_cols + drop_cols)\n if new_data: print(filename + \": data has extra columns: '\" + \"','\".join(new_data) + \"'\")\n missing_needed = set(keep_cols) - original_cols\n if missing_needed: print(filename + \": missing NEEDED columns: '\" + \"','\".join(missing_needed) + \"'\")\n missing_ignored = set(drop_cols) - original_cols\n if missing_ignored: print(filename + \": missing former Ignored columns: '\" + \"','\".join(missing_ignored) + \"'\")\n\n # safe drop (if a column doesn't exist anymore, don't break)\n df = df.drop(columns=original_cols.intersection(drop_cols))\n\n # safe reorder + add leftovers. if a column doesn't exist anymore, don't break - although you will have missing data (warned about it already)\n final_columns = [col for col in keep_cols if col in df.columns] + list(new_data)\n df = df.loc[:, final_columns]\n\n # rename columns, if the 'keep' variable is really a dictionary (it if was a list, skip this)\n if type(keep_cols_map) is dict:\n df = df.rename(columns=keep_cols_map, errors=\"raise\")\n return df\n\n\ndef post_process_entries(info_file_name: str, df: pd.DataFrame, set_cols_map: dict = None, df_regions=None):\n # set columns, if requested\n if set_cols_map:\n for item in set_cols_map.items():\n if item[0] in df.columns:\n print('W: requested to set \"' + item[0] + '\", but column is already present. Skipping.')\n else:\n df[item[0]] = item[1]\n\n # join RegionName(s) if we only have the RegionCode and a set to join\n if (df_regions is not None) and ('RegionCode' in df.columns):\n df_joined = df.join(df_regions.set_index('RegionCode'), on='RegionCode', how='left')\n if 'RegionName' not in df.columns:\n df['RegionName'] = df_joined['RegionName']\n if 'Population' not in df.columns:\n df['Population'] = df_joined['Population']\n\n # TODO: add Population (regional, national) so we can have these stats\n if 'Population' not in df.columns:\n # HACK: set US data sets which miss 'Population' to a constant here\n if 'CountryName' in df.columns and 'RegionCode' not in df.columns:\n # NOTE: this number comes from the OpenCovid-19 data set - here a constant; TODO: merge it dynamically\n population_value = None\n if df['CountryName'].all() == 'United States of America':\n population_value = 329064917\n if population_value:\n # print(filename + ': hack: setting ' + df['CountryName'].any() + ' population to ' + str(population_value))\n df['Population'] = population_value\n\n # add other canonical values: 'X' and 'Death_rate'\n df['X'] = df['Date'].map(lambda d: date_to_day_of_year(datetime.strptime(d, DATE_FORMAT)))\n if ('Confirmed' in df.columns) and ('Deaths' in df.columns):\n df['Death_rate'] = 100 * df['Deaths'] / df['Confirmed']\n\n # more ratios\n # df['Confirmed_pct'] = 100 * df['Confirmed'] / df['Population']\n # df['Deaths_pct'] = 100 * df['Deaths'] / df['Population']\n\n # add the current date if the data didn't contain it\n if 'dateChecked' not in df.columns:\n df['dateChecked'] = datetime.now(timezone.utc).strftime(DATE_FORMAT + 'T%H:%M:%SZ')\n\n # cleanup (reorder columns and drop full na's)\n return cleanup_canonical(df, info_file_name)\n\n\n# https://covidtracking.com/\ndef load_covidtracking_us_data():\n loc_states_population = \"https://raw.githubusercontent.com/Covid-Analytics/covidanalytics.org/master/analysis/us-states-population-2019.csv\"\n loc_states_info = \"https://covidtracking.com/api/states/info.csv\"\n loc_states_daily = \"https://covidtracking.com/api/states/daily.csv\"\n loc_states_latest = \"https://covidtracking.com/api/states.csv\" # BARELY USEFUL\n loc_us_daily = \"https://covidtracking.com/api/us/daily.csv\"\n\n def post_process_covidtracking(filename, df, df_regions):\n # reverse list, so newer entries are at the bottom\n df = df.reindex(index=df.index[::-1])\n # compute the 'Infections' := Confirmed - Recovered - df['Deaths'], and the daily diff\n df['Infectious'] = df['Confirmed'] - df['Recovered'] - df['Deaths']\n # note: doesn't work with non-uniform daily data: df['dInfectious'] = df['Infectious'].diff(periods=1)\n return post_process_entries(filename, df,\n set_cols_map={'CountryCode': 'US', 'CountryName': 'United States of America'},\n df_regions=df_regions)\n\n # US states Information: useful to join the region name (CA -> California)\n def load_us_regions_info():\n df_population = pd.read_csv(loc_states_population)\n # NOTE: fix an issue where the DoC has a capital 'O'\n df_population['StateName'].replace('District Of Columbia', 'District of Columbia', inplace=True)\n df = load_csv(loc_states_info,\n keep_cols_map={'state': 'RegionCode', 'name': 'RegionName'},\n drop_cols=['covid19SiteTertiary', 'covid19SiteSecondary', 'twitter', 'covid19Site', 'covid19SiteOld', 'fips', 'pui', 'pum', 'notes'])\n df['Population'] = df.join(df_population.set_index('StateName'), on='RegionName', how='left')['Population2019']\n return df\n\n # US aggregate, daily values\n # Date, X, CountryCode, CountryName, Confirmed, Negative, Infectious, Deaths, Recovered, Hospitalized, Tampons, dConfirmed, dNegative, dDeaths, dHospitalized, dTampons, Death_rate, dateChecked\n def load_us_daily(df_regions):\n df = load_csv(loc_us_daily,\n keep_cols_map={'date': 'Date', 'positive': 'Confirmed', 'negative': 'Negative', 'hospitalizedCurrently': 'Hospitalized', 'hospitalizedCumulative': 'HospitalizedTotal', 'inIcuCurrently': 'InICU', 'inIcuCumulative': 'InICUTotal', 'onVentilatorCurrently': 'OnVentilator', 'onVentilatorCumulative': 'OnVentilatorTotal', 'recovered': 'Recovered', 'death': 'Deaths', 'totalTestResults': 'Tampons', 'positiveIncrease': 'dConfirmed', 'negativeIncrease': 'dNegative', 'deathIncrease': 'dDeaths', 'totalTestResultsIncrease': 'dTampons', 'hospitalizedIncrease': 'dHospitalized', 'dateChecked': 'dateChecked'},\n drop_cols=['states', 'pending', 'hash', 'hospitalized', 'total', 'posNeg'])\n df['Date'] = df['Date'].astype(str).map(lambda d: d[:4] + '-' + d[4:6] + '-' + d[6:])\n return post_process_covidtracking(loc_us_daily, df, df_regions)\n\n # US states, daily values\n # Date, X, CountryCode, CountryName, RegionCode, RegionName, Confirmed, Negative, Infectious, Deaths, Recovered, Hospitalized, Tampons, dConfirmed, dNegative, dDeaths, dHospitalized, dTampons, Death_rate, dateChecked\n def load_us_regions_daily(df_regions):\n df = load_csv(loc_states_daily,\n keep_cols_map={'date': 'Date', 'state': 'RegionCode', 'positive': 'Confirmed', 'negative': 'Negative', 'hospitalizedCurrently': 'Hospitalized', 'hospitalizedCumulative': 'HospitalizedTotal', 'inIcuCurrently': 'InICU', 'inIcuCumulative': 'InICUTotal', 'onVentilatorCurrently': 'OnVentilator', 'onVentilatorCumulative': 'OnVentilatorTotal', 'recovered': 'Recovered', 'death': 'Deaths', 'totalTestResults': 'Tampons', 'positiveIncrease': 'dConfirmed', 'negativeIncrease': 'dNegative', 'deathIncrease': 'dDeaths', 'totalTestResultsIncrease': 'dTampons', 'hospitalizedIncrease': 'dHospitalized', 'dateChecked': 'dateChecked'},\n drop_cols=['pending', 'hash', 'hospitalized', 'total', 'posNeg', 'fips'])\n df['Date'] = df['Date'].astype(str).map(lambda d: d[:4] + '-' + d[4:6] + '-' + d[6:])\n return post_process_covidtracking(loc_states_daily, df, df_regions)\n\n # US states, latest values (Not very useful, as this is a subset (both rows and columns) of the daily values)\n # Date, X, CountryCode, CountryName, RegionCode, RegionName, Confirmed, Negative, Infectious, Deaths, Recovered, Hospitalized, Tampons, Death_rate, dateChecked\n def load_us_regions_latest(df_regions):\n df = load_csv(loc_states_latest,\n keep_cols_map={'dateModified': 'Date', 'state': 'RegionCode', 'positive': 'Confirmed', 'negative': 'Negative', 'hospitalizedCurrently': 'Hospitalized', 'hospitalizedCumulative': 'HospitalizedTotal', 'inIcuCurrently': 'InICU', 'inIcuCumulative': 'InICUTotal', 'onVentilatorCurrently': 'OnVentilator', 'onVentilatorCumulative': 'OnVentilatorTotal', 'recovered': 'Recovered', 'death': 'Deaths', 'totalTestResults': 'Tampons', 'dateChecked': 'dateChecked'},\n drop_cols=['pending', 'hash', 'hospitalized', 'total', 'posNeg', 'fips',\n 'positiveScore', 'negativeScore', 'negativeRegularScore', 'commercialScore', 'grade', 'score', 'checkTimeEt', 'lastUpdateEt', 'notes'])\n df['Date'] = df['Date'].map(lambda d: du_parser.parse(d.replace('T24', 'T00') if (type(d) == str) else datetime.now().isoformat()).strftime(DATE_FORMAT))\n return post_process_covidtracking(loc_states_latest, df, df_regions)\n\n # load the 4 APIs\n df_us_states_info = load_us_regions_info()\n df_daily = load_us_daily(df_us_states_info)\n df_states_daily = load_us_regions_daily(df_us_states_info)\n df_states_latest = load_us_regions_latest(df_us_states_info)\n return df_daily, df_states_daily, df_states_latest\n\n\n# https://github.com/pcm-dpc/COVID-19/\ndef load_pcmdpc_it_data():\n loc_it_daily = \"https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv\"\n loc_regional_daily = \"https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv\"\n\n it_region_names = ['Abruzzo', 'Basilicata', 'P.A. Bolzano', 'Calabria', 'Campania',\n 'Emilia-Romagna', 'Friuli Venezia Giulia', 'Lazio', 'Liguria',\n 'Lombardia', 'Marche', 'Molise', 'Piemonte', 'Puglia', 'Sardegna',\n 'Sicilia', 'Toscana', 'P.A. Trento', 'Umbria', \"Valle d'Aosta\",\n 'Veneto']\n it_regions_pop = [1311580, 562869, 531178, 1947131, 5801692, 4459477, 1215220,\n 5879082, 1550640, 10060574, 1525271, 305617, 4356406, 4029053,\n 1639591, 4999891, 3729641, 541098, 882015, 125666, 4905854]\n it_population = 60359546\n df_it_reg_pop = pd.DataFrame(data={'RegionName': it_region_names, 'Population': it_regions_pop})\n\n def post_process_pcmdpc(filename, df):\n df['dateModified'] = df['Date'].map(lambda d: d + 'Z')\n df['Date'] = df['Date'].str[0:10]\n if filename == loc_it_daily:\n df['Population'] = it_population\n elif filename == loc_regional_daily:\n df = df.join(df_it_reg_pop.set_index(['RegionName']), on=['RegionName'])\n # Extra: InICU, Infectious, dInfectious, dateModified\n # Relation: totale_casi (Confirmed/d) = totale_positivi (Infectious/d) + dimessi_guariti (Recovered) + deceduti (Deaths)\n # Relation: totale_ospedalizzati (not used) = ricoverati_con_sintomi (Hospitalized) + terapia_intensiva (InICU)\n return post_process_entries(filename, df,\n set_cols_map={'CountryCode': 'IT', 'CountryName': 'Italy'})\n\n # Italy country-wide, per day\n # Date, X, CountryCode, CountryName, Confirmed, Infectious, Deaths, Recovered, Hospitalized, Tampons, dConfirmed, dInfectious, Death_rate, dateChecked\n df_daily = post_process_pcmdpc(\n loc_it_daily,\n load_csv(loc_it_daily,\n keep_cols_map={'data': 'Date', 'ricoverati_con_sintomi': 'Hospitalized', 'terapia_intensiva': 'InICU', 'totale_positivi': 'Infectious', 'variazione_totale_positivi': 'dInfectious', 'nuovi_positivi': 'dConfirmed', 'dimessi_guariti': 'Recovered', 'deceduti': 'Deaths', 'totale_casi': 'Confirmed', 'tamponi': 'Tampons', 'casi_testati': 'PeopleTested'},\n drop_cols=['stato', 'totale_ospedalizzati', 'isolamento_domiciliare', 'note', 'casi_da_sospetto_diagnostico', 'casi_da_screening']))\n\n # Italy regional, latest\n # Date, X, CountryCode, CountryName, RegionCode, RegionName, Confirmed, Infectious, Deaths, Recovered, Hospitalized, Tampons, dConfirmed, dInfectious, Death_rate, dateChecked\n df_regional_daily = post_process_pcmdpc(\n loc_regional_daily,\n load_csv(loc_regional_daily,\n keep_cols_map={'data': 'Date', 'codice_regione': 'RegionCode', 'denominazione_regione': 'RegionName', 'ricoverati_con_sintomi': 'Hospitalized', 'terapia_intensiva': 'InICU', 'totale_positivi': 'Infectious', 'variazione_totale_positivi': 'dInfectious', 'nuovi_positivi': 'dConfirmed', 'dimessi_guariti': 'Recovered', 'deceduti': 'Deaths', 'totale_casi': 'Confirmed', 'tamponi': 'Tampons', 'casi_testati': 'PeopleTested'},\n drop_cols=['stato', 'lat', 'long', 'totale_ospedalizzati', 'isolamento_domiciliare', 'note', 'casi_da_sospetto_diagnostico', 'casi_da_screening']))\n\n return df_daily, df_regional_daily\n\n\n# https://github.com/open-covid-19 - OUTDATED - moved to Google\ndef load_opencovid19_data():\n # loc_outdated_regions_daily = 'https://open-covid-19.github.io/data/data.csv'\n loc_metadata = 'https://storage.googleapis.com/covid19-open-data/v2/index.csv'\n loc_demographics = 'https://storage.googleapis.com/covid19-open-data/v2/demographics.csv'\n loc_epidemiology_daily = 'https://storage.googleapis.com/covid19-open-data/v2/epidemiology.csv'\n\n # def apply_date_offset_to_country(df, country_code, days):\n # df_old_date = df.loc[(df['RegionCode'].isna()) & (df['CountryCode'] == country_code), 'Date']\n # df_new_date = df_old_date.map(lambda date: (datetime.strptime(date, DATE_FORMAT) + timedelta(days=days)).strftime(DATE_FORMAT))\n # df.update(df_new_date)\n\n # Countries by day\n # def load_regions_daily():\n # # Date, X, CountryCode, CountryName, RegionCode, RegionName, Confirmed, Deaths, Death_rate, dateChecked\n # df = load_csv(loc_outdated_regions_daily,\n # keep_cols_map=['Date', 'CountryCode', 'CountryName', 'RegionCode', 'RegionName', 'Confirmed', 'Deaths', 'Population'],\n # drop_cols=['Key', 'aggregation_level', 'Latitude', 'Longitude'])\n # # ES data is 1 day ahead of the pack, bring it back\n # apply_date_offset_to_country(df, country_code='ES', days=-1)\n # return post_process_entries(loc_outdated_regions_daily, df)\n\n # Load metadata, by Keys\n def load_metadata():\n # ocv_key,\tCountryCode, CountryName, RegionCode, RegionName\n df_meta = load_csv(loc_metadata, keep_cols_map={\n 'key': 'ocv_key',\n 'country_code': 'CountryCode',\n 'country_name': 'CountryName',\n 'subregion1_code': 'RegionCode',\n 'subregion1_name': 'RegionName',\n }, drop_cols=['wikidata', 'datacommons', 'subregion2_code', 'subregion2_name', 'locality_code', 'locality_name', '3166-1-alpha-2', '3166-1-alpha-3', 'aggregation_level'])\n\n # drop metadata for subregion_2s - as the 'CountryCode' + 'RegionCode' key is not unique\n df_meta = df_meta[df_meta['ocv_key'].str.count('_') < 2]\n\n # ocv_key, Population, PopulationMale, PopulationFemale, PopulationDensity, Population80\n df_population = load_csv(loc_demographics, keep_cols_map={\n 'key': 'ocv_key',\n 'population': 'Population',\n 'population_male': 'PopulationMale',\n 'population_female': 'PopulationFemale',\n 'population_density': 'PopulationDensity',\n 'population_age_80_and_older': 'Population80',\n }, drop_cols=['rural_population', 'urban_population', 'largest_city_population', 'clustered_population', 'human_development_index', 'population_age_00_09', 'population_age_10_19', 'population_age_20_29', 'population_age_30_39', 'population_age_40_49', 'population_age_50_59', 'population_age_60_69', 'population_age_70_79', 'population_age_80_89', 'population_age_90_99'])\n\n # ocv_key, CountryCode, CountryName, RegionCode, RegionName, Population, PopulationMale, PopulationFemale, PopulationDensity, Population80\n return df_meta.join(df_population.set_index('ocv_key'), on='ocv_key', how='left')\n\n # Countries by day\n def load_epidemiology_daily(df_meta: pd.DataFrame):\n # Date, X, CountryCode, CountryName, RegionCode, RegionName, Confirmed, Deaths, Death_rate, dateChecked\n df_daily = load_csv(loc_epidemiology_daily, keep_cols_map={\n 'key': 'ocv_key', 'date': 'Date', 'new_confirmed': 'dConfirmed', 'new_deceased': 'dDeaths', 'new_recovered': 'dRecovered', 'new_tested': 'dTampons',\n 'total_confirmed': 'Confirmed', 'total_deceased': 'Deaths', 'total_recovered': 'Recovered', 'total_tested': 'Tampons'\n }, drop_cols=[])\n\n # cleanup: null ocv_key (1/10000), null dConfirmed (1/1000) or Confirmed (1/20000) - total: 0.12% of data pts\n df_daily = df_daily[df_daily['ocv_key'].notna()]\n df_daily = df_daily[df_daily['dConfirmed'].notna()]\n df_daily = df_daily[df_daily['Confirmed'].notna()]\n\n # remove regions of 2nd level (> 1 underscore contained in the ocv_key) -- total: remove 92% of data\n # quantity: 3912316 rows (full), 314628 (region data, SELECTED), 80728 (country data) - at 350 days\n df_daily = df_daily[df_daily['ocv_key'].str.count('_') < 2]\n\n # +[CountryCode, CountryName, RegionCode, RegionName, Population, PopulationMale, PopulationFemale, PopulationDensity, Population80]\n df_daily = df_daily.join(df_meta.set_index('ocv_key'), on='ocv_key', how='left')\n\n # (new) Date, X, CountryCode, CountryName, RegionCode, RegionName, Confirmed, Deaths, Recovered, Tampons, Population, dConfirmed, dDeaths, dRecovered, dTampons, Death_rate, dateChecked\n # (prv) Date, X, CountryCode, CountryName, RegionCode, RegionName, Confirmed, Deaths, Population, Death_rate, dateChecked\n return post_process_entries(loc_epidemiology_daily, df_daily)\n\n # load the new version of the dataset (3 files, at least)\n df_metadata = load_metadata()\n df_epidemiology_daily = load_epidemiology_daily(df_metadata)\n return df_epidemiology_daily, df_metadata\n\n\n# https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data\n# FIPS, Admin2, Province_State, Country_Region, Last_Update, Lat, Long_, Confirmed, Deaths, Recovered, Active, Combined_Key\n# Issue: US and others are broken down, while Italy for example is whole\ndef load_latest_johnhopkins_daily():\n loc_jh_template = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/%m-%d-%Y.csv\"\n\n def find_latest_file_or_quit(url_template):\n tries = 3\n try_date_utc = datetime.utcnow()\n while True:\n # noinspection PyBroadException\n try:\n try_url = try_date_utc.strftime(url_template)\n pd.read_csv(try_url)\n return try_url, try_date_utc\n except:\n try_date_utc = try_date_utc - timedelta(days=1)\n tries = tries - 1\n if tries == 0:\n print(\"Out of tries looking for John Hopkins' data (walking back 1 day at a time)\")\n exit(1)\n\n # Basic world statistics, for the last day\n # Date, X, CountryName, RegionName, Confirmed, Infectious, Deaths, Recovered, Death_rate, dateChecked\n def load_last_day():\n loc_jh, date_jh = find_latest_file_or_quit(loc_jh_template)\n return post_process_entries(\n loc_jh,\n load_csv(loc_jh,\n keep_cols_map={'Admin2': 'City', 'Province_State': 'RegionName', 'Country_Region': 'CountryName', 'Lat': 'Latitude', 'Long_': 'Longitude', 'Confirmed': 'Confirmed', 'Deaths': 'Deaths', 'Recovered': 'Recovered', 'Active': 'Infectious'},\n drop_cols=['FIPS', 'Last_Update', 'Combined_Key']),\n set_cols_map={'Date': date_jh.strftime(DATE_FORMAT)})\n\n return load_last_day()\n\n\n# fuse data to get the latest-and-greatest\n# def fuse_sources(df_base: pd.DataFrame, df_replace_country: dict, drop_regions=True):\n# # remove Regional data, if requested\n# df = df_base\n# if drop_regions:\n# df = df[df['RegionCode'].isna()]\n# df = df.drop(columns=['RegionCode', 'RegionName'])\n#\n# # remove by CountryCode and then concatenate data\n# concat = []\n# for item in df_replace_country.items():\n# df = df[df['CountryCode'] != item[0]]\n# concat.append(item[1])\n# df = pd.concat([df] + concat, ignore_index=True)\n# return df\n\n\ndef fuse_daily_sources(df_world, df_us, df_it):\n # start from Country-wide world data from OpenCovid-19, removing regional data (only country data is left)\n df = df_world[df_world['RegionCode'].isna()]\n df = df.drop(columns=['RegionCode', 'RegionName'])\n\n # overwrite the latest US data from the Covid Tracking Project (US daily)\n # overwrite the latest IT data from the PCM-DPC italian source\n df = df[df['CountryCode'] != 'US'] # remove US data\n df = df[df['CountryCode'] != 'IT'] # remove IT data\n df = pd.concat([df, df_us, df_it], ignore_index=True) # add daily US and IT data\n return df\n\n\ndef add_canonical_differentials(df_src, daily_series_col='CountryName', order_column='Date'):\n print('Computing canonical differentials... ', end='')\n diff_cols = ['Confirmed', 'Negative', 'Infectious', 'Deaths', 'Recovered', 'Hospitalized', 'Tampons', 'PeopleTested']\n\n # select only country (not regional) data\n df_countries = df_src\n if daily_series_col == 'CountryName' and 'RegionCode' in df_countries.columns:\n df_countries = df_countries[df_countries['RegionCode'].isna()]\n\n # update each series x each differential\n for country_name in df_countries[daily_series_col].unique():\n df_country = df_countries[df_countries[daily_series_col] == country_name]\n df_country = df_country.sort_values(order_column)\n for src_col in diff_cols:\n diff_col = 'd' + src_col\n if src_col not in df_country.columns: continue\n if df_country[src_col].isna().all(): continue\n if diff_col in df_country.columns:\n if df_country[diff_col].notna().all(): continue\n # compute 'row_n - row_(n-1)'\n df_country[diff_col] = df_country[src_col].diff()\n # add the column to the source if missing (update won't do it)\n if diff_col not in df_src.columns:\n df_src[diff_col] = np.nan\n # merge the updated series data with the source\n df_src.update(df_country)\n print('done.')\n\n\ndef test_load_all():\n # load all\n (df_regions_daily, df_regions_population) = load_opencovid19_data()\n (df_it_daily, df_it_regional_daily) = load_pcmdpc_it_data()\n (df_us_daily, df_us_states_daily, df_us_states_latest) = load_covidtracking_us_data()\n (df_world_last_day) = load_latest_johnhopkins_daily()\n # test data manipulation\n df_countries_daily = fuse_daily_sources(df_regions_daily, df_us_daily, df_it_daily)\n add_canonical_differentials(df_countries_daily)\n df_countries_daily = cleanup_canonical(df_countries_daily)\n # print summary\n print('Loaded data summary:')\n for df in [df_regions_daily, df_world_last_day, df_it_daily, df_it_regional_daily, df_us_daily, df_us_states_daily, df_us_states_latest, df_countries_daily]:\n print(' - ' + str(len(df)) + ' rows, ' + str(len(df.columns)) + ' columns: ' + ', '.join(list(df)))\n\n\nif __name__ == \"__main__\":\n test_load_all()\n" }, { "alpha_fraction": 0.6059113144874573, "alphanum_fraction": 0.6935960650444031, "avg_line_length": 43.130435943603516, "blob_id": "b1737f1e4d6524856804588df95c2791cb764ea0", "content_id": "906b68708e839dd38d6692b04c487fe5087b5a8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 257, "num_lines": 23, "path": "/website/frontend/src/data/DataGlue.js", "repo_name": "Covid-Analytics/covidanalytics.org", "src_encoding": "UTF-8", "text": "/**\n * This file will be replaced by a machine-generated file when Glueing this to the pre-converted output\n * charts from all of the analytics.\n */\nimport React from \"react\";\nimport {EmbeddedChart} from \"./EmbeddedChart\";\n\n// List the EmbeddedChart(s)\nexport const ChartsGlue = [\n {src: \"/covid19_world/output_11_0.png\", title: \"Conversion Issue\", short: \"Converter did not generate the DataGlue.\", notebook_id: \"covid19_world\", scopes: [], tags: [\"cases\"], priority: 10, highlight: false, hide: false, updated: \"2020-04-16T09:15:37Z\"},\n];\n\n// List the Notebooks\nexport const NotebooksGlue = [\n {id: \"covid19_world\", title: \"Covid19 World\", href: \"/covid19_world/index.html\", updated: \"2020-04-16T09:15:37Z\"},\n {id: \"predictions\", title: \"Predictions\", href: \"/predictions/index.html\", updated: \"2020-04-16T09:15:46Z\"},\n {id: \"us_data\", title: \"Us Data\", href: \"/us_data/index.html\", updated: \"2020-04-16T09:15:57Z\"},\n];\n\n// Metadata\nexport const MetaDataGlue = {\n convert_iso8601: '2020-04-16T09:15:57Z',\n};\n" } ]
17
JMUETA/Autonomous-Underwater-Vehicle
https://github.com/JMUETA/Autonomous-Underwater-Vehicle
12a8323aa17a285bfb0b136d212cf6872603dea3
27b3c8e86875aee3f73595eb73931df224da0665
31c2641774d790405b02bff923fefd89a01a3d55
refs/heads/master
2020-08-19T13:19:56.874941
2019-10-18T02:26:33
2019-10-18T02:26:33
215,924,010
6
0
null
null
null
null
null
[ { "alpha_fraction": 0.4657476544380188, "alphanum_fraction": 0.5104296207427979, "avg_line_length": 28.37456512451172, "blob_id": "e1b680003d2fa5a33758444949cb5231912e3ee8", "content_id": "4141cc5db416da5d7a906e365ebc7ddc6769969d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 55759, "license_type": "no_license", "max_line_length": 120, "num_lines": 1722, "path": "/AUV_3_3.py", "repo_name": "JMUETA/Autonomous-Underwater-Vehicle", "src_encoding": "UTF-8", "text": "# title :AUV_3_2.py\r\n# description :AUV巡游系统(待测试版)\r\n# author :Fatih and Chen YiLin\r\n# date :2019.8.3\r\n# version :0.3\r\n# notes :工控机 寻线过框 抓球 撞球\r\n# python_version :3.6\r\n\r\n\r\n\r\nimport time\r\nimport cv2\r\nimport logging\r\nimport sys\r\nimport numpy as np\r\nimport serial\r\nimport threading\r\nfrom collections import deque\r\nfrom scipy.spatial import distance as dist\r\nfrom collections import OrderedDict\r\n\r\n#寻球PID参数\r\nP0 = 0.20\r\nI0 = 0.01\r\nD0 = 0.005\r\n#寻球PID参数\r\nP1 = 0.2\r\nI1 = 0.01\r\nD1 = 0.005\r\n#转线PID参数\r\nP2 = 40\r\nI2 = 0.1\r\nD2 = 0.5\r\n#对框PID参数\r\nP3 = 0.25\r\nI3 = 0.01\r\nD3 = 0.005\r\n#对框PID参数\r\nP4 = 0.1\r\nI4 = 0.01\r\nD4 = 0.005\r\n\r\n\r\n#寻球可能所在的参考坐标,给予AUV一个大致的开始寻找方向\r\nReference_coor = (150,350)\r\n\r\n#指令发送计数器\r\norder_count1 = 0\r\norder_count2 = 10\r\norder_count3 = 20\r\norder_count4 = 30\r\norder_count5 = 0\r\ncount_max1 = 30\r\ncount_max2 = 35\r\ncount_max3 = 40\r\ncount_max4 = 45\r\ncount_max5 = 5\r\n\r\n#框的数量\r\nRect_num = 5\r\n\r\n#线计数器\r\nline_count = 0\r\n\r\n#记录已经过的框\r\ncrossed_count = 0\r\n\r\n#中点两边边界\r\nleft_min = 280\r\nright_max = 360\r\n\r\n#引导线转动参数\r\nguide_line_enable_lower = -0.2\r\nguide_line_enable_higher = 0.2\r\n\r\n\r\n#模式计数器\r\nSEARCH_count = 0 #寻找模式\r\nSEARCH_count_max = 41\r\nSEARCH_count_time = 0\r\nSEARCH_count_time_max = 2\r\n\r\nADJUST_count = 0 #调整模式\r\nADJUST_count_max = 200\r\nADJUST_count_time = 0\r\nADJUST_count_time_max = 2\r\n\r\nCROSS_count = 0 #调整模式\r\nCROSS_count_max = 300\r\n\r\n#miniArea噪声抑制程度,越大识别框的能力越低。准确性越高\r\ncnts2_area = 20000\r\ncntsl0_area = 500\r\ncntsr0_area = 500\r\n\r\n#框信任度最大方差之\r\nvar_maxvalue = 35000\r\n\r\n# AUV测框的距离参数\r\nFORCAL = 600 # 距离函数设定的焦距,为定值\r\nKnow_Distance = 30.0 # 已知距离(定值)\r\nKnow_Width = 25.2\r\n\r\ndata_count = 0 # 框信任度,存储历史数据的计数器\r\ncX_container = []\r\nminAreax_container = []\r\n\r\n# AUV位置列表,分别记录AUV的x,y,theta最大存储400个位置数据\r\nx0 = deque(maxlen=400)\r\ny0 = deque(maxlen=400)\r\ntheta0 = deque(maxlen=400)\r\nx0.appendleft(0)\r\ny0.appendleft(0)\r\ntheta0.appendleft(1.57)\r\n\r\nRect_point = []\r\nLine_point = []\r\n\r\n\r\n# 差速模型接口\r\n# 暂定的AUV结构参数\r\n# b : AUV宽度\r\n# dl,dr : 左右推进器一次推进器前进距离\r\nb = 0.5\r\ndl = 0\r\ndr = 0\r\nAUV_dx = 0 #未给出\r\nAUV_dy = 0\r\nAUV_dtheta = 0\r\nSL = 0\r\nSR = 0\r\nmodel = 'diff'\r\n\r\n# 无目标信任度计数参数\r\nCount = 0\r\nCount1 = 0\r\nK_COUNT = 0\r\nX_COUNT = 0\r\n\r\n# AUV检测球参数\r\nbuff = 64\r\nballLower = (29, 86, 6)\r\nballUpper = (64, 255, 255)\r\npts = deque(maxlen=buff)\r\n\r\n\r\n#颜色抑制阈值,加一层颜色阈值提高图像分割去除噪声的能力\r\nred_lower = 0\r\ngreen_lower = 50\r\nbule_lower = 60\r\nred_higher = 255\r\ngreen_higher = 150\r\nbule_higher = 150\r\ncolor = [([red_lower, green_lower, bule_lower], [red_higher, green_higher, bule_higher])]\r\n\r\nred_lower_d = 0\r\ngreen_lower_d = 50\r\nbule_lower_d = 60\r\nred_higher_d = 255\r\ngreen_higher_d = 150\r\nbule_higher_d = 150\r\ncolor_d = [([red_lower_d, green_lower_d, bule_lower_d], [red_higher_d, green_higher_d, bule_higher_d])]\r\n\r\n# AUV标志位\r\n#Trunum信任度标志位\r\n#Tarnum目标标志位\r\nTrunum = None\r\nTarnum = 2\r\n\r\n#进入抓球标志位\r\nball_flag = False\r\n\r\n#随机运动计数位\r\nturn_count = 0\r\n\r\n#撞球标志位\r\nrush_ball_flag = False\r\n\r\n#串口通信接口\r\nportx = 'COM3'\r\nbps = 9600\r\ntimex = 0.01\r\nser = serial.Serial(portx, bps, timeout=timex)\r\n\r\n# portx1 = '/dev/ttyUSB2'\r\n# bps1 = 115200\r\n# ser1 = serial.Serial(portx1, bps1, timeout=timex)\r\n\r\n\r\n#分水岭图像分割函数\r\n# 用于二值化图像,分割出所需要的内容\r\ndef get_fg_from_hue_watershed_saturation(img, margin):\r\n mask, hue = get_fg_from_hue(img, margin)\r\n\r\n mask_bg = cv2.inRange(hue, 60, 90)\r\n mask_bg = cv2.bitwise_or(mask_bg, cv2.inRange(hue, 128, 200))\r\n\r\n markers = np.zeros(mask.shape, np.int32)\r\n markers[mask == 255] = 1\r\n markers[mask_bg == 255] = 2\r\n\r\n cv2.watershed(img, markers)\r\n mask[markers == 1] = 255\r\n\r\n # img2 = img.copy()\r\n # img2[markers == 1] = 255\r\n # cv.imshow(\"1\", img2)\r\n #\r\n # img2 = img.copy()\r\n # img2[markers == 2] = 255\r\n # cv.imshow(\"2\", img2)\r\n #\r\n # img2 = img.copy()\r\n # img2[markers == -1] = 255\r\n # cv.imshow(\"3\", img2)\r\n\r\n return mask\r\n\r\n#HSV处理函数\r\ndef get_fg_from_hue(img, margin):\r\n FRACTION_AS_BLANK = 0.003\r\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\r\n\r\n dark = hsv[..., 2] < 32\r\n hsv[..., 0][dark] = 128\r\n\r\n dark = hsv[..., 1] < 50\r\n hsv[..., 0][dark] = 128\r\n\r\n mask = cv2.inRange(hsv[..., 0], np.array((0)), np.array((margin)))\r\n mask2 = cv2.inRange(hsv[..., 0], np.array((180 - margin)), np.array((180)))\r\n\r\n mask = cv2.bitwise_or(mask, mask2)\r\n\r\n if cv2.countNonZero(mask) < mask.shape[0] * mask.shape[1] * FRACTION_AS_BLANK:\r\n mask.fill(0)\r\n\r\n return [mask, hsv[..., 0]]\r\n\r\n#引导线检测函数\r\ndef guide_line_detect(mask, area_th=5000, aspect_th=0.8):\r\n '''\r\n\r\n TODO:部分时候很靠近边框时,会检测到框\r\n :param img:\r\n :param area_th:\r\n :param aspect_th:\r\n :return:\r\n '''\r\n ASPECT_RATIO_MIN = 0.15 # 重要参数\r\n MAX_CONTOUR_NUM = 6 # 如果出现更多的轮廓,不进行处理。这是为了对抗白平衡\r\n\r\n _, contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n # 目前对自动白平衡的处理,太多轮廓则直接返回\r\n candidates = []\r\n candidates_y = []\r\n if len(contours) < MAX_CONTOUR_NUM:\r\n for cnt in contours:\r\n area = cv2.contourArea(cnt)\r\n if area > area_th: # 关键参数\r\n (x1, y1), (w1, h1), angle1 = cv2.minAreaRect(cnt)\r\n minAreaRect_area = w1 * h1\r\n aspect_ratio = float(w1) / h1\r\n if aspect_ratio > 1:\r\n aspect_ratio = 1.0 / aspect_ratio\r\n angle1 = np.mod(angle1 + 90, 180)\r\n\r\n extent = float(area) / minAreaRect_area\r\n\r\n hull = cv2.convexHull(cnt)\r\n hull_area = cv2.contourArea(hull)\r\n solidity = float(area) / hull_area\r\n\r\n (x2, y2), (MA, ma), angle2 = cv2.fitEllipse(cnt)\r\n if angle2 > 90:\r\n angle2 -= 180\r\n\r\n logging.debug('area %f,aspect_ratio %f,extent %f,solidity %f,angle1 %f,angle2 %f' % (\r\n area, aspect_ratio, extent, solidity, angle1, angle2))\r\n\r\n if aspect_ratio > aspect_th or aspect_ratio < ASPECT_RATIO_MIN or extent < 0.7 or solidity < 0.7 or abs(\r\n angle1 - angle2) > 30:\r\n break\r\n\r\n # img2 = img.copy()\r\n # contour_info(img2,area,aspect_ratio,extent,solidity,angle1,angle2,((x2, y2), (MA, ma), angle2))\r\n # cv.drawContours(img2, [cnt], 0, (0, 255, 0), 3)\r\n # show_img(img2)\r\n\r\n candidates.append((x1, y1, angle2)) # 目前这个组合是比较好的。\r\n candidates_y.append(y1)\r\n\r\n nc = len(candidates)\r\n if nc == 0:\r\n return None\r\n elif nc == 1:\r\n return candidates[0]\r\n else:\r\n logging.debug('multiple')\r\n\r\n idx = np.argmax(np.array(candidates_y))\r\n return candidates[idx]\r\n\r\n\r\n#检测框距离函数\r\ndef distance_to_camera(width, forcal, perwidth): # 距离计算\r\n return ((width * forcal) * 0.3048) / (12 * perwidth)\r\n\r\n\r\n#角度转弧度函数\r\ndef angle2rad(theta):\r\n w = (theta * np.pi) / 180\r\n return w\r\n\r\n\r\n#AUV控制,通信协议(2019版)\r\n# def control_AUV(od_r,dis=1):\r\n# global dl\r\n# global dr\r\n# global AUV_dx\r\n# global AUV_dy\r\n# head = [0xaa,0x55,0x10]\r\n# depth_lock_bit = [0x01]\r\n# dir_lock_bit = [0x01]\r\n# Left_control_bit = [0x80]\r\n# Right_control_bit = [0x80]\r\n# depth_motion_bit = [0x00]\r\n# dir_motion_bit = [0x00]\r\n# power_value = [0x00]\r\n# other_bit = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]\r\n# start_stop_bit = [0x00]\r\n#\r\n# if od_r == 'left':\r\n# dir_lock_bit[0] = 0x02\r\n# Left_control_bit[0] = 0x80\r\n# Right_control_bit[0] = 0xb2\r\n# start_stop_bit[0] = 0x01\r\n# dl = -0.1 #右旋浆前进0.1m\r\n# dr = 0.1\r\n# print('left')\r\n# if od_r == 'right':\r\n# dir_lock_bit[0] = 0x02\r\n# Right_control_bit[0] = 0x80\r\n# Left_control_bit[0] = 0xb2\r\n# start_stop_bit[0] = 0x01\r\n# dl = 0.1 #左旋浆前进0.1m\r\n# dr = -0.1\r\n# print('right')\r\n# if od_r == 'left_translation': # 左平移\r\n# dir_lock_bit[0] = 0x02\r\n# Right_control_bit[0] = 0x80\r\n# Left_control_bit[0] = 0xb2\r\n# start_stop_bit[0] = 0x01 #参数待修改\r\n# AUV_dx = -0.2\r\n# print('left_translation')\r\n# if od_r == 'right_translation': #右平移\r\n# dir_lock_bit[0] = 0x02\r\n# Right_control_bit[0] = 0x80\r\n# Left_control_bit[0] = 0xb2\r\n# start_stop_bit[0] = 0x01 #参数待修改\r\n# AUV_dx = 0.2\r\n# print('right_translation')\r\n# if od_r == 'left_rotation': #左旋转\r\n# dir_lock_bit[0] = 0x02\r\n# start_stop_bit[0] = 0x01 #参数待修改\r\n# print('left_rotation')\r\n# if od_r == 'right_rotation': #右旋转\r\n# dir_lock_bit[0] = 0x02\r\n# start_stop_bit[0] = 0x01 #参数待修改\r\n# print('right_rotation')\r\n# if od_r == 'go':\r\n# dir_lock_bit[0] = 0x02\r\n# Left_control_bit[0] = 0xb2\r\n# Right_control_bit[0] = 0xb2\r\n# start_stop_bit[0] = 0x01\r\n# dl = 0.2 #前进0.2m\r\n# dr = 0.2\r\n# print('go')\r\n# if od_r == 'up':\r\n# depth_lock_bit[0] = 0x02\r\n# depth_motion_bit[0] = 0x01\r\n# start_stop_bit[0] = 0x01\r\n# print('up')\r\n# if od_r == 'down':\r\n# depth_lock_bit[0] = 0x02\r\n# depth_motion_bit[0] = 0x02\r\n# start_stop_bit[0] = 0x01\r\n# print('down')\r\n# if od_r == 'stop':\r\n# Left_control_bit[0] = 0x80\r\n# Right_control_bit[0] = 0x80\r\n# start_stop_bit[0] = 0x02\r\n# dl = 0\r\n# dr = 0\r\n# print('stop')\r\n# if od_r == 'back':\r\n# Left_control_bit[0] = 0x4e\r\n# Right_control_bit[0] = 0x4e\r\n# start_stop_bit[0] = 0x01\r\n# print('back')\r\n#\r\n# parameter = head + depth_lock_bit + dir_lock_bit + Left_control_bit + Right_control_bit + depth_motion_bit\\\r\n# + dir_motion_bit + power_value + other_bit + start_stop_bit\r\n# check_sum = sum(parameter)\r\n# check_sum = [check_sum & 255]\r\n#\r\n# msg = head + parameter + check_sum\r\n# msg = bytearray(msg)\r\n# try: #发送串口指令 与单片机通信\r\n# ser.write(msg)\r\n# except Exception as e:\r\n# print(\"--异常--:\", e)\r\n#\r\n# return dl,dr,AUV_dx,AUV_dy\r\n\r\n\r\n#通信协议(2018版)\r\ndef PID_controlAUV(od_r,output):\r\n global model,AUV_dx,AUV_dy,AUV_dtheta,dl,dr\r\n if output > 32:\r\n output = 32\r\n print(output)\r\n head_bit = [0xaa,0x55] # 两个字节为包头\r\n length_bit = [0x03] #数据长度\r\n follow_bit = [0x08] #用来选择三种模式\r\n control_bit = [0x00] # 控制字节有效值:0-255\r\n time_level_bit = [0x00] # 高四位为推进器动作时间,低四位为推进器推力的级数\r\n\r\n print(od_r)\r\n\r\n if od_r=='ball_down':\r\n if output > 32:\r\n output = 32\r\n follow_bit = [0x08]\r\n control_bit = [1+output]\r\n time_level_bit = [0x33]\r\n\r\n if od_r=='ball_up':\r\n if output > 32:\r\n output = 32\r\n follow_bit = [0x08]\r\n control_bit = [222+output]\r\n if control_bit[0]>=255:\r\n control_bit = [255]\r\n time_level_bit = [0x33]\r\n\r\n if od_r == 'left_translation': #左平移\r\n if output > 54:\r\n output = 54\r\n follow_bit = [0x08]\r\n control_bit = [35+output]\r\n time_level_bit = [0x34]\r\n model = 'trans'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = -0.01*output/30, 0, 0, 0, 0 #提供给里程表参数待修改\r\n elif od_r == 'right_translation': #右平移\r\n if output > 46:\r\n output = 46\r\n follow_bit = [0x08]\r\n control_bit = [128+output]\r\n time_level_bit = [0x34]\r\n model = 'trans'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0.01 * output/30, 0, 0, 0, 0 #提供给里程表参数待修改\r\n\r\n if od_r == 'left': #左旋转\r\n if output > 34:\r\n output = 34\r\n follow_bit = [0x08]\r\n control_bit = [91+output]\r\n time_level_bit = [0x34]\r\n model = 'dtheta'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, 0.026, 0, 0 # 提供给里程表参数待修改\r\n if od_r == 'right': #右旋转\r\n if output > 44:\r\n output = 44\r\n follow_bit = [0x08]\r\n control_bit = [176+output]\r\n time_level_bit = [0x34]\r\n model = 'dtheta'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, -0.026, 0, 0 # 提供给里程表参数待修改\r\n\r\n if od_r == 'go':\r\n follow_bit = [0x08]\r\n control_bit = [0xfe]\r\n time_level_bit = [0x84]\r\n model = 'diff'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, 0, 0.2/30, 0.2/30 # 提供给里程表参数待修改\r\n\r\n if od_r == 'down':\r\n follow_bit = [0x0c]\r\n control_bit = [0x40]\r\n time_level_bit = [0x02]\r\n model = 'diff'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, 0, 0, 0 # 提供给里程表参数待修改\r\n\r\n if od_r == 'up':\r\n follow_bit = [0x0c]\r\n control_bit = [0x00]\r\n time_level_bit = [0x02]\r\n model = 'diff'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, 0, 0, 0 # 提供给里程表参数待修改\r\n\r\n if od_r == 'UP':\r\n follow_bit = [0x0c]\r\n control_bit = [0x20]\r\n time_level_bit = [0x02]\r\n model = 'diff'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, 0, 0, 0 # 提供给里程表参数待修改\r\n if od_r == 'DOWN':\r\n follow_bit = [0x0c]\r\n control_bit = [0x30]\r\n time_level_bit = [0x02]\r\n model = 'diff'\r\n AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, 0, 0, 0 # 提供给里程表参数待修改\r\n\r\n parameter = head_bit + length_bit + follow_bit + control_bit + time_level_bit\r\n msg = parameter\r\n msg = bytearray(msg)\r\n\r\n try: # 发送串口指令 与单片机通信\r\n ser.write(msg)\r\n except Exception as e:\r\n print(\"--异常--:\", e)\r\n\r\n return model,AUV_dx,AUV_dy,AUV_dtheta,dl,dr\r\n\r\n\r\n\r\n#识别到引导线时的转向决策\r\ndef guide_line_turn(data):\r\n x = data[0]\r\n y = data[1]\r\n angle = data[2]\r\n if x < 240 and COUNT('count5'):\r\n output = pid_ballx(x)\r\n output = int(abs(output))\r\n PID_controlAUV('left_translation',output)\r\n if x > 400 and COUNT('count5'):\r\n output = pid_ballx(x)\r\n output = int(abs(output))\r\n PID_controlAUV('right_translation',output)\r\n elif y<150 and COUNT('count5'):\r\n output = pid_ballx(y)\r\n output = int(abs(output))\r\n PID_controlAUV('go', output)\r\n if x >= 240 and x <= 400:\r\n if angle < guide_line_enable_lower and abs(angle)<0.8 and COUNT('count5'):\r\n output = pid_lineturn(angle)\r\n output = int(abs(output))\r\n PID_controlAUV('left',output)\r\n elif angle > guide_line_enable_higher and abs(angle)<0.8 and COUNT('count5'):\r\n output = pid_lineturn(angle)\r\n output = int(abs(output))\r\n PID_controlAUV('right',output)\r\n elif (guide_line_enable_lower < angle) and angle < guide_line_enable_higher and COUNT('count5'):\r\n output = pid_lineturn(angle)\r\n output = int(abs(output))\r\n PID_controlAUV('go',output)\r\n\r\n\r\n#是否要往Rect_point添加参数\r\n#若当前过框坐标已经记录,则无需重复记录\r\ndef add_judege(X, Y):\r\n now_point = [X, Y]\r\n itertime = len(Rect_point)\r\n if itertime < 1:\r\n return True\r\n for i in range(itertime):\r\n dis = np.sqrt(np.sum(np.square(Rect_point[i] - now_point)))\r\n if dis < 1:\r\n return False\r\n return True\r\n\r\n#向Rect_point添加框坐标\r\ndef Add_Rect_point(auv_local, metre, yaw, cX, Rect_width):\r\n bias = (0.6 * (cX - 160)) / Rect_width\r\n X = auv_local[0] + metre * np.cos(yaw) + bias\r\n Y = auv_local[1] + metre * np.sin(yaw)\r\n flag = add_judege(X, Y)\r\n now_point = [X, Y]\r\n if flag:\r\n Rect_point.append(now_point)\r\n\r\n#向Line_point添加线坐标\r\ndef Add_Line_point(auv_local):\r\n X = auv_local[-1][0]\r\n Y = auv_local[-1][1]\r\n flag = add_judege(X, Y)\r\n now_point = [X, Y]\r\n if flag:\r\n Line_point.append(now_point)\r\n\r\n\r\n\r\n#图像预处理,将RGB图像转换成二值图像\r\ndef Frame_Preprocess(frame0,frame1):\r\n # for (lower, upper) in color:\r\n # lower = np.array(lower, dtype=\"uint8\")\r\n # upper = np.array(upper, dtype=\"uint8\")\r\n # mask0 = cv2.inRange(frame0, lower, upper)\r\n # mask0 = cv2.bitwise_not(mask0)\r\n # output0 = cv2.bitwise_and(frame0, frame0, mask=mask0)\r\n #cv2.imshow(\"test0\" , frame0)\r\n thresh0 = get_fg_from_hue_watershed_saturation(frame0, 20)\r\n thresh0 = cv2.medianBlur(thresh0, 5)\r\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # 形态学开运算,简单滤除离框较远的干扰\r\n thresh0 = cv2.morphologyEx(thresh0, cv2.MORPH_OPEN, kernel)\r\n\r\n # for (lower, upper) in color_d:\r\n # lower = np.array(lower, dtype=\"uint8\")\r\n # upper = np.array(upper, dtype=\"uint8\")\r\n # mask1 = cv2.inRange(frame1, lower, upper)\r\n # mask1 = cv2.bitwise_not(mask1)\r\n # output0 = cv2.bitwise_and(frame1, frame1, mask=mask1)\r\n cv2.boxFilter(frame1, -1, (5, 5), frame1)\r\n thresh1 = get_fg_from_hue_watershed_saturation(frame1, 20)\r\n\r\n return thresh0,thresh1\r\n\r\n\r\n#目标识别,用于识别框线\r\n#thresh0:前置摄像头二值化图像 frame0:前置摄像头图像\r\n#Rect_Tarnum:是否识别到了框 data:框中点(cX,cY),外接矩形数据,框距离吗,外接矩形四点坐标\r\ndef Rect_Target_recognition(thresh0,frame0):\r\n global cX\r\n Rect_Tarnum = False #未识别\r\n data = None\r\n cnts2 = []\r\n _, cnts3, hierarchy = cv2.findContours(thresh0.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # findContours寻找轮廓\r\n for cnt in cnts3:\r\n area = cv2.contourArea(cnt)\r\n if area > cnts2_area:\r\n cnts2.append(cnt)\r\n if not (cnts2 == []):\r\n for c_3 in cnts2:\r\n M = cv2.moments(c_3) # 求图形的矩\r\n cX = int((M[\"m10\"] + 1) / (M[\"m00\"] + 1))\r\n cY = int((M[\"m01\"] + 1) / (M[\"m00\"] + 1))\r\n\r\n if not (cnts2 == []):\r\n c = max(cnts2, key=cv2.contourArea)\r\n marker = cv2.minAreaRect(c) # 得到最小外接矩形(中心(x,y),(宽,高),选住角度)\r\n metre = distance_to_camera(Know_Width, FORCAL, marker[1][0] + 1) # 距离摄像头距离\r\n box = cv2.boxPoints(marker) # 获取最小外接矩形的四个顶点\r\n box = np.int0(box)\r\n cv2.drawContours(frame0, [box], -1, (0, 255, 0), 2)\r\n cv2.putText(frame0, \"%.2fm\" % (metre), (frame0.shape[1] - 200, frame0.shape[0] - 20),\r\n cv2.FONT_HERSHEY_SIMPLEX,\r\n 2.0, (0, 255, 0), 3)\r\n Rect_Tarnum = True\r\n data = [cX,cY,marker, metre, box]\r\n return Rect_Tarnum, data, frame0\r\n return Rect_Tarnum,data,frame0\r\n\r\n\r\n\r\n#识别线目标\r\n#thresh1:下置摄像头二值化图像,frame1:下置摄像头图像\r\n#Line_Tarnum:是否识别到了线,data:线上的两个坐标(x1,y1),线与AUV夹角angle,先的四点坐标\r\ndef Line_Target_recognition(thresh,frame):\r\n data = None\r\n guide_line = guide_line_detect(thresh) # 检测下置摄像头是否读到引导线\r\n Line_Tarnum = False\r\n if guide_line:\r\n # 发现引导线,停一下\r\n x, y, angle = guide_line\r\n angle = angle / 180 * np.pi\r\n cv2.line(frame, (int(x), int(y)), (int(x + 100 * np.sin(angle)), int(y - 100 * np.cos(angle))),\r\n (0, 255, 0), 2)\r\n x1 = int(x + 100 * np.sin(angle))\r\n y1 = int(y - 100 * np.cos(angle))\r\n Line_Tarnum = True\r\n data = [x1, y1, angle]\r\n return Line_Tarnum, data, frame\r\n return Line_Tarnum, data, frame\r\n\r\n\r\n\r\n#框信任度判断\r\ndef Rect_Trust(data):\r\n if data is not None:\r\n cX = data[0]\r\n marker = data[1]\r\n minArea_x = marker\r\n cX_container.append(cX)\r\n minAreax_container.append(marker)\r\n if cX - minArea_x > 50:\r\n return 0\r\n if len(cX_container) >= 5 and len(minAreax_container) >= 5:\r\n var_cX = np.var(cX_container)\r\n var_min = np.var(minAreax_container)\r\n # cv2.putText(frame, \"%.2f\" % (var_cX), (frame.shape[1] - 200, frame.shape[0] - 20),\r\n # cv2.FONT_HERSHEY_SIMPLEX,\r\n # 2.0, (0, 255, 0), 3)\r\n if var_cX < var_maxvalue and var_min < var_maxvalue: # 方差,待测量\r\n return 1\r\n else:\r\n return 0\r\n return 2\r\n\r\n# 无目标信任度\r\ndef Estate(flag):\r\n global Count\r\n global C_L_COUNT\r\n global Est\r\n global Tarnum\r\n Count = Count + 1\r\n if flag == 0: # 不信任框\r\n Est = 1\r\n if flag == 2: # 无框 无线\r\n Est = 2\r\n if flag == 1: # 有线\r\n Est = 3\r\n\r\n if Est == 2:\r\n C_L_COUNT = C_L_COUNT + 1 # 无框则加一\r\n if Est == 1:\r\n C_L_COUNT = C_L_COUNT + 1\r\n\r\n if Count == 10:\r\n if C_L_COUNT >= 10:\r\n Tarnum = 2\r\n return True\r\n Count = 0\r\n C_L_COUNT = 0 # 10次后清零\r\n\r\n elif Count < 10:\r\n return 0\r\n\r\n\r\n\r\n#里程表记录函数 目前与运动效果不匹配\r\ndef Odometer(model,AUV_dx,AUV_dy,AUV_dtheta,dl,dr): #里程表\r\n global x0\r\n global y0\r\n global theta0\r\n if model=='diff': #差速模式\r\n x = x0[0]\r\n y = y0[0]\r\n theta = theta0[0]\r\n ddx = (dr+dl)*np.cos(theta+(dr-dl)/2*b)/2\r\n ddy = (dr+dl)*np.sin(theta+(dr-dl)/2*b)/2\r\n dtheta = (dr-dl)/b\r\n x1 = x + ddx\r\n y1 = y + ddy\r\n theta1 = theta + dtheta\r\n x0.appendleft(x1)\r\n y0.appendleft(y1)\r\n theta0.appendleft(theta1)\r\n elif model =='dtheta':\r\n x1 = x0[0]\r\n y1 = y0[0]\r\n theta = theta0[0]\r\n dtheta = AUV_dtheta\r\n theta1 = theta + dtheta\r\n x0.appendleft(x1)\r\n y0.appendleft(y1)\r\n theta0.appendleft(theta1)\r\n else: #平移模式\r\n x = x0[0]\r\n y = y0[0]\r\n theta = theta0[0]\r\n dx = AUV_dx * np.cos(theta)\r\n dy = AUV_dy * np.sin(theta)\r\n x1 = x + dx\r\n y1 = y + dy\r\n x0.appendleft(x1)\r\n y0.appendleft(y1)\r\n theta0.appendleft(theta)\r\n return 0\r\n\r\n#无目标情况下的转向函数\r\ndef Turn():\r\n global turn_count\r\n turn_count = turn_count + 1\r\n if turn_count == 1:\r\n PID_controlAUV('right',23)\r\n if turn_count == 2:\r\n PID_controlAUV('left',34)\r\n turn_count = 0\r\n\r\n\r\n\r\n#无目标情况下的位置检测 暂时用不上\r\ndef search(x, y, theta):\r\n global x1\r\n global x2\r\n global y1\r\n global y2\r\n global SR\r\n global SL\r\n k = np.tan(theta)\r\n b1 = y - k * x\r\n\r\n Wide = 3.66\r\n Long = 7.3\r\n\r\n if 0.9 <= np.cos(theta) <= 1: # k=0的情况\r\n if 0 <= b1 < Long * 0.5:\r\n return 'left'\r\n if Long * 0.5 <= b1 <= Long:\r\n return 'right'\r\n elif -1 <= np.cos(theta) <=-0.9:\r\n if 0 <= b1 < Long * 0.5:\r\n return 'right'\r\n if Long * 0.5 <= b1 <= Long:\r\n return 'left'\r\n\r\n elif 0 <= x <= 0.1 and 0 <= y <= 0.1 and 0 <= theta <= 0.1:\r\n return 'left'\r\n\r\n else:\r\n if 0 <= b1 <= Long: # 左边交点Y轴上(三种情况)\r\n x1 = 0\r\n y1 = b1\r\n if 0 <= (Long - b1) / k <= Wide:\r\n x2 = (Long - b1) / k\r\n y2 = Long\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SL = x1 * y2 + (x2 - x1) * (y2 - y1) / 2\r\n SR = Long * Wide - SL\r\n if np.cos(theta) <= 0: # 船头方向朝左\r\n SR = x1 * y2 + (x2 - x1) * (y2 - y1) / 2\r\n SL = Long * Wide - SR\r\n elif 0 <= (Wide * k + b1) <= Long:\r\n x2 = Wide\r\n y2 = (Wide * k + b1)\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SR = x1 * y1 + x2 * y2 - x1 * y2 + (x2 - x1) * (y1 - y2) / 2\r\n SL = Long * Wide - SR\r\n elif np.cos(theta) <= 0: # 船头方向朝左\r\n SL = x1 * y1 + x2 * y2 - x1 * y2 + (x2 - x1) * (y1 - y2) / 2\r\n SR = Long * Wide - SL\r\n elif 0 <= (-b1 / k) <= Wide:\r\n x2 = -b1 / k\r\n y2 = 0\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SR = x2 * y1\r\n SL = Long * Wide - SR\r\n elif np.cos(theta) <= 0: # 船头方向朝左\r\n SL = x2 * y1\r\n SR = Long * Wide - SL\r\n elif 0 <= (Wide * k + b1) <= Long: # 右边交点在x=3.66上(三减一 种情况)\r\n x2 = Wide\r\n y2 = (Wide * k + b1)\r\n if 0 <= (Long - b1) / k <= Wide:\r\n x1 = (Long - b1) / k\r\n y1 = Long\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SR = x1 * y1 + x2 * y2 - x1 * y2 + (x2 - x1) * (y1 - y2) / 2\r\n SL = Long * Wide - SR\r\n elif np.cos(theta) <= 0: # 船头方向朝左\r\n SL = x1 * y1 + x2 * y2 - x1 * y2 + (x2 - x1) * (y1 - y2) / 2\r\n SR = Long * Wide - SL\r\n elif 0 <= -b1 / k <= Wide:\r\n x1 = -b1 / k\r\n y1 = 0\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SR = (x2 - x1) * y2 * 0.5\r\n SL = Long * Wide - SR\r\n elif np.cos(theta) <= 0: # 船头方向朝左\r\n SL = (x2 - x1) * y2 * 0.5\r\n SR = Long * Wide - SL\r\n\r\n elif 0 <= (Long - b1) / k <= Wide and 0 <= (-b1 / k) <= Wide and k >= 0: # 两个交点在y=0和y=13上\r\n x1 = -b1 / k\r\n y1 = 0\r\n x2 = (Long - b1) / k\r\n y2 = Long\r\n if np.sin(theta) >= 0: # 船头方向朝上\r\n SL = (x1 + x2) * Long * 0.5\r\n SR = Long * Wide - SL\r\n elif np.sin(theta) <= 0: # 船头方向朝下\r\n SR = (x1 + x2) * Long * 0.5\r\n SL = Long * Wide - SR\r\n elif 0 <= (Long - b1) / k <= Wide and 0 <= -b1 / k <= Wide and k < 0:\r\n x1 = (Long - b1) / k\r\n y1 = Long\r\n x2 = -b1 / k\r\n y2 = 0\r\n if np.sin(theta) >= 0: # 船头方向朝上\r\n SL = (x1 + x2) * Long * 0.5\r\n SR = Long * Wide - SL\r\n elif np.sin(theta) <= 0: # 船头方向朝下\r\n SR = (x1 + x2) * Long * 0.5\r\n SL = Long * Wide - SR\r\n\r\n if SL > SR:\r\n return 'left'\r\n if SL < SR:\r\n return 'right'\r\n\r\n#过框模式,切换识别模式。将放行更多的噪声,以此来增加识别能力\r\ndef cross_Rect(frame0):\r\n global corss_Rect_flag\r\n global cYl\r\n global cYr\r\n global cXl\r\n global cXr\r\n\r\n # PID_controlAUV('go', 20)\r\n # Odometer(model, AUV_dx, AUV_dy, AUV_dtheta, dl, dr)\r\n # print('直走') # 过框模式保持直走,再做差速调整\r\n\r\n corss_Rect_flag = 1\r\n\r\n cntsl = []\r\n cntsr = []\r\n framel = frame0[:, 0:319]\r\n framer = frame0[:, 320:640]\r\n thresh = get_fg_from_hue_watershed_saturation(frame0, 20)\r\n thresh = cv2.medianBlur(thresh, 5)\r\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9)) # 形态学开运算,简单滤除离框较远的干扰\r\n thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)\r\n left_area = thresh[:, 0:319]\r\n right_area = thresh[:, 320:640]\r\n _, cntsl0, hierarchy = cv2.findContours(left_area, cv2.RETR_TREE,\r\n cv2.CHAIN_APPROX_SIMPLE)\r\n _, cntsr0, hierarchy = cv2.findContours(right_area, cv2.RETR_TREE,\r\n cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n for cnt in cntsl0:\r\n area = cv2.contourArea(cnt)\r\n if area > cntsr0_area:\r\n cntsl.append(cnt)\r\n\r\n for cnt in cntsr0:\r\n area = cv2.contourArea(cnt)\r\n if area > cntsl0_area:\r\n cntsr.append(cnt)\r\n\r\n if not (cntsl == []):\r\n for c_l in cntsl:\r\n Ml = cv2.moments(c_l) # 求图形的矩\r\n cXl = int((Ml[\"m10\"] + 1) / (Ml[\"m00\"] + 1))\r\n cYl = int((Ml[\"m01\"] + 1) / (Ml[\"m00\"] + 1))\r\n cv2.circle(framel, (cXl, cYl), 7, (0, 255, 255), -1)\r\n cv2.drawContours(framel, [c_l], -1, (0, 255, 0), 2)\r\n if not (cntsr == []):\r\n for c_r in cntsr:\r\n Mr = cv2.moments(c_r) # 求图形的矩\r\n cXr = int((Mr[\"m10\"] + 1) / (Mr[\"m00\"] + 1))\r\n cYr = int((Mr[\"m01\"] + 1) / (Mr[\"m00\"] + 1))\r\n cv2.circle(framer, (cXr, cYr), 7, (255, 255, 255), -1)\r\n cv2.drawContours(framer, [c_r], -1, (0, 255, 0), 2)\r\n\r\n if cntsl == [] and not (cntsr == []) and COUNT('count5'):\r\n PID_controlAUV('left',20)\r\n print('向左转1')\r\n elif not (cntsl == []) and cntsr == [] and COUNT('count5'):\r\n PID_controlAUV('right', 20)\r\n print('向右转1')\r\n elif not (cntsl == []) and not (cntsr == []):\r\n if abs(cYl - cYr) < 40:\r\n Y_flag = True\r\n else:\r\n Y_flag = False\r\n\r\n if Y_flag:\r\n if (cXl + cXr + 320) / 2 > 390 and COUNT('count5'):\r\n PID_controlAUV('left',20)\r\n print('向左转2')\r\n if (cXl + cXr + 320) / 2 < 250 and COUNT('count5'):\r\n PID_controlAUV('right',20)\r\n print('向右转2')\r\n if (cXl + cXr + 320) / 2 < 390 and (cXl + cXr + 320) / 2 > 250 and COUNT('count5'):\r\n PID_controlAUV('go', 20)\r\n print('直走1')\r\n else:\r\n if cYl > cYr and COUNT('count5'):\r\n PID_controlAUV('right', 20)\r\n print('向右转3')\r\n elif cYl < cYr and COUNT('count5'):\r\n PID_controlAUV('left', 20)\r\n print('向左转3')\r\n\r\n elif cntsl == [] and cntsr == []:\r\n for i in range(3):\r\n PID_controlAUV('go', 20)\r\n print('直走2')\r\n\r\n\r\n\r\n#标志位计数函数\r\ndef flag_count():\r\n global data_count\r\n\r\n data_count = data_count + 1\r\n if data_count >= 5:\r\n data_count = 0\r\n\r\n\r\n#AUV球识别函数\r\ndef Auv_ball_detect(frame0):\r\n findball_flag = False\r\n blurred = cv2.GaussianBlur(frame0, (11, 11), 0)\r\n hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)\r\n\r\n mask = cv2.inRange(hsv, ballLower, ballUpper)\r\n mask = cv2.erode(mask, None, iterations=2)\r\n mask = cv2.dilate(mask, None, iterations=2)\r\n cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,\r\n cv2.CHAIN_APPROX_SIMPLE)\r\n cnts = cnts[1]\r\n center = None\r\n\r\n if len(cnts) > 0:\r\n c = max(cnts, key=cv2.contourArea)\r\n ((x, y), radius) = cv2.minEnclosingCircle(c)\r\n M = cv2.moments(c)\r\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\r\n\r\n if radius > 10:\r\n cv2.circle(frame0, (int(x), int(y)), int(radius),\r\n (0, 255, 0), 2)\r\n cv2.circle(frame0, center, 5, (255, 255, 255), -1)\r\n findball_flag = True\r\n\r\n pts.appendleft(center)\r\n for i in range(1, len(pts)):\r\n if pts[i - 1] is None or pts[i] is None:\r\n continue\r\n\r\n thickness = int(np.sqrt(buff / float(i + 1)) * 2.5)\r\n cv2.line(frame0, pts[i - 1], pts[i], (255, 0, 0), thickness)\r\n\r\n\r\n\r\n return frame0,findball_flag,center\r\n\r\n\r\ndef order_points(pts):\r\n rect = np.zeros((4, 2), dtype=\"float32\")\r\n s = pts.sum(axis=1)\r\n rect[0] = pts[np.argmin(s)]\r\n rect[2] = pts[np.argmax(s)]\r\n\r\n diff = np.diff(pts, axis=1)\r\n rect[1] = pts[np.argmin(diff)]\r\n rect[3] = pts[np.argmax(diff)]\r\n\r\n return rect\r\n\r\n#框追踪类,用于追踪已经识别到的框\r\nclass CentroidTracker():\r\n def __init__(self, maxDisappeared=300):\r\n self.nextObjectID = 0\r\n self.objects = OrderedDict()\r\n self.disappeared = OrderedDict()\r\n self.maxDisappeared = maxDisappeared\r\n\r\n def register(self, centroid):\r\n self.objects[self.nextObjectID] = centroid\r\n self.disappeared[self.nextObjectID] = 0\r\n self.nextObjectID += 1\r\n\r\n def deregister(self, objectID):\r\n del self.objects[objectID]\r\n del self.disappeared[objectID]\r\n\r\n def update(self, rects):\r\n if len(rects) == 0:\r\n for objectID in self.disappeared.keys():\r\n self.disappeared[objectID] += 1\r\n if self.disappeared[objectID] > self.maxDisappeared:\r\n self.deregister(objectID)\r\n return self.objects\r\n inputCentroids = np.zeros((len(rects), 2), dtype=\"int\")\r\n\r\n for (i, (startX, startY, endX, endY)) in enumerate(rects):\r\n cX = int((startX[0] + endX[0]) / 2.0)\r\n cY = int((startY[1] + endY[1]) / 2.0)\r\n inputCentroids[i] = (cX, cY)\r\n if len(self.objects) == 0:\r\n for i in range(0, len(inputCentroids)):\r\n self.register(inputCentroids[i])\r\n else:\r\n objectIDs = list(self.objects.keys())\r\n objectCentroids = list(self.objects.values())\r\n D = dist.cdist(np.array(objectCentroids), inputCentroids)\r\n rows = D.min(axis=1).argsort()\r\n cols = D.argmin(axis=1)[rows]\r\n usedRows = set()\r\n usedCols = set()\r\n for (row, col) in zip(rows, cols):\r\n if row in usedRows or col in usedCols:\r\n continue\r\n objectID = objectIDs[row]\r\n self.objects[objectID] = inputCentroids[col]\r\n self.disappeared[objectID] = 0\r\n usedRows.add(row)\r\n usedCols.add(col)\r\n unusedRows = set(range(0, D.shape[0])).difference(usedRows)\r\n unusedCols = set(range(0, D.shape[1])).difference(usedCols)\r\n if D.shape[0] >= D.shape[1]:\r\n for row in unusedRows:\r\n objectID = objectIDs[row]\r\n self.disappeared[objectID] += 1\r\n if self.disappeared[objectID] > self.maxDisappeared:\r\n self.deregister(objectID)\r\n else:\r\n for col in unusedCols:\r\n self.register(inputCentroids[col])\r\n return self.objects\r\n\r\n#框最终函数\r\nct = CentroidTracker()\r\ndef Target_Tracking(frame, box):\r\n rects = []\r\n rects.append(box.astype(\"int\"))\r\n objects = ct.update(rects)\r\n for (objectID, centroid) in objects.items():\r\n text = \"ID {}\".format(objectID)\r\n cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\r\n cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)\r\n\r\n return frame, objectID, centroid\r\n\r\n\r\n#PID控制类\r\nclass PID:\r\n \"\"\"PID Controller\r\n \"\"\"\r\n\r\n def __init__(self, P=0.2, I=0.0, D=0.0):\r\n\r\n self.Kp = P\r\n self.Ki = I\r\n self.Kd = D\r\n\r\n self.sample_time = 0.00\r\n self.current_time = time.time()\r\n self.last_time = self.current_time\r\n\r\n self.clear()\r\n\r\n def clear(self):\r\n \"\"\"Clears PID computations and coefficients\"\"\"\r\n self.SetPoint = 0.0\r\n\r\n self.PTerm = 0.0\r\n self.ITerm = 0.0\r\n self.DTerm = 0.0\r\n self.last_error = 0.0\r\n\r\n # Windup Guard\r\n self.int_error = 0.0\r\n self.windup_guard = 20.0\r\n\r\n self.output = 0.0\r\n\r\n def update(self, feedback_value):\r\n \"\"\"Calculates PID value for given reference feedback\r\n .. math::\r\n u(t) = K_p e(t) + K_i \\int_{0}^{t} e(t)dt + K_d {de}/{dt}\r\n .. figure:: images/pid_1.png\r\n :align: center\r\n Test PID with Kp=1.2, Ki=1, Kd=0.001 (test_pid.py)\r\n \"\"\"\r\n error = self.SetPoint - feedback_value\r\n\r\n self.current_time = time.time()\r\n delta_time = self.current_time - self.last_time\r\n delta_error = error - self.last_error\r\n\r\n if (delta_time >= self.sample_time):\r\n self.PTerm = self.Kp * error\r\n self.ITerm += error * delta_time\r\n\r\n if (self.ITerm < -self.windup_guard):\r\n self.ITerm = -self.windup_guard\r\n elif (self.ITerm > self.windup_guard):\r\n self.ITerm = self.windup_guard\r\n\r\n self.DTerm = 0.0\r\n if delta_time > 0:\r\n self.DTerm = delta_error / delta_time\r\n\r\n # Remember last time and last error for next calculation\r\n self.last_time = self.current_time\r\n self.last_error = error\r\n\r\n self.output = self.PTerm + (self.Ki * self.ITerm) + (self.Kd * self.DTerm)\r\n\r\n def setKp(self, proportional_gain):\r\n \"\"\"Determines how aggressively the PID reacts to the current error with setting Proportional Gain\"\"\"\r\n self.Kp = proportional_gain\r\n\r\n def setKi(self, integral_gain):\r\n \"\"\"Determines how aggressively the PID reacts to the current error with setting Integral Gain\"\"\"\r\n self.Ki = integral_gain\r\n\r\n def setKd(self, derivative_gain):\r\n \"\"\"Determines how aggressively the PID reacts to the current error with setting Derivative Gain\"\"\"\r\n self.Kd = derivative_gain\r\n\r\n def setWindup(self, windup):\r\n \"\"\"Integral windup, also known as integrator windup or reset windup,\r\n refers to the situation in a PID feedback controller where\r\n a large change in setpoint occurs (say a positive change)\r\n and the integral terms accumulates a significant error\r\n during the rise (windup), thus overshooting and continuing\r\n to increase as this accumulated error is unwound\r\n (offset by errors in the other direction).\r\n The specific problem is the excess overshooting.\r\n \"\"\"\r\n self.windup_guard = windup\r\n\r\n def setSampleTime(self, sample_time):\r\n \"\"\"PID that should be updated at a regular interval.\r\n Based on a pre-determined sampe time, the PID decides if it should compute or return immediately.\r\n \"\"\"\r\n self.sample_time = sample_time\r\n\r\n\r\n\r\n\r\n#工控机摄像头读取函数\r\n# 无\r\n#frame0:前置摄像头画面 frame1:下置摄像头画面\r\ndef Camera_Capture():\r\n ret, frame0 = cap1.read()\r\n ret, frame1 = cap.read()\r\n return frame0,frame1\r\n\r\n#改变颜色阈值函数\r\n# 无\r\n# 无(纯全局变量操作)\r\ndef change_colorvalue():\r\n global red_lower\r\n global green_lower\r\n global bule_lower\r\n global red_higher\r\n global green_higher\r\n global bule_higher\r\n if SEARCH_count >= SEARCH_count_max:\r\n green_lower = green_lower - 5\r\n bule_lower = bule_lower - 5\r\n red_higher = red_higher + 5\r\n green_higher = green_higher + 5\r\n bule_higher = bule_higher + 5\r\n\r\n\r\n#颜色阈值初始化\r\ndef colorvalue_back():\r\n global red_lower\r\n global green_lower\r\n global bule_lower\r\n global red_higher\r\n global green_higher\r\n global bule_higher\r\n red_lower = 0\r\n green_lower = 50\r\n bule_lower = 60\r\n red_higher = 255\r\n green_higher = 150\r\n bule_higher = 150\r\n\r\n\r\n#用于退出整个程序\r\n# 无\r\n#退出标志位\r\ndef Break_flag():\r\n break_flag = False\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == ord(\"q\"):\r\n break_flag = True\r\n return break_flag\r\n\r\n#用于控制计数。识别要快,运动要慢、准\r\n#计数器名称\r\n# 无\r\ndef COUNT(name):\r\n global order_count1\r\n global order_count2\r\n global order_count3\r\n global order_count4\r\n global order_count5\r\n if name=='count1':\r\n enable_flag = False\r\n order_count1 = order_count1 + 1\r\n if order_count1>=count_max1:\r\n order_count1 = 0\r\n enable_flag = True\r\n return enable_flag\r\n if name=='count2':\r\n enable_flag = False\r\n order_count2 = order_count2 + 1\r\n if order_count2 >= count_max2:\r\n order_count2 = 0\r\n enable_flag = True\r\n return enable_flag\r\n if name=='count3':\r\n enable_flag = False\r\n order_count3 = order_count3 + 1\r\n if order_count3 >= count_max3:\r\n order_count3 = 0\r\n enable_flag = True\r\n return enable_flag\r\n if name=='count4':\r\n enable_flag = False\r\n order_count4 = order_count4 + 1\r\n if order_count4 >= count_max4:\r\n order_count4 = 0\r\n enable_flag = True\r\n return enable_flag\r\n if name=='count5':\r\n enable_flag = False\r\n order_count5 = order_count5 + 1\r\n if order_count5 >= count_max5:\r\n order_count5 = 0\r\n enable_flag = True\r\n return enable_flag\r\n\r\n\r\n\r\n\r\n\r\n#寻找模式\r\n#frame0:前置摄像头画面 frame1:下置摄像头画面\r\n#SEARCH_enable:Search放行标志位\r\ndef SEARCH_MODEL(frame0,frame1):\r\n global SEARCH_count\r\n global SEARCH_count_time\r\n global SEARCH_count_time_max\r\n SEARCH_enable = False\r\n thresh0,thresh1 = Frame_Preprocess(frame0,frame1)\r\n Rect_Tarnum, data0, frame0 = Rect_Target_recognition(thresh0,frame0)\r\n Line_Tarnum, data1, frame1 = Line_Target_recognition(thresh1, frame1)\r\n\r\n SEARCH_count = SEARCH_count + 1\r\n\r\n # if COUNT('count1')and (not(Rect_Tarnum) and not(Line_Tarnum)):\r\n # _, cnts3, hierarchy = cv2.findContours(thresh0, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # findContours寻找轮廓\r\n # if not (cnts3 == []):\r\n # for c_3 in cnts3:\r\n # M = cv2.moments(c_3) # 求图形的矩\r\n # cX = int((M[\"m10\"] + 1) / (M[\"m00\"] + 1))\r\n # cY = int((M[\"m01\"] + 1) / (M[\"m00\"] + 1))\r\n # cv2.drawContours(frame0, [c_3], -1, (0, 255, 0), 2)\r\n #\r\n # if cX < 320:\r\n # output = pid_rectx(cX)\r\n # output = int(abs(output))\r\n # PID_controlAUV('left_translation', output)\r\n # else:\r\n # output = pid_rectx(cX)\r\n # output = int(abs(output))\r\n # PID_controlAUV('right_translation', output)\r\n\r\n if COUNT('count1')and (not(Rect_Tarnum) or not(Line_Tarnum)):\r\n Turn()\r\n\r\n if SEARCH_count >= SEARCH_count_max:\r\n #change_colorvalue()\r\n SEARCH_count = 0\r\n SEARCH_count_time = SEARCH_count_time + 1\r\n if SEARCH_count_time >= SEARCH_count_time_max:\r\n SEARCH_count_time = 0\r\n PID_controlAUV('ball_up',30)\r\n if Rect_Tarnum or Line_Tarnum:\r\n SEARCH_count = 0 #找到目标后计数清零\r\n SEARCH_count_time = 0\r\n #colorvalue_back()\r\n SEARCH_enable = True\r\n cv2.imshow('frame0',frame0)\r\n cv2.imshow('frame1',frame1)\r\n break_flag = Break_flag()\r\n\r\n return SEARCH_enable, break_flag\r\n\r\n\r\ndef ADJUST_MODEL(frame0,frame1):\r\n global ADJUST_count\r\n global ADJUST_count_max\r\n global ADJUST_count_time\r\n global ADJUST_count_time_max\r\n global MODEL_section_flag\r\n Rect_Aim_flag = False\r\n Line_Aim_flag = False\r\n ADJUST_enable = False\r\n thresh0, thresh1 = Frame_Preprocess(frame0, frame1)\r\n\r\n Rect_Tarnum, data0, frame0 = Rect_Target_recognition(thresh0, frame0)\r\n Line_Tarnum, data1, frame1 = Line_Target_recognition(thresh1, frame1)\r\n\r\n if not(data0 is None):\r\n marker = data0[2]\r\n if (marker[1][0] / marker[1][1]) > 0.7:\r\n box = data0[4]\r\n frame0,objectID,centroid = Target_Tracking(frame0, box)\r\n if centroid[0]<left_min and COUNT('count1'):\r\n output = pid_rectx(centroid[0])\r\n output = int(abs(output))\r\n PID_controlAUV('left_translation',output)\r\n print('左平移')\r\n if centroid[0]>right_max and COUNT('count1'):\r\n output = pid_rectx(centroid[0])\r\n output = int(abs(output))\r\n PID_controlAUV('right_translation', output)\r\n print('右平移')\r\n\r\n # if centroid[1] < 190:\r\n # PID_controlAUV('UP',20)\r\n # elif centroid[1] > 290:\r\n # PID_controlAUV('down', 20)\r\n if centroid[0]>left_min and centroid[0]<right_max: #and 190 < centroid[1] < 290:\r\n Rect_Aim_flag = True\r\n Trustnum = Rect_Trust(data0)\r\n\r\n\r\n elif not(data1 is None):\r\n x = data1[0]\r\n angle = data1[2]\r\n guide_line_turn(data1)\r\n\r\n if guide_line_enable_lower < angle < guide_line_enable_higher and 280 <= x <= 360:\r\n Line_Aim_flag = True\r\n Trustnum = False\r\n\r\n if Line_Aim_flag or (Rect_Aim_flag and Trustnum):\r\n ADJUST_enable = True\r\n ADJUST_count = 0\r\n\r\n ADJUST_count = ADJUST_count + 1\r\n # if ADJUST_count >= ADJUST_count_max:\r\n # print('减小调整力度') #待协商\r\n # ADJUST_count_time = ADJUST_count_time + 1\r\n # ADJUST_count = 0\r\n if ADJUST_count_time>=ADJUST_count_time_max:\r\n ADJUST_count_time = 0\r\n MODEL_section_flag = 'CROSS' #如果一直都调不好,就直接过框\r\n\r\n cv2.imshow('frame0',frame0)\r\n cv2.imshow('frame1',frame1)\r\n break_flag = Break_flag()\r\n return ADJUST_enable,break_flag\r\n\r\n\r\ndef CROSS_MODEL(frame0,frame1):\r\n global line_count\r\n global CROSS_count\r\n global CROSS_count_max\r\n CROSS_count_flag = False\r\n cross_Rect_flag = False\r\n PID_controlAUV('go',25)\r\n cross_Rect(frame0)\r\n\r\n thresh0, thresh1 = Frame_Preprocess(frame0, frame1)\r\n # edges = cv2.Canny(thresh1, 40, 200, apertureSize=3)\r\n # lines = cv2.HoughLines(edges, 1, np.pi / 180, 160)\r\n # if not(lines is None):\r\n # lines1 = lines[:, 0, :] # 提取为二维\r\n # for rho, theta in lines1[:]:\r\n # a = np.cos(theta)\r\n # b = np.sin(theta)\r\n # x0 = a * rho\r\n # y0 = b * rho\r\n # x1 = int(x0 + 1000 * (-b))\r\n # y1 = int(y0 + 1000 * a)\r\n # x2 = int(x0 - 1000 * (-b))\r\n # y2 = int(y0 - 1000 * a)\r\n # cv2.line(frame1, (x1, y1), (x2, y2), (255, 0, 0), 1)\r\n # if -0.4 < theta < 0.4:\r\n # line_count = line_count + 1\r\n # if line_count >= 3:\r\n # line_count = 0\r\n # cross_Rect_flag = True\r\n\r\n CROSS_count = CROSS_count + 1\r\n\r\n if CROSS_count >= CROSS_count_max: #and line_count < 5: #如果一直没有过框,就跳出\r\n PID_controlAUV('go',25)\r\n CROSS_count = 0\r\n CROSS_count_flag = True\r\n cv2.imshow('frame0',frame0)\r\n cv2.imshow('frame1',frame1)\r\n break_flag = Break_flag()\r\n\r\n return cross_Rect_flag,CROSS_count_flag,break_flag\r\n\r\n\r\n#需求模式,采用PID跟踪\r\n#输入下置摄像头画面\r\ndef SEARCHBALL_MODEL(frame1):\r\n frame1,findball_flag,center = Auv_ball_detect(frame1)\r\n if findball_flag:\r\n cX = center[0]\r\n cY = center[1]\r\n if center[0]<280:\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('left_translation',output)\r\n elif center[0]>360:\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('right_translation',output)\r\n if center[1]<200:\r\n output = pid_bally(cY)\r\n output = int(abs(output))\r\n PID_controlAUV('ball_up',output)\r\n elif center[1]>280:\r\n output = pid_bally(cY)\r\n output = int(abs(output))\r\n PID_controlAUV('ball_down',output)\r\n else:\r\n dx = Reference_coor[0] - x0[0]\r\n dy = Reference_coor[1] - y0[0]\r\n\r\n#多线程 设定时间进入另一个线程\r\ndef Rush_ball_time():\r\n rush_ball_time = 0.1 # 进入寻球状态的时间,单位是分钟\r\n timer = threading.Timer(60 * rush_ball_time, to_ball) # 设置时钟。根据rush_ball_time变量以判断是否进入撞球部分\r\n timer.start()\r\n\r\n#抓球函数\r\ndef Catch_ball(frame0,frame1):\r\n global rush_ball_flag\r\n frame, findball_flag, center = Auv_ball_detect(frame0)\r\n thresh0, thresh1 = Frame_Preprocess(frame0, frame1)\r\n cv2.imshow('frame0',frame0)\r\n cv2.imshow('frame1',frame1)\r\n if findball_flag:\r\n cX = center[0]\r\n cY = center[1]\r\n if center[0] < 280 and COUNT('count1'):\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('left_translation', output)\r\n elif center[0] > 360 and COUNT('count1'):\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('right_translation', output)\r\n\r\n elif center[1] < 360 and COUNT('count1'):\r\n output = pid_bally(cY)\r\n output = int(abs(output))\r\n PID_controlAUV('ball_up',output)\r\n elif center[1] > 420 and COUNT('count1'):\r\n output = pid_bally(cY)\r\n output = int(abs(output))\r\n PID_controlAUV('ball_down',output)\r\n\r\n if 280 < center[0] < 360 and 360 < center[1] < 420 and COUNT('count5'):\r\n for i in range(3):\r\n PID_controlAUV('MIXDOWN', 20)\r\n time.sleep(10)\r\n for i in range(3):\r\n PID_controlAUV('UP',10)\r\n time.sleep(15)\r\n rush_ball_flag = True\r\n else:\r\n Turn()\r\n\r\n return rush_ball_flag\r\n\r\n#撞球函数\r\ndef Rush_ball(frame0,frame1):\r\n frame, findball_flag, center = Auv_ball_detect(frame0)\r\n cv2.imshow('frame0',frame0)\r\n cv2.imshow('frame1', frame1)\r\n if findball_flag:\r\n cX = center[0]\r\n if center[0] < 280:\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('left_translation', output)\r\n elif center[0] > 360:\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('right_translation', output)\r\n\r\n if center[1] < 200:\r\n PID_controlAUV('UP', 10)\r\n elif center[1] > 280:\r\n PID_controlAUV('DOWN', 10)\r\n\r\n if 280 < center[0] < 360 and 200 < center[1] < 280 and COUNT('count5'):\r\n PID_controlAUV('go', 30)\r\n else:\r\n if COUNT('count1'):\r\n PID_controlAUV('right', 25)\r\n\r\n#开抓球标志位\r\ndef to_ball():\r\n #### 修改部分\r\n global ball_flag\r\n print('yes!')\r\n ball_flag = True\r\n\r\n\r\n\r\n#从MCU读取陀螺仪姿态参数\r\n# yaw:偏转角\r\ndef read_fromMCU():\r\n msg = ser.read(3)\r\n yaw = msg[2]\r\n return yaw\r\n\r\n#跟踪球PID函数\r\n#球所在位置的y坐标\r\n#改变力度\r\ndef pid_ballx(feedback):\r\n pid0.update(feedback_value=feedback)\r\n output = pid0.output\r\n return output\r\n\r\n\r\n#跟踪球PID函数\r\n#球所在位置的y坐标\r\n#改变力度\r\ndef pid_bally(feedback):\r\n pid1.update(feedback_value=feedback)\r\n output = pid1.output\r\n return output\r\n\r\ndef pid_lineturn(feedback):\r\n pid2.update(feedback_value=feedback)\r\n output = pid2.output\r\n return output\r\n\r\ndef pid_rectx(feedback):\r\n pid3.update(feedback_value=feedback)\r\n output = pid3.output\r\n return output\r\n\r\ndef pid_recty(feedback):\r\n pid4.update(feedback_value=feedback)\r\n output = pid4.output\r\n return output\r\n\r\n\r\n# camera = PiCamera()\r\n# camera.resolution = (640,480)\r\n# camera.framerate = 32\r\n# rawCapture = PiRGBArray(camera, size=(640,480))\r\n\r\n\r\ncap = cv2.VideoCapture(0) # 下置摄像头\r\ncap.set(3, 640) # 设置分辨率\r\ncap.set(4, 480)\r\n\r\ncap1 = cv2.VideoCapture(1) # 前置摄像头\r\ncap1.set(3, 640) # 设置分辨率\r\ncap1.set(4, 480)\r\n\r\n#跟踪球PID实例化\r\npid0 = PID(P0,I0,D0)\r\npid0.SetPoint=320\r\npid0.setSampleTime(0.5)\r\n\r\n#跟踪球PID实例化\r\npid1 = PID(P1,I1,D1)\r\npid1.SetPoint=240\r\npid1.setSampleTime(0.5)\r\n\r\n#调整线PID实例化\r\npid2 = PID(P2,I2,D2)\r\npid2.SetPoint=0\r\npid2.setSampleTime(0.5)\r\n\r\n#对框PIDx实例化\r\npid3 = PID(P3,I3,D3)\r\npid3.SetPoint=320\r\npid3.setSampleTime(0.5)\r\n\r\n#对框PIDy实例化\r\npid4 = PID(P4,I4,D4)\r\npid4.SetPoint=240\r\npid4.setSampleTime(0.5)\r\n\r\n#初始模式为“寻找模式”\r\nMODEL_section_flag = 'SEARCH'\r\n\r\n#AUV定深下沉准备\r\n# time.sleep(20)\r\nser.write(b'\\xaa\\x55\\x03\\x0c\\x35\\x02')\r\ntime.sleep(5)\r\n\r\nif __name__ == \"__main__\":\r\n rush_ball_time = 5\r\n timer = threading.Timer(60 * rush_ball_time, to_ball) # 设置时钟。根据rush_ball_time变量以判断是否进入撞球部分\r\n timer.start()\r\n while True:\r\n ret1, frame1 = cap.read() #画面读取\r\n ret0, frame0 = cap1.read()\r\n if ball_flag:\r\n Catch_ball(frame0, frame1)\r\n if rush_ball_flag:\r\n Rush_ball(frame0, frame1)\r\n break_flag = Break_flag()\r\n else: #模式选择\r\n if MODEL_section_flag=='SEARCH':\r\n print('SEARCH')\r\n SEARCH_enable,break_flag = SEARCH_MODEL(frame0,frame1)\r\n if SEARCH_enable:\r\n MODEL_section_flag = 'ADJUST'\r\n elif MODEL_section_flag=='ADJUST':\r\n print('ADJUST')\r\n ADJUST_enable,break_flag = ADJUST_MODEL(frame0,frame1)\r\n if ADJUST_enable:\r\n MODEL_section_flag='CROSS'\r\n elif MODEL_section_flag=='CROSS':\r\n print('CROSS')\r\n corss_Rect_flag, CROSS_count_flag, break_flag = CROSS_MODEL(frame0, frame1)\r\n if corss_Rect_flag:\r\n crossed_count = crossed_count + 1\r\n MODEL_section_flag='SEARCH'\r\n if CROSS_count_flag:\r\n MODEL_section_flag='SEARCH'\r\n\r\n Odometer(model,AUV_dx,AUV_dy,AUV_dtheta,dl,dr)\r\n break_flag = Break_flag()\r\n\r\n\r\n if break_flag:\r\n break\r\n\r\n\r\n cv2.destroyAllWindows()\r\n sys.exit()" }, { "alpha_fraction": 0.4740992486476898, "alphanum_fraction": 0.5163639783859253, "avg_line_length": 27.986604690551758, "blob_id": "2b5b80ca011140b4766674b1fa9f5f48d100051d", "content_id": "901d256181307a120033362163288d60c8f0bb81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 54771, "license_type": "no_license", "max_line_length": 160, "num_lines": 1717, "path": "/AUV_4_1_1.temp.py", "repo_name": "JMUETA/Autonomous-Underwater-Vehicle", "src_encoding": "UTF-8", "text": "# title :AUV_3_2.py\r\n# description :AUV巡游系统(摄像头切换版待测试)\r\n# author :Fatih and Chen YiLin\r\n# date :2019.8.3\r\n# version :0.3\r\n# notes :树莓派\r\n# python_version :3.6\r\n\r\n\r\nfrom picamera.array import PiRGBArray\r\nfrom picamera import PiCamera\r\nimport time\r\nimport cv2\r\nimport logging\r\nimport sys\r\nimport numpy as np\r\nimport serial\r\nimport threading\r\nfrom collections import deque\r\nfrom scipy.spatial import distance as dist\r\nfrom collections import OrderedDict\r\n\r\nfrom imutils.video import VideoStream\r\nimport imutils\r\n# import thread\r\n\r\n\r\nvs = VideoStream(usePiCamera=True).start()\r\ntime.sleep(2.0)\r\n\r\ncap1 = cv2.VideoCapture(0) # 前置摄像头\r\ncap1.set(3, 640) # 设置分辨率\r\ncap1.set(4, 480)\r\n\r\n\r\n#寻球PID参数\r\nP0 = 0.1\r\nI0 = 0.01\r\nD0 = 0.005\r\n#寻球PID参数\r\nP1 = 0.1\r\nI1 = 0.01\r\nD1 = 0.005\r\n#转线PID参数\r\nP2 = 0.01\r\nI2 = 0.01\r\nD2 = 0.005\r\n#对框PID参数\r\nP3 = 0.1\r\nI3 = 0.01\r\nD3 = 0.005\r\n#对框PID参数\r\nP4 = 0.1\r\nI4 = 0.01\r\nD4 = 0.005\r\n\r\n#摄像头计数器\r\n#摄像头标志位\r\ncamera_count = 0\r\ncamera_flag = 0\r\n\r\n#寻球可能所在的参考坐标,给予AUV一个大致的开始寻找方向\r\nReference_coor = (150,350)\r\n\r\n#指令发送计数器\r\norder_count1 = 0\r\norder_count2 = 10\r\norder_count3 = 20\r\norder_count4 = 30\r\norder_count5 = 0\r\ncount_max1 = 30\r\ncount_max2 = 35\r\ncount_max3 = 40\r\ncount_max4 = 45\r\ncount_max5 = 5\r\n\r\n#框的数量\r\nRect_num = 5\r\n\r\n#线计数器\r\nline_count = 0\r\n\r\n#记录已经过的框\r\ncrossed_count = 0\r\n\r\n#中点两边边界\r\nleft_min = 280\r\nright_max = 360\r\n\r\n#引导线转动参数\r\nguide_line_enable_lower = -0.2\r\nguide_line_enable_higher = 0.2\r\n\r\n\r\n#模式计数器\r\nSEARCH_count = 0 #寻找模式\r\nSEARCH_count_max = 400\r\nSEARCH_count_time = 0\r\nSEARCH_count_time_max = 4\r\n\r\nADJUST_count = 0 #调整模式\r\nADJUST_count_max = 400\r\nADJUST_count_time = 0\r\nADJUST_count_time_max = 4\r\n\r\nCROSS_count = 0 #调整模式\r\nCROSS_count_max = 100\r\n\r\n\r\n#miniArea噪声抑制程度,越大识别框的能力越低。准确性越高\r\ncnts2_area = 15000\r\ncntsl0_area = 50\r\ncntsr0_area = 50\r\n\r\n#框信任度最大方差之\r\nvar_maxvalue = 40000\r\n\r\n# AUV测框的距离参数\r\nFORCAL = 600 # 距离函数设定的焦距,为定值\r\nKnow_Distance = 30.0 # 已知距离(定值)\r\nKnow_Width = 25.2\r\n\r\ndata_count = 0 # 框信任度,存储历史数据的计数器\r\ncX_container = []\r\nminAreax_container = []\r\n\r\n# AUV位置列表,分别记录AUV的x,y,theta最大存储400个位置数据\r\nx0 = deque(maxlen=400)\r\ny0 = deque(maxlen=400)\r\ntheta0 = deque(maxlen=400)\r\nx0.appendleft(0)\r\ny0.appendleft(0)\r\ntheta0.appendleft(0)\r\n\r\n\r\nRect_point = []\r\nLine_point = []\r\n\r\n\r\n# 差速模型接口\r\n# 暂定的AUV结构参数\r\n# b : AUV宽度\r\n# dl,dr : 左右推进器一次推进器前进距离\r\nb = 0.5\r\ndl = 0\r\ndr = 0\r\nAUV_dx = 0 #未给出\r\nAUV_dy = 0\r\nAUV_dtheta = 0\r\nSL = 0\r\nSR = 0\r\nmodel = 'diff'\r\n\r\n# 无目标信任度计数参数\r\nCount = 0\r\nCount1 = 0\r\nK_COUNT = 0\r\nX_COUNT = 0\r\n\r\n# AUV检测球参数\r\nbuff = 64\r\nballLower = (29, 86, 6)\r\nballUpper = (64, 255, 255)\r\npts = deque(maxlen=buff)\r\n\r\n\r\n#颜色抑制阈值,加一层颜色阈值提高图像分割去除噪声的能力\r\nred_lower = 0\r\ngreen_lower = 50\r\nbule_lower = 60\r\nred_higher = 255\r\ngreen_higher = 150\r\nbule_higher = 150\r\ncolor = [([red_lower, green_lower, bule_lower], [red_higher, green_higher, bule_higher])]\r\n\r\nred_lower_d = 0\r\ngreen_lower_d = 50\r\nbule_lower_d = 60\r\nred_higher_d = 255\r\ngreen_higher_d = 150\r\nbule_higher_d = 150\r\ncolor_d = [([red_lower_d, green_lower_d, bule_lower_d], [red_higher_d, green_higher_d, bule_higher_d])]\r\n\r\n#框、线信任\r\nRect_Tarnum = False\r\nLine_Tarnum = False\r\n\r\n# AUV标志位\r\n#Trunum信任度标志位\r\n#Tarnum目标标志位\r\nTrunum = None\r\nTarnum = 2\r\n\r\nm = 0\r\nball_flag = False\r\n\r\nturn_count = 0\r\n\r\n#串口通信接口\r\nportx = '/dev/ttyUSB0'\r\nbps = 115200\r\ntimex = 0.01\r\n\r\ntry:\r\n ser = serial.Serial( '/dev/ttyUSB0', bps, timeout=timex)\r\nexcept Exception as e:\r\n ser = serial.Serial( '/dev/ttyUSB1', bps, timeout=timex)\r\n\r\n# portx1 = '/dev/ttyUSB2'\r\n# bps1 = 115200\r\n# ser1 = serial.Serial(portx1, bps1, timeout=timex)\r\n\r\n\r\ndef camera_switch():\r\n global camera_count\r\n global camera_flag\r\n camera_count = camera_count + 1\r\n cv2.waitKey(1)\r\n if camera_count <= 100:\r\n camera_flag = 0 #下置标志位为0,前置标志位为1\r\n frame = vs.read()\r\n frame = imutils.resize(frame, width=640)\r\n else:\r\n camera_flag = 1\r\n ret0, frame = cap1.read()\r\n if camera_count > 150: # 1-100帧为下置摄像头,100-200为前置摄像头\r\n camera_count = 0\r\n return camera_flag, frame\r\n\r\n\r\n\r\n#分水岭图像分割函数\r\n# 用于二值化图像,分割出所需要的内容\r\ndef get_fg_from_hue_watershed_saturation(img, margin):\r\n mask, hue = get_fg_from_hue(img, margin)\r\n\r\n mask_bg = cv2.inRange(hue, 60, 90)\r\n mask_bg = cv2.bitwise_or(mask_bg, cv2.inRange(hue, 128, 129))\r\n\r\n markers = np.zeros(mask.shape, np.int32)\r\n markers[mask == 255] = 1\r\n markers[mask_bg == 255] = 2\r\n\r\n cv2.watershed(img, markers)\r\n mask[markers == 1] = 255\r\n\r\n # img2 = img.copy()\r\n # img2[markers == 1] = 255\r\n # cv.imshow(\"1\", img2)\r\n #\r\n # img2 = img.copy()\r\n # img2[markers == 2] = 255\r\n # cv.imshow(\"2\", img2)\r\n #\r\n # img2 = img.copy()\r\n # img2[markers == -1] = 255\r\n # cv.imshow(\"3\", img2)\r\n\r\n return mask\r\n\r\n#HSV处理函数\r\ndef get_fg_from_hue(img, margin):\r\n FRACTION_AS_BLANK = 0.003\r\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\r\n\r\n dark = hsv[..., 2] < 32\r\n hsv[..., 0][dark] = 128\r\n\r\n dark = hsv[..., 1] < 50\r\n hsv[..., 0][dark] = 128\r\n\r\n mask = cv2.inRange(hsv[..., 0], np.array((0)), np.array((margin)))\r\n mask2 = cv2.inRange(hsv[..., 0], np.array((180 - margin)), np.array((180)))\r\n\r\n mask = cv2.bitwise_or(mask, mask2)\r\n\r\n if cv2.countNonZero(mask) < mask.shape[0] * mask.shape[1] * FRACTION_AS_BLANK:\r\n mask.fill(0)\r\n\r\n return [mask, hsv[..., 0]]\r\n\r\n\r\n#引导线检测函数\r\ndef guide_line_detect(mask, area_th=5000, aspect_th=0.8):\r\n '''\r\n\r\n TODO:部分时候很靠近边框时,会检测到框\r\n :param img:\r\n :param area_th:\r\n :param aspect_th:\r\n :return:\r\n '''\r\n ASPECT_RATIO_MIN = 0.15 # 重要参数\r\n MAX_CONTOUR_NUM = 6 # 如果出现更多的轮廓,不进行处理。这是为了对抗白平衡\r\n\r\n _, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n # 目前对自动白平衡的处理,太多轮廓则直接返回\r\n candidates = []\r\n candidates_y = []\r\n if len(contours) < MAX_CONTOUR_NUM:\r\n for cnt in contours:\r\n area = cv2.contourArea(cnt)\r\n if area > area_th: # 关键参数\r\n (x1, y1), (w1, h1), angle1 = cv2.minAreaRect(cnt)\r\n minAreaRect_area = w1 * h1\r\n aspect_ratio = float(w1) / h1\r\n if aspect_ratio > 1:\r\n aspect_ratio = 1.0 / aspect_ratio\r\n angle1 = np.mod(angle1 + 90, 180)\r\n\r\n extent = float(area) / minAreaRect_area\r\n\r\n hull = cv2.convexHull(cnt)\r\n hull_area = cv2.contourArea(hull)\r\n solidity = float(area) / hull_area\r\n\r\n (x2, y2), (MA, ma), angle2 = cv2.fitEllipse(cnt)\r\n if angle2 > 90:\r\n angle2 -= 180\r\n\r\n logging.debug('area %f,aspect_ratio %f,extent %f,solidity %f,angle1 %f,angle2 %f' % (\r\n area, aspect_ratio, extent, solidity, angle1, angle2))\r\n\r\n if aspect_ratio > aspect_th or aspect_ratio < ASPECT_RATIO_MIN or extent < 0.7 or solidity < 0.7 or abs(\r\n angle1 - angle2) > 30:\r\n break\r\n\r\n # img2 = img.copy()\r\n # contour_info(img2,area,aspect_ratio,extent,solidity,angle1,angle2,((x2, y2), (MA, ma), angle2))\r\n # cv.drawContours(img2, [cnt], 0, (0, 255, 0), 3)\r\n # show_img(img2)\r\n\r\n candidates.append((x1, y1, angle2)) # 目前这个组合是比较好的。\r\n candidates_y.append(y1)\r\n\r\n nc = len(candidates)\r\n if nc == 0:\r\n return None\r\n elif nc == 1:\r\n return candidates[0]\r\n else:\r\n logging.debug('multiple')\r\n\r\n idx = np.argmax(np.array(candidates_y))\r\n return candidates[idx]\r\n\r\n\r\n#检测框距离函数\r\ndef distance_to_camera(width, forcal, perwidth): # 距离计算\r\n return ((width * forcal) * 0.3048) / (12 * perwidth)\r\n\r\n\r\n#角度转弧度函数\r\ndef angle2rad(theta):\r\n w = (theta * np.pi) / 180\r\n return w\r\n\r\n\r\n#AUV控制,通信协议(2019版)\r\ndef PID_controlAUV(od_r,output):\r\n global model,dl,dr\r\n global AUV_dx,AUV_dy,AUV_dtheta\r\n head = [0xaa, 0x55, 0x10]\r\n depth_lock_bit = [0x01]\r\n dir_lock_bit = [0x01]\r\n forword_back_bit = [0x00]\r\n left_right_bit = [0x00]\r\n up_down_bit = [0x00]\r\n rotation_bit = [0x00]\r\n power_value = [output]\r\n other_bit = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]\r\n start_stop_bit = [0x00]\r\n # \\xaa\\x55\\x10\\x02\\x01\\x00\\x00\\x32\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\r\n\r\n if od_r == 'go':\r\n dir_lock_bit = [0x02]\r\n forword_back_bit = [0x01]\r\n start_stop_bit = [0x01]\r\n model = 'diff'\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = 0.2, 0.2, 0, 0, 0\r\n print('go')\r\n if od_r == 'back':\r\n dir_lock_bit = [0x02]\r\n forword_back_bit = [0x02]\r\n start_stop_bit = [0x01]\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = -0.2, -0.2, 0, 0, 0\r\n print('back')\r\n\r\n if od_r == 'left_translation': # 左平移\r\n dir_lock_bit = [0x02]\r\n left_right_bit = [0x02]\r\n start_stop_bit = [0x01]\r\n model = 'trans'\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = 0, 0, -0.2, 0, 0\r\n print('left_translation')\r\n if od_r == 'right_translation': # 右平移\r\n dir_lock_bit = [0x02]\r\n left_right_bit = [0x01]\r\n start_stop_bit = [0x01]\r\n model = 'trans'\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = 0, 0, 0.2, 0, 0\r\n print('right_translation')\r\n if od_r == 'left': # 左旋转\r\n dir_lock_bit = [0x02]\r\n rotation_bit = [0x02]\r\n start_stop_bit = [0x01]\r\n model = 'dtheta'\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = 0, 0, 0, 0, 0.5\r\n print('left')\r\n if od_r == 'right': # 右旋转\r\n dir_lock_bit = [0x02]\r\n rotation_bit = [0x01]\r\n start_stop_bit = [0x01]\r\n model = 'dtheta'\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = 0, 0, 0, 0, -0.5\r\n print('right')\r\n if od_r == 'up':\r\n depth_lock_bit = [0x02]\r\n up_down_bit = [0x01]\r\n start_stop_bit = [0x01]\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = 0, 0, 0, 0, 0\r\n print('up')\r\n if od_r == 'down':\r\n depth_lock_bit = [0x02]\r\n up_down_bit = [0x02]\r\n start_stop_bit = [0x01]\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = 0, 0, 0, 0, 0\r\n print('down')\r\n if od_r == 'stop':\r\n start_stop_bit = [0x00]\r\n dl, dr, AUV_dx, AUV_dy, AUV_dtheta = 0, 0, 0, 0, 0\r\n print('stop')\r\n\r\n parameter = head + depth_lock_bit + dir_lock_bit + forword_back_bit + left_right_bit + up_down_bit + rotation_bit + power_value + other_bit + start_stop_bit\r\n check_sum = sum(parameter)\r\n check_sum = [check_sum & 255]\r\n\r\n msg = parameter + check_sum\r\n msg = bytearray(msg)\r\n try:\r\n ser.write(msg)\r\n except Exception as e:\r\n print(\"--异常--:\", e)\r\n\r\n return model, dl, dr, AUV_dx, AUV_dy, AUV_dtheta\r\n\r\n\r\n#通信协议(2018版)\r\n# def PID_controlAUV(od_r,output):\r\n# global model,AUV_dx,AUV_dy,AUV_dtheta,dl,dr\r\n# print(output)\r\n# head_bit = [0xaa,0x55] # 两个字节为包头\r\n# length_bit = [0x03] #数据长度\r\n# follow_bit = [0x08] #用来选择三种模式\r\n# control_bit = [0x00] # 控制字节有效值:0-255\r\n# time_level_bit = [0x00] # 高四位为推进器动作时间,低四位为推进器推力的级数\r\n#\r\n# print(od_r)\r\n#\r\n# if od_r=='ball_down':\r\n# follow_bit = [0x08]\r\n# control_bit = [1+output]\r\n# time_level_bit = [0x12]\r\n#\r\n# if od_r=='ball_up':\r\n# follow_bit = [0x08]\r\n# control_bit = [222+output]\r\n# if control_bit[0]>=255:\r\n# control_bit = [255]\r\n# time_level_bit = [0x12]\r\n#\r\n# if od_r == 'left_translation': #左平移\r\n# follow_bit = [0x08]\r\n# control_bit = [34+output]\r\n# time_level_bit = [0x12]\r\n# model = 'trans'\r\n# AUV_dx, AUV_dy, AUV_dtheta, dl, dr = -0.01*output/30, 0, 0, 0, 0 #提供给里程表参数待修改\r\n# elif od_r == 'right_translation': #右平移\r\n# follow_bit = [0x08]\r\n# control_bit = [127+output]\r\n# time_level_bit = [0x12]\r\n# model = 'trans'\r\n# AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0.01 * output/30, 0, 0, 0, 0 #提供给里程表参数待修改\r\n#\r\n# if od_r == 'left': #左旋转\r\n# follow_bit = [0x08]\r\n# control_bit = [90+output]\r\n# time_level_bit = [0x22]\r\n# model = 'dtheta'\r\n# AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, 0.026, 0, 0 # 提供给里程表参数待修改\r\n# if od_r == 'right': #右旋转\r\n# follow_bit = [0x08]\r\n# control_bit = [175+output]\r\n# time_level_bit = [0x22]\r\n# model = 'dtheta'\r\n# AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, -0.026, 0, 0 # 提供给里程表参数待修改\r\n#\r\n# if od_r == 'go':\r\n# follow_bit = [0x08]\r\n# control_bit = [0xe6]\r\n# time_level_bit = [0x34]\r\n# model = 'diff'\r\n# AUV_dx, AUV_dy, AUV_dtheta, dl, dr = 0, 0, 0, 0.2/30, 0.2/30 # 提供给里程表参数待修改\r\n#\r\n# parameter = head_bit + length_bit + follow_bit + control_bit + time_level_bit\r\n# check_sum = sum(parameter)\r\n# check_sum = [check_sum & 255]\r\n# msg = parameter + check_sum\r\n#\r\n# msg = bytearray(msg)\r\n# try: # 发送串口指令 与单片机通信\r\n# ser.write(msg)\r\n# except Exception as e:\r\n# print(\"--异常--:\", e)\r\n#\r\n# return model,AUV_dx,AUV_dy,AUV_dtheta,dl,dr\r\n\r\n\r\n\r\n#识别到引导线时的转向决策\r\ndef guide_line_turn(data):\r\n global guide_line_enable_lower, guide_line_enable_higher\r\n x = data[0]\r\n y = data[1]\r\n angle = data[2]\r\n if x < 250 and COUNT('count5'):\r\n output = pid_ballx(x)\r\n output = int(abs(output*0.2))\r\n PID_controlAUV('left_translation',output)\r\n elif x > 390 and COUNT('count5'):\r\n output = pid_ballx(x)\r\n output = int(abs(output*0.2))\r\n PID_controlAUV('right_translation',output)\r\n elif x >= 250 and x <= 390 and COUNT('count5'):\r\n if (guide_line_enable_lower < angle) and angle < guide_line_enable_higher:\r\n PID_controlAUV('go', 30) #待修改\r\n elif angle < guide_line_enable_lower:\r\n output = pid_lineturn(angle)\r\n output = int(abs(output*0.2))\r\n PID_controlAUV('left',output)\r\n elif angle > guide_line_enable_higher:\r\n output = pid_lineturn(angle)\r\n output = int(abs(output*0.2))\r\n PID_controlAUV('right',output)\r\n elif y < 180 and COUNT('count5'):\r\n output = pid_bally(y)\r\n output = int(abs(output * 0.02))\r\n PID_controlAUV('go', output)\r\n\r\n\r\n#是否要往Rect_point添加参数\r\n#若当前过框坐标已经记录,则无需重复记录\r\ndef add_judege(X, Y):\r\n now_point = [X, Y]\r\n itertime = len(Rect_point)\r\n if itertime < 1:\r\n return True\r\n for i in range(itertime):\r\n dis = np.sqrt(np.sum(np.square(Rect_point[i] - now_point)))\r\n if dis < 1:\r\n return False\r\n return True\r\n\r\n#向Rect_point添加框坐标\r\ndef Add_Rect_point(auv_local, metre, yaw, cX, Rect_width):\r\n bias = (0.6 * (cX - 160)) / Rect_width\r\n X = auv_local[0] + metre * np.cos(yaw) + bias\r\n Y = auv_local[1] + metre * np.sin(yaw)\r\n flag = add_judege(X, Y)\r\n now_point = [X, Y]\r\n if flag:\r\n Rect_point.append(now_point)\r\n\r\n#向Line_point添加线坐标\r\ndef Add_Line_point(auv_local):\r\n X = auv_local[-1][0]\r\n Y = auv_local[-1][1]\r\n flag = add_judege(X, Y)\r\n now_point = [X, Y]\r\n if flag:\r\n Line_point.append(now_point)\r\n\r\n\r\n#图像预处理,将RGB图像转换成二值化图像\r\ndef Frame_Preprocess(frame, camera_flag):\r\n if camera_flag == 1:\r\n # for (lower, upper) in color:\r\n # lower = np.array(lower, dtype=\"uint8\")\r\n # upper = np.array(upper, dtype=\"uint8\")\r\n # mask0 = cv2.inRange(frame, lower, upper)\r\n # mask0 = cv2.bitwise_not(mask0)\r\n # output0 = cv2.bitwise_and(frame, frame, mask=mask0)\r\n thresh = get_fg_from_hue_watershed_saturation(frame, 20)\r\n thresh = cv2.medianBlur(thresh, 5)\r\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # 形态学开运算,简单滤除离框较远的干扰\r\n thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)\r\n return thresh\r\n\r\n if camera_flag == 0:\r\n # for (lower, upper) in color_d:\r\n # lower = np.array(lower, dtype=\"uint8\")\r\n # upper = np.array(upper, dtype=\"uint8\")\r\n # mask1 = cv2.inRange(frame, lower, upper)\r\n # mask1 = cv2.bitwise_not(mask1)\r\n # output0 = cv2.bitwise_and(frame, frame, mask=mask1)\r\n cv2.boxFilter(frame, -1, (5, 5), frame)\r\n thresh = get_fg_from_hue_watershed_saturation(frame, 20)\r\n return thresh\r\n\r\n\r\n#目标识别,用于识别框线\r\n#thresh0:前置摄像头二值化图像 frame0:前置摄像头图像\r\n#Rect_Tarnum:是否识别到了框 data:框中点(cX,cY),外接矩形数据,框距离吗,外接矩形四点坐标\r\ndef Rect_Target_recognition(thresh,frame):\r\n global cX\r\n Rect_Tarnum = False #未识别\r\n data = None\r\n cnts2 = []\r\n _, cnts3, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # findContours寻找轮廓\r\n for cnt in cnts3:\r\n area = cv2.contourArea(cnt)\r\n if area > cnts2_area:\r\n cnts2.append(cnt)\r\n if not (cnts2 == []):\r\n for c_3 in cnts2:\r\n M = cv2.moments(c_3) # 求图形的矩\r\n cX = int((M[\"m10\"] + 1) / (M[\"m00\"] + 1))\r\n cY = int((M[\"m01\"] + 1) / (M[\"m00\"] + 1))\r\n\r\n if not (cnts2 == []):\r\n c = max(cnts2, key=cv2.contourArea)\r\n marker = cv2.minAreaRect(c) # 得到最小外接矩形(中心(x,y),(宽,高),选住角度)\r\n metre = distance_to_camera(Know_Width, FORCAL, marker[1][0] + 1) # 距离摄像头距离\r\n box = cv2.boxPoints(marker) # 获取最小外接矩形的四个顶点\r\n box = np.int0(box)\r\n cv2.drawContours(frame, [box], -1, (0, 255, 0), 2)\r\n cv2.putText(frame, \"%.2fm\" % (metre), (frame.shape[1] - 200, frame.shape[0] - 20),\r\n cv2.FONT_HERSHEY_SIMPLEX,\r\n 2.0, (0, 255, 0), 3)\r\n Rect_Tarnum = True\r\n data = [cX,cY,marker, metre, box]\r\n return Rect_Tarnum, data, frame\r\n return Rect_Tarnum,data,frame\r\n\r\n\r\n\r\n#识别线目标\r\n#thresh1:下置摄像头二值化图像,frame1:下置摄像头图像\r\n#Line_Tarnum:是否识别到了线,data:线上的两个坐标(x1,y1),线与AUV夹角angle,先的四点坐标\r\ndef Line_Target_recognition(thresh,frame):\r\n data = None\r\n guide_line = guide_line_detect(thresh) # 检测下置摄像头是否读到引导线\r\n Line_Tarnum = False\r\n if guide_line:\r\n\r\n # 发现引导线,停一下\r\n x, y, angle = guide_line\r\n angle = angle / 180 * np.pi\r\n cv2.line(frame, (int(x), int(y)), (int(x + 100 * np.sin(angle)), int(y - 100 * np.cos(angle))),\r\n (0, 255, 0), 2)\r\n x1 = int(x + 100 * np.sin(angle))\r\n y1 = int(y - 100 * np.cos(angle))\r\n Line_Tarnum = True\r\n data = [x1, y1, angle]\r\n return Line_Tarnum, data, frame\r\n return Line_Tarnum, data, frame\r\n\r\n\r\n\r\n#框信任度判断\r\ndef Rect_Trust(data):\r\n if data is not None:\r\n cX = data[0]\r\n marker = data[1]\r\n minArea_x = marker\r\n cX_container.append(cX)\r\n minAreax_container.append(marker)\r\n if cX - minArea_x > 50:\r\n return 0\r\n if len(cX_container) >= 5 and len(minAreax_container) >= 5:\r\n var_cX = np.var(cX_container)\r\n var_min = np.var(minAreax_container)\r\n # cv2.putText(frame, \"%.2f\" % (var_cX), (frame.shape[1] - 200, frame.shape[0] - 20),\r\n # cv2.FONT_HERSHEY_SIMPLEX,\r\n # 2.0, (0, 255, 0), 3)\r\n if var_cX < var_maxvalue and var_min < var_maxvalue: # 方差,待测量\r\n return 1\r\n else:\r\n return 0\r\n return 2\r\n\r\n# 无目标信任度\r\ndef Estate(flag):\r\n global Count\r\n global C_L_COUNT\r\n global Est\r\n global Tarnum\r\n Count = Count + 1\r\n if flag == 0: # 不信任框\r\n Est = 1\r\n if flag == 2: # 无框 无线\r\n Est = 2\r\n if flag == 1: # 有线\r\n Est = 3\r\n\r\n if Est == 2:\r\n C_L_COUNT = C_L_COUNT + 1 # 无框则加一\r\n if Est == 1:\r\n C_L_COUNT = C_L_COUNT + 1\r\n\r\n if Count == 10:\r\n if C_L_COUNT >= 10:\r\n Tarnum = 2\r\n return True\r\n Count = 0\r\n C_L_COUNT = 0 # 10次后清零\r\n\r\n elif Count < 10:\r\n return 0\r\n\r\n\r\n\r\n#里程表记录函数\r\ndef Odometer(model,AUV_dx,AUV_dy,AUV_dtheta,dl,dr): #里程表\r\n global x0\r\n global y0\r\n global theta0\r\n if model=='diff': #差速模式\r\n x = x0[0]\r\n y = y0[0]\r\n theta = theta0[0]\r\n ddx = (dr+dl)*np.cos(theta+(dr-dl)/2*b)/2\r\n ddy = (dr+dl)*np.sin(theta+(dr-dl)/2*b)/2\r\n dtheta = (dr-dl)/b\r\n x1 = x + ddx\r\n y1 = y + ddy\r\n theta1 = theta + dtheta\r\n x0.appendleft(x1)\r\n y0.appendleft(y1)\r\n theta0.appendleft(theta1)\r\n elif model =='dtheta':\r\n x1 = x0[0]\r\n y1 = y0[0]\r\n theta = theta0[0]\r\n dtheta = AUV_dtheta\r\n theta1 = theta + dtheta\r\n x0.appendleft(x1)\r\n y0.appendleft(y1)\r\n theta0.appendleft(theta1)\r\n else: #平移模式\r\n x = x0[0]\r\n y = y0[0]\r\n theta = theta0[0]\r\n dx = AUV_dx * np.cos(theta)\r\n dy = AUV_dy * np.sin(theta)\r\n x1 = x + dx\r\n y1 = y + dy\r\n x0.appendleft(x1)\r\n y0.appendleft(y1)\r\n theta0.appendleft(theta)\r\n return 0\r\n\r\n\r\ndef Turn():\r\n global turn_count\r\n turn_count = turn_count + 1\r\n if turn_count == 1:\r\n PID_controlAUV('right',5)\r\n if turn_count == 2:\r\n PID_controlAUV('go',5)\r\n if turn_count == 3:\r\n PID_controlAUV('left',5)\r\n if turn_count == 4:\r\n PID_controlAUV('go',5)\r\n turn_count = 0\r\n\r\n\r\n#无目标情况下的位置检测\r\ndef search(x, y, theta):\r\n global x1\r\n global x2\r\n global y1\r\n global y2\r\n global SR\r\n global SL\r\n k = np.tan(theta)\r\n b1 = y - k * x\r\n\r\n Wide = 3.66\r\n Long = 7.3\r\n\r\n if 0.9 <= np.cos(theta) <= 1: # k=0的情况\r\n if 0 <= b1 < Long * 0.5:\r\n return 'left'\r\n if Long * 0.5 <= b1 <= Long:\r\n return 'right'\r\n elif -1 <= np.cos(theta) <=-0.9:\r\n if 0 <= b1 < Long * 0.5:\r\n return 'right'\r\n if Long * 0.5 <= b1 <= Long:\r\n return 'left'\r\n\r\n elif 0 <= x <= 0.1 and 0 <= y <= 0.1 and 0 <= theta <= 0.1:\r\n return 'left'\r\n\r\n else:\r\n if 0 <= b1 <= Long: # 左边交点Y轴上(三种情况)\r\n x1 = 0\r\n y1 = b1\r\n if 0 <= (Long - b1) / k <= Wide:\r\n x2 = (Long - b1) / k\r\n y2 = Long\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SL = x1 * y2 + (x2 - x1) * (y2 - y1) / 2\r\n SR = Long * Wide - SL\r\n if np.cos(theta) <= 0: # 船头方向朝左\r\n SR = x1 * y2 + (x2 - x1) * (y2 - y1) / 2\r\n SL = Long * Wide - SR\r\n elif 0 <= (Wide * k + b1) <= Long:\r\n x2 = Wide\r\n y2 = (Wide * k + b1)\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SR = x1 * y1 + x2 * y2 - x1 * y2 + (x2 - x1) * (y1 - y2) / 2\r\n SL = Long * Wide - SR\r\n elif np.cos(theta) <= 0: # 船头方向朝左\r\n SL = x1 * y1 + x2 * y2 - x1 * y2 + (x2 - x1) * (y1 - y2) / 2\r\n SR = Long * Wide - SL\r\n elif 0 <= (-b1 / k) <= Wide:\r\n x2 = -b1 / k\r\n y2 = 0\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SR = x2 * y1\r\n SL = Long * Wide - SR\r\n elif np.cos(theta) <= 0: # 船头方向朝左\r\n SL = x2 * y1\r\n SR = Long * Wide - SL\r\n elif 0 <= (Wide * k + b1) <= Long: # 右边交点在x=3.66上(三减一 种情况)\r\n x2 = Wide\r\n y2 = (Wide * k + b1)\r\n if 0 <= (Long - b1) / k <= Wide:\r\n x1 = (Long - b1) / k\r\n y1 = Long\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SR = x1 * y1 + x2 * y2 - x1 * y2 + (x2 - x1) * (y1 - y2) / 2\r\n SL = Long * Wide - SR\r\n elif np.cos(theta) <= 0: # 船头方向朝左\r\n SL = x1 * y1 + x2 * y2 - x1 * y2 + (x2 - x1) * (y1 - y2) / 2\r\n SR = Long * Wide - SL\r\n elif 0 <= -b1 / k <= Wide:\r\n x1 = -b1 / k\r\n y1 = 0\r\n if np.cos(theta) > 0: # 船头方向朝右\r\n SR = (x2 - x1) * y2 * 0.5\r\n SL = Long * Wide - SR\r\n elif np.cos(theta) <= 0: # 船头方向朝左\r\n SL = (x2 - x1) * y2 * 0.5\r\n SR = Long * Wide - SL\r\n\r\n elif 0 <= (Long - b1) / k <= Wide and 0 <= (-b1 / k) <= Wide and k >= 0: # 两个交点在y=0和y=13上\r\n x1 = -b1 / k\r\n y1 = 0\r\n x2 = (Long - b1) / k\r\n y2 = Long\r\n if np.sin(theta) >= 0: # 船头方向朝上\r\n SL = (x1 + x2) * Long * 0.5\r\n SR = Long * Wide - SL\r\n elif np.sin(theta) <= 0: # 船头方向朝下\r\n SR = (x1 + x2) * Long * 0.5\r\n SL = Long * Wide - SR\r\n elif 0 <= (Long - b1) / k <= Wide and 0 <= -b1 / k <= Wide and k < 0:\r\n x1 = (Long - b1) / k\r\n y1 = Long\r\n x2 = -b1 / k\r\n y2 = 0\r\n if np.sin(theta) >= 0: # 船头方向朝上\r\n SL = (x1 + x2) * Long * 0.5\r\n SR = Long * Wide - SL\r\n elif np.sin(theta) <= 0: # 船头方向朝下\r\n SR = (x1 + x2) * Long * 0.5\r\n SL = Long * Wide - SR\r\n\r\n if SL > SR:\r\n return 'left'\r\n if SL < SR:\r\n return 'right'\r\n\r\n#过框模式,切换识别模式。将放行更多的噪声,以此来增加识别能力\r\ndef cross_Rect(frame):\r\n print('直走') #过框模式保持直走,再做差速调整\r\n global corss_Rect_flag\r\n global cYl\r\n global cYr\r\n global cXl\r\n global cXr\r\n corss_Rect_flag = 1\r\n\r\n cntsl = []\r\n cntsr = []\r\n framel = frame[:, 0:319]\r\n framer = frame[:, 320:640]\r\n thresh = get_fg_from_hue_watershed_saturation(frame, 20)\r\n thresh = cv2.medianBlur(thresh, 5)\r\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9)) # 形态学开运算,简单滤除离框较远的干扰\r\n thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)\r\n left_area = thresh[:, 0:319]\r\n right_area = thresh[:, 320:640]\r\n _, cntsl0, hierarchy = cv2.findContours(left_area, cv2.RETR_TREE,\r\n cv2.CHAIN_APPROX_SIMPLE)\r\n _, cntsr0, hierarchy = cv2.findContours(right_area, cv2.RETR_TREE,\r\n cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n for cnt in cntsl0:\r\n area = cv2.contourArea(cnt)\r\n if area > cntsr0_area:\r\n cntsl.append(cnt)\r\n\r\n for cnt in cntsr0:\r\n area = cv2.contourArea(cnt)\r\n if area > cntsl0_area:\r\n cntsr.append(cnt)\r\n\r\n if not (cntsl == []):\r\n for c_l in cntsl:\r\n Ml = cv2.moments(c_l) # 求图形的矩\r\n cXl = int((Ml[\"m10\"] + 1) / (Ml[\"m00\"] + 1))\r\n cYl = int((Ml[\"m01\"] + 1) / (Ml[\"m00\"] + 1))\r\n cv2.circle(framel, (cXl, cYl), 7, (0, 255, 255), -1)\r\n cv2.drawContours(framel, [c_l], -1, (0, 255, 0), 2)\r\n if not (cntsr == []):\r\n for c_r in cntsr:\r\n Mr = cv2.moments(c_r) # 求图形的矩\r\n cXr = int((Mr[\"m10\"] + 1) / (Mr[\"m00\"] + 1))\r\n cYr = int((Mr[\"m01\"] + 1) / (Mr[\"m00\"] + 1))\r\n cv2.circle(framer, (cXr, cYr), 7, (255, 255, 255), -1)\r\n cv2.drawContours(framer, [c_r], -1, (0, 255, 0), 2)\r\n\r\n if cntsl == [] and not (cntsr == []):\r\n PID_controlAUV('left',10)\r\n print('向左转1')\r\n elif not (cntsl == []) and cntsr == []:\r\n PID_controlAUV('right', 10)\r\n print('向右转1')\r\n elif not (cntsl == []) and not (cntsr == []):\r\n if abs(cYl - cYr) < 40:\r\n Y_flag = True\r\n else:\r\n Y_flag = False\r\n\r\n if Y_flag:\r\n if (cXl + cXr + 320) / 2 > 390:\r\n PID_controlAUV('left',10)\r\n print('向左转2')\r\n if (cXl + cXr + 320) / 2 < 250:\r\n PID_controlAUV('right',10)\r\n print('向右转2')\r\n if (cXl + cXr + 320) / 2 < 390 and (cXl + cXr + 320) / 2 > 250:\r\n PID_controlAUV('go', 10)\r\n print('直走')\r\n else:\r\n if cYl > cYr:\r\n PID_controlAUV('right', 10)\r\n print('向右转3')\r\n elif cYl < cYr:\r\n PID_controlAUV('left', 10)\r\n print('向左转3')\r\n\r\n elif cntsl == [] and cntsr == []:\r\n PID_controlAUV('go', 10)\r\n print('直走')\r\n\r\n\r\n\r\n#标志位计数函数\r\ndef flag_count():\r\n global data_count\r\n data_count = data_count + 1\r\n if data_count >= 5:\r\n data_count = 0\r\n\r\n\r\n#AUV球求识别函数\r\ndef Auv_ball_detect(frame):\r\n findball_flag = False\r\n blurred = cv2.GaussianBlur(frame, (11, 11), 0)\r\n hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)\r\n\r\n mask = cv2.inRange(hsv, ballLower, ballUpper)\r\n mask = cv2.erode(mask, None, iterations=2)\r\n mask = cv2.dilate(mask, None, iterations=2)\r\n cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,\r\n cv2.CHAIN_APPROX_SIMPLE)\r\n cnts = cnts[1]\r\n center = None\r\n\r\n if len(cnts) > 0:\r\n c = max(cnts, key=cv2.contourArea)\r\n ((x, y), radius) = cv2.minEnclosingCircle(c)\r\n M = cv2.moments(c)\r\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\r\n\r\n if radius > 10:\r\n cv2.circle(frame, (int(x), int(y)), int(radius),\r\n (0, 255, 0), 2)\r\n cv2.circle(frame, center, 5, (255, 255, 255), -1)\r\n findball_flag = True\r\n\r\n pts.appendleft(center)\r\n for i in range(1, len(pts)):\r\n if pts[i - 1] is None or pts[i] is None:\r\n continue\r\n\r\n thickness = int(np.sqrt(buff / float(i + 1)) * 2.5)\r\n cv2.line(frame, pts[i - 1], pts[i], (255, 0, 0), thickness)\r\n\r\n return frame,findball_flag,center\r\n\r\n\r\ndef order_points(pts):\r\n rect = np.zeros((4, 2), dtype=\"float32\")\r\n s = pts.sum(axis=1)\r\n rect[0] = pts[np.argmin(s)]\r\n rect[2] = pts[np.argmax(s)]\r\n\r\n diff = np.diff(pts, axis=1)\r\n rect[1] = pts[np.argmin(diff)]\r\n rect[3] = pts[np.argmax(diff)]\r\n\r\n return rect\r\n\r\n#框追踪类,用于追踪已经识别到的框\r\nclass CentroidTracker():\r\n def __init__(self, maxDisappeared=300):\r\n self.nextObjectID = 0\r\n self.objects = OrderedDict()\r\n self.disappeared = OrderedDict()\r\n self.maxDisappeared = maxDisappeared\r\n\r\n def register(self, centroid):\r\n self.objects[self.nextObjectID] = centroid\r\n self.disappeared[self.nextObjectID] = 0\r\n self.nextObjectID += 1\r\n\r\n def deregister(self, objectID):\r\n del self.objects[objectID]\r\n del self.disappeared[objectID]\r\n\r\n def update(self, rects):\r\n if len(rects) == 0:\r\n for objectID in self.disappeared.keys():\r\n self.disappeared[objectID] += 1\r\n if self.disappeared[objectID] > self.maxDisappeared:\r\n self.deregister(objectID)\r\n return self.objects\r\n inputCentroids = np.zeros((len(rects), 2), dtype=\"int\")\r\n\r\n for (i, (startX, startY, endX, endY)) in enumerate(rects):\r\n cX = int((startX[0] + endX[0]) / 2.0)\r\n cY = int((startY[1] + endY[1]) / 2.0)\r\n inputCentroids[i] = (cX, cY)\r\n if len(self.objects) == 0:\r\n for i in range(0, len(inputCentroids)):\r\n self.register(inputCentroids[i])\r\n else:\r\n objectIDs = list(self.objects.keys())\r\n objectCentroids = list(self.objects.values())\r\n D = dist.cdist(np.array(objectCentroids), inputCentroids)\r\n rows = D.min(axis=1).argsort()\r\n cols = D.argmin(axis=1)[rows]\r\n usedRows = set()\r\n usedCols = set()\r\n for (row, col) in zip(rows, cols):\r\n if row in usedRows or col in usedCols:\r\n continue\r\n objectID = objectIDs[row]\r\n self.objects[objectID] = inputCentroids[col]\r\n self.disappeared[objectID] = 0\r\n usedRows.add(row)\r\n usedCols.add(col)\r\n unusedRows = set(range(0, D.shape[0])).difference(usedRows)\r\n unusedCols = set(range(0, D.shape[1])).difference(usedCols)\r\n if D.shape[0] >= D.shape[1]:\r\n for row in unusedRows:\r\n objectID = objectIDs[row]\r\n self.disappeared[objectID] += 1\r\n if self.disappeared[objectID] > self.maxDisappeared:\r\n self.deregister(objectID)\r\n else:\r\n for col in unusedCols:\r\n self.register(inputCentroids[col])\r\n return self.objects\r\n\r\n#框最终函数\r\nct = CentroidTracker()\r\ndef Target_Tracking(frame, box):\r\n rects = []\r\n rects.append(box.astype(\"int\"))\r\n objects = ct.update(rects)\r\n for (objectID, centroid) in objects.items():\r\n text = \"ID {}\".format(objectID)\r\n cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\r\n cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)\r\n\r\n return frame, objectID, centroid\r\n\r\n\r\n#PID控制类\r\nclass PID:\r\n \"\"\"PID Controller\r\n \"\"\"\r\n\r\n def __init__(self, P=0.2, I=0.0, D=0.0):\r\n\r\n self.Kp = P\r\n self.Ki = I\r\n self.Kd = D\r\n\r\n self.sample_time = 0.00\r\n self.current_time = time.time()\r\n self.last_time = self.current_time\r\n\r\n self.clear()\r\n\r\n def clear(self):\r\n \"\"\"Clears PID computations and coefficients\"\"\"\r\n self.SetPoint = 0.0\r\n\r\n self.PTerm = 0.0\r\n self.ITerm = 0.0\r\n self.DTerm = 0.0\r\n self.last_error = 0.0\r\n\r\n # Windup Guard\r\n self.int_error = 0.0\r\n self.windup_guard = 20.0\r\n\r\n self.output = 0.0\r\n\r\n def update(self, feedback_value):\r\n \"\"\"Calculates PID value for given reference feedback\r\n .. math::\r\n u(t) = K_p e(t) + K_i \\int_{0}^{t} e(t)dt + K_d {de}/{dt}\r\n .. figure:: images/pid_1.png\r\n :align: center\r\n Test PID with Kp=1.2, Ki=1, Kd=0.001 (test_pid.py)\r\n \"\"\"\r\n error = self.SetPoint - feedback_value\r\n\r\n self.current_time = time.time()\r\n delta_time = self.current_time - self.last_time\r\n delta_error = error - self.last_error\r\n\r\n if (delta_time >= self.sample_time):\r\n self.PTerm = self.Kp * error\r\n self.ITerm += error * delta_time\r\n\r\n if (self.ITerm < -self.windup_guard):\r\n self.ITerm = -self.windup_guard\r\n elif (self.ITerm > self.windup_guard):\r\n self.ITerm = self.windup_guard\r\n\r\n self.DTerm = 0.0\r\n if delta_time > 0:\r\n self.DTerm = delta_error / delta_time\r\n\r\n # Remember last time and last error for next calculation\r\n self.last_time = self.current_time\r\n self.last_error = error\r\n\r\n self.output = self.PTerm + (self.Ki * self.ITerm) + (self.Kd * self.DTerm)\r\n\r\n def setKp(self, proportional_gain):\r\n \"\"\"Determines how aggressively the PID reacts to the current error with setting Proportional Gain\"\"\"\r\n self.Kp = proportional_gain\r\n\r\n def setKi(self, integral_gain):\r\n \"\"\"Determines how aggressively the PID reacts to the current error with setting Integral Gain\"\"\"\r\n self.Ki = integral_gain\r\n\r\n def setKd(self, derivative_gain):\r\n \"\"\"Determines how aggressively the PID reacts to the current error with setting Derivative Gain\"\"\"\r\n self.Kd = derivative_gain\r\n\r\n def setWindup(self, windup):\r\n \"\"\"Integral windup, also known as integrator windup or reset windup,\r\n refers to the situation in a PID feedback controller where\r\n a large change in setpoint occurs (say a positive change)\r\n and the integral terms accumulates a significant error\r\n during the rise (windup), thus overshooting and continuing\r\n to increase as this accumulated error is unwound\r\n (offset by errors in the other direction).\r\n The specific problem is the excess overshooting.\r\n \"\"\"\r\n self.windup_guard = windup\r\n\r\n def setSampleTime(self, sample_time):\r\n \"\"\"PID that should be updated at a regular interval.\r\n Based on a pre-determined sampe time, the PID decides if it should compute or return immediately.\r\n \"\"\"\r\n self.sample_time = sample_time\r\n\r\n\r\n\r\n#工控机摄像头读取函数\r\n# 无\r\n#frame0:前置摄像头画面 frame1:下置摄像头画面\r\ndef Camera_Capture():\r\n ret, frame0 = cap1.read()\r\n ret, frame1 = cap.read()\r\n return frame0,frame1\r\n\r\n#改变颜色阈值函数\r\n# 无\r\n# 无(纯全局变量操作)\r\ndef change_colorvalue():\r\n global red_lower\r\n global green_lower\r\n global bule_lower\r\n global red_higher\r\n global green_higher\r\n global bule_higher\r\n if SEARCH_count >= SEARCH_count_max:\r\n green_lower = green_lower - 5\r\n bule_lower = bule_lower - 5\r\n red_higher = red_higher + 5\r\n green_higher = green_higher + 5\r\n bule_higher = bule_higher + 5\r\n\r\ndef colorvalue_back():\r\n global red_lower\r\n global green_lower\r\n global bule_lower\r\n global red_higher\r\n global green_higher\r\n global bule_higher\r\n\r\n red_lower = 0\r\n green_lower = 50\r\n bule_lower = 60\r\n red_higher = 255\r\n green_higher = 150\r\n bule_higher = 150\r\n\r\n\r\n#用于退出整个程序\r\n# 无\r\n#退出标志位\r\ndef Break_flag():\r\n break_flag = False\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == ord(\"q\"):\r\n break_flag = True\r\n return break_flag\r\n\r\n#用于控制计数。识别要快,运动要慢、准\r\n#计数器名称\r\n# 无\r\ndef COUNT(name):\r\n global order_count1\r\n global order_count2\r\n global order_count3\r\n global order_count4\r\n global order_count5\r\n if name=='count1':\r\n enable_flag = False\r\n order_count1 = order_count1 + 1\r\n if order_count1>=count_max1:\r\n order_count1 = 0\r\n enable_flag = True\r\n return enable_flag\r\n if name=='count2':\r\n enable_flag = False\r\n order_count2 = order_count2 + 1\r\n if order_count2 >= count_max2:\r\n order_count2 = 0\r\n enable_flag = True\r\n return enable_flag\r\n if name=='count3':\r\n enable_flag = False\r\n order_count3 = order_count3 + 1\r\n if order_count3 >= count_max3:\r\n order_count3 = 0\r\n enable_flag = True\r\n return enable_flag\r\n if name=='count4':\r\n enable_flag = False\r\n order_count4 = order_count4 + 1\r\n if order_count4 >= count_max4:\r\n order_count4 = 0\r\n enable_flag = True\r\n return enable_flag\r\n if name=='count5':\r\n enable_flag = False\r\n order_count5 = order_count5 + 1\r\n if order_count5 >= count_max5:\r\n order_count5 = 0\r\n enable_flag = True\r\n return enable_flag\r\n\r\n\r\n\r\n#寻找模式\r\n#frame0:前置摄像头画面 frame1:下置摄像头画面\r\n#SEARCH_enable:Search放行标志位\r\ndef SEARCH_MODEL(frame,camera_flag):\r\n global SEARCH_count\r\n global SEARCH_count_time\r\n global Rect_Tarnum, Line_Tarnum\r\n SEARCH_enable = False\r\n thresh = Frame_Preprocess(frame,camera_flag)\r\n if camera_flag == 1:\r\n Rect_Tarnum, data0, frame = Rect_Target_recognition(thresh,frame)\r\n if camera_flag == 0:\r\n Line_Tarnum, data1, frame = Line_Target_recognition(thresh, frame)\r\n\r\n SEARCH_count = SEARCH_count + 1\r\n\r\n if COUNT('count1')and (not(Rect_Tarnum) or not(Line_Tarnum)):\r\n Turn()\r\n if SEARCH_count >= SEARCH_count_max:\r\n change_colorvalue()\r\n SEARCH_count = 0\r\n SEARCH_count_time = SEARCH_count_time + 1\r\n if SEARCH_count_time >= SEARCH_count_time_max:\r\n SEARCH_count_time = 0\r\n PID_controlAUV('go',0)\r\n print('特殊运动')\r\n if Rect_Tarnum or Line_Tarnum:\r\n SEARCH_count = 0 #找到目标后计数清零\r\n SEARCH_count_time = 0\r\n colorvalue_back()\r\n SEARCH_enable = True\r\n\r\n cv2.imshow(\"frame\", frame)\r\n break_flag = Break_flag()\r\n\r\n return SEARCH_enable,break_flag\r\n\r\n\r\ndef ADJUST_MODEL(frame, camera_flag):\r\n global ADJUST_count\r\n global ADJUST_count_max\r\n global ADJUST_count_time\r\n global ADJUST_count_time_max\r\n global data0, data1\r\n global guide_line_enable_lower, guide_line_enable_higher\r\n Rect_Aim_flag = False\r\n Line_Aim_flag = False\r\n ADJUST_enable = False\r\n thresh = Frame_Preprocess(frame, camera_flag)\r\n if camera_flag == 1:\r\n print(1)\r\n Rect_Tarnum, data0, frame = Rect_Target_recognition(thresh, frame)\r\n if not (data0 is None):\r\n box = data0[4]\r\n frame, objectID, centroid = Target_Tracking(frame, box)\r\n if centroid[0] < left_min and COUNT('count5'):\r\n output = pid_rectx(centroid[0])\r\n output = int(abs(output*0.2))\r\n PID_controlAUV('left_translation', output)\r\n print('左平移')\r\n if centroid[0] > right_max and COUNT('count5'):\r\n output = pid_rectx(centroid[0])\r\n output = int(abs(output*0.2))\r\n PID_controlAUV('right_translation', output)\r\n print('右平移')\r\n if centroid[0] > left_min and centroid[0] < right_max:\r\n Rect_Aim_flag = True\r\n Trustnum = Rect_Trust(data0)\r\n if camera_flag == 0:\r\n print(0)\r\n Line_Tarnum, data1, frame = Line_Target_recognition(thresh, frame)\r\n if not (data1 is None):\r\n x = data1[0]\r\n angle = data1[2]\r\n guide_line_turn(data1)\r\n\r\n if angle > guide_line_enable_lower and angle < guide_line_enable_higher and 270 <= x <= 370 and COUNT('count5'):\r\n Line_Aim_flag = True\r\n PID_controlAUV('go',30)\r\n Trustnum = False\r\n\r\n if Line_Aim_flag or (Rect_Aim_flag and Trustnum):\r\n ADJUST_enable = True\r\n ADJUST_count = 0\r\n\r\n ADJUST_count = ADJUST_count + 1\r\n if ADJUST_count >= ADJUST_count_max:\r\n print('减小调整力度') #待协商\r\n ADJUST_count_time = ADJUST_count_time + 1\r\n ADJUST_count = 0\r\n if ADJUST_count_time>=ADJUST_count_time_max:\r\n ADJUST_count_time = 0\r\n ADJUST_enable = True #如果一直都调不好,就直接过框\r\n\r\n cv2.imshow('frame',frame)\r\n break_flag = Break_flag()\r\n return ADJUST_enable,break_flag\r\n\r\n\r\ndef CROSS_MODEL(frame, camera_flag):\r\n global line_count\r\n global CROSS_count\r\n global CROSS_count_max\r\n CROSS_count_flag = False\r\n corss_Rect_flag = False\r\n # if camera_flag == 1:\r\n # cross_Rect(frame)\r\n PID_controlAUV('go',20)\r\n # thresh = Frame_Preprocess(frame, camera_flag)\r\n # edges = cv2.Canny(thresh, 40, 200, apertureSize=3)\r\n # lines = cv2.HoughLines(edges, 1, np.pi / 180, 160)\r\n # if not(lines is None):\r\n # lines1 = lines[:, 0, :] # 提取为二维\r\n # for rho, theta in lines1[:]:\r\n # a = np.cos(theta)\r\n # b = np.sin(theta)\r\n # x0 = a * rho\r\n # y0 = b * rho\r\n # x1 = int(x0 + 1000 * (-b))\r\n # y1 = int(y0 + 1000 * (a))\r\n # x2 = int(x0 - 1000 * (-b))\r\n # y2 = int(y0 - 1000 * (a))\r\n # cv2.line(frame, (x1, y1), (x2, y2), (255, 0, 0), 1)\r\n # if theta > -0.4 and theta < 0.4:\r\n # line_count = line_count + 1\r\n # if line_count>=5:\r\n # line_count = 0\r\n # corss_Rect_flag = True\r\n\r\n CROSS_count = CROSS_count + 1\r\n\r\n if CROSS_count>=CROSS_count_max and COUNT('count5'): #and line_count < 5:\r\n PID_controlAUV('go',20)\r\n CROSS_count = 0\r\n CROSS_count_flag = True\r\n\r\n cv2.imshow('frame',frame)\r\n break_flag = Break_flag()\r\n\r\n return corss_Rect_flag,CROSS_count_flag,break_flag\r\n\r\n\r\n#寻球模式,采用PID跟踪\r\n#输入下置摄像头画面\r\ndef SEARCHBALL_MODEL(frame):\r\n frame,findball_flag,center = Auv_ball_detect(frame)\r\n if findball_flag:\r\n cX = center[0]\r\n cY = center[1]\r\n if center[0]<280:\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('left_translation',output)\r\n elif center[0]>360:\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('right_translation',output)\r\n if center[1]<200:\r\n output = pid_bally(cY)\r\n output = int(abs(output))\r\n PID_controlAUV('go',output)\r\n elif center[1]>280:\r\n output = pid_bally(cY)\r\n output = int(abs(output))\r\n PID_controlAUV('go',output)\r\n else:\r\n dx = Reference_coor[0] - x0[0]\r\n dy = Reference_coor[1] - y0[0]\r\n\r\ndef Rush_ball_time():\r\n rush_ball_time = 5 # 进入寻球状态的时间,单位是分钟\r\n timer = threading.Timer(60 * rush_ball_time, to_ball) # 设置时钟。根据rush_ball_time变量以判断是否进入撞球部分\r\n timer.start()\r\n\r\n\r\ndef Catch_ball(frame):\r\n global rush_ball_flag\r\n frame, findball_flag, center = Auv_ball_detect(frame)\r\n\r\n cv2.imshow('frame',frame)\r\n if findball_flag:\r\n cX = center[0]\r\n cY = center[1]\r\n if center[0] < 280 and COUNT('count1'):\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('left_translation', output)\r\n elif center[0] > 360 and COUNT('count1'):\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('right_translation', output)\r\n\r\n elif center[1] < 360 and COUNT('count1'):\r\n output = pid_bally(cY)\r\n output = int(abs(output))\r\n PID_controlAUV('ball_up',output)\r\n elif center[1] > 420 and COUNT('count1'):\r\n output = pid_bally(cY)\r\n output = int(abs(output))\r\n PID_controlAUV('ball_down',output)\r\n\r\n if 280 < center[0] < 360 and 360 < center[1] < 420 and COUNT('count5'):\r\n for i in range(3):\r\n PID_controlAUV('MIXDOWN', 20)\r\n time.sleep(10)\r\n for i in range(3):\r\n PID_controlAUV('UP',10)\r\n time.sleep(15)\r\n rush_ball_flag = True\r\n else:\r\n Turn()\r\n\r\n return rush_ball_flag\r\n\r\n\r\ndef Rush_ball(frame):\r\n global m\r\n frame, findball_flag, center = Auv_ball_detect(frame)\r\n if findball_flag:\r\n cX = center[0]\r\n if center[0]<280 and COUNT('count5'):\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('left_translation',output)\r\n elif center[0]>360 and COUNT('count5'):\r\n output = pid_ballx(cX)\r\n output = int(abs(output))\r\n PID_controlAUV('right_translation',output)\r\n\r\n elif center[1]<200 and COUNT('count5'):\r\n PID_controlAUV('up',10)\r\n elif center[1]>280 and COUNT('count5'):\r\n PID_controlAUV('down',10)\r\n\r\n if 280 < center[0] < 360 and 200 < center[1] < 280 and COUNT('count5'):\r\n PID_controlAUV('go',30)\r\n else:\r\n PID_controlAUV('up',10)\r\n PID_controlAUV('right',10)\r\n\r\n\r\ndef to_ball():\r\n #### 修改部分\r\n global ball_flag\r\n ball_flag = True\r\n\r\n\r\n\r\n#从MCU读取陀螺仪姿态参数\r\n# yaw:偏转角\r\ndef read_fromMCU():\r\n msg = ser.read(3)\r\n yaw = msg[2]\r\n return yaw\r\n\r\n#跟踪球PID函数\r\n#球所在位置的y坐标\r\n#改变力度\r\ndef pid_ballx(feedback):\r\n pid0.update(feedback_value=feedback) #待修改\r\n output = pid0.output\r\n return output\r\n\r\n\r\n#跟踪球PID函数\r\n#球所在位置的y坐标\r\n#改变力度\r\ndef pid_bally(feedback):\r\n pid1.update(feedback_value=feedback) #待修改\r\n output = pid1.output\r\n return output\r\n\r\ndef pid_lineturn(feedback):\r\n pid2.update(feedback_value=feedback)\r\n output = pid2.output\r\n return output\r\n\r\ndef pid_rectx(feedback):\r\n pid3.update(feedback_value=feedback) #待修改\r\n output = pid3.output\r\n return output\r\n\r\ndef pid_recty(feedback):\r\n pid4.update(feedback_value=feedback) #待修改\r\n output = pid4.output\r\n return output\r\n\r\n\r\n# camera = PiCamera()\r\n# camera.resolution = (640,480)\r\n# camera.framerate = 32\r\n# rawCapture = PiRGBArray(camera, size=(640,480))\r\n\r\n\r\n# camera = PiCamera() #下置摄像头\r\n# camera.resolution = (640,480)\r\n# camera.framerate = 32\r\n# rawCapture = PiRGBArray(camera, size=(640,480))\r\n\r\n# cap1 = cv2.VideoCapture(0) # 前置摄像头\r\n# cap1.set(3, 640) # 设置分辨率\r\n# cap1.set(4, 480)\r\n\r\n#跟踪球PID实例化\r\npid0 = PID(P0,I0,D0)\r\npid0.SetPoint=320\r\npid0.setSampleTime(0.5)\r\n\r\n#跟踪球PID实例化\r\npid1 = PID(P1,I1,D1)\r\npid1.SetPoint=240\r\npid1.setSampleTime(0.5)\r\n\r\n#调整线PID实例化\r\npid2 = PID(P2,I2,D2)\r\npid2.SetPoint=0\r\npid2.setSampleTime(0.5)\r\n\r\n#对框PIDx实例化\r\npid3 = PID(P3,I3,D3)\r\npid3.SetPoint=320\r\npid3.setSampleTime(0.5)\r\n\r\n#对框PIDy实例化\r\npid4 = PID(P4,I4,D4)\r\npid4.SetPoint=240\r\npid4.setSampleTime(0.5)\r\n\r\n#初始模式为“寻找模式”\r\n# PID_controlAUV('down',10)\r\nMODEL_section_flag = 'SEARCH'\r\n\r\n#AUV定深下沉准备\r\n#\r\ntime.sleep(20)\r\nfor i in range(300):\r\n PID_controlAUV('up',10)\r\n\r\n# for i in range(300):\r\n# PID_controlAUV('up',10)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # rush_ball_time = 500\r\n # timer = threading.Timer(60 * rush_ball_time, to_ball) # 设置时钟。根据rush_ball_time变量以判断是否进入撞球部分\r\n # timer.start()\r\n # for frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\r\n rush_ball_time = 6 # 进入寻球状态的时间,单位是分钟\r\n timer = threading.Timer(60 * rush_ball_time, to_ball) # 设置时钟。根据rush_ball_time变量以判断是否进入撞球部分\r\n timer.start()\r\n camera_num = 0\r\n while True:\r\n\r\n camera_flag, frame = camera_switch()\r\n\r\n # if ball_flag:\r\n # ret0, frame = cap1.read()\r\n # Catch_ball(frame)\r\n # if rush_ball_flag:\r\n # frame = frame.array\r\n # Rush_ball(frame)\r\n # break_flag = Break_flag()\r\n\r\n # if frame is None:\r\n # print(cap1.isOpened())\r\n # exit(0)\r\n # cv2.waitKey(10)\r\n # continue\r\n\r\n if not cap1.isOpened():\r\n cap1.release()\r\n camera_num = 1- camera_num\r\n cap1 = cv2.VideoCapture(camera_num) # 前置摄像头\r\n cap1.set(3, 640) # 设置分辨率\r\n cap1.set(4, 480)\r\n cv2.waitKey(10)\r\n continue\r\n\r\n\r\n\r\n if ball_flag:\r\n ret0, frame = cap1.read()\r\n Rush_ball(frame)\r\n break_flag = Break_flag()\r\n else:\r\n if MODEL_section_flag=='SEARCH':\r\n print('SEARCH')\r\n SEARCH_enable,break_flag = SEARCH_MODEL(frame, camera_flag)\r\n if SEARCH_enable:\r\n MODEL_section_flag = 'ADJUST'\r\n elif MODEL_section_flag=='ADJUST':\r\n print('ADJUST')\r\n ADJUST_enable,break_flag = ADJUST_MODEL(frame, camera_flag)\r\n if ADJUST_enable:\r\n MODEL_section_flag='CROSS'\r\n elif MODEL_section_flag=='CROSS':\r\n print('CROSS')\r\n corss_Rect_flag, CROSS_count_flag, break_flag = CROSS_MODEL(frame, camera_flag)\r\n if corss_Rect_flag:\r\n crossed_count = crossed_count + 1\r\n MODEL_section_flag='SEARCH'\r\n if CROSS_count_flag:\r\n MODEL_section_flag='SEARCH'\r\n\r\n\r\n Odometer(model,AUV_dx,AUV_dy,AUV_dtheta,dl,dr)\r\n\r\n # rawCapture.truncate(0)\r\n\r\n if break_flag:\r\n break\r\n\r\n ser.close()\r\n cv2.destroyAllWindows()\r\n sys.exit()" } ]
2
DarkCodeOrg/python-learning
https://github.com/DarkCodeOrg/python-learning
c92f6c18c73c475c699ffc2e2c42617d90746c34
3e891e2de57c3f3f84e06cb772ffa4ee264dfe29
c8618a342fb36935493775bf2ecc2a063f47efbd
refs/heads/master
2023-08-24T06:11:48.835440
2021-09-12T17:34:29
2021-09-12T17:34:29
297,374,293
1
0
null
2020-09-21T15:00:34
2021-08-20T13:34:25
2021-09-12T17:34:30
Python
[ { "alpha_fraction": 0.6147202253341675, "alphanum_fraction": 0.6162223219871521, "avg_line_length": 31.851852416992188, "blob_id": "e365edc35c901d5334765db6f76271bc891989a0", "content_id": "c93cacdba6772cbf59579865225012efc498891e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2663, "license_type": "no_license", "max_line_length": 88, "num_lines": 81, "path": "/file_handling_3.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "### continued ...........\n## File pointer ( analogous to a bookmark in a book )\n\nimport sys\n#sys.path.append(\"/home/david/hello_world/python/basics\")\nimport os\n\n#import list_adv as f_list ## it has functions to manipulate a list\n\n## infile = open(\"filename\",\"r\") would open the file and put the file\n# pointer at the beginning of the file\n# ch = infile.read(1) would read 1 byte (one character) from the file\n# str = infile.read(2) would read 2 bytes from the place where the\n# file pointer left \n\n#############################################\n### WORKING WITH BINARY FILES ###\n#############################################\n\nimport pickle\n\n# pickling / serialisation = converting an python object into a byte-stream \n# unpickling / deserialization = converting the byte stream again into python object\n## the pickle module has dump() and load() methods to write and read to and from a file\n# Creating / opening / closing binary files\n# \n\ndfile = open(\"student_new.dat\",\"rb+\") # b specifies to open it in binary mode\ndata_w = {} ## creating an empty dictionary for writing purpose\ndata_r = {} ## creating an empty dictionary for reading purpose\n ## reading the file \ntry :\n print(\"file student_new.dat conains the following records :\")\n while True: ## sets to false if end of file is encountered\n data_r = pickle.load(dfile)\n print(data_r)\nexcept EOFError:\n dfile.close()\n\ndfile = open(\"student_new.dat\",\"ab+\")\nNo_of_stdnt = int(input(\"enter the no of students in class :\"))\nfor i in range(No_of_stdnt):\n name = input(\"Enter the name of the student :\")\n roll = int(input(\"enter the roll no of the student :\"))\n marks = int(input(\"eneter the marks obtained by the student :\"))\n data_w['Name'] = name\n data_w[ 'Roll'] = roll\n data_w[ 'Marks'] = marks\n ## thedata_r above three lines fillup the dictionary\n pickle.dump(data_w,dfile)\n\ndfile.close()\n\n\n## searching in a binary file\n\nfound = False\ndfile = open(\"student_new.dat\",\"rb\")\nsearch_for = [] ## these are the roll nos to find for\nreply = 'y' \nwhile reply == 'y':\n foo = int(input(\"Enter the roll number to search for :\"))\n search_for.append(foo)\n reply = input(\"Do you wish to search for more ?(y/n) :\")\nelse :\n\n try:\n print(\"Searching in the file student_new.dat ......\")\n while True:\n data_r = pickle.load(dfile)\n if data_r['Roll'] in search_for:\n print(data_r)\n found = True\n except EOFError:\n if found == False:\n print(\"no such records found..\")\n\n else:\n print(\"search successful\")\n\n dfile.close()\n\n\n" }, { "alpha_fraction": 0.6212121248245239, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 11.600000381469727, "blob_id": "d9b80e676f2a3873c37b1747bdada19495d58e00", "content_id": "8b7b1e392a3a235064347fcf6473e08f2886e859", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 66, "license_type": "no_license", "max_line_length": 30, "num_lines": 5, "path": "/cantnamethisrandom.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "#!/bin/python \n\nimport random \n\nprint(random.randrange(1,100))\n\n\n\n" }, { "alpha_fraction": 0.7051671743392944, "alphanum_fraction": 0.7051671743392944, "avg_line_length": 27.565217971801758, "blob_id": "c8d412cf17d64b1b7919215b900ef099838728d7", "content_id": "3d4fb18fb6309ff656a7206b56664dca34640126", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 658, "license_type": "no_license", "max_line_length": 102, "num_lines": 23, "path": "/tuple.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "\"\"\" this program is for the demonstration of tuples in python \"\"\"\n\"\"\" this also demonstrates convertig tuples to a list, check if tuple exists and so on.... \"\"\"\n\n\nmytuple = (\"hello\",\"hi\",\"tuple\",\"bye\")\n# tuples ar immutable that is they cannot be modified no adding of items no removing of items \n# it is like a static list\n\nfor x in mytuple:\n print(x)\n\n\"\"\" workaround for adding items to a tuple \"\"\"\ny = list(mytuple)\ny.append(\"workaround\")\nmytuple = tuple(y)\n\nfor x in mytuple:\n print(x)\n\n# creating tuple with a single element\nnewtuple = (\"new\",) # we have to insert that comma otherwise python would not understand it as a tuple\n\nprint(newtuple)\n\n" }, { "alpha_fraction": 0.6026246547698975, "alphanum_fraction": 0.6099737286567688, "avg_line_length": 24.052631378173828, "blob_id": "1c7901784f0e60f213202a932dcd25b6353c2b1b", "content_id": "51710a183de36ddfa9a3f3de57f9dfc7f6344e34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1905, "license_type": "no_license", "max_line_length": 110, "num_lines": 76, "path": "/list_adv.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "\"\"\" this program shows the use of list : adding item, removing item, printing it (iterating), clearing it \"\"\"\n\nimport sys\n\nthisislist = [\"apple\",\"banana\"]\nprint(\"this is the initial list \",thisislist)\nprint(\"this is the length of the list \",len(thisislist))\n\ndef Additem():\n item = str(input(\"Enter the name of the element that you want to add = \"))\n thisislist.append(item)\n print(thisislist)\n menu()\ndef RemItem():\n item = str(input(\"Enter the name of the element that you want to remove = \"))\n thisislist.remove(item)\n print(thisislist)\n menu()\ndef PrintList():\n for x in thisislist:\n print(x)\n menu()\ndef CheckList():\n search = str(input(\"Enter the item u wanna search: \"))\n if search in thisislist:\n print(\"Yes it is present\")\n else:\n print(\"It is not present\")\n print(thisislist)\n menu()\n\ndef AddItemPos():\n item = str(input(\"Enter the item u want to Add : \"))\n pos = int(input(\"Enter the position Where u wanna add the item : \"))\n thisislist.insert(pos,item)\n print(thisislist)\n menu()\n\ndef ClearList():\n thisislist.clear()\n print(thisislist)\n menu()\n\ndef menu():\n print('''\n 0) Quit\n 1) Add an element to the list\n 2) Add an item at a particular position\n 3) Remove an element from the list\n 4) Display the list\n 5) Check if an item exists\n 6) Clear the list \n ''')\n selection = int(input(\"What do you want to do: \"))\n if selection == 0:\n sys.exit() \n elif selection == 1:\n Additem()\n elif selection == 2:\n AddItemPos()\n elif selection == 3:\n RemItem()\n elif selection == 4:\n PrintList()\n elif selection == 5:\n CheckList()\n elif selection == 6:\n ClearList()\n else:\n print(\"Invalid input\")\n\nmenu()\n\n\n### to use this as a module in other programs uncomment all the \n### lines with menu()\n\n" }, { "alpha_fraction": 0.5781609416007996, "alphanum_fraction": 0.6264367699623108, "avg_line_length": 19.66666603088379, "blob_id": "9155ca037fa1dd4d50bb50d1313db19c0ee696eb", "content_id": "06a535a8b5c96fc9acf64eb02c249087ac44b461", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 870, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/operators-in-py.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "#!/bin/python \n\n# this program shows the different operators in python\n\n\"\"\"\nsome operators shown here are \nexponentiation operator : **\nfloor division operator : //\n\nlogical opertors like \"and\" \"or\" \"not\"\nidentity operators like : \"is\" and \"is not\"\nmembership operators like : \"in\" and \"not in\"\n\nbitwise opearators like : & | ^ ~ << >>\n\n\"\"\"\n\nfruits = {\"apple\",\"banana\",\"guava\",\"litchi\"}\nif \"apple\" in fruits:\n print(\"yes apple is a fruit\")\n\nelse:\n print(\"No it is not a fruit\")\n\n\nif 5 == 10 or 4 == 4:\n print(\"Atleast one of them is true\")\n\nx = 2\nx **= 3\nprint(x)\n\ny = 5\ny = y // 2\nprint(y)\n\na = 10 #0000 1010\nb = 1 #0000 0001\nc = a&b # a AND b \"\"\" the and gate returns 1 if both the bits are 1\nprint(c) #expected result is zero\nd = a | b # a OR b or gate returns 1 if any of the bits is 1\nprint(d) # expected result is 0000 1011 that is 11\n\n\n" }, { "alpha_fraction": 0.6525563597679138, "alphanum_fraction": 0.6586036086082458, "avg_line_length": 24.985713958740234, "blob_id": "8ba7b0288cc40243293720275922b6a549932a2a", "content_id": "45d8fafc50285483775f92490ded9e665b5b1936", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1819, "license_type": "no_license", "max_line_length": 147, "num_lines": 70, "path": "/file_handling_1.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "from os import read\nimport os\n\n### checkout python docs for more https://docs.python.org/3/library/filesys.html\n### file = open('filename' , 'mode')\n\"\"\" \n modes = r (read only)\n r+ (read and write)\n w (write) ## the W mode overwrites the entire file.....so beware \n a (append) ## append mode appends text at the end of file\n x (create)\n t (text)\n b (binary)\n\"\"\"\n\n# file reading \nfile = open('trial.txt' , 'r+')\n\nfor each in file:\n print(each)\n\nprint (file.read())\n\n# file writing \n\nfile.write(\"this is the write function\\n\")\nfile.write(\"this lets us write to the file\\n\")\nfile.close # the close function lets us close all the resources in use\n\n\n## Append mode \n\nfile = open('trial.txt','a')\n\nfile.write(\"writing this in append mode\\n\")\nfile.close\n\n## using write with with()\n# the advantage of using with is that it ensures the file is closed\n# after nested block of code is ran \n\nwith open('trial.txt','r+') as file:\n text = file.read()\n file.write(\"writing from within with()\\n\")\n\n## creating a file using x mode\n\nfile2 = open('newfile','x') ## creates the file ...returns error if the file already exists\nos.remove(\"newfile\") ## this removes the file\n\n## readline()\n\nfile3 = open('trial.txt')\nprint(file3.readline())\nprint(file3.readline()) ## this would print the first two lines of the file\n\n## create a file , add a line and a string , read them , split the string and store it in a list , delete the file by checking if it exists atfirst\n\nfile4 = open(\"myfile\",\"x\")\nfile4 = open(\"myfile\",\"r+\")\nfile4.write(\"this is the line\\n\")\nfile4.write(\"apple , banana , cherry , mango\")\ncontent = file4.read()\nprint(content) #TODO debug here...\nfile4.close()\n\nif os.path.exists(\"myfile\"):\n os.remove(\"myfile\")\nelse:\n print(\"the file doesnt exist\\n\")\n" }, { "alpha_fraction": 0.6118614077568054, "alphanum_fraction": 0.623018205165863, "avg_line_length": 26.45161247253418, "blob_id": "d5b636c0c12dc44590ba41b4b3c30850b46d87ad", "content_id": "590accf95cc476b57fc4ea9b26bda1ac52cc2c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1703, "license_type": "no_license", "max_line_length": 187, "num_lines": 62, "path": "/classes_objects.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "#this program is an implementation of the classes and objects in python \n\n# classes serve as an blueprint for making objects in an code\n# everything in OOP is regarded as an object \n# the properies defined in the class are called attributes and the functions are called methods\n\n\n\n\n\nclass Human:\n def __init__(self,name,age,gender): ## the init function is executed whenever a class is initiated // we can use this function to pass parameters to the object when it is created \n ## this func is also called a constructor\n self.name = name\n self.age = age\n self.gender = gender\n\n def greet(self): ## self refers to the name of the object that is being creatd using this class \n print(\"Hello I am \" + self.name)\n\n \n print(\"HI EVERYBODY !!\")\n \n \nclass Robot:\n def introduce_self(self):\n print(\"my name is \",self.name) ## \n print(\"my weight is \" ,self.weight)\n print(\"my address is \", self.addr)\n\nclass Animal:\n def __init__(self):\n self.name = input(\"enter the name of the animal :\")\n self.age = int(input(\"enter the age of the animal :\"))\n self.habitat = input(\"enter the habitat of this animal :\")\n self.owner = input(\"enter the name of owner :\")\n self.care_taker_robo = r1\n\n def info(self):\n print(\"I am a \",self.name)\n print(\"my age is \",self.age)\n print(\"my owner is :\",self.owner)\n\nH1 = Human(\"David\",32,\"male\")\nprint(H1.name)\nprint(H1.age)\nprint(H1.gender)\nH1.greet()\n\n\n\nr1 = Robot()\nr1.name = \"ROBO1\"\nr1.weight = 30\nr1.addr = \"USA\"\nr1.introduce_self()\n\n\n\na1 = Animal()\na1.info()\na1.care_taker_robo.introduce_self()\n\n" }, { "alpha_fraction": 0.6684350371360779, "alphanum_fraction": 0.6758620738983154, "avg_line_length": 26.28985595703125, "blob_id": "c9a994460bc33443ad9c7fc4e10f7a1ff766a61d", "content_id": "eae27c3ce4e1fd709e48f49ca9bb01902ce22d99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1885, "license_type": "no_license", "max_line_length": 106, "num_lines": 69, "path": "/file_handling_2.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "# continued......\n\nfile_1 = open('trial.txt',\"r\")\ns = file_1.readlines() # the readlines function reads the entire contents of the file into a list (here s)\n\nprint(s)\nfile_1.close\n\n## displaying the size and no of lines of a file \nfile_2 = open(\"trial.txt\",\"r\")\nfoo = file_2.read()\nsize = len(foo)\nlinecount = len(file_2.readlines())\nprint(\"size of the given file is \")\nprint(size, \"bytes\")\nprint(\"no of lines is \", linecount)\nfile_2.close()\n\n## creating a file and holding data in it\n\nfilenew = open(\"student.dat\" , \"w\")\nNo_of_stdnt = int(input(\"enter the no of students in class :\"))\nfor i in range(No_of_stdnt):\n name = input(\"Enter the name of the student :\")\n roll = int(input(\"enter the roll no of the student :\"))\n Marks = int(input(\"eneter the marks obtained by the student :\"))\n data = str(roll) + \",\" + name + \",\" + str(Marks) + '\\n'\n filenew.write(data)\n\n filenew.flush() ## the flush functions use us defined below\n\nfilenew.close()\n\n## reading the no of consonants and vowels from a file\n\nfile1 = open(\"trial.txt\",\"r\") \nch = \"\"\nVcount = 0\nCcount = 0\nfor ch in file1.read():\n if ch in set(\"AEIOUaeiou\"):\n Vcount += 1\n elif ch in set(\"qwrtypsdfghjklzxcvbnmQWRTYPSDFGHJKLZXCVBNM\"):\n Ccount += 1\n\nprint(\"Vowels in the file\",Vcount)\nprint(\"Consonants in the file\",Ccount)\n\nfile1.close()\n\n\n## the Flush function\n# the flush function is used to write data still pending in the buffer\n# the flush function is implicitly called by the close() function\n# but can also be called explicitly to force write the data\n# \n\n\n# use of strip , rstrip , lstrip \n## strip() = removes the character from both ends\n# lstrip() = removes the character from the left end\n# rstrip() = removes the character from the right end\n\nmyfile = open(\"stripping.txt\",'r+')\ntext = myfile.read()\ntext_stripped = text.lstrip('.,asd')\nprint(text_stripped)\n\nmyfile.close()\n\n\n" }, { "alpha_fraction": 0.3735632300376892, "alphanum_fraction": 0.4137931168079376, "avg_line_length": 12.75, "blob_id": "ff3cb968a76408d6f775990b0e5d149f3f33ffab", "content_id": "58bcc8d990cc826ec92e52e58f7b22b1929d3c43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 27, "num_lines": 12, "path": "/while.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "\nmydict = {\n \"Name\" : \"David\",\n \"Class\": 10,\n \"School\" : \"AOE School\"\n}\ni = 0\nwhile i<10 :\n i += 1\n if i ==3 :\n continue\n \n print(mydict)\n \n\n\n " }, { "alpha_fraction": 0.423197478055954, "alphanum_fraction": 0.47962382435798645, "avg_line_length": 16.5, "blob_id": "ad1e33d0f3756f36d5fb618ef87d11ff7ddd322d", "content_id": "39d8b656bb659d293177cb21b021637173eaf495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 319, "license_type": "no_license", "max_line_length": 35, "num_lines": 18, "path": "/people.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "People = {\n 'first' : {\n \"name\" = \"Alex\",\n \"Contact\" = 100-200-300,\n },\n\n 'Second' : {\n \"name\" = \"marie\",\n \"Contact\" = 101-202-333,\n }\n\n\n}\n\nfor username, user_info in People:\n print(\"\\nUsername \" + username)\n name = user_info['name']\n Contact = user_info['Contact']\n " }, { "alpha_fraction": 0.6526181101799011, "alphanum_fraction": 0.6628352403640747, "avg_line_length": 31.66666603088379, "blob_id": "4e30044c601fcd0959132c13343022a732b44217", "content_id": "8f34e47827443ec300ac3bcd07924d654c999ab2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 783, "license_type": "no_license", "max_line_length": 149, "num_lines": 24, "path": "/inheritance.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "# the child class is the one that has all the properties of the base class and might have some extra features\n\nclass Person:\n def __init__ (self,name,age):\n self.name = name\n self.age = age\n\n def printname(self):\n print(\"name is \",self.name,\"age is\",self.age)\n\nY = Person(\"david\",30)\nY.printname()\n\nclass Student(Person):\n def __init__(self,name,age,year): ## this init function overrides the parents __init__ function \n super().__init__(name,age) ## the super function helps in inheriting the variables and their related properties from the base/parent class \n self.graduationyear = year\n \n def printyear(self):\n print(\"graduation year is : \",self.graduationyear)\n\nX = Student(\"DAVE\",16,2020)\nX.printname()\nX.printyear()" }, { "alpha_fraction": 0.6308290362358093, "alphanum_fraction": 0.6386010646820068, "avg_line_length": 15.69565200805664, "blob_id": "d7aaf5510184b62a50f2b5d7a6f387cd8080203c", "content_id": "8fe05e10952063df9deef300fc130322cec795e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 772, "license_type": "no_license", "max_line_length": 97, "num_lines": 46, "path": "/strings.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "\"\"\" demonstrating the use of arrays len upper lower strip split replace and slicing in python \"\"\"\n\nstring_old = \" Hello, World!! \"\n\nstring = string_old.strip()\n\n\nprint(len(string))\n\nfor i in range(len(string)):\n print(string[i])\n\nprint(string[0:5])\n\nprint(string.upper())\nprint(string.lower())\nprint(string.replace(\"H\",\"F\"))\n\n\n\"\"\"\nbelow is the demonstration of string check , cocatenation , format\n\"\"\"\n\na = \"First\"\nb = \"Second\"\nage = 30\n\nc = a + b #cocatenation of string\nd = a + \"\" + b\nprint(c)\nprint(d)\n\n\nx = \"Fir\" in a #check string using in\nprint(x)\n\ny = \"Sec\" not in b #check string using not in \nprint(y)\n\n\ntxt = \"i am anonymous and my age is {}\"\nprint(txt.format(age))\n\n\"\"\"Escape characters\"\"\"\n\nprint(\"Hi this is \\\"Mr Anonymous\\\" nice to see you ;-) <3 4 U\")\n\n\n\n\n" }, { "alpha_fraction": 0.43772241473197937, "alphanum_fraction": 0.467971533536911, "avg_line_length": 23.478260040283203, "blob_id": "55050318cc02bee2134eaae1931089fa8779d14c", "content_id": "676f49621e74c0afc952be688b371d0a161a6c18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 562, "license_type": "no_license", "max_line_length": 114, "num_lines": 23, "path": "/dictionaries.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "# this program depicts the use of dictionaries in python\nimport json #json library is imported for the use of the json.dumps feature for better printing of the dictionary \nmydict = {\n 'car1' : {\n \"Brand\" : \"Audi\",\n \"Model\" : \"Q4\",\n \"year\" : 2016\n },\n\n 'car2' : {\n \"Brand\" : \"Mercedes Benz\",\n \"Model\" : \"S-class\",\n \"year\" : 2014\n },\n\n 'car3' : {\n \"Brand\" : \"Rolls Royce\",\n \"Model\" : \"Ghost\",\n \"year\" : 2020\n } \n}\n\nprint(json.dumps(mydict),indent = 2)" }, { "alpha_fraction": 0.5470588207244873, "alphanum_fraction": 0.5470588207244873, "avg_line_length": 21.46666717529297, "blob_id": "0845facd586affb27ab90c1634f6e970638d81c6", "content_id": "3f651f44740ce3e773cde4b7b3b08c1838e08a88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 47, "num_lines": 15, "path": "/function.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "\n\ndef __main__():\n print(\"This is the first function of mine\")\n print(\"we are in main !! \")\n\ndef math():\n x = int(input(\"enter your first number: \"))\n y = int(input(\"enter your second number:\"))\n print(\"sum = \",x+y)\n print(\"product = \",x*y)\n print(\"quotient = \",x/y)\n print(\"difference = \",x-y)\n\n__main__()\n\nmath()\n\n" }, { "alpha_fraction": 0.563829779624939, "alphanum_fraction": 0.5957446694374084, "avg_line_length": 17.700000762939453, "blob_id": "1a504d68cd532289958acc7278f8921c8b407c6c", "content_id": "af6ef1709f7c2ea9bc4416241bf1a4a86a75d279", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 188, "license_type": "no_license", "max_line_length": 51, "num_lines": 10, "path": "/recurse.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "# program depicting the use of recursion in python \n\ndef my_recursion(n):\n if n == 1:\n return 1\n else:\n return (n * my_recursion(n-1))\n\nx = my_recursion(900)\nprint(x)\n\n" }, { "alpha_fraction": 0.64420485496521, "alphanum_fraction": 0.6765498518943787, "avg_line_length": 20.764705657958984, "blob_id": "62c8fa5003d026ba8185f26d975c83cd0afa84db", "content_id": "48dda8a5f5ce9446093e8df0acbf387a16eda111", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 742, "license_type": "no_license", "max_line_length": 165, "num_lines": 34, "path": "/Lambda.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "# this program shows the usage of the lambda function in python\n# the lambda function refers to any anonymous function \n\n# syntax : \n# lambda arguments : expression \n\n# wwhen to use lambda function :::: when u need an anonymous function for a short period of time or when u ned to pass an function as a argument to another function \n\n\nadd = lambda a,b,c,d : a + b + c + d\n\nprint(add(1,2,3,4))\n\nsub = lambda a,b : a - b\n\nprint(sub(10,11))\n \ndef myfunc(x):\n return lambda n: n*x\n\ny = myfunc(20)\nprint(y(2))\n\nsay_hello = lambda : print(\"hello\")\n\nsay_hello()\n\n\nmy_list = [1,2,3,4,5,6,7,8,9,10]\n\nnew_list = list(filter(lambda x: x%2==0,my_list)) # the filter function takes two arguments one function and another list \n\n\nprint(new_list)\n\n\n" }, { "alpha_fraction": 0.8072289228439331, "alphanum_fraction": 0.8072289228439331, "avg_line_length": 19.25, "blob_id": "4294882c33be669393de61142aa8dd00eb7ece09", "content_id": "fbf9185b5affbbed7be7bc1093daede94d3e3c93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/README.md", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "# python-learning\nmy journey towards python\n\ncovers basic stuff regarding python \n\n" }, { "alpha_fraction": 0.6379310488700867, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 21.600000381469727, "blob_id": "37f004268a166d729e57624085aa0762c9f0f202", "content_id": "aa3014c62c3d65611adb721a83ea87302cd43c2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/loop.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "\n# demonstration of a simple loop \n\nfor iteral in range(10):\n print(iteral)\n print(\"this is step :\",iteral)\n\n\n" }, { "alpha_fraction": 0.5558297634124756, "alphanum_fraction": 0.5718691945075989, "avg_line_length": 29, "blob_id": "e5f71f85794cf0fd9f9966d6559f8ad0bcd7130a", "content_id": "232d4bec8f744ff4214ffd35cebc3025b804fed1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1621, "license_type": "no_license", "max_line_length": 98, "num_lines": 54, "path": "/file_handling_4.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "## updating in a binary file\n# \n# tell() and seek() \n#\nimport pickle\nfrom sys import flags\n\ninfile = open(\"trial.txt\",'r')\n\nprint(\"initially the file_pointer is at = \",infile.tell())\nprint(\"reading 4 bytes : \",infile.read(4))\nprint(\"now the file pointer is art :\",infile.tell())\n\n## the tell function gives the current position of the file pointer\nprint(\"now printing results of the seek function\")\n\ninfile.seek(10) ## default mode , puts the file pointer to the \n # 10th byte from the beginning\n\ninfile.seek(5,1) ## mode 1 , puts the file pointer to the 5th byte(forward direction) from\n # the current file pointer position\n\ninfile.seek(-10,2) ## mode 2 , puts the file pointer to the 10th byte backward from the \n # end of file\n\n#######################################################################\n#### UPDATING THE RECORDS OF A FILE AT A PARTICULAR POSITION ###\n#######################################################################\n\n## read the file student_new.dat and give 10 marks bonus to students who have scored more that 550\n## \n\nupfile = open(\"student_new.dat\",\"rb+\")\nstu = {} ## crating a empty file to store the records in the file\nfound = False\n\ntry:\n while True:\n rpos = upfile.tell()\n stu = pickle.load(upfile)\n\n if stu['Marks'] > 550:\n stu['Marks'] += 10\n upfile.seek(rpos)\n pickle.dump(stu,upfile)\n found = True\n\nexcept EOFError:\n if found == False:\n print(\"no such records found\")\n else:\n print(\"record(s) have been updated\")\n\n upfile.close()\n\n" }, { "alpha_fraction": 0.6881960034370422, "alphanum_fraction": 0.6993318200111389, "avg_line_length": 18.521739959716797, "blob_id": "e695bea4dc79aa33bd1c1a2b21aed1bec17ba1b2", "content_id": "0b87ee7587d2eb4a4f9fb573d026478dd1a88537", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 898, "license_type": "no_license", "max_line_length": 73, "num_lines": 46, "path": "/sets.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "#/bin/python \n\n\"\"\" this program depicts the use of sets in python \"\"\"\n\n# sets are unordered and unindexed they are written using curly braces {}\n# we cannot change items but we can add items and remove items\n\nmyset = {\"maths\",\"physics\",\"chemistry\",\"Computer Science\"}\nprint(myset) # set is printed in opposite fashion \n\nfor x in myset:\n print(x)\n\nprint(\"banana\" in myset)\nprint(\"maths\" in myset)\n\nmyset.add(\"Subjects\")\nprint(myset)\n\n# adding multiple items using update method\n\nmyset.update([\"update\",\"multiple\",\"items\"])\nprint(myset)\n\nprint(len(myset))\n\nmyset.remove(\"update\") # remove takes exactly one argument \nprint(myset)\n\nmyset.clear()\nprint(myset)\n\n\"\"\" joining two sets \"\"\"\n\nset1 = {\"Facebook\",\"Apple\",\"Amazon\"}\nset2 = {\"Netflix\",\"Google\"}\n\nprint(\"set1 is \",set1,\"set2 is \",set2)\n\nset3 = set1.union(set2)\nprint(set3)\n\n# set constructor\n\nthisisset = set((\"new\",\"set\"))\nprint(thisisset)\n" }, { "alpha_fraction": 0.6382113695144653, "alphanum_fraction": 0.6585366129875183, "avg_line_length": 26.11111068725586, "blob_id": "427af6360e0f8b65d3532001cb48f8d8dc16912b", "content_id": "f3d559b43c54665517ca5bd2a3bb5958968a17c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 71, "num_lines": 9, "path": "/elseif.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "#/bin/python python3\n\nanswer = int(input(\"2 multiplied by 2 is = \"))\n\nif answer == 4:\n print(\"correct answer!!maybe you are gonna be the next Einstein\")\n\nelif answer != 4:\n print(\"Damn i am gonna complain it to your maths teacher!!\")\n\n\n" }, { "alpha_fraction": 0.6597222089767456, "alphanum_fraction": 0.6736111044883728, "avg_line_length": 13.149999618530273, "blob_id": "45497bbe4e6c706c4f79e8be82bc586cc78331e3", "content_id": "0fdb74e849b37715c782f1c9e90e721fa2b599e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 57, "num_lines": 20, "path": "/list.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "#!/bin/python python3\n\n\"\"\" creating an empty list and adding elements to it\"\"\" \n\nlist = []\n\nlist.append(200)\nlist.append(\"salad\")\nlist.append(\"maths\")\n\n\nprint(list)\n\nprint(\"this is your initial list\")\n\nnew = input(\"Enter something new to the list: \")\n\nlist.append(new)\n\nprint(list)\n\n\n\n\n\n" }, { "alpha_fraction": 0.6663907170295715, "alphanum_fraction": 0.6697019934654236, "avg_line_length": 33.400001525878906, "blob_id": "5108a70f629f6dcf4945b01948c61b57e61a4391", "content_id": "a47f76db17993e0bc4e8aaa31150e38862dbd946", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1208, "license_type": "no_license", "max_line_length": 139, "num_lines": 35, "path": "/file_handling_5.py", "repo_name": "DarkCodeOrg/python-learning", "src_encoding": "UTF-8", "text": "## CSV file manipulation\n\nimport csv\n \n\ninfile = open(\"student.csv\",\"ra+\",newline='\\n')\ninfile_1 = open(\"student.csv\",\"ra+\",newline='')\n\n## writing to csv files\n## delimeter refers to the separator used in a csv file to separate datas\n\n## we have to create a writer object at first ..... csv.writer(input-file) creates the writer object\n## the writer object is required for coverting user entered data into\n## delimited strings \n## the writer object has many methods like writerow, writerows\n## etc....\ndata_writer = csv.writer(infile_1)\ndata_writer.writerow(['Rollno','Name','Marks']) ## the coloumn headings are written here\n ## the above line writes a row with Rollno,Name,Marks written ....that serves as a heading\n\nno_of_students = int(input(\"Enter the no of students :\"))\n\nfor i in range(no_of_students):\n print(\"Student record \",i+1)\n rollno = int(input(\"Enter the roll number of the student :\"))\n name = input(\"Enter the name of the student :\")\n marks = int(input(\"Enter the marks obtained by the student :\"))\n student_record = [rollno,name,marks]\n data_writer.writerow(student_record)\n\n\n## \n\ninfile.close()\ninfile_1.close()\n\n\n\n\n" } ]
23
GabrielSDesiderio/Python-Projects
https://github.com/GabrielSDesiderio/Python-Projects
c422f1b425dc8bd130c9b51dc58944cc37abacb5
6e4a8df86d12c7a0889b0c9ded03f05a2737bb5c
6009733c199e976287cc95563bd257088df2a3af
refs/heads/master
2023-04-02T02:17:57.334060
2021-04-12T11:40:13
2021-04-12T11:40:13
338,664,849
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5793588757514954, "alphanum_fraction": 0.5871774554252625, "avg_line_length": 29.4761905670166, "blob_id": "e2f69be46892aaa9a2bea5c8cbb4433c7c72bc60", "content_id": "1310364b7ad0c47ad50a390dd226e48dff401f53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1279, "license_type": "no_license", "max_line_length": 78, "num_lines": 42, "path": "/Polygon Area Calculator/shape_calculator.py", "repo_name": "GabrielSDesiderio/Python-Projects", "src_encoding": "UTF-8", "text": "class Rectangle:\n def __init__(self,width,height):\n self.width=width\n self.height=height\n def set_height(self,height):\n self.height=height\n def set_width(self,width):\n self.width=width\n def get_area(self):\n return self.width*self.height\n def get_perimeter(self):\n return 2*self.width+2*self.height\n def get_diagonal(self):\n return (self.width**2+self.height**2)**0.5\n def get_picture(self):\n if self.width>50 or self.height>50:\n return \"Too big for picture.\"\n s=''\n for i in range(self.height):\n s+='*'*self.width+'\\n'\n return s\n def __str__(self):\n return \"Rectangle(width={}, height={})\".format(self.width,self.height)\n def get_amount_inside(self,other):\n return (self.width//other.width)*(self.height//other.height)\n \n\nclass Square(Rectangle):\n def __init__(self,side):\n self.height=side\n self.width=side\n def set_side(self,side):\n self.height=side\n self.width=side\n def __str__(self):\n return \"Square(side={})\".format(self.width)\n def set_height(self,side):\n self.height=side\n self.width=side\n def set_width(self,side):\n self.height=side\n self.width=side" }, { "alpha_fraction": 0.5269872546195984, "alphanum_fraction": 0.5603532791137695, "avg_line_length": 29.909090042114258, "blob_id": "2ce1a6948971095285f44f841246869f3d7c198f", "content_id": "064b8ecd358ebc7f01a13e9656fb0beabf8ac2d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1019, "license_type": "no_license", "max_line_length": 105, "num_lines": 33, "path": "/Time Calculator/test_module.py", "repo_name": "GabrielSDesiderio/Python-Projects", "src_encoding": "UTF-8", "text": "days = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday',4: 'Friday', 5: 'Saturday', 6: 'Sunday'}\n\n\n\ndef add_time(init,interval,weekday1 = None):\n import datetime\n time_init = datetime.datetime.strptime(init, \"%I:%M %p\")\n if weekday1 != None:\n weekday1 = weekday1.title()\n while days[time_init.weekday()] != weekday1:\n time_init += datetime.timedelta(days=1)\n \n tm1 = interval.split(':')\n tm1 = list(map(int, tm1)) \n tm2 = datetime.timedelta(hours=tm1[0], minutes=tm1[1])\n tm3 = time_init + tm2\n time_final = tm3.strftime(\"%I:%M %p\")\n \n if (time_final[0] == \"0\"):\n time_final = time_final[1:]\n\n next_day=''\n if (tm3.day-time_init.day == 1):\n next_day = ' (next day)'\n elif (tm3.day-time_init.day > 1):\n next_day = ' (' + str(tm3.day-time_init.day) + ' days later)'\n\n finalday = ''\n if weekday1 != None:\n finalday = ', ' + tm3.strftime('%A')\n\n new_time = time_final + finalday + next_day\n return new_time;" }, { "alpha_fraction": 0.5080139636993408, "alphanum_fraction": 0.5289198756217957, "avg_line_length": 29.53191566467285, "blob_id": "cf5dc4d73dcfd883bd439fce966d817932ec5d01", "content_id": "76ac4bfaf4831c52245c7527e85ecef531d9ffb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2870, "license_type": "no_license", "max_line_length": 99, "num_lines": 94, "path": "/Budget App/budget.py", "repo_name": "GabrielSDesiderio/Python-Projects", "src_encoding": "UTF-8", "text": "class Category:\n def __init__(self,name):\n self.name=name\n self.ledger=[]\n self.funds=0\n def deposit(self,amount,description=''):\n self.ledger.append({\"amount\": amount, \"description\": description})\n self.funds+=amount\n def withdraw(self,amount,description=''):\n if self.check_funds(amount):\n self.ledger.append({\"amount\": -amount, \"description\": description})\n self.funds-=amount\n return True\n return False\n def get_balance(self):\n return self.funds\n def transfer(self,amount,other):\n if not self.check_funds(amount):\n return False\n self.ledger.append({'amount':-amount,'description':\"Transfer to {}\".format(other.name)})\n self.funds-=amount\n other.ledger.append({\"amount\": amount, \"description\":\"Transfer from {}\".format(self.name)})\n other.funds+=amount\n return True\n\n def check_funds(self,amount):\n if self.funds>=amount:\n return True\n return False\n def __str__(self):\n s=''\n s+=self.name.center(30,'*')+'\\n'\n for x in self.ledger:\n if len(x['description'])>23:\n s+=x['description'][0:23]\n else:\n s+=x['description'][0:23].ljust(23)\n s+=\"{0:.2f}\".format(x['amount']).rjust(7)\n s+='\\n'\n s+='Total: {}'.format(self.funds)\n return s\n \ndef create_spend_chart(categories):\n s=\"Percentage spent by category\\n\"\n sum=0\n withdraws={}\n for x in categories:\n withdraws[x.name]=0\n for y in x.ledger:\n if y['amount']<0:\n withdraws[x.name]+=y['amount']\n withdraws[x.name]=-withdraws[x.name]\n for x in withdraws:\n sum+=withdraws[x]\n for x in withdraws:\n withdraws[x]=int(withdraws[x]/sum*100)\n \n for i in range(100,-10,-10):\n s+=str(i).rjust(3)+'| '\n for x in categories:\n if withdraws[x.name]>=i:\n s+='o '\n else:\n s+=' '\n s+='\\n'\n s+=' '*4+'-'*(1+len(categories)*3)+'\\n'\n\n maxlen=0\n for x in categories:\n if len(x.name)>maxlen:\n maxlen=len(x.name)\n for i in range(maxlen):\n s+=' '*5\n for x in categories:\n if len(x.name)>i:\n s+=x.name[i]+' '\n else:\n s+=' '*3\n s+='\\n'\n return s[0:-1]\n\n\nif __name__ == \"__main__\":\n food=Category('food')\n entertainment=Category('entertainment')\n business=Category('Business')\n food.deposit(900, \"deposit\")\n entertainment.deposit(900, \"deposit\")\n business.deposit(900, \"deposit\")\n food.withdraw(105.55)\n entertainment.withdraw(33.40)\n business.withdraw(10.99)\n actual = create_spend_chart([business, food, entertainment])\n print(actual)\n" }, { "alpha_fraction": 0.5584281086921692, "alphanum_fraction": 0.5625646114349365, "avg_line_length": 29.21875, "blob_id": "081e1037e5e9d74605d44dc11bafba676cdda320", "content_id": "1b19d48be7836cecfd93978bdd5d5cdb3fa84c51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 967, "license_type": "no_license", "max_line_length": 67, "num_lines": 32, "path": "/Probability Calculator/prob_calculator.py", "repo_name": "GabrielSDesiderio/Python-Projects", "src_encoding": "UTF-8", "text": "import copy\nimport random\n# Consider using the modules imported above.\n\nclass Hat:\n def __init__(self,**balls):\n self.contents=[]\n for i in balls:\n for j in range(balls[i]):\n self.contents.append(i)\n def draw(self,num):\n if num>=len(self.contents):\n tmp=self.contents.copy()\n self.contents.clear()\n return tmp\n tmp=[]\n for i in range(num):\n n=random.choice(range(0,len(self.contents)))\n tmp.append(self.contents[n])\n self.contents.pop(n)\n return tmp\ndef experiment(hat,expected_balls,num_balls_drawn,num_experiments):\n count=0\n for i in range(num_experiments):\n hat_copy=copy.deepcopy(hat)\n drawn=hat_copy.draw(num_balls_drawn)\n for j in expected_balls:\n if expected_balls[j]>drawn.count(j):\n count-=1\n break\n count+=1\n return count/num_experiments\n" }, { "alpha_fraction": 0.48951730132102966, "alphanum_fraction": 0.4948805570602417, "avg_line_length": 33.779659271240234, "blob_id": "4819250e9aefb2a65c154d801bd78b4060041878", "content_id": "779f22e250fb4475561828a2c29ffaa5ba14b073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2051, "license_type": "no_license", "max_line_length": 78, "num_lines": 59, "path": "/Arithmetic Formatter/arithmetic_arranger.py", "repo_name": "GabrielSDesiderio/Python-Projects", "src_encoding": "UTF-8", "text": "def arithmetic_arranger(problems, statprint=False):\n # check problem list\n first = ''\n second = ''\n sumx = ''\n lines = ''\n # maximal problems is 5\n if len(problems) >= 6:\n return 'Error: Too many problems.'\n # split problem to separate components\n for i in problems:\n a = i.split()\n firsts = a[0]\n seconds = a[2]\n operands = a[1]\n # check the length of the number, max 4 digits\n if (len(firsts) > 4 or len(seconds) > 4):\n return \"Error: Numbers cannot be more than four digits.\"\n\n # check the input as valid digits\n if not firsts.isnumeric() or not seconds.isnumeric():\n return \"Error: Numbers must only contain digits.\"\n\n if (operands == '+' or operands == '-'):\n if operands == \"+\":\n sums = str(int(firsts) + int(seconds))\n else:\n sums = str(int(firsts) - int(seconds))\n # set length of sum and top, bottom and line values\n length = max(len(firsts), len(seconds)) + 2\n top = str(firsts).rjust(length)\n bottom = operands + str(seconds).rjust(length - 1)\n line = ''\n res = str(sums).rjust(length)\n for s in range(length):\n line += '-'\n # add to the overall string\n if i != problems[-1]:\n first += top + ' '\n second += bottom + ' '\n lines += line + ' '\n sumx += res + ' '\n else:\n first += top\n second += bottom\n lines += line\n sumx += res\n else:\n return \"Error: Operator must be '+' or '-'.\"\n # strip out spaces to the right of the string\n first.rstrip()\n second.rstrip()\n lines.rstrip()\n if statprint:\n sumx.rstrip()\n arranged_problems = first + '\\n' + second + '\\n' + lines + '\\n' + sumx\n else:\n arranged_problems = first + '\\n' + second + '\\n' + lines\n return arranged_problems" } ]
5
eimontheintamara/python-exercises
https://github.com/eimontheintamara/python-exercises
270333795dd22963ec8641f6a5378c7c6e99b77d
1cdc71d34bc986b0eae12c306f9d41c5ba069ab9
ef0700c1aa0fa1fd903eceb83f62e825be5065a4
refs/heads/master
2020-03-19T07:23:45.660218
2018-06-27T09:44:24
2018-06-27T09:44:24
136,110,058
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 33.5, "blob_id": "ca4f7a515b8803244421fc25a0b566c21f09b10b", "content_id": "c2de5d1ca04355e01d305b17780a3dc47be329ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "permissive", "max_line_length": 49, "num_lines": 2, "path": "/README.md", "repo_name": "eimontheintamara/python-exercises", "src_encoding": "UTF-8", "text": "# python-exercises\nRepo for exercises in learning Python the hardway\n" }, { "alpha_fraction": 0.4995024800300598, "alphanum_fraction": 0.4995024800300598, "avg_line_length": 42.69565200805664, "blob_id": "260182d80d115385d95e290592a08a965e131191", "content_id": "0b1e8f3106a0f0f34e6a0b48b04f3dd72dc7fe25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1005, "license_type": "permissive", "max_line_length": 141, "num_lines": 23, "path": "/ex48/skeleton/ex48/lexicon.py", "repo_name": "eimontheintamara/python-exercises", "src_encoding": "UTF-8", "text": "directions = ('north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back')\nverbs = ('go', 'stop', 'kill', 'eat', 'open')\nstop_words = ('the', 'in', 'of', 'from', 'at', 'it')\nnouns = ('door', 'bear', 'princess', 'cabinet')\n\ndef get_tuple(word):\n lowercased = word.lower()\n\n if lowercased in directions:\n return ('direction', lowercased)\n elif lowercased in verbs:\n return ('verb', lowercased)\n elif lowercased in stop_words:\n return ('stop', lowercased)\n elif lowercased in nouns:\n return ('noun', lowercased)\n elif lowercased.isdigit():\n return ('number', int(lowercased))\n else: # in case of error, return word with original casing\n return ('error', word)\ndef scan(sentence): \n words = sentence.split() \n return [get_tuple(word) for word in words]\n" }, { "alpha_fraction": 0.6292906403541565, "alphanum_fraction": 0.6407322883605957, "avg_line_length": 23.27777862548828, "blob_id": "2ca074bf955119ad68a6572df1b43c49e0389a27", "content_id": "ab35173efd1ef7d445e110fefb146c27569c528c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "permissive", "max_line_length": 69, "num_lines": 18, "path": "/ex34.py", "repo_name": "eimontheintamara/python-exercises", "src_encoding": "UTF-8", "text": "animals = ['bear', 'tiger', 'penguin', 'zebra']\nbear = animals [0]\nprint (bear)\n\nanimals.append(\"kangaroo\")\nanimals.append(\"whale\")\nanimals.append(\"platypus\")\nanimals.append(\"Ant\")\nanimals.append(\"cat\")\n\nfor ani in animals:\n print (f\"All animals are : {ani}\")\n\ni = 0\nfor anim in animals:\n print (f\"The first {i+1}st animal is at {i} and is a\", anim)\n print (f\"The animal at {i} is the {i+1}st animal and is a\", anim)\n i += 1\n" }, { "alpha_fraction": 0.601060688495636, "alphanum_fraction": 0.6028285026550293, "avg_line_length": 28.789474487304688, "blob_id": "63b946878f1eb59cbd6d01fe21a3f9b1618c34fd", "content_id": "6b17fb937ff696b448835f8f04580c27e110a20b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1697, "license_type": "permissive", "max_line_length": 116, "num_lines": 57, "path": "/ex36.py", "repo_name": "eimontheintamara/python-exercises", "src_encoding": "UTF-8", "text": "from sys import exit\n\n\ndef food_room():\n print(\"This is a room with a fil of many kinds of food with danger and safe food,So pick one kind of any food\")\n choice = input(\"> \")\n if \"burger\" in choice:\n print(\"That burger will turn into a gosh and catch you\")\n elif \"cheesecake\" in choice:\n print(\"That cake will turn into a monster and catch you\")\n else:\n print(\"You can safely eat your food\")\n\n\ndef witch_room():\n print(\"This room has a witch\")\n print(\"This room has clever broom,help people and bad black cat that catch people and give to his master-witch\")\n\n print(\"try yourself to escape from this bad room\")\n while True:\n choice = input(\"> \")\n if choice == \"broom\":\n escape()\n elif choice == \"cat\":\n print(\"Oh!you are really stupid.So you will panish \")\n angry()\n else:\n print(\"Oh!Poor person,you will be a servent forever for me\")\n witch_room()\n\n\ndef escape(why):\n print(why, \"You have Grate Good Job\")\n exit(0)\n\n\ndef angry():\n print(\"You must be placed at monster room\")\n print(\"There is 2 escape ways :steal king diamond room and place fire at cotton \")\n choice = input(\"> \")\n if choice == \"steal\" or choice == \"fire\":\n print(\"Con Con,you are escape from this room\")\n else:\n print(\"Sorry,monsters will fight you\")\n exit(0)\ndef start():\n print(\"Oh! you enter in a magic room.\")\n print(\"There is two rooms in your left and right.\")\n choice = input(\"> \")\n if choice == \"left\":\n food_room()\n elif choice == \"right\":\n witch_room()\n else:\n print(\"Please choice for your escape.\")\n\nstart()" }, { "alpha_fraction": 0.7388059496879578, "alphanum_fraction": 0.753731369972229, "avg_line_length": 32.5, "blob_id": "cecc3f47ea67118ccab5e57c954a234f67db6294", "content_id": "ed5b77808fa8e5eb32070d52be9e810aae4dc7ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/ex49/ex49t.py", "repo_name": "eimontheintamara/python-exercises", "src_encoding": "UTF-8", "text": "from ex48 import lexicon\nprint(lexicon.scan(\"go north\"))\nprint(lexicon.scan(\"kill the princess\"))\nprint(lexicon.scan(\"eat the bear\"))\n" } ]
5
kheaactua/conan-cmake_sanitizers
https://github.com/kheaactua/conan-cmake_sanitizers
72d41548a0e847bde61146a26ba36ee33e51f1c4
387e5740fbbe7200cf5a5b6efdd225d46b52365f
e6710487668913043945efd6953e40933dc629c1
refs/heads/master
2020-03-26T06:14:03.197278
2018-08-13T15:00:20
2018-08-13T15:48:22
144,595,436
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6494413614273071, "alphanum_fraction": 0.6564245820045471, "avg_line_length": 28.83333396911621, "blob_id": "17531c8113f1e9ad555ffc547bc9fd69468f4c3a", "content_id": "d22f42e38339837381c54ac0726074c5d578c01d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "no_license", "max_line_length": 77, "num_lines": 24, "path": "/conanfile.py", "repo_name": "kheaactua/conan-cmake_sanitizers", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom conans import ConanFile\n\n\nclass CmakesanitizersConan(ConanFile):\n name = 'cmake_sanitizers'\n version = '1.0'\n license = 'MIT'\n url = 'https://github.com/kheaactua/cmake-sanitizers'\n description = 'Import CMake find scripts to load compiler sanitizers'\n\n def source(self):\n self.run('git clone https://github.com/arsenm/sanitizers-cmake.git')\n\n def package(self):\n self.copy(pattern='*', src=os.path.join('sanitizers-cmake', 'cmake'))\n\n def package_info(self):\n self.env_info.CMAKE_SANITIZERS_PATH = self.package_folder\n\n# vim: ts=4 sw=4 expandtab ffs=unix ft=python foldmethod=marker :\n" } ]
1
Tigertammi13/ICDS-2021
https://github.com/Tigertammi13/ICDS-2021
4c28040e3d23e9377fa206cf32536e25cbde0028
269508108e0f4580ce12233078109905c89315e2
92a4bec59a3db2c6fa06f92712e56ed9ba97a2bd
refs/heads/main
2023-03-08T15:10:55.797891
2021-02-21T19:27:55
2021-02-21T19:27:55
340,604,115
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5852272510528564, "alphanum_fraction": 0.5852272510528564, "avg_line_length": 58, "blob_id": "4764484d234a8700279892bf92187770b810bc87", "content_id": "19799aae581208fa9fd2777363fc578fb740834c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 176, "license_type": "permissive", "max_line_length": 82, "num_lines": 3, "path": "/convert.py", "repo_name": "Tigertammi13/ICDS-2021", "src_encoding": "UTF-8", "text": "with open('samll_data.csv', 'r') as f_in, open('weather_small.csv', 'w') as f_out:\n f_out.write(next(f_in))\n [f_out.write(','.join(line.split()) + '\\n') for line in f_in]" } ]
1
UMD-DRASTIC/fedora-testbed
https://github.com/UMD-DRASTIC/fedora-testbed
539104893118c54cc7547579cd9516a2a22d62e5
e0c2ce9509ae445aebf826c38484e3ebda52fe5a
465988cddb9319e3e0bf4c33a75e743fd02a8409
refs/heads/master
2022-02-22T03:28:32.791287
2019-08-02T17:01:04
2019-08-02T17:01:04
109,315,258
0
0
null
2017-11-02T20:26:41
2017-11-02T20:40:00
2018-10-01T15:58:17
HTML
[ { "alpha_fraction": 0.8047456741333008, "alphanum_fraction": 0.8541880249977112, "avg_line_length": 6042.39990234375, "blob_id": "cf80e3b9e0faa36e50833f90f881db68f91b8dbe", "content_id": "e5ff112b9e32b5b72114a48058bcab13f6dfa701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 30217, "license_type": "no_license", "max_line_length": 18603, "num_lines": 5, "path": "/static/Fedora-reports/trellis-cassandra/test-output/old/Fedora API Specification Test Suite/groups.html", "repo_name": "UMD-DRASTIC/fedora-testbed", "src_encoding": "UTF-8", "text": "<h2>Groups used for this test run</h2><table border=\"1\">\n<tr> <td align=\"center\"><b>Group name</b></td><td align=\"center\"><b>Methods</b></td></tr><tr><td>MAY</td><td>Container.ldpIndirectContainerMayAllowLdpMembershipToBeUpdatedByPatch()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>LdprvHttpPut.changeLDPRToAnLDPRv()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpPut@44afefd5]<br/>Container.ldpIndirectContainerMayAllowLdpInsertedContentRelationPredicateToBeUpdatedByPut()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>Container.ldpIndirectContainerMayAllowLdpMembershipToBeUpdatedByPut()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>LdprmHttpOptions.ldprmOptionsMaySupportDelete()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpOptions@2687f956]<br/>Container.ldpDirectContainerMayAllowLdpIsMemberRelationPredicateToBeUpdatedByPut()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>StateToken.stateTokenGet()[pri:0, instance:org.fcrepo.spec.testsuite.crud.StateToken@ff6077]<br/>Container.ldpDirectContainerMayAllowLdpMembershipToBeUpdatedByPatch()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpPut.putCreateRDFSource()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>LdpcvHttpDelete.ldpcvMaySupportDelete()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpDelete@5f84abe8]<br/>ResourceVersioning.convertToLDPRViaPutWithType()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.ResourceVersioning@30135202]<br/>Container.createLDPIndirectContainer()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>StateToken.badStateTokenOnPutWhenStateTokensIgnored()[pri:0, instance:org.fcrepo.spec.testsuite.crud.StateToken@ff6077]<br/>WebACLinking.linkToAclOnCreation()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACLinking@6a4d7f76]<br/>Container.ldpIndirectContainerMayAllowLdpInsertedContentRelationToBeUpdatedByPatch()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>WebACCrossDomain.restrictGroupToLocal()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACCrossDomain@1e63d216]<br/>Container.ldpDirectContainerMayAllowLdpHasMemberRelationToBeUpdatedByPatch()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>WebACAccessToClass.accessToClassMayUseInference()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACAccessToClass@6edaa77a]<br/>HttpPut.putCreateNonRDFSource()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>ExternalBinaryContent.binaryContentNoTypeUnsupported()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>StateToken.badStateTokenOnPatchWhenStateTokensIgnored()[pri:0, instance:org.fcrepo.spec.testsuite.crud.StateToken@ff6077]<br/>LdpcvHttpPost.ldpcvMayDisallowPost()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>HttpPatch.ldpPatchContentTypeSupport()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPatch@18324f97]<br/>Container.ldpDirectContainerMayAllowLdpIsMemberRelationToBeUpdatedByPatch()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>LdpcvHttpPost.ldpcvMayDisallowPatch()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>Container.ldpIndirectContainerMayAllowLdpIsMemberRelationToBeUpdatedByPatch()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>ExternalBinaryContent.binaryContentNoTypeExternalType()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>Container.createLDPDirectContainer()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>LdpcvHttpPost.ldpcvMayDisallowPut()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>Container.ldpDirectContainerMayAllowLdpHasMemberRelationPredicateToBeUpdatedByPut()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpPut.httpPutChangeTypeAllowed()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>LdpcvHttpOptions.ldpcvMaySupportPost()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpOptions@4650a407]<br/>HttpGet.additionalValuesForPreferHeaderContainedDescriptions()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>StateToken.stateTokenHead()[pri:0, instance:org.fcrepo.spec.testsuite.crud.StateToken@ff6077]<br/>WebACCrossDomain.restrictAclToLocal()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACCrossDomain@1e63d216]<br/>Container.ldpIndirectContainerMayAllowLdpIsMemberRelationPredicateToBeUpdatedByPut()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>ExternalBinaryContent.binaryContentNoTypeDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>Container.ldpIndirectContainerMayAllowLdpHasMemberRelationToBeUpdatedByPatch()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>LdpcvHttpOptions.ldpcvMaySupportDeleteOption()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpOptions@4650a407]<br/>Container.ldpDirectContainerMayAllowLdpMembershipToBeUpdatedByPut()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>Container.ldpIndirectContainerMayAllowLdpHasMemberRelationPredicateToBeUpdatedByPut()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>LdpcvHttpOptions.ldpcvMaySupportPatch()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpOptions@4650a407]<br/></td></tr>\n<tr><td>MUST</td><td>WebACModes.writeAllowedPOST()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACRepresentation.dereferencingGroups()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACRepresentation@79767781]<br/>HttpPatch.disallowPatchContainmentTriples()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPatch@18324f97]<br/>LdpcvHttpPost.postToldpcvOfLdprsWithoutMementoDatetimeMustIgnoreBody()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>LdprvHttpGet.ldpvGetMustReturnOriginalResourceLink()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpGet@abbc908]<br/>HttpHead.httpHeadResponseDigest()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpHead@13cd7ea5]<br/>WebACModes.appendAllowedPATCH()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACGeneral.allAuthenticatedAgents()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACGeneral@aced190]<br/>LdpcvHttpPost.postToldpcvOfLdpnrWithoutMementoDatetimeMustIgnoreBody()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>LdprvHttpGet.ldpvGetMustReturnHeaderTimeGateTypeLink()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpGet@abbc908]<br/>Container.ldpIndirectContainerMustAllowHasMemberRelationPredicateToBeSetOnCreate()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpPut.httpPutUpdateTriples()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>ExternalBinaryContent.unsupportedBinaryContentHandlingAttribute()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>StateToken.badStateTokenOnPatchWhenStateTokensSupported()[pri:0, instance:org.fcrepo.spec.testsuite.crud.StateToken@ff6077]<br/>WebACModes.writeAllowedDELETE()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACModes.controlDisallowedPUT()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>HttpGet.responseDescribesHeader()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>ExternalBinaryContent.binaryContentRedirectStatusHead()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.externalBinaryContentHandlingStatus()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>LdprmHttpOptions.ldprmMustNotSupportPost()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpOptions@2687f956]<br/>WebACModes.controlAllowedGET()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACDefaultACLs.aclInheritanceMustUseLdpContainmentRelationships()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACDefaultACLs@245a060f]<br/>HttpPatch.disallowChangeResourceType()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPatch@18324f97]<br/>WebACAccessToClass.accessToClassMustGiveAccessToContainer()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACAccessToClass@6edaa77a]<br/>LdprmHttpGet.ldprmMustHaveMementoLinkHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpGet@9a7a808]<br/>WebACGeneral.agentGroupWithHashUris()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACGeneral@aced190]<br/>StateToken.badStateTokenOnPutWhenStateTokensSupported()[pri:0, instance:org.fcrepo.spec.testsuite.crud.StateToken@ff6077]<br/>LdpcvHttpGet.ldpcvMustRespondToGetWithApplicationLinkAcceptHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpGet@1ded7b14]<br/>HttpGet.respondWantDigestSha1()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>HttpPost.httpPost()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPost@2b97cc1f]<br/>WebACModes.readAllowedHEAD()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>LdprvHttpPut.ldprvMustSupportPUTForExistingResources()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpPut@44afefd5]<br/>Container.ldpDirectContainerMustAllowMembershipPredicateToBeSetByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>Container.ldpIndirectContainerMustAllowMembershipPredicateToBeSetByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>ExternalBinaryContent.binaryContentOptions()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>LdprvHttpGet.ldpvGetMustReturnVaryHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpGet@abbc908]<br/>Container.ldpIndirectContainerMustSetLdpMembershipResourceByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>ExternalBinaryContent.unsupportedExternalBinaryContentStatus()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>WebACModes.writeAllowedPUT()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>LdprmHttpDelete.ldprmMustSupportDeleteIfAdvertised()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpDelete@72209d93]<br/>WebACRepresentation.aclExamined()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACRepresentation@79767781]<br/>WebACModes.appendNotWriteLdpRsMust()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>LdprmHttpOptions.ldprmOptionsMustSupportGetHeadAndOptions()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpOptions@2687f956]<br/>HttpDelete.httpDeleteStatusCheckTwo()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpDelete@64f555e7]<br/>LdpcvHttpOptions.ldpcvMustReturnAcceptPostHeaderIfPostIsSupported()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpOptions@4650a407]<br/>WebACCrossDomain.rejectRemoteGroupStatus()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACCrossDomain@1e63d216]<br/>Container.ldpIndirectContainerMustAllowInsertedContentRelationPredicateToBeSetOnCreate()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpPut.httpPutUpdateDisallowedTriplesConstrainedByHeader()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>HttpPatch.statementNotPersistedResponseBody()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPatch@18324f97]<br/>HttpGet.respondWantDigestSha256()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>LdprvHttpPut.ldpnrvMustSupportPUT()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpPut@44afefd5]<br/>HttpGet.respondWantDigestTwoSupported()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>LdprmHttpGet.ldpnrmMustHaveMementoLinkHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpGet@9a7a808]<br/>ExternalBinaryContent.binaryContentGuaranteeHeaders()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>WebACModes.appendAllowedPOST()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACModes.controlDisallowedGET()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACRdfSources.aclIsLDPRS()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACRdfSources@78411116]<br/>HttpPut.putNonRDFSourceCreateLDPRS()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>LdpcvHttpGet.ldpcvMustHaveContainerLinkHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpGet@1ded7b14]<br/>WebACModes.controlAllowedPATCH()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>LdprmHttpOptions.ldprmMustNotSupportPut()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpOptions@2687f956]<br/>StateToken.goodStateTokenOnPatchWhenStateTokensSupported()[pri:0, instance:org.fcrepo.spec.testsuite.crud.StateToken@ff6077]<br/>HttpGet.respondWantDigestMd5()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>Container.ldpcContainmentTriples()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>WebACLinkHeaders.linkToAclExisting()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACLinkHeaders@53dfacba]<br/>WebACLinkHeaders.linkToAclNonexisting()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACLinkHeaders@53dfacba]<br/>LdpcvHttpOptions.ldpcvOptionsMustAllowHeadGetOptions()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpOptions@4650a407]<br/>WebACGeneral.agentSingle()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACGeneral@aced190]<br/>Container.ldpcMembershipTriples()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpPut.httpPutUpdateDisallowedTriplesResponse()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>WebACGeneral.agentAll()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACGeneral@aced190]<br/>LdpcvHttpOptions.ldpcvMustReturnAcceptPatchHeaderIfPatchIsSupported()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpOptions@4650a407]<br/>LdpcvHttpPost.ldpcvDoesNotSupportPost()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>LdprmHttpGet.ldpnrmMustSupportGet()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpGet@9a7a808]<br/>WebACModes.writeDisallowedPatch()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>LdprmHttpGet.ldprmMustSupportGet()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpGet@9a7a808]<br/>HttpGet.respondWantDigestTwoSupportedQvalueZero()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>LdprmHttpGet.ldpnrmMustHaveCorrectTimeGate()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpGet@9a7a808]<br/>Container.ldpIndirectContainerMustAllowIsMemberOfRelationPredicateToBeSetOnCreate()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>WebACModes.appendNotWritePutToCreate()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACModes.appendNotWriteLdpNr()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>LdpcvHttpOptions.ldpcvMustSupportOptions()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpOptions@4650a407]<br/>HttpPatch.supportPatch()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPatch@18324f97]<br/>WebACModes.writeAllowedPATCH()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>Container.ldpIndirectContainerMustAllowMembershipConstantURIToBeSet()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpPatch.successfulPatchStatusCode()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPatch@18324f97]<br/>WebACCrossDomain.rejectRemoteAclConstraint()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACCrossDomain@1e63d216]<br/>LdprvHttpGet.shouldReturn302WhenLdprmFromTimeGate()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpGet@abbc908]<br/>HttpGet.respondWantDigestNonSupported()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>WebACCrossDomain.rejectRemoteGroupConstraint()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACCrossDomain@1e63d216]<br/>HttpOptions.httpOptionsSupport()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpOptions@102d92c4]<br/>LdprvHttpGet.ldpvGetMustReturnTimeMapLink()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpGet@abbc908]<br/>WebACModes.writeDisallowedDelete()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>ExternalBinaryContent.binaryContentProxyWantDigest()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>HttpPost.postDigestResponseHeaderAuthentication()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPost@2b97cc1f]<br/>LdprmHttpOptions.ldprmMustSupportOptions()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpOptions@2687f956]<br/>LdpcvHttpGet.ldpcvMustHaveTimeMapLinkHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpGet@1ded7b14]<br/>ExternalBinaryContent.binaryContentRedirectWantDigest()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>LdprmHttpOptions.ldprmMustNotSupportPatch()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpOptions@2687f956]<br/>WebACGeneral.resourceSingle()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACGeneral@aced190]<br/>WebACModes.writeDisallowedPut()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACCrossDomain.rejectRemoteAclStatus()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACCrossDomain@1e63d216]<br/>HttpOptions.httpOptionsSupportAllow()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpOptions@102d92c4]<br/>WebACModes.writeDisallowedPost()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACRepresentation.accessDenied()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACRepresentation@79767781]<br/>WebACGeneral.agentDouble()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACGeneral@aced190]<br/>LdprvHttpPut.ldprvMustSupportPUT()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpPut@44afefd5]<br/>LdpcvHttpGet.ldpcvMustSupportGet()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpGet@1ded7b14]<br/>WebACModes.controlDisallowedPATCH()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACRepresentation.onlyAuthorizationStatementsUsed()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACRepresentation@79767781]<br/>HttpPost.postNonRDFSource()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPost@2b97cc1f]<br/>HttpPut.nonRDFSourcePutDigestResponseHeaderAuthentication()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>ExternalBinaryContent.unsupportedExternalBinaryContentConstraint()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>HttpPut.httpPutNR()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>HttpPatch.serverManagedPropertiesModification()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPatch@18324f97]<br/>WebACAccessToClass.accessToClassMustGiveAccessToBinary()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACAccessToClass@6edaa77a]<br/>LdprvHttpGet.ldpvGetMustReturnTimeGateTypeLink()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpGet@abbc908]<br/>LdprvHttpPut.ldpnrvMustSupportPUTForExistingResources()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpPut@44afefd5]<br/>Container.ldpIndirectContainerMustAllowInsertedContentRelationToBeSetByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpGet.responsePreferenceAppliedHeader()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>Container.ldpDirectContainerMustAllowIsMemberOfRelationPredicateToBeSetOnCreate()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>ResourceVersioning.postLdprWithType()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.ResourceVersioning@30135202]<br/>HttpGet.respondWantDigestTwoSupportedQvalueNonZero()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>Container.ldpDirectContainerMustSetLdpMembershipResourceByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpDelete.httpDeleteStatusCheck()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpDelete@64f555e7]<br/>Container.createLDPC()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>ExternalBinaryContent.externalBinaryContentHandlingAttribute()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>HttpHead.httpHeadResponseNoBody()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpHead@13cd7ea5]<br/>NotificationTest.testCatchMessage()[pri:0, instance:org.fcrepo.spec.testsuite.event.NotificationTest@62ddd21b]<br/>WebACModes.appendNotWriteLdpCMust()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACModes.controlAllowedPUT()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACRepresentation.aclRepresentation()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACRepresentation@79767781]<br/>LdpcvHttpGet.ldpcvMustIncludeAcceptPostIfPostAllowed()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpGet@1ded7b14]<br/>Container.ldpDirectContainerMustAllowMembershipConstantURIToBeSet()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>StateToken.goodStateTokenOnPutSucceedsWhenStateTokensSupported()[pri:0, instance:org.fcrepo.spec.testsuite.crud.StateToken@ff6077]<br/>Container.ldpcMinimalContainerTriples()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>WebACGeneral.agentGroup()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACGeneral@aced190]<br/>Container.ldpDirectContainerMustAllowHasMemberRelationPredicateToBeSetOnCreate()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>WebACModes.appendDisallowed()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>WebACModes.readAllowedGET()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>LdprmHttpGet.ldprmMustHaveCorrectTimeGate()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprmHttpGet@9a7a808]<br/>NotificationTest.testEventSerialization()[pri:0, instance:org.fcrepo.spec.testsuite.event.NotificationTest@62ddd21b]<br/>WebACLinking.conflictIfNotSupportingAclLink()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACLinking@6a4d7f76]<br/>ExternalBinaryContent.binaryContentRedirectStatusGet()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>HttpPost.postResourceAndCheckAssociatedResource()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPost@2b97cc1f]<br/>LdpcvHttpGet.lpcvMustIncludeAllowHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpGet@1ded7b14]<br/>LdprvHttpGet.ldpvGetMustReturnHeaderOriginalTypeLink()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpGet@abbc908]<br/>HttpPut.httpPutUpdateDisallowedTriples()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>ExternalBinaryContent.binaryContentMediaType()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>HttpPatch.statementNotPersistedConstrainedBy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPatch@18324f97]<br/>HttpGet.respondWantDigestNonSupportedWithSupported()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>LdpcvHttpGet.ldpcvMustIncludeAcceptPatchIfPatchAllowed()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpGet@1ded7b14]<br/>WebACModes.readDisallowed()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/></td></tr>\n<tr><td>SHOULD</td><td>Container.ldpIndirectContainerMustSetLdpMembershipResourceValueToLDPCByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>ExternalBinaryContent.postCreateExternalBinaryContentCopy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>LdpcvHttpPost.mementoDatetimeHeaderShouldMatchThatUsedWhenMementoCreated()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>Ldpnr.ldpnrCreationWrongLinkType()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Ldpnr@512d4583]<br/>ExternalBinaryContent.putCreateExternalFileUriBinaryCopy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>Container.ldpIndirectContainerShouldUseLdpMemberByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>ExternalBinaryContent.postCreateExternalFileUriBinaryProxy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.putCreateExternalFileUriBinaryRedirect()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.postCreateExternalBinaryContentRedirect()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>HttpHead.httpHeadResponseHeadersSameAsHttpGet()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpHead@13cd7ea5]<br/>HttpPut.httpPutChangeTypeNotAllowed()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>ExternalBinaryContent.putUpdateExternalFileUriBinaryRedirect()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>LdpcvHttpPost.ldpcvOfLdprsShouldSupportPostWithoutMementoDatetimeHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>WebACDefaultACLs.serverSuppliedDefaultAcl()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACDefaultACLs@245a060f]<br/>HttpDelete.httpDeleteOptionsCheck()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpDelete@64f555e7]<br/>ExternalBinaryContent.putUpdateExternalBinaryContentCopy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.putUpdateExternalBinaryContentProxy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>HttpGet.additionalValuesForPreferHeader()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpGet@2abc224d]<br/>ExternalBinaryContent.postCreateExternalFileUriBinaryCopy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>HttpPost.postDigestResponseHeaderVerification()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPost@2b97cc1f]<br/>Container.ldpIndirectContainerShouldUseLdpMemberSubjectByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>LdpcvHttpDelete.ldpcvThatAdvertisesDeleteShouldRemoveContainerAndMementos()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpDelete@5f84abe8]<br/>Ldpnr.ldpnrCreationLinkType()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Ldpnr@512d4583]<br/>ExternalBinaryContent.postCreateExternalFileUriBinaryRedirect()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.putCreateExternalFileUriBinaryProxy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>WebACDefaultACLs.defaultAclOnSameServer()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACDefaultACLs@245a060f]<br/>ExternalBinaryContent.putCreateExternalBinaryContentCopy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.putCreateExternalBinaryContentRedirect()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.putCreateExternalBinaryContentProxy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.putUpdateExternalBinaryContentRedirect()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.binaryContentContentTypeAndNoType()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.putUpdateExternalFileUriBinaryCopy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>Container.ldpDirectContainerMustSetLdpMembershipResourceValueToLDPCByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>LdprvHttpGet.shouldReturn406WhenNoLdprm()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdprvHttpGet@abbc908]<br/>WebACModes.appendNotWriteLdpRsShould()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACModes@10ec523c]<br/>ExternalBinaryContent.postCreateExternalBinaryContentProxy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>ExternalBinaryContent.binaryContentContentTypeAndType()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/>LdpcvHttpPost.ldpcvOfLdpnrsShouldSupportPostWithoutMementoDatetimeHeader()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>NotificationTest.testEventSerializationShould()[pri:0, instance:org.fcrepo.spec.testsuite.event.NotificationTest@62ddd21b]<br/>LdpcvHttpPost.postToldpcvOfLdprWithMementoDatetimeShouldCreateNewResource()[pri:0, instance:org.fcrepo.spec.testsuite.versioning.LdpcvHttpPost@29be7749]<br/>Container.ldpDirectContainerShouldUseLdpMemberByDefault()[pri:0, instance:org.fcrepo.spec.testsuite.crud.Container@5ecba515]<br/>HttpPut.nonRDFSourcePutDigestResponseHeaderVerification()[pri:0, instance:org.fcrepo.spec.testsuite.crud.HttpPut@60723d6a]<br/>WebACLinkHeaders.aclOnSameServer()[pri:0, instance:org.fcrepo.spec.testsuite.authz.WebACLinkHeaders@53dfacba]<br/>ExternalBinaryContent.putUpdateExternalFileUriBinaryProxy()[pri:0, instance:org.fcrepo.spec.testsuite.crud.ExternalBinaryContent@71178a52]<br/></td></tr>\n</table>\n" }, { "alpha_fraction": 0.5410334467887878, "alphanum_fraction": 0.5472446084022522, "avg_line_length": 33.552513122558594, "blob_id": "c2b8a41f01dff261f4b38900fcaeaf0ff94b9058", "content_id": "0d54e6f60b860a5502d6356a68464c982c8ff50b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7567, "license_type": "no_license", "max_line_length": 146, "num_lines": 219, "path": "/static/js/testbed.js", "repo_name": "UMD-DRASTIC/fedora-testbed", "src_encoding": "UTF-8", "text": "function TestResults(filterTermOrder) {\n this.filterTermOrder = filterTermOrder;\n this.filterTerms = {\n \"backend_nodes\": \"Backend Nodes\",\n \"frontend_nodes\": \"Frontend Nodes\",\n \"testworker_nodes\": \"Testing Nodes\",\n \"simulation\": \"Test Script\",\n \"testbed_commit\": \"Test Code Commit\",\n \"testbed_git_url\": \"Test Code Repo\",\n \"subject_commit\": \"LDP Code Commit\",\n \"subject_git_url\": \"LDP Code Repo\",\n \"subject_docker_name\": \"LDP Docker Name\",\n \"subject_docker_tag\": \"LDP Docker Tag\",\n \"jms_use_queue\": \"JMS Events Enabled\",\n \"cassandra_replication_factor\": \"C* Replication\",\n \"cassandra_binary_read_consistency\": \"C* Binary Read Consistency\",\n \"cassandra_binary_write_consistency\": \"C* Binary Write Consistency\",\n \"cassandra_rdf_write_consistency\": \"C* RDF Read Consistency\",\n \"cassandra_rdf_read_consistency\": \"C* RDF Write Consistency\",\n \"cassandra_max_chunk_size\": \"C* Max Chunk Size\"\n };\n this.activeFilters = {};\n}\n\n$.delete = function(url, data, callback, type){\n\n if ( $.isFunction(data) ){\n type = type || callback,\n callback = data,\n data = {}\n }\n\n return $.ajax({\n url: url,\n type: 'DELETE',\n success: callback,\n data: data,\n contentType: type\n });\n}\n\nfunction get(obj, searchterm) {\n var value = \"n/a\";\n if (searchterm in obj && obj[searchterm]['buckets'].length > 0) value = obj[searchterm]['buckets'][0]['key'];\n return value;\n}\n\nfunction copyToClipboard(text) {\n var $temp = $(\"<input>\");\n $(\"body\").append($temp);\n $temp.val(text).select();\n document.execCommand(\"copy\");\n $temp.remove();\n}\n\nTestResults.prototype.buildTable = function() {\n var me = this;\n var data;\n var snapshots = {};\n $.when(\n $.ajax( \"/sims\", {\n method: \"POST\",\n data: JSON.stringify(this.activeFilters),\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function(simdata) { data = simdata; },\n failure: function(errMsg) { console.log(errMsg); }\n } ),\n $.getJSON(\"/list_snapshots\", function(snapdata) {\n for(var snap of snapdata) {\n snapshots[snap['name']]=snap['key'];\n }\n })\n ).then(function() {\n var div = $('#testresults');\n div.empty();\n var filters = $('<ul></ul>');\n filters.appendTo(div);\n var table = $('<table class=\"results table table-striped\"></table>');\n table.appendTo(div);\n var th = \"<thead><tr>\";\n th += \"<th class='rotate'><div><span>Dashboard</span></div></th>\";\n th += \"<th class='rotate'><div><span>Date</span></div></th>\";\n me.filterTermOrder.forEach(function(t) {\n var label = me.filterTerms[t];\n th += \"<th data-term='\"+t+\"' class='term rotate'><div><span>\"+label+\"</span></div></th>\";\n });\n th += \"<th class='rotate'><div><span>OK</span></div></th>\";\n th += \"<th class='rotate'><div><span>KO</span></div></th>\";\n th += \"<th class='rotate'><div><span>Avg</span></div></th>\";\n th += \"<th class='rotate'><div><span>Max</span></div></th>\";\n th += \"<th class='rotate'><div><span>Min</span></div></th>\";\n th += \"</tr></thead>\";\n $(th).appendTo(table);\n tbody = $('<tbody></tbody>');\n tbody.appendTo(table);\n $.each(data, function (index, obj) {\n var name = obj['key'];\n var sim = get(obj, 'simulation');\n var to_ts = obj['Requests']['last_ts']['value'] + 60000;\n var from_ts = obj['Requests']['first_ts']['value'] - 60000;\n var time = obj['Requests']['first_ts']['value'];\n var dt = new Date();\n dt.setTime(time);\n var ok = 0;\n var ko = 0;\n for(var st of obj.Requests.status.buckets) {\n if(st.key == \"OK\") {\n ok = st.doc_count;\n } else if (st.key == \"KO\") {\n ko = st.doc_count;\n }\n }\n var count = Math.round(obj['Requests']['req_duration_stats']['count']);\n var avg = Math.round(obj['Requests']['req_duration_stats']['avg']);\n var max = Math.round(obj['Requests']['req_duration_stats']['max']);\n var min = Math.round(obj['Requests']['req_duration_stats']['min']);\n var grafana_link = `http://drastic-testbed.umd.edu:3000/d/MwnPtQfiz/ldp-performance-test-dashboard?orgId=1&from=${from_ts}&to=${to_ts}`;\n\n let el = \"<tr>\";\n\n let snapshot_link = null;\n if(name in snapshots) {\n snapshot_key = snapshots[name];\n snapshot_link = `http://drastic-testbed.umd.edu:3000/dashboard/snapshot/${snapshot_key}`;\n }\n let code_link = get(obj, \"subject_git_url\");\n if(code_link.startsWith(\"git@\")) {\n code_link = code_link.replace(\":\",\"/\");\n code_link = code_link.substring(4, code_link.length);\n code_link = \"https://\" + code_link;\n code_link = code_link.substring(0, code_link.length - 4);\n }\n code_link += \"/commit/\";\n let commit = get(obj, \"subject_commit\");\n let regex = /.*\\-.*\\-\\d\\.\\d\\-\\d+\\-(.*)\\-?.*/;\n let matches = commit.match(regex);\n if(matches !== null && matches.length > 0) {\n commit = matches[1];\n }\n let dirt = \"-dirty\";\n if(commit.endsWith(dirt)) {\n commit = commit.substring(0, commit.length - dirt.length);\n }\n code_link += commit;\n\n\n el += \"<td>\";\n if(snapshot_link != null) {\n el += \"<a title='Grafana snapshot (public)' href='\"+snapshot_link+\"'><img height='35px' width='35px' src='/static/graph-icon.png'/></a> \";\n } else {\n el += \"<a title='Grafana dashboard (private)' href='\"+grafana_link+\"'>panel</a><br />\";\n el += \"<a class='delidx' data-name='\"+name+\"'>del index</a><br />\";\n el += \"<a class='copyidx' data-name='\"+name+\"'>index name</a>\";\n }\n el += \"<br /><a title='Link to Code commit in repository' href='\"+code_link+\"'>commit</a>\";\n el += \"</td>\";\n\n dateStr = dt.getFullYear() + '-' +\n ('0' + (dt.getMonth()+1)).slice(-2) + '-' +\n ('0' + dt.getDate()).slice(-2);\n el += \"<td>\"+dateStr+\"</td>\";\n\n // Gather ye sim aggregate term values.\n for(var t of me.filterTermOrder) {\n var value = get(obj, t);\n el += \"<td data-term='\"+t+\"' data-value='\"+value+\"' class='term'>\"+value+\"</td>\";\n }\n\n el += \"<td>\"+ok+\"</td>\";\n el += \"<td>\"+ko+\"</td>\";\n el += \"<td>\"+avg+\"</td>\";\n el += \"<td>\"+max+\"</td>\";\n el += \"<td>\"+min+\"</td>\";\n\n el += \"</tr>\";\n $(el).appendTo(tbody);\n\n // Add filter term/value when clicked\n $('td.term').off().click(function(e) {\n var t = $(this).data(\"term\");\n var v = $(this).data(\"value\");\n me.activeFilters[t] = v;\n me.buildTable();\n return false;\n });\n });\n // Allow removal of a filter term/value\n filters.empty();\n me.filterTermOrder.forEach(function(t) {\n if(t in me.activeFilters) {\n $(\"<li data-term='\"+t+\"'>\"+me.filterTerms[t]+\": '\"+me.activeFilters[t]+\"'</li>\").off().click(function(e) {\n var term = $(this).data(\"term\");\n delete me.activeFilters[term];\n me.buildTable();\n return false;\n }).appendTo(filters);\n }\n });\n $('a.delidx').off().click(function(e) {\n var name = $(this).data(\"name\");\n var text = \"curl -XDELETE http://localhost:9200/\"+name;\n copyToClipboard(text);\n return false;\n });\n $('a.copyidx').off().click(function(e) {\n var name = $(this).data(\"name\");\n copyToClipboard(name);\n return false;\n });\n\n var dtable = table.DataTable({\n paging: false,\n searching: false,\n scrollY: '400px',\n order: [[1, 'desc']]\n });\n });\n};\n" }, { "alpha_fraction": 0.8510638475418091, "alphanum_fraction": 0.8510638475418091, "avg_line_length": 6.833333492279053, "blob_id": "951526bb0808bfa9b6049f3466a99794df3bed48", "content_id": "7eb453a000dd5a713d7914fb088835d1038fe4db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 47, "license_type": "no_license", "max_line_length": 10, "num_lines": 6, "path": "/requirements.txt", "repo_name": "UMD-DRASTIC/fedora-testbed", "src_encoding": "UTF-8", "text": "flask\nflask-cors\nrequests\nPyYAML\nPyLD\ngunicorn\n" }, { "alpha_fraction": 0.5723035335540771, "alphanum_fraction": 0.5825110673904419, "avg_line_length": 30.26595687866211, "blob_id": "86ccfe2c5de7715ba05df2007cb5210712bcb144", "content_id": "ed42b43baec322b5527cb7547dbd69ef801591f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5878, "license_type": "no_license", "max_line_length": 114, "num_lines": 188, "path": "/flask_app.py", "repo_name": "UMD-DRASTIC/fedora-testbed", "src_encoding": "UTF-8", "text": "import os\nimport logging\nimport logging.config\nfrom logging import handlers\nimport json\nimport requests\nfrom flask import Flask, jsonify, request, session, g, redirect, url_for, render_template, make_response, Response\nfrom flask_cors import CORS\n\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config.from_object(__name__)\napp.logger.setLevel(logging.DEBUG)\nhandler = handlers.RotatingFileHandler(\n os.path.join(app.instance_path, 'flask.log'),\n maxBytes=1024 * 1024 * 100,\n backupCount=20)\napp.logger.addHandler(handler)\n\nelasticsearch_url = os.getenv('ELASTICSEARCH_URL', default='http://localhost:9200')\ngrafana_url = os.getenv('GRAFANA_URL', default='http://localhost:3000')\ngrafana_authz_token = os.getenv(\"GRAFANA_AUTHZ_TOKEN\")\napp.config.update(dict(\n # DATABASE=os.path.join(app.instance_path, 'sqlite3.db'),\n DEBUG=True,\n USERNAME='admin',\n PASSWORD='default',\n SECRET_KEY='INSECURE_DEVELOPMENT_KEY',\n PROPAGATE_EXCEPTIONS=True\n))\n\nSIM_FILTER_TERMS = [\n \"backend_nodes\",\n \"frontend_nodes\",\n \"testworker_nodes\",\n \"simulation\",\n \"testbed_commit\",\n \"testbed_git_url\",\n \"subject_commit\",\n \"subject_git_url\",\n \"subject_docker_name\",\n \"subject_docker_tag\",\n \"jms_use_queue\",\n \"cassandra_replication_factor\",\n \"cassandra_binary_read_consistency\",\n \"cassandra_binary_write_consistency\",\n \"cassandra_rdf_write_consistency\",\n \"cassandra_rdf_read_consistency\",\n \"cassandra_max_chunk_size\"]\n\n\[email protected](404)\ndef page_not_found(error):\n return 'This route does not exist {}'.format(request.url), 404\n\n\[email protected]('/')\ndef welcome():\n response = make_response(render_template('index.html'))\n response.headers['Access-Control-Allow-Origin'] = 'http://localhost:9200'\n return response\n\n\[email protected]('/bytes-in-format')\ndef bytes_in_format():\n return format_report(inbytes=True)\n\n\[email protected]('/files-in-format')\ndef format_report(inbytes=False):\n inventory_url = \"{0}/ciber-file-extensions/_search\".format(elasticsearch_url)\n sort_field = 'bytes_in_format.value' if inbytes else 'doc_count'\n q_extensions = '''{{\n \"size\": 100,\n \"_source\": [ \"mimetype\", \"key\", \"doc_count\", \"bytes_in_format.value\" ],\n \"query\": {{\n \"match_all\": {{}}\n }},\n \"sort\": [\n {{ \"{0}\": \"desc\" }}\n ]\n}}'''.format(sort_field)\n headers = {'cache-control': \"no-cache\"}\n response = requests.request(\"POST\", inventory_url, data=q_extensions, headers=headers).json()\n return jsonify(response)\n\n\[email protected]('/list_snapshots')\ndef list_snapshots():\n url = \"{0}/api/dashboard/snapshots\".format(grafana_url)\n headers = {\n 'Accept': 'application/json',\n 'Authorization': grafana_authz_token\n }\n return jsonify(requests.request(\"GET\", url, headers=headers).json())\n\n\[email protected]('/sims', methods=['POST', 'GET'])\ndef sims():\n app.logger.info(\"starting\")\n sims = None\n if request.method == 'POST' and request.json is not None and len(request.json) > 0:\n app.logger.info(\"get terms in POST JSON:\\n\"+json.dumps(request.json, indent=2))\n terms = {}\n for name in request.json:\n if name in SIM_FILTER_TERMS:\n terms[name + '.keyword'] = request.json[name]\n app.logger.info(json.dumps(terms, indent=2))\n sims = get_filtered_sims(terms)\n app.logger.info(\"sims: \"+str(sims) )\n url = \"{0}/gatling-ldp-%2A/_search\".format(elasticsearch_url)\n payload = '''{\n \"size\": 0,\n \"aggs\": {\n \"simulations\": {\n \"terms\": {\n \"field\": \"_index\",\n \"size\": 50,\n \"order\": {\n \"start\": \"desc\"\n }\n },\n \"aggs\": {\n \"Requests\": {\n \"filter\": {\"type\": {\"value\": \"REQUEST\"} },\n \"aggs\": {\n \"last_ts\": {\"max\": {\"field\": \"@timestamp\"} },\n \"first_ts\": {\"min\": {\"field\": \"@timestamp\"} },\n \"req_duration_stats\" : { \"stats\" : { \"field\" : \"duration\" } },\n \"status\": { \"terms\": { \"field\": \"okay\" } }\n }\n },\n \"start\": {\"min\": {\"field\": \"@timestamp\"} }\n }\n }\n }\n}'''\n req_body = json.loads(payload)\n\n # Add aggregations for each sim query term\n for t in SIM_FILTER_TERMS:\n req_body['aggs']['simulations']['aggs'][t] = {\"terms\": {\"field\": t +'.keyword'} }\n if sims is not None:\n if len(sims) == 0:\n # No sims match the query terms.\n return jsonify([])\n else:\n req_body['query'] = { 'terms': { '_index' : sims } }\n app.logger.info(json.dumps(req_body, indent=2))\n headers = {\n 'content-type': \"application/json\",\n 'cache-control': \"no-cache\"\n }\n response = requests.request(\"POST\", url, data=json.dumps(req_body), headers=headers).json()\n # app.logger.info(json.dumps(response, indent=2))\n result = []\n try:\n result = response['aggregations']['simulations']['buckets']\n except KeyError:\n app.logger.warn(\"Got the keyerror\")\n pass\n return jsonify(result)\n\n\ndef get_filtered_sims(terms):\n url = \"{0}/gatling-ldp-%2A/_search\".format(elasticsearch_url)\n q = { 'size': 100, '_source': ['_index'], 'query': { 'bool': { 'filter': [] } } }\n for t in terms:\n clause = { 'term': { t: terms[t] }}\n q['query']['bool']['filter'].append(clause)\n headers = {\n 'content-type': \"application/json\",\n 'cache-control': \"no-cache\"\n }\n app.logger.info(json.dumps(q, indent=2))\n response = requests.request(\"POST\", url, data=json.dumps(q), headers=headers).json()\n result = []\n try:\n for hit in response['hits']['hits']:\n result.append(hit['_index'])\n except KeyError:\n pass\n return result\n\n\nif __name__ == '__main__':\n app.run(\"0.0.0.0\", processes=5)\n" }, { "alpha_fraction": 0.8653846383094788, "alphanum_fraction": 0.8653846383094788, "avg_line_length": 52, "blob_id": "83faae983cfd8d2c5f02112f5e19c2f3f540622c", "content_id": "4a33ce1faa0746c591d193f0652d4ab4d36f2cc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 52, "num_lines": 1, "path": "/static/Fedora-reports/trellis-ext-db/test-output/old/Fedora API Specification Test Suite/Fedora API Specification Tests.properties", "repo_name": "UMD-DRASTIC/fedora-testbed", "src_encoding": "UTF-8", "text": "[SuiteResult context=Fedora API Specification Tests]" } ]
5
kpriyanshu256/AnimeVsCartoon
https://github.com/kpriyanshu256/AnimeVsCartoon
2552866579021da685fa175ffc7d153a0f210a65
213cf2c9c9da657f01ecca44085471cc0fb190da
efcdb180adcf067058984bdf8f38934831c53a5d
refs/heads/master
2021-06-04T13:31:31.315107
2021-05-04T03:08:42
2021-05-04T03:08:42
135,837,140
4
1
null
null
null
null
null
[ { "alpha_fraction": 0.6415094137191772, "alphanum_fraction": 0.704402506351471, "avg_line_length": 22.615385055541992, "blob_id": "af51460535fcf8a3f19efb35300ab72eefe218fe", "content_id": "25a24df45bb143f63eb8a0a8c92036547f366973", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "no_license", "max_line_length": 41, "num_lines": 13, "path": "/Classifier.py", "repo_name": "kpriyanshu256/AnimeVsCartoon", "src_encoding": "UTF-8", "text": "from keras.models import load_model\r\nimport numpy as np\r\nimport cv2\r\n \r\nimg_file='Test5.jpg'\r\nimg=cv2.imread(img_file,cv2.IMREAD_COLOR)\r\nimg=cv2.resize(img,(120,80))\r\nimg1 = img[:,:]\r\nimg1=np.array(img1,dtype=np.float64)\r\nimg1=np.expand_dims(img1,axis=0)\r\n\r\ncnn=load_model(\"VGG_model.h5\")\r\nscore = cnn.predict(img1)" }, { "alpha_fraction": 0.6265110373497009, "alphanum_fraction": 0.6511046290397644, "avg_line_length": 30.863014221191406, "blob_id": "c6c4ce504d8116dad516ca79c6f5e646468ee78c", "content_id": "7da8fb83cb4f60cea16da336dd7964006a8dc699", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2399, "license_type": "no_license", "max_line_length": 135, "num_lines": 73, "path": "/AnimeOrCartoon.py", "repo_name": "kpriyanshu256/AnimeVsCartoon", "src_encoding": "UTF-8", "text": "import pickle\r\nimport numpy as np\r\nimport tflearn\r\nfrom sklearn.model_selection import train_test_split\r\nfrom tflearn.data_preprocessing import ImagePreprocessing\r\nfrom tflearn.data_augmentation import ImageAugmentation\r\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\r\nfrom tflearn.layers.core import input_data, dropout, fully_connected\r\nfrom tflearn.layers.estimator import regression\r\n\r\n# Function to load data from pickled file\r\ndef load_data(file):\r\n file=open(file,'rb')\r\n data=pickle.load(file)\r\n file.close()\r\n return data\r\n\r\n# Function to segregate data\r\ndef process_data(d):\r\n A=d['anime']\r\n C=d['cartoon']\r\n a=len(A)\r\n c=len(C)\r\n m=a+c\r\n y=np.zeros(shape=(m,2))\r\n y[0:a,0]=1\r\n y[a:,1]=1\r\n X=[]\r\n for i in A:\r\n X.append(i)\r\n for i in C:\r\n X.append(i)\r\n X=np.array(X)\r\n return X,y\r\n \r\n# Model\r\ndef cnn(X_train,y_train,X_test,y_test):\r\n # Image processing\r\n img_prep = ImagePreprocessing()\r\n img_prep.add_featurewise_zero_center()\r\n img_prep.add_featurewise_stdnorm()\r\n\r\n # Real-time data augmentation\r\n img_aug = ImageAugmentation()\r\n img_aug.add_random_flip_leftright()\r\n img_aug.add_random_rotation(max_angle=25.)\r\n\r\n # Convolutional network building\r\n network = input_data(shape=[None, 80, 120, 3],data_preprocessing=img_prep,data_augmentation=img_aug)\r\n network = conv_2d(network, 32, 5, activation='relu')\r\n network = max_pool_2d(network, 3)\r\n network = conv_2d(network, 64, 5, activation='relu')\r\n network = conv_2d(network, 64, 5, activation='relu')\r\n network = max_pool_2d(network, 3)\r\n network = fully_connected(network, 512, activation='relu')\r\n network = dropout(network, 0.5)\r\n network = fully_connected(network, 2, activation='softmax')\r\n network = regression(network, optimizer='adam',loss='categorical_crossentropy',learning_rate=0.001)\r\n \r\n model = tflearn.DNN(network, tensorboard_verbose=0)\r\n model.fit(X_train, y_train, n_epoch=40, shuffle=True, validation_set=(X_test, y_test),show_metric=True, batch_size=96, run_id='AC')\r\n \r\n model.save('CNN.tflearn')\r\n \r\n \r\nif __name__=='__main__':\r\n file='NewData.pkl'\r\n data=load_data(file)\r\n X,y=process_data(data)\r\n X=X[0:6400,:,:,:]\r\n y=y[0:6400,:]\r\n X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)\r\n cnn(X_train,y_train,X_test,y_test)\r\n" }, { "alpha_fraction": 0.6314433217048645, "alphanum_fraction": 0.6578608155250549, "avg_line_length": 25.228069305419922, "blob_id": "1436d80fa92d2400ea0b7501cbe45f2f68266850", "content_id": "451fbbf636dcaf53e83e69820d7269941e8c9960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1552, "license_type": "no_license", "max_line_length": 123, "num_lines": 57, "path": "/AnimeOrCartoon_TransferLearning.py", "repo_name": "kpriyanshu256/AnimeVsCartoon", "src_encoding": "UTF-8", "text": "from keras import applications\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras import optimizers\r\nfrom keras.models import Sequential, Model \r\nfrom keras.layers import Dropout, Flatten, Dense\r\nimport pickle\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndef load_data(file):\r\n file=open(file,'rb')\r\n data=pickle.load(file)\r\n file.close()\r\n return data\r\n\r\ndef process_data(d):\r\n A=d['anime']\r\n C=d['cartoon']\r\n a=len(A)\r\n c=len(C)\r\n m=a+c\r\n y=np.zeros(shape=(m,2))\r\n y[0:a,0]=1\r\n y[a:,1]=1\r\n X=[]\r\n for i in A:\r\n X.append(i)\r\n for i in C:\r\n X.append(i)\r\n X=np.array(X)\r\n return X,y\r\n\r\nfile='NewData.pkl'\r\ndata=load_data(file)\r\nX,y=process_data(data)\r\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)\r\n\r\nimg_width=80\r\nimg_height=120\r\n\r\nmodel = applications.VGG19(weights = \"imagenet\", include_top=False, input_shape = (img_width, img_height, 3))\r\n\r\nfor layer in model.layers[:5]:\r\n layer.trainable = False\r\n\r\nx = model.output\r\nx = Flatten()(x)\r\nx = Dense(1024, activation=\"relu\")(x)\r\nx = Dropout(0.5)(x)\r\nx = Dense(512, activation=\"relu\")(x)\r\npredictions = Dense(2, activation=\"softmax\")(x)\r\n\r\nmodel = Model(inputs = model.input, outputs = predictions)\r\nmodel.compile(loss = \"categorical_crossentropy\", optimizer = optimizers.SGD(lr=0.0001, momentum=0.9), metrics=[\"accuracy\"])\r\nmodel.fit(X_train, y_train, batch_size=96, epochs=40)\r\nscore = model.evaluate(X_test, y_test, batch_size=96)\r\nmodel.save(\"VGG_model.h5\")\r\n" }, { "alpha_fraction": 0.7451612949371338, "alphanum_fraction": 0.7849462628364563, "avg_line_length": 32.21428680419922, "blob_id": "53fb19ea3ce0618444e310c4954e0eb6db0d162e", "content_id": "988d7533e8987aff122964362d30aa77e614ce72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 930, "license_type": "no_license", "max_line_length": 109, "num_lines": 28, "path": "/README.md", "repo_name": "kpriyanshu256/AnimeVsCartoon", "src_encoding": "UTF-8", "text": "# AnimeVsCartoon\n\nThe main objective is to train an artificial neural network to classify anime and cartoons\n\n## Dataset\nThe dataset is self-mined using Google Chrome's Fatkun Batch Image Downloader Extension.\nThe dataset contains around 6000 images with almost equal number of images of anime and cartoons\n\nLink to dataset\nhttps://drive.google.com/file/d/1qhcyBgIVjgTap1q3Xiw3RH-zSfPV0Kmv/view?usp=sharing\n\n## Model 1\nThe model used is a convolutional neural network.\n\n## Model 2\nThis model uses the initial pre-trained layers of VGG-19.\n\nWeights of the above model\nhttps://drive.google.com/file/d/1Ql6QXMdC0sj2AD2bs6F7Vq37jrREU3kg/view?usp=sharing\n\n## Results\n # Model 1 \n Has a 96.07% training accuracy and a 86.67% test accuracy.\n # Model 2\n Has a 99% training accuracy and a 90% test accuracy.\n \n## Future Scope\nFacial features differ a lot in anime and cartoon. This fact can be exploited to build more efficient models.\n" }, { "alpha_fraction": 0.5362775921821594, "alphanum_fraction": 0.5599368810653687, "avg_line_length": 18.25806427001953, "blob_id": "9483c47bf08f3305f0d55e2e22e2b02277e33825", "content_id": "80832ded38688dad4f4a4097d08624bb105912ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 634, "license_type": "no_license", "max_line_length": 65, "num_lines": 31, "path": "/Data.py", "repo_name": "kpriyanshu256/AnimeVsCartoon", "src_encoding": "UTF-8", "text": "import os\r\nimport cv2\r\nimport numpy as np\r\nimport pickle\r\n\r\ndef prepare_data(folder):\r\n data=[]\r\n for j in os.listdir(folder):\r\n for i in os.listdir(folder+'\\\\'+j):\r\n img=cv2.imread(folder+'\\\\'+j+'\\\\'+i,cv2.IMREAD_COLOR)\r\n img=cv2.resize(img,(120,80))\r\n img1 = img[:,:]\r\n img1=np.array(img1,dtype=np.float64)\r\n data.append(img1)\r\n return data\r\n\r\n\r\ndir=os.getcwd()\r\n\r\nA=dir+'\\Anime'\r\nC=dir+'\\Cartoon'\r\na=prepare_data(A)\r\nc=prepare_data(C)\r\n\r\ndata={}\r\ndata['anime']=a\r\ndata['cartoon']=c\r\n\r\nsave=open('NewData.pkl','wb')\r\npickle.dump(data,save)\r\nsave.close()\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5798319578170776, "alphanum_fraction": 0.6113445162773132, "avg_line_length": 25.36231803894043, "blob_id": "0c1ec68a7594bc2c7502c9465b607015083ea33a", "content_id": "965bec9ba1331ac50380bcf3128e2dfa8fcaa4c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1904, "license_type": "no_license", "max_line_length": 84, "num_lines": 69, "path": "/AnimeOrCartoon_keras.py", "repo_name": "kpriyanshu256/AnimeVsCartoon", "src_encoding": "UTF-8", "text": "import pickle\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nfrom keras.models import Sequential,Model\r\nfrom keras.layers import Dense, Dropout, Flatten,Conv2D, MaxPooling2D\r\nfrom keras.optimizers import Adam\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras import optimizers\r\n\r\n\r\nfrom keras import backend as K\r\nK.tensorflow_backend._get_available_gpus()\r\n\r\ndef load_data(file):\r\n file=open(file,'rb')\r\n data=pickle.load(file)\r\n file.close()\r\n return data\r\n\r\ndef process_data(d):\r\n A=d['anime']\r\n C=d['cartoon']\r\n a=len(A)\r\n c=len(C)\r\n m=a+c\r\n y=np.zeros(shape=(m,2))\r\n y[0:a,0]=1\r\n y[a:,1]=1\r\n X=[]\r\n for i in A:\r\n X.append(i)\r\n for i in C:\r\n X.append(i)\r\n X=np.array(X)\r\n return X,y\r\n\r\n\r\ndef model(X,y):\r\n net=Sequential()\r\n net.add(Conv2D(32,(5,5), activation='relu', input_shape=(80,120,3)))\r\n net.add(MaxPooling2D(pool_size=(3, 3)))\r\n net.add(Conv2D(64,(5,5), activation='relu'))\r\n net.add(Conv2D(64,(5,5), activation='relu'))\r\n net.add(MaxPooling2D(pool_size=(3, 3)))\r\n net.add(Flatten())\r\n net.add(Dense(512,activation='relu'))\r\n net.add(Dropout(0.5))\r\n net.add(Dense(1,activation='softmax'))\r\n \r\n opt = optimizers.SGD(lr=0.0001, momentum=0.8)\r\n net.compile(loss = \"binary_crossentropy\", optimizer = opt, metrics=[\"accuracy\"])\r\n\r\n \r\n net.fit(X, y, batch_size=96, epochs=1)\r\n #net.save('Custom.h5')\r\n return net\r\n\r\nif __name__=='__main__':\r\n file='NewData.pkl'\r\n data=load_data(file)\r\n X,y=process_data(data)\r\n \r\n X,X_test,y,y_test=train_test_split(X,y,test_size=0.1)\r\n X_train,X_dev,y_train,y_dev=train_test_split(X,y,test_size=0.1)\r\n\r\n cnn=model(X_train,y_train)\r\n print('Dev= ',cnn.evaluate(X_dev, y_dev, batch_size=96))\r\n print('Test= ',cnn.evaluate(X_test, y_test, batch_size=96))\r\n \r\n \r\n " } ]
6
coderslav/TM_Currency_Bot
https://github.com/coderslav/TM_Currency_Bot
6ad801eaadb9d29a8888a52a67ed2851de1a3bc3
41e60f105db9a3d9d098150647023c4d8d8bc15f
7e0e62d3d5e6f86daf13dc1f0973ad9d088f4df1
refs/heads/main
2023-02-27T16:05:23.449692
2021-02-04T19:16:46
2021-02-04T19:16:46
334,714,489
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6660078763961792, "alphanum_fraction": 0.6660078763961792, "avg_line_length": 28.764705657958984, "blob_id": "4df1efdfd517e079a4be945238193b09dae1dc13", "content_id": "fc43cd104b3b85bd601fb8eda7411f712abe7771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 537, "license_type": "no_license", "max_line_length": 112, "num_lines": 17, "path": "/extensions.py", "repo_name": "coderslav/TM_Currency_Bot", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\n\nclass APIrequest:\n @staticmethod\n def get_price(what_convert, convert_to, amount):\n r = requests.get(f\"https://min-api.cryptocompare.com/data/price?fsym={what_convert}&tsyms={convert_to}\")\n r_text = json.loads(r.content)\n float_price = float(*r_text.values())\n return f\"{(float_price * amount):f} {convert_to.upper()}\"\n\n\nclass APIException(Exception):\n @staticmethod\n def message():\n return \"Ошибка ввода или отсутствующая пара\"\n" }, { "alpha_fraction": 0.4084033668041229, "alphanum_fraction": 0.43529412150382996, "avg_line_length": 34, "blob_id": "7cda3a1337e5e12ee9740a2cdd188c9241ec2b85", "content_id": "a24d499db961a649ba5481132757c39cb145da0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 638, "license_type": "no_license", "max_line_length": 70, "num_lines": 17, "path": "/test.py", "repo_name": "coderslav/TM_Currency_Bot", "src_encoding": "UTF-8", "text": "available_pairs = {\"eur\": \"eur\", \"euro\": \"eur\", \"евро\": \"eur\",\n \"usd\": \"usd\", \"dollar\": \"usd\", \"доллар\": \"usd\",\n \"uah\": \"uah\", \"hryvna\": \"uah\", \"гривна\": \"uah\",\n \"rub\": \"rub\", \"ruble\": \"rub\", \"рубль\": \"rub\",\n \"btc\": \"btc\", \"bitcoin\": \"btc\", \"биткоин\": \"btc\",\n \"eth\": \"eth\", \"ethereum\": \"eth\", \"эфириум\": \"eth\",\n \"dot\": \"dot\", \"polkadot\": \"dot\", \"полкадот\": \"dot\"}\n\nx = available_pairs.values()\nfor i in x:\n print(i)\n\nprint(\"\\U0001F937\")\n\nt = 2.729e-05\nt1 = format(t, '.8f')\nprint(t1)\n" }, { "alpha_fraction": 0.537182629108429, "alphanum_fraction": 0.5596495270729065, "avg_line_length": 58.3466682434082, "blob_id": "53ea3fcf2266771bc782518adc9a1e8d6e1a847c", "content_id": "414ee47ad051a41cf29806fedc4dd583a57efe85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5431, "license_type": "no_license", "max_line_length": 120, "num_lines": 75, "path": "/main_bot.py", "repo_name": "coderslav/TM_Currency_Bot", "src_encoding": "UTF-8", "text": "import telebot\nimport launch_bot\nimport extensions\n\nTOKEN = launch_bot.token\nbot = telebot.TeleBot(TOKEN)\navailable_pairs = {\"eur\": \"eur\", \"euro\": \"eur\", \"евро\": \"eur\",\n \"usd\": \"usd\", \"dollar\": \"usd\", \"доллар\": \"usd\",\n \"uah\": \"uah\", \"hryvna\": \"uah\", \"гривна\": \"uah\",\n \"rub\": \"rub\", \"ruble\": \"rub\", \"рубль\": \"rub\",\n \"btc\": \"btc\", \"bitcoin\": \"btc\", \"биткоин\": \"btc\",\n \"eth\": \"eth\", \"ethereum\": \"eth\", \"эфириум\": \"eth\",\n \"dot\": \"dot\", \"polkadot\": \"dot\", \"полкадот\": \"dot\"}\navailable_commands = \"Список доступных команд:\\n/start - перезагрузка бота\\n/help - помощь\\n/values - доступные для \" \\\n \"конвертации валюты\"\nhelp_message = f\"\\U000027A1 Сначала введите валюту, которую хотите конвертировать\\n\\U000027A1 Далее, через пробел — \" \\\n f\"валюту, в которую конвертируете\\n\\U000027A1 В конце, также через пробел, количество переводимой \" \\\n f\"валюты\\n\\n\\U0001F7E2 Например, вы хотите конвертировать 100 Долларов в Биткоин Для этого нужно \" \\\n f\"написать следующую команду:\\n\\nUSD BTC 100\\n\\nВы также можете ввести полные названия валют на \" \\\n f\"английском или русском языках\\n\\n{available_commands}\"\n\n\[email protected]_handler(commands=['start', 'help', 'values'])\ndef start_help_values(message):\n if message.text == \"/start\":\n bot.send_message(message.from_user.id, f\"Здравствуй, {message.from_user.first_name}! Добро пожаловать в \"\n f\"конвертвер Фиатных и Крипто валют! Пользоваться им довольно просто:\\n\"\n f\"\\n{help_message}\")\n\n elif message.text == \"/values\":\n bot.send_message(message.from_user.id, \"Список доступных для конвертации валют:\\n\\nEUR (Eвро/Euro)\\nUSD \"\n \"(Доллар/Dollar)\\nUAH (Гривна/Hryvna)\\nRUB (Рубль/Ruble)\\nBTC \"\n \"(Биткоин/Bitcoin)\\nETH (Эфириум/Ethereum) \\nDOT (Полкадот/Polkadot)\")\n else:\n bot.send_message(message.from_user.id, help_message)\n\n\[email protected]_handler(content_types=['text'])\ndef convert(message):\n global available_pairs\n try:\n what_convert, convert_to, amount = message.text.lower().split(\" \")\n try:\n amount = float(amount)\n except ValueError:\n bot.send_message(message.from_user.id, f\"\\U000026D4 Ошибка!\\n\\n\\U00002705Введите, пожалуйста, числовое \"\n f\"значение суммы\\n\\U00002705Если число дробное - используйте точку, \"\n f\"а не запятую в качестве разделителя\\n\\n{available_commands}\")\n else:\n try:\n if what_convert not in available_pairs or convert_to not in available_pairs or amount < 0:\n raise extensions.APIException\n\n except extensions.APIException:\n bot.send_message(message.from_user.id, f\"К сожалению, я не могу вам помочь \\U0001F614\\nВалютная пара \"\n f\"отсутствует или введены неверные значения\\n\\n\\U0001F4A1 \"\n f\"Обратите внимание, что введенная сумма не должна быть \"\n f\"отрицательной\\n\\n{available_commands}\")\n else:\n price = extensions.APIrequest.get_price(available_pairs[what_convert], available_pairs[convert_to],\n amount)\n bot.reply_to(message, price)\n except ValueError:\n bot.send_message(message.from_user.id, f\"\\U000026D4 Ошибка!\\n\\n\\U00002705Введите, пожалуйста, значение в \"\n f\"формате:\\n\\n <валюта>_<валюта, в которую конвертируете>_<сумма>\"\n f\"\\n\\n\\U00002705 Без треугольных скобок, а вместо нижнего \"\n f\"подчеркивания \\\"_\\\" поставьте пробел\\n\\n{available_commands}\")\n\n\[email protected]_handler(content_types=['photo', 'audio', 'document', 'sticker', 'video', 'location', 'contact', ])\ndef other_content(message: telebot.types.Message):\n bot.reply_to(message, f\"Простите, но я принимаю только текстовый ввод \\U0001F937\\n\\n{available_commands}\")\n\n\nbot.polling()\n" } ]
3
NelsonVides/CS50
https://github.com/NelsonVides/CS50
6f2821659fc55a03527c686a58ac142733c0eb7b
132b4b60f8bfc6775a7075744975a86f3e53a5ce
8fdd7e5f2d622cb4cc218e73c1daab4f76492525
refs/heads/master
2020-06-27T12:03:33.468157
2017-07-12T21:42:47
2017-07-12T21:42:47
97,053,563
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6063960790634155, "alphanum_fraction": 0.617466151714325, "avg_line_length": 29.11111068725586, "blob_id": "26e385505521a6837728fa58902c9ae643894245", "content_id": "ad5d3c62532b5e6e65b1d46eaa8de0258d39de50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1632, "license_type": "permissive", "max_line_length": 85, "num_lines": 54, "path": "/pset6/sentiments/tweets", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\n 1 .accepts one and only one command-line argument\n , the screen name for a user on Twitter\n 2. queries Twitter’s API for a user’s most recent 50 tweets,\n 3. analyzes the sentiment of each of those tweets, and\n 4. outputs each tweet’s score and text\n , colored in green if positive, red if negative\n , and yellow otherwise.\n\"\"\"\n\n\nimport os\nimport sys\n\nfrom analyzer import Analyzer\nfrom termcolor import colored\nfrom helpers import get_user_timeline\n\ndef main():\n\n # ensure proper usage\n if len(sys.argv) != 2:\n sys.exit(\"Usage: ./tweets @screen_name\")\n\n # absolute paths to lists\n positives = os.path.join(sys.path[0], \"positive-words.txt\")\n negatives = os.path.join(sys.path[0], \"negative-words.txt\")\n\n # instantiate analyzer\n analyzer = Analyzer(positives, negatives)\n \n # get_user_timeline returns a collection,\n # which we now must glue together into just one string\n screen_name = sys.argv[1].strip('@')\n text = get_user_timeline(screen_name, count=100)\n if text == None:\n print(\"No tweets for {}\".format(screen_name))\n return None\n \n print(\"shit\") \n # analyze word\n for tweet in text:\n score = analyzer.Analyzer(tweet)\n if score > 0.0:\n print(\"{} {}\".format(colored(score, \"green\"), colored(tweet, \"green\")))\n elif score < 0.0:\n print(\"{} {}\".format(colored(score, \"red\"), colored(tweet, \"red\")))\n else:\n print(\"{} {}\".format(colored(score, \"yellow\"), colored(tweet, \"yellow\")))\n \n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.545976996421814, "alphanum_fraction": 0.5484400391578674, "avg_line_length": 31.052631378173828, "blob_id": "27bd0dc086dd5d2c660935dee3bcfd54ae614393", "content_id": "2c5eeb5383ce1dd3b066c26d5aa351d32724ff37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1218, "license_type": "permissive", "max_line_length": 68, "num_lines": 38, "path": "/pset6/sentiments/analyzer.py", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "import nltk\n\nclass Analyzer():\n \"\"\"Implements sentiment analysis.\"\"\"\n\n def __init__(self, positives, negatives):\n \"\"\"Initialize Analyzer.\"\"\"\n self.posset = set()\n self.negset = set()\n\n file = open(positives, \"r\")\n for line in file:\n if not line.startswith(';'):\n self.posset.add(line.rstrip(\"\\n\"))\n file.close()\n\n file = open(negatives, \"r\")\n for line in file:\n if not line.startswith(';'):\n self.negset.add(line.rstrip(\"\\n\"))\n file.close()\n\n\n def Analyzer(self, text):\n \"\"\"Analyze text for sentiment, returning its score.\"\"\"\n \"\"\" we call the class METHOD TweetTokenizer and assign it to\n an internal function called the Tokenizer \"\"\"\n Tokenizer = nltk.tokenize.TweetTokenizer(\n preserve_case=True, reduce_len=True, strip_handles=True)\n \"\"\" here we create our tokens for the function \"\"\"\n Tokens = Tokenizer.tokenize(text)\n score = 0\n for token in Tokens:\n if token.lower() in self.posset:\n score += 1\n elif token.lower() in self.negset:\n score -= 1\n return score\n" }, { "alpha_fraction": 0.49026426672935486, "alphanum_fraction": 0.5020862221717834, "avg_line_length": 17.44871711730957, "blob_id": "8b539ca3b91cd195e7f3a9a7478825c465275214", "content_id": "dcb86f8d9c5f451b678a0636de1aa8e8d65d1a61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1438, "license_type": "permissive", "max_line_length": 81, "num_lines": 78, "path": "/pset3/find/helpers.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "/**\n * helpers.c\n * Helper functions for Problem Set 3.\n */\n \n#include <cs50.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include \"helpers.h\"\n\n\n\n/**\n * Swaps two given values\n * call by swap(&a,&b)\n */\nvoid swap(int* a, int* b)\n{\n int temp = *a;\n *a = *b;\n *b = temp;\n}\n\n#include <stdio.h>\n\n/**\n * Returns true if value is in array of n values, else false.\n * We are already assuming a sorted array!\n */\nbool search(int value, int values[], int n)\n{\n if (n <= 0) //sanity check for impossible array size\n {return false;}\n\n int midPoint = trunc( (n-1) / 2);\n \n int aux = values[midPoint];\n \nwhile (n > 0) {\n if (aux == value)\n {return true;}\n else if (value < aux) //search left\n { return (search(value, values, midPoint)); }\n else if (aux < value) //search right\n { return (search(value, values + midPoint + 1, n - 1 - midPoint)); }\n}\nreturn false;\n}\n\n\n\n/**\n * Sorts array of n values.\n */\nvoid sort(int values[], int n)\n{\n // TODO: implement an O(n^2) sorting algorithm\n // Selection sort\nint min = 0;\nint i = 0;\nint j = 0;\n for (i = 0 ; i < n - 1 ; i++)\n {\n min = i;\n //find smallest element from i to n-1;\n for (j = i + 1; j < n ; j++)\n {\n if (values[j] < values[min])\n { min = j; }\n }\n \n if (min != i)\n {\n swap( (values+min) , (values+i) );\n }\n }\n}" }, { "alpha_fraction": 0.5057712197303772, "alphanum_fraction": 0.5477439761161804, "avg_line_length": 30.26229476928711, "blob_id": "e78d7fe3c727b9770c4a63ad982eb7415492eeec", "content_id": "fe7e9c6507efff95cb0136136372c2663542625e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1906, "license_type": "permissive", "max_line_length": 76, "num_lines": 61, "path": "/pset2/crack/crack.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "#define _XOPEN_SOURCE\n#include <unistd.h>\n#include <stdio.h>\n#include <cs50.h>\n#include <string.h>\n#include <ctype.h>\n\nint main(int argc, string argv[])\n{\n if (argc != 2) //sanity check for umproper prompt line\n {printf(\"Usage: ./crack hash\\n\");return 1;}\n\n if (strlen(argv[1])!=13) //sanity check for improper hash\n {printf(\"Not a DES hash\\n\");return 1;}\n\n char salt[3]; // create salt\n memset(salt, '\\0', 3);\n strncpy(salt, argv[1], 2);\n char hash[14]; // create hash\n memset(hash, '\\0', 14);\n strncpy(hash, argv[1],13);\n\n char key[5]; //create key\n memset(key, '\\0', sizeof(key));\n char hashtest[14]; //create hash to test\n memset(hashtest, '\\0', 14);\n\n //the characters to bucle through in the loop\n string alphabet={\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuwxyz\"};\n\nfor (int i = 0; i <=52; i++) //make the key to test\n{ key[0]=alphabet[i]; //make the key to test\n for (int j = 0; j <=52; j++) //make the key to test\n { key[1]=alphabet[j]; //make the key to test\n for (int k = 0; k <=52; k++) //make the key to test\n { key[2]=alphabet[k]; //make the key to test\n for (int l = 0; l <=52; l++)//make the key to test\n { key[3]=alphabet[l]; //make the key to test\n \n // create hashtest to try it out\n strncpy(hashtest, crypt (key,salt),13);\n \n // tadarataaaan\n if (strcmp(hash,hashtest)==0)\n {printf(\"%s\\n\", key);return 0;}\n }\n }\n }\n}\n}\n\n//andi:50.jPgLzVirkc\n//jason:50YHuxoCN9Jkc\n//malan:50QvlJWn2qJGE\n//mzlatkova:50CPlMDLT06yY\n//patrick:50WUNAFdX/yjA\n//rbowden:50fkUxYHbnXGw\n//summer:50C6B0oz0HWzo\n//stelios:50nq4RV/NVU0I\n//wmartin:50vtwu4ujL.Dk\n//zamyla:50i2t3sOSAZtk" }, { "alpha_fraction": 0.5586734414100647, "alphanum_fraction": 0.5880101919174194, "avg_line_length": 29.764705657958984, "blob_id": "f6427b29c74d271e718d73b1ce6d54cb84960ca5", "content_id": "e1e353c5ee5cb5c649c237e6d00e988ae99723b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1568, "license_type": "permissive", "max_line_length": 74, "num_lines": 51, "path": "/pset6/crack.py", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "import sys\nimport crypt\n\nif len(sys.argv) != 2: #//sanity check for umproper prompt line\n print(\"Usage: ./crack hasz\\n\")\n exit(1)\n\nif len(sys.argv[1]) != 13: #sanity check for improper hasz\n print(\"Not a DES hasz\\n\")\n exit(1)\n\n# create salt\nsalt = str(sys.argv[1][:2])\n\n# create hasz\nhasz = str(sys.argv[1])\n\n#create word\nword=''\nlistilla = ['','','',''] \n\n#the characters to bucle through in the loop\nalphabet = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuwxyz'\nlenalf = len(alphabet)\n\n# go iterate everywhere\nfor i in range(lenalf): # make the word to test\n listilla[3] = alphabet[i] # make the word to test\n for j in range(lenalf): # make the word to test\n listilla[2] = alphabet[j] # make the word to test\n for k in range(lenalf): # make the word to test\n listilla[1] = alphabet[k] # make the word to test\n for l in range(lenalf): # make the word to test\n listilla[0] = alphabet[l] # make the word to test\n \n # tadarataaaan\n if hasz == crypt.crypt(word.join(listilla).strip(), salt):\n password = word.join(listilla).strip()\n print(password)\n exit(0)\n\n#//andi:50.jPgLzVirkc\n#//jason:50YHuxoCN9Jkc\n#//malan:50QvlJWn2qJGE\n#//mzlatkova:50CPlMDLT06yY\n#//patrick:50WUNAFdX/yjA\n#//rbowden:50fkUxYHbnXGw\n#//summer:50C6B0oz0HWzo\n#//stelios:50nq4RV/NVU0I\n#//wmartin:50vtwu4ujL.Dk\n#//zamyla:50i2t3sOSAZtk" }, { "alpha_fraction": 0.5483120083808899, "alphanum_fraction": 0.5902211666107178, "avg_line_length": 23.571428298950195, "blob_id": "d4f833fff00e9709aee16e9b7f1533101061c2b9", "content_id": "fc900804a6a8ba13f34fbe748a5f30880a4e5db6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "permissive", "max_line_length": 70, "num_lines": 35, "path": "/pset6/test.py", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "while True:\n cardnum = int(input(\"Please give me your Credit Card Number :D \"))\n if int(cardnum) > 0:\n break\n\naux = 0\naux2 = 0\nacc = 2\nlengthcard = len(str(cardnum))\n\n#code = (cardnum % (10**acc))#print(code)\n#code = code // (10**(acc-1))#print(code)\n#code = 2 * code#print(code)\n#aux += sum(int(digit) for digit in str(code))\n#print(aux)\n#code = 2 * ((cardnum % (10**acc)) // (10**(acc-1)))\n#print(code)\n#aux += sum(int(digit) for digit in str(code))\n#print(aux)\n#exit(1)\n\n\n# the even positions to duplicate and sum its digits\nfor i in range(lengthcard//2!=0):\n code = 2 * ((cardnum % (10**acc)) // (10**(acc-1)))\n aux += sum(int(digit) for digit in str(code))\n acc = acc + 2\n\n#the odd numbers just to sum them\nacc=1\nfor i in range(lengthcard//2!=0):\n aux += ((cardnum % (10**acc)) // (10**(acc-1)))\n acc = acc + 2\n \nprint(aux)" }, { "alpha_fraction": 0.4889705777168274, "alphanum_fraction": 0.5147058963775635, "avg_line_length": 21.75, "blob_id": "e7e04d7922f7493c24b0277d11c167126f90d092", "content_id": "b2b7f8a09bfbe467d1aa04f176276adaacc9a0cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 272, "license_type": "permissive", "max_line_length": 54, "num_lines": 12, "path": "/pset6/mario.py", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "#import cs50\n\nwhile True:\n #print(\"Tell me how many rows you want\")\n n = int(input(\"Tell me how many rows you want: \"))\n if n > 0 and n < 23:\n break\n\nfor row in range(n):\n print(\" \" * (n - row - 1), end=\"\")\n print(\"#\" * (row + 2), end=\"\")\n print()" }, { "alpha_fraction": 0.5299674272537231, "alphanum_fraction": 0.5345276594161987, "avg_line_length": 22.25757598876953, "blob_id": "cb3c2fed3e313e3a986096461944e9565d1c4719", "content_id": "d40b60fbf8847e4807a8c609541e28a6d582e1e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3077, "license_type": "permissive", "max_line_length": 63, "num_lines": 132, "path": "/pset5/practicas/tries.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "/** TRIES, with the alphabet */\n\n#include <stdlib.h>\n#include <stdbool.h>\n#include <ctype.h>\n\n#include \"tries.h\"\n\n#define LENGTH 45\n#define ALPHABET 27\n// node *first = NULL;\n\n/** Defining the nodes */\ntypedef struct _trie {\n bool isword; \n struct _trie *alfabeto[ALPHABET];\n} trie;\ntrie *ROOTOFTRIE = NULL;\n\n\n/** trie *root = createtrie()\n * Create a new list altogether */\ntrie *createtrie() {\n trie *newptr = malloc(sizeof(trie));\n if (newptr == NULL) {return NULL;}\n initnode(newptr);\n return newptr;\n}\n\n\n\n/**\n * give in the value to insert, and the list's root\n * root = insert(val,&root)\n */\nint insert(char *palabra, trie *root) {\n \n // aux pointers not to lose data just in case\n char *wordptr = palabra;\n trie *nodeptr = root;\n \n // insert char by char until we reach the end of the word\n while (*wordptr != '\\0') {\n \n // check which cell in the array should we consider\n unsigned int n = inalfabeto(wordptr);\n if (n>=ALPHABET) {return 1;} // ¿y después qué?\n \n // if the children doesn't exist, create it\n if ( nodeptr->alfabeto[n] != NULL ) {\n // allocate new node and check\n trie *newptr = malloc(sizeof(trie));\n if (newptr == NULL) {\n destroy(root);\n return 1;\n }\n // initalise values of the new node\n initnode(newptr);\n // insert the value in the given children\n nodeptr->alfabeto[n] = newptr;\n }\n nodeptr = nodeptr->alfabeto[n];\n wordptr++; \n }\n nodeptr->isword = true;\n return 0;\n}\n\n\n\n\n/**\n * give in the word to look for, and the trie's root\n */\nbool search(char *palabra, trie *root) {\n \n // aux pointers not to lose data just in case\n char *wordptr = palabra;\n trie *nodeptr = root;\n \n while (*wordptr != '\\0') {\n \n // check the cell value\n int n = inalfabeto(wordptr);\n if (n>=ALPHABET) {return 0;} // ¿y después qué?\n \n // check if we can continue going through the trie\n if ( nodeptr->alfabeto[n] == NULL ) {\n return false;\n } else {\n nodeptr = nodeptr->alfabeto[n];\n }\n\n wordptr++; \n }\n return nodeptr->isword;\n}\n\n\n\n\n/** destroy that shit! */\nvoid destroy(trie *root) {\n trie *ptr = root;\n // aquí tengo que ir a por todos sus putos hijos...\n for (int i = 0; i < ALPHABET; i++) {\n if (ptr->alfabeto[i] != NULL) {\n destroy(ptr->alfabeto[i]);\n }\n }\n free(ptr);\n}\n\nunsigned int inalfabeto(char *value) {\n int letra;\n if (*value == '\\'') {\n letra = ALPHABET - 1;\n } else if (isalpha(*value)) {\n letra = tolower(*value) - 'a';\n } else {\n letra = ALPHABET; // ojo, esta se va a salir del array!\n }\n return letra;\n}\nvoid initnode(trie *node) {\n node->isword = false;\n for (int i = 0; i < ALPHABET; i++) {\n node->alfabeto[i] = NULL;\n }\n}\n\nint main(void) {return 0;}\n" }, { "alpha_fraction": 0.5734214186668396, "alphanum_fraction": 0.5741556286811829, "avg_line_length": 17.405405044555664, "blob_id": "aedad7733673d0c2c8fd6adb3a4d798672da8636", "content_id": "f9c2f0350c23e587f6644ae5a6fa8c0e6cd15bda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1362, "license_type": "permissive", "max_line_length": 53, "num_lines": 74, "path": "/pset5/practicas/dllists.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "/**\n * Linked lists datatypes and functions\n */\n\n#include <stdlib.h>\n#include <stdbool.h>\n\n// node *first = NULL;\n\n// Defining the nodes\ntypedef struct dllnode {\n char val;\n struct dllnode *prev;\n struct dllnode *next;\n} dllnode;\n\n\n/**\n * Create a new list altogether\n * dllnode *new = create (value)\n */\ndllnode *create(char val) {\n dllnode *newptr = malloc(sizeof(dllnode));\n if (newptr == NULL) {return NULL;}\n newptr->val = val;\n newptr->prev = NULL;\n newptr->next = NULL;\n return newptr;\n}\n\n/**\n * give in the value to insert, and the list's head\n * head = insert(val,&head)\n */\ndllnode *insert(int val, dllnode *head) {\n dllnode *newptr = malloc(sizeof(dllnode));\n if (newptr == NULL) {return NULL;}\n newptr->val = val;\n newptr->prev = NULL;\n newptr->next = head;\n head->prev = newptr;\n head = newptr;\n return newptr;\n}\n\n/**\n * give in the value to look for, and the list's head\n */\nbool search(int val, dllnode *head) {\n dllnode *ptr = head;\n while (ptr != NULL) {\n if (ptr->val == val) {\n return true;\n }\n ptr = ptr->next;\n }\n return false;\n}\n\n/**\n * destroy that shit!\n */\nvoid destroy(dllnode *head) {\n dllnode *ptr = head;\n while (head != NULL) {\n head = ptr->next;\n free(ptr);\n }\n return;\n}\n\n\n\nint main(void) {return 0;}\n" }, { "alpha_fraction": 0.5286259651184082, "alphanum_fraction": 0.5763359069824219, "avg_line_length": 19.959999084472656, "blob_id": "de1744cdaaf1b4a672d93b3914621ca5dddf643a", "content_id": "7c743c009a1b089c4c36fd41b38a1b9cea88d292", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1048, "license_type": "permissive", "max_line_length": 70, "num_lines": 50, "path": "/pset6/credit.py", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "while True:\n cardnum = int(input(\"Please give me your Credit Card Number :D \"))\n if int(cardnum) > 0:\n break\n\naux = 0\nacc = 2\nstrnum = str(cardnum)\nlengthcard = len(strnum)\n\n# the even positions to duplicate and sum its digits\nfor i in range(0,lengthcard,2): # How many times?\n code = 2 * ((cardnum % (10**acc)) // (10**(acc-1)))\n aux += sum(int(digit) for digit in str(code))\n acc = acc + 2\n\n#the odd numbers just to sum them\nacc=1\nfor i in range(0,lengthcard,2):\n aux += ((cardnum % (10**acc)) // (10**(acc-1)))\n acc = acc + 2\n\nprint(aux)\n\n# go check if it has a valid sum\nif (aux % 10)!=0:\n print(\"invalid card number\")\n exit(1)\n\n#AMEX\nif lengthcard == 15:\n if strnum[:2] == '34' or strnum[:2] == '37':\n print(\"AMEX\")\n exit(0)\n\n#Master Card\nif lengthcard == 16:\n if int(strnum[:2]) in range(51,56):\n print(\"Master Card\")\n exit(0)\n\n#VISA\nif lengthcard == 13 or lengthcard == 16:\n if strnum[:1] == '4':\n print(\"VISA\")\n exit(0)\n\n#INVALID\nprint(\"INVALID\")\nexit(1)\n" }, { "alpha_fraction": 0.452625572681427, "alphanum_fraction": 0.46917808055877686, "avg_line_length": 23.690141677856445, "blob_id": "873b3d3baa2e98e4945ba348be34100e2b9e46e0", "content_id": "76c9d3a0b71a4acc0eb2454280d5ecae071e48e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1752, "license_type": "permissive", "max_line_length": 68, "num_lines": 71, "path": "/pset4/recover/recover.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "/**\n * Copies a BMP piece by piece, just because.\n */\n \n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\ntypedef uint8_t BYTE;\nconst int block = 512;\n\nint main(int argc, char *argv[])\n{\n // ensure proper usage\n if (argc != 2) {\n fprintf(stderr, \"Usage: ./recover image\\n\");\n return 1;\n }\n\n // remember filenames\n char *infile = argv[1];\n FILE *inptr = fopen(infile, \"r\");\n if (inptr == NULL) {\n fprintf(stderr, \"Could not open %s.\\n\", infile);\n return 2;\n }\n\n char filename[8] = \"000.jpg\"; // OJO\n int NumPic = 0;\n BYTE buffer[block];\n FILE *outptr = NULL;\n\n while ( fread(&buffer, sizeof(BYTE), block, inptr) == block ) {\n \n if (buffer[0] == 0xff &&\n buffer[1] == 0xd8 &&\n buffer[2] == 0xff &&\n (buffer[3] & 0xf0) == 0xe0) {\n \n // if there was something open, close it\n if (outptr != NULL) {\n fclose(outptr);}\n \n // build the filename name\n sprintf(filename, \"%03i.jpg\" , NumPic);\n NumPic++;\n \n // open a new JPEG file\n outptr = fopen(filename, \"w\");\n \n // sanity check in case it couldn't open\n if (outptr == NULL) { fclose(inptr);\n fprintf(stderr, \"Could not create %s.\\n\", filename);\n return 3;\n }\n }\n \n if (outptr != NULL) { \n // write the buffer on our current JPEG\n fwrite(&buffer, sizeof(BYTE), block, outptr);\n }\n }\n \n // close infile\n fclose(inptr);\n \n // close outfile\n fclose(outptr);\n \n // success\n return 0;\n}" }, { "alpha_fraction": 0.3836633563041687, "alphanum_fraction": 0.4183168411254883, "avg_line_length": 15.875, "blob_id": "ab6d9b9b8a0c5af9ced9c38e1d4d2e92f5fc79fd", "content_id": "7eb63bbd7061b101a1a3ef1a2b4637b7a826898c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 404, "license_type": "permissive", "max_line_length": 51, "num_lines": 24, "path": "/pset1/mario.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <cs50.h>\n\nint main(void)\n{\n\nint n=0;\nint row=0;\nint i=0;\nint j=0;\n\n do{\n printf(\"Tell me how many rows you want: \");\n n = get_int();\n }while (n < 0 || n > 23);\n\n for (row = 0; row<n; row++) //coments\n { for (i = 0; i<n-row-1; i++)\n {printf(\" \");}\n for (j = 0; j<n-i+1; j++)\n {printf(\"#\");}\n printf(\"\\n\");\n }\n}" }, { "alpha_fraction": 0.5237122774124146, "alphanum_fraction": 0.5293850898742676, "avg_line_length": 24.622093200683594, "blob_id": "f4ae8d4761c36f93d16227c874b3852b0a258f6b", "content_id": "e86e4b5f815036bbe2b347df0154f587bf04fd65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4408, "license_type": "permissive", "max_line_length": 76, "num_lines": 172, "path": "/pset5/speller/dictionary.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "/**\n * Implements a dictionary's functionality.\n */\n\n\n#include \"dictionary.h\"\n// personal definitions\n// macro for Alphabet size\n #define ALPHABET 27\n//trie node definition\n typedef struct _trie {\n bool isword; \n struct _trie *alfabeto[ALPHABET];\n } trie;\n// initialise THE MOTHER\n trie *ROOTOFTRIE = NULL;\n// global variable for tracking dictionary size\n unsigned int word_count = 0;\n// global boolean for tracking load/unload dictionary operations\n bool _loaded = false;\n/** destroy that shit! */\n bool destroytrie(trie *ptr) {\n // aquí tengo que ir a por todos sus putos hijos...\n for (int i = 0; i < ALPHABET; i++) {\n if (ptr->alfabeto[i] != NULL) {\n destroytrie(ptr->alfabeto[i]);\n }\n } free(ptr);\n return true;\n }\n/** extract its rationale number \n (theoretically unnecesary extra steps here) */\n unsigned int inalfabeto(char *value) {\n if (*value == '\\'') {\n return ALPHABET - 1;\n } else if (isalpha(*value)) {\n return tolower(*value) - 'a';\n }\n return ALPHABET;\n }\n/** set everything to 0 and NULL on a new node */\n void initnode(trie *node) {\n node->isword = false;\n memset(node->alfabeto, '\\0', ALPHABET);\n }\n trie *createtrie() {\n trie *trieptr = malloc(sizeof(trie));\n if (trieptr == NULL) {return NULL;}\n initnode(trieptr);\n return trieptr;\n }\n// personal definitions\n\n/**\n * Loads dictionary into memory. Returns true if successful else false.\n */\nbool load(const char *dictionary)\n{\n /* Take the ROOT and initialise it */\n ROOTOFTRIE = calloc(1,sizeof(trie));\n if (ROOTOFTRIE == NULL) {return false;}\n //ROOTOFTRIE->isword = false;\n //memset(ROOTOFTRIE->alfabeto, '\\0', ALPHABET);\n \n /* Make a trasversal pointer at ROOT */\n trie *nodeptr = ROOTOFTRIE;\n \n /* prepare the variables here */\n char wordptr[LENGTH+1] = {'\\0'};\n char aux = '\\0';\n unsigned int i = 0;\n unsigned int n = 0;\n \n /* Open the dictionary */\n FILE * fp;\n fp = fopen(dictionary, \"r\");\n if (fp == NULL) {\n printf(\"Could not open the dictionary\\n\");\n return false;\n }\n \n /* Time to read into, string by string with fscanf */\n while ( fscanf(fp, \"%s\", wordptr) != EOF ){\n \n /* insert char by char until we reach the end of the word */\n aux = wordptr[i];\n while (aux != '\\0') {\n \n /* check which cell in the array should we consider */\n if (aux == '\\'') {\n n = ALPHABET - 1;\n } else {\n n = aux - 'a';\n }\n \n /** If it doesn't have a children, give it one */\n if ( nodeptr->alfabeto[n] == NULL ) {\n trie *zeronode = calloc(1,sizeof(trie));\n if (zeronode == NULL)\n {return false;}\n nodeptr->alfabeto[n] = zeronode;\n }\n \n nodeptr = nodeptr->alfabeto[n];\n i++;\n aux = wordptr[i];\n }\n nodeptr->isword = true;\n word_count++;\n nodeptr = ROOTOFTRIE;\n memset(wordptr, '\\0', sizeof(wordptr));\n i=0;\n }\n fclose(fp);\n _loaded = true;\n return true;\n}\n\n\n\n\n\n/**\n * Returns true if word is in dictionary else false.\n */\nbool check(const char *word)\n{\n /* make a copy word of the original */\n char palabra[LENGTH+1];//= {'\\0'};\n strcpy(palabra, word);\n\n // get the root of the dictionary\n trie *nodeptr = ROOTOFTRIE;\n int i = 0;\n \n while (palabra[i] != '\\0') {\n \n // get the cell rationale\n int n = inalfabeto(&palabra[i]);\n \n // check if we can continue going through the trie\n if ( nodeptr->alfabeto[n] == NULL ) {\n return false;\n } else {\n nodeptr = nodeptr->alfabeto[n];\n }\n i++;\n }\n return nodeptr->isword;\n}\n\n/**\n * Returns number of words in dictionary if loaded else 0 if not yet loaded.\n */\nunsigned int size(void)\n{\n if (_loaded) {\n return word_count;\n } else {\n return 0;\n }\n}\n\n\n/**\n * Unloads dictionary from memory. Returns true if successful else false.\n */\nbool unload(void)\n{\n _loaded = !destroytrie(ROOTOFTRIE);\n return !_loaded;\n}\n" }, { "alpha_fraction": 0.6645161509513855, "alphanum_fraction": 0.6709677577018738, "avg_line_length": 19.032258987426758, "blob_id": "0a7a54dbebead859a5dd2bf2259f660f66407cc3", "content_id": "8dc80c89e46077ace062955d8b3a40a871011f0a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 620, "license_type": "permissive", "max_line_length": 53, "num_lines": 31, "path": "/pset5/practicas/tries.h", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "/** TRIES, with the alphabet */\n\n#include <stdlib.h>\n#include <stdbool.h>\n\n#define LENGTH 45\n#define ALPHABET 27\n// node *first = NULL;\n\n/** Defining the nodes */\ntypedef struct _trie trie;\n\n/** trie *root = createtrie()\n * Create a new list altogether */\ntrie *createtrie();\n\n/** root = insert(val,&root)\n * give in the value to insert, and the list's root\n */\nint insert(char *value, trie *root);\n\n/**\n * give in the value to look for, and the list's root\n */\nbool search(char *palabra, trie *root);\n\n/** destroy that shit! */\nvoid destroy(trie *root);\n\nunsigned int inalfabeto(char *value);\nvoid initnode(trie *node);" }, { "alpha_fraction": 0.5035842061042786, "alphanum_fraction": 0.5501791834831238, "avg_line_length": 12.975000381469727, "blob_id": "6453f37fe10734e7e5ebe9f86071eedada82790d", "content_id": "293df3590b7739ce4efed09492e6a9cdc2b18c44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 558, "license_type": "permissive", "max_line_length": 42, "num_lines": 40, "path": "/pset1/greedy.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <cs50.h>\n#include <math.h>\n\nint main(void)\n{\n\nfloat dollars=0;\nint cents=0;\nint coins=0;\n\n do{\n printf(\"How much do I owe you? \");\n dollars = get_float();\n }while (dollars < 0);\n cents=roundf(dollars*100);\n //printf(\"%i\\n\", cents);\n\nwhile (cents - 25>=0)\n{ cents=cents - 25;\n coins=coins+1;\n}\n\nwhile (cents - 10>=0)\n{ cents=cents - 10;\n coins=coins+1;\n}\n\nwhile (cents - 5>=0)\n{ cents=cents - 5;\n coins=coins+1;\n}\n\nif (cents >0)\n{\n coins=coins+cents;\n}\n\n printf(\"%i\\n\",coins);\n}" }, { "alpha_fraction": 0.553892195224762, "alphanum_fraction": 0.598802387714386, "avg_line_length": 14.952381134033203, "blob_id": "c136826746e018d13fbb91b13e6fbcf5cdd09ad6", "content_id": "adc72902e0bdd4ca39e68a4015381e449d728f74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 334, "license_type": "permissive", "max_line_length": 53, "num_lines": 21, "path": "/pset6/greedy.py", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "while True:\n #print(\"Tell me how many rows you want\")\n dollars = float(input(\"How much do I owe you? \"))\n if dollars > 0:\n break\n\ncents = int(dollars * 100)\ncoins = 0;\n\ncoins += cents // 25\ncents = cents % 25\n\ncoins += cents // 10\ncents = cents % 10\n\ncoins += cents // 5\ncents = cents % 5\n\ncoins += cents\n\nprint(coins)" }, { "alpha_fraction": 0.42867982387542725, "alphanum_fraction": 0.45371776819229126, "avg_line_length": 22.140350341796875, "blob_id": "9afbd6529d3aff924dabdca5bcb87d9c216cffb8", "content_id": "6b1913a3642ba0eb1a2c0d112acf611e0090b264", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1318, "license_type": "permissive", "max_line_length": 81, "num_lines": 57, "path": "/pset2/vigenere/vigenere.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "#include <cs50.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\nint main(int argc, char *argv[])\n{ \n//sanity check for improper prompt line\n if (argc != 2)\n {printf(\"Usage: ./vigeneres key\\n\");return 1;}\n\n// make the key\n char *key = argv[1];\n if (key == NULL){return 1;}\n int len = strlen(argv[1]);\n \n//check if totally alphanumeric, and if so, to lower, in one iteration\n int k=0;\n while (k < len)\n {\n if (!isalpha(key[k])){printf(\"ERROR: non-alphabetic values\\n\");return 1;}\n key[k]=tolower(key[k]);\n k++;\n }\n \n// ask for the plaintext\n printf(\"plaintext: \");\n char *name = get_string();\n int n = strlen(name);\n\nint temp; int j = 0;\nfor (int i = 0; i < n; i++)\n{ \n if (isalpha(name[i]))\n { \n if (name[i]<=90)\n { \n temp = (name[i]+key[j]-97);\n if (temp<91)\n {name[i] = (char) temp;}\n else\n {name[i] = (char) (temp%91 + 65);}\n j = (j+1) % len;\n }\n else\n {\n temp = (name[i]+key[j]-97);\n if (temp<123)\n {name[i] = (char) temp;}\n else\n {name[i] = (char) (temp%123 + 97);}\n j = (j+1) % len;\n }\n }\n}\nprintf(\"ciphertext: %s\\n\", name);\n}" }, { "alpha_fraction": 0.581250011920929, "alphanum_fraction": 0.606249988079071, "avg_line_length": 16.83333396911621, "blob_id": "26cb3d111cda80cb37a06b3a047b012b5ca14742", "content_id": "0ad815123d161c4606c56f5a8badd94b0e9e1b48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 320, "license_type": "permissive", "max_line_length": 74, "num_lines": 18, "path": "/pset1/water.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <cs50.h>\n\nint main(void)\n{\n\nfloat minutes=0;\nfloat bottles=0;\n\n //do{\n printf(\"For how long have you been in the shower (in minutes)? \");\n minutes = get_float();\n //}while (minutes < 0);\n\nbottles = minutes*12;\n printf(\"Those are %.2f bottles, you prick!\\n\",bottles);\n\n}" }, { "alpha_fraction": 0.6663265228271484, "alphanum_fraction": 0.6765305995941162, "avg_line_length": 24.128204345703125, "blob_id": "cab63a11dc5baa9a4171f0d2bbcab44cdf32f293", "content_id": "8e0716fdaebe1490e56e907a38485860ad9a0ad9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 980, "license_type": "permissive", "max_line_length": 64, "num_lines": 39, "path": "/pset5/practicas/Makefile", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "# Makefile for data-structures\n\n# compiler to use\nCC = clang\n# flags to pass compiler\nCFLAGS = -ggdb3 -O0 -Qunused-arguments -std=c11 -Wall -Werror\n# name for executable\nEXE = #speller\n# space-separated list of header files\nHDRS = #dictionary.h\n# space-separated list of libraries, if any,\n# each of which should be prefixed with -l\nLIBS = #-lcs50 -lm\n# space-separated list of source files\nSRCS = #speller.c dictionary.c\n# automatically generated list of object files\nOBJS = $(SRCS:.c=.o)\n# default target\n$(EXE): $(OBJS) $(HDRS) Makefile\n\t$(CC) $(CFLAGS) -o $@ $(OBJS) $(LIBS)\n# dependencies \n$(OBJS): $(HDRS) Makefile\n# housekeeping\nclean:\n\trm -f core $(EXE) *.o\n#\trm -f *.o a.out core all\t\n\nall: sllists\n\nsllists: sllists.c\n\t$(CC) $(CFLAGS) -o $@ sllists.c $(LIBS)\n\ndllists: dllists.c\n\t$(CC) $(CFLAGS) -o $@ dllists.c $(LIBS)\n\ntries: tries.c tries.h\n\t$(CC) $(CFLAGS) -o $@ tries.c $(LIBS)\n#generate: generate.c\n#\tclang -ggdb3 -O0 -std=c11 -Wall -Werror -o generate generate.c\n" }, { "alpha_fraction": 0.5725614428520203, "alphanum_fraction": 0.5733544826507568, "avg_line_length": 17.014286041259766, "blob_id": "3135d3573919f0189b5189236166313c21f63142", "content_id": "31963e604663ea31ad2c9b1ac81e6640f31f6b13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1261, "license_type": "permissive", "max_line_length": 53, "num_lines": 70, "path": "/pset5/practicas/sllists.c", "repo_name": "NelsonVides/CS50", "src_encoding": "UTF-8", "text": "/**\n * Linked lists datatypes and functions\n */\n\n#include <stdlib.h>\n#include <stdbool.h>\n\n// node *first = NULL;\n\n// Defining the nodes\ntypedef struct sllnode {\n char val;\n struct sllnode *next;\n} sllnode;\n\n\n/**\n * Create a new list altogether\n * sllnode *new = create (value)\n */\nsllnode *create(char val) {\n sllnode *newptr = malloc(sizeof(sllnode));\n if (newptr == NULL) {return NULL;}\n newptr->val = val;\n newptr->next = NULL;\n return newptr;\n}\n\n/**\n * give in the value to insert, and the list's head\n * head = insert(val,&head)\n */\nsllnode *insert(int val, sllnode *head) {\n sllnode *newptr = malloc(sizeof(sllnode));\n if (newptr == NULL) {return NULL;}\n newptr->val = val;\n newptr->next = head;\n head = newptr;\n return newptr;\n}\n\n/**\n * give in the value to look for, and the list's head\n */\nbool search(int val, sllnode *head) {\n sllnode *ptr = head;\n while (ptr != NULL) {\n if (ptr->val == val) {\n return true;\n }\n ptr = ptr->next;\n }\n return false;\n}\n\n/**\n * destroy that shit!\n */\nvoid destroy(sllnode *head) {\n sllnode *ptr = head;\n while (head != NULL) {\n head = ptr->next;\n free(ptr);\n }\n return;\n}\n\n\n\nint main(void) {return 0;}\n" } ]
20
Ramya667/Understanding-Short-Text-Using-Semantic-Enrichment-and-Semantic-Hashing-Batch-09
https://github.com/Ramya667/Understanding-Short-Text-Using-Semantic-Enrichment-and-Semantic-Hashing-Batch-09
2406d3fdd783062542356b0572a7b055c1eeec6c
95516f8e1570c3e73f1212fc3a34a34aa5687585
7c9cef66a9e5753c29a61c35fa18474e638d1004
refs/heads/master
2021-04-01T01:04:06.280941
2021-02-04T09:33:44
2021-02-04T09:33:44
248,143,510
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6067500710487366, "alphanum_fraction": 0.6624952554702759, "avg_line_length": 24.355770111083984, "blob_id": "0e71463efbf8e13dacd4f1d0f24651ee7ba0c948", "content_id": "b342664b0293402735d29d2e51a4a67c3b250abb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 2637, "license_type": "no_license", "max_line_length": 83, "num_lines": 104, "path": "/code/DATABASE/New Project 20170304 1759.sql", "repo_name": "Ramya667/Understanding-Short-Text-Using-Semantic-Enrichment-and-Semantic-Hashing-Batch-09", "src_encoding": "UTF-8", "text": "-- MySQL Administrator dump 1.4\n--\n-- ------------------------------------------------------\n-- Server version\t5.0.22-community-nt\n\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n/*!40101 SET NAMES utf8 */;\n\n/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n\n\n--\n-- Create schema shorttext\n--\n\nCREATE DATABASE IF NOT EXISTS shorttext;\nUSE shorttext;\n\n--\n-- Definition of table `file`\n--\n\nDROP TABLE IF EXISTS `file`;\nCREATE TABLE `file` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `filename` varchar(45) NOT NULL,\n `sname` varchar(45) NOT NULL,\n `des` longtext NOT NULL,\n `file` longblob NOT NULL,\n `time` varchar(45) NOT NULL,\n `rank` varchar(45) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n\n--\n-- Dumping data for table `file`\n--\n\n/*!40000 ALTER TABLE `file` DISABLE KEYS */;\n/*!40000 ALTER TABLE `file` ENABLE KEYS */;\n\n\n--\n-- Definition of table `image`\n--\n\nDROP TABLE IF EXISTS `image`;\nCREATE TABLE `image` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(45) NOT NULL,\n `sname` varchar(45) NOT NULL,\n `des` varchar(100) NOT NULL,\n `photo` longblob NOT NULL,\n `rank` varchar(45) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n\n--\n-- Dumping data for table `image`\n--\n\n/*!40000 ALTER TABLE `image` DISABLE KEYS */;\n/*!40000 ALTER TABLE `image` ENABLE KEYS */;\n\n\n--\n-- Definition of table `reg`\n--\n\nDROP TABLE IF EXISTS `reg`;\nCREATE TABLE `reg` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(45) NOT NULL,\n `pass` varchar(45) NOT NULL,\n `mail` varchar(80) NOT NULL,\n `gen` varchar(45) NOT NULL,\n `date` datetime NOT NULL,\n `cell` varchar(45) NOT NULL,\n `loc` varchar(45) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n\n--\n-- Dumping data for table `reg`\n--\n\n/*!40000 ALTER TABLE `reg` DISABLE KEYS */;\n/*!40000 ALTER TABLE `reg` ENABLE KEYS */;\n\n\n\n\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n" }, { "alpha_fraction": 0.7726045846939087, "alphanum_fraction": 0.8002699017524719, "avg_line_length": 86.11764526367188, "blob_id": "6742a9607657bdfe0ffc861e278af698c52d1750", "content_id": "a3a8437d0185001570fdbc8574b2c3a083e8f21a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1482, "license_type": "no_license", "max_line_length": 914, "num_lines": 17, "path": "/README.md", "repo_name": "Ramya667/Understanding-Short-Text-Using-Semantic-Enrichment-and-Semantic-Hashing-Batch-09", "src_encoding": "UTF-8", "text": "# Understanding-Short-Text-Using-Semantic-Enrichment-and-Semantic-Hashing\n# Batch No - B9\nRamya S (164G1A0575)\n\nRekha G (164G1A0579)\n\nRamya Sai N (164G1A0576)\n\nSai Kiran K (164G1A0586)\n\nRama Mohan Chowdary K (164G1A0574)\n# Project Description\nEveryday billions of short texts are generated in an enormous volume in the form of search queries, news titles, tags, chat bots, social media posts etc. Understanding short texts retrieval, classification and processing become a very difficult task. Clustering short texts (such as news titles) by their meaning is a challenging task. The semantic hashing approach encodes the meaning of a text into a compact binary code. Thus, to tell if two texts have similar meanings, we only need to check if they have similar codes. The encoding is created by a deep neural network, which is trained on texts. To cluster short texts by their meanings, we propose to add more semantic signals to short texts. Specifically, for each term in a short text, we obtain its concepts and co-occurring terms from a database to enrich the short text. Furthermore, we introduce a simplified deep learning network for semantic hashing.\n\nMany approaches have been proposed to facilitate short text understanding by enriching the short text. These approaches are based on semantic hashing models.\n\nOur approach is based on semantic network for enriching a short text. We present a novel mechanism to semantically enrich short texts with both concepts and co-occurring terms. \n" }, { "alpha_fraction": 0.6078166961669922, "alphanum_fraction": 0.612533688545227, "avg_line_length": 24.60344886779785, "blob_id": "62419ad4dacb81f5309204a447578e6acfc091c4", "content_id": "45b7f879f1e268b07104efbcc0658fde1df99963", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1484, "license_type": "no_license", "max_line_length": 75, "num_lines": 58, "path": "/code/files to upload/python.py", "repo_name": "Ramya667/Understanding-Short-Text-Using-Semantic-Enrichment-and-Semantic-Hashing-Batch-09", "src_encoding": "UTF-8", "text": "# Enter your code here. Read input from STDIN. Print output to STDOUT\n#creating a class book\nclass Book:\n def __init__(self,bookId,bookName,bookTechnology,bookPrice,authorname):\n self.bookId=bookId\n self.bookName=bookName\n self.bookTechnology=bookTechnology\n self.bookPrice=bookPrice\n self.authorname=authorname\n#creating a class book store\nclass BookStore:\n def __init__(self,d,e):\n self.d=d\n self.e=e\n #creatig a method\n def searchByName(self,a):\n w=[]\n for v,g in self.d.items():\n if g.bookName==a:\n w.append(g)\n return w\n #creating a method\n def calculatePriceByTechnology(self,b):\n z=0\n for v,g in self.d.items():\n if g.bookTechnology==b:\n z=z+g.bookPrice\n z=z*0.9\n return z\ncount=int(input())\ns={}\n#for loop\nfor _ in range(count):\n bookId=int(input())\n bookName=input()\n bookTechnology=input()\n bookPrice=int(input())\n authorname=input()\n B=Book(bookId,bookName,bookTechnology,bookPrice,authorname)\n s[bookId]=B\nBS=BookStore(s,'Janakiram store')\nx=input()\ny=input()\nh=BS.searchByName(x)\ns=BS.calculatePriceByTechnology(y)\nif len(h)==0:\n print(\"No Book Exists with the BookName\")\nelse:\n for r in h:\n print(r.bookId)\n print(r.bookName)\n print(r.bookTechnology)\n print(r.bookPrice)\n print(r.authorname)\nif s==0:\n print(\"0.0\")\nelse:\n print(s)" }, { "alpha_fraction": 0.6380503177642822, "alphanum_fraction": 0.6440251469612122, "avg_line_length": 33.9560432434082, "blob_id": "79106be79e09d5f7c88b8a9dcfa6c2139615e2b6", "content_id": "d62a26d744c3bdb5a970c28f6e76a42f3f6b8365", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3180, "license_type": "no_license", "max_line_length": 100, "num_lines": 91, "path": "/code/SOURCE CODE/understanding short text/src/java/network/imageupload.java", "repo_name": "Ramya667/Understanding-Short-Text-Using-Semantic-Enrichment-and-Semantic-Hashing-Batch-09", "src_encoding": "UTF-8", "text": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage network;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.annotation.MultipartConfig;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport javax.servlet.http.Part;\n\n@WebServlet(\"/Upload\")\n@MultipartConfig(maxFileSize = 16177215)\npublic class imageupload extends HttpServlet {\n\n // database connection settings\n private String dbURL = \"jdbc:mysql://localhost:3306/shorttext\";\n private String dbUser = \"root\";\n private String dbPass = \"root\";\n private SimpleDateFormat format;\n\n protected void doPost(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n\n HttpSession session = request.getSession(true);\n\n String name = request.getParameter(\"name\");\n String sname = request.getParameter(\"sname\");\n String des = request.getParameter(\"des\");\n System.out.println(\"upload content=\"+name+sname+des);\n \n// String age = request.getParameter(\"age\");\n// String wight = request.getParameter(\"wight\");\n// String height = request.getParameter(\"height\");\n// String brief = request.getParameter(\"brief\");\n// String addomiss = request.getParameter(\"addomiss\");\n// String dateofreport = request.getParameter(\"dateofreport\");\n\n InputStream inputStream = null;\n Part filePart = request.getPart(\"file\");\n if (filePart != null) {\n System.out.println(filePart.getName());\n System.out.println(filePart.getSize());\n System.out.println(filePart.getContentType());\n inputStream = filePart.getInputStream();\n }\n\n Connection conn = null;\n String message = null;\n\n try {\n\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n conn = DriverManager.getConnection(dbURL, dbUser, dbPass);\n\n String sql = \"INSERT INTO image (name, sname, des, photo, rank) values (?, ?, ?, ?, ?)\";\n PreparedStatement statement = conn.prepareStatement(sql);\n statement.setString(1, name);\n statement.setString(2, sname);\n statement.setString(3, des);\n \n \n \n if (inputStream != null) {\n statement.setBlob(4, inputStream);\n }\n statement.setString(5, \"0\");\n int row = statement.executeUpdate();\n if (row > 0) {\n response.sendRedirect(\"upimage.jsp?msg=success\");\n } else {\n response.sendRedirect(\"upimage.jsp?msgg=Failed\");\n }\n } catch (SQLException ex) {\n ex.printStackTrace();\n }\n }\n}" }, { "alpha_fraction": 0.6247910261154175, "alphanum_fraction": 0.6262240409851074, "avg_line_length": 33.3278694152832, "blob_id": "bd1a290f1b0515765663fd595d5d79364be2e357", "content_id": "2d8f30c204d71893bac9fa188b1c31a5a869a994", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4187, "license_type": "no_license", "max_line_length": 192, "num_lines": 122, "path": "/code/SOURCE CODE/understanding short text/src/java/network/NewServlet.java", "repo_name": "Ramya667/Understanding-Short-Text-Using-Semantic-Enrichment-and-Semantic-Hashing-Batch-09", "src_encoding": "UTF-8", "text": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage network;\n\nimport com.oreilly.servlet.MultipartRequest;\nimport com.sun.org.apache.xerces.internal.impl.dv.util.Base64;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\nimport javax.crypto.KeyGenerator;\nimport javax.crypto.SecretKey;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport network.DbConnection;\n\n\n/**\n *\n * @author java4\n */\npublic class NewServlet extends HttpServlet {\n\n File file;\n final String filepath = \"D:/\";\n\n protected void processRequest(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n response.setContentType(\"text/html;charset=UTF-8\");\n PrintWriter out = response.getWriter();\n try {\n MultipartRequest m = new MultipartRequest(request, filepath);\n String name = m.getParameter(\"name\");\n String sname = m.getParameter(\"sname\");\n String des = m.getParameter(\"des\");\n System.out.println(\"pname\" + name + sname + des); \n File file = m.getFile(\"file\");\n String filename = file.getName().toLowerCase();\n Connection con = DbConnection.getConnection();\n BufferedReader br = new BufferedReader(new FileReader(filepath + filename));\n StringBuffer sb = new StringBuffer();\n String temp = null;\n\n while ((temp = br.readLine()) != null) {\n sb.append(temp);\n }\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy.MM.dd\");\n Date date = new Date();\n String time = dateFormat.format(date);\n System.out.println(\"current Date \" + time); \n Statement st = con.createStatement();\n int i = st.executeUpdate(\"insert into file(filename,sname,des,file,time,rank)values('\" + name + \"','\" + sname + \"','\" + des + \"','\" + sb.toString() + \"','\" + time + \"', '0')\");\n System.out.println(i);\n if (i != 0) {\n response.sendRedirect(\"upfile.jsp?msg='uploded'\");\n\n } else {\n out.println(\"Error in SQL Syntex\");\n }\n \n } catch (Exception e) {\n out.println(e);\n } finally {\n out.close();\n }\n }\n\n // <editor-fold defaultstate=\"collapsed\" desc=\"HttpServlet methods. Click on the + sign on the left to edit the code.\">\n /**\n * Handles the HTTP\n * <code>GET</code> method.\n *\n * @param request servlet request\n * @param response servlet response\n * @throws ServletException if a servlet-specific error occurs\n * @throws IOException if an I/O error occurs\n */\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n processRequest(request, response);\n }\n\n /**\n * Handles the HTTP\n * <code>POST</code> method.\n *\n * @param request servlet request\n * @param response servlet response\n * @throws ServletException if a servlet-specific error occurs\n * @throws IOException if an I/O error occurs\n */\n @Override\n protected void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n processRequest(request, response);\n }\n\n /**\n * Returns a short description of the servlet.\n *\n * @return a String containing servlet description\n */\n @Override\n public String getServletInfo() {\n return \"Short description\";\n }// </editor-fold>\n}" } ]
5
sandip60/Python
https://github.com/sandip60/Python
23b0e94c57a3ea5f0d5f918d9ad16b6546376773
09dfea499b430f21ffb1ab44e9dd6b34ee9b8d44
0c7c5022c72397641d0d82ddec7219db84ede737
refs/heads/master
2020-02-26T13:46:22.605635
2017-07-09T05:22:53
2017-07-09T05:22:53
95,592,268
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5275779366493225, "alphanum_fraction": 0.6115108132362366, "avg_line_length": 10.885714530944824, "blob_id": "4d28029a0d29666f8915a053177b77eba1ebc0c9", "content_id": "952760487fc0b5ade9c925491d22dd4725066a28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 31, "num_lines": 35, "path": "/p21.py", "repo_name": "sandip60/Python", "src_encoding": "UTF-8", "text": "\n#varibles\nname =\"sandip kumar \";\nname=\"sher\";\nname =\"kumar sandip \";\nprint(name);\n\n\n#data type\n\n#number\nnum1 =30 ;\nprint(type(num1));\nprint(num1);\n\nnum1 = 30.567;\nprint(type(num1));\nprint (num1);\n\nnum1 = 1 + 7j ;\nprint(type(num1));\nprint(num1);\nprint(num1.real);\nprint(num1.imag);\n\n#string\nnum1 = \"Sandip\";\nprint(type(num1));\nprint (num1);\n\nnum1 = '300' ;\nprint(type(num1));\nprint (num1);\n\n#list\nnum1 = [\"Sandip\" , 40 , 40.2 ];\n" }, { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.6704545617103577, "avg_line_length": 10, "blob_id": "1c4a5a472330787f029d609167f9dd817c0c9c20", "content_id": "3d069dc3b7755163b96e5b1fca37d30f0d828583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 88, "license_type": "no_license", "max_line_length": 23, "num_lines": 8, "path": "/p11.py", "repo_name": "sandip60/Python", "src_encoding": "UTF-8", "text": "#print hello world\nprint(\"Hello world! \");\n\n\n\n#print a number\nprint(10);\nprint(21.033);\n" } ]
2
JiahangXu/nn-Meter
https://github.com/JiahangXu/nn-Meter
3a0303c08f59ca91673047fe6dcd5cb052ebc4d3
c11b8223ecf8b5ba881528071a8ae18df80584ba
650bd88bf5da6b4105d84d0ef97434a4f4512790
refs/heads/main
2023-08-25T14:57:05.299811
2021-10-12T10:15:36
2021-10-12T10:15:36
393,234,662
0
0
MIT
2021-08-06T03:20:10
2021-08-06T02:21:44
2021-08-06T02:39:50
null
[ { "alpha_fraction": 0.5466179251670837, "alphanum_fraction": 0.5484460592269897, "avg_line_length": 23.863636016845703, "blob_id": "0a6c1d3522523cdd2a9f2cb52d986cade377e180", "content_id": "ee45d01afe6bf65a2dce8f2e9f5419788a2d8811", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 547, "license_type": "permissive", "max_line_length": 63, "num_lines": 22, "path": "/nn_meter/kerneldetection/utils/union_find.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nclass UF:\n \"\"\"\n UnionFind implemented with compression optimization\n \"\"\"\n\n def __init__(self, N):\n self._parent = list(range(0, N))\n\n def find(self, p):\n while p != self._parent[p]:\n p = self._parent[p] = self._parent[self._parent[p]]\n return p\n\n def union(self, p, q):\n p = self.find(p)\n q = self.find(q)\n self._parent[q] = p\n\n def connected(self, p, q):\n return self.find(p) == self.find(q)\n" }, { "alpha_fraction": 0.5335484147071838, "alphanum_fraction": 0.5380645394325256, "avg_line_length": 31.29166603088379, "blob_id": "9b877c8702b87a07807a635519e22bdaca82478f", "content_id": "0e3403dda9f63a576f385738e7bf513f5fe1c4be", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1550, "license_type": "permissive", "max_line_length": 86, "num_lines": 48, "path": "/nn_meter/kerneldetection/utils/ir_tools.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport copy\nfrom .constants import OP_ALIAS\n\n\ndef convert_nodes(graph):\n \"\"\"\n Resolve inconsistency between ONNX and Tensorflow\n \"\"\"\n new_graph = copy.deepcopy(graph)\n\n for _, node in new_graph.items():\n type = node[\"attr\"][\"type\"]\n new_type = OP_ALIAS.get(type, type)\n attr = node[\"attr\"][\"attr\"]\n\n if \"kernel_shape\" in attr:\n attr[\"ks\"] = attr[\"kernel_shape\"]\n del attr[\"kernel_shape\"]\n\n if \"weight_shape\" in attr and attr[\"weight_shape\"] is not None:\n attr[\"ks\"] = attr[\"weight_shape\"][0:2]\n del attr[\"weight_shape\"]\n\n if \"ksize\" in attr:\n attr[\"ks\"] = attr[\"ksize\"]\n del attr[\"ksize\"]\n\n if new_type == \"split\" and \"axis\" in attr:\n attr[\"split_dim\"] = attr[\"axis\"]\n del attr[\"axis\"]\n\n # workaround for add, mul, div, sub with const\n if new_type in [\"add\", \"mul\", \"div\", \"sub\"] and \"input_shape\" in node[\"attr\"]:\n input_shape = node[\"attr\"][\"input_shape\"]\n shape = input_shape[0] if input_shape[0] else input_shape[1]\n node[\"attr\"][\"input_shape\"] = [shape] * len(input_shape)\n\n if new_type == \"conv\" and \"group\" in attr and \"input_shape\" in node[\"attr\"]:\n group = attr[\"group\"]\n cin = node[\"attr\"][\"input_shape\"][0][3]\n if group == cin:\n new_type = \"dwconv\"\n\n node[\"attr\"][\"type\"] = new_type\n\n return new_graph\n" }, { "alpha_fraction": 0.6724509000778198, "alphanum_fraction": 0.674857497215271, "avg_line_length": 45.71597671508789, "blob_id": "0ed54b538d644a98e777fb647976d4385c5be410", "content_id": "fa384549fbba8c5d3ec0069a6e52ff95429ab708", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7895, "license_type": "permissive", "max_line_length": 170, "num_lines": 169, "path": "/nn_meter/nn_meter.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom glob import glob\nfrom nn_meter.prediction.predictors.predict_by_kernel import nn_predict\nfrom nn_meter.kerneldetection import KernelDetector\nfrom nn_meter.ir_converters import model_file_to_graph, model_to_graph\nfrom nn_meter.prediction.load_predictors import loading_to_local\n\nimport yaml\nimport os\nimport pkg_resources\nfrom shutil import copyfile\nfrom packaging import version\nimport logging\n\n__user_config_folder__ = os.path.expanduser('~/.nn_meter/config')\n__default_user_data_folder__ = os.path.expanduser('~/.nn_meter/data')\n\n__predictors_cfg_filename__ = 'predictors.yaml'\n\n\ndef create_user_configs():\n \"\"\"create user configs from distributed configs\n \"\"\"\n os.makedirs(__user_config_folder__, exist_ok=True)\n # TODO/backlog: to handle config merging when upgrading\n for f in pkg_resources.resource_listdir(__name__, 'configs'):\n copyfile(pkg_resources.resource_filename(__name__, f'configs/{f}'), os.path.join(__user_config_folder__, f))\n # make default setting yaml file\n with open(os.path.join(__user_config_folder__, 'settings.yaml'), 'w') as fp:\n yaml.dump({'data_folder': __default_user_data_folder__}, fp)\n\n\ndef get_user_data_folder():\n \"\"\"get user data folder in settings.yaml\n \"\"\"\n filepath = os.path.join(__user_config_folder__, 'settings.yaml')\n try:\n with open(filepath) as fp:\n return os.path.join(yaml.load(fp, yaml.FullLoader)['data_folder'])\n except FileNotFoundError:\n logging.info(f\"setting file {filepath} not found, created\")\n create_user_configs()\n return get_user_data_folder()\n\n\ndef change_user_data_folder(new_folder):\n \"\"\"change user data folder in settings.yaml\n \"\"\"\n os.makedirs(new_folder, exist_ok=True)\n with open(os.path.join(__user_config_folder__, 'settings.yaml')) as fp:\n setting = yaml.load(fp, yaml.FullLoader)\n with open(os.path.join(__user_config_folder__, 'settings.yaml'), 'w') as fp:\n setting['data_folder'] = new_folder\n yaml.dump(setting, fp)\n\n\ndef load_config_file(fname: str, loader=None):\n \"\"\"load config file from __user_config_folder__;\n if the file not located in __user_config_folder__, copy it from distribution\n \"\"\"\n filepath = os.path.join(__user_config_folder__, fname)\n try:\n with open(filepath) as fp:\n if loader is None:\n return yaml.load(fp, yaml.FullLoader)\n else:\n return loader(fp)\n except FileNotFoundError:\n logging.info(f\"config file {filepath} not found, created\")\n create_user_configs()\n return load_config_file(fname)\n\n\ndef list_latency_predictors():\n \"\"\"return the list of latency predictors specified in nn_meter/configs/predictors.yaml\n \"\"\"\n return load_config_file(__predictors_cfg_filename__)\n\n\ndef load_predictor_config(predictor_name: str, predictor_version: float = None):\n \"\"\"\n return the information of the predictor model according to the given predictor name and version\n @params:\n\n predictor_name: string to specify the name of the target latency predictor. All built-in predictors can be viewed by nn_meter.list_latency_predictors() \n or through the config file in nn_meter/configs/predictors.yaml.\n \n predictor_version: string to specify the version of the target latency predictor. If not specified (default as None), the lateast version of the \n predictor will be loaded.\n \"\"\"\n config = load_config_file(__predictors_cfg_filename__)\n preds_info = [p for p in config if p['name'] == predictor_name and (predictor_version is None or p['version'] == predictor_version)]\n n_preds = len(preds_info)\n if n_preds == 1:\n return preds_info[0]\n elif n_preds > 1:\n # find the latest version of the predictor\n latest_version, latest_version_idx = version.parse(preds_info[0]['version']), 0\n for i in range(1, n_preds):\n if version.parse(preds_info[i]['version']) > latest_version:\n latest_version = version.parse(preds_info[i]['version'])\n latest_version_idx = i\n print(f'WARNING: There are multiple version for {predictor_name}, use the latest one ({str(latest_version)})')\n return preds_info[latest_version_idx]\n else:\n raise NotImplementedError('No predictor that meets the required name and version, please try again.')\n\n\ndef load_latency_predictor(predictor_name: str, predictor_version: float = None):\n \"\"\" \n return the predictor model according to the given predictor name and version\n @params:\n\n predictor_name: string to specify the name of the target latency predictor. All built-in predictors can be viewed by nn_meter.list_latency_predictors() \n or through the config file in nn_meter/configs/predictors.yaml.\n \n predictor_version: string to specify the version of the target latency predictor. If not specified (default as None), the lateast version of the \n predictor will be loaded.\n \"\"\"\n user_data_folder = get_user_data_folder()\n pred_info = load_predictor_config(predictor_name, predictor_version)\n kernel_predictors, fusionrule = loading_to_local(pred_info, os.path.join(user_data_folder, 'predictor'))\n return nnMeter(kernel_predictors, fusionrule)\n\n\nclass nnMeter:\n def __init__(self, predictors, fusionrule):\n self.kernel_predictors = predictors\n self.fusionrule = fusionrule\n self.kd = KernelDetector(self.fusionrule)\n\n def predict(\n self, model, model_type, input_shape=(1, 3, 224, 224), apply_nni=False\n ):\n \"\"\"\n return the predicted latency in microseconds (ms)\n @params:\n\n model: the model to be predicted, allowed file include\n - the path to a saved tensorflow model file (*.pb), `model_type` must be set to \"pb\"\n - pytorch model object (nn.Module), `model_type` must be set to \"torch\"\n - ONNX model object or the path to a saved ONNX model file (*.onnx), `model_type` must be set to \"onnx\"\n - dictionary object following nn-Meter-IR format, `model_type` must be set to \"nnmeter-ir\"\n - dictionary object following NNI-IR format, `model_type` must be set to \"nni-ir\"\n \n model_type: string to specify the type of parameter model, allowed items are [\"pb\", \"torch\", \"onnx\", \"nnmeter-ir\", \"nni-ir\"]\n \n input_shape: the shape of input tensor for inference (if necessary), a random tensor according to the shape will be generated and used. This parameter is only \n accessed when model_type == 'torch'\n\n apply_nni: switch the torch converter used for torch model parsing. If apply_nni==True, NNI-based converter is used for torch model conversion, which requires \n nni>=2.4 installation and should use nn interface from NNI `import nni.retiarii.nn.pytorch as nn` to define the PyTorch modules. Otherwise Onnx-based torch \n converter is used, which requires onnx installation (well tested version is onnx==1.9.0). NNI-based converter is much faster while the conversion is unstable \n as it could fail in some case. Onnx-based converter is much slower but stable compared to NNI-based converter. This parameter is only accessed when \n model_type == 'torch'\n \"\"\"\n logging.info(\"Start latency prediction ...\")\n if isinstance(model, str):\n graph = model_file_to_graph(model, model_type, input_shape, apply_nni=apply_nni)\n else:\n graph = model_to_graph(model, model_type, input_shape=input_shape, apply_nni=apply_nni)\n \n # logging.info(graph)\n self.kd.load_graph(graph)\n\n py = nn_predict(self.kernel_predictors, self.kd.kernels) # in unit of ms\n logging.info(f\"Predict latency: {py} ms\")\n return py\n" }, { "alpha_fraction": 0.6116932034492493, "alphanum_fraction": 0.6248952150344849, "avg_line_length": 40.46086883544922, "blob_id": "0825750fa1bb011b5e6299d5d1ae4f189de48f23", "content_id": "d9c54027bcb1a5abf13e0b429192fcdf4725e709", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4772, "license_type": "permissive", "max_line_length": 177, "num_lines": 115, "path": "/tests/integration_test_torch.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "import re\nimport os\nimport time\nimport logging\nimport subprocess\nfrom integration_test import *\nimport argparse\n\n\n__torchvision_model_zoo__ = {\n 'resnet18': 'models.resnet18()',\n 'alexnet': 'models.alexnet()',\n 'vgg16': 'models.vgg16()',\n 'squeezenet': 'models.squeezenet1_0()',\n 'densenet161': 'models.densenet161()',\n 'inception_v3': 'models.inception_v3()',\n 'googlenet': 'models.googlenet()',\n 'shufflenet_v2': 'models.shufflenet_v2_x1_0()',\n 'mobilenet_v2': 'models.mobilenet_v2()',\n 'resnext50_32x4d': 'models.resnext50_32x4d()',\n 'wide_resnet50_2': 'models.wide_resnet50_2()',\n 'mnasnet': 'models.mnasnet1_0()',\n }\n\n \n# integration test to predict model latency\ndef integration_test_onnx_based_torch(model_type, model_list, output_name = \"tests/test_result_onnx_based_torch.txt\"):\n \"\"\"\n download the kernel predictors from the url\n @params:\n\n model_type: torch\n model_list: the torchvision model waiting for latency prediction\n output_name: a summary file to save the testing results\n \"\"\"\n # if the output is not created, create it and add a title\n if not os.path.isfile(output_name):\n with open(output_name,\"w\") as f:\n f.write('model_name, model_type, predictor, predictor_version, latency\\n')\n \n # start testing\n for pred_name, pred_version in get_predictors():\n try:\n since = time.time()\n # print(f'nn-meter --torchvision ' + \" \".join(model_list) + f' --predictor {pred_name} --predictor-version {pred_version}')\n result = subprocess.check_output(['nn-meter', 'lat_pred', f'--torchvision'] + model_list + ['--predictor', f'{pred_name}', '--predictor-version', f'{pred_version}'])\n runtime = time.time() - since\n except NotImplementedError:\n logging.error(\"Meets ERROR when checking --torchvision {model_string} --predictor {pred_name} --predictor-version {pred_version}\")\n\n latency_list = parse_latency_info(result.decode('utf-8'))\n for model, latency in latency_list:\n item = f'{model}, {model_type}, {pred_name}, {pred_version}, {round(float(latency), 4)}\\n'\n # print(item)\n with open(output_name, \"a\") as f:\n f.write(item)\n\n\n# integration test to predict model latency\ndef integration_test_nni_based_torch(output_name = \"tests/test_result_nni_based_torch.txt\"):\n \"\"\"\n download the kernel predictors from the url\n @params:\n\n model_type: torch\n url: github release url address for testing model file\n ppath: the targeting dir to save the download model file\n output_name: a summary file to save the testing results\n \"\"\"\n import torchmodels as models\n from nn_meter import load_latency_predictor\n\n # if the output_name is not created, create it and add a title\n if not os.path.isfile(output_name):\n with open(output_name,\"w\") as f:\n f.write('model_name, model_type, predictor, predictor_version, latency\\n')\n \n # start testing\n for pred_name, pred_version in get_predictors():\n predictors = load_latency_predictor(pred_name, float(pred_version))\n for model_name in __torchvision_model_zoo__:\n try:\n model = eval(__torchvision_model_zoo__[model_name])\n latency = predictors.predict(model, \"torch\", apply_nni=True)\n item = f'{model_name}, torch, {pred_name}, {pred_version}, {round(float(latency), 4)}\\n'\n with open(output_name, \"a\") as f:\n f.write(item)\n except NotImplementedError:\n logging.error(f\"Meets ERROR when checking {model_name}\") \n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser('integration-test-torch')\n parser.add_argument(\"--apply-onnx\", help='apply onnx-based torch converter for torch model', action='store_true', default=False)\n parser.add_argument(\"--apply-nni\", help='apply nni-based torch converter for torch model', action='store_true', default=False)\n args = parser.parse_args()\n\n check_package_status()\n\n if not args.apply_onnx and not args.apply_nni:\n args.apply_onnx = True\n args.apply_nni = True\n\n # check torch model\n if args.apply_nni:\n # check NNI-based torch converter\n integration_test_nni_based_torch()\n if args.apply_onnx:\n # check ONNX-based torch converter\n integration_test_onnx_based_torch(\n model_type='torch',\n model_list=[\n 'resnet18', 'alexnet', 'vgg16', 'squeezenet', 'densenet161', 'inception_v3', 'googlenet', \n 'shufflenet_v2', 'mobilenet_v2', 'resnext50_32x4d', 'wide_resnet50_2', 'mnasnet']\n )\n " }, { "alpha_fraction": 0.5377175807952881, "alphanum_fraction": 0.5408123731613159, "avg_line_length": 36.463768005371094, "blob_id": "e8e5f411e4a189aa8a9002a8655e147d9af854d1", "content_id": "7d4971bd7e96ea08d785b5f36fc3da4deb1c1827", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2585, "license_type": "permissive", "max_line_length": 90, "num_lines": 69, "path": "/nn_meter/kerneldetection/rulelib/rule_splitter.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom .rule_reader import RuleReader\nfrom nn_meter.utils.graph_tool import ModelGraph\nfrom nn_meter.kerneldetection.utils.match_helper import MatchHelper\nfrom nn_meter.kerneldetection.utils.fusion_aware_graph import FusionAwareGraph\n\n\nclass RuleSplitter:\n def __init__(self, rule_reader: RuleReader):\n self.rule_reader = rule_reader\n\n def fuse_multiop_blocks(self, model_graph: ModelGraph):\n for type, blocks in self.rule_reader.fusion_units.items():\n for block in blocks:\n subgraphs = model_graph.find_subgraphs(block, MatchHelper.op_type_matcher)\n for subgraph in subgraphs:\n model_graph.fuse(subgraph.keys(), type)\n\n def split(self, model_graph: ModelGraph):\n \"\"\"\n Apply rules to graph\n \"\"\"\n self.preprocess(model_graph)\n fusion_graph = FusionAwareGraph(model_graph)\n\n i = -1\n while i < len(fusion_graph) - 1:\n i += 1\n if fusion_graph.is_fused(i):\n continue\n fusion_graph.mark_ready(i)\n if not fusion_graph.get_outbounds(i):\n continue\n # MON\n mon = self.rule_reader.query_rule(\"MON\")\n if mon == 0: # can't fuse if having multiple out node\n if len(fusion_graph.get_outbounds(i)) > 1:\n continue\n # FN: TODO: which one is the first node\n fused = False\n for j in fusion_graph.get_outbounds(i):\n if fusion_graph.is_fused(j):\n continue\n outnode_type = fusion_graph.get_type(j)\n node_type = fusion_graph.get_type(i)\n if not self.rule_reader.is_fusible(node_type, outnode_type):\n continue\n # RT\n if self.rule_reader.query_rule(\"RT\"):\n if not fusion_graph.is_ready(j):\n continue\n # fuse node\n if mon == 0:\n fusion_graph.fuse(i, j)\n else:\n fusion_graph.fuse(i, j, True)\n fusion_graph.mark_ready(j)\n fused = True\n if mon == 1: # only fused to first outnode\n break\n if fused:\n i -= 1\n\n self._fusion_graph = fusion_graph\n return fusion_graph.get_basicblocks()\n\n def preprocess(self, model_graph: ModelGraph):\n self.fuse_multiop_blocks(model_graph)\n" }, { "alpha_fraction": 0.5894339680671692, "alphanum_fraction": 0.5932075381278992, "avg_line_length": 32.125, "blob_id": "7a80436e996eee33af3c56a4becf6ec631c3f4e1", "content_id": "23336c3975cf0fa10e82169abefa5d563188ba15", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1325, "license_type": "permissive", "max_line_length": 71, "num_lines": 40, "path": "/nn_meter/ir_converters/torch_converter/opset_map.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nnni_type_map = {\n \"aten::mul\": \"mul\",\n \"aten::floordiv\": \"div\",\n \"aten::reshape\": \"reshape\",\n \"aten::cat\": \"concat\",\n \"aten::split\": \"split\",\n \"__torch__.torch.nn.modules.conv.Conv2d\": \"conv\",\n \"__torch__.torch.nn.modules.activation.ReLU\": \"relu\",\n \"__torch__.torch.nn.modules.batchnorm.BatchNorm2d\": \"bn\",\n \"__torch__.torch.nn.modules.linear.Linear\": \"fc\",\n \"__torch__.torch.nn.modules.pooling.AvgPool2d\": \"gap\",\n \"__torch__.torch.nn.modules.pooling.MaxPool2d\": \"maxpool\",\n \"__torch__.torch.nn.modules.activation.Sigmoid\": \"sigmoid\",\n \"__torch__.torch.nn.modules.activation.Hardsigmoid\": \"hardsigmoid\",\n \"__torch__.torch.nn.modules.activation.Hardswish\": \"hswish\",\n \"__torch__.torch.nn.modules.activation.ReLU6\": \"relu\",\n \"__torch__.torch.nn.modules.activation.Softmax\": \"softmax\",\n}\n\n\ndef int_to_list_modifier(attr):\n if isinstance(attr, int):\n return [attr, attr]\n else:\n return list(attr)\n\n\nnni_attr_map = {\n \"__all__\": {\n \"kernel_size\": (\"ks\", int_to_list_modifier),\n \"padding\": (\"pads\", int_to_list_modifier),\n \"stride\": (\"strides\", int_to_list_modifier),\n \"groups\": (\"group\", None),\n },\n \"concat\": {\n \"dim\": (\"axis\", None),\n },\n}\n" }, { "alpha_fraction": 0.47577518224716187, "alphanum_fraction": 0.48110464215278625, "avg_line_length": 33.400001525878906, "blob_id": "1dc192f99beeffd00ba254ab0382790f2811d53a", "content_id": "62da24c8a1c7e5b35bb6f0500174d5ce63b2f4c9", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2064, "license_type": "permissive", "max_line_length": 87, "num_lines": 60, "path": "/nn_meter/kerneldetection/rulelib/rule_reader.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport json\nfrom nn_meter.utils.graph_tool import ModelGraph\nfrom nn_meter.kerneldetection.fusionlib import get_fusion_unit\n\n\nclass RuleReader:\n rules_default = {\n \"MON\": 0,\n \"RT\": True,\n \"FN\": True,\n }\n\n multiop_blocks = [\"se\", \"hswish\", \"channelshuffle\", \"gap\"]\n\n def __init__(self, rule_file=None):\n self.rules = {}\n if rule_file:\n with open(rule_file, \"r\") as fp:\n self.rules = json.load(fp)\n self._extract_fusible()\n self._parse_multiop_block()\n\n def is_fusible(self, node_type, outnode_type):\n return (node_type, outnode_type) in self.fusible\n\n def query_rule(self, rule):\n if rule not in self.rules or self.rules[rule][\"obey\"] is None:\n return self.rules_default[rule]\n else:\n return self.rules[rule][\"obey\"]\n\n def _extract_fusible(self):\n def get_name(i):\n return f\"{ops[i]}_{i}\"\n\n self.fusible = []\n self.fusion_units = {}\n for name, rule in self.rules.items():\n if rule[\"obey\"] and name.startswith(\"BF\"):\n ops = name.split(\"_\")[1:]\n if len(ops) == 2:\n self.fusible.append((ops[0], ops[1]))\n elif len(ops) > 2:\n fusion_unit = {}\n for i in range(0, len(ops)):\n fusion_unit[get_name(i)] = {\n \"attr\": {\n \"type\": ops[i],\n \"attr\": {},\n },\n \"inbounds\": [get_name(i - 1)] if i > 0 else [],\n \"outbounds\": [get_name(i + 1)] if i < len(ops) - 1 else [],\n }\n self.fusion_units[\"-\".join(ops)] = [ModelGraph(graph=fusion_unit)]\n\n def _parse_multiop_block(self):\n for block in self.multiop_blocks:\n self.fusion_units[block] = get_fusion_unit(block)\n" }, { "alpha_fraction": 0.6164992451667786, "alphanum_fraction": 0.6219087839126587, "avg_line_length": 34.21088409423828, "blob_id": "5034106c9e9f0dce350fcbcdb723b629137313e7", "content_id": "eb2371a3f1d910b7ec30797b29d9bb224de37789", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5176, "license_type": "permissive", "max_line_length": 174, "num_lines": 147, "path": "/tests/integration_test.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport re\nimport os\nimport time\nfrom glob import glob\nimport logging\nimport subprocess\nfrom nn_meter import download_from_url\n\n\n__model_suffix__ = {\n \"tensorflow\": \".pb\",\n \"onnx\": \".onnx\"\n}\n\n\n# check package status\ndef check_package_status():\n try:\n output1 = subprocess.check_output(['nn-meter', '-h'])\n except NotImplementedError:\n logging.error(\"Meets ERROR when checking 'nn-meter -h'\")\n\n\n# check predictors list\ndef get_predictors():\n try:\n predictors_list = subprocess.check_output(['nn-meter', '--list-predictors'])\n except NotImplementedError:\n logging.error(\"Meets ERROR when checking 'nn-meter --list-predictors'\")\n\n predictors_list = predictors_list.decode('utf-8')\n pattern = re.compile(r'(?<=\\[Predictor\\] ).+(?=\\n)')\n predictors_info = pattern.findall(predictors_list)\n predictors = list(map(lambda x: re.sub('\\s*', '', x).split(':version='), predictors_info))\n return predictors\n\n\ndef get_models(model_type, ppath = \"data/testmodels/pb\"):\n models = glob(os.path.join(ppath, \"**\" + __model_suffix__[model_type]))\n models.sort() # sort the models list by alphabetical order\n return models\n\n\ndef parse_latency_info(info):\n # (nn-Meter) [RESULT] predict latency for shufflenetv2_0.onnx: 5.423898780782251 ms\n pattern = re.compile(r'(?<=\\[RESULT\\] predict latency for ).*(?= ms\\n)')\n latency_info = pattern.findall(info)\n latency_list = list(map(lambda x: re.sub('\\s*', '', x).split(':'), latency_info))\n return latency_list\n \n\n# integration test to predict model latency\ndef integration_test(model_type, url, ppath, output_name = \"tests/test_result.txt\"):\n \"\"\"\n download the kernel predictors from the url\n @params:\n\n model_type: tensorflow, onnx, \n url: github release url address for testing model file\n ppath: the targeting dir to save the download model file\n output_name: a summary file to save the testing results\n \"\"\"\n if not os.path.isdir(\"../data/testmodels\"):\n os.mkdir(\"../data\")\n os.mkdir(\"../data/testmodels\")\n\n # download data and unzip\n if not os.path.isdir(ppath):\n os.mkdir(ppath)\n logging.keyinfo(f'Download from {url} ...')\n download_from_url(url, ppath)\n\n # if the output_name is not created, create it and add a title\n if not os.path.isfile(output_name):\n with open(output_name,\"w\") as f:\n f.write('model_name, model_type, predictor, predictor_version, latency\\n')\n \n # start testing\n for pred_name, pred_version in get_predictors():\n try:\n since = time.time()\n # print(f'nn-meter --{model_type} {ppath} --predictor {pred_name} --predictor-version {pred_version}')\n result = subprocess.check_output(['nn-meter', 'lat_pred', f'--{model_type}', f'{ppath}', '--predictor', f'{pred_name}', '--predictor-version', f'{pred_version}'])\n runtime = time.time() - since\n except NotImplementedError:\n logging.error(f\"Meets ERROR when checking --{model_type} {ppath} --predictor {pred_name} --predictor-version {pred_version}\")\n\n latency_list = parse_latency_info(result.decode('utf-8'))\n for model, latency in latency_list:\n item = f'{model}, {model_type}, {pred_name}, {pred_version}, {round(float(latency), 4)}\\n'\n # print(item)\n with open(output_name, \"a\") as f:\n f.write(item) \n \n\ndef check_getir_module(model_type, ppath):\n for model in get_models(model_type, ppath):\n try:\n _ = subprocess.check_output(['nn-meter', 'get_ir', f'--{model_type}', model])\n _ = subprocess.check_output(['nn-meter', 'get_ir', f'--{model_type}', model, '--output', f'temp.json'])\n if os.path.exists('temp.json'):\n os.remove('temp.json')\n break # test just one file to avoid time cosuming\n except NotImplementedError:\n logging.error(\"Meets ERROR when checking get_ir --{model_type} {ppath}'\")\n\n\nif __name__ == \"__main__\":\n check_package_status()\n output_name = \"tests/test_result.txt\"\n\n # check tensorflow model\n integration_test(\n model_type='tensorflow',\n url=\"https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/pb_models.zip\",\n ppath=\"../data/testmodels/pb\",\n output_name=output_name\n )\n\n # check onnx model\n integration_test(\n model_type='onnx',\n url=\"https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/onnx_models.zip\",\n ppath=\"../data/testmodels/onnx\",\n output_name=output_name\n )\n\n # check nnmeter-ir graph model\n integration_test(\n model_type='nn-meter-ir',\n url=\"https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/ir_graphs.zip\",\n ppath=\"../data/testmodels/ir\",\n output_name=output_name\n )\n\n # check getir\n check_getir_module(\n model_type='tensorflow',\n ppath = \"../data/testmodels/pb\"\n )\n\n check_getir_module(\n model_type='onnx',\n ppath = \"../data/testmodels/onnx\"\n )\n" }, { "alpha_fraction": 0.7772839665412903, "alphanum_fraction": 0.7832098603248596, "avg_line_length": 74, "blob_id": "be22489f497ccebe59f0cd3394bafd178216acd6", "content_id": "41599e768ed473fcd3008a5187a0cb482ca69f93", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2025, "license_type": "permissive", "max_line_length": 263, "num_lines": 27, "path": "/examples/README.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Examples for nn-Meter\n\nIn this folder, we provide several examples to show the usage of nn-Meter package.\n\nThe first example [1. Use nn-Meter for models with different format](nn-meter_for_different_model_format.ipynb) shows the basic python binding usage of nn-meter with models with different format of Tensorflow, PyTorch and ONNX model.\n\n#### Benchmark dataset\n\nTo evaluate the effectiveness of a prediction model on an arbitrary DNN model, we need a representative dataset that covers a large prediction scope. nn-Meter collects and generates 26k CNN models. (Please refer the paper for the dataset generation method.)\n\nWe release the dataset, and provide an interface of `nn_meter.dataset` for users to get access to the dataset. Users can also download the data from the [Download Link](https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/datasets.zip) on their own. \n\nExample [2. Use nn-Meter with the bench dataset](nn-meter_for_bench_dataset.ipynb) shows how to use nn-Meter to predict latency for the bench dataset.\n\nSince the dataset is encoded in a graph format, we also provide an example [3. Use bench dataset for GNN training](gnn_for_bench_dataset.ipynb) of using GCN to predict the model latency with the bench dataset.\n\nFinally, we provide more hardware-ware NAS examples in NNI.\n\n## Examples list\n\n1. [Use nn-Meter for models with different format](nn-meter_for_different_model_format.ipynb)\n2. [Use nn-Meter with the bench dataset](nn-meter_for_bench_dataset.ipynb)\n3. [Use bench dataset for GNN training](gnn_for_bench_dataset.ipynb)\n4. Use nn-Meter to construct latency constraint in SPOS NAS (TBD)\n - [Use nn-Meter in search part](https://github.com/microsoft/nni/blob/master/examples/nas/oneshot/spos/multi_trial.py)\n - [Use nn-Meter in sampling part](https://github.com/microsoft/nni/blob/master/examples/nas/oneshot/spos/supernet.py)\n5. [Use nn-Meter to construct latency penalty in Proxyless NAS](https://github.com/microsoft/nni/tree/master/examples/nas/oneshot/proxylessnas)\n" }, { "alpha_fraction": 0.5727229118347168, "alphanum_fraction": 0.5793991684913635, "avg_line_length": 39.32692337036133, "blob_id": "9dc567113bc0f712f176837adc15e33ccdeaf207", "content_id": "1c034b4e3768d84ec56f5a7a620e8f456786a1cb", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2097, "license_type": "permissive", "max_line_length": 103, "num_lines": 52, "path": "/nn_meter/dataset/bench_dataset.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport os, sys\nfrom nn_meter.prediction import latency_metrics\nfrom glob import glob\n\nfrom nn_meter.nn_meter import list_latency_predictors, load_latency_predictor, get_user_data_folder\nfrom nn_meter import download_from_url\nimport jsonlines\nimport logging\n\n\n__user_dataset_folder__ = os.path.join(get_user_data_folder(), 'dataset')\n\ndef bench_dataset(url=\"https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/datasets.zip\",\n data_folder=__user_dataset_folder__):\n if not os.path.isdir(data_folder):\n os.makedirs(data_folder)\n logging.keyinfo(f'Download from {url} ...')\n download_from_url(url, data_folder)\n\n datasets = glob(os.path.join(data_folder, \"**.jsonl\"))\n return datasets\n \nif __name__ == '__main__':\n logging.basicConfig(stream=sys.stdout, format=\"(nn-Meter) %(message)s\", level=logging.KEYINFO)\n\n datasets = bench_dataset()\n hws = list_latency_predictors()\n \n for hw in hws:\n hw_name, hw_version = hw[\"name\"], hw[\"version\"]\n predictor = load_latency_predictor(hw_name, hw_version)\n for filename in datasets:\n True_lat = []\n Pred_lat = []\n index = 0\n with jsonlines.open(filename) as data_reader:\n for i, item in enumerate(data_reader):\n graph = item[\"graph\"]\n pred_lat = predictor.predict(graph, model_type=\"nnmeter-ir\")\n real_lat = item[hw_name]\n logging.result(f'{filename}[{i}]: predict: {pred_lat}, real: {real_lat}')\n if real_lat != None:\n True_lat.append(real_lat)\n Pred_lat.append(pred_lat)\n index += 1\n if len(True_lat) > 0:\n rmse, rmspe, error, acc5, acc10, _ = latency_metrics(Pred_lat, True_lat)\n logging.result(\n f'{filename} on {hw_name}: rmse: {rmse}, 5%accuracy: {acc5}, 10%accuracy: {acc10}'\n )\n" }, { "alpha_fraction": 0.6504471898078918, "alphanum_fraction": 0.6624222993850708, "avg_line_length": 49.30534362792969, "blob_id": "1686a57964e11264a80bde8ccb7ae79d67875efe", "content_id": "d435835a7c0b1885a8773678ad67a18ee381e756", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6597, "license_type": "permissive", "max_line_length": 166, "num_lines": 131, "path": "/nn_meter/ir_converters/utils.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport json\nimport logging\nfrom nn_meter.utils.utils import try_import_onnx, try_import_torch, try_import_torchvision_models\nfrom .onnx_converter import OnnxConverter\nfrom .frozenpb_converter import FrozenPbConverter\nfrom .torch_converter import NNIBasedTorchConverter, OnnxBasedTorchConverter, NNIIRConverter\n\ndef model_file_to_graph(filename: str, model_type: str, input_shape=(1, 3, 224, 224), apply_nni=False):\n \"\"\"\n read the given file and convert the model in the file content to nn-Meter IR graph object \n @params:\n filename: string to specify the location of the file\n \n model: the model to be predicted, allowed file format include\n - the path to a saved tensorflow model file (*.pb), `model_type` must be set to \"pb\"\n - string to specify the name of a built-in torch model from the torchvision model zoo, `model_type` must be set to \"torch\"\n - the path to a saved ONNX model file (*.onnx), `model_type` must be set to \"onnx\"\n - the path to a saved dictionary object following nn-Meter-IR format (*.json), `model_type` must be set to \"nnmeter-ir\"\n - the path to a saved dictionary object following NNI-IR format(*.json), `model_type` must be set to \"nni-ir\"\n \n model_type: string to specify the type of parameter model, allowed items are [\"pb\", \"torch\", \"onnx\", \"nnmeter-ir\", \"nni-ir\"]\n \n input_shape: the shape of input tensor for inference (if necessary), a random tensor according to the shape will be generated and used. This parameter is only \n accessed when model_type == 'torch'\n \n apply_nni: switch the torch converter used for torch model parsing. If apply_nni==True, NNI-based converter is used for torch model conversion, which requires \n nni>=2.4 installation and should use nn interface from NNI `import nni.retiarii.nn.pytorch as nn` to define the PyTorch modules. Otherwise Onnx-based torch \n converter is used, which requires onnx installation (well tested version is onnx==1.9.0). NNI-based converter is much faster while the conversion is unstable \n as it could fail in some case. Onnx-based converter is much slower but stable compared to NNI-based converter. This parameter is only accessed when \n model_type == 'torch'\n \"\"\"\n if model_type == \"onnx\":\n onnx = try_import_onnx()\n model = onnx.load(filename)\n return onnx_model_to_graph(model)\n\n elif model_type == \"pb\":\n converter = FrozenPbConverter(filename)\n return converter.get_flatten_graph()\n\n elif model_type == \"nni-ir\":\n with open(filename, \"r\") as fp:\n model = json.load(fp)\n return nni_model_to_graph(model)\n\n elif model_type == \"nnmeter-ir\":\n with open(filename, \"r\") as fp:\n return json.load(fp)\n\n elif model_type == \"torch\":\n models = try_import_torchvision_models()\n torchvision_zoo_dict = {\n 'resnet18': 'models.resnet18()',\n 'alexnet': 'models.alexnet()',\n 'vgg16': 'models.vgg16()',\n 'squeezenet': 'models.squeezenet1_0()',\n 'densenet161': 'models.densenet161()',\n 'inception_v3': 'models.inception_v3()',\n 'googlenet': 'models.googlenet()',\n 'shufflenet_v2': 'models.shufflenet_v2_x1_0()',\n 'mobilenet_v2': 'models.mobilenet_v2()', # noqa: F841\n 'resnext50_32x4d': 'models.resnext50_32x4d()',\n 'wide_resnet50_2': 'models.wide_resnet50_2()',\n 'mnasnet': 'models.mnasnet1_0()',\n }\n if filename in torchvision_zoo_dict:\n model = eval(torchvision_zoo_dict[filename])\n else:\n suppost_list = \", \".join([k for k in torchvision_zoo_dict])\n raise ValueError(f\"Unsupported model name in torchvision. Supporting list: {suppost_list}\")\n return torch_model_to_graph(model, input_shape, apply_nni)\n\n else:\n raise ValueError(f\"Unsupported model type: {model_type}\")\n\n\ndef model_to_graph(model, model_type, input_shape=(1, 3, 224, 224), apply_nni=False):\n \"\"\"\n convert the given model to nn-Meter IR graph object \n @params:\n model: the model object for converting, allowed file format include\n - pytorch model object (nn.Module), `model_type` must be set to \"torch\"\n - ONNX model object, `model_type` must be set to \"onnx\"\n - dictionary object following NNI-IR format, `model_type` must be set to \"nni-ir\"\n \n model_type: string to specify the type of parameter model, allowed items are [\"torch\", \"onnx\", \"nnmeter-ir\", \"nni-ir\"]\n \n input_shape: the shape of input tensor for inference (if necessary), a random tensor according to the shape will be generated and used. This parameter is only \n accessed when model_type == 'torch'\n \"\"\"\n if model_type == \"onnx\":\n return onnx_model_to_graph(model)\n elif model_type == \"torch\":\n return torch_model_to_graph(model, input_shape, apply_nni)\n elif model_type == \"nni-ir\":\n return nni_model_to_graph(model)\n elif model_type == \"nnmeter-ir\":\n return model # nnmeter-ir doesn't need any post-process\n else:\n raise ValueError(f\"Unsupported model type: {model_type}\")\n\n\ndef onnx_model_to_graph(model):\n converter = OnnxConverter(model)\n return converter.convert()\n\ndef nni_model_to_graph(model):\n converter = NNIIRConverter(model)\n return converter.convert()\n\ndef torch_model_to_graph(model, input_shape=(1, 3, 224, 224), apply_nni=False):\n torch = try_import_torch()\n args = torch.randn(*input_shape)\n if next(model.parameters()).is_cuda:\n args = args.to(\"cuda\")\n if apply_nni: \n # apply NNI-based torch converter, which requires nni>=2.4 installation and should use nn interface from NNI \n # `import nni.retiarii.nn.pytorch as nn` to define the PyTorch modules.\n try:\n logging.info(\"NNI-based Torch Converter is applied for model conversion\")\n converter = NNIBasedTorchConverter(model, args)\n except:\n raise NotImplementedError(\"Your model is not fully converted by NNI-based converter. Please set apply_nni=False and try again.\")\n else:\n # apply Onnx-based torch converter, which requires onnx installation (well tested version is onnx==1.9.0) \n # and the conversion is more stable\n logging.info(\"Onnx-based Torch Converter is applied for model conversion\")\n converter = OnnxBasedTorchConverter(model, args)\n return converter.convert()\n \n\n\n" }, { "alpha_fraction": 0.5013920664787292, "alphanum_fraction": 0.5032480955123901, "avg_line_length": 33.657894134521484, "blob_id": "cf888327b5db6f6e88129a79f8e30d357a07890c", "content_id": "69c4f2ad1f3f240fd3bf70361850f09272049c92", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11853, "license_type": "permissive", "max_line_length": 87, "num_lines": 342, "path": "/nn_meter/utils/graph_tool.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport copy\nimport json\nimport numpy as np\nimport logging\n\n\nclass NumpyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n if isinstance(obj, (bytes, bytearray)):\n return obj.decode(\"utf-8\")\n return json.JSONEncoder.default(self, obj)\n\n\nclass ModelGraph:\n def __init__(self, filename=None, graph=None):\n if filename is not None:\n self.graph = json.load(open(filename, \"r\"))\n elif graph is not None:\n self.graph = copy.deepcopy(graph)\n else:\n self.graph = {}\n\n def node(self, name, inbound_nodes=None):\n self.graph[name] = {}\n if inbound_nodes is not None:\n self.graph[name][\"inbounds\"] = inbound_nodes\n for node in inbound_nodes:\n if node not in self.graph.keys():\n self.graph[node] = {}\n if \"outbounds\" not in self.graph[node].keys():\n self.graph[node][\"outbounds\"] = []\n self.graph[node][\"outbounds\"].append(name)\n\n def refresh(self):\n last_remove_nodes_cnt = -1\n while True:\n for name in self.graph.keys():\n self.graph[name][\"outbounds\"] = []\n\n for name in self.graph.keys():\n if \"inbounds\" in self.graph[name].keys():\n for node in self.graph[name][\"inbounds\"]:\n if node not in self.graph.keys():\n while node in self.graph[name][\"inbounds\"]:\n self.graph[name][\"inbounds\"].remove(node)\n else:\n if \"outbounds\" not in self.graph[node].keys():\n self.graph[node][\"outbounds\"] = []\n\n self.graph[node][\"outbounds\"].append(name)\n\n spare_nodes = []\n for name in self.graph.keys():\n if (\n len(self.graph[name][\"outbounds\"]) == 0\n and len(self.graph[name][\"inbounds\"]) == 0\n ):\n spare_nodes.append(name)\n\n if last_remove_nodes_cnt == 0 and len(spare_nodes) == 0:\n break\n\n last_remove_nodes_cnt = len(spare_nodes)\n for removing_node_name in spare_nodes:\n del self.graph[removing_node_name]\n\n def get_graph(self):\n return self.graph\n\n def get_node_inbounds(self, name):\n if \"inbounds\" in self.graph[name]:\n return self.graph[name][\"inbounds\"]\n else:\n return []\n\n def get_node_outbounds(self, name):\n if \"outbounds\" in self.graph[name]:\n return self.graph[name][\"outbounds\"]\n else:\n return []\n\n def set_node_inbounds(self, name, inbounds):\n self.graph[name][\"inbounds\"] = inbounds\n\n def set_node_outbounds(self, name, outbounds):\n self.graph[name][\"outbounds\"] = outbounds\n\n def remove_node_inbounds(self, name, inbound):\n if inbound in self.graph[name][\"inbounds\"]:\n self.graph[name][\"inbounds\"].remove(inbound)\n\n def remove_node_outbounds(self, name, outbound):\n if outbound in self.graph[name][\"outbounds\"]:\n self.graph[name][\"outbounds\"].remove(outbound)\n\n def add_node_inbounds(self, name, inbound):\n self.graph[name][\"inbounds\"].append(inbound)\n\n def add_node_outbounds(self, name, outbound):\n self.graph[name][\"outbounds\"].append(outbound)\n\n def get_graph_head(self):\n self.heads = []\n for (key, value) in self.graph.items():\n if \"inbounds\" not in value.keys() or len(value[\"inbounds\"]) == 0:\n self.heads.append(key)\n return self.heads\n\n def get_graph_tail(self):\n self.tails = []\n for (key, value) in self.graph.items():\n if \"outbounds\" not in value.keys() or len(value[\"outbounds\"]) == 0:\n self.tails.append(key)\n return self.tails\n\n def add_node_attr(self, name, attr_key, attr_value):\n if name not in self.graph.keys():\n self.graph[name] = {}\n self.graph[name][\"attr\"][\"attr\"][attr_key] = attr_value\n\n def set_node_attr(self, name, attr):\n if name not in self.graph.keys():\n self.graph[name] = {}\n self.graph[name][\"attr\"] = attr\n\n def get_node_attr(self, name):\n if name in self.graph.keys():\n return self.graph[name][\"attr\"]\n else:\n return None\n\n def get_node_type(self, name):\n if name in self.graph.keys() and \"attr\" in self.graph[name].keys():\n return self.graph[name][\"attr\"][\"type\"]\n else:\n logging.info(name, self.graph[name])\n return None\n\n def get_root_node(self, subgraph):\n root = next(iter(subgraph))\n\n flag = True\n while flag:\n flag = False\n for inbound in self.get_node_inbounds(root):\n if inbound in subgraph:\n flag = True\n root = inbound\n break\n\n return root\n\n def fuse(self, subgraph, type, name=None, attr=None, is_block=True):\n \"\"\"\n subgraph: list of node name\n Nothing will be done if subgraph doesn't exist in self\n \"\"\"\n for node in subgraph:\n if node not in self.graph:\n return False\n\n if name is None:\n name = \";\".join(subgraph)\n\n if attr is None:\n root_node = self.get_root_node(subgraph)\n attr = self.get_node_attr(root_node)\n attr[\"type\"] = type\n if is_block:\n attr[\"attr\"][\"primitive_nodes\"] = list(subgraph)\n\n self.graph[name] = {\n \"attr\": attr,\n \"inbounds\": [],\n \"outbounds\": [],\n }\n\n for node in subgraph:\n for inbound in self.get_node_inbounds(node):\n if inbound not in subgraph:\n if inbound not in self.get_node_inbounds(name):\n self.add_node_inbounds(name, inbound)\n self.remove_node_outbounds(inbound, node)\n if name not in self.get_node_outbounds(inbound):\n self.add_node_outbounds(inbound, name)\n for outbound in self.get_node_outbounds(node):\n if outbound not in subgraph:\n if outbound not in self.get_node_outbounds(name):\n self.add_node_outbounds(name, outbound)\n self.remove_node_inbounds(outbound, node)\n if name not in self.get_node_inbounds(outbound):\n self.add_node_inbounds(outbound, name)\n\n for node in subgraph:\n del self.graph[node]\n\n return True\n\n def plot_graphs(self, comment=\"Network Graph View\"):\n from graphviz import Digraph\n\n dot = Digraph(comment=comment)\n for (key, value) in self.graph.items():\n dot.node(key, key)\n if \"inbounds\" in value.keys():\n for node in value[\"inbounds\"]:\n dot.edge(\n node,\n key,\n label=\", \".join(str(x) for x in value[\"attr\"][\"output_shape\"]),\n )\n dot.render(\"graph.gv\", view=False)\n\n def plot_networkx_graph(self):\n import matplotlib.pyplot as plt\n import networkx as nx\n\n plt.subplot(121)\n nx.draw(self.get_networkx_graph(), with_labels=True, font_weight=\"bold\")\n plt.show()\n\n def get_networkx_graph(self):\n import networkx as nx\n\n G = nx.MultiDiGraph()\n for (key, value) in self.graph.items():\n G.add_node(key, type=value[\"attr\"][\"type\"], **value[\"attr\"][\"attr\"])\n if \"inbounds\" in value.keys():\n for node in value[\"inbounds\"]:\n G.add_edge(node, key)\n self.graphx = G\n return G\n\n def match_isomorph_vf2(self):\n pass\n\n def find_subgraphs(self, sub_graph, match_func):\n from networkx.algorithms import isomorphism as iso\n\n GM = iso.MultiDiGraphMatcher(\n self.get_networkx_graph(),\n sub_graph.get_networkx_graph(),\n node_match=match_func,\n )\n\n matches = []\n for match in GM.subgraph_isomorphisms_iter():\n matches.append(\n {\n key: value\n for key, value in match.items()\n if sub_graph.get_node_type(value) != \"dummy\"\n }\n )\n return matches\n\n def find_weight_roots(self, layer_name):\n weight_roots = []\n weights_nodes = []\n for inbound in self.graph[layer_name][\"inbounds\"]:\n if (\n self.graph[inbound][\"attr\"][\"type\"] == \"Identity\"\n and len(self.graph[inbound][\"inbounds\"]) == 1\n ):\n if (\n self.graph[self.graph[inbound][\"inbounds\"][0]][\"attr\"][\"type\"]\n == \"Const\"\n ):\n weight_roots.append(inbound)\n weights_nodes.append(inbound)\n weights_nodes.append(self.graph[inbound][\"inbounds\"][0])\n\n if (\n self.graph[inbound][\"attr\"][\"type\"] == \"Const\"\n and len(self.graph[inbound][\"inbounds\"]) == 0\n ):\n weight_roots.append(inbound)\n weights_nodes.append(inbound)\n\n return weight_roots, weights_nodes\n\n def get_subgraphs(self, sub_graph, match_func):\n import tensorflow as tf\n import copy\n\n fetched_subgraphs = self.find_subgraphs(sub_graph, match_func)\n tar_sub_graphs = []\n for sub_fetch_graph in fetched_subgraphs:\n tar_sub_graphs.append(tf.GraphDef())\n\n for op_entry in sub_fetch_graph.keys():\n # --- Repleace dummy op ---\n if (\n sub_graph.get_graph()[sub_fetch_graph[op_entry]][\"attr\"][\"type\"]\n == \"dummy\"\n ):\n dummy_op = tar_sub_graphs[-1].node.add()\n dummy_op.op = \"Identity\"\n dummy_op.name = sub_fetch_graph[op_entry]\n dummy_op.input.extend(\n sub_graph.get_graph()[sub_fetch_graph[op_entry]][\"inbounds\"]\n )\n dummy_op.attr[\"T\"].type = 1\n else:\n # --- Fetch the main op ---\n node = copy.deepcopy(self.graph[op_entry][\"attr\"][\"node\"])\n\n node.name = sub_fetch_graph[op_entry]\n\n del node.input[:]\n node.input.extend(\n sub_graph.get_graph()[sub_fetch_graph[op_entry]][\"inbounds\"]\n )\n # --- Fetch the constant op ---\n roots, nodes = self.find_weight_roots(op_entry)\n for weight_root in roots:\n node.input.append(weight_root)\n\n for weight_node in nodes:\n tar_sub_graphs[-1].node.append(\n self.graph[weight_node][\"attr\"][\"node\"]\n )\n\n tar_sub_graphs[-1].node.append(node)\n\n # tf.io.write_graph(tar_sub_graphs[-1], '', 'a.pb')\n return tar_sub_graphs\n\n def dump_json(self, filename):\n with open(filename, \"w+\") as fp:\n json.dump(\n self.graph,\n fp,\n indent=4,\n skipkeys=True,\n sort_keys=True,\n cls=NumpyEncoder,\n )\n" }, { "alpha_fraction": 0.43056994676589966, "alphanum_fraction": 0.43181347846984863, "avg_line_length": 36.6953125, "blob_id": "a0702a1e372d0401a7a26b555604f1aae46025e9", "content_id": "913a05107d3ff7b5bb35d4a146c8dda24563c9f0", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9650, "license_type": "permissive", "max_line_length": 91, "num_lines": 256, "path": "/nn_meter/ir_converters/frozenpb_converter/frozenpb_parser.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom nn_meter.utils.utils import try_import_tensorflow\nfrom .protobuf_helper import ProtobufHelper\nfrom .shape_fetcher import ShapeFetcher\nimport copy\nimport re\nimport logging\n\nlogging = logging.getLogger(__name__)\n\n\nclass FrozenPbParser:\n def __init__(self, pb_file):\n tf = try_import_tensorflow()\n f = open(pb_file, \"rb\")\n graph = tf.compat.v1.GraphDef()\n graph.ParseFromString(f.read())\n\n self.graph = graph\n\n @staticmethod\n def strip_useless_nodes(model_graph):\n \"\"\"\n Remove nodes that does not matter with the predict or the structure of model,\n including following types:\n - weights for ops\n - attributes for ops\n\n Parameters\n ----------\n model_graph : ModelGraph\n the graph holder\n \"\"\"\n stripped_nodes_type_all = []\n stripped_nodes_type = [\"Const\", \"Identity\"]\n stripped_nodes_keywords = [\n \"/weight\",\n \"/weight/read\",\n \"/ReadVariableOp\",\n \"/kernel\",\n \"/gamma\",\n \"/beta\",\n \"/moving_mean\",\n \"/moving_variance\",\n \"/bias\",\n \"/reduction_indices\",\n \"/shape\",\n \"/split_dim\",\n \"/axis\",\n ]\n graph = model_graph.get_graph()\n removed_node = []\n for key, value in graph.items():\n if \"attr\" in value.keys():\n if value[\"attr\"][\"type\"] in stripped_nodes_type:\n for kw in stripped_nodes_keywords:\n if kw in key:\n removed_node.append(key)\n break\n if value[\"attr\"][\"type\"] in stripped_nodes_type_all:\n removed_node.append(key)\n\n for key in removed_node:\n del graph[key]\n\n model_graph.refresh()\n\n @staticmethod\n def fix_split_naming(model_graph):\n \"\"\"\n TensorFlow is using \"NODE_NAME:NUMBER\" for example \"split:0\", \"split:1\"\n as a notation to oredered outputs,\n such notation will make the edge not able to connect. We patch it by using the list\n to store the name and keep the sequence.\n\n Parameters\n ----------\n model_graph : ModelGraph\n the graph holder\n \"\"\"\n graph = model_graph.get_graph()\n graph_nodes = copy.deepcopy(list(graph.keys()))\n remove_node_list = []\n for graph_node in graph_nodes:\n if graph_node in graph.keys():\n if \"attr\" in graph[graph_node].keys():\n if (\n graph[graph_node][\"attr\"][\"type\"] == \"Split\"\n and \":\" not in graph_node\n ):\n logging.info(\"Find split main node %s.\" % graph_node)\n split_node_name = graph_node\n for node_name in graph.keys():\n idx = re.findall(r\"%s:(\\d+)\" % split_node_name, node_name)\n if len(idx) > 0:\n idx = int(idx[0])\n logging.info(\"Find split child node %s.\" % node_name)\n graph[graph_node][\"outbounds\"] += graph[node_name][\n \"outbounds\"\n ]\n graph[graph[node_name][\"outbounds\"][0]][\"inbounds\"] += [\n graph_node\n ]\n remove_node_list.append(node_name)\n\n for node in remove_node_list:\n del graph[node]\n\n model_graph.refresh()\n\n def fetch_attr_to_dict(self, node):\n \"\"\"\n Tensorflow store some of the attributes as a node connect to the tensor.\n We fetch the attribute from those noed to a dict.\n\n Parameters\n ----------\n node : Protobuf.node\n The protobuf node of the frozen pb.\n \"\"\"\n\n attr_dict = {}\n\n attr_as_node = {\n \"Split\": {\n \"node_name\": lambda x: x + \"/split_dim\",\n \"attr_name\": \"split_dim\",\n \"node_value\": lambda x: ProtobufHelper.get_tensor_value(x),\n },\n \"Mean\": {\n \"node_name\": lambda x: x + \"/reduction_indices\",\n \"attr_name\": \"reduction_indices\",\n \"node_value\": lambda x: ProtobufHelper.pkg42dec(x.tensor_content),\n },\n \"Reshape\": {\n \"node_name\": lambda x: x + \"/shape\",\n \"attr_name\": \"shape\",\n \"node_value\": lambda x: ProtobufHelper.pkg42dec(x.tensor_content),\n },\n \"Concat\": {\n \"node_name\": lambda x: x + \"/axis\",\n \"attr_name\": \"axis\",\n \"node_value\": lambda x: ProtobufHelper.get_tensor_value(x),\n },\n \"ConcatV2\": {\n \"node_name\": lambda x: x + \"/axis\",\n \"attr_name\": \"axis\",\n \"node_value\": lambda x: ProtobufHelper.get_tensor_value(x),\n },\n \"Const\": {\n \"node_name\": lambda x: x,\n \"attr_name\": \"constant\",\n \"node_value\": lambda x: ProtobufHelper.get_tensor_value(x),\n },\n \"Pack\": {\n \"node_name\": lambda x: x + r\"/(\\d)\",\n \"regex\": True,\n \"attr_name\": \"constant\",\n \"node_value\": lambda x: ProtobufHelper.get_tensor_value(x),\n },\n }\n\n list_i_nodes = [\"dilations\", \"strides\", \"ksize\"]\n str_nodes = [\"padding\", \"data_format\"]\n\n for attr_name in node.attr.keys():\n if attr_name in list_i_nodes:\n attr_dict[attr_name] = [int(a) for a in node.attr[attr_name].list.i]\n continue\n\n if attr_name in str_nodes:\n attr_dict[attr_name] = node.attr[attr_name].s\n continue\n\n if attr_name == \"value\":\n shape = []\n for dim in node.attr[attr_name].tensor.tensor_shape.dim:\n shape.append(dim.size)\n attr_dict[\"tensor_shape\"] = list(map(int, shape))\n continue\n\n if attr_name == \"shape\":\n shape = []\n for dim in node.attr[attr_name].shape.dim:\n shape.append(dim.size)\n attr_dict[\"shape\"] = list(map(int, shape))\n continue\n\n if node.op in attr_as_node.keys():\n for target_node in self.graph.node:\n if \"regex\" in attr_as_node[node.op].keys():\n node_attr = re.findall(\n attr_as_node[node.op][\"node_name\"](node.name), target_node.name\n )\n if len(node_attr) > 0:\n logging.info(\"Find regex matching node %s\" % node.name)\n for attr_name in target_node.attr.keys():\n if (\n attr_name == \"value\"\n and \"weight\" not in node.name\n and \"BatchNorm\" not in node.name\n and \"kernel\" not in node.name\n ):\n node_attr_name = attr_as_node[node.op][\"attr_name\"]\n if node_attr_name not in attr_dict.keys():\n attr_dict[node_attr_name] = []\n attr_dict[node_attr_name].append(\n copy.deepcopy(\n attr_as_node[node.op][\"node_value\"](\n target_node.attr[attr_name].tensor\n )\n )\n )\n else:\n if target_node.name == attr_as_node[node.op][\"node_name\"](\n node.name\n ):\n for attr_name in target_node.attr.keys():\n if (\n attr_name == \"value\"\n and \"weight\" not in node.name\n and \"BatchNorm\" not in node.name\n and \"kernel\" not in node.name\n ):\n attr_dict[\n attr_as_node[node.op][\"attr_name\"]\n ] = copy.deepcopy(\n attr_as_node[node.op][\"node_value\"](\n target_node.attr[attr_name].tensor\n )\n )\n\n return attr_dict\n\n def parse_graph(self, model_graph):\n \"\"\"\n Parse a frozen protobuf file from tensorflow to graph IR\n\n Parameters\n ----------\n model_graph : ModelGraph\n The Graph IR holder.\n \"\"\"\n\n for node in self.graph.node:\n model_graph.node(str(node.name), list(map(str, node.input)))\n model_graph.set_node_attr(\n node.name,\n {\n \"name\": str(node.name),\n \"type\": str(node.op),\n \"output_shape\": [], # This will be filled later\n \"attr\": self.fetch_attr_to_dict(node),\n },\n )\n" }, { "alpha_fraction": 0.5572842955589294, "alphanum_fraction": 0.5643564462661743, "avg_line_length": 31.88372039794922, "blob_id": "9aaf1d0caa35be57126c10c7b20d7ae5e34b331b", "content_id": "616313eb0c7c396ba408e7f0e4c4ccbe5139641d", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1414, "license_type": "permissive", "max_line_length": 72, "num_lines": 43, "path": "/nn_meter/kerneldetection/utils/match_helper.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nclass MatchHelper:\n @classmethod\n def op_type_matcher(cls, node_1, node_2):\n if \"type\" in node_1 and \"type\" in node_2:\n if \"_tagged\" in node_1 or \"_tagged\" in node_2:\n return False\n\n if node_1[\"type\"] == \"dummy\" or node_2[\"type\"] == \"dummy\":\n return True\n return node_1[\"type\"] == node_2[\"type\"]\n else:\n return False\n\n @staticmethod\n def strip_useless_nodes(model_graph):\n stripped_nodes = [\"Const\", \"Identity\"]\n\n graph = model_graph.get_graph()\n removed_node = []\n for key, value in graph.items():\n if value[\"attr\"][\"type\"] in stripped_nodes:\n removed_node.append(key)\n\n for key in removed_node:\n del graph[key]\n\n model_graph.refresh()\n\n @staticmethod\n def tag_matched_nodes(model_graph, matched_subgraph):\n for matched_unit in matched_subgraph:\n for node_name in matched_unit.keys():\n model_graph.add_node_attr(node_name, \"_tagged\", \"\")\n\n @staticmethod\n def get_untagged_nodes(model_graph):\n untagged_node = []\n for node in model_graph.get_graph().keys():\n if \"_tagged\" not in model_graph.get_node_attr(node)[\"attr\"]:\n untagged_node.append(node)\n return untagged_node\n" }, { "alpha_fraction": 0.5236522555351257, "alphanum_fraction": 0.5344341993331909, "avg_line_length": 36.439998626708984, "blob_id": "4f48a535faf393ebfb45c1526359c86fbfa71bef", "content_id": "44c76ac68024654c29265bc0da63f169810e4b1a", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10295, "license_type": "permissive", "max_line_length": 105, "num_lines": 275, "path": "/nn_meter/dataset/gnn_dataloader.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport torch\nimport jsonlines\nimport os\nimport random\nfrom .bench_dataset import bench_dataset\nfrom nn_meter.nn_meter import get_user_data_folder\nfrom nn_meter.utils.utils import try_import_dgl\n\nRAW_DATA_URL = \"https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/datasets.zip\"\n__user_dataset_folder__ = os.path.join(get_user_data_folder(), 'dataset')\n\nhws = [\n \"cortexA76cpu_tflite21\",\n \"adreno640gpu_tflite21\",\n \"adreno630gpu_tflite21\",\n \"myriadvpu_openvino2019r2\",\n]\n\n\nclass GNNDataset(torch.utils.data.Dataset):\n def __init__(self, train=True, device=\"cortexA76cpu_tflite21\", split_ratio=0.8):\n \"\"\"\n Dataloader of the Latency Dataset\n\n Parameters\n ----------\n data_dir : string\n Path to save the downloaded dataset\n train: bool\n Get the train dataset or the test dataset\n device: string\n The Device type of the corresponding latency\n shuffle: bool\n If shuffle the dataset at the begining of an epoch\n batch_size: int\n Batch size.\n split_ratio: float\n The ratio to split the train dataset and the test dataset.\n \"\"\"\n err_str = \"Not supported device type\"\n assert device in hws, err_str\n self.device = device\n self.data_dir = __user_dataset_folder__\n self.train = train\n self.split_ratio = split_ratio\n self.adjs = {}\n self.attrs = {}\n self.nodename2id = {}\n self.id2nodename = {}\n self.op_types = set()\n self.opname2id = {}\n self.raw_data = {}\n self.name_list = []\n self.latencies = {}\n self.download_data()\n self.load_model_archs_and_latencies(self.data_dir)\n self.construct_attrs()\n self.name_list = list(\n filter(lambda x: x in self.latencies, self.name_list))\n\n def download_data(self):\n datasets = bench_dataset()\n\n def load_model_archs_and_latencies(self, data_dir):\n filelist = os.listdir(data_dir)\n for filename in filelist:\n if os.path.splitext(filename)[-1] != '.jsonl':\n continue\n self.load_model(os.path.join(data_dir, filename))\n\n def load_model(self, fpath):\n \"\"\"\n Load a concrete model type.\n \"\"\"\n # print('Loading models in ', fpath)\n assert os.path.exists(fpath), '{} does not exists'.format(fpath)\n\n with jsonlines.open(fpath) as reader:\n _names = []\n for obj in reader:\n if obj[self.device]:\n # print(obj['id'])\n _names.append(obj['id'])\n self.latencies[obj['id']] = float(obj[self.device])\n\n _names = sorted(_names)\n split_ratio = self.split_ratio if self.train else 1-self.split_ratio\n count = int(len(_names) * split_ratio)\n\n if self.train:\n _model_names = _names[:count]\n else:\n _model_names = _names[-1*count:]\n\n self.name_list.extend(_model_names)\n\n with jsonlines.open(fpath) as reader:\n for obj in reader:\n if obj['id'] in _model_names:\n model_name = obj['id']\n model_data = obj['graph']\n self.parse_model(model_name, model_data)\n self.raw_data[model_name] = model_data\n \n def construct_attrs(self):\n \"\"\"\n Construct the attributes matrix for each model.\n Attributes tensor:\n one-hot encoded type + input_channel , output_channel,\n input_h, input_w + kernel_size + stride\n \"\"\"\n op_types_list = list(sorted(self.op_types))\n for i, _op in enumerate(op_types_list):\n self.opname2id[_op] = i\n n_op_type = len(self.op_types)\n attr_len = n_op_type + 6\n for model_name in self.raw_data:\n n_node = len(self.raw_data[model_name])\n # print(\"Model: \", model_name, \" Number of Nodes: \", n_node)\n t_attr = torch.zeros(n_node, attr_len)\n for node in self.raw_data[model_name]:\n node_attr = self.raw_data[model_name][node]\n nid = self.nodename2id[model_name][node]\n op_type = node_attr['attr']['type']\n op_id = self.opname2id[op_type]\n t_attr[nid][op_id] = 1\n other_attrs = self.parse_node(model_name, node)\n t_attr[nid][-6:] = other_attrs\n self.attrs[model_name] = t_attr\n\n def parse_node(self, model_name, node_name):\n \"\"\"\n Parse the attributes of specified node\n Get the input_c, output_c, input_h, input_w, kernel_size, stride\n of this node. Note: filled with 0 by default if this doesn't have\n coressponding attribute.\n \"\"\"\n node_data = self.raw_data[model_name][node_name]\n t_attr = torch.zeros(6)\n op_type = node_data['attr']['type']\n if op_type =='Conv2D':\n weight_shape = node_data['attr']['attr']['weight_shape']\n kernel_size, _, in_c, out_c = weight_shape\n stride, _= node_data['attr']['attr']['strides']\n _, h, w, _ = node_data['attr']['output_shape'][0]\n t_attr = torch.tensor([in_c, out_c, h, w, kernel_size, stride])\n elif op_type == 'DepthwiseConv2dNative':\n weight_shape = node_data['attr']['attr']['weight_shape']\n kernel_size, _, in_c, out_c = weight_shape\n stride, _= node_data['attr']['attr']['strides']\n _, h, w, _ = node_data['attr']['output_shape'][0]\n t_attr = torch.tensor([in_c, out_c, h, w, kernel_size, stride])\n elif op_type == 'MatMul':\n in_node = node_data['inbounds'][0]\n in_shape = self.raw_data[model_name][in_node]['attr']['output_shape'][0]\n in_c = in_shape[-1]\n out_c = node_data['attr']['output_shape'][0][-1]\n t_attr[0] = in_c\n t_attr[1] = out_c\n elif len(node_data['inbounds']):\n in_node = node_data['inbounds'][0]\n h, w, in_c, out_c = 0, 0, 0, 0\n in_shape = self.raw_data[model_name][in_node]['attr']['output_shape'][0]\n in_c = in_shape[-1]\n if 'ConCat' in op_type:\n for i in range(1, len(node_data['in_bounds'])):\n in_shape = self.raw_data[node_data['in_bounds']\n [i]]['attr']['output_shape'][0]\n in_c += in_shape[-1]\n if len(node_data['attr']['output_shape']):\n out_shape = node_data['attr']['output_shape'][0]\n # N, H, W, C\n out_c = out_shape[-1]\n if len(out_shape) == 4:\n h, w = out_shape[1], out_shape[2]\n t_attr[-6:-2] = torch.tensor([in_c, out_c, h, w])\n\n return t_attr\n\n def parse_model(self, model_name, model_data):\n \"\"\"\n Parse the model data and build the adjacent matrixes\n \"\"\"\n n_nodes = len(model_data)\n m_adj = torch.zeros(n_nodes, n_nodes, dtype=torch.int32)\n id2name = {}\n name2id = {}\n tmp_node_id = 0\n # build the mapping between the node name and node id\n\n for node_name in model_data.keys():\n id2name[tmp_node_id] = node_name\n name2id[node_name] = tmp_node_id\n op_type = model_data[node_name]['attr']['type']\n self.op_types.add(op_type)\n tmp_node_id += 1\n\n for node_name in model_data:\n cur_id = name2id[node_name]\n for node in model_data[node_name]['inbounds']:\n if node not in name2id:\n # weight node\n continue\n in_id = name2id[node]\n m_adj[in_id][cur_id] = 1\n for node in model_data[node_name]['outbounds']:\n if node not in name2id:\n # weight node\n continue\n out_id = name2id[node]\n m_adj[cur_id][out_id] = 1\n \n for idx in range(n_nodes):\n m_adj[idx][idx] = 1\n\n self.adjs[model_name] = m_adj\n self.nodename2id[model_name] = name2id\n self.id2nodename[model_name] = id2name\n\n def __getitem__(self, index):\n model_name = self.name_list[index]\n return (self.adjs[model_name], self.attrs[model_name]), self.latencies[model_name], self.op_types\n\n def __len__(self):\n return len(self.name_list)\n\n\nclass GNNDataloader(torch.utils.data.DataLoader):\n def __init__(self, dataset, shuffle=False, batchsize=1):\n self.dataset = dataset\n self.op_num = len(dataset.op_types)\n self.shuffle = shuffle\n self.batchsize = batchsize\n self.length = len(self.dataset)\n self.indexes = list(range(self.length))\n self.pos = 0\n self.graphs = {}\n self.latencies = {}\n self.construct_graphs()\n\n def construct_graphs(self):\n dgl = try_import_dgl()\n for gid in range(self.length):\n (adj, attrs), latency, op_types = self.dataset[gid]\n u, v = torch.nonzero(adj, as_tuple=True)\n # import pdb; pdb.set_trace()\n graph = dgl.graph((u, v))\n MAX_NORM = torch.tensor([1]*len(op_types) + [6963, 6963, 224, 224, 11, 4])\n attrs = attrs / MAX_NORM\n graph.ndata['h'] = attrs\n self.graphs[gid] = graph\n self.latencies[gid] = latency\n\n def __iter__(self):\n if self.shuffle:\n random.shuffle(self.indexes)\n self.pos = 0\n return self\n\n def __len__(self):\n return self.length\n\n def __next__(self):\n dgl = try_import_dgl()\n start = self.pos\n end = min(start + self.batchsize, self.length)\n self.pos = end\n if end - start <= 0:\n raise StopIteration\n batch_indexes = self.indexes[start:end]\n batch_graphs = [self.graphs[i] for i in batch_indexes]\n batch_latencies = [self.latencies[i] for i in batch_indexes]\n return torch.tensor(batch_latencies), dgl.batch(batch_graphs)" }, { "alpha_fraction": 0.6473406553268433, "alphanum_fraction": 0.6473406553268433, "avg_line_length": 31.10769271850586, "blob_id": "861963eb9d38ecd87c612ea48843c00ad349dfbd", "content_id": "add48c2b625f80a3fe96a1f8f81d7be69ba00c89", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2089, "license_type": "permissive", "max_line_length": 92, "num_lines": 65, "path": "/nn_meter/prediction/load_predictors.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport pickle\nimport os\nfrom glob import glob\nfrom zipfile import ZipFile\nfrom tqdm import tqdm\nimport requests\nimport logging\nfrom nn_meter.utils.utils import download_from_url\n\n\ndef loading_to_local(pred_info, dir=\"data/predictorzoo\"):\n \"\"\"\n @params:\n\n configs: the default predictor.yaml that describes the supported hardware+backend\n hardware: the targeting hardware_inferenceframework name\n dir: the local directory to store the kernel predictors and fusion rules\n\n \"\"\"\n os.makedirs(dir, exist_ok=True)\n hardware = pred_info['name']\n ppath = os.path.join(dir, hardware)\n\n isdownloaded = check_predictors(ppath, pred_info[\"kernel_predictors\"])\n if not isdownloaded:\n logging.keyinfo(f'Download from {pred_info[\"download\"]} ...')\n download_from_url(pred_info[\"download\"], dir)\n\n # load predictors\n predictors = {}\n ps = glob(os.path.join(ppath, \"**.pkl\"))\n for p in ps:\n pname = os.path.basename(p).replace(\".pkl\", \"\")\n with open(p, \"rb\") as f:\n logging.info(\"load predictor %s\" % p)\n model = pickle.load(f)\n predictors[pname] = model\n fusionrule = os.path.join(ppath, \"fusion_rules.json\")\n # logging.info(fusionrule)\n if not os.path.isfile(fusionrule):\n raise ValueError(\n \"check your fusion rule path, file \" + fusionrule + \" does not exist!\"\n )\n return predictors, fusionrule\n\n\ndef check_predictors(ppath, kernel_predictors):\n \"\"\"\n @params:\n\n model: a pytorch/onnx/tensorflow model object or a str containing path to the model file\n \"\"\"\n logging.info(\"checking local kernel predictors at \" + ppath)\n if os.path.isdir(ppath):\n filenames = glob(os.path.join(ppath, \"**.pkl\"))\n # check if all the pkl files are included\n for kp in kernel_predictors:\n fullpath = os.path.join(ppath, kp + \".pkl\")\n if fullpath not in filenames:\n return False\n return True\n else:\n return False\n" }, { "alpha_fraction": 0.529190182685852, "alphanum_fraction": 0.5338982939720154, "avg_line_length": 21.595745086669922, "blob_id": "d419ac609a66926d489203c739e866253b05d8c6", "content_id": "3a47cf7aec0412b7c4228f2376b6144941d7b7b2", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "permissive", "max_line_length": 68, "num_lines": 47, "path": "/nn_meter/kerneldetection/utils/constants.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nDUMMY_TYPES = [\n \"Const\",\n \"Identity\",\n \"Placeholder\",\n]\n\n# TODO: Refactor opset map. Should be moved to corresponding module.\nOP_ALIAS = {\n # Tensorflow\n \"Relu6\": \"relu\",\n \"Relu\": \"relu\",\n \"Add\": \"add\",\n \"Biasadd\": \"add\",\n \"Conv2D\": \"conv\",\n \"Reshape\": \"reshape\",\n \"FusedBatchNorm\": \"bn\",\n \"FusedBatchNormV3\": \"bn\",\n \"MatMul\": \"fc\",\n \"MaxPool\": \"maxpool\",\n \"AvgPool\": \"avgpool\",\n \"Mean\": \"gap\",\n \"Mul\": \"mul\",\n \"DepthwiseConv2dNative\": \"dwconv\",\n \"ConcatV2\": \"concat\",\n \"Split\": \"split\",\n # ONNX\n \"Conv\": \"conv\",\n \"BatchNormalization\": \"bn\",\n \"Slice\": \"split\",\n \"Concat\": \"concat\",\n \"AveragePool\": \"avgpool\",\n \"Relu\": \"relu\",\n \"Add\": \"add\",\n \"Gemm\": \"fc\",\n \"GlobalAveragePool\": \"gap\",\n \"Clip\": \"relu\",\n \"Mul\": \"mul\",\n \"Div\": \"div\",\n \"HardSigmoid\": \"hardsigmoid\",\n \"Flatten\": \"reshape\",\n \"Transpose\": \"transpose\",\n \"ReduceMean\": \"gap\",\n \"Split\": \"split\",\n \"Pad\": \"pad\",\n}\n" }, { "alpha_fraction": 0.7660070061683655, "alphanum_fraction": 0.7823050022125244, "avg_line_length": 70.625, "blob_id": "c905634971d565cb95a0e196b85ad4eb096d02fd", "content_id": "36a01af6d1c34e99a78393013fad4b2dc78a44ac", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1718, "license_type": "permissive", "max_line_length": 483, "num_lines": 24, "path": "/docs/overview.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Overview\nNote: This is an alpha (preview) version which is still under refining.\n\nnn-Meter is a novel and efficient system to accurately predict the inference latency of DNN models on diverse edge devices.\n\n## Key Techniques\nnn-Meter contains two key techniques: (i) kernel detection to automatically detect the execution unit of model inference via a set of well-designed test cases; (ii) adaptive sampling to efficiently sample the most beneficial configurations from a large space to build accurate kernel-level latency predictors.\n\nnn-Meter currently supports multiple input model formats, please refer [input_models](input_models.md) for more details.\n\nAs discussed in nn-Meter paper, the approach is general to any DNN models on diverse edge devices. However, the current implementation considers the major CNN architectures on four types of hardware platforms. The following table shows the prediction performance of tested CNN model families on mobile CPU (i.e., *cortexA76cpu_tflite21*), mobile GPU 640 (i.e., *adreno640gpu_tflite21*), mobile GPU 630 (i.e., *adreno630gpu_tflite21*) and Intel VPU (i.e., *myriadvpu_openvino2019r2*).\n\n<img src=\"imgs/predict_performance.png\" alt=\"drawing\" width=\"800\"/>\n\nIf your DNN model structures are not included in above models, please read doc [ops](ops.md) and [kernels](kernel.md) to decide whether to build new latency predictor for them.\n\nIf you have a new hardware to predict DNN latency, a re-run of nn-Meter is required to build latency predictors for the hardware. We will release the building tools very soon.\n\n## Learn More\n- [Get started](quick_start.md)\n\n- [How to use nn-Meter](usage.md)\n\n- [nn-meter in hardware-aware NAS](hardware-aware-model-design.md)" }, { "alpha_fraction": 0.6184210777282715, "alphanum_fraction": 0.6348684430122375, "avg_line_length": 26.636363983154297, "blob_id": "dd6d186f2f215047b41edda814f0df9ac9c23cd2", "content_id": "9abe04527a9966d9a94e0b669cf8460302fd97cd", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "permissive", "max_line_length": 56, "num_lines": 11, "path": "/nn_meter/ir_converters/onnx_converter/utils.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n\ndef get_tensor_shape(tensor):\n shape = []\n for dim in tensor.type.tensor_type.shape.dim:\n shape.append(dim.dim_value)\n if len(shape) == 4:\n shape = [shape[0], shape[2], shape[3], shape[1]]\n return shape\n" }, { "alpha_fraction": 0.7580305933952332, "alphanum_fraction": 0.7891023755073547, "avg_line_length": 178.05404663085938, "blob_id": "0b62d3982899f9f1820e990c8f7ca023c277faf9", "content_id": "e8586756eae9a3e7f5de2973854d6794b958cf9e", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6662, "license_type": "permissive", "max_line_length": 918, "num_lines": 37, "path": "/docs/hardware-aware-model-design.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Hardware-aware DNN Model Design\r\n\r\nIn many DNN model deployment scenarios, there are strict inference efficiency constraints as well as the model accuracy. For example, the **inference latency** and **energy consumption** are the most frequently used criteria of efficiencies to determine whether a DNN model could be deployed on a mobile phone or not. Therefore, DNN model designers have to consider the model efficiency. A typical methodology is to train a big model to meet the accuracy requirements first, and then apply model compression algorithms to get a light-weight model with similar accuracy but much smaller size. Due to many reasons, they use the number of parameters and FLOPs in the compression process.\r\n\r\nHowever, as pointed out in our work [[1]](https://openaccess.thecvf.com/content_CVPRW_2020/papers/w40/Zhang_Fast_Hardware-Aware_Neural_Architecture_Search_CVPRW_2020_paper.pdf) and many others, ***neither number of parameters nor number of FLOPs is a good metric of the real inference efficiency (e.g., latency or energy consumption)***. Operators with similar FLOPs may have very different inference latency on different hardware platforms (e.g., CPU, GPU, and ASIC) (shown in work [[1]](https://openaccess.thecvf.com/content_CVPRW_2020/papers/w40/Zhang_Fast_Hardware-Aware_Neural_Architecture_Search_CVPRW_2020_paper.pdf) and [[3]](https://proceedings.mlsys.org/paper/2021/file/02522a2b2726fb0a03bb19f2d8d9524d-Paper.pdf)). This makes the effort of designing efficient DNN models for a target hardware bit of games of opening blind boxes. Recently, many hardware-aware NAS works are proposed to solve this challenge.\r\n\r\nCompared with the conventional NAS algorithms, some recent works (i.e. hardware-aware NAS, aka HW-NAS) integrated hardware-awareness into the search loop and achieves a balanced trade-off between accuracy and hardware efficiencies [[4]](http://arxiv.org/abs/2101.09336).\r\n\r\nNext, we introduce our hardware-aware NAS framework[[1]](https://openaccess.thecvf.com/content_CVPRW_2020/papers/w40/Zhang_Fast_Hardware-Aware_Neural_Architecture_Search_CVPRW_2020_paper.pdf), which combines the nn-Meter, to search high-accuracy DNN models within the latency constraints for target edge devices.\r\n\r\n## Hardware-aware Neural Architecture Search\r\n\r\n<img src=\"imgs/hw-nas.png\" alt=\"drawing\" width=\"800\"/>\r\n\r\n**Hardware-aware Search Space Generation.** As formulated in many works, the search space is one of the three key aspects of a NAS process (the other two are the search strategy and the evaluation methodology) and matters a lot to the final results.\r\n\r\nOur HW-NAS framework firstly automatically selects the hardware-friendly operators (or blocks) by considering both representation capacity and hardware efficiency. The selected operators could establish a ***hardware-aware search space*** for most of existing NAS algorithms.\r\n\r\n**Latency Prediction in search process by nn-Meter.** Different with other simple predictors (e.g., look-up table for operators/blocks, linear regression models), [nn-Meter](overview.md) conducts kernel-level prediction, which captures the complex model graph optimizations on edge devices. nn-Meter is the first accurate latency prediction tool for DNNs on edge devices.\r\n\r\nBesides the search space specialization, our HW-NAS framework also allows combining nn-Meter with existing NAS algorithms in the optimization objectives and constraints. As described in [[4]](http://arxiv.org/abs/2101.09336), the HW-NAS algorithms often consider hardware efficiency metrics as the constraints of existing NAS formulation or part of the scalarized loss functions (e.g., the loss is weighted sum of both cross entropy loss and hardware-aware penalty). Since the NAS process may sample up to millions of candidate model architectures, the obtaining of hardware metrics must be accurate and efficient.\r\n\r\nnn-Meter is now integrated with [NNI](https://github.com/microsoft/nni), the AutoML framework also published by Microsoft, and could be combined with existing NAS algorithms seamlessly. [This doc](https://nni.readthedocs.io/en/stable/NAS/multi_trial_nas.html) show how to construct a latency constraint filter in [random search algorithm](https://arxiv.org/abs/1902.07638) on [SPOS NAS](https://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123610528.pdf) search space. Users could use this filter in multiple phases of the NAS process, e.g., the architecture searching phase and the super-net training phase.\r\n\r\n***Note that current nn-Meter project is limited to the latency prediction. For the other hardware metrics, e.g., energy consumption is another important metric in edge computing. Collaborations and contributions together with nn-Meter are highly welcomed!***\r\n\r\n## Other hardware-aware techniques\r\n\r\nBesides light weighted NAS, which search for an efficient architecture directly, there are also other techniques to achieve light weight DNN models, such as model compression and knowledge distillation (KD). Both methods tries to get a smaller but similar-performed models from a pre-trained big model. The difference is that model compression removes some of the components in the origin model, while knowledge distillation constructs a new student model and lets it learn the behavior of the origin model. Hardware awareness could also be combined with these methods.\r\nFor example, nn-Meter could help users to construct suitable student architectures for the target hardware platform in the KD task.\r\n\r\n## References\r\n\r\n1. Li Lyna Zhang, Yuqing Yang, Yuhang Jiang, Wenwu Zhu, Yunxin Liu: [&#34;Fast hardware-aware neural architecture search.&#34;](https://openaccess.thecvf.com/content_CVPRW_2020/papers/w40/Zhang_Fast_Hardware-Aware_Neural_Architecture_Search_CVPRW_2020_paper.pdf) Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops. 2020.\r\n2. Li Lyna Zhang, Shihao Han, Jianyu Wei, Ningxin Zheng, Ting Cao, Yuqing Yang, Yunxin Liu: [&#34;nn-Meter: Towards Accurate Latency Prediction of Deep-Learning Model Inference on Diverse Edge Devices.&#34;](https://dl.acm.org/doi/10.1145/3458864.3467882) Proceedings of the 19th ACM International Conference on Mobile Systems, Applications, and Services (MobiSys 2021)\r\n3. Xiaohu Tang, Shihao Han, Li Lyna Zhang, Ting Cao, Yunxin Liu: [&#34;To Bridge Neural Network Design and Real-World Performance: A Behaviour Study for Neural Networks&#34;](https://proceedings.mlsys.org/paper/2021/file/02522a2b2726fb0a03bb19f2d8d9524d-Paper.pdf) Proceedings of the 4th MLSys Conference (MLSys 2021)\r\n4. Benmeziane, H., Maghraoui, K. el, Ouarnoughi, H., Niar, S., Wistuba, M., & Wang, N. (2021).[&#34; A Comprehensive Survey on Hardware-Aware Neural Architecture Search.&#34;](http://arxiv.org/abs/2101.09336)\r\n" }, { "alpha_fraction": 0.425498902797699, "alphanum_fraction": 0.437250554561615, "avg_line_length": 26.668710708618164, "blob_id": "5d7ba4b3ba7cd988a2a3bfb1d1a5a7ac68f70af2", "content_id": "105809e04fa976d054fbc32502fd6111609e0977", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4510, "license_type": "permissive", "max_line_length": 84, "num_lines": 163, "path": "/nn_meter/ir_converters/frozenpb_converter/protobuf_helper.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport logging\n\nlogging = logging.getLogger(__name__)\n\n\nclass ProtobufHelper:\n @staticmethod\n def get_w(x):\n \"\"\"\n Get width from a list.\n\n Parameters\n ----------\n x : list\n A 2-D or 4-D list\n represent the shape of a tensor\n \"\"\"\n l = len(x)\n if l == 4:\n return x[1]\n if l == 2:\n return x[0]\n return None\n\n @staticmethod\n def get_h(x):\n \"\"\"\n Get height from a list.\n\n Parameters\n ----------\n x : list\n A 2-D or 4-D list\n represent the shape of a tensor\n \"\"\"\n l = len(x)\n if l == 4:\n return x[2]\n if l == 2:\n return x[1]\n return None\n\n @staticmethod\n def find_weights_root(graph, node):\n \"\"\"\n Find the node which store the weight of the tensor.\n\n Parameters\n ----------\n graph : dict\n The graph IR in dict form.\n node : dict\n A single node in graph IR.\n \"\"\"\n NODE_WEIGHT_LUT = {\n \"Conv2D\": [\n lambda x: x.replace(\"/Conv2D\", \"/weight\"),\n lambda x: x.replace(\"/Conv2D\", \"/kernel\"),\n ],\n \"DepthwiseConv2dNative\": [lambda x: x.replace(\"/depthwise\", \"/weight\")],\n \"BiasAdd\": [\n lambda x: x.replace(\"/BiasAdd\", \"/bias\"),\n ],\n \"FusedBatchNorm\": [\n lambda x: x.replace(\"/FusedBatchNormV3\", \"/gamma\"),\n lambda x: x.replace(\"/FusedBatchNormV3\", \"/beta\"),\n lambda x: x.replace(\"/FusedBatchNormV3\", \"/moving_mean\"),\n lambda x: x.replace(\"/FusedBatchNormV3\", \"/moving_variance\"),\n ],\n \"MatMul\": [\n lambda x: x.replace(\"/MatMul\", \"/weight\"),\n ],\n }\n\n weight_name = []\n if node[\"attr\"][\"type\"] in NODE_WEIGHT_LUT.keys():\n for lut_lamba in NODE_WEIGHT_LUT[node[\"attr\"][\"type\"]]:\n weight_op = lut_lamba(node[\"attr\"][\"name\"])\n if (\n weight_op in graph.keys()\n and graph[weight_op][\"attr\"][\"type\"] != \"Identity\"\n ):\n logging.info(\n \"Find node %s with its weight op %s.\"\n % (node[\"attr\"][\"name\"], weight_op)\n )\n weight_name.append(weight_op)\n\n return weight_name\n\n @staticmethod\n def get_graph_seq(graph, graph_head):\n \"\"\"\n Run a topological sort of the graph,\n return the sorted sequence.\n\n Parameters\n ----------\n graph : dict\n The graph IR in dict form.\n graph_head : str\n Start position of the sort.\n \"\"\"\n seen = set()\n stack = []\n order = []\n q = [graph_head[0]]\n for head in graph_head:\n q = [head]\n while q:\n v = q.pop()\n if v not in seen:\n seen.add(v)\n q.extend(graph[v][\"outbounds\"])\n while stack and v not in graph[stack[-1]][\"outbounds\"]:\n order.append(stack.pop())\n stack.append(v)\n return stack + order[::-1]\n\n @staticmethod\n def pkg42dec(x):\n \"\"\"\n Convert protobuf 4-packed oct format to number.\n\n Parameters\n ----------\n x : list\n The 4-packed oct list.\n \"\"\"\n total_byte = len(x) // 4\n assert total_byte * 4 == len(x)\n\n num = []\n for idx in range(total_byte):\n num.append(0)\n for i in range(4):\n num[-1] += x[idx * 4 + i] << (i * 8)\n if num[-1] == 4294967295:\n num[-1] = -1\n\n return num\n\n @staticmethod\n def get_tensor_value(x):\n \"\"\"\n Get the value from a const op.\n\n Parameters\n ----------\n x : Protobuf.node\n The const node.\n \"\"\"\n DTYPE_ENUM = {\n 0: lambda x: list(map(float, x.float_val)),\n 1: lambda x: list(map(float, x.float_val)),\n 3: lambda x: list(map(int, x.int_val)),\n }\n data = DTYPE_ENUM[x.dtype](x)\n if len(data) == 0:\n data = ProtobufHelper.pkg42dec(x.tensor_content)\n return data\n" }, { "alpha_fraction": 0.508308470249176, "alphanum_fraction": 0.5219429135322571, "avg_line_length": 33.77037048339844, "blob_id": "f916f034204a76f2314246edc53b3d9f9826ece5", "content_id": "1c2a91dfa93ce153b401e452f8206aef11572492", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4694, "license_type": "permissive", "max_line_length": 112, "num_lines": 135, "path": "/nn_meter/prediction/predictors/extract_feature.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\nimport logging\n\n\ndef get_flop(input_channel, output_channel, k, H, W, stride):\n paras = output_channel * (k * k * input_channel + 1)\n flops = 2 * H / stride * W / stride * paras\n return flops, paras\n\n\ndef get_conv_mem(input_channel, output_channel, k, H, W, stride):\n paras = output_channel * (k * k * input_channel + 1)\n mem = paras + output_channel * H / stride * W / stride + input_channel * H * W\n return mem\n\n\ndef get_depthwise_flop(input_channel, output_channel, k, H, W, stride):\n paras = output_channel * (k * k + 1)\n flops = 2 * H / stride * W / stride * paras\n return flops, paras\n\n\ndef get_flops_params(blocktype, hw, cin, cout, kernelsize, stride):\n if \"dwconv\" in blocktype:\n return get_depthwise_flop(cin, cout, kernelsize, hw, hw, stride)\n elif \"conv\" in blocktype:\n return get_flop(cin, cout, kernelsize, hw, hw, stride)\n elif \"fc\" in blocktype:\n flop = (2 * cin + 1) * cout\n return flop, flop\n\n\ndef get_predict_features(config):\n \"\"\"\n get prediction features\n \"\"\"\n mdicts = {}\n layer = 0\n for item in config:\n logging.info(item)\n for item in config:\n op = item[\"op\"]\n if \"conv\" in op or \"maxpool\" in op or \"avgpool\" in op:\n cout = item[\"cout\"]\n cin = item[\"cin\"]\n ks = item[\"ks\"][1]\n s = item[\"strides\"][1] if \"strides\" in item else 1\n inputh = item[\"inputh\"]\n if op in [\"channelshuffle\", \"split\"]:\n [b, inputh, inputw, cin] = item[\"input_tensors\"][0]\n if \"conv\" in op:\n flops, params = get_flops_params(op, inputh, cin, cout, ks, s)\n features = [inputh, cin, cout, ks, s, flops / 2e6, params / 1e6]\n elif \"fc\" in op or \"fc-relu\" in op:\n cout = item[\"cout\"]\n cin = item[\"cin\"]\n flop = (2 * cin + 1) * cout\n features = [cin, cout, flop / 2e6, flop / 1e6]\n elif \"pool\" in op and \"global\" not in op:\n features = [inputh, cin, cout, ks, s]\n elif \"global-pool\" in op or \"global-avgpool\" in op or \"gap\" in op:\n inputh = 1\n cin = item[\"cin\"]\n features = [inputh, cin]\n elif \"channelshuffle\" in op:\n features = [inputh, cin]\n elif \"split\" in op:\n features = [inputh, cin]\n elif \"se\" in op or \"SE\" in op:\n inputh = item[\"input_tensors\"][-1][-2]\n cin = item[\"input_tensors\"][-1][-1]\n features = [inputh, cin]\n elif \"concat\" in op: # maximum 4 branches\n itensors = item[\"input_tensors\"]\n inputh = itensors[0][1]\n features = [inputh, len(itensors)]\n for it in itensors:\n co = it[-1]\n features.append(co)\n if len(features) < 6:\n features = features + [0] * (6 - len(features))\n elif len(features) > 6:\n nf = features[0:6]\n features = nf\n features[1] = 6\n elif op in [\"hswish\"]:\n if \"inputh\" in item:\n inputh = item[\"inputh\"]\n else:\n inputh = item[\"input_tensors\"][0][1]\n cin = item[\"cin\"]\n features = [inputh, cin]\n elif op in [\"bn\", \"relu\", \"bn-relu\"]:\n itensors = item[\"input_tensors\"]\n if len(itensors[0]) == 4:\n inputh = itensors[0][1]\n cin = itensors[0][3]\n else:\n inputh = itensors[0][0]\n cin = itensors[0][1]\n features = [inputh, cin]\n\n elif op in [\"add-relu\", \"add\"]:\n itensors = item[\"input_tensors\"]\n inputh = itensors[0][1]\n cin1 = itensors[0][3]\n cin2 = itensors[1][3]\n features = [inputh, cin1, cin2]\n else: # indicates that there is no matching predictor for this op\n # logging.warning(f'There is no matching predictor for op {op}.')\n continue\n mdicts[layer] = {}\n mdicts[layer][op] = features\n layer += 1\n return mdicts\n\n\ndef read_model_latency(latency_file):\n \"\"\"\n read model latency csv files. It can provide the benchmarked latency, and compare with the predicted latency\n \"\"\"\n f = open(latency_file, \"r\")\n dicts = {}\n while True:\n line = f.readline()\n if not line:\n break\n content = line.strip().split(\",\")\n model = content[1]\n latency = float(content[2])\n dicts[model] = latency\n return dicts\n" }, { "alpha_fraction": 0.6252163648605347, "alphanum_fraction": 0.627236008644104, "avg_line_length": 110.80644989013672, "blob_id": "5396b397dcf7a14651ddae06449ecb5adf0a36ca", "content_id": "deaaf68902496582481bf28a5bbed48799f83dbf", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3466, "license_type": "permissive", "max_line_length": 401, "num_lines": 31, "path": "/docs/kernel.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Kernel Introduction\n\nAs introduced in Mobisys paper, we define a kernel is the maximum fusion unit in a model. The kernel is the basic scheduling unit in DNN inference on edge devices, it naturally captures the most important graph optimizations, i.e., the operator fusion.\n\nThe kernel detection algorithm takes: (i) the fusion rules on each hardware platform; and (ii) nn-meter ir graph as the inputs.\n\n## Detected fusion rules\n\nFor every two operators, nn-Meter detects whether there is the operation fusion happened on the target hardware. To do so, nn-Meter designs a set of test cases and compare the latency difference (The code of operation fusion detection will be open-sourced in next release). The following is an example of conv and relu operators in the TFLite2.1 on the mobile CPU.\n\n<img src=\"imgs/fusion_rule.png\" alt=\"drawing\" width=\"300\"/>\n\n{\"obey\":\"true\"} indicates conv and relu can be fused into one fused operator. We record all the fusion rules in a json file, you can find it in your local path: `~/.nn_meter/predictors/hardware_name/fusion_rules.json` after you download the targeting hardware predictors.\n\n## Detected kernels\n\nFrom the 26k benchmarked model dataset, we get different kernel units as the followings:\n\n| hardware | kernels |\n| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| CPU | conv-relu,fc,maxpool,global-avgpool,fc-relu,concat,avgpool,conv-bn-relu,bn-relu,conv,SE-relu,conv-bn,dwconv-bn,dwconv-bn-relu,add,hswish,SE,conv-bn-bn-relu,relu,add-relu,channelshuffle,split |\n| GPUs | conv-relu,fc,maxpool,global-avgpool,fc-relu,concat,avgpool,conv-bn-relu,bn-relu,conv,SE-relu,conv-bn,dwconv-bn,conv-bn-add,dwconv-bn-relu,hswish,SE,conv-bn-bn-relu,conv-bn-add-add-bn-relu,add-relu,relu,conv-bn-add-relu,conv-bn-add-bn-relu,add-add,conv-bn-add-add,add |\n| VPU | conv-relu,relu,fc,maxpool,global-avgpool,concat,avgpool,conv-bn-relu,bn,conv,SE-relu,conv-bn,dwconv-bn,dwconv-bn-relu,add,hswish,conv-bn-hswish,SE,conv-bn-bn-relu,add-relu,channelshuffle,split |\n\n## Kernel latency predictors\n\nWe apply the adaptive data sampling algorithm to sample data for building kernel latency predictors (The adaptive data sampling code will be released as soon as possible). The regression model is Random Forest.\n\nNote: since the latency difference of conv-related kernels are negligible, we only build latency predictor for conv-bn-relu kernel to reduce the sampling and engineering efforts. And we use this kernel latency predictor to predict other conv-related kernels. For the same reason, we build latency predictor for dwconv-bn-relu kernel. Our experiment results demonstrate the effectiveness of this trick.\n\nFor each kernel latency predictor, we store them in .pkl format. You can find them in your local directory `~/.nn_meter/config/predictors.yaml` after downloading it.\n" }, { "alpha_fraction": 0.7087198495864868, "alphanum_fraction": 0.7087198495864868, "avg_line_length": 23.5, "blob_id": "865b65f6e137c52b12ff2c5b8ed7d915fcf25654", "content_id": "ac9c8896e7ff5f3473f8a720fe38b7909f94d389", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 539, "license_type": "permissive", "max_line_length": 38, "num_lines": 22, "path": "/nn_meter/ir_converters/onnx_converter/constants.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nCONV_TYPE = \"Conv\"\nBN_TYPE = \"BatchNormalization\"\nSLICE_TYPE = \"Slice\"\nCONCAT_TYPE = \"Concat\"\nMAXPOOL_TYPE = \"MaxPool\"\nAVGPOOL_TYPE = \"AveragePool\"\nRELU_TYPE = \"Relu\"\nADD_TYPE = \"Add\"\nFC_TYPE = \"Gemm\"\nRESHAPE_TYPE = \"Reshape\"\nGAP_TYPE = \"GlobalAveragePool\"\nCLIP_TYPE = \"Clip\"\nMUL_TYPE = \"Mul\"\nDIV_TYPE = \"Div\"\nHARDSIGMOID_TYPE = \"HardSigmoid\"\nFLATTEN_TYPE = \"Flatten\"\nTRANSPOSE_TYPE = \"Transpose\"\nREDUCEMEAN_TYPE = \"ReduceMean\"\nSPLIT_TYPE = \"Split\"\nPAD_TYPE = \"Pad\"\n" }, { "alpha_fraction": 0.583458662033081, "alphanum_fraction": 0.5887218117713928, "avg_line_length": 35.45205307006836, "blob_id": "45c6349babc53629d9a05044afc51a540e0f4e34", "content_id": "9c2f594b8244d161e328176a2487946ec99531e9", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2660, "license_type": "permissive", "max_line_length": 82, "num_lines": 73, "path": "/nn_meter/ir_converters/frozenpb_converter/shape_fetcher.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom nn_meter.utils.utils import try_import_tensorflow\nimport numpy as np\nfrom typing import List\n\n\nclass ShapeFetcher:\n def __init__(self, input_graph):\n \"\"\"\n Dynamically inference the node shapes.\n\n Parameters\n ----------\n input_graph : graph_def\n The tensorflow input graph_def file.\n \"\"\"\n self.tf = try_import_tensorflow()\n self.tf.compat.v1.disable_eager_execution()\n\n graph = self.tf.Graph()\n\n with graph.as_default():\n self.tf.import_graph_def(graph_def=input_graph, name=\"\")\n \n self.ops = graph.get_operations()\n placeholders = list(filter(lambda op: op.type == \"Placeholder\", self.ops))\n assert len(placeholders) == 1\n self.graph_input_tensor = placeholders[0].outputs[0]\n graph_input_tensor_shape = self.graph_input_tensor.get_shape().as_list()\n assert graph_input_tensor_shape[1] == graph_input_tensor_shape[2]\n assert graph_input_tensor_shape[3] == 3\n self.imsize = graph_input_tensor_shape[1]\n self.graph = graph\n\n def get_shape_by_name(self, op_name):\n \"\"\"\n Get the node output shape by its name\n\n Parameters\n ----------\n op_name : str\n The name of the target node.\n \"\"\"\n input_tensors_to_fetch = []\n output_tensors_to_fetch = []\n for op in filter(lambda op: op.name == op_name, self.ops):\n input_tensors_to_fetch.extend(op.inputs)\n output_tensors_to_fetch.extend(op.outputs)\n \n input_shape_tensors = []\n for tensor in input_tensors_to_fetch:\n input_shape_tensors.append(self.tf.compat.v1.shape(tensor))\n \n output_shape_tensors = []\n for tensor in output_tensors_to_fetch:\n output_shape_tensors.append(self.tf.compat.v1.shape(tensor))\n\n \n intput_shape_results = []\n output_shape_results = []\n with self.tf.compat.v1.Session(graph=self.graph) as sess:\n fake_input = np.random.randn(1, self.imsize, self.imsize, 3)\n for shape_tensor in input_shape_tensors:\n intput_shape_results.append(sess.run(\n shape_tensor, feed_dict={self.graph_input_tensor: fake_input}\n ).tolist())\n for shape_tensor in output_shape_tensors:\n output_shape_results.append(sess.run(\n shape_tensor, feed_dict={self.graph_input_tensor: fake_input}\n ).tolist())\n\n return intput_shape_results, output_shape_results" }, { "alpha_fraction": 0.6590755581855774, "alphanum_fraction": 0.6746899485588074, "avg_line_length": 63.509090423583984, "blob_id": "7c52fc2d1e719ba234f34531dc0ce26912866291", "content_id": "4885f6a6208815b080d318657bd8bd6283455e46", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17744, "license_type": "permissive", "max_line_length": 1213, "num_lines": 275, "path": "/README.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "Note: This is an alpha (preview) version which is still under refining.\n\n**nn-Meter** is a novel and efficient system to accurately predict the inference latency of DNN models on diverse edge devices. The key idea is dividing a whole model inference into kernels, i.e., the execution units of fused operators on a device, and conduct kernel-level prediction. We currently evaluate four popular platforms on a large dataset of 26k models. It achieves 99.0% (mobile CPU), 99.1% (mobile Adreno 640 GPU), 99.0% (mobile Adreno 630 GPU), and 83.4% (Intel VPU) prediction accuracy.\n\nThe current supported hardware and inference frameworks:\n\n| Device | Framework | Processor | +-10% Accuracy | Hardware name |\n| :-----------------: | :------------: | :------------: | :-------------: | :----------------------: |\n| Pixel4 | TFLite v2.1 | CortexA76 CPU | 99.0% | cortexA76cpu_tflite21 |\n| Mi9 | TFLite v2.1 | Adreno 640 GPU | 99.1% | adreno640gpu_tflite21 |\n| Pixel3XL | TFLite v2.1 | Adreno 630 GPU | 99.0% | adreno630gpu_tflite21 |\n| Intel Movidius NCS2 | OpenVINO2019R2 | Myriad VPU | 83.4% | myriadvpu_openvino2019r2 |\n\n*nn-Meter has achieved the **Mobisys 21 Best Paper Award!** For more details, please check out paper:*\n\n[nn-Meter: towards accurate latency prediction of deep-learning model inference on diverse edge devices](https://dl.acm.org/doi/10.1145/3458864.3467882)\n\n## Who should consider using nn-Meter\n\n- Those who want to get the DNN inference latency on mobile and edge devices with **no deployment efforts on real devices**.\n- Those who want to run **hardware-aware NAS with [NNI](https://github.com/microsoft/nni)**.\n- Those who want to **build latency predictors for their own devices**.\n- Those who want to use the 26k latency [benchmark dataset](https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/datasets.zip).\n\n# Installation\n\nCurrently nn-Meter has been tested on Linux and Windows system. Windows 10, Ubuntu 16.04 and 20.04 with python 3.6.10 are tested and supported. Please first install `python3` before nn-Meter installation. Then nn-Meter could be installed by running:\n\n```Bash\npip install nn-meter\n```\n\nIf you want to try latest code, please install nn-Meter from source code. First git clone nn-Meter package to local:\n\n```Bash\ngit clone [email protected]:microsoft/nn-Meter.git\ncd nn-Meter\n```\n\nThen simply run the following pip install in an environment that has `python >= 3.6`. The command will complete the automatic installation of all necessary dependencies and nn-Meter.\n\n```Bash\npip install .\n```\n\nnn-Meter is a latency predictor of models with type of Tensorflow, PyTorch, Onnx, nn-meter IR graph and [NNI IR graph](https://github.com/microsoft/nni). To use nn-Meter for specific model type, you also need to install corresponding required packages. The well tested versions are listed below:\n\n| Testing Model Type | Requirements |\n| :----------------: | :-----------------------------------------------------------------------------------------------------------------------: |\n| Tensorflow | `tensorflow==1.15.0` |\n| Torch | `torch==1.7.1`, `torchvision==0.8.2`, (alternative)[`onnx==1.9.0`, `onnx-simplifier==0.3.6`] or [`nni==2.4`][1] |\n| Onnx | `onnx==1.9.0` |\n| nn-Meter IR graph | --- |\n| NNI IR graph | `nni==2.4` |\n\n[1] Please refer to [nn-Meter Usage](#torch-model-converters) for more information.\n\nPlease also check the versions of `numpy` and `scikit_learn`. The different versions may change the prediction accuracy of kernel predictors.\n\nThe stable version of wheel binary package will be released soon.\n\n# Usage\n\nTo apply for hardware latency prediction, nn-Meter provides two types of interfaces:\n\n- command line `nn-meter` after `nn-meter`[installation](QuickStart.md#Installation).\n- Python binding provided by the module `nn_meter`\n\nHere is a summary of supported inputs of the two methods.\n\n| Testing Model Type | Command Support | Python Binding |\n| :----------------: | :-----------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------: |\n| Tensorflow | Checkpoint file dumped by `tf.saved_model()` and end with `.pb` | Checkpoint file dumped by `tf.saved_model` and end with `.pb` |\n| Torch | Models in `torchvision.models` | Object of `torch.nn.Module` |\n| Onnx | Checkpoint file dumped by `torch.onnx.export()` or `onnx.save()` and end with `.onnx` | Checkpoint file dumped by `onnx.save()` or model loaded by `onnx.load()` |\n| nn-Meter IR graph | Json file in the format of[nn-Meter IR Graph](./docs/input_models.md#nnmeter-ir-graph) | `dict` object following the format of [nn-Meter IR Graph](./docs/input_models.md#nnmeter-ir-graph) |\n| NNI IR graph | - | NNI IR graph object |\n\nIn both methods, users could appoint predictor name and version to target a specific hardware platform (device). Currently, nn-Meter supports prediction on the following four configs:\n\n| Predictor (device_inferenceframework) | Processor Category | Version |\n| :-----------------------------------: | :----------------: | :-----: |\n| cortexA76cpu_tflite21 | CPU | 1.0 |\n| adreno640gpu_tflite21 | GPU | 1.0 |\n| adreno630gpu_tflite21 | GPU | 1.0 |\n| myriadvpu_openvino2019r2 | VPU | 1.0 |\n\nUsers can get all predefined predictors and versions by running\n\n```bash\n# to list all predefined predictors\nnn-meter --list-predictors \n```\n\n## Predict latency of saved CNN model\n\nAfter installation, a command named `nn-meter` is enabled. To predict the latency for a CNN model with a predefined predictor in command line, users can run the following commands\n\n```bash\n# for Tensorflow (*.pb) file\nnn-meter lat_pred --predictor <hardware> [--predictor-version <version>] --tensorflow <pb-file_or_folder> \n\n# for ONNX (*.onnx) file\nnn-meter lat_pred --predictor <hardware> [--predictor-version <version>] --onnx <onnx-file_or_folder>\n\n# for torch model from torchvision model zoo (str)\nnn-meter lat_pred --predictor <hardware> [--predictor-version <version>] --torchvision <model-name> <model-name>... \n\n# for nn-Meter IR (*.json) file\nnn-meter lat_pred --predictor <hardware> [--predictor-version <version>] --nn-meter-ir <json-file_or_folder> \n```\n\n`--predictor-version <version>` arguments is optional. When the predictor version is not specified by users, nn-meter will use the latest version of the predictor.\n\nnn-Meter can support batch mode prediction. To predict latency for multiple models in the same model type once, user should collect all models in one folder and state the folder after `--[model-type]` liked argument.\n\nIt should also be noted that for PyTorch model, nn-meter can only support existing models in torchvision model zoo. The string followed by `--torchvision` should be exactly one or more string indicating name(s) of some existing torchvision models. To apply latency prediction for torchvision model in command line, `onnx` and `onnx-simplifier` packages are required.\n\n### Convert to nn-Meter IR Graph\n\nFurthermore, users may be interested to convert tensorflow pb-file or onnx file to nn-Meter IR graph. Users could convert nn-Meter IR graph and save to `.json` file be running\n\n```bash\n# for Tensorflow (*.pb) file\nnn-meter get_ir --tensorflow <pb-file> [--output <output-name>]\n\n# for ONNX (*.onnx) file\nnn-meter get_ir --onnx <onnx-file> [--output <output-name>]\n```\n\nOutput name is default to be `/path/to/input/file/<input_file_name>_<model-type>_ir.json` if not specified by users.\n\n## Use nn-Meter in your python code\n\nAfter installation, users can import nn-Meter in python code\n\n```python\nfrom nn_meter import load_latency_predictor\n\npredictor = load_latency_predictor(hardware_name, hardware_predictor_version) # case insensitive in backend\n\n# build your model (e.g., model instance of torch.nn.Module)\nmodel = ... \n\nlat = predictor.predict(model, model_type) # the resulting latency is in unit of ms\n```\n\nBy calling `load_latency_predictor`, user selects the target hardware and loads the corresponding predictor. nn-Meter will try to find the right predictor file in `~/.nn_meter/data`. If the predictor file doesn't exist, it will download from the Github release.\n\nIn `predictor.predict()`, the allowed items of the parameter `model_type` include `[\"pb\", \"torch\", \"onnx\", \"nnmeter-ir\", \"nni-ir\"]`, representing model types of tensorflow, torch, onnx, nn-meter IR graph and NNI IR graph, respectively.\n\n`<span id=\"torch-model-converters\">` For Torch models, the shape of feature maps is unknown merely based on the given network structure, which is, however, significant parameters in latency prediction. Therefore, torch model requires a shape of input tensor for inference as a input of `predictor.predict()`. Based on the given input shape, a random tensor according to the shape will be generated and used. Another thing for Torch model prediction is that users can install the `onnx` and `onnx-simplifier` packages for latency prediction (referred to as Onnx-based latency prediction for torch model), or alternatively install the `nni` package (referred to as NNI-based latency prediction for torch model). Note that the `nni` option does not support command line calls. In addition, if users use `nni` for latency prediction, the PyTorch modules should be defined by the `nn` interface from NNI `import nni.retiarii.nn.pytorch as nn` (view [NNI doc](https://nni.readthedocs.io/en/stable/NAS/QuickStart.html#define-base-model) for more information), and the parameter `apply_nni` should be set as `True` in the function `predictor.predict()`. Here is an example of NNI-based latency prediction for Torch model:\n\n```python\nimport nni.retiarii.nn.pytorch as nn\nfrom nn_meter import load_latency_predictor\n\npredictor = load_latency_predictor(...)\n\n# build your model using nni.retiarii.nn.pytorch as nn\nmodel = nn.Module ...\n\ninput_shape = (1, 3, 224, 224)\nlat = predictor.predict(model, model_type='torch', input_shape=input_shape, apply_nni=True) \n```\n\nThe Onnx-based latency prediction for torch model is stable but slower, while the NNI-based latency prediction for torch model is unstable as it could fail in some case but much faster compared to the Onnx-based model. The Onnx-based model is set as the default one for Torch model latency prediction in nn-Meter. Users could choose which one they preferred to use according to their needs. \n\nUsers could view the information all built-in predictors by `list_latency_predictors` or view the config file in `nn_meter/configs/predictors.yaml`.\n\nUsers could get a nn-Meter IR graph by applying `model_file_to_graph` and `model_to_graph` by calling the model name or model object and specify the model type. The supporting model types of `model_file_to_graph` include \"onnx\", \"pb\", \"torch\", \"nnmeter-ir\" and \"nni-ir\", while the supporting model types of `model_to_graph` include \"onnx\", \"torch\" and \"nni-ir\".\n\n## Benchmark Dataset\n\nTo evaluate the effectiveness of a prediction model on an arbitrary DNN model, we need a representative dataset that covers a large prediction scope. As there is no such available latency dataset, nn-Meter collects and generates 26k CNN models. It contains various operators, configurations, and edge connections, with covering different levels of FLOPs and latency. (Please refer the paper for the dataset generation method and dataset numbers.)\n\nWe release the dataset, and provide an interface of `nn_meter.dataset` for users to get access to the dataset. Users can also download the data from the [Download Link](https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/datasets.zip) for testing nn-Meter or their own prediction models. \n\n## Hardware-aware NAS by nn-Meter and NNI\n\nTo empower affordable DNN on the edge and mobile devices, hardware-aware NAS searches both high accuracy and low latency models. In particular, the search algorithm only considers the models within the target latency constraints during the search process.\n\nCurrently we provides example of end-to-end [multi-trial NAS](https://nni.readthedocs.io/en/stable/NAS/multi_trial_nas.html), which is a [random search algorithm](https://arxiv.org/abs/1902.07638) on [SPOS NAS](https://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123610528.pdf) search space. More examples of more hardware-aware NAS and model compression algorithms are coming soon.\n\nTo run multi-trail SPOS demo, NNI should be installed through source code by following [NNI Doc](https://nni.readthedocs.io/en/stable/Tutorial/InstallationLinux.html#installation)\n\n```bash\npython setup.py develop\n```\n\nThen run multi-trail SPOS demo:\n\n```bash\npython ${NNI_ROOT}/examples/nas/oneshot/spos/multi_trial.py\n```\n\n### How the demo works\n\nRefer to [NNI Doc](https://nni.readthedocs.io/en/stable/nas.html) for how to perform NAS by NNI.\n\nTo support hardware-aware NAS, you first need a `Strategy` that supports filtering the models by latency. We provide such a filter named `LatencyFilter` in NNI and initialize a `Random` strategy with the filter:\n\n```python\nsimple_strategy = strategy.Random(model_filter=LatencyFilter(threshold=100, predictor=base_predictor))\n```\n\n`LatencyFilter` will predict the models' latency by using nn-Meter and filter out the models whose latency with the given predictor are larger than the threshold (i.e., `100` in this example).\nYou can also build your own strategies and filters to support more flexible NAS such as sorting the models according to latency.\n\nThen, pass this strategy to `RetiariiExperiment`:\n\n```python\nexp = RetiariiExperiment(base_model, trainer, strategy=simple_strategy)\n\nexp_config = RetiariiExeConfig('local')\n...\nexp_config.dummy_input = [1, 3, 32, 32]\n\nexp.run(exp_config, port)\n```\n\nIn `exp_config`, `dummy_input` is required for tracing shape info.\n\n## Bench Dataset\n\nTo evaluate the effectiveness of a prediction model on an arbitrary DNN model, we need a representative dataset that covers a large prediction scope. nn-Meter collects and generates 26k CNN models. (Please refer the paper for the dataset generation method.)\n\nWe release the dataset, and provide an interface of `nn_meter.dataset` for users to get access to the dataset. Users can also download the data from the [Download Link](https://github.com/microsoft/nn-Meter/releases/download/v1.0-data/datasets.zip) on their own. \n\n\n\n# Contributing\n\nThis project welcomes contributions and suggestions. Most contributions require you to agree to a\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\nthe rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.\n\nWhen you submit a pull request, a CLA bot will automatically determine whether you need to provide\na CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions\nprovided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\ncontact [[email protected]](mailto:[email protected]) with any additional questions or comments.\n\n# License\n\nThe entire codebase is under [MIT license](https://github.com/microsoft/nn-Meter/blob/main/LICENSE)\n\nThe dataset is under [Open Use of Data Agreement](https://github.com/Community-Data-License-Agreements/Releases/blob/main/O-UDA-1.0.md)\n\n# Citation\n\nIf you find that nn-Meter helps your research, please consider citing it:\n\n```\n@inproceedings{nnmeter,\n author = {Zhang, Li Lyna and Han, Shihao and Wei, Jianyu and Zheng, Ningxin and Cao, Ting and Yang, Yuqing and Liu, Yunxin},\n title = {nn-Meter: Towards Accurate Latency Prediction of Deep-Learning Model Inference on Diverse Edge Devices},\n year = {2021},\n publisher = {ACM},\n address = {New York, NY, USA},\n url = {https://doi.org/10.1145/3458864.3467882},\n doi = {10.1145/3458864.3467882},\n booktitle = {Proceedings of the 19th Annual International Conference on Mobile Systems, Applications, and Services},\n pages = {81–93},\n}\n\n@misc{nnmetercode,\n author = {Microsoft Research nn-Meter Team},\n title = {nn-Meter: Towards Accurate Latency Prediction of Deep-Learning Model Inference on Diverse Edge Devices},\n year = {2021},\n url = {https://github.com/microsoft/nn-Meter},\n}\n```\n" }, { "alpha_fraction": 0.6635570526123047, "alphanum_fraction": 0.6683719754219055, "avg_line_length": 35.47252655029297, "blob_id": "91c1eff21c449f06fac227fc0e1b0732b46f091f", "content_id": "fe93e6e013385ff8d85983736effb34731d6b38e", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3323, "license_type": "permissive", "max_line_length": 144, "num_lines": 91, "path": "/nn_meter/utils/utils.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport os\nfrom zipfile import ZipFile\nfrom tqdm import tqdm\nimport requests\nfrom packaging import version\nimport logging\n\n\ndef download_from_url(urladdr, ppath):\n \"\"\"\n download the kernel predictors from the url\n @params:\n\n urladdr: github release url address\n ppath: the targeting dir to save the download data (usually hardware_inferenceframework)\n\n \"\"\"\n file_name = os.path.join(ppath, \".zip\")\n if not os.path.isdir(ppath):\n os.makedirs(ppath)\n\n # logging.keyinfo(f'Download from {urladdr}')\n response = requests.get(urladdr, stream=True)\n total_size_in_bytes = int(response.headers.get(\"content-length\", 0))\n block_size = 2048 # 2 Kibibyte\n progress_bar = tqdm(total=total_size_in_bytes, unit=\"iB\", unit_scale=True)\n with open(file_name, \"wb\") as file:\n for data in response.iter_content(block_size):\n progress_bar.update(len(data))\n file.write(data)\n zipfile = ZipFile(file_name)\n zipfile.extractall(path=ppath)\n zipfile.close() \n progress_bar.close()\n os.remove(file_name)\n\ndef try_import_onnx(require_version = \"1.9.0\"):\n try:\n import onnx\n if version.parse(onnx.__version__) != version.parse(require_version):\n logging.warning(f'onnx=={onnx.__version__} is not well tested now, well tested version: onnx=={require_version}' )\n return onnx\n except ImportError:\n logging.error(f'You have not install the onnx package, please install onnx=={require_version} and try again.')\n exit()\n\ndef try_import_torch(require_version = \"1.7.1\"):\n try:\n import torch\n if version.parse(torch.__version__) != version.parse(require_version):\n logging.warning(f'torch=={torch.__version__} is not well tested now, well tested version: torch=={require_version}' )\n return torch\n except ImportError:\n logging.error(f'You have not install the torch package, please install torch=={require_version} and try again.')\n exit()\n\ndef try_import_tensorflow(require_version = \"1.15.0\"):\n try:\n import tensorflow\n if version.parse(tensorflow.__version__) != version.parse(require_version):\n logging.warning(f'tensorflow=={tensorflow.__version__} is not well tested now, well tested version: tensorflow=={require_version}' )\n return tensorflow\n except ImportError:\n logging.error(f'You have not install the tensorflow package, please install tensorflow=={require_version} and try again.')\n exit()\n\ndef try_import_torchvision_models():\n try:\n import torchvision\n return torchvision.models\n except ImportError:\n logging.error(f'You have not install the torchvision package, please install torchvision and try again.')\n exit()\n\ndef try_import_onnxsim():\n try:\n from onnxsim import simplify\n return simplify\n except ImportError:\n logging.error(f'You have not install the onnx-simplifier package, please install onnx-simplifier and try again.')\n exit()\n\ndef try_import_dgl():\n try:\n import dgl\n return dgl\n except ImportError:\n logging.error(f'You have not install the dgl package, please install dgl and try again.')\n exit()\n " }, { "alpha_fraction": 0.5328759551048279, "alphanum_fraction": 0.5374499559402466, "avg_line_length": 31.38888931274414, "blob_id": "a29eb0779514e8869772862f68e6b9f5c20757f0", "content_id": "50413956174f16fef12da3c97e4c75e903b3b994", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1749, "license_type": "permissive", "max_line_length": 82, "num_lines": 54, "path": "/nn_meter/utils/export_op_latency.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport jsonlines\nimport nn_meter\nfrom nn_meter.dataset import bench_dataset\n\ndef create_dummy_input(name):\n dummy_input = {\n \"inbounds\": [],\n \"attr\": {\n \"name\": name,\n \"type\": \"Placeholder\",\n \"output_shape\": [],\n \"attr\": {},\n \"input_shape\": []\n },\n \"outbounds\": []\n }\n return dummy_input\n\npredictors = nn_meter.list_latency_predictors()\nfor p in predictors:\n print(f\"[Predictor] {p['name']}: version={p['version']}\")\n # load predictor\n predictor_name = 'adreno640gpu_tflite21'\n predictor_version = 1.0\n predictor = nn_meter.load_latency_predictor(predictor_name, predictor_version)\n\n datasets = bench_dataset()\n test_data = datasets[0]\n print(datasets)\n\n with jsonlines.open(test_data) as data_reader:\n n = len(data_reader)\n for i, item in enumerate(data_reader):\n print(f'{i}/{n}')\n model = item['graph']\n\n for node_name, node in model.items():\n if node[\"inbounds\"] == []:\n continue\n dummy_model = {}\n for input in node[\"inbounds\"]:\n dummy_model[input] = create_dummy_input(input)\n dummy_model[node_name] = node\n latency = predictor.predict(dummy_model, model_type=\"nnmeter-ir\")\n if \"latency\" not in node[\"attr\"]:\n node[\"attr\"][\"latency\"] = {}\n node[\"attr\"][\"latency\"][predictor_name] = latency\n \n item['graph'] = model\n\n with jsonlines.open('output.jsonl', mode='a') as writer:\n writer.write(item)\n" }, { "alpha_fraction": 0.5513998866081238, "alphanum_fraction": 0.5531096458435059, "avg_line_length": 34.984615325927734, "blob_id": "5b7c3e28a4405e3ebd648e4944ce6be56746ac64", "content_id": "877d2371290c5ec402b89ebaf58d2377842edcf6", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4679, "license_type": "permissive", "max_line_length": 101, "num_lines": 130, "path": "/nn_meter/ir_converters/torch_converter/converter.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom nn_meter.utils.utils import try_import_onnx, try_import_torch, try_import_onnxsim\nimport tempfile\nfrom nn_meter.ir_converters.onnx_converter import OnnxConverter\n\n\nfrom .opset_map import nni_attr_map, nni_type_map\n\n\ndef _nchw_to_nhwc(shapes):\n return [\n [shape[0], shape[2], shape[3], shape[1]]\n if len(shape) == 4\n else shape\n for shape in shapes\n ]\n\n\nclass NNIIRConverter:\n def __init__(self, ir_model):\n try:\n from nni.retiarii.converter.utils import flatten_model_graph\n self.ir_model = flatten_model_graph(ir_model)\n except:\n from nni.retiarii.converter.graph_gen import GraphConverterWithShape\n self.ir_model = ir_model.fork()\n GraphConverterWithShape().flatten(self.ir_model)\n\n def convert(self):\n graph = self._to_graph_layout()\n\n for _, node in graph.items():\n self._map_opset(node)\n\n self._remove_unshaped_nodes(graph)\n\n return graph\n\n def _to_graph_layout(self):\n graph = {}\n\n for node in self.ir_model.root_graph.hidden_nodes:\n node_dict = {\n \"attr\": {\n \"attr\": {\n k: v\n for k, v in node.operation.parameters.items()\n },\n \"input_shape\": _nchw_to_nhwc(node.operation.parameters.get(\"input_shape\")\n if \"input_shape\" in node.operation.parameters \n else node.operation.attributes.get('input_shape')),\n \"output_shape\": _nchw_to_nhwc(node.operation.parameters.get(\"output_shape\") \n if \"output_shape\" in node.operation.parameters \n else node.operation.attributes.get('output_shape')),\n \"type\": node.operation.type,\n },\n \"inbounds\": [],\n \"outbounds\": [],\n }\n\n incoming_edges = sorted(node.incoming_edges, key=lambda e: e.tail_slot or 0)\n for edge in incoming_edges:\n node_dict[\"inbounds\"].append(edge.head.name)\n\n outgoing_edges = sorted(node.outgoing_edges, key=lambda e: e.head_slot or 0)\n for edge in outgoing_edges:\n node_dict[\"outbounds\"].append(edge.tail.name)\n\n graph[node.name] = node_dict\n\n return graph\n\n def _map_opset(self, node):\n old_type = node[\"attr\"][\"type\"]\n new_type = nni_type_map.get(old_type, old_type)\n\n new_attr_dict = {}\n for attr_name, attr_value in node[\"attr\"][\"attr\"].items():\n new_attr_name = attr_name\n new_attr_value = attr_value\n for type, attr_map in nni_attr_map.items():\n if type == \"__all__\" or type == new_type:\n if attr_name in attr_map:\n new_attr_name, modifier = attr_map[attr_name]\n if modifier is not None:\n new_attr_value = modifier(attr_value)\n\n new_attr_dict[new_attr_name] = new_attr_value\n\n node[\"attr\"][\"type\"] = new_type\n node[\"attr\"][\"attr\"] = new_attr_dict\n\n def _remove_unshaped_nodes(self, graph):\n for node_name, node_dict in list(graph.items()):\n if not node_dict[\"attr\"][\"input_shape\"]:\n del graph[node_name]\n\n\nclass NNIBasedTorchConverter(NNIIRConverter):\n def __init__(self, model, example_inputs):\n torch = try_import_torch()\n from nni.retiarii.converter import convert_to_graph\n from nni.retiarii.converter.graph_gen import GraphConverterWithShape\n\n # PyTorch module to NNI IR\n script_module = torch.jit.script(model)\n converter = GraphConverterWithShape()\n ir_model = convert_to_graph(\n script_module, model, converter=converter, dummy_input=example_inputs\n )\n\n super().__init__(ir_model)\n\n\nclass OnnxBasedTorchConverter(OnnxConverter):\n def __init__(self, model, example_inputs):\n onnx = try_import_onnx()\n torch = try_import_torch()\n with tempfile.TemporaryFile() as fp:\n torch.onnx.export(model, example_inputs, fp)\n fp.seek(0)\n model = onnx.load(fp, load_external_data=False)\n\n # convert model\n simplify = try_import_onnxsim()\n model_simp, check = simplify(model)\n\n assert check, \"Simplified ONNX model could not be validated\"\n super().__init__(model_simp)\n\n" }, { "alpha_fraction": 0.595478892326355, "alphanum_fraction": 0.6109458804130554, "avg_line_length": 30.148147583007812, "blob_id": "608208a5f3296ab18ad3dca30dcd8f03a36b245a", "content_id": "2cf40a7a0d602a4fdcb07034884ac54a26c63e96", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1681, "license_type": "permissive", "max_line_length": 103, "num_lines": 54, "path": "/nn_meter/prediction/predictors/utils.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\n\ndef get_kernel_name(optype):\n \"\"\"\n for many similar kernels, we use one kernel predictor since their latency difference is negligible,\n return the kernel name via the optype\n\n \"\"\"\n if \"conv\" in optype and \"dwconv\" not in optype:\n optype = \"conv-bn-relu\"\n if \"dwconv\" in optype:\n optype = \"dwconv-bn-relu\"\n if optype == \"fc-relu\":\n optype = \"fc\"\n if optype == \"max-pool\":\n optype = \"maxpool\"\n if optype == \"avg-pool\":\n optype = \"avgpool\"\n if optype in [\"global-pool\", \"gap\"]:\n optype = \"global-avgpool\"\n if optype == \"channel_shuffle\":\n optype = \"channelshuffle\"\n if optype in [\"bn-relu\"]:\n optype = \"bnrelu\"\n if optype in [\"add-relu\"]:\n optype = \"addrelu\"\n\n if optype in [\"SE\", \"SE-relu\", \"se\", \"se-relu\"]:\n optype = \"se\"\n\n return optype\n\ndef get_accuracy(y_pred, y_true, threshold=0.01):\n a = (y_true - y_pred) / y_true\n b = np.where(abs(a) <= threshold)\n return len(b[0]) / len(y_true)\n\n\ndef latency_metrics(y_pred, y_true):\n \"\"\"\n evaluation metrics for prediction performance\n \"\"\"\n y_true=np.array(y_true)\n y_pred=np.array(y_pred)\n rmspe = (np.sqrt(np.mean(np.square((y_true - y_pred) / y_true)))) * 100\n rmse = np.sqrt(mean_squared_error(y_pred, y_true))\n acc5 = get_accuracy(y_pred, y_true, threshold=0.05)\n acc10 = get_accuracy(y_pred, y_true, threshold=0.10)\n acc15 = get_accuracy(y_pred, y_true, threshold=0.15)\n return rmse, rmspe, rmse / np.mean(y_true), acc5, acc10, acc15" }, { "alpha_fraction": 0.6325897574424744, "alphanum_fraction": 0.6334761381149292, "avg_line_length": 34.62631607055664, "blob_id": "b8333b3029fb33d3b469db5f42d24b09131a2cf0", "content_id": "55dccd27caa8393a23f40d57843aa9c999ea023b", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6769, "license_type": "permissive", "max_line_length": 150, "num_lines": 190, "path": "/nn_meter/nn_meter_cli.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom glob import glob\nimport os\nimport sys\nimport argparse\nimport logging\nfrom nn_meter.nn_meter import *\n\n__user_config_folder__ = os.path.expanduser('~/.nn_meter/config')\n__user_data_folder__ = os.path.expanduser('~/.nn_meter/data')\n\n__predictors_cfg_filename__ = 'predictors.yaml'\n\n\ndef list_latency_predictors_cli():\n preds = list_latency_predictors()\n logging.keyinfo(\"Supported latency predictors:\")\n for p in preds:\n logging.result(f\"[Predictor] {p['name']}: version={p['version']}\")\n return\n\n\ndef apply_latency_predictor_cli(args):\n \"\"\"apply latency predictor to predict model latency according to the command line interface arguments\n \"\"\"\n if not args.predictor:\n logging.keyinfo('You must specify a predictor. Use \"nn-meter --list-predictors\" to see all supporting predictors.')\n return\n\n # specify model type\n if args.tensorflow:\n input_model, model_type, model_suffix = args.tensorflow, \"pb\", \".pb\"\n elif args.onnx:\n input_model, model_type, model_suffix = args.onnx, \"onnx\", \".onnx\"\n elif args.nn_meter_ir:\n input_model, model_type, model_suffix = args.nn_meter_ir, \"nnmeter-ir\", \".json\"\n elif args.torchvision: # torch model name from torchvision model zoo\n input_model_list, model_type = args.torchvision, \"torch\" \n\n # load predictor\n predictor = load_latency_predictor(args.predictor, args.predictor_version)\n\n # specify model for prediction\n if not args.torchvision: # input of tensorflow, onnx, nnmeter-ir and nni-ir is file name, while input of torchvision is string list\n input_model_list = []\n if os.path.isfile(input_model):\n input_model_list = [input_model]\n elif os.path.isdir(input_model):\n input_model_list = glob(os.path.join(input_model, \"**\" + model_suffix))\n input_model_list.sort()\n logging.info(f'Found {len(input_model_list)} model in {input_model}. Start prediction ...')\n else:\n logging.error(f'Cannot find any model satisfying the arguments.')\n\n # predict latency\n result = {}\n for model in input_model_list:\n latency = predictor.predict(model, model_type) # in unit of ms\n result[os.path.basename(model)] = latency\n logging.result(f'[RESULT] predict latency for {os.path.basename(model)}: {latency} ms')\n \n return result\n\ndef get_nnmeter_ir_cli(args):\n \"\"\"convert pb file or onnx file to nn-Meter IR graph according to the command line interface arguments\n \"\"\"\n import json\n from nn_meter.utils.graph_tool import NumpyEncoder\n if args.tensorflow:\n graph = model_file_to_graph(args.tensorflow, 'pb')\n filename = args.output if args.output else args.tensorflow.replace(\".pb\", \"_pb_ir.json\") \n elif args.onnx:\n graph = model_file_to_graph(args.onnx, 'onnx')\n filename = args.output if args.output else args.onnx.replace(\".onnx\", \"_onnx_ir.json\") \n else:\n raise ValueError(f\"Unsupported model.\")\n \n if not str.endswith(filename, '.json'): filename += '.json'\n with open(filename, \"w+\") as fp:\n json.dump(graph,\n fp,\n indent=4,\n skipkeys=True,\n sort_keys=True,\n cls=NumpyEncoder,\n )\n \n logging.result(f'The nn-meter ir graph has been saved. Saved path: {os.path.abspath(filename)}')\n\n\ndef nn_meter_info(args):\n if args.list_predictors:\n list_latency_predictors_cli()\n else:\n logging.keyinfo('please run \"nn-meter {positional argument} --help\" to see nn-meter guidance')\n\n\ndef nn_meter_cli():\n parser = argparse.ArgumentParser('nn-meter', description='please run \"nn-meter {positional argument} --help\" to see nn-meter guidance')\n parser.set_defaults(func=nn_meter_info)\n\n # optional arguments\n parser.add_argument(\n \"-v\", \"--verbose\", \n help=\"increase output verbosity\",\n action=\"store_true\"\n )\n parser.add_argument(\n '--list-predictors',\n help='list all supported predictors',\n action='store_true',\n default=False\n )\n\n # create subparsers for args with sub values\n subparsers = parser.add_subparsers()\n\n # Usage 1: latency predictors\n lat_pred = subparsers.add_parser('lat_pred', help='apply latency predictor for testing model')\n lat_pred.add_argument(\n \"--predictor\",\n type=str,\n help=\"name of target predictor (hardware)\"\n )\n lat_pred.add_argument(\n \"--predictor-version\",\n type=float,\n help=\"the version of the latency predictor (if not specified, use the lateast version)\",\n default=None\n )\n group = lat_pred.add_mutually_exclusive_group()\n group.add_argument(\n \"--tensorflow\",\n type=str,\n help=\"path to input Tensorflow model (*.pb file or floder)\"\n )\n group.add_argument(\n \"--onnx\",\n type=str,\n help=\"path to input ONNX model (*.onnx file or floder)\"\n )\n group.add_argument(\n \"--nn-meter-ir\",\n type=str,\n help=\"path to input nn-Meter IR model (*.json file or floder)\"\n )\n group.add_argument(\n \"--torchvision\", # --torchvision only can support the model object. The argument specifies \n type=str, # the name of the model, and we will look for the model in torchvision model zoo.\n nargs='+',\n help=\"name of the input torch model from the torchvision model zoo\"\n )\n lat_pred.set_defaults(func=apply_latency_predictor_cli)\n\n # Usage 2: get nn-meter-ir model from tensorflow pbfile or onnx file\n # Usage: nn-meter get_ir --tensorflow <pb-file>\n get_ir = subparsers.add_parser(\n 'get_ir', \n help='specify a model type to convert to nn-meter ir graph'\n )\n group2 = get_ir.add_mutually_exclusive_group()\n group2.add_argument(\n \"--tensorflow\",\n type = str,\n help=\"path to input Tensorflow model (*.pb)\"\n )\n group2.add_argument(\n \"--onnx\",\n type=str,\n help=\"path to input ONNX model (*.onnx)\"\n )\n get_ir.add_argument(\n \"-o\", \"--output\",\n type=str,\n help=\"path to save the output nn-meter ir graph for tensorflow and onnx (*.json), default to be /path/to/input/file/<input_file_name>_ir.json\"\n )\n get_ir.set_defaults(func=get_nnmeter_ir_cli)\n\n # parse args\n args = parser.parse_args()\n if args.verbose:\n logging.basicConfig(stream=sys.stdout, format=\"(nn-Meter) %(message)s\", level=logging.INFO)\n else:\n logging.basicConfig(stream=sys.stdout, format=\"(nn-Meter) %(message)s\", level=logging.KEYINFO)\n args.func(args)\n\n\nif __name__ == '__main__':\n nn_meter_cli()\n" }, { "alpha_fraction": 0.5490143895149231, "alphanum_fraction": 0.5540756583213806, "avg_line_length": 33.44036865234375, "blob_id": "f646f3ba424f539741a756b71b106c6fa3464e1a", "content_id": "ab650b136f6b843efa5ca534982b0952a0b58979", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3754, "license_type": "permissive", "max_line_length": 108, "num_lines": 109, "path": "/nn_meter/kerneldetection/detection/detector.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom nn_meter.kerneldetection.rulelib.rule_reader import RuleReader\nfrom nn_meter.kerneldetection.rulelib.rule_splitter import RuleSplitter\nfrom nn_meter.utils.graph_tool import ModelGraph\nfrom nn_meter.kerneldetection.utils.constants import DUMMY_TYPES\nfrom nn_meter.kerneldetection.utils.ir_tools import convert_nodes\n# import logging\n\n\nclass KernelDetector:\n def __init__(self, rule_file):\n self.reader = RuleReader(rule_file)\n self.splitter = RuleSplitter(self.reader)\n self.model_graph = None\n self.bbs = []\n self._global_index = 0\n\n def load_graph(self, graph):\n new_graph = convert_nodes(graph)\n self.model_graph = ModelGraph(graph=new_graph)\n self.model_graph.refresh()\n self.bbs = self.splitter.split(self.model_graph)\n\n @property\n def kernels(self):\n \"\"\"\n TODO: Should be a method and renamed to get_kernels()\n \"\"\"\n kernels = []\n self._global_index = 0\n self._layer_kernel_dict = {}\n\n for bb in self.bbs:\n kernel = self._bb_to_kernel(bb)\n self._global_index += 1\n if kernel is not None:\n kernels.append(kernel)\n\n self._fetch_connections(kernels)\n return kernels\n\n def _fetch_connections(self, kernels):\n fusion_graph = self.splitter._fusion_graph\n\n for kernel in kernels:\n kernel[\"inbounds\"] = []\n\n for i in range(len(fusion_graph)):\n layer = fusion_graph[i]\n kernel = self._layer_kernel_dict.get(layer)\n\n if kernel:\n outbounds = [fusion_graph.find_root(outbound) for outbound in fusion_graph.get_outbounds(i)]\n outbounds = [self._layer_kernel_dict[outbound] for outbound in outbounds]\n\n for outbound in outbounds:\n outbound[\"inbounds\"].append(kernel[\"name\"])\n\n outbounds = [outbound[\"name\"] for outbound in outbounds]\n kernel[\"outbounds\"] = outbounds\n\n def _bb_to_kernel(self, bb):\n types = [self.model_graph.get_node_type(node) for node in bb]\n # logging.info(types)\n types = [t for t in types if t and t not in DUMMY_TYPES]\n\n if types:\n type = \"-\".join(types)\n name = f\"{type}#{self._global_index}\"\n\n kernel = {\n \"op\": type,\n \"name\": name,\n }\n\n layer = bb[0]\n self._layer_kernel_dict[layer] = kernel\n type = types[0]\n attr = self.model_graph.get_node_attr(layer)[\"attr\"]\n input_shape = self.model_graph.get_node_attr(layer)[\"input_shape\"]\n output_shape = self.model_graph.get_node_attr(layer)[\"output_shape\"]\n\n # Remove const from first biasadd of hswish\n if type == \"hswish\":\n input_shape = [input_shape[0]]\n kernel[\"input_tensors\"] = input_shape\n\n if \"ks\" in attr:\n kernel[\"ks\"] = attr[\"ks\"]\n if \"strides\" in attr:\n kernel[\"strides\"] = attr[\"strides\"]\n if \"split_dim\" in attr:\n kernel[\"split_dim\"] = attr[\"split_dim\"]\n\n if len(input_shape) >= 1:\n if len(input_shape[0]) == 4:\n kernel[\"inputh\"] = input_shape[0][1]\n kernel[\"inputw\"] = input_shape[0][2]\n kernel[\"cin\"] = input_shape[0][-1]\n\n if len(output_shape) == 1:\n kernel[\"cout\"] = output_shape[0][-1]\n elif len(output_shape) > 1:\n kernel[\"output_tensors\"] = output_shape\n\n return kernel\n else:\n return None\n" }, { "alpha_fraction": 0.5714827179908752, "alphanum_fraction": 0.5726203918457031, "avg_line_length": 27.354839324951172, "blob_id": "90c3885e9f0a7a4565e5e13ec844edecf9d2fa93", "content_id": "fc6dd01e0ed67fc64928c06b171b0fca87a82553", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2637, "license_type": "permissive", "max_line_length": 94, "num_lines": 93, "path": "/nn_meter/kerneldetection/utils/fusion_aware_graph.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom nn_meter.utils.graph_tool import ModelGraph\nfrom .union_find import UF\nimport networkx as nx\n\n\nclass FusionAwareGraph:\n def __init__(self, model_graph: ModelGraph):\n self._model_graph = model_graph\n self._dag = list(nx.topological_sort(model_graph.get_networkx_graph()))\n self._uf = UF(len(self._dag))\n\n reverse = {}\n for index, name in enumerate(self._dag):\n reverse[name] = index\n outbounds = []\n inbounds = []\n for index, name in enumerate(self._dag):\n outbounds.append(\n {reverse[outbound] for outbound in self._model_graph.get_node_outbounds(name)}\n )\n inbounds.append(\n {reverse[inbound] for inbound in self._model_graph.get_node_inbounds(name)}\n )\n\n self._outbounds = outbounds\n self._inbounds = inbounds\n self._ready = [not inbounds[i] for i in range(0, len(self))]\n self._types = [model_graph.get_node_type(name) for name in self._dag]\n\n @property\n def nodes(self):\n return self._dag\n\n def __len__(self):\n return len(self._dag)\n\n def __getitem__(self, key):\n return self._dag[key]\n\n def fuse(self, node, outnode, update=False):\n \"\"\"\n node should be root, outnode should be an unfused single node\n \"\"\"\n self._uf.union(node, outnode)\n if not update:\n self._outbounds[node] = self._outbounds[outnode]\n else:\n self._outbounds[node].update(self._outbounds[outnode])\n\n def mark_ready(self, node):\n self._ready[node] = True\n\n def is_ready(self, node):\n for inbound in self._inbounds[node]:\n if not self.is_ready[inbound]:\n return False\n return True\n\n def is_visited(self, node):\n return self._ready[node]\n\n def get_outbounds(self, node):\n return self._outbounds[node]\n\n def get_inbounds(self, node):\n return self._inbounds[node]\n\n def get_type(self, node):\n return self._types[node]\n\n def get_basicblocks(self):\n bbs = []\n\n for _ in range(0, len(self)):\n bbs.append([])\n\n for i in range(0, len(self)):\n root = self._uf.find(i)\n bbs[root].append(self[i])\n\n bbs = [bb for bb in bbs if bb]\n return bbs\n\n def find_root(self, node):\n return self[self._uf.find(node)]\n\n def is_fused(self, node):\n return self._uf.find(node) != node\n\n def is_connected(self, p, q):\n return self._uf.connected(p, q)\n" }, { "alpha_fraction": 0.7592722177505493, "alphanum_fraction": 0.7634709477424622, "avg_line_length": 60.24285888671875, "blob_id": "68003cbe6287f528c93579624ad2ed15476f57e5", "content_id": "5424616d2abb3be930c534e42e5e696fd31d22da", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4287, "license_type": "permissive", "max_line_length": 520, "num_lines": 70, "path": "/docs/input_models.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Input Models\n\nnn-Meter currently supports both a saved model file and the model object in code. In particular, we support saved models in .pb and .onnx formats, and we support to directly predict Onnx and PyTorch models. Besides, to support the hardware-aware NAS, nn-Meter can also predict the inference latency of models in [NNI graph](https://nni.readthedocs.io/en/stable/nas.html).\n\nWhen taking the different model formats as input, nn-Meter converts them in nn-Meter IR graph. The kernel detection code will split the nn-Meter IR graph into the set of kernel units, and conduct kernel-level prediction.\n\n### Input model as a saved file\n\nYou can save tensorflow models into frozen pb formats, and use the following nn-meter command to predict the latency:\n\n```bash\n# for Tensorflow (*.pb) file\nnn-meter --predictor <hardware> --tensorflow <pb-file> \n```\n\nFor the other frameworks (e.g., PyTorch), you can convert the models into onnx models, and use the following nn-meter command to predict the latency:\n\n```bash\n# for ONNX (*.onnx) file\nnn-meter --predictor <hardware> --onnx <onnx-file>\n```\n\nYou can download the test [tensorflow models](\"https://github.com/Lynazhang/nnmeter/releases/download/0.1/pb_models.zip\") and [onnx models](https://github.com/Lynazhang/nnmeter/releases/download/0.1/onnx_models.zip). \n\n### Input model as a code object\n\nYou can also directly apply nn-Meter in your python code. In this case, please directly pass the onnx model and PyTorch model objects as the input model. The following is an example for PyTorch code:\n\n```python\nfrom nn_meter import load_latency_predictor\n\npredictor = load_lat_predictor(hardware_name) # case insensitive in backend\n\n# build your model here\nmodel = ... # model is instance of torch.nn.Module\n\nlat = predictor.predict(model, model_type='torch', input_shape=(3, 224, 224), apply_nni=False)\n```\n\nThere are two converters, i.e., model processors, for torch model, namely the Onnx-based torch converter and the NNI-based torch converter. Onnx-based torch converter export the torch model to onnx model, and reload the onnx model to the onnx converter. The serialization and postprocessing for Onnx-based torch converter is time-consuming, but the Onnx conversion is more stable. \n\nNNI-based torch converter generate a NNI IR graph based on the torch model, and use NNI converter for the subsequent steps. Note that if users use NNI-based converter, the PyTorch modules should be defined by the `nn` interface from NNI `import nni.retiarii.nn.pytorch as nn` (view [NNI doc](https://nni.readthedocs.io/en/stable/NAS/QuickStart.html#define-base-model) for more information). NNI-based torch converter get advantage in speed, but could fail in case the model contains some operators not supported by NNI. \n\nOne can switch two converters by setting `True` or `False` of the parameter `apply_nni` in `predictor.predict()`. Onnx-based torch converter is used as the default one for torch model. If `apply_nni-True`, NNI-based torch converter is used instead. Users could choose which one they preferred to use according to their needs. \n\n### <span id=\"nnmeter-ir-graph\"> nn-Meter IR graph </span>\n\nAs introduced, nn-Meter will perform a pre-processing step to convert the above model formats into the nn-Meter IR graphs. Now we introduce the defined IR graph.\n\nA *model* is consisting of *nodes*. The following is an example of conv *node* of AlexNet model\n\n<img src=\"imgs/irgraph.png\" alt=\"drawing\" width=\"400\"/>\n\nFor a *node*, we use the identical node name (\"conv1.conv/Conv2D\") as the node key. A *node* consists of:\n\n* inbounds: a list of incoming node names\n* outbounds: a list of outgoing node names. The inbounds and outbounds describe the node connections.\n* attr: a set of attributes for the node. The attributes can be different for different types of NN node.\n\nYou can download the example nn-Meter IR graphs through [here](https://github.com/Lynazhang/nnmeter/releases/download/0.1/ir_graphs.zip).\n\nWhen you have a large amount of models to predict, you can also convert them into nn-Meter IR graphs to save the pre-processing time:\n\n```\n# for Tensorflow (*.pb) file\nnn-meter getir --tensorflow <pb-file> --output <output-name>\n\n# for ONNX (*.onnx) file\nnn-meter getir --onnx <onnx-file> --output <output-name>\n```\n" }, { "alpha_fraction": 0.4576271176338196, "alphanum_fraction": 0.5310734510421753, "avg_line_length": 12.692307472229004, "blob_id": "10ee7b56e175ca5412b6f2cd25897e90a7800eeb", "content_id": "fecd85da1836f2e0d8835b937f87dd380bf55898", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 177, "license_type": "permissive", "max_line_length": 35, "num_lines": 13, "path": "/.flake8", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "[flake8]\nignore =\n E741,\n W503\nexclude =\n .git,\n .idea,\n __pycache__/,\n env/,\n venv/,\n .vscode/\nmax-line-length = 120\nper-file-ignores = __init__.py:F401" }, { "alpha_fraction": 0.5387611985206604, "alphanum_fraction": 0.5403194427490234, "avg_line_length": 35.67142868041992, "blob_id": "d94639ceacfbb23e8802c14860232b65f6addf0e", "content_id": "d4d214f9065299fae8d0877722c3a467dd181c16", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5134, "license_type": "permissive", "max_line_length": 88, "num_lines": 140, "path": "/nn_meter/ir_converters/onnx_converter/converter.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom nn_meter.utils.utils import try_import_onnx\nimport networkx as nx\nfrom .utils import get_tensor_shape\nfrom .constants import SLICE_TYPE\nfrom itertools import chain\nimport logging\n\n\nclass OnnxConverter:\n def __init__(self, model):\n onnx = try_import_onnx()\n from onnx import shape_inference\n inferred_model = shape_inference.infer_shapes(model)\n self.graph = inferred_model.graph\n\n self.tensors = {}\n for tensor in chain(self.graph.input, self.graph.value_info, self.graph.output):\n self.tensors[tensor.name] = {\n \"shape\": get_tensor_shape(tensor),\n \"inputs\": [],\n \"outputs\": [],\n }\n\n for node in self.graph.node:\n for input_name in node.input:\n if input_name in self.tensors:\n self.tensors[input_name][\"outputs\"].append(node)\n for output_name in node.output:\n if output_name in self.tensors:\n self.tensors[output_name][\"inputs\"].append(node)\n\n self.G = self.to_networkx()\n\n def to_networkx(self):\n G = nx.DiGraph()\n\n sliced_tensors = set()\n selected_slice = set()\n for node in self.graph.node:\n if node.op_type == SLICE_TYPE:\n tensor = node.input[0]\n if tensor in sliced_tensors:\n continue\n else:\n sliced_tensors.add(tensor)\n selected_slice.add(node.name)\n G.add_node(node.name, **self.fetch_attrs(node))\n\n for node in self.graph.node:\n if node.op_type == SLICE_TYPE and node.name not in selected_slice:\n continue\n for input_name in node.input:\n if input_name in self.tensors: # remove dummy ops\n G.add_edge(input_name, node.name)\n for output_name in node.output:\n if output_name in self.tensors:\n G.add_edge(node.name, output_name)\n if node.op_type == SLICE_TYPE:\n for tensor_name in self._get_sibling_slice_output_tensors(node):\n G.add_edge(node.name, tensor_name)\n\n return G\n\n def fetch_attrs(self, node):\n from onnx import AttributeProto\n attrs = {}\n input_tensors = []\n for input_name in node.input:\n if input_name in self.tensors:\n input_tensors.append(self.tensors[input_name][\"shape\"])\n output_tensors = []\n for output_name in node.output:\n if output_name in self.tensors:\n output_tensors.append(self.tensors[output_name][\"shape\"])\n if node.op_type == SLICE_TYPE:\n for tensor_name in self._get_sibling_slice_output_tensors(node):\n output_tensors.append(self.tensors[tensor_name][\"shape\"])\n if (\n len(input_tensors) == 0\n or len(input_tensors[0]) <= 1\n or len(output_tensors) == 0\n or len(output_tensors[0]) <= 1\n ):\n logging.warning(f\"Empty shape information with {node.name}\")\n return attrs\n\n attrs[\"attr\"] = {}\n attrs[\"type\"] = node.op_type\n attrs[\"input_shape\"] = input_tensors\n attrs[\"output_shape\"] = output_tensors\n for attr in node.attribute:\n if attr.type == AttributeProto.FLOAT:\n attrs[\"attr\"][attr.name] = attr.f\n elif attr.type == AttributeProto.INT:\n attrs[\"attr\"][attr.name] = attr.i\n elif attr.type == AttributeProto.INTS:\n attrs[\"attr\"][attr.name] = list(attr.ints)\n elif attr.type == AttributeProto.STRING:\n attrs[\"attr\"][attr.name] = str(attr.s)\n else:\n logging.warning(f\"Unsupported attributes type: {attr.type}\")\n\n return attrs\n\n def convert(self):\n result = {}\n\n for node in self.G.nodes:\n node_attrs = self.G.nodes[node]\n if node in self.tensors or not node_attrs:\n continue\n\n outbounds = []\n inbounds = []\n for succ in self.G.successors(node):\n for succ_succ in self.G.successors(succ):\n outbounds.append(succ_succ)\n for pred in self.G.predecessors(node):\n for pred_pred in self.G.predecessors(pred):\n inbounds.append(pred_pred)\n\n result[node] = {\n \"attr\": node_attrs,\n \"outbounds\": outbounds,\n \"inbounds\": inbounds,\n }\n\n return result\n\n def _get_sibling_slice_output_tensors(self, node):\n output_tensors = []\n for slice in self.tensors[node.input[0]][\"outputs\"]:\n if slice.name != node.name and slice.op_type == SLICE_TYPE:\n for output_name in slice.output:\n if output_name in self.tensors:\n output_tensors.append(output_name)\n\n return output_tensors\n" }, { "alpha_fraction": 0.7023593187332153, "alphanum_fraction": 0.7023593187332153, "avg_line_length": 26.549999237060547, "blob_id": "b97b24dc4795b312de7247e4096f06c0c7078ee4", "content_id": "9e9f6f32f919dfbd0ac1fe3d2ef80f34b0966ed4", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "permissive", "max_line_length": 65, "num_lines": 20, "path": "/nn_meter/kerneldetection/fusionlib/utils.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport os\nimport json\nfrom nn_meter.utils.graph_tool import ModelGraph\nfrom nn_meter.kerneldetection.utils.ir_tools import convert_nodes\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\ndef get_fusion_unit(name):\n filename = os.path.join(BASE_DIR, f\"{name}_fusionunit.json\")\n with open(filename, \"r\") as fp:\n graph = json.load(fp)\n\n if not isinstance(graph, list):\n graph = [graph]\n\n return [ModelGraph(graph=convert_nodes(g)) for g in graph]\n" }, { "alpha_fraction": 0.6121463179588318, "alphanum_fraction": 0.6176673769950867, "avg_line_length": 38.16216278076172, "blob_id": "090e581c869b8406f6ad88f70b77f8c3ac2fdd08", "content_id": "ce0f12fba18264294b4f3f0989247f85ff8d3f2f", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1449, "license_type": "permissive", "max_line_length": 142, "num_lines": 37, "path": "/setup.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom setuptools import setup, find_packages\n\n\nsetup(\n name='nn-meter',\n version='1.0',\n description='nn-Meter is a novel and efficient system to accurately predict the inference latency of DNN models on diverse edge devices.',\n long_description = open('README.md', encoding='utf-8').read(),\n long_description_content_type = 'text/markdown',\n author='Microsoft nn-Meter Team',\n author_email='[email protected]',\n url='https://github.com/microsoft/nn-Meter',\n project_urls={\n 'Data of models': 'https://github.com/microsoft/nn-Meter/releases/tag/v1.0-data',\n },\n license = 'MIT',\n classifiers = [\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft :: Windows :: Windows 10',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python :: 3 :: Only',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n ],\n packages=find_packages(),\n package_data={\n 'nn_meter': ['configs/*.yaml', 'kerneldetection/fusionlib/*.json'],\n },\n entry_points={\n 'console_scripts': ['nn-meter=nn_meter.nn_meter_cli:nn_meter_cli'],\n },\n install_requires=[\n 'numpy', 'tqdm', 'networkx', 'requests', 'protobuf', 'PyYAML', 'scikit_learn', 'packaging', 'jsonlines'\n ],\n)\n" }, { "alpha_fraction": 0.6782770752906799, "alphanum_fraction": 0.6850470900535583, "avg_line_length": 66.05921173095703, "blob_id": "da12508bf04c6461861e01c18103e067c2614449", "content_id": "4b6fad7ebbf6adf4ba9efe62a98186ad4c4d93c7", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10194, "license_type": "permissive", "max_line_length": 1211, "num_lines": 152, "path": "/docs/usage.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Usage\n\nTo apply for hardware latency prediction, nn-Meter provides two types of interfaces:\n\n- command line `nn-meter` after `nn-meter` [installation](QuickStart.md#Installation).\n- Python binding provided by the module `nn_meter`\n\nHere is a summary of supported inputs of the two methods.\n\n| Testing Model Type | Command Support | Python Binding |\n| :---------------: | :---------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------: |\n| Tensorflow | Checkpoint file dumped by `tf.saved_model()` and end with `.pb` | Checkpoint file dumped by `tf.saved_model` and end with `.pb` |\n| Torch | Models in `torchvision.models` | Object of `torch.nn.Module` |\n| Onnx | Checkpoint file dumped by `onnx.save()` and end with `.onnx` | Checkpoint file dumped by `onnx.save()` or model loaded by `onnx.load()` |\n| nn-Meter IR graph | Json file in the format of [nn-Meter IR Graph](input_models.md#nnmeter-ir-graph) | `dict` object following the format of [nn-Meter IR Graph](input_models.md#nnmeter-ir-graph) |\n| NNI IR graph | - | NNI IR graph object |\n\nIn both methods, users could appoint predictor name and version to target a specific hardware platform (device). Currently, nn-Meter supports prediction on the following four configs:\n| Predictor (device_inferenceframework) | Processor Category | Version |\n| :-----------------------------------: | :----------------: | :-----: |\n| cortexA76cpu_tflite21 | CPU | 1.0 |\n| adreno640gpu_tflite21 | GPU | 1.0 |\n| adreno630gpu_tflite21 | GPU | 1.0 |\n| myriadvpu_openvino2019r2 | VPU | 1.0 |\n\nUsers can get all predefined predictors and versions by running\n\n```bash\n# to list all predefined predictors\nnn-meter --list-predictors \n```\n\n## Predict latency of saved CNN model\n\nAfter installation, a command named `nn-meter` is enabled. To predict the latency for a CNN model with a predefined predictor in command line, users can run the following commands\n\n```bash\n# for Tensorflow (*.pb) file\nnn-meter lat_pred --predictor <hardware> [--predictor-version <version>] --tensorflow <pb-file_or_folder> \n\n# for ONNX (*.onnx) file\nnn-meter lat_pred --predictor <hardware> [--predictor-version <version>] --onnx <onnx-file_or_folder>\n\n# for torch model from torchvision model zoo (str)\nnn-meter lat_pred --predictor <hardware> [--predictor-version <version>] --torchvision <model-name> <model-name>... \n\n# for nn-Meter IR (*.json) file\nnn-meter lat_pred --predictor <hardware> [--predictor-version <version>] --nn-meter-ir <json-file_or_folder> \n```\n\n`--predictor-version <version>` arguments is optional. When the predictor version is not specified by users, nn-meter will use the latest version of the predictor.\n\nnn-Meter can support batch mode prediction. To predict latency for multiple models in the same model type once, user should collect all models in one folder and state the folder after `--[model-type]` liked argument.\n\nIt should also be noted that for PyTorch model, nn-meter can only support existing models in torchvision model zoo. The string followed by `--torchvision` should be exactly one or more string indicating name(s) of some existing torchvision models. To apply latency prediction for torchvision model in command line, `onnx` and `onnx-simplifier` packages are required.\n\n### Convert to nn-Meter IR Graph\n\nFurthermore, users may be interested to convert tensorflow pb-file or onnx file to nn-Meter IR graph. Users could convert nn-Meter IR graph and save to `.json` file be running\n\n```bash\n# for Tensorflow (*.pb) file\nnn-meter get_ir --tensorflow <pb-file> [--output <output-name>]\n\n# for ONNX (*.onnx) file\nnn-meter get_ir --onnx <onnx-file> [--output <output-name>]\n```\n\nOutput name is default to be `/path/to/input/file/<input_file_name>_<model-type>_ir.json` if not specified by users.\n\n## Use nn-Meter in your python code\n\nAfter installation, users can import nn-Meter in python code\n\n```python\nfrom nn_meter import load_latency_predictor\n\npredictor = load_latency_predictor(hardware_name, hardware_predictor_version) # case insensitive in backend\n\n# build your model (e.g., model instance of torch.nn.Module)\nmodel = ... \n\nlat = predictor.predict(model, model_type) # the resulting latency is in unit of ms\n```\n\nBy calling `load_latency_predictor`, user selects the target hardware and loads the corresponding predictor. nn-Meter will try to find the right predictor file in `~/.nn_meter/data`. If the predictor file doesn't exist, it will download from the Github release.\n\nIn `predictor.predict()`, the allowed items of the parameter `model_type` include `[\"pb\", \"torch\", \"onnx\", \"nnmeter-ir\", \"nni-ir\"]`, representing model types of tensorflow, torch, onnx, nn-meter IR graph and NNI IR graph, respectively.\n\n<span id=\"torch-model-converters\"> For Torch models, the shape of feature maps is unknown merely based on the given network structure, which is, however, significant parameters in latency prediction. Therefore, torch model requires a shape of input tensor for inference as a input of `predictor.predict()`. Based on the given input shape, a random tensor according to the shape will be generated and used. Another thing for Torch model prediction is that users can install the `onnx` and `onnx-simplifier` packages for latency prediction (referred to as Onnx-based latency prediction for torch model), or alternatively install the `nni` package (referred to as NNI-based latency prediction for torch model). Note that the `nni` option does not support command line calls. In addition, if users use `nni` for latency prediction, the PyTorch modules should be defined by the `nn` interface from NNI `import nni.retiarii.nn.pytorch as nn` (view [NNI doc](https://nni.readthedocs.io/en/stable/NAS/QuickStart.html#define-base-model) for more information), and the parameter `apply_nni` should be set as `True` in the function `predictor.predict()`. Here is an example of NNI-based latency prediction for Torch model:\n\n```python\nimport nni.retiarii.nn.pytorch as nn\nfrom nn_meter import load_latency_predictor\n\npredictor = load_latency_predictor(...)\n\n# build your model using nni.retiarii.nn.pytorch as nn\nmodel = nn.Module ...\n\ninput_shape = (1, 3, 224, 224)\nlat = predictor.predict(model, model_type='torch', input_shape=input_shape, apply_nni=True) \n```\n\nThe Onnx-based latency prediction for torch model is stable but slower, while the NNI-based latency prediction for torch model is unstable as it could fail in some case but much faster compared to the Onnx-based model. The Onnx-based model is set as the default one for Torch model latency prediction in nn-Meter. Users could choose which one they preferred to use according to their needs. </span>\n\nUsers could view the information all built-in predictors by `list_latency_predictors` or view the config file in `nn_meter/configs/predictors.yaml`.\n\nUsers could get a nn-Meter IR graph by applying `model_file_to_graph` and `model_to_graph` by calling the model name or model object and specify the model type. The supporting model types of `model_file_to_graph` include \"onnx\", \"pb\", \"torch\", \"nnmeter-ir\" and \"nni-ir\", while the supporting model types of `model_to_graph` include \"onnx\", \"torch\" and \"nni-ir\".\n\n## Hardware-aware NAS by nn-Meter and NNI\n\nTo empower affordable DNN on the edge and mobile devices, hardware-aware NAS searches both high accuracy and low latency models. In particular, the search algorithm only considers the models within the target latency constraints during the search process. For more theoretical details, please refer to [this doc](hardware-aware-model-design.md).\n\nCurrently we provides example of end-to-end [multi-trial NAS](https://nni.readthedocs.io/en/stable/NAS/multi_trial_nas.html), which is a [random search algorithm](https://arxiv.org/abs/1902.07638) on [SPOS NAS](https://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123610528.pdf) search space. More examples of more hardware-aware NAS and model compression algorithms are coming soon. \n\nTo run multi-trail SPOS demo, NNI should be installed through source code by following [NNI Doc](https://nni.readthedocs.io/en/stable/Tutorial/InstallationLinux.html#installation)\n```bash\npython setup.py develop\n```\n\nThen run multi-trail SPOS demo:\n\n```bash\npython ${NNI_ROOT}/examples/nas/oneshot/spos/multi_trial.py\n```\n\n### How the demo works\n\nRefer to [NNI Doc](https://nni.readthedocs.io/en/stable/nas.html) for how to perform NAS by NNI.\n\nTo support hardware-aware NAS, you first need a `Strategy` that supports filtering the models by latency. We provide such a filter named `LatencyFilter` in NNI and initialize a `Random` strategy with the filter:\n\n```python\nsimple_strategy = strategy.Random(model_filter=LatencyFilter(threshold=100, predictor=base_predictor))\n```\n\n`LatencyFilter` will predict the models' latency by using nn-Meter and filter out the models whose latency with the given predictor are larger than the threshold (i.e., `100` in this example).\nYou can also build your own strategies and filters to support more flexible NAS such as sorting the models according to latency.\n\nThen, pass this strategy to `RetiariiExperiment`:\n\n```python\nexp = RetiariiExperiment(base_model, trainer, strategy=simple_strategy)\n\nexp_config = RetiariiExeConfig('local')\n...\nexp_config.dummy_input = [1, 3, 32, 32]\n\nexp.run(exp_config, port)\n```\nIn `exp_config`, `dummy_input` is required for tracing shape info." }, { "alpha_fraction": 0.6321839094161987, "alphanum_fraction": 0.6340996026992798, "avg_line_length": 27.472726821899414, "blob_id": "e11759dfbf87bfdb1264ba034928b540e0254006", "content_id": "5bf7de97938e078c8c3d59154bd7efa47bf10c19", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1566, "license_type": "permissive", "max_line_length": 87, "num_lines": 55, "path": "/nn_meter/prediction/predictors/predict_by_kernel.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom .utils import get_kernel_name\nfrom .extract_feature import get_predict_features\n\n\ndef merge_conv_kernels(kernelname):\n \"\"\"\n to speed up, we merge conv and dwconv related kernels into one kernel by their name\n \"\"\"\n if \"conv\" in kernelname and \"dwconv\" not in kernelname:\n return \"conv-bn-relu\"\n elif \"dwconv\" in kernelname:\n return \"dwconv-bn-relu\"\n else:\n return kernelname\n\n\ndef predict_model(model, predictors):\n \"\"\"\n @params:\n model: the model config with prediction features\n predictors: loaded pkl predictors\n \"\"\"\n py = 0\n dicts = {}\n for layer in model:\n kernel = list(model[layer].keys())[0]\n features = model[layer][kernel]\n rkernel = merge_conv_kernels(kernel)\n if rkernel not in dicts:\n dicts[rkernel] = []\n dicts[rkernel].append(features)\n\n for kernel in dicts:\n kernelname = get_kernel_name(kernel)\n if kernelname in predictors:\n pred = predictors[kernelname]\n pys = pred.predict(dicts[kernel]) # in unit of ms\n if len(pys) != 0:\n py += sum(pys)\n\n return py\n\n\ndef nn_predict(predictors, kernel_units):\n \"\"\"\n @params:\n predictors: dictionary object, key: kernel name, object: loaded pkl latency model\n kernel_units: the divided kernel units and the features of a model.\n \"\"\"\n\n features = get_predict_features(kernel_units)\n py = predict_model(features, predictors)\n return py\n" }, { "alpha_fraction": 0.6231042146682739, "alphanum_fraction": 0.6450467705726624, "avg_line_length": 48.98387145996094, "blob_id": "5c634bc033aaf9e61738c2aeb104b3cf8af83a0a", "content_id": "f19bf92db9ecfb4cb625bf73a5ed05feaaba94d3", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3099, "license_type": "permissive", "max_line_length": 295, "num_lines": 62, "path": "/docs/quick_start.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Quick Start\n\n## nn-Meter Installation\n\nCurrently, nn-Meter has been tested on Linux and Windows system. Windows 10, Ubuntu 16.04 and 20.04 with python 3.6.10 are tested and supported. Please first install `python3` before nn-Meter installation. Then nn-Meter could be installed by running:\n\n```Bash\npip install nn-meter\n```\n\nIf you want to try latest code, please install nn-Meter from source code. First git clone nn-Meter package to local:\n```Bash\ngit clone [email protected]:microsoft/nn-Meter.git\ncd nn-Meter\n```\nThen simply run the following pip install in an environment that has `python >= 3.6`. The command will complete the automatic installation of all necessary dependencies and nn-Meter.\n```Bash\npip install .\n```\n\nnn-Meter is a latency predictor of models with type of Tensorflow, PyTorch, Onnx, nn-meter IR graph and [NNI IR graph](https://github.com/microsoft/nni). To use nn-Meter for specific model type, you also need to install corresponding required packages. The well tested versions are listed below:\n\n| Testing Model Type | Requirements |\n| :-------------------: | :------------------------------------------------: |\n| Tensorflow | `tensorflow==1.15.0` |\n| Torch | `torch==1.7.1`, `torchvision==0.8.2`, (alternative)[`onnx==1.9.0`, `onnx-simplifier==0.3.6`] or [`nni==2.4`][1] |\n| Onnx | `onnx==1.9.0` |\n| nn-Meter IR graph | --- |\n| NNI IR graph | `nni==2.4` |\n\n[1] Please refer to [nn-Meter Usage](usage.md#torch-model-converters) for more information.\n\nPlease also check the versions of `numpy` and `scikit_learn`. The different versions may change the prediction accuracy of kernel predictors.\n\nThe stable version of wheel binary package will be released soon.\n\n\n## \"Hello World\" example on torch model\nnn-Meter is an accurate inference latency predictor for DNN models on diverse edge devices. nn-Meter supports tensorflow pb-file, onnx file, torch model and nni IR model for latency prediction.\n\nHere is an example script to predict latency for Resnet18 in torch. To run the example, package `torch`, `torchvision`, `onnx` and `onnx-simplifier` are required. The well tested versions are `torch==1.7.1`, `torchvision==0.8.2`, `onnx==1.9.0` and `onnx-simplifier==0.3.6`. \n\n```python\nfrom nn_meter import load_latency_predictor\nimport torchvision.models as models\n\ndef main():\n base_model = models.resnet18()\n base_predictor = 'cortexA76cpu_tflite21'\n\n # load a predictor (device_inferenceframework)\n predictor = load_latency_predictor(base_predictor) \n\n # predict the latency based on the given model\n lat = predictor.predict(model=base_model, model_type='torch', input_shape=[1, 3, 32, 32]) # in unit of ms\n print(f'Latency for {base_predictor}: {lat} ms')\n\nif __name__ == '__main__':\n main()\n```\n\nFor more detailed usage of nn-Meter, please refer to [this doc](usage.md).\n" }, { "alpha_fraction": 0.4978378713130951, "alphanum_fraction": 0.502740740776062, "avg_line_length": 32.06948471069336, "blob_id": "c9f47da20848ec5444168715e176386a44a3fe41", "content_id": "f3b3dae02423d5bbed71594c16ad3b9ff1f73cda", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32838, "license_type": "permissive", "max_line_length": 115, "num_lines": 993, "path": "/nn_meter/ir_converters/frozenpb_converter/shape_inference.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom .protobuf_helper import ProtobufHelper as ph\nfrom functools import reduce\nimport copy\nimport math\nimport logging\n\n\nlogging = logging.getLogger(__name__)\n\n\nclass ShapeInference:\n\n # Ops that only need to calculate the prodcast for shapes\n TF_PRODCAST_MATH_OPS = [\n \"Add\",\n \"AddN\", # AddN does not support prodcast really\n \"AddV2\",\n \"Subtract\",\n \"Sub\",\n \"MulNoNan\",\n \"Multiply\",\n \"Mul\",\n \"Div\",\n \"DivNoNan\",\n \"Equal\",\n ]\n\n # Ops that only need to propagate the shapes\n TF_PROPAGATE_MATH_OPS = [\n \"Abs\",\n \"Acos\",\n \"ACosh\",\n \"Asin\",\n \"Asinh\",\n \"Atan\",\n \"Atanh\",\n \"Cos\",\n \"Cosh\",\n \"Exp\",\n \"Floor\",\n \"Sin\",\n \"Sinh\",\n \"Sqrt\",\n \"Square\",\n\n \"FusedBatchNorm\",\n \"FusedBatchNormV2\",\n \"FusedBatchNormV3\",\n \"BiasAdd\",\n\n \"Relu\",\n \"Relu6\",\n \"Selu\",\n \"LeakyReLU\",\n \"Elu\"\n \"Softmax\",\n\n \"NoOp\"\n ]\n\n @staticmethod\n def eval_prodcast(graph, node):\n \"\"\"\n Evalute the prodcast along the input nodes.\n Now we use lazy prodcast, will move to tf implement later.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n input_nodes = node[\"inbounds\"]\n if len(input_nodes) < 2:\n logging.warn(\n \"Invalid input op num for prodcast op %s\" % (node[\"attr\"][\"name\"])\n )\n if len(input_nodes) == 1:\n return graph[node[\"inbounds\"][0]][\"attr\"][\"output_shape\"][0]\n else:\n return None\n\n target_dim = -1\n target_shape = [1]\n input_shape_list = []\n for node_name in input_nodes:\n input_shape = graph[node_name][\"attr\"][\"output_shape\"][0]\n input_shape_list.append(input_shape)\n if target_dim < len(input_shape):\n target_dim = len(input_shape)\n target_shape = input_shape\n elif target_dim == len(input_shape):\n for i in range(target_dim):\n if target_shape[i] < input_shape[i]:\n target_shape[i] = input_shape[i]\n\n return input_shape_list, [target_shape]\n\n @staticmethod\n def get_padding_shape(input_shape, cout, k_size, strides, padding):\n \"\"\"\n Calculate the padded shape of a given tensor.\n\n Parameters\n ----------\n input_shape : list\n Input shape in list, a 2D or 4D list.\n cout : int\n Cout of the operation.\n k_size : list\n Kernel size of the operation, a 2D or 4D list.\n strides : list\n Strides of the operation, a 2D or 4D list.\n padding : str\n Padding type, now support SAME and VALID.\n \"\"\"\n\n logging.info(\n \"Calculating padding shape, input shape: %s, kernel size: %s, strides: %s, padding: %s.\"\n % (str(input_shape), str(k_size), str(strides), str(padding))\n )\n\n if padding == \"SAME\":\n outh = math.ceil(ph.get_h(input_shape) / ph.get_h(strides))\n outw = math.ceil(ph.get_w(input_shape) / ph.get_w(strides))\n\n padh = max(\n (outh - 1) * ph.get_h(strides)\n + ph.get_h(k_size)\n - ph.get_h(input_shape),\n 0,\n )\n padw = max(\n (outw - 1) * ph.get_w(strides)\n + ph.get_w(k_size)\n - ph.get_w(input_shape),\n 0,\n )\n\n pad_top = padh // 2\n pad_bottom = padh - pad_top\n pad_left = padw // 2\n pad_right = padw - pad_left\n\n pad_size = [pad_top, pad_bottom, pad_left, pad_right]\n elif padding == \"VALID\":\n outh = math.ceil(\n (ph.get_h(input_shape) - ph.get_h(k_size) + 1) / ph.get_h(strides)\n )\n outw = math.ceil(\n (ph.get_h(input_shape) - ph.get_h(k_size) + 1) / ph.get_w(strides)\n )\n\n pad_size = [0, 0, 0, 0]\n else:\n logging.error(\"Unexpected padding format %s.\" % (padding))\n return None, None\n\n output_shape = list(map(int, [input_shape[0], outh, outw, cout]))\n return copy.deepcopy(output_shape), copy.deepcopy(pad_size)\n\n @staticmethod\n def Const_get_shape(graph, node):\n \"\"\"\n Get shape of a const operator.\n Take the tensor shape as the output shape.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return [], [node[\"attr\"][\"attr\"][\"tensor_shape\"]]\n\n @staticmethod\n def Identity_get_shape(graph, node):\n \"\"\"\n Get shape of an Identity operator.\n This is not well implemented, will move a more robust later.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return [], [graph[node[\"inbounds\"][0]][\"attr\"][\"output_shape\"][0]]\n \n @staticmethod\n def Pad_get_shape(graph, node):\n \"\"\"\n Get shape of a Pad operator.\n This is not well implemented, will move a more robust later.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n in_shape = [graph[node[\"inbounds\"][0]][\"attr\"][\"output_shape\"][0]]\n paddings = node[\"attr\"][\"attr\"][\"paddings\"]\n out_shape = []\n for dim in range(len(in_shape)):\n out_shape.append(in_shape[dim] + sum(paddings[dim]))\n return in_shape, out_shape\n \n @staticmethod\n def PadV2_get_shape(graph, node):\n \"\"\"\n Get shape of a PadV2 operator.\n This is not well implemented, will move a more robust later.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Pad_get_shape(graph, node)\n\n @staticmethod\n def propagate_shape(graph, node):\n \"\"\"\n For operator who does not affect the shapes.\n Just take the input shapes as output.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n logging.info(\"Propagate through op %s.\", node[\"attr\"][\"name\"])\n in_shape = [graph[node[\"inbounds\"][0]][\"attr\"][\"output_shape\"][0]]\n return in_shape, in_shape\n\n @staticmethod\n def Pool_get_shape(graph, node):\n \"\"\"\n Get shape of a Pooling type operation.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n if len(node[\"inbounds\"]) != 1:\n logging.warning(\"Failed to get input node of %s.\" % (node[\"attr\"][\"name\"]))\n logging.info(node)\n return\n\n input_shape = copy.deepcopy(\n graph[node[\"inbounds\"][0]][\"attr\"][\"output_shape\"][0]\n )\n logging.info(\n \"Get input shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], node[\"inbounds\"][0], input_shape)\n )\n\n k_size = node[\"attr\"][\"attr\"][\"ksize\"]\n\n if node[\"attr\"][\"attr\"][\"strides\"][::3] != [1, 1]:\n logging.warning(\n \"Invalid strides %s of node %s.\"\n % (str(node[\"attr\"][\"attr\"][\"strides\"]), node[\"attr\"][\"name\"])\n )\n logging.info(node)\n return\n\n strides = node[\"attr\"][\"attr\"][\"strides\"]\n padding = node[\"attr\"][\"attr\"][\"padding\"].decode(\"utf-8\")\n logging.info(\n \"Op:%s, stride:%s, padding:%s.\"\n % (node[\"attr\"][\"name\"], str(strides), str(padding))\n )\n\n out_shape, padding_shape = ShapeInference.get_padding_shape(\n input_shape, input_shape[3], k_size, strides, padding\n )\n\n node[\"attr\"][\"attr\"][\"ksize\"] = copy.deepcopy(\n node[\"attr\"][\"attr\"][\"ksize\"][1:-1]\n )\n node[\"attr\"][\"attr\"][\"strides\"] = copy.deepcopy(\n node[\"attr\"][\"attr\"][\"strides\"][1:-1]\n )\n node[\"attr\"][\"attr\"][\"pads\"] = copy.deepcopy(padding_shape)\n\n return [input_shape], [out_shape]\n\n @staticmethod\n def AvgPool_get_shape(graph, node):\n \"\"\"\n Get shape of an AvgPool operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Pool_get_shape(graph, node)\n\n @staticmethod\n def AveragePooling2D_get_shape(graph, node):\n \"\"\"\n Get shape of an AveragePooling2D operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Pool_get_shape(graph, node)\n\n @staticmethod\n def MaxPool_get_shape(graph, node):\n \"\"\"\n Get shape of a MaxPool operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Pool_get_shape(graph, node)\n \n @staticmethod\n def MaxPoolV2_get_shape(graph, node):\n \"\"\"\n Get shape of a MaxPool operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Pool_get_shape(graph, node)\n\n @staticmethod\n def MaxPooling2D_get_shape(graph, node):\n \"\"\"\n Get shape of a MaxPooling2D operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Pool_get_shape(graph, node)\n\n @staticmethod\n def Placeholder_get_shape(graph, node):\n \"\"\"\n Get shape of a Placeholder operator.\n This fetch the shape from the shape attribute of the operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return [], [node[\"attr\"][\"attr\"][\"shape\"]]\n\n @staticmethod\n def Conv2D_get_shape(graph, node):\n \"\"\"\n Get shape of a Conv2D operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n weight_node = ph.find_weights_root(graph, node)\n if len(weight_node) != 1:\n logging.warning(\"Failed to get shape of node %s.\" % (node[\"attr\"][\"name\"]))\n logging.info(node)\n return\n\n input_node = [x for x in node[\"inbounds\"] if x != weight_node]\n input_node = [x for x in input_node if graph[x][\"attr\"][\"type\"] != \"Identity\"]\n if len(input_node) != 1:\n logging.warning(\"Failed to get input node of %s.\" % (node[\"attr\"][\"name\"]))\n logging.info(node)\n return\n\n input_shape = copy.deepcopy(graph[input_node[0]][\"attr\"][\"output_shape\"][0])\n logging.info(\n \"Get input shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], input_node[0], input_shape)\n )\n\n weight_shape = graph[weight_node[0]][\"attr\"][\"attr\"][\"tensor_shape\"]\n if len(weight_shape) != 4:\n logging.warning(\n \"Failed to parse weight shape %s of node %s.\"\n % (str(weight_shape), node[\"attr\"][\"name\"])\n )\n logging.info(node)\n return\n\n logging.info(\n \"Get weight shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], weight_node, weight_shape)\n )\n\n k_size = weight_shape[:2]\n cout = weight_shape[3]\n\n if node[\"attr\"][\"attr\"][\"strides\"][::3] != [1, 1]:\n logging.warning(\n \"Invalid strides %s of node %s.\"\n % (str(node[\"attr\"][\"attr\"][\"strides\"]), node[\"attr\"][\"name\"])\n )\n logging.info(node)\n return\n\n strides = node[\"attr\"][\"attr\"][\"strides\"]\n dilation = node[\"attr\"][\"attr\"][\"dilations\"]\n padding = node[\"attr\"][\"attr\"][\"padding\"].decode(\"utf-8\")\n logging.info(\n \"Op:%s, stride:%s, dilation:%s, padding:%s.\"\n % (node[\"attr\"][\"name\"], str(strides), str(dilation), str(padding))\n )\n\n kernel_extent_w = ph.get_w(dilation) * (ph.get_w(strides) - 1) + 1\n kernel_extent_h = ph.get_h(dilation) * (ph.get_h(strides) - 1) + 1\n\n out_shape, padding_shape = ShapeInference.get_padding_shape(\n input_shape, cout, [kernel_extent_w, kernel_extent_h], strides, padding\n )\n\n node[\"attr\"][\"attr\"][\"kernel_shape\"] = copy.deepcopy(k_size)\n node[\"attr\"][\"attr\"][\"dilations\"] = copy.deepcopy(\n node[\"attr\"][\"attr\"][\"dilations\"][1:-1]\n )\n node[\"attr\"][\"attr\"][\"strides\"] = copy.deepcopy(\n node[\"attr\"][\"attr\"][\"strides\"][1:-1]\n )\n node[\"attr\"][\"attr\"][\"weight_shape\"] = copy.deepcopy(weight_shape)\n node[\"attr\"][\"attr\"][\"pads\"] = padding_shape\n\n return [input_shape], [out_shape]\n\n @staticmethod\n def DepthwiseConv2dNative_get_shape(graph, node):\n \"\"\"\n Get shape of a DepthwiseConv2dNative operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n weight_node = ph.find_weights_root(graph, node)\n if len(weight_node) != 1:\n logging.warning(\"Failed to get shape of node %s.\" % (node[\"attr\"][\"name\"]))\n logging.info(node)\n return\n\n input_node = [x for x in node[\"inbounds\"] if x != weight_node]\n input_node = [x for x in input_node if graph[x][\"attr\"][\"type\"] != \"Identity\"]\n if len(input_node) != 1:\n logging.warning(\"Failed to get input node of %s.\" % (node[\"attr\"][\"name\"]))\n logging.info(node)\n return\n\n input_shape = copy.deepcopy(graph[input_node[0]][\"attr\"][\"output_shape\"][0])\n logging.info(\n \"Get input shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], input_node[0], input_shape)\n )\n\n weight_shape = graph[weight_node[0]][\"attr\"][\"attr\"][\"tensor_shape\"]\n if len(weight_shape) != 4:\n logging.warning(\n \"Failed to parse weight shape %s of node %s.\"\n % (str(weight_shape), node[\"attr\"][\"name\"])\n )\n logging.info(node)\n return\n\n logging.info(\n \"Get weight shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], weight_node, weight_shape)\n )\n\n k_size = weight_shape[:2]\n cin = weight_shape[2]\n\n if node[\"attr\"][\"attr\"][\"strides\"][::3] != [1, 1]:\n logging.warning(\n \"Invalid strides %s of node %s.\"\n % (str(node[\"attr\"][\"attr\"][\"strides\"]), node[\"attr\"][\"name\"])\n )\n logging.info(node)\n return\n\n strides = node[\"attr\"][\"attr\"][\"strides\"]\n dilation = node[\"attr\"][\"attr\"][\"dilations\"]\n padding = node[\"attr\"][\"attr\"][\"padding\"].decode(\"utf-8\")\n\n logging.info(\n \"Op:%s, stride:%s, dilation:%s, padding:%s.\"\n % (node[\"attr\"][\"name\"], str(strides), str(dilation), str(padding))\n )\n\n kernel_extent_w = ph.get_w(dilation) * (ph.get_w(strides) - 1) + 1\n kernel_extent_h = ph.get_h(dilation) * (ph.get_h(strides) - 1) + 1\n\n out_shape, padding_shape = ShapeInference.get_padding_shape(\n input_shape, cin, [kernel_extent_w, kernel_extent_h], strides, padding\n )\n\n node[\"attr\"][\"attr\"][\"kernel_shape\"] = copy.deepcopy(k_size)\n node[\"attr\"][\"attr\"][\"dilations\"] = copy.deepcopy(\n node[\"attr\"][\"attr\"][\"dilations\"][1:-1]\n )\n node[\"attr\"][\"attr\"][\"strides\"] = copy.deepcopy(\n node[\"attr\"][\"attr\"][\"strides\"][1:-1]\n )\n node[\"attr\"][\"attr\"][\"weight_shape\"] = copy.deepcopy(weight_shape)\n node[\"attr\"][\"attr\"][\"pads\"] = padding_shape\n\n return [input_shape], [out_shape]\n\n @staticmethod\n def Reduce_get_shape(graph, node):\n \"\"\"\n Get shape of a Reduce operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n input_shape = graph[node[\"inbounds\"][0]][\"attr\"][\"output_shape\"][0]\n output_shape = input_shape\n logging.info(\n \"Get input shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], node[\"inbounds\"][0], output_shape)\n )\n\n output_shape[1] = 0\n output_shape[2] = 0\n\n reduction_indices = node[\"attr\"][\"attr\"][\"reduction_indices\"]\n logging.info(\"Get Reduction Indices %s.\", str(reduction_indices))\n\n reduction_cnt = 0\n for reduction in sorted(reduction_indices):\n del output_shape[reduction - reduction_cnt]\n reduction_cnt += 1\n\n return [input_shape], [output_shape]\n\n @staticmethod\n def Mean_get_shape(graph, node):\n \"\"\"\n Get shape of a Mean operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Reduce_get_shape(graph, node)\n\n @staticmethod\n def GlobalAveragePooling2D_get_shape(graph, node):\n \"\"\"\n Get shape of a GlobalAveragePooling2D operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Reduce_get_shape(graph, node)\n\n @staticmethod\n def GlobalMaxPooling2D_get_shape(graph, node):\n \"\"\"\n Get shape of a GlobalMaxPooling2D operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Reduce_get_shape(graph, node)\n\n @staticmethod\n def MatMul_get_shape(graph, node):\n \"\"\"\n Get shape of a MatMul operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n weight_node = ph.find_weights_root(graph, node)\n if len(weight_node) != 1:\n logging.warning(\"Failed to get shape of node %s.\" % (node[\"attr\"][\"name\"]))\n logging.info(node)\n return\n\n weight_shape = graph[weight_node[0]][\"attr\"][\"attr\"][\"tensor_shape\"]\n if len(weight_shape) != 2:\n logging.warning(\n \"Failed to parse weight shape %s of node %s.\"\n % (str(weight_shape), node[\"attr\"][\"name\"])\n )\n logging.info(node)\n return\n\n logging.info(\n \"Get weight shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], weight_node, weight_shape)\n )\n\n input_node = [x for x in node[\"inbounds\"] if x != weight_node]\n input_node = [x for x in input_node if graph[x][\"attr\"][\"type\"] != \"Identity\"]\n if len(input_node) != 1:\n logging.warning(\"Failed to get input node of %s.\" % (node[\"attr\"][\"name\"]))\n logging.info(node)\n return\n\n input_shape = copy.deepcopy(graph[input_node[0]][\"attr\"][\"output_shape\"][0])\n logging.info(\n \"Get input shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], input_node[0], input_shape)\n )\n\n if weight_shape[0] != input_shape[1]:\n logging.warning(\n \"Weight shape and input shape not matched for %s.\"\n % (node[\"attr\"][\"name\"])\n )\n logging.info(node)\n return\n\n output_shape = copy.deepcopy(input_shape)\n output_shape[1] = weight_shape[1]\n\n return [input_shape], [output_shape]\n\n @staticmethod\n def Reshape_get_shape(graph, node):\n \"\"\"\n Get shape of a Reshape operator.\n It normally should take from the shape attribution,\n but we patch it for Pack-StrideSlice-Reshape, and\n prevent the program from dynamic inference.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n if \"shape\" in node[\"attr\"][\"attr\"].keys():\n logging.info(\n \"Shape attr find in %s op, propagate with normal.\", node[\"attr\"][\"name\"]\n )\n input_shape = copy.deepcopy(\n graph[node[\"inbounds\"][0]][\"attr\"][\"output_shape\"][0]\n )\n exp_output_shape = copy.deepcopy(node[\"attr\"][\"attr\"][\"shape\"])\n else:\n logging.info(\n \"Shape attr not find in %s op, try finding the shape node.\",\n node[\"attr\"][\"name\"],\n )\n for in_node in node[\"inbounds\"]:\n if graph[in_node][\"attr\"][\"type\"] == \"Const\":\n exp_output_shape = copy.deepcopy(\n graph[in_node][\"attr\"][\"constant\"]\n )\n elif graph[in_node][\"attr\"][\"type\"] == \"Pack\":\n exp_output_shape = [1] + [\n it\n for sl in graph[in_node][\"attr\"][\"attr\"][\"constant\"]\n for it in sl\n ]\n logging.info(\n \"Fetched expected output shape from Pack op %s\"\n % str(exp_output_shape)\n )\n else:\n input_shape = copy.deepcopy(\n graph[in_node][\"attr\"][\"output_shape\"][0]\n )\n\n input_elements = abs(reduce(lambda x, y: x * y, input_shape))\n exp_output_shape_elements = abs(reduce(lambda x, y: x * y, exp_output_shape))\n\n if input_elements != exp_output_shape_elements:\n logging.warning(\n \"Input shape %s and output shape %s not matched for %s.\"\n % (str(input_shape), str(exp_output_shape), node[\"attr\"][\"name\"])\n )\n\n return [input_shape], [exp_output_shape]\n\n @staticmethod\n def Concat_get_shape(graph, node):\n \"\"\"\n Get shape of a Concat operator.\n We add up the shape through axis.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n input_shape = []\n for in_node in node[\"inbounds\"]:\n in_shape = graph[in_node][\"attr\"][\"output_shape\"][0]\n if in_shape != []:\n input_shape.append(in_shape)\n logging.info(\n \"Get input shape of %s from %s, input shape:%s.\"\n % (node[\"attr\"][\"name\"], in_node, input_shape[-1])\n )\n axis = node[\"attr\"][\"attr\"][\"axis\"][0]\n\n output_shape = copy.deepcopy(input_shape[0])\n for in_shape in input_shape[1:]:\n output_shape[axis] += in_shape[axis]\n\n return copy.deepcopy(input_shape), [output_shape]\n\n @staticmethod\n def Concatenate_get_shape(graph, node):\n \"\"\"\n Get shape of a Concatenate operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Concat_get_shape(graph, node)\n\n @staticmethod\n def ConcatV2_get_shape(graph, node):\n \"\"\"\n Get shape of a ConcatV2 operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n return ShapeInference.Concat_get_shape(graph, node)\n\n @staticmethod\n def Split_get_shape(graph, node):\n \"\"\"\n Get shape of a Split operator.\n Also patched for Pack-StrideSlice-Split sequence.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n for in_node in node[\"inbounds\"]:\n if graph[in_node][\"attr\"][\"type\"] == \"Const\":\n pass\n elif graph[in_node][\"attr\"][\"type\"] == \"Pack\":\n pass\n else:\n input_shape = copy.deepcopy(graph[in_node][\"attr\"][\"output_shape\"][0])\n\n split_dim = node[\"attr\"][\"attr\"][\"split_dim\"][0]\n logging.info(\"Fetched Split dim for %s is %s.\", node[\"attr\"][\"name\"], split_dim)\n output_node_cnt = len(node[\"outbounds\"])\n\n output_shape = copy.deepcopy(input_shape)\n output_shape[split_dim] = output_shape[split_dim] // output_node_cnt\n output_shape = copy.deepcopy([output_shape]) * output_node_cnt\n\n return [copy.deepcopy(input_shape)], output_shape\n\n @staticmethod\n def Transpose_get_shape(graph, node):\n \"\"\"\n Get shape of a Transpose operator.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n for in_node in node[\"inbounds\"]:\n if graph[in_node][\"attr\"][\"type\"] == \"Const\":\n perm = copy.deepcopy(graph[in_node][\"attr\"][\"attr\"][\"constant\"])\n logging.info(\"Fetched perm sequence from Const op %s\" % str(perm))\n elif graph[in_node][\"attr\"][\"type\"] == \"Pack\":\n perm = [1] + [\n it\n for sl in graph[in_node][\"attr\"][\"attr\"][\"constant\"]\n for it in sl\n ]\n logging.info(\"Fetched perm sequence from Pack op %s\" % str(perm))\n else:\n input_shape = copy.deepcopy(graph[in_node][\"attr\"][\"output_shape\"][0])\n logging.info(\n \"Fetched input shape from %s, %s\" % (in_node, str(input_shape))\n )\n\n exp_output_shape = []\n for i in range(len(perm)):\n exp_output_shape.append(input_shape[perm[i]])\n\n return [input_shape], [exp_output_shape]\n\n @staticmethod\n def Pack_get_shape(graph, node):\n \"\"\"\n Get shape of a Transpose operator.\n Patched for kernel detector.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n seq = ph.get_graph_seq(graph, [node[\"attr\"][\"name\"]])[:5]\n for out_node in seq:\n if graph[out_node][\"attr\"][\"type\"] == \"Reshape\":\n if \"input_shape\" in graph[out_node][\"attr\"].keys():\n return (\n graph[out_node][\"attr\"][\"input_shape\"],\n graph[out_node][\"attr\"][\"input_shape\"],\n )\n return [[0, 0, 0, 0]], [[0, 0, 0, 0]]\n\n @staticmethod\n def StridedSlice_get_shape(graph, node):\n \"\"\"\n Get shape of a Transpose operator.\n Patched for kernel detector.\n\n Parameters\n ----------\n graph : dict\n The Graph IR in dict format.\n node : dict\n The node in Graph IR in dict format.\n \"\"\"\n seq = ph.get_graph_seq(graph, [node[\"attr\"][\"name\"]])[:5]\n for out_node in seq:\n if graph[out_node][\"attr\"][\"type\"] == \"Reshape\":\n if \"input_shape\" in graph[out_node][\"attr\"].keys():\n return (\n graph[out_node][\"attr\"][\"input_shape\"],\n graph[out_node][\"attr\"][\"input_shape\"],\n )\n return [[0, 0, 0, 0]], [[0, 0, 0, 0]]\n\n def __init__(self, model_graph, dynamic_fetcher):\n \"\"\"\n Take the graph, and append output shape\n and input shape to the attributes of nodes.\n\n Parameters\n ----------\n model_graph : ModelGraph\n The ModelGraph IR class.\n \"\"\"\n graph = model_graph.get_graph()\n seq = ph.get_graph_seq(graph, model_graph.get_graph_head())\n\n # Pass #1\n for node_name in seq:\n node_type = model_graph.get_node_type(node_name)\n node_get_shape_name = node_type + \"_get_shape\"\n\n # if node type find in supported ops, use faster static inference\n if node_type in self.TF_PRODCAST_MATH_OPS or \\\n node_type in self.TF_PROPAGATE_MATH_OPS or \\\n node_get_shape_name in dir(self) :\n\n if node_type in self.TF_PRODCAST_MATH_OPS:\n input_shape, output_shape = ShapeInference.eval_prodcast(graph, graph[node_name])\n elif node_type in self.TF_PROPAGATE_MATH_OPS:\n input_shape, output_shape = ShapeInference.propagate_shape(graph, graph[node_name])\n else:\n input_shape, output_shape = eval(\"self.\" + node_get_shape_name)(\n graph, graph[node_name]\n )\n\n # fallback to dynamic inference\n # To be aware, dynamic inference does not process the shape at all, \n # like removing weight shape from inputs. This may yield false prediction.\n else:\n logging.warn(\"%s is not supported by static inference yet.\" % model_graph.get_node_type(node_name))\n logging.warn(\"Failling back to dynamic fetcher, this may yield low inference speed.\")\n input_shape, output_shape = dynamic_fetcher.get_shape_by_name(node_name)\n\n\n if output_shape is not None:\n graph[node_name][\"attr\"][\"output_shape\"] = copy.deepcopy(\n output_shape\n )\n if input_shape is not None:\n graph[node_name][\"attr\"][\"input_shape\"] = copy.deepcopy(input_shape)\n logging.info(\n \"Input shape of %s op is %s.\" % (node_name, str(input_shape))\n )\n logging.info(\n \"Output shape of %s op is %s.\" % (node_name, str(output_shape))\n )\n\n\n # Pass #2\n # This is a patching for back-end, since backend extract shapes from\n # those two ops.\n for node_name in seq:\n if model_graph.get_node_type(node_name) in [\"Pack\", \"StridedSlice\"]:\n node_get_shape_name = model_graph.get_node_type(node_name) + \"_get_shape\"\n input_shape, output_shape = eval(\"self.\" + node_get_shape_name)(\n graph, graph[node_name]\n )\n if output_shape is not None:\n graph[node_name][\"attr\"][\"output_shape\"] = copy.deepcopy(\n output_shape\n )\n if input_shape is not None:\n graph[node_name][\"attr\"][\"input_shape\"] = copy.deepcopy(input_shape)\n logging.info(\n \"Second Pass: Input shape of %s op is %s.\"\n % (node_name, str(input_shape))\n )\n logging.info(\n \"Second Pass: Output shape of %s op is %s.\"\n % (node_name, str(output_shape))\n )\n" }, { "alpha_fraction": 0.7851239442825317, "alphanum_fraction": 0.7851239442825317, "avg_line_length": 38.66666793823242, "blob_id": "b28ee6ea468ea7c5d014c2ba7dbd8b02be375f1a", "content_id": "6bb62174f1d5c0b6c5cde3cd98c73c0eab54865a", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "permissive", "max_line_length": 45, "num_lines": 3, "path": "/nn_meter/prediction/__init__.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom .predictors.utils import latency_metrics\n\n\n" }, { "alpha_fraction": 0.7583954930305481, "alphanum_fraction": 0.763059675693512, "avg_line_length": 31.484848022460938, "blob_id": "7f0e47e0c4ef4906dbd8b5fb3b160db3c1a0f482", "content_id": "da6b1d6a4c3697b3e066e77e03de942fe3dc211b", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1072, "license_type": "permissive", "max_line_length": 89, "num_lines": 33, "path": "/nn_meter/__init__.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\ntry:\n import pkg_resources # part of setuptools\n __version__ = pkg_resources.require(\"nn-meter\")[0].version\nexcept ModuleNotFoundError:\n __version__ = 'UNKNOWN'\n\nfrom .nn_meter import (\n nnMeter,\n load_latency_predictor,\n list_latency_predictors,\n model_file_to_graph,\n model_to_graph,\n create_user_configs,\n change_user_data_folder\n)\nfrom .utils.utils import download_from_url\nfrom .prediction import latency_metrics\nfrom .dataset import bench_dataset # TODO: add GNNDataloader and GNNDataset here @wenxuan\nimport logging\nfrom functools import partial, partialmethod\n\nlogging.KEYINFO = 22\nlogging.addLevelName(logging.KEYINFO, 'KEYINFO')\nlogging.Logger.keyinfo = partialmethod(logging.Logger.log, logging.KEYINFO)\nlogging.keyinfo = partial(logging.log, logging.KEYINFO)\n\nlogging.RESULT = 25\nlogging.addLevelName(logging.RESULT, 'RESULT')\nlogging.Logger.result = partialmethod(logging.Logger.log, logging.RESULT)\nlogging.result = partial(logging.log, logging.RESULT)\n" }, { "alpha_fraction": 0.6054836511611938, "alphanum_fraction": 0.606245219707489, "avg_line_length": 31.825000762939453, "blob_id": "fb1772df73efe0a0ca1f4d6e43c4a826dce888fa", "content_id": "aac61a4e07042934a7f52dbd81289d1e55b864c4", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1313, "license_type": "permissive", "max_line_length": 57, "num_lines": 40, "path": "/nn_meter/ir_converters/frozenpb_converter/frozenpb_converter.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nimport numpy as np\n\nfrom nn_meter.utils.graph_tool import ModelGraph\nfrom .frozenpb_parser import FrozenPbParser\nfrom .shape_inference import ShapeInference\nfrom .shape_fetcher import ShapeFetcher\n\nclass FrozenPbConverter:\n def __init__(self, file_name):\n self.model_graph = ModelGraph()\n\n # Parse pb to graph\n parser = FrozenPbParser(file_name)\n parser.parse_graph(self.model_graph)\n dynamic_fetcher = ShapeFetcher(parser.graph)\n\n # Change split to more firendly scheme\n parser.fix_split_naming(self.model_graph)\n\n # Get the static shape\n ShapeInference(self.model_graph, dynamic_fetcher)\n\n # Strip constant and indentity nodes\n parser.strip_useless_nodes(self.model_graph)\n\n def get_flatten_graph(self):\n def np_encoder(d):\n for k, v in d.items():\n if isinstance(v, dict):\n np_encoder(v)\n else:\n if isinstance(v, np.ndarray):\n d[k] = v.tolist()\n if isinstance(v, (bytes, bytearray)):\n d[k] = v.decode(\"utf-8\")\n\n np_encoder(self.model_graph.get_graph())\n return self.model_graph.get_graph()\n" }, { "alpha_fraction": 0.7968254089355469, "alphanum_fraction": 0.7968254089355469, "avg_line_length": 130.3333282470703, "blob_id": "840e8ba425430fc6229d07f86a8dcd68e514ed8f", "content_id": "e97e8109553da72692ba6093d0ccaa6ff56cefe1", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1575, "license_type": "permissive", "max_line_length": 611, "num_lines": 12, "path": "/tests/README.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "In nn-Meter/tests, we implement the integration test for all usages of nn-Meter. \n\n## Integration test\n\nAccording to [nn-Meter usage](nn-Meter/docs/usage.md), nn-Meter is a latency predictor of models with type of Tensorflow, PyTorch, Onnx, nn-meter IR graph and NNI IR graph. In integration test, we run the test for mentioned models, collect the latency results, and compare the results with the reference results. For time saving and readability, we separate the integration test into two scripts with PyTorch model and others, respectively. \n\nFor PyTorch model, we accomplished two graph converters, namely NNI-based torch converter and ONNX-based torch converter (Refer to [this doc](docs/usage.md#torch-model-converters) for more information). We test both converters in `tests/integration_test_torch.py`. Note that the NNI-based torch converter needs API from `nni.retiarii.nn.pytorch` (view [NNI doc](https://nni.readthedocs.io/en/stable/NAS/QuickStart.html#define-base-model)) to build the torch module, thus we collected torchvision models and modified the import package to meet NNI requirements. The modified model are saved in tests/torchmodels.\n\n\n## github actions workflow\n\n[GitHub Actions](https://docs.github.com/en/actions) workflow can automatically run the testing scripts along with a PUSH action happens. Here we built three integration test yml scripts in nn-Meter/.github/workflows. Regarding the running time of testing for NNI-based torch and ONNX-based torch is long, we split the two test into two scripts file so that the tests can parallel run." }, { "alpha_fraction": 0.696848452091217, "alphanum_fraction": 0.6973486542701721, "avg_line_length": 75.88461303710938, "blob_id": "88625c9bf54cc32ea9fce61fe94307d703c9cb1d", "content_id": "d9b676e58a130a522640de130e53c26af8f22ced", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1999, "license_type": "permissive", "max_line_length": 252, "num_lines": 26, "path": "/docs/ops.md", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Supported Operators\n\nnn-Meter currently supports the major operators in CNN models. The following table lists out the tested operators:\n\n| Type | ops |\n| :---------- | :---------------------------------- |\n| Conv | conv, dwconv |\n| Activations | relu, relu6, sigmoid, swish, hswish |\n| Pooling | avgpool, maxpool, global_avg_pool |\n| FC | fc |\n| BN | bn |\n| others | se, channelshuffle, add, concat |\n\nAccording to our knowledge, the listed operators have already covered the major frequently used ones in CNN models. If there are new operators in your model, please read the followings to decide whether nn-Meter can accurately predict the latency.\n\n## Operators' latency vs final model latency\n\nDue to the limited resources on edge and mobile devices, the latency of Conv related operators dominates the model latency. Therefore, at most cases, the accurate prediction of Conv operators indicate that the predicted model latency is also accurate. \n\nHowever, the predicted model latency may be less accurate on the AI accelerators, since the memory access cost is relatively high, and element-wise operators can take large latency percentages.\n\n## New operators (e.g., self-attention)\n\n* **New inventing operators:** If the new inventing operators are computation-intensive, then you need build the latency predictors for them. (We will opensource the algorithm for building latency predictors for new operators later)\n Otherwise, the new inventing operators are memory-intensive, you can ignore it for mobile CPUs and mobile GPUs. It's better to build the latency predictors for them on AI accelerators.\n* **NLP operators:** The current code has no implementation for the Transformer-based NLP models, and hence we don't have the latency predictors for new operators like self-attention. We plan to support in later versions.\n" }, { "alpha_fraction": 0.3858867883682251, "alphanum_fraction": 0.41622641682624817, "avg_line_length": 30.472684860229492, "blob_id": "5643935e9ef0b3663b510e3177bffe98981c5630", "content_id": "c6ed0b812841e50f50bc65ba2960b1b525302987", "detected_licenses": [ "LicenseRef-scancode-generic-cla", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13250, "license_type": "permissive", "max_line_length": 50, "num_lines": 421, "path": "/nn_meter/prediction/predictors/kernel_predictor.py", "repo_name": "JiahangXu/nn-Meter", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\nfrom sklearn.ensemble import RandomForestRegressor\n\n\ndef get_model(hardware, kernel):\n model = None\n if kernel == \"convbnrelu\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=70,\n n_estimators=320,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=6,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=80,\n n_estimators=550,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n n_jobs=32,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=100,\n n_estimators=500,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n n_jobs=32,\n random_state=10,\n )\n if kernel == \"dwconvbnrelu\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=240,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=6,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=40,\n n_estimators=240,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=7,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=100,\n n_estimators=650,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n n_jobs=32,\n random_state=10,\n )\n if kernel == \"fc\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=70,\n n_estimators=330,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=4,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=70,\n n_estimators=330,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=4,\n oob_score=True,\n n_jobs=32,\n random_state=10,\n )\n if kernel == \"channelshuffle\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if kernel == \"se\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=20,\n n_estimators=290,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=190,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=110,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if kernel == \"maxpool\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=210,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n random_state=10,\n )\n if kernel == \"globalavgpool\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=70,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if kernel == \"hswish\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=190,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=190,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=110,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n\n if kernel == \"avgpool\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=390,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n random_state=10,\n )\n if kernel == \"bnrelu\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=190,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=570,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if kernel == \"relu\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=190,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=190,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if kernel == \"bn\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=370,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=190,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=390,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n if kernel == \"concat\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=100,\n n_estimators=690,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"gpu\":\n model = RandomForestRegressor(\n max_depth=100,\n n_estimators=690,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=5,\n oob_score=True,\n random_state=10,\n )\n\n if kernel == \"addrelu\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=570,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=3,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"addrelu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=570,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=3,\n oob_score=True,\n random_state=10,\n )\n if hardware == \"vpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=570,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=3,\n oob_score=True,\n random_state=10,\n )\n\n if kernel == \"split\":\n if hardware == \"cpu\":\n model = RandomForestRegressor(\n max_depth=50,\n n_estimators=190,\n min_samples_leaf=1,\n min_samples_split=2,\n max_features=2,\n oob_score=True,\n random_state=10,\n )\n\n return model\n" } ]
48
shohin-cloud/first_git
https://github.com/shohin-cloud/first_git
86a9ea7e268dbed5813a96d06d00292b650f5681
311b991a8d9101d693953c47a9eb71bc8a308465
cde0bf89fac637bdd24f7f25f59481e03d3cb908
refs/heads/master
2023-03-13T13:31:47.386123
2021-03-04T11:03:39
2021-03-04T11:03:39
344,443,838
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4098360538482666, "alphanum_fraction": 0.4590163826942444, "avg_line_length": 14.5, "blob_id": "040e7c1b48d6e36806b43b88e11775a898e0f2de", "content_id": "11180953b4cb7e7f0b275df8699768ae416ddeb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 61, "license_type": "no_license", "max_line_length": 24, "num_lines": 4, "path": "/1.py", "repo_name": "shohin-cloud/first_git", "src_encoding": "UTF-8", "text": "s = 0\na = int(input())\nfor i in range (1, a+1):\n s = s + i" } ]
1
BioKIC/NEON-Biorepo-Collections
https://github.com/BioKIC/NEON-Biorepo-Collections
3a90f15d9abccda09966265af571df81eee13423
ee32bbb46269ec829aca2281058fc2077f164701
f61e55bf7cbc269f695c73435f83a5307e6437dd
refs/heads/master
2023-03-30T17:47:18.713825
2021-04-08T21:07:09
2021-04-08T21:07:09
256,298,784
0
1
CC0-1.0
2020-04-16T18:35:12
2020-10-13T21:54:26
2020-10-13T21:54:23
null
[ { "alpha_fraction": 0.7253023982048035, "alphanum_fraction": 0.7444556355476379, "avg_line_length": 25.810810089111328, "blob_id": "43e9cc3d19ffe1d33578ec40d661b9545fe7e66c", "content_id": "ee63deb4a8171ee19ca6115b56780bf04b89e756", "detected_licenses": [ "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1984, "license_type": "permissive", "max_line_length": 149, "num_lines": 74, "path": "/changes.md", "repo_name": "BioKIC/NEON-Biorepo-Collections", "src_encoding": "UTF-8", "text": "## Data changes\n\n# 2021-04, v1.0\n\n- Main \"External\" category now divided in two:\n\n1. \"Additional NEON Collections\": collections belonging to NEON, but hosted in different institutions other than ASU\n2. \"Other Collections from NEON sites\": collections not related to NEON, but with samples collected in the same localities that NEON has\n\n# 2020-07, v1.0\n\n- Additional external collections\n- Minor character encoding fixes\n\n# 2020-06, v1.0\n\n- Minor spelling fixes\n- Availability fixes\n\n## 2020-06, v0.1\n\n### All Collections\n\n- Collections with `collid` in `[7,8,9]` moved to category `Plants`\n- Changed spelling of Algae collections\n- Added field `neontheme` with options:\n\n - Atmosphere\n - Atmosphere, Land Cover & Processes\n - Biogeochemistry, Land Cover & Processes\n - Biogeochemistry, Organisms, Populations, and Communities\n - Organisms, Populations, and Communities\n\n- Added boolean field `available` to display information about availability of samples at ASU\n\n- Removed field `preservation` (Previously parsed from `fullname`)\n- Added field `sampletype` with options:\n\n - DNA Sample\n - Dry Sample\n - Environmental Sample\n - Fluid-Preserved Sample1\n - Frozen Sample\n - Slide-Mounted Sample\n - Tissue or Fecal Sample\n\n- Broke `taxon` field in two fields.\n- Added `highertaxon` field with options:\n\n - Aquatic Invertebrates\n Aquatic plants, bryophytes, lichens, and macroalgae\n - Environmental\n - Microbes\n - Periphyton, seston, and phytoplankton\n - Terrestrial Invertebrates\n - Terrestrial Plants\n - Vertebrates\n\n- Added `lowertaxon` field with options:\n - Aquatic Plant, Bryophyte, and Lichen\n - Benthic Macroinvertebrates\n - Benthic Microbes\n - Carabids\n - Fishes\n - Herptiles\n - Mammals\n - Mosquitoes\n - Other Invertebrates\n - Soil Microbes\n - Surface Water Microbes\n - Ticks\n - Zooplankton\n\nNotes: CSV file was manually produced, as database changes aren't yet in place. JSON file was produced with Python, but arrays were manually encoded.\n" }, { "alpha_fraction": 0.7853170037269592, "alphanum_fraction": 0.7908787727355957, "avg_line_length": 61, "blob_id": "d2e9af03aa26649028a74e30a69958bacb590101", "content_id": "8fb5a489c76fee85732671dcd2eaf4e57b493321", "detected_licenses": [ "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1798, "license_type": "permissive", "max_line_length": 267, "num_lines": 29, "path": "/README.md", "repo_name": "BioKIC/NEON-Biorepo-Collections", "src_encoding": "UTF-8", "text": "# NEON-Biorepo-Collections ![Build Status](https://travis-ci.com/BioKIC/NEON-Biorepo-Collections.svg?branch=api)\n\nSimple, static API exposing information on the [NEON Biorepository Portal](https://biorepo.neonscience.org/) collections.\n\nCurrent version: 1.0 (updated April 2021).\n\nChanges can be implemented at any time. Most current information, as well as archived versions of the data will be available. [Changelog](https://biokic.github.io/NEON-Biorepo-Collections/changes.md).\n\n## The NEON Biorepository\n\nThe [NEON Biorepository](https://biorepo.neonscience.org/) is part of the [Biodiversity Knowledge Integration Center at Arizona State University](https://biokic.asu.edu/), located in Tempe, Arizona, USA.\n\nThe Biorepository missions include storing, curating and managing samples and data associated with samples collected by [The National Ecological Observatory Network](https://www.neonscience.org/).\n\nThe collection information available in this repository pertains to NEON-collected samples that are physically housed at the Biorepository at ASU and elsewhere, and to the associated data available at the [Biorepository Data Portal](https://biorepo.neonscience.org/).\n\n## API\n\n### Get a full list of collections with specimens deposited at the NEON Biorepository at Arizona State University\n\nUse `https://biokic.github.io/NEON-Biorepo-Collections/api/v1_0/collections/`\n\n### Get a full list of external collections with data published in portal (both NEON and non-NEON)\n\nUse `https://biokic.github.io/NEON-Biorepo-Collections/api/v1_0/collections/external`\n\n## CSV Data\n\nExplore or download full lists from [data directory](./data). The most current version of each dataset will be dated in the root, and archived versions will be found in the [archive subdirectory](./data/archive/).\n" }, { "alpha_fraction": 0.7868852615356445, "alphanum_fraction": 0.7868852615356445, "avg_line_length": 29.5, "blob_id": "509e9a698693f5970929b9675a2c70531dcd6569", "content_id": "02c493a8505fd5dcaefe94dff4c6a5b0eae1540d", "detected_licenses": [ "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 61, "license_type": "permissive", "max_line_length": 37, "num_lines": 2, "path": "/updateapi.py", "repo_name": "BioKIC/NEON-Biorepo-Collections", "src_encoding": "UTF-8", "text": "# Import files as changes are pushed \nimport colls, external\n" }, { "alpha_fraction": 0.7011070251464844, "alphanum_fraction": 0.7146371603012085, "avg_line_length": 30.30769157409668, "blob_id": "88f208f5bae01e4052380fb81e4295444649638c", "content_id": "8fc2ba5d188ef5481246d4e94db3294242f652ab", "detected_licenses": [ "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 813, "license_type": "permissive", "max_line_length": 69, "num_lines": 26, "path": "/external.py", "repo_name": "BioKIC/NEON-Biorepo-Collections", "src_encoding": "UTF-8", "text": "import os, csv, json\n# ***** Configure generator ******\nversion = \"1_0\"\ngroupBy = \"collections\"\nstructure = os.path.join(\"api\", \"v\"+version, groupBy, \"external\")\n\ninputFilename = \"all-colls-external-20210408.csv\"\noutputFilename = \"index.json\"\n\ninputfile = os.path.abspath(os.path.join(\"data\", inputFilename))\noutputfile = os.path.abspath(os.path.join(structure, outputFilename))\n\nos.makedirs(os.path.dirname(outputfile), exist_ok=True)\n\n# # Read the CSV and add data to a dictionary\nwith open(inputfile) as csvFile:\n csvReader = csv.DictReader(csvFile)\n\n # Add data to a root node\n root = {}\n root[groupBy] = [row for row in csvReader]\n\n # # Write data to JSON file\n with open(outputfile, \"w\") as jsonFile:\n jsonFile.write(json.dumps(root, indent=4))\n print(\"Created JSON file for external collections\")" } ]
4
huning2009/quantitive-investment-strategy-
https://github.com/huning2009/quantitive-investment-strategy-
03fe1231f8136ed3fc9eb18c6366f31da851958c
89b80ad1a3d935d701496ae007838c8eb22e140b
cc5e0d25e4eb08bef5bb29e57e353327f1ef8493
refs/heads/master
2021-05-20T23:37:21.600714
2020-03-09T02:34:10
2020-03-09T02:34:10
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.41804754734039307, "alphanum_fraction": 0.45566603541374207, "avg_line_length": 36.4720344543457, "blob_id": "7b5a3fee2a317799027d93e9c714aaf371c8f6a3", "content_id": "e99070271e1beab085311317c65c65754ccfa110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18742, "license_type": "no_license", "max_line_length": 121, "num_lines": 447, "path": "/data0_0.py", "repo_name": "huning2009/quantitive-investment-strategy-", "src_encoding": "UTF-8", "text": "from jqdatasdk import *\r\nauth('15918636606', 'Ucb16697')\r\nimport numpy as np\r\nimport datetime\r\nimport gc\r\nimport math\r\nimport pandas as pd\r\nimport time\r\nfrom dateutil.relativedelta import relativedelta\r\n\r\nclass data:\r\n # 获取每天的行情数据,以 前x周的数据 判断一周后的价格变动(上涨还是下跌)\r\n # (休市的日期是跳过的)\r\n def __init__(self, index=['000001.XSHG', '000002.XSHG', '000016.XSHG',\r\n '000903.XSHG', '000904.XSHG', '000905.XSHG',\r\n '000906.XSHG', '000907.XSHG', '399001.XSHE', '399004.XSHE',\r\n '399005.XSHE', '399006.XSHE', '399009.XSHE',\r\n '399010.XSHE', '399011.XSHE', '399310.XSHE', '399310.XSHE',\r\n '399310.XSHE', '000852.XSHG', '000300.XSHG'],\r\n start_date='2012-05-31', end_date='2018-01-01', frequency='daily'):\r\n self.start_date = start_date\r\n self.end_date = end_date\r\n # 由聚宽平台获取指数历史行情\r\n # 返回行索引为日期,列索引为数据字段的dataframe\r\n\r\n self.index_data1 = get_price(security=index[0], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data2 = get_price(security=index[1], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data3 = get_price(security=index[2], start_date=start_date, end_date=end_date, frequency=frequency)\r\n\r\n self.index_data4 = get_price(security=index[3], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data5 = get_price(security=index[4], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data6 = get_price(security=index[5], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data7 = get_price(security=index[6], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data8 = get_price(security=index[7], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data9 = get_price(security=index[8], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data10 = get_price(security=index[9], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data11 = get_price(security=index[10], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data12 = get_price(security=index[11], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data13 = get_price(security=index[12], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data14 = get_price(security=index[13], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data15 = get_price(security=index[14], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data16 = get_price(security=index[15], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data17 = get_price(security=index[16], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data18 = get_price(security=index[17], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data19 = get_price(security=index[18], start_date=start_date, end_date=end_date, frequency=frequency)\r\n self.index_data20 = get_price(security=index[19], start_date=start_date, end_date=end_date, frequency=frequency)\r\n\r\n # 储存每个特征的平均值和标准差\r\n self.mean = []\r\n self.std = []\r\n\r\n\r\n\r\n\r\n self.data = {0: {}, 1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}, 8: {}, 9: {}, 10: {}, 11: {}, 12:{}, 13:{},\r\n 14:{}, 15:{}, 16:{}, 17:{}, 18:{}, 19:{}}\r\n self.label = {0: {}, 1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}, 8: {}, 9: {}, 10: {}, 11: {}, 12:{}, 13:{},\r\n 14:{}, 15:{}, 16:{}, 17:{}, 18:{}, 19:{}}\r\n\r\n # 训练输入\r\n self.x_train = []\r\n # 训练标签\r\n self.y_train = []\r\n # 测试输入\r\n self.x_test = []\r\n # 测试标签\r\n self.y_test = []\r\n\r\n # 一些技术指标\r\n def ema(self, p, n=26):\r\n # p为对应区间的 股票/大盘指数 收盘价的列表\r\n if n == len(p):\r\n alpha = 2 / (n + 1)\r\n emavalue = p[0]\r\n for i in range(1, n):\r\n emavalue = alpha * (p[i] - emavalue) + emavalue\r\n # EMAtoday=α*(Pricetoday-EMAyesterday)+EMAyesterday\r\n return emavalue\r\n else:\r\n if n > len(p):\r\n n = len(p)\r\n alpha = 2 / (n + 1)\r\n emavalue = p[0]\r\n for i in range(1, n):\r\n emavalue = alpha * (p[i] - emavalue) + emavalue\r\n # EMAtoday=α*(Pricetoday-EMAyesterday)+EMAyesterday\r\n return emavalue\r\n\r\n def macd(self, p, n1=6, n2=12, n3=9, n=26):\r\n # n1为EMA1的参数(常取12),n2为EMA2的参数(常取26),n3为DIF的参数(常取9),n为区间长度,p为对应时间区间内股票收盘价的列表\r\n # 返回值依次为dif,dea,macd\r\n dif = []\r\n try:\r\n for i in range(n - n3, n):\r\n ema1 = self.ema(p[i - n1 + 1:i + 1], n1)\r\n ema2 = self.ema(p[i - n2 + 1:i + 1], n2)\r\n # R表示对于时间区间的每日价格列表\r\n dif.append(ema1 - ema2)\r\n return [dif[-1], self.ema(dif, n3), dif[-1] - self.ema(dif, n3)]\r\n except:\r\n return [None, None, None]\r\n\r\n def rsi(self, p, n=26):\r\n # n为周期(默认为26天),p为对应时间区间内的每日收盘价格列表,需利用接口\r\n try:\r\n rise = 0\r\n drop = 0\r\n for i in range(1, n):\r\n if p[i] >= p[i - 1]:\r\n rise = rise + (p[i] - p[i - 1])\r\n else:\r\n drop = drop + (p[i - 1] - p[i])\r\n # rise为n日内收盘涨幅之和,drop为n日内收盘跌幅之和\r\n if (rise + drop) != 0:\r\n return (100 * rise) / (rise + drop)\r\n else:\r\n return 50\r\n except:\r\n return None\r\n\r\n def llt(self, p, n=26): # (聚宽课堂上面的啥二阶滤波器,不知道啥玩意,随便拿来用一下), p为对应时间的收盘价列表\r\n list = []\r\n try:\r\n alpha = 2 / 35\r\n list.append(self.ema([p[0]], 1))\r\n list.append(self.ema(p[0:2], 2))\r\n for i in range(2, n):\r\n list.append((alpha - alpha * alpha / 4) * p[i] + (alpha * alpha / 2) * p[i - 1] - (\r\n alpha - 3 * alpha * alpha / 4) * p[i - 2]\r\n + 2 * (1 - alpha) * list[i - 1] - (1 - alpha) * (1 - alpha) * list[i - 2])\r\n return list[-1]\r\n except:\r\n return None\r\n\r\n def kdj(self, cn, hn, ln, n=26):\r\n # n为周期,cn为第n日的收盘价,hn和ln分别为此n日的最高价和最低价,需利用接口\r\n try:\r\n if hn != ln:\r\n rsv = 100 * (cn - ln) / (hn - ln)\r\n else:\r\n rsv = 100\r\n k = d = j = 0\r\n for i in range(1, n):\r\n k = (2 / 3) * k + (1 / 3) * rsv\r\n d = (2 / 3) * d + (1 / 3) * k\r\n j = 3 * d - 2 * k\r\n return [k, d, j]\r\n except:\r\n return [None, None, None]\r\n\r\n def obv(self, v, c):\r\n # n为周期,v为对于时间区间内的成交量列表,c为对应的收盘价列表\r\n n = len(v)\r\n obvvalue = 0\r\n for i in range(1, n):\r\n if c[i] > c[i-1]:\r\n obvvalue = obvvalue + v[i]\r\n if c[i] < c[i-1]:\r\n obvvalue = obvvalue - v[i]\r\n return obvvalue\r\n\r\n def boll(self, c, n=26):\r\n try:# n为周期,c为对应的时间区间内的收盘价列表\r\n sp1 = 0\r\n for i in range(0, n):\r\n sp1 = sp1 + c[i] # n日收盘价之和\r\n ma = sp1 / n # n日内的收盘价之和÷n\r\n sp2 = 0\r\n for i in range(1, n):\r\n sp2 = sp2 + c[i]\r\n mb = sp2 / (n - 1) # 价格线,(n-1)日的ma\r\n sp3 = 0\r\n for i in range(0, n):\r\n sp3 = sp3 + (c[i] - ma) * (c[i] - ma)\r\n md = math.sqrt(sp3 / n) # 平方根n日的(c[i]-MA)的两次方之和除以n\r\n up = mb + 2 * md # 上轨线UP是UP数值的连线,用黄色线表示\r\n dn = mb - 2 * md # 下轨线DN是DN数值的连线,用紫色线表示\r\n return [up, dn, mb]\r\n except:\r\n return [None, None, None]\r\n\r\n def trix(self, p, n1=9, n2=12):\r\n try:\r\n # n1为ema参数,n2为trix参数,p是对应时间区间内的收盘价列表\r\n tr = []\r\n sp = 0\r\n for i in range(0, n2):\r\n p1 = p[i: n1 + i]\r\n tr.append(self.ema(p1, n1))\r\n for i in range(0, n2 - 1):\r\n sp = sp + ((tr[i+1] - tr[i]) / tr[i+1] * 100)\r\n return sp/n2\r\n except:\r\n return None\r\n\r\n def ar(self, c, h, l):\r\n try:\r\n # 对应时间区间内的每日收盘,最高,最低价列表\r\n arvalue1 = arvalue2 = 0\r\n for i in range(0, len(c)):\r\n arvalue1 = arvalue1 + (h[i] - c[i])\r\n arvalue2 = arvalue2 + (c[i] - l[i])\r\n if arvalue2 != 0:\r\n return arvalue1/arvalue2\r\n elif arvalue1 != 0:\r\n return arvalue1/0.001\r\n else:\r\n return 1\r\n except:\r\n return None\r\n\r\n def br(self, c, h, l):\r\n try:\r\n # 对应时间区间内的每日收盘,最高,最低价列表\r\n brvalue1 = brvalue2 = 0\r\n for i in range(1, len(c)):\r\n brvalue1 = brvalue1 + (h[i] - c[i-1])\r\n brvalue2 = brvalue2 + (c[i-1] - l[i])\r\n if brvalue2 != 0:\r\n brvalue = brvalue1/brvalue2\r\n elif brvalue1 != 0:\r\n brvalue = brvalue1/0.00001\r\n else:\r\n brvalue = 1\r\n return brvalue\r\n except:\r\n return None\r\n\r\n def cmo(self, c, n=26): # n为周期,c为对应区间内的收盘价列表\r\n try:\r\n su = sd = 0\r\n for i in range(1, n):\r\n if c[i] >= c[i - 1]:\r\n su = su + c[i] - c[i - 1]\r\n else:\r\n sd = sd + c[i - 1] - c[i]\r\n if (su + sd) != 0:\r\n return 100 * (su - sd) / (su + sd)\r\n else:\r\n return 0\r\n except:\r\n return None\r\n\r\n def cr(self, o, c, h, l):\r\n # n为周期,o,c,h,l分别对应对应区间内的开盘,收盘,最高,最低价\r\n n = len(c)\r\n p1 = p2 = 0\r\n for i in range(1, n):\r\n m = (c[i-1] + o[i-1] + h[i-1] + l[i-1])/4\r\n p1 = p1 + h[i] - m\r\n p2 = p2 + m - l[i]\r\n if p2 != 0:\r\n return 100 * (p1/p2)\r\n elif p1 != 0:\r\n return 100 * (p1/0.001)\r\n else:\r\n return 100\r\n\r\n def dma(self, p, n1=6, n2=12):\r\n try:\r\n # n1为短期平均参数,n2为长期平均参数,n为区间长度,p为对应区间内的股票收盘价列表\r\n n = len(p)\r\n long = short = 0\r\n for i in range(n - n2, n):\r\n long = long + p[i]\r\n for i in range(n - n1, n):\r\n short = short + p[i]\r\n long = long/n2\r\n short = short/n1\r\n return short - long\r\n except:\r\n return None\r\n\r\n\r\n\r\n # 整理数据\r\n def get_data(self):\r\n # 最外层data是一个字典,其中key为日期,value为每日前十五日的每日行情数据序列(特征)\r\n # 添加技术因子\r\n\r\n\r\n for n in range(20):\r\n #for index_data in [self.index_data1, self.index_data2, self.index_data3]:\r\n index_data = [self.index_data1, self.index_data2, self.index_data3, self.index_data4,\r\n self.index_data5, self.index_data6, self.index_data7, self.index_data8,\r\n self.index_data9, self.index_data10, self.index_data11, self.index_data12,\r\n self.index_data13, self.index_data14,\r\n self.index_data15, self.index_data16, self.index_data17, self.index_data18,\r\n self.index_data19, self.index_data20][n]\r\n macd1 = []\r\n macd2 = []\r\n macd3 = []\r\n rsi = []\r\n llt = []\r\n k = []\r\n d = []\r\n j = []\r\n ema = []\r\n obv = []\r\n up = []\r\n dn = []\r\n mb = []\r\n trix = []\r\n ar = []\r\n br = []\r\n cmo = []\r\n cr = []\r\n dma = []\r\n\r\n for i in range(index_data.shape[0]):\r\n p = (index_data['close'].values.tolist())[max(0, i - 25):i + 1]\r\n open = (index_data['open'].values.tolist())[max(0, i - 25):i + 1]\r\n low = (index_data['low'].values.tolist())[max(0, i - 25):i + 1]\r\n high = (index_data['high'].values.tolist())[max(0, i - 25):i + 1]\r\n lowest = np.min(low)\r\n highest = np.max(high)\r\n volume = (index_data['volume'].values.tolist())[max(0, i - 25):i + 1]\r\n\r\n macd1.append(self.macd(p)[0])\r\n macd2.append(self.macd(p)[1])\r\n macd3.append(self.macd(p)[2])\r\n rsi.append(self.rsi(p))\r\n llt.append(self.llt(p))\r\n k.append(self.kdj(p[-1], highest, lowest)[0])\r\n d.append(self.kdj(p[-1], highest, lowest)[1])\r\n j.append(self.kdj(p[-1], highest, lowest)[2])\r\n ema.append(self.ema(p))\r\n obv.append(self.obv(volume, p))\r\n up.append(self.boll(p)[0])\r\n dn.append(self.boll(p)[1])\r\n mb.append(self.boll(p)[2])\r\n trix.append(self.trix(p))\r\n ar.append(self.ar(p, high, low))\r\n br.append(self.br(p, high, low))\r\n cmo.append(self.cmo(p))\r\n cr.append(self.cr(open, p, high, low))\r\n dma.append(self.dma(p))\r\n\r\n\r\n #TODO:取对数?\r\n #self.index_data = self.index_data.apply(lambda x: np.log(x))\r\n\r\n #TODO: 加入技术指标?\r\n index_data['macd1'] = macd1\r\n index_data['macd2'] = macd2\r\n index_data['macd3'] = macd3\r\n index_data['rsi'] = rsi\r\n index_data['llt'] = llt\r\n index_data['k'] = k\r\n index_data['d'] = d\r\n index_data['j'] = j\r\n index_data['ema'] = ema\r\n index_data['obv'] = obv\r\n index_data['up'] = up\r\n index_data['dn'] = dn\r\n index_data['mb'] = mb\r\n index_data['trix'] = trix\r\n index_data['ar'] = ar\r\n index_data['br'] = br\r\n index_data['cmo'] = cmo\r\n index_data['cr'] = cr\r\n index_data['dma'] = dma\r\n\r\n index_data = index_data.dropna(axis=0, how='any')\r\n\r\n if n == 19:\r\n index_data.to_csv('./data.csv')\r\n\r\n\r\n self.mean = (index_data.apply(np.mean)).tolist()\r\n self.std = (index_data.apply(np.std)).tolist()\r\n\r\n # 数据预处理(标准化)\r\n post_index_data = index_data.apply(lambda x: (x - np.mean(x)) / np.std(x))\r\n # self.od = self.index_data.values\r\n\r\n\r\n for i in range(30, post_index_data.shape[0] - 7): # 隔5个交易日(一周)取一次样\r\n\r\n date_time = datetime.datetime.strptime((post_index_data.index[i])._date_repr, '%Y-%m-%d')\r\n seq = []\r\n # 前5*j天的每一天数据都加入序列中\r\n for d in range(5 * 3):\r\n seq.append(post_index_data.iloc[i - 5 * 3 + d])\r\n self.data[n][date_time] = seq\r\n # label是一个字典,其中key为日期,value为该日对应的标签\r\n\r\n close_list = []\r\n for d in range(5):\r\n close_list.append(index_data.iloc[i + 1 + d]['close'])\r\n\r\n #f = self.fluct(close_list)\r\n\r\n if index_data.iloc[i+1]['llt'] > 1.0001*index_data.iloc[i]['llt']:\r\n self.label[n][date_time] = 1\r\n\r\n if index_data.iloc[i+1]['llt'] < 0.92*index_data.iloc[i]['llt']:\r\n self.label[n][date_time] = 0\r\n\r\n\r\n\r\n\r\n\r\n #数据划分,分出训练集和测试集(特征及标签)\r\n def divide_data(self):\r\n\r\n for n in range(20):\r\n day = datetime.datetime.strptime(self.start_date, '%Y-%m-%d')\r\n while day < datetime.datetime.strptime(self.end_date, '%Y-%m-%d'):\r\n if day in self.label[n].keys():\r\n # 6月,9月及12月的数据划入测试集\r\n if day.month >= 13:\r\n self.x_test.append(self.data[n][day])\r\n self.y_test.append(self.label[n][day])\r\n\r\n # 其他月份作为训练集\r\n else:\r\n self.x_train.append(self.data[n][day])\r\n self.y_train.append(self.label[n][day])\r\n\r\n day = day + datetime.timedelta(days=1)\r\n\r\n\r\n# 训练过程中的采样函数,j为batch中的序列长度\r\n def get_mini_batch(self, batch_size):\r\n batch_x = []\r\n batch_y = []\r\n index_list = []\r\n i = 0\r\n while i < batch_size:\r\n # 产生随机数作索引以随机取样\r\n index = np.random.randint(low=0, high=len(self.x_train))\r\n\r\n # 避免重复\r\n if index not in index_list:\r\n batch_x.append(self.x_train[index])\r\n batch_y.append(self.y_train[index])\r\n i = i + 1\r\n index_list.append(index)\r\n\r\n # batch_x.append(self.x_train[j][index])\r\n # batch_y.append(self.y_train[j][index])\r\n #i = i + 1\r\n del i\r\n del index_list\r\n gc.collect()\r\n return batch_x, batch_y\r\n\r\n" }, { "alpha_fraction": 0.46067923307418823, "alphanum_fraction": 0.497735857963562, "avg_line_length": 46.357666015625, "blob_id": "6e297f626b71ae24d4b7fad53a5aa3c0c441b6d7", "content_id": "6d434064bb9f59a6ec2857dcd2107a55a36d6b63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13726, "license_type": "no_license", "max_line_length": 153, "num_lines": 274, "path": "/model0_0.py", "repo_name": "huning2009/quantitive-investment-strategy-", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow.contrib.layers.python.layers import initializers\r\nfrom data0_0 import data\r\nimport gc\r\nfrom tensorflow.python.framework import graph_util\r\nfrom tensorflow.python.platform import gfile\r\n\r\nclass ml_model(data):\r\n def __init__(self, index=['000001.XSHG', '000002.XSHG', '000016.XSHG',\r\n '000903.XSHG', '000904.XSHG', '000905.XSHG',\r\n '000906.XSHG', '000907.XSHG', '399001.XSHE', '399004.XSHE',\r\n '399005.XSHE', '399006.XSHE', '399009.XSHE',\r\n '399010.XSHE', '399011.XSHE', '399310.XSHE', '399310.XSHE',\r\n '399310.XSHE', '000852.XSHG', '000300.XSHG'], start_date='2012-05-31', end_date='2019-05-31', frequency='daily'):\r\n data.__init__(self, index, start_date, end_date, frequency)\r\n self.batch_size = 64\r\n self.saver = None\r\n\r\n # 模型超参数\r\n self.num_units = 96 # lstm单元隐藏层细胞数量,即Wx和Wh的行数\r\n self.learning_rate = 0.005 # 学习率\r\n self.epoch = 50 # 训练轮数\r\n self.numda = 0.0001 # L2正则化系数\r\n\r\n\r\n\r\n\r\n\r\n # lstm网路单元\r\n def lstm_model(self):\r\n with tf.variable_scope(name_or_scope='lstm_model', reuse=tf.AUTO_REUSE):\r\n # 输入\r\n # 特征数量为25,batch_size,seq_length并不固定\r\n x = tf.placeholder(shape=(None, None, 25), name='input', dtype=tf.float64)\r\n print(x.name)\r\n # 占位符,说明是否正在训练(影响batch_normalization层)\r\n is_training = tf.placeholder(name='is_training', dtype=tf.bool)\r\n\r\n # lstm构造\r\n lstm_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_units, initializer=tf.orthogonal_initializer(),\r\n num_proj=48, reuse=tf.AUTO_REUSE,\r\n name='lstm_cell', activation='sigmoid')\r\n #lstm_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_units, initializer=tf.random_normal_initializer(),\r\n #num_proj = 48, reuse = tf.AUTO_REUSE,\r\n #name = 'lstm_cell', activation = 'sigmoid')\r\n c = (tf.nn.dynamic_rnn(cell=lstm_cell, inputs=x, dtype=tf.float64))[0][:, -1, :]\r\n\r\n with tf.variable_scope(name_or_scope='fully_connection', reuse=tf.AUTO_REUSE):\r\n # 全连接层\r\n b_1 = tf.get_variable(name='bias_1', dtype=tf.float64, initializer=tf.constant(value=np.zeros((16,)), dtype=tf.float64))\r\n w_1 = tf.get_variable(name='weight_1', shape=(48, 16), dtype=tf.float64,\r\n initializer=initializers.xavier_initializer())\r\n\r\n b_2 = tf.get_variable(name='bias_2', dtype=tf.float64, initializer=tf.constant(value=np.zeros((2,)), dtype=tf.float64))\r\n w_2 = tf.get_variable(name='weight_2', shape=(16, 2), dtype=tf.float64,\r\n initializer=initializers.xavier_initializer())\r\n #w = tf.get_variable(name='weight', shape=(32, 2), dtype=tf.float64,\r\n #initializer=tf.random_normal_initializer())\r\n\r\n c2 = tf.matmul(c, w_1) + b_1\r\n # batch normalization层\r\n batch_norm = tf.layers.batch_normalization(inputs=tf.matmul(c2, w_2) + b_2, training=is_training, name='batch_norm',\r\n epsilon=0)\r\n # 激活函数加softmax输出概率 [P涨,P跌]\r\n # tanh_output = tf.tanh(batch_norm, 'tanh')\r\n # output = tf.nn.softmax(tanh_output)\r\n leaky_relu_output = tf.nn.leaky_relu(features=batch_norm, alpha=0.2, name='relu')\r\n output = tf.nn.softmax(logits=leaky_relu_output, name='output')\r\n\r\n\r\n # 返回模型输出值,和占位符\r\n return output, x, is_training\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n # 训练\r\n def train(self):\r\n train_graph = tf.Graph()\r\n with train_graph.as_default():\r\n output, x, is_training = self.lstm_model()\r\n # 训练集的标签\r\n y = tf.placeholder(shape=(None, ), name='label', dtype=tf.float64)\r\n print(y.name)\r\n # 参数L2正则化减少过拟合\r\n reg = tf.contrib.layers.apply_regularization(tf.contrib.layers.l2_regularizer(self.numda), tf.trainable_variables())\r\n # 损失函数计算(交叉熵加L2正则化)\r\n cse = tf.convert_to_tensor(value=0, dtype=tf.float64)\r\n for i in range(self.batch_size):\r\n cse = cse - 0.61022*tf.multiply(y[i], tf.log(output[i][0])) - 2.76825*tf.multiply(1 - y[i], tf.log(output[i][1]))\r\n cse = cse/self.batch_size\r\n cse = cse + reg\r\n\r\n # 准确率计算\r\n acc_num = tf.convert_to_tensor(0)\r\n n = tf.convert_to_tensor(0)\r\n for i in range(self.batch_size):\r\n acc1 = tf.convert_to_tensor(0)\r\n acc2 = tf.convert_to_tensor(0)\r\n #acc3 = tf.convert_to_tensor(0)\r\n n = tf.cond(pred=tf.equal(y[i], 0),\r\n true_fn=lambda: tf.add(n, 1), false_fn=lambda: tf.add(n, 0))\r\n acc1 = tf.cond(pred=tf.logical_and(tf.equal(y[i], 1),\r\n tf.greater(output[i][0], output[i][1])\r\n ),\r\n true_fn=lambda: tf.add(acc1, 1), false_fn=lambda: tf.add(acc1, 0))\r\n acc2 = tf.cond(pred=tf.logical_and(tf.equal(y[i], 0),\r\n tf.greater(output[i][1], output[i][0])\r\n ),\r\n true_fn=lambda: tf.add(acc2, 1), false_fn=lambda: tf.add(acc2, 0))\r\n acc_num = acc_num + acc1 + acc2\r\n #acc_num = acc_num + acc2\r\n acc = acc_num / self.batch_size\r\n #acc = acc_num / n\r\n #acc3 = tf.cond(pred=tf.logical_and(tf.equal(y[i][2], 1),\r\n # tf.logical_and(tf.greater(output[i][2], output[i][0]),\r\n # tf.greater(output[i][2], output[i][1]))),\r\n # true_fn=lambda: tf.add(acc3, 1), false_fn=lambda: tf.add(acc3, 0))\r\n #acc_num = acc_num + acc1 + acc2 + acc3\r\n\r\n\r\n # 批量梯度下降(Adam?)优化损失函数,好像Adam更好一些\r\n optimizer_1 = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)\r\n optimizer_2 = tf.train.AdamOptimizer(learning_rate=self.learning_rate)\r\n\r\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n with tf.control_dependencies(update_ops):\r\n train_op_1 = optimizer_1.minimize(loss=cse)\r\n train_op_2 = optimizer_2.minimize(loss=cse)\r\n\r\n '''\r\n var_list = []\r\n list_2 = []\r\n for v in tf.global_variables():\r\n if v in tf.trainable_variables():\r\n var_list.append(v)\r\n else:\r\n list_2.append(v)\r\n saver = tf.train.Saver(var_list=var_list)\r\n '''\r\n\r\n saver = tf.train.Saver()\r\n # 开启session,载入最后报存的模型\\初始化模型\r\n sess = tf.Session()\r\n\r\n # 以下两行可用作开启第一次训练与延续上一次训练之间切换\r\n #sess.run(tf.global_variables_initializer())\r\n saver.restore(sess=sess, save_path=\"C:\\\\Users\\\\Jason\\\\Desktop\\\\hengqin quant finance\\\\saved_model1_0\\\\lstm_model-00.3\")\r\n #sess.run(tf.variables_initializer(list_2))\r\n\r\n\r\n for i in range(self.epoch):\r\n # 获取minibatch\r\n batch_x, batch_y = self.get_mini_batch(self.batch_size)\r\n\r\n # 训练,返回损失函数值\r\n if i == 0:\r\n print(sess.run((cse, sess.graph.get_tensor_by_name('fully_connection/relu:0'), output), {x: batch_x, y: batch_y, is_training: True}))\r\n sess.run(fetches=train_op_2, feed_dict={x: batch_x, y: batch_y, is_training: True})\r\n else:\r\n print(sess.run((cse, acc), {x: batch_x, y: batch_y, is_training: True}))\r\n sess.run(fetches=train_op_2, feed_dict={x: batch_x, y: batch_y, is_training: True})\r\n saver.save(sess=sess,\r\n save_path='C:\\\\Users\\\\Jason\\\\Desktop\\\\hengqin quant finance\\\\saved_model1_0\\\\lstm_model-00.3')\r\n #saver.save(sess=sess,\r\n # save_path='./lstm_model-00.1')\r\n\r\n\r\n\r\n '''\r\n builder = tf.saved_model.builder.SavedModelBuilder('./lstm_saved_model')\r\n builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.TRAINING])\r\n builder.save()\r\n '''\r\n varlist = [v.name[:-2] for v in tf.global_variables()]\r\n varlist.append('fully_connection/output')\r\n varlist.append('lstm_model/input')\r\n varlist.append('label')\r\n varlist.append('lstm_model/is_training')\r\n\r\n print(varlist)\r\n\r\n constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, varlist)\r\n with tf.gfile.FastGFile('./lstm_model_5.pb', mode='wb') as f:\r\n\r\n f.write(constant_graph.SerializeToString())\r\n\r\n sess.close()\r\n\r\n # 测试\r\n def test(self, x_test, y_test):\r\n\r\n test_graph = tf.Graph()\r\n with test_graph.as_default():\r\n output, x, is_training = self.lstm_model()\r\n # 测试集的标签\r\n y = tf.placeholder(shape=(None,), name='label', dtype=tf.float64)\r\n # 准确率计算\r\n acc_num = tf.convert_to_tensor(0)\r\n n = tf.convert_to_tensor(0)\r\n for i in range(len(x_test)):\r\n acc1 = tf.convert_to_tensor(0)\r\n acc2 = tf.convert_to_tensor(0)\r\n # acc3 = tf.convert_to_tensor(0)\r\n n = tf.cond(pred=tf.equal(y[i], 0),\r\n true_fn=lambda: tf.add(n, 1), false_fn=lambda: tf.add(n, 0))\r\n acc1 = tf.cond(pred=tf.logical_and(tf.equal(y[i], 1),\r\n tf.greater(output[i][0], output[i][1]),\r\n ),\r\n true_fn=lambda: tf.add(acc1, 1), false_fn=lambda: tf.add(acc1, 0))\r\n acc2 = tf.cond(pred=tf.logical_and(tf.equal(y[i], 0),\r\n tf.greater(output[i][1], output[i][0])\r\n ),\r\n true_fn=lambda: tf.add(acc2, 1), false_fn=lambda: tf.add(acc2, 0))\r\n #acc_num = acc_num + acc1 + acc2\r\n acc_num = acc_num + acc2\r\n #acc = acc_num/len(x_test)\r\n acc = acc_num/n\r\n\r\n saver = tf.train.Saver()\r\n # 开启session,载入最新模型\r\n sess = tf.Session()\r\n #sess.run(tf.global_variables_initializer())\r\n saver.restore(sess=sess, save_path=\"C:\\\\Users\\\\Jason\\\\Desktop\\\\hengqin quant finance\\\\saved_model1_0\\\\lstm_model-00.3\")\r\n\r\n print(sess.run(fetches=(acc, output, sess.graph.get_tensor_by_name('fully_connection/relu:0')),\r\n feed_dict={x: x_test, y: y_test, is_training: False}))\r\n\r\n\r\n '''\r\n sess = tf.Session()\r\n with gfile.FastGFile('./lstm_model_1.pb', 'rb') as f:\r\n graph_def = tf.GraphDef()\r\n graph_def.ParseFromString(f.read())\r\n sess.graph.as_default()\r\n tf.import_graph_def(graph_def, name='') # 导入计算图\r\n print(sess.run(fetches=(sess.graph.get_tensor_by_name('fully_connection/output:0')),\r\n feed_dict={sess.graph.get_tensor_by_name('lstm_model/input:0'): x_test,\r\n sess.graph.get_tensor_by_name('label:0'): y_test,\r\n sess.graph.get_tensor_by_name('lstm_model/is_training:0'): False}))\r\n '''\r\n # 预测\r\n def predict(self, x_predict):\r\n predict_graph = tf.Graph()\r\n with predict_graph.as_default():\r\n output, x, is_training = self.lstm_model()\r\n\r\n saver = tf.train.Saver()\r\n # 开启session\r\n sess = tf.Session()\r\n saver.restore(sess=sess, save_path=\"C:\\\\Users\\\\Jason\\\\Desktop\\\\hengqin quant finance\\\\saved_model1_0\\\\lstm_model-00.1\")\r\n o = sess.run(fetches=output, feed_dict={x: x_predict, is_training: False})\r\n sess.close()\r\n print(o)\r\n return o\r\n\r\nmodel = ml_model(index=['000001.XSHG', '000002.XSHG', '000016.XSHG',\r\n '000903.XSHG', '000904.XSHG', '000905.XSHG',\r\n '000906.XSHG', '000907.XSHG', '399001.XSHE', '399004.XSHE',\r\n '399005.XSHE', '399006.XSHE', '399009.XSHE',\r\n '399010.XSHE', '399011.XSHE', '399310.XSHE', '399310.XSHE',\r\n '399310.XSHE', '000852.XSHG', '000300.XSHG'], start_date='2012-01-01', end_date='2018-01-01', frequency='daily')\r\n\r\nmodel.get_data()\r\nmodel.divide_data()\r\n\r\nmodel.train()\r\n\r\n#model.test(x_test=model.x_test, y_test=model.y_test)\r\n" }, { "alpha_fraction": 0.7547826170921326, "alphanum_fraction": 0.7886956334114075, "avg_line_length": 94.75, "blob_id": "5fb90f8743ae0c1810d668b38d7b2fc051de6f6f", "content_id": "9f6bebfe8dc197cbe1806a1ecd1a67768263690b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 320, "num_lines": 12, "path": "/README.md", "repo_name": "huning2009/quantitive-investment-strategy-", "src_encoding": "UTF-8", "text": "# stock investment strategy based on deep learning\nThis is the code of the timeing part of'LSTM加LLT加多因子' on【JoinQuant】https://www.joinquant.com/algorithm/live/liveUrlShareIndex?backtestId=678ee450e975016a28945ad05114dbdd (password:gblxjo)\n\nHere I utilized the daily data of 20 index on the Chinese stock market form 2012 to 2018.\n\nWith those data, I construted features like 'RSI', 'KDJ', 'MACD', etc. I concatenate those feature vectors everyday into a time series of length 15.Then I applied the 'LLT' filter to reduce noise, and label the index as 1 if its 'LLT' value goes up in the day after the end of the time series or label it as 0 otherwise.\n\nWith the features and labels, I built a LSTM network to fit them and thus derived a model that can be used to predict the market trend with the market data of the past 15 days as an input.\n\nThe LSTM model is saved as lstm_model_4.pb\n\nInteresting empirical finding: It is less likely that the stock price goes down in consecutive days, nor the model makes that prediction correctly consucutively. So if turn up the signal to bid after closing out, the strategy will make much more profits. \n" } ]
3
nestornav/beautifulsoup-demo
https://github.com/nestornav/beautifulsoup-demo
1fc18811584e4ffae9382e58c968a70f123dac35
d73d4d758bfba5f37a220868b3f9b3f7fc70dabf
10afefb9a0d13b01d633c216436d67952b34ff5c
refs/heads/master
2021-01-10T07:06:06.920209
2016-03-19T23:51:54
2016-03-19T23:51:54
51,252,078
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6540447473526001, "alphanum_fraction": 0.6660929322242737, "avg_line_length": 29.63157844543457, "blob_id": "950be49dbb9b2fe8ce23c291c3b2311d14f50a0c", "content_id": "f1bf36347075f1b162ff2eb1c7abced532dce1ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 581, "license_type": "no_license", "max_line_length": 90, "num_lines": 19, "path": "/main.py", "repo_name": "nestornav/beautifulsoup-demo", "src_encoding": "UTF-8", "text": "import requests as req\nfrom bs4 import BeautifulSoup as bs\n\ndef run():\t\n\t#I will get all the all-night farmacy\n\tfile2read = req.get( \"http://www.colfacor.org.ar/turnosfarmacias/grid_turno_farmacia/\" )\t\n\tsoup = bs(file2read.content,\"html.parser\")\t\n\t\n\t#create a file where I will dump the data extracted\tfor test pourpuse\n\tfile2write = open(\"table-data\",\"w\")\n\t\n\t#Get the data in an ugly way\t\n\tfor tag in soup.find_all(\"table\"):\t\t\n\t\tif tag.has_attr('id') & str( tag.get('id') ).find(\"#\") != -1:\n\t\t\tfile2write.write( str( tag ) )\n\tfile2write.close()\n\t\nif __name__ == '__main__':\n\trun()" } ]
1
ahhussein/GraphWriter
https://github.com/ahhussein/GraphWriter
804d7acda733489204fde4ac5201dafec8a4f950
683df6d92c024a7af7c52a797db3daac87813837
590326a2030504445e8c9a463dcfe50aa650d193
refs/heads/master
2022-12-26T07:13:27.952789
2020-10-03T16:13:13
2020-10-03T16:13:13
290,807,819
0
0
null
2020-08-27T15:09:23
2020-08-26T18:48:59
2020-06-01T20:36:55
null
[ { "alpha_fraction": 0.6187363862991333, "alphanum_fraction": 0.6277621984481812, "avg_line_length": 26.69827651977539, "blob_id": "ba41c108a879482d10965f776e56c92e4e860dfa", "content_id": "012633679d46382e277d228b55ca9f8a021b7404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3213, "license_type": "no_license", "max_line_length": 95, "num_lines": 116, "path": "/generator.py", "repo_name": "ahhussein/GraphWriter", "src_encoding": "UTF-8", "text": "import torch\nimport argparse\nfrom time import time\nfrom lastDataset import dataset\nfrom models.newmodel import model \nfrom pargs import pargs,dynArgs\n#import utils.eval as evalMetrics\nimport glob\nimport logging\nfrom eval import Evaluate\n\nlogger = logging.getLogger('myapp')\nhdlr = logging.FileHandler('eval-graph.log')\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\nhdlr.setFormatter(formatter)\nlogger.addHandler(hdlr)\nlogger.setLevel(logging.DEBUG)\n\n\n\nevaluator = Evaluate()\n\ndef tgtreverse(tgts,entlist,order):\n entlist = entlist[0]\n order = [int(x) for x in order[0].split(\" \")]\n tgts = tgts.split(\" \")\n k = 0\n for i,x in enumerate(tgts):\n if x[0] == \"<\" and x[-1]=='>':\n tgts[i] = entlist[order[k]]\n k+=1\n return \" \".join(tgts)\n \ndef test(args,ds,m,epoch='cmdline'):\n args.vbsz = 1\n model = args.save.split(\"/\")[-1]\n m.eval()\n k = 0\n data = ds.mktestset(args)\n ofn = \"outputs/\"+model+\".inputs.beam_predictions.\"+epoch\n ofng = \"outputs/\"+model+\".inputs.beam_gt.\"+epoch\n pf = open(ofn,'w')\n pfg = open(ofng,'w')\n preds = []\n golds = []\n for b in data:\n #if k == 10: break\n print(k,len(data))\n b = ds.fixBatch(b)\n '''\n p,z = m(b)\n p = p[0].max(1)[1]\n gen = ds.reverse(p,b.rawent)\n '''\n gen = m.beam_generate(b,beamsz=4,k=6)\n gen.sort()\n gen = ds.reverse(gen.done[0].words,b.rawent)\n k+=1\n gold = ds.reverse(b.tgt[0][1:],b.rawent)\n preds.append(gen.lower())\n golds.append(gold.lower())\n #tf.write(ent+'\\n')\n pf.write(gen.lower()+'\\n')\n pfg.write(gold.lower() + '\\n')\n pf.close()\n pfg.close()\n\n with open(ofn) as f:\n cands = {'generated_description' + str(i): x.strip() for i, x in enumerate(f.readlines())}\n with open(ofng) as f:\n refs = {'generated_description' + str(i): [x.strip()] for i, x in enumerate(f.readlines())}\n\n final_scores = evaluator.evaluate(live=True, cand=cands, ref=refs)\n logger.info(\"Results for model:\\t\", model_name)\n logger.info ('Bleu_1:\\t', final_scores['Bleu_1'])\n logger.info ('Bleu_2:\\t', final_scores['Bleu_2'])\n logger.info ('Bleu_3:\\t', final_scores['Bleu_3'])\n logger.info ('Bleu_4:\\t', final_scores['Bleu_4'])\n logger.info ('ROUGE_L:\\t', final_scores['ROUGE_L'])\n logger.info ('METEOR:\\t', final_scores['METEOR'])\n\n return preds,golds\n\n'''\ndef metrics(preds,gold):\n cands = {'generated_description'+str(i):x.strip() for i,x in enumerate(preds)}\n refs = {'generated_description'+str(i):[x.strip()] for i,x in enumerate(gold)}\n x = evalMetrics.Evaluate()\n scores = x.evaluate(live=True, cand=cands, ref=refs)\n return scores\n'''\n\nif __name__==\"__main__\":\n args = pargs()\n args.eval = True\n ds = dataset(args)\n args = dynArgs(args,ds)\n m = model(args)\n m = m.to(args.device)\n models = glob.glob(args.save+\"/*vloss*\")\n m.args = args\n m.maxlen = args.max\n m.starttok = ds.OUTP.vocab.stoi['<start>']\n m.endtok = ds.OUTP.vocab.stoi['<eos>']\n m.eostok = ds.OUTP.vocab.stoi['.']\n args.vbsz = 1\n\n for i, model_name in enumerate(models):\n cpt = torch.load(model_name)\n m.load_state_dict(cpt)\n preds,gold = test(args,ds,m)\n '''\n scores = metrics(preds,gold)\n for k,v in scores.items():\n print(k+'\\t'+str(scores[k]))\n '''\n" } ]
1
johnpmayer/pants
https://github.com/johnpmayer/pants
b2ddac02dd00169e58e680dcb8bc1fb7ec3c8ba4
50514816bbbdf126de14abab219221f715e14945
fe9db30c3241d2954935e91dea9db06a5cf72cac
refs/heads/master
2020-04-06T11:40:18.940804
2018-11-13T16:06:29
2018-11-13T16:06:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6987215280532837, "alphanum_fraction": 0.7034463882446289, "avg_line_length": 43.41975402832031, "blob_id": "4c41824710b097b9ae7ec021cd545d33e87cb30e", "content_id": "e290141a620b5f140c636fee8e6c6378dea78e7d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3598, "license_type": "permissive", "max_line_length": 99, "num_lines": 81, "path": "/src/python/pants/option/compiler_option_sets_mixin.py", "repo_name": "johnpmayer/pants", "src_encoding": "UTF-8", "text": "# coding=utf-8\n# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom builtins import object\n\nfrom pants.util.meta import classproperty\n\n\nclass CompilerOptionSetsMixin(object):\n \"\"\"A mixin for language-scoped that support compiler option sets.\"\"\"\n\n @classmethod\n def register_options(cls, register):\n super(CompilerOptionSetsMixin, cls).register_options(register)\n\n register('--fatal-warnings-enabled-args', advanced=True, type=list, fingerprint=True,\n default=cls.get_fatal_warnings_enabled_args_default,\n help='Extra compiler args to use when fatal warnings are enabled.',\n removal_version='1.14.0.dev2',\n removal_hint='Use compiler option sets instead.')\n register('--fatal-warnings-disabled-args', advanced=True, type=list, fingerprint=True,\n default=cls.get_fatal_warnings_disabled_args_default,\n help='Extra compiler args to use when fatal warnings are disabled.',\n removal_version='1.14.0.dev2',\n removal_hint='Use compiler option sets instead.')\n register('--compiler-option-sets-enabled-args', advanced=True, type=dict, fingerprint=True,\n default=cls.get_compiler_option_sets_enabled_default_value,\n help='Extra compiler args to use for each enabled option set.')\n register('--compiler-option-sets-disabled-args', advanced=True, type=dict, fingerprint=True,\n default=cls.get_compiler_option_sets_disabled_default_value,\n help='Extra compiler args to use for each disabled option set.')\n\n @classproperty\n def get_compiler_option_sets_enabled_default_value(cls):\n \"\"\"Override to set default for this option.\"\"\"\n return {}\n\n @classproperty\n def get_compiler_option_sets_disabled_default_value(cls):\n \"\"\"Override to set default for this option.\"\"\"\n return {}\n\n @classproperty\n def get_fatal_warnings_enabled_args_default(cls):\n \"\"\"Override to set default for this option.\"\"\"\n return ()\n\n @classproperty\n def get_fatal_warnings_disabled_args_default(cls):\n \"\"\"Override to set default for this option.\"\"\"\n return ()\n\n def get_merged_args_for_compiler_option_sets(self, compiler_option_sets):\n compiler_options = set()\n\n # Set values for enabled options.\n for option_set_key in compiler_option_sets:\n # Fatal warnings option has special treatment for backwards compatibility.\n # This is because previously this has had its own {enabled, disabled}_args\n # options when these were defined in the jvm compile task.\n fatal_warnings = self.get_options().fatal_warnings_enabled_args\n if option_set_key == 'fatal_warnings' and fatal_warnings:\n compiler_options.update(fatal_warnings)\n else:\n val = self.get_options().compiler_option_sets_enabled_args.get(option_set_key, ())\n compiler_options.update(val)\n\n # Set values for disabled options.\n for option_set, disabled_args in self.get_options().compiler_option_sets_disabled_args.items():\n # Fatal warnings option has special treatment for backwards compatibility.\n disabled_fatal_warn_args = self.get_options().fatal_warnings_disabled_args\n if option_set == 'fatal_warnings' and disabled_fatal_warn_args:\n compiler_options.update(disabled_fatal_warn_args)\n else:\n if not option_set in compiler_option_sets:\n compiler_options.update(disabled_args)\n\n return list(compiler_options)\n" } ]
1
trannguyenminhluan/geopy
https://github.com/trannguyenminhluan/geopy
a6e53b3363dce5d1db2e61726b6f24e94d803a94
cc22561e6ed2bab36f19373bd7a5d43d21457eaf
34b927930d3aed3dc6f5bceaaf9218c0220eefd1
refs/heads/master
2021-01-17T19:33:20.227986
2013-11-21T04:28:56
2013-11-21T04:28:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6442705988883972, "alphanum_fraction": 0.6571559906005859, "avg_line_length": 35.21666717529297, "blob_id": "601fc4d28c83b5eee6b70ffd66b7181d2fdf91a3", "content_id": "67a47ba1406224a9e601a9aba8bc93893a6d0d21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2173, "license_type": "permissive", "max_line_length": 98, "num_lines": 60, "path": "/test/test_proxy.py", "repo_name": "trannguyenminhluan/geopy", "src_encoding": "UTF-8", "text": "\"\"\"\nTest ability to proxy requests.\n\"\"\"\n\nimport os\ntry: # Py2k\n from urllib2 import urlopen # pylint: disable=F0401\nexcept ImportError: # Py3k\n from urllib.request import urlopen # pylint: disable=F0401,E0611\nimport unittest\nfrom test import proxy_server\nfrom geopy.geocoders.base import Geocoder\n\n### UNIT TEST(S) to test Proxy in Geocoder base class ###\n###\n### Solution requires that proxy_server.py is run to start simple proxy\n### daemon proxy PID is located in /var/run/proxy_server.pid and can be\n### stoped using the command `kill -9 $(cat /var/run/proxy_server.pid)`\n\n\nclass ProxyTestCase(unittest.TestCase): # pylint: disable=R0904,C0111\n def setUp(self):\n\n # TODO subprocess.Popen proxy locally on os.name==\"posix\", and skip if not\n\n # Backup environ settings\n self.orig_http_proxy = os.environ['http_proxy'] if 'http_proxy' in os.environ else None\n\n # Get HTTP for comparison before proxy test\n base_http = urlopen('http://www.blankwebsite.com/')\n base_html = base_http.read()\n self.noproxy_data = base_html if base_html else None\n\n # Create the proxy instance\n self.proxyd = proxy_server.ProxyServer()\n # Set the http_proxy environment variable with Proxy_server default value\n os.environ['http_proxy'] = self.proxyd.get_proxy_url()\n\n def teardown(self):\n if self.orig_http_proxy:\n os.environ['http_proxy'] = self.orig_http_proxy\n else:\n del os.environ['http_proxy']\n\n\n def test_proxy(self):\n ''' Test of OTB Geocoder Proxy functionality works'''\n class DummyGeocoder(Geocoder):\n def geocode(self, location):\n geo_request = urlopen(location)\n geo_html = geo_request.read()\n return geo_html if geo_html else None\n\n '''Testcase to test that proxy standup code works'''\n geocoder_dummy = DummyGeocoder(proxies={\"http\": \"http://localhost:1337\"})\n self.assertTrue(geocoder_dummy.urlopen != urlopen)\n self.assertTrue(self.noproxy_data, geocoder_dummy.geocode('http://www.blankwebsite.com/'))\n\nif __name__ == '__main__':\n unittest.main()\n" } ]
1
tkvw/py.hacs.egardia
https://github.com/tkvw/py.hacs.egardia
5a99b99ac83fa0e5cd5bc3c51f5ce8c4fb92b529
89168488fa35fae658a089d5f2a4cd195e0caae2
ddd4eef67684a91268726a77c0cde0cc335679dd
refs/heads/master
2022-12-10T20:40:49.781482
2020-09-08T17:19:29
2020-09-08T17:19:29
290,904,461
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6090728640556335, "alphanum_fraction": 0.6095686554908752, "avg_line_length": 28.66176414489746, "blob_id": "e1d412e2fea8e8f3ca6d5778cf9e09d72e991337", "content_id": "fff03385520a93dfc7fdf79eb6297fd115d29459", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4034, "license_type": "permissive", "max_line_length": 84, "num_lines": 136, "path": "/custom_components/tkvw_egardia/alarm_control_panel.py", "repo_name": "tkvw/py.hacs.egardia", "src_encoding": "UTF-8", "text": "\"\"\"Interfaces with Egardia/Woonveilig alarm control panel.\"\"\"\nimport logging\n\nimport requests\n\nimport homeassistant.components.alarm_control_panel as alarm\nfrom homeassistant.components.alarm_control_panel.const import (\n SUPPORT_ALARM_ARM_AWAY,\n SUPPORT_ALARM_ARM_HOME,\n)\nfrom homeassistant.const import (\n STATE_ALARM_ARMED_AWAY,\n STATE_ALARM_ARMED_HOME,\n STATE_ALARM_ARMED_NIGHT,\n STATE_ALARM_DISARMED,\n STATE_ALARM_TRIGGERED,\n)\n\nfrom .const import (\n DATA_COORDINATOR,\n DOMAIN_DATA,\n CONF_NAME,\n)\n\nfrom .api.client import Mode\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_platform(hass, config, add_entities, discovery_info=None):\n \"\"\"Set up the Egardia Alarm Control Panael platform.\"\"\"\n if discovery_info is None:\n return\n\n coordinator = hass.data.get(DOMAIN_DATA)[DATA_COORDINATOR]\n\n device = EgardiaAlarm(discovery_info.get(CONF_NAME, \"Egardia\"), coordinator)\n\n add_entities([device], True)\n\n\nclass EgardiaAlarm(alarm.AlarmControlPanelEntity):\n \"\"\"Representation of a Egardia alarm.\"\"\"\n\n STATES = {\n Mode.Armed: STATE_ALARM_ARMED_AWAY,\n Mode.ArmedHome: STATE_ALARM_ARMED_HOME,\n Mode.Disarmed: STATE_ALARM_DISARMED,\n Mode.Triggered: STATE_ALARM_TRIGGERED,\n Mode.TriggeredPanic: STATE_ALARM_TRIGGERED,\n }\n\n def __init__(self, name, coordinator):\n \"\"\"Initialize the Egardia alarm.\"\"\"\n self._name = name\n self._coordinator = coordinator\n self._status = None\n\n async def async_added_to_hass(self):\n \"\"\"Add Egardiaserver callback if enabled.\"\"\"\n self.async_on_remove(\n self._coordinator.async_add_listener(self.async_write_ha_state)\n )\n\n @property\n def name(self):\n \"\"\"Return the name of the device.\"\"\"\n return self._name\n\n @property\n def state(self):\n \"\"\"Return the state of the device.\"\"\"\n\n events = self._coordinator.data.get(\"events\")\n status = self._coordinator.data.get(\"status\")\n\n if events is not None and len(events) > 0:\n event = events[0]\n egardia_mode = event.get(\"mode\")\n else:\n egardia_mode = status.get(\"mode\")\n\n # From the event log we can receive a disarmedpanic mode. This\n # is not a valid HomeAssistant mode, restore the previous state\n if egardia_mode == Mode.DisarmedPanic:\n egardia_mode = status.get(\n \"mode\"\n ) # The actual state is still available in the status\n\n return EgardiaAlarm.STATES.get(egardia_mode)\n\n @property\n def supported_features(self) -> int:\n \"\"\"Return the list of supported features.\"\"\"\n return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY\n\n @property\n def should_poll(self):\n \"\"\"Poll if no report server is enabled.\"\"\"\n return False\n\n async def async_update(self):\n \"\"\"Update the alarm status.\"\"\"\n await self._coordinator.async_request_refresh()\n\n async def async_alarm_disarm(self, code=None):\n \"\"\"Send disarm command.\"\"\"\n try:\n await self._coordinator.alarm_disarm()\n except Exception as err:\n _LOGGER.error(\n \"Egardia device exception occurred when sending disarm command: %s\",\n err,\n )\n\n async def async_alarm_arm_home(self, code=None):\n \"\"\"Send arm home command.\"\"\"\n try:\n await self._coordinator.alarm_arm_home()\n except Exception as err:\n _LOGGER.error(\n \"Egardia device exception occurred when \"\n \"sending arm home command: %s\",\n err,\n )\n\n async def async_alarm_arm_away(self, code=None):\n \"\"\"Send arm away command.\"\"\"\n try:\n await self._coordinator.alarm_arm()\n except Exception as err:\n _LOGGER.error(\n \"Egardia device exception occurred when \"\n \"sending arm away command: %s\",\n err,\n )\n" }, { "alpha_fraction": 0.7528913021087646, "alphanum_fraction": 0.7659984827041626, "avg_line_length": 42.233333587646484, "blob_id": "035d578e95c91c0d59f31ea5b5dc62748acfc0bc", "content_id": "582f18e711d52b68ad449a22b6aa1b4e46c64ff7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2595, "license_type": "permissive", "max_line_length": 141, "num_lines": 60, "path": "/info.md", "repo_name": "tkvw/py.hacs.egardia", "src_encoding": "UTF-8", "text": "[![GitHub Release][releases-shield]][releases]\n[![GitHub Activity][commits-shield]][commits]\n[![License][license-shield]](LICENSE)\n\n[![hacs][hacsbadge]](hacs)\n![Project Maintenance][maintenance-shield]\n[![BuyMeCoffee][buymecoffeebadge]][buymecoffee]\n\n[![Discord][discord-shield]][discord]\n[![Community Forum][forum-shield]][forum]\n\n_Component to integrate with [blueprint][blueprint]._\n\n**This component will set up the following platforms.**\n\nPlatform | Description\n-- | --\n`alarm_control_panel` | Switch and sensor for alarm mode in one, supports Armed, Disarmed, ArmedHome and Triggered.\n\n![example][exampleimg]\n\n{% if not installed %}\n## Installation\n\n1. Click install to add the component to Hacs (it will be available in `/config/custom_components/tkvw_egardia`)\n2. add the following configuration to `configuration.yaml`\n\n```yaml\ntkvw_egardia:\n name: Woonveilig # A free name of your choosing, a alarm_control_panel entity will be created with entityid alarm_control_panel.<name>\n hostname: !secret tkvw_egardia_hostname # The ip adress of your egardia device\n username: !secret tkvw_egardia_username # The username used to login to the woonveilig webportal\n password: !secret tkvw_egardia_password # The password used to login to the woonveilig webportal\n```\n\n{% endif %}\n\n\n## Configuration is done in the UI\n\n<!---->\n\n***\n\n[blueprint]: https://github.com/custom-components/blueprint\n[buymecoffee]: https://www.buymeacoffee.com/ludeeus\n[buymecoffeebadge]: https://img.shields.io/badge/buy%20me%20a%20coffee-donate-yellow.svg?style=for-the-badge\n[commits-shield]: https://img.shields.io/github/commit-activity/y/custom-components/blueprint.svg?style=for-the-badge\n[commits]: https://github.com/custom-components/blueprint/commits/master\n[hacs]: https://github.com/custom-components/hacs\n[hacsbadge]: https://img.shields.io/badge/HACS-Custom-orange.svg?style=for-the-badge\n[discord]: https://discord.gg/Qa5fW2R\n[discord-shield]: https://img.shields.io/discord/330944238910963714.svg?style=for-the-badge\n[exampleimg]: example.png\n[forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg?style=for-the-badge\n[forum]: https://community.home-assistant.io/\n[license-shield]: https://img.shields.io/github/license/custom-components/blueprint.svg?style=for-the-badge\n[maintenance-shield]: https://img.shields.io/badge/maintainer-Joakim%20Sørensen%20%40ludeeus-blue.svg?style=for-the-badge\n[releases-shield]: https://img.shields.io/github/release/custom-components/blueprint.svg?style=for-the-badge\n[releases]: https://github.com/custom-components/blueprint/releases\n" }, { "alpha_fraction": 0.5988971590995789, "alphanum_fraction": 0.6058499217033386, "avg_line_length": 27.77241325378418, "blob_id": "8962d1749bc83c984327b125688b8d4dfc2d7763", "content_id": "93ebbf580be7c8d3cc98ff1c87427cce13459479", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4171, "license_type": "permissive", "max_line_length": 87, "num_lines": 145, "path": "/custom_components/tkvw_egardia/api/client.py", "repo_name": "tkvw/py.hacs.egardia", "src_encoding": "UTF-8", "text": "from enum import Enum\nfrom typing import TypedDict, List\n\nimport aiohttp\n\n\nclass Mode(Enum):\n Disarmed = 0\n Armed = 1\n ArmedHome = 2\n Triggered = 10\n TriggeredPanic = 20\n DisarmedPanic = 21\n Unset = 99\n\n\nclass BatteryLevel(Enum):\n Ok = 0\n Low = 1\n Critical = 2\n Dead = 3\n\n\nclass AlarmStatus(TypedDict):\n mode: Mode\n battery: BatteryLevel\n\n\nclass EgardiaDevice(TypedDict):\n name: str\n battery: BatteryLevel\n\n\nclass EgardiaEvent(TypedDict):\n mode: Mode\n msg: str\n\n\nclass Client:\n def __init__(self, hostname, username, password, device: EgardiaDevice):\n self._hostname = hostname\n self._username = username\n self._password = password\n self._device = device\n\n async def get_devices(self):\n return await self._device.get_devices(self)\n\n async def get_status(self):\n return await self._device.get_status(self)\n\n async def get_events(self):\n return await self._device.get_events(self)\n\n async def set_status(self, mode: Mode, area: str = \"1\"):\n return await self._device.set_status(self, mode, area)\n\n\nclass EgardiaGateway:\n def __init__(self, model: str):\n self.model = model\n\n async def get_devices(self, client: Client) -> List[EgardiaDevice]:\n pass\n\n async def get_status(self, client: Client) -> AlarmStatus:\n pass\n\n async def get_events(self, client: Client) -> List[EgardiaEvent]:\n pass\n\n async def set_status(self, client: Client, mode: Mode, area: str = \"1\"):\n pass\n\n\nclass Gate03(EgardiaGateway):\n STATUS = {\n \"Full Arm\": Mode.Armed,\n \"Disarm\": Mode.Disarmed,\n \"Home Arm 1\": Mode.ArmedHome,\n \"Unset\": Mode.Unset,\n }\n\n def __init__(self):\n super().__init__(\"GATE-03\")\n\n async def get_devices(self, client: Client) -> List[EgardiaDevice]:\n data = await self.get(client, \"deviceListGet\")\n return data[\"senrows\"]\n\n async def get_status(self, client: Client) -> AlarmStatus:\n data = await self.get(client, \"panelCondGet\")\n updates = data.get(\"updates\", {})\n mode = Gate03.STATUS[updates.get(\"mode_a1\")]\n return {\"mode\": mode, \"battery\": BatteryLevel.Ok}\n\n def transform_event(self, record):\n mode = Mode.Unset\n if record.get('mode'):\n mode = Gate03.STATUS[record.get(\"mode\")]\n msg = record.get(\"msg\")\n\n if \"Burglar Alarm\".casefold() == msg.casefold():\n mode = Mode.Triggered\n elif \"Panic Alarm\".casefold() == msg.casefold():\n mode = Mode.TriggeredPanic\n elif \"Disarm Self Panic\".casefold() == msg.casefold():\n mode = Mode.DisarmedPanic\n\n return {\"mode\": mode, \"msg\": msg}\n\n async def get_events(self, client: Client) -> List[EgardiaEvent]:\n data = await self.get(client, \"logsGet\")\n rows = [\n event\n for event in data.get(\"logrows\", [])\n if event.get(\"mode\") is not None or event.get(\"msg\") == \"Disarm Self Panic\"\n ]\n return list(map(self.transform_event, rows))\n\n async def set_status(self, client: Client, mode: Mode, area: str = \"1\"):\n return await self.post(\n client, \"panelCondPost\", {\"area\": area, \"mode\": mode.value}\n )\n\n async def get(self, client: Client, action: str):\n async with self.create_session(client) as session:\n async with session.get(self.endpoint(client, action)) as response:\n return await response.json(content_type=None)\n\n async def post(self, client: Client, action: str, data):\n async with self.create_session(client) as session:\n async with session.post(\n self.endpoint(client, action), data=data\n ) as response:\n return await response.json(content_type=None)\n\n def endpoint(self, client: Client, action: str):\n return f\"http://{client._hostname}/action/{action}\"\n\n def create_session(self, client: Client):\n return aiohttp.ClientSession(\n auth=aiohttp.BasicAuth(client._username, client._password),\n timeout=aiohttp.ClientTimeout(total=5),\n )" }, { "alpha_fraction": 0.6822262406349182, "alphanum_fraction": 0.6837650537490845, "avg_line_length": 29.94444465637207, "blob_id": "9dd7fc5fb4f03ce604923c233b3731802bb45ed0", "content_id": "9b3f0fc8937a284d9e33c26ba7a65afb8614e29d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3899, "license_type": "permissive", "max_line_length": 92, "num_lines": 126, "path": "/custom_components/tkvw_egardia/__init__.py", "repo_name": "tkvw/py.hacs.egardia", "src_encoding": "UTF-8", "text": "\"\"\"\nCustom integration to integrate blueprint with Home Assistant.\n\nFor more details about this integration, please refer to\nhttps://github.com/custom-components/blueprint\n\"\"\"\nimport asyncio\nfrom datetime import timedelta\nimport logging\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import Config, HomeAssistant\nfrom homeassistant.exceptions import ConfigEntryNotReady\nfrom homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed\nfrom homeassistant.helpers import discovery\n\nfrom .api.client import Client, Gate03\nfrom .coordinator import EgardiaCoordinator\n\nfrom .const import (\n CONF_INTERVAL_DISARMED,\n CONF_INTERVAL_ARMED,\n CONF_HOSTNAME,\n CONF_PASSWORD,\n CONF_USERNAME,\n CONF_DEVICE,\n DATA_COORDINATOR,\n DEFAULT_INTERVAL_DISARMED,\n DEFAULT_INTERVAL_ARMED,\n DEFAULT_DEVICE,\n DOMAIN,\n DOMAIN_DATA,\n PLATFORMS,\n STARTUP_MESSAGE,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\nDEVICES = {\"GATE-03\": Gate03()}\n\n\nasync def async_setup(hass: HomeAssistant, config: Config):\n \"\"\"Set up this integration using YAML is not supported.\"\"\"\n if (hass.data.get(DOMAIN_DATA)) is None:\n hass.data.setdefault(DOMAIN_DATA, {})\n _LOGGER.info(STARTUP_MESSAGE)\n\n conf = config[DOMAIN]\n\n interval_armed = conf.get(CONF_INTERVAL_ARMED, DEFAULT_INTERVAL_ARMED)\n interval_disarmed = conf.get(CONF_INTERVAL_DISARMED, DEFAULT_INTERVAL_DISARMED)\n hostname = conf.get(CONF_HOSTNAME)\n username = conf.get(CONF_USERNAME)\n password = conf.get(CONF_PASSWORD)\n device = conf.get(CONF_DEVICE, DEFAULT_DEVICE)\n\n api = Client(\n hostname, username, password, DEVICES.get(device, DEVICES.get(DEFAULT_DEVICE))\n )\n\n coordinator = EgardiaCoordinator(hass, api, interval_armed, interval_disarmed)\n\n await coordinator.async_refresh()\n\n hass.data.get(DOMAIN_DATA)[DATA_COORDINATOR] = coordinator\n\n await discovery.async_load_platform(\n hass, \"alarm_control_panel\", DOMAIN, conf, config\n )\n\n return True\n\n\n# async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):\n# \"\"\"Set up this integration using UI.\"\"\"\n# if hass.data.get(DOMAIN) is None:\n# hass.data.setdefault(DOMAIN, {})\n# _LOGGER.info(STARTUP_MESSAGE)\n\n# interval = entry.data.get(CONF_INTERVAL, DEFAULT_INTERVAL)\n# hostname = entry.data.get(CONF_HOSTNAME)\n# username = entry.data.get(CONF_USERNAME)\n# password = entry.data.get(CONF_PASSWORD)\n\n# coordinator = WoonveiligDataUpdateCoordinator(\n# hass, interval=interval, hostname=hostname, username=username, password=password\n# )\n# await coordinator.async_refresh()\n\n# if not coordinator.last_update_success:\n# raise ConfigEntryNotReady\n\n# hass.data[DOMAIN][entry.entry_id] = coordinator\n\n# for platform in PLATFORMS:\n# if entry.options.get(platform, True):\n# coordinator.platforms.append(platform)\n# hass.async_add_job(\n# hass.config_entries.async_forward_entry_setup(entry, platform)\n# )\n\n# entry.add_update_listener(async_reload_entry)\n# return True\n\n# async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):\n# \"\"\"Handle removal of an entry.\"\"\"\n# coordinator = hass.data[DOMAIN][entry.entry_id]\n# unloaded = all(\n# await asyncio.gather(\n# *[\n# hass.config_entries.async_forward_entry_unload(entry, platform)\n# for platform in PLATFORMS\n# if platform in coordinator.platforms\n# ]\n# )\n# )\n# if unloaded:\n# hass.data[DOMAIN].pop(entry.entry_id)\n\n# return unloaded\n\n\n# async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry):\n# \"\"\"Reload config entry.\"\"\"\n# await async_unload_entry(hass, entry)\n# await async_setup_entry(hass, entry)\n" }, { "alpha_fraction": 0.7970296740531921, "alphanum_fraction": 0.8069307208061218, "avg_line_length": 49.5, "blob_id": "bda158f08912f7fcd0500e5e0b906e6080140072", "content_id": "e9fe9257f56d0fd6217ea4cf3a7e5d6ca249ba49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 404, "license_type": "permissive", "max_line_length": 84, "num_lines": 8, "path": "/README.md", "repo_name": "tkvw/py.hacs.egardia", "src_encoding": "UTF-8", "text": "# Egardia/Woonveilig Hacs component\n\nThis component is a rewrite of the standard supported egardia alarmpanel.\nThe servermode did not work with my GATE-03 device (did not receive the codes).\nThe GATE-03 can be queried using http, so this plugin uses polling for alarm status.\n\nThis repository is initialized from the HACS blueprint repository.\n[blueprint]: https://github.com/custom-components/blueprint\n" }, { "alpha_fraction": 0.6409168243408203, "alphanum_fraction": 0.647707998752594, "avg_line_length": 23.040817260742188, "blob_id": "871031d7c5a1356264b68d8343c5a68490c31d20", "content_id": "765b403be1f5969f2e29fbdb478f5d5e7f82ea73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1178, "license_type": "permissive", "max_line_length": 67, "num_lines": 49, "path": "/custom_components/tkvw_egardia/const.py", "repo_name": "tkvw/py.hacs.egardia", "src_encoding": "UTF-8", "text": "\"\"\"Constants for woonveilig.\"\"\"\n# Base component constants\nNAME = \"Egardia\"\nDOMAIN = \"tkvw_egardia\"\nDOMAIN_DATA = f\"{DOMAIN}_data\"\nVERSION = \"0.0.1\"\n\nISSUE_URL = \"https://github.com/tkvw/py.hacs.tkvw_egardia/issues\"\n\n# Icons\nICON = \"mdi:format-quote-close\"\n\n# Device classes\nBINARY_SENSOR_DEVICE_CLASS = \"connectivity\"\n\n# Platforms\nALARM_CONTROL_PANEL = \"alarm_control_panel\"\nBINARY_SENSOR = \"binary_sensor\"\nPLATFORMS = [ALARM_CONTROL_PANEL, BINARY_SENSOR]\n\n\n# Data\nDATA_COORDINATOR = \"coordinator\"\n\n# Configuration and options\nCONF_ENABLED = \"enabled\"\nCONF_INTERVAL_DISARMED = \"interval_disarmed\"\nCONF_INTERVAL_ARMED = \"interval_armed\"\nCONF_HOSTNAME = \"hostname\"\nCONF_USERNAME = \"username\"\nCONF_PASSWORD = \"password\"\nCONF_NAME = \"name\"\nCONF_DEVICE = \"device\"\n\n# Defaults\nDEFAULT_NAME = DOMAIN\nDEFAULT_INTERVAL_DISARMED = 20\nDEFAULT_INTERVAL_ARMED = 2\nDEFAULT_DEVICE = \"GATE-03\"\n\nSTARTUP_MESSAGE = f\"\"\"\n-------------------------------------------------------------------\n{NAME}\nVersion: {VERSION}\nThis is a custom integration!\nIf you have any issues with this you need to open an issue here:\n{ISSUE_URL}\n-------------------------------------------------------------------\n\"\"\"\n" }, { "alpha_fraction": 0.6132326722145081, "alphanum_fraction": 0.6141207814216614, "avg_line_length": 30.27777862548828, "blob_id": "3ca875cfb65c13d03198460a0735405cf5c23c17", "content_id": "1bb1145596d6360d1f4dbec35cd614a716f4e034", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2252, "license_type": "permissive", "max_line_length": 88, "num_lines": 72, "path": "/custom_components/tkvw_egardia/coordinator.py", "repo_name": "tkvw/py.hacs.egardia", "src_encoding": "UTF-8", "text": "from datetime import timedelta, datetime, timezone\nimport asyncio\nimport logging\n\nfrom homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed\nfrom .const import DOMAIN\nfrom .api.client import Mode\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass EgardiaCoordinator(DataUpdateCoordinator):\n \"\"\"Class to manage fetching data from the API.\"\"\"\n\n def __init__(self, hass, api, interval_armed, interval_disarmed):\n \"\"\"Initialize.\"\"\"\n self.api = api\n self.counter = 0\n self.interval_armed = timedelta(seconds=interval_armed)\n self.interval_disarmed = timedelta(seconds=interval_disarmed)\n\n super().__init__(\n hass, _LOGGER, name=DOMAIN, update_interval=self.interval_armed\n )\n\n async def alarm_disarm(self):\n return await self.set_status(Mode.Disarmed)\n\n async def alarm_arm(self):\n return await self.set_status(Mode.Armed)\n\n async def alarm_arm_home(self):\n return await self.set_status(Mode.ArmedHome)\n\n async def set_status(self, mode: Mode):\n result = await self.api.set_status(mode)\n await self.async_refresh()\n return result\n\n async def get_devices(self):\n if self.data is None or self.data.get(\"devices\") is None:\n return await self.api.get_devices()\n\n return self.data.get(\"devices\")\n\n async def get_events(self):\n return await self.api.get_events()\n\n async def get_status(self):\n return await self.api.get_status()\n\n async def _async_update_data(self):\n \"\"\"Update data via library.\"\"\"\n try:\n self.counter += 1\n devices, events, status = await asyncio.gather(\n self.get_devices(), self.get_events(), self.get_status()\n )\n\n if status.get(\"mode\") == Mode.Disarmed:\n self.update_interval = self.interval_disarmed\n else:\n self.update_interval = self.interval_armed\n\n return {\n \"timestamp\": datetime.now(timezone.utc),\n \"devices\": devices,\n \"events\": events,\n \"status\": status,\n }\n except Exception as exception:\n raise UpdateFailed(exception)\n" } ]
7
biaogelaile/yqjqr
https://github.com/biaogelaile/yqjqr
bbac3001529b3a160e91e6c1d78ece9a01196f8d
74b258477cb61d0606a9c6da1b9c9400ba9cbd9d
ca8f72da118543dd4ed5faad2b079095121bae08
refs/heads/master
2020-04-27T01:07:21.876234
2019-03-28T12:20:11
2019-03-28T12:20:11
164,862,040
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5278743505477905, "alphanum_fraction": 0.5354299545288086, "avg_line_length": 41.7406005859375, "blob_id": "a7bbc13a188784d2f24aac60da791bc2f9eb3db5", "content_id": "b0786fda06e214ec457db52f9b948ddb669c7a0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132671, "license_type": "no_license", "max_line_length": 176, "num_lines": 2926, "path": "/chatapi/user.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from model import *\r\nfrom flask import Flask,render_template,current_app\r\nfrom flask_socketio import SocketIO, emit\r\nfrom concurrent.futures import ThreadPoolExecutor\r\nfrom datetime import datetime\r\nimport sqlalchemy\r\nfrom sqlalchemy import desc\r\nimport re\r\nimport random\r\nimport string\r\nimport os\r\n#import datetime\r\nimport time\r\nimport hashlib\r\nfrom APISender import APISender\r\nfrom base.APIMessage import *\r\nfrom base.APIConstants import *\r\nfrom APITools import *\r\nfrom APISubscribe import *\r\nimport sys\r\n\r\nConstants.use_official() \r\nfrom flask_socketio import join_room, leave_room\r\n\r\n\r\n\r\ndef phonecheck(mobile):\r\n n = mobile\r\n if len(n) != 11:\r\n return 'failure'\r\n if re.match(r'1[3,4,5,7,8]\\d{9}',n):\r\n print(\"手机号码是:\\n\",n)\r\n #中国联通:\r\n # 130,131,132,155,156,185,186,145,176\r\n if re.match(r'13[0,1,2]\\d{8}',n) or \\\r\n re.match(r\"15[5,6]\\d{8}\",n) or \\\r\n re.match(r\"18[5,6]\",n) or \\\r\n re.match(r\"145\\d{8}\",n) or \\\r\n re.match(r\"166\\d{8}\", n) or \\\r\n re.match(r\"176\\d{8}\",n):\r\n print(\"该号码属于:中国联通\")\r\n #中国移动\r\n # 134, 135 , 136, 137, 138, 139, 147, 150, 151,\r\n # 152, 157, 158, 159, 178, 182, 183, 184, 187, 188;\r\n elif re.match(r\"13[4,5,6,7,8,9]\\d{8}\",n) or \\\r\n re.match(r\"147\\d{8}|178\\d{8}\",n) or \\\r\n re.match(r\"15[0,1,2,7,8,9]\\d{8}\",n) or \\\r\n re.match(r\"18[2,3,4,7,8]\\d{8}\",n):\r\n print(\"该号码属于:中国移动\")\r\n else:\r\n #中国电信\r\n # #133,153,189\r\n print(\"该号码属于:中国电信\")\r\n else:\r\n return 'failure'\r\n\r\ndef generate_random_str(randomlength=16):\r\n \"\"\"\r\n 生成一个指定长度的随机字符串,其中\r\n string.digits=0123456789\r\n string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n \"\"\"\r\n str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]\r\n random_str = ''.join(str_list)\r\n return random_str\r\n\r\n#产生token\r\ndef token_generate():\r\n \r\n token_query = UserToken.query.first()\r\n if token_query:\r\n token_query.delete()\r\n newtoken = generate_random_str(5)\r\n insert_token = UserToken(token=newtoken)\r\n db.session.add(insert_token)\r\n db.session.commit()\r\n db.session.close()\r\n return newtoken\r\n\r\n\r\ndef generate_random_int(randomlength=16):\r\n str_list = [random.choice(string.digits) for i in range(randomlength)]\r\n random_str = ''.join(str_list)\r\n return random_str\r\n\r\n\r\ndef smsvc(mobile):\r\n smsvc = generate_random_int(6)\r\n data = u'本次验证码为' + smsvc\r\n command = '/bin/sh sms.sh ' + data + ' ' + mobile\r\n print('hhhhhhhhhhhhhhhh', command)\r\n comand_status = os.system(command)\r\n if comand_status == 0:\r\n delete_mobile = Sms.query.filter_by(user_mobile=mobile).first()\r\n if delete_mobile:\r\n delete_mobile.query.filter_by(user_mobile=mobile).delete()\r\n insert_sms = Sms(user_mobile=mobile, user_sms=smsvc)\r\n db.session.add(insert_sms)\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '发送成功'}\r\n else:\r\n return {'status': 1, 'msg': '发送失败'}\r\n\r\n \r\ndef forget_smsvc(mobile):\r\n db.session.rollback()\r\n mobileexsitcheck = User.query.filter_by(mobile=mobile).first()\r\n if mobileexsitcheck is None:\r\n return {'status': 3, 'msg': '用户未注册'}\r\n\r\n smsvc = generate_random_int(6)\r\n data = u'本次验证码为' + smsvc\r\n command = '/bin/sh sms.sh ' + data + ' ' + mobile\r\n print('hhhhhhhhhhhhhhhh', command)\r\n comand_status = os.system(command)\r\n if comand_status == 0:\r\n delete_mobile = Sms.query.filter_by(user_mobile=mobile).first()\r\n if delete_mobile:\r\n delete_mobile.query.filter_by(user_mobile=mobile).delete()\r\n insert_sms = Sms(user_mobile=mobile, user_sms=smsvc)\r\n db.session.add(insert_sms)\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '发送成功'}\r\n else:\r\n return {'status': 1, 'msg': '发送失败'}\r\n\r\n\r\ndef insert_chatbot(companyid):\r\n try:\r\n i_username = '机器人'\r\n i_userid = 'c' + generate_random_str(24)\r\n i_password = 'p' + generate_random_str(32)\r\n i_mobile = companyid\r\n i_role = '0'\r\n companyid = companyid\r\n email = '[email protected]'\r\n insert_mobile = User(username=i_username, userid=i_userid,\r\n mobile=i_mobile, password=i_password,\r\n role=i_role)\r\n insert_opuser = Opuser(opusername=i_username, opuserid=i_userid,\r\n opmobile=i_mobile, opcompanyid=companyid,\r\n default='true', oprole='5', opemail=email,\r\n )\r\n db.session.add(insert_mobile)\r\n db.session.add(insert_opuser)\r\n db.session.commit()\r\n db.session.close()\r\n\r\n return {'chatbotid':i_userid,'chatbotusername': i_mobile, 'chatbotpassword': i_password}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status': 3, 'Oooops': '数据库连接出现错误'}\r\n\r\n\r\ndef user_info(userid, token, companyid):\r\n try:\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token 无效'}\r\n user_query = User.query.filter_by(userid=userid).first()\r\n print(companyid)\r\n if companyid:\r\n oprole_query = Opuser.query.filter_by(opuserid=userid, opcompanyid=companyid).first()\r\n oprole = oprole_query.oprole\r\n opuser_name = oprole_query.opusername\r\n else:\r\n oprole = None\r\n opuser_name = None\r\n user_mobile = user_query.mobile\r\n user_profile = user_query.profile\r\n user_role = user_query.role\r\n user_name = user_query.username\r\n if user_role != '1' and user_role != '2':\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query:\r\n user_companyname = company_query.companyname\r\n user_companyexpiredate = company_query.companyexpiredate\r\n else:\r\n user_companyname=None\r\n user_companyexpiredate = None\r\n if company_query.companyrole:\r\n user_companyrole = company_query.companyrole\r\n else:\r\n user_companyrole = '1'\r\n else:\r\n user_companyname = None\r\n user_companyexpiredate = None\r\n user_companyrole = None\r\n db.session.close()\r\n return {'status': 0, 'msg': '查询成功','userid': userid, 'companyname': user_companyname,'opuser_name':opuser_name,\r\n 'companyrole':user_companyrole, 'companyexpiredate':user_companyexpiredate,\r\n 'companyid':companyid,'username':user_name, 'email': None,'oprole':oprole,\r\n 'mobile': user_mobile, 'role':user_role, 'imageUrl':user_profile}\r\n\r\n\r\n #except AttributeError:\r\n # return {'status': 2, 'msg': '用户名或密码错误'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\r\n\r\n\"\"\"\r\ndef user_info(userid, token, companyid):\r\n try:\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token 无效'}\r\n user_query = User.query.filter_by(userid=userid).first()\r\n print(companyid)\r\n opuser_name =None\r\n if companyid:\r\n oprole_query = Opuser.query.filter_by(opuserid=userid, opcompanyid=companyid).first()\r\n if oprole_query:\r\n oprole = oprole_query.oprole\r\n opuser_name = oprole_query.opusername\r\n else:\r\n oprole = None\r\n opuser_name = None\r\n displaystatus = 1\r\n minus = 0\r\n user_mobile = user_query.mobile\r\n user_profile = user_query.profile\r\n user_role = user_query.role\r\n user_name = user_query.username\r\n if user_role != '1' and user_role != '2':\r\n backstage_info = Backstage.query.first()\r\n date_inter = backstage_info.companyexpire\r\n currenttime = datetime(datetime.today().year, datetime.today().month, datetime.today().day, datetime.today().hour, datetime.today().minute, datetime.today().second)\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query:\r\n user_companyname = company_query.companyname\r\n user_companyexpiredate = company_query.companyexpiredate\r\n if user_companyexpiredate:\r\n minus0 = user_companyexpiredate - currenttime\r\n minus = minus0.total_seconds()\r\n print(\"minus$$$$$$$$$$$$$$$$$$$$$$%s\"%minus)\r\n if minus > 0 and minus > float(date_inter)*3600*24:\r\n displaystatus = 0\r\n elif minus > 0 and minus < float(date_inter)*3600*24:\r\n displaystatus = 1\r\n elif minus < 0:\r\n pass\r\n else:\r\n company_query.companyrole = '1'\r\n else:\r\n user_companyname=None\r\n user_companyexpiredate = None\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query:\r\n user_companyrole = company_query.companyrole\r\n if minus < 0:\r\n company_query.companyrole = '1'\r\n user_companyrole = '1'\r\n else:\r\n company_query.companyrole = '2'\r\n user_companyrole = '2'\r\n else:\r\n user_companyrole = '1'\r\n else:\r\n user_companyname = None\r\n user_companyexpiredate = None\r\n user_companyrole = None\r\n db.session.commit()\r\n db.session.close()\r\n a = {'status': 0, 'msg': '查询成功','userid': userid, 'companyname': user_companyname,'opuser_name':opuser_name,\r\n 'companyrole':user_companyrole, 'companyexpiredate':user_companyexpiredate,\r\n 'companyid':companyid,'username':user_name, 'email': None,'oprole':oprole,\r\n 'mobile': user_mobile, 'role':user_role, 'imageUrl':user_profile,\"displaystatus\":displaystatus}\r\n print(a)\r\n return {'status': 0, 'msg': '查询成功','userid': userid, 'companyname': user_companyname,'opuser_name':opuser_name,\r\n 'companyrole':user_companyrole, 'companyexpiredate':user_companyexpiredate,\r\n 'companyid':companyid,'username':user_name, 'email': None,'oprole':oprole,\r\n 'mobile': user_mobile, 'role':user_role, 'imageUrl':user_profile,\"displaystatus\":displaystatus}\r\n\r\n #except AttributeError:\r\n # return {'status': 2, 'msg': '用户名或密码错误'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\"\"\"\r\n\r\n\r\n\r\n\r\ndef mobile_insert(smsvc, password, mobile):\r\n try:\r\n mobilecheck = re.findall(r\"1\\d{10}\", mobile)\r\n print(mobilecheck)\r\n passwordlen = len(password)\r\n user_sms_query = Sms.query.filter_by(user_mobile=mobile).first()\r\n\r\n if user_sms_query:\r\n smsvcode = user_sms_query.user_sms\r\n nowtime = datetime.now()\r\n smscreatetime = user_sms_query.createtime\r\n if (nowtime - smscreatetime).seconds >= 360:\r\n return {'status':7,'msg':'注册失败,验证码已失效'}\r\n else:\r\n smsvcode = None\r\n #0 为注册成功\r\n #1 为手机号码为空,请先填写手机号码\r\n #2 为手机号码格式不正确\r\n #3 为验证码为空\r\n #4 为验证码不正确\r\n #5 为密码长度不符合要求,长度需为6-20位\r\n #6 为手机号码已经被注册\r\n\r\n if mobile == 'null':\r\n return {'status': 1, 'msg': '请先填写手机号码'}\r\n elif phonecheck(mobile) == 'failure':\r\n return {'status': 2, 'msg': '手机号码格式不正确'}\r\n elif smsvc == 'null':\r\n return {'status':3, 'msg':'验证码不能为空'}\r\n elif smsvc != smsvcode and smsvc != '11111':\r\n return {'status': 4, 'msg': '短信验证码不正确'}\r\n verification_mobile = User.query.filter_by(mobile=mobile).first()\r\n if verification_mobile:\r\n return {'status': 6, 'msg': '手机号码已被注册'}\r\n\r\n userid = 'u' + generate_random_str(24)\r\n \r\n\r\n insert_mobile = User(username=mobile, mobile=mobile, password=password, role='1', userid=userid)\r\n db.session.add(insert_mobile)\r\n db.session.commit()\r\n check_opuser_querys = Opuser.query.filter_by(opmobile=mobile).all()\r\n if check_opuser_querys:\r\n change_user_role_query = User.query.filter_by(mobile=mobile).first()\r\n change_user_role_query.role = '0'\r\n for check_opuser in check_opuser_querys:\r\n check_opuser.userstatus = 'register'\r\n check_opuser.opuserid = userid\r\n db.session.commit()\r\n\r\n userinfors = User.query.filter_by(userid=userid).first()\r\n q_username = userinfors.username\r\n q_userid = userinfors.userid\r\n q_role = userinfors.role\r\n q_mobile = userinfors.mobile\r\n q_profile = userinfors.profile\r\n db.session.close()\r\n return {'status': 0, 'msg': '注册成功', 'mobile': q_mobile,\r\n 'userid':q_userid, 'username':q_username,\r\n 'role':q_role,'mobile':mobile,\r\n 'imageUrl': q_profile, 'token':q_userid+ '-11111'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': '数据库连接似乎出了问题'}\r\n\r\ndef password_jiaoyan(token, userid, password):\r\n try:\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'Ooooops, token不可用'}\r\n else:\r\n user_password_query = User.query.filter_by(userid=userid).first()\r\n user_password = user_password_query.password\r\n \r\n if user_password == password:\r\n db.session.close()\r\n return {'status': 0, 'msg': '校验成功'}\r\n else:\r\n db.session.close()\r\n return {'status': 2, 'msg': '密码错误'}\r\n\r\n except AttributeError:\r\n return {'status': 2, 'msg': 'Oooops, something is wrong'}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库似乎出了问题'}\r\n\r\ndef user_forget_password(smsvc, password, mobile):\r\n try:\r\n passwordlen = len(password)\r\n userexsitcheck = User.query.filter_by(mobile=mobile).first()\r\n\r\n if userexsitcheck is None:\r\n db.session.close()\r\n return {'status': 4, 'msg': '用户不存在'}\r\n\r\n user_sms_query = Sms.query.filter_by(user_mobile=mobile).first()\r\n if user_sms_query:\r\n smsvcode = user_sms_query.user_sms\r\n nowtime = datetime.now()\r\n smscreatetime = user_sms_query.createtime\r\n if (nowtime - smscreatetime).seconds >= 360:\r\n return {'status':5,'msg':'验证码已失效,请重新申请验证码'}\r\n else:\r\n smsvcode = None\r\n\r\n if smsvc != smsvcode and smsvc != '11111':\r\n db.session.close()\r\n return {'status': 1, 'msg':'验证码错误'}\r\n elif smsvc == 'null':\r\n db.session.close()\r\n return {'status': 2, 'msg': '验证码不能为空'}\r\n else:\r\n change_password_userid = User.query.filter_by(mobile=mobile).first()\r\n change_password_userid.password = password\r\n db.session.commit()\r\n return_userinfo = User.query.filter_by(mobile=mobile).first()\r\n q_username = return_userinfo.username\r\n q_userid = return_userinfo.userid\r\n return_usercompanyinfo = Opuser.query.filter_by(opmobile=mobile, default='true').first()\r\n if return_usercompanyinfo:\r\n q_companyid = return_usercompanyinfo.opcompanyid\r\n retuen_company_query = Company.query.filter_by(companyid=q_companyid).first()\r\n q_companyname = retuen_company_query.companyname\r\n q_companyrole = retuen_company_query.companyrole\r\n q_companyexpiredate = retuen_company_query.companyexpiredate\r\n else:\r\n q_companyid = None\r\n q_companyname = None\r\n q_companyrole = None\r\n q_companyexpiredate = None\r\n q_role = return_userinfo.role\r\n q_mobile = return_userinfo.mobile\r\n q_profile = return_userinfo.profile\r\n db.session.close()\r\n return {'status': 0, 'msg': '修改成功','mobile':q_mobile,'username': q_username,\r\n 'companyname': q_companyname, 'role': q_role, 'companyid': q_companyid,\r\n 'companyrole':q_companyrole,\r\n 'companyexpiredate':q_companyexpiredate, 'userid':q_userid, 'imageUrl': q_profile}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\n\r\ndef change_password(token, userid, newpassword, oldpassword):\r\n try:\r\n passwordlen = len(newpassword)\r\n if token != '11111':\r\n return {'status': 1, 'msg':'token无效'}\r\n else:\r\n return_userinfo = User.query.filter_by(userid=userid).first()\r\n password = return_userinfo.password\r\n if oldpassword == password:\r\n return_userinfo.password = newpassword\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '修改成功'}\r\n else:\r\n db.session.close()\r\n return {'status': 2, 'msg': '旧密码错误'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': '数据库连接似乎出了问题'}\r\n\r\ndef user_update_username(token, userid, newusername):\r\n try:\r\n if token != '11111':\r\n return {'status': 1, 'msg':'token无效'}\r\n elif len(newusername) > 12:\r\n return {'status': 2, 'msg': '用户名长度不符合要求,用户名应在12字以内'}\r\n else:\r\n # return_userinfo = User.query.filter_by(userid=userid).first()\r\n return_userinfo = User.query.filter_by(userid=userid).first()\r\n return_userinfo.username = newusername\r\n db.session.commit()\r\n db.session.close()\r\n\r\n return {'status': 0, 'msg': '修改成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': '数据库连接似乎出了问题'}\r\n\r\ndef user_update_mobile(smsvc, token, userid, newmobile):\r\n try:\r\n mobilecheck = re.findall(r\"1\\d{10}\", newmobile)\r\n print(mobilecheck)\r\n db.session.rollback()\r\n user_mobile_query = User.query.filter_by(mobile=newmobile).first()\r\n\r\n if user_mobile_query:\r\n db.session.close()\r\n return {'status': 4, 'msg':'手机号码已存在'}\r\n\r\n user_sms_query = Sms.query.filter_by(user_mobile=newmobile).first()\r\n if user_sms_query:\r\n smsvcode = user_sms_query.user_sms\r\n nowtime = datetime.now()\r\n smscreatetime = user_sms_query.createtime\r\n if (nowtime - smscreatetime).seconds >= 360:\r\n return {'status':5,'msg':'注册失败,验证码已失效'}\r\n else:\r\n smsvcode = None\r\n\r\n if smsvc != smsvcode and smsvc != '11111':\r\n return {'status': 1, 'msg':'验证码错误'}\r\n elif token != '11111':\r\n return {'status': 2, 'msg': 'token无效'}\r\n elif phonecheck(newmobile) == 'failure':\r\n return {'status': 3, 'msg': '请输入正确的手机号码'}\r\n else:\r\n return_userinfo = User.query.filter_by(userid=userid).first()\r\n return_userinfo.mobile = newmobile\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '修改成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': '数据库连接似乎出了问题'}\r\n\r\ndef user_default_company(token, userid):\r\n try:\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n user_query = User.query.filter_by(userid=userid).first()\r\n\r\n mobile = user_query.mobile\r\n user_id = user_query.userid\r\n user_role = user_query.role\r\n user_name = user_query.username\r\n user_profile = user_query.profile\r\n if user_query.role == '1':\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n if user_query.role == '2':\r\n user_youke_company_query = Opuser.query.filter_by(opuserid=userid).first()\r\n youkecompanyid = user_youke_company_query.opcompanyid\r\n youkecompanyinfo = Company.query.filter_by(companyid=youkecompanyid).first()\r\n youke_companyexpiredate = youkecompanyinfo.companyexpiredate\r\n youke_companyname = youkecompanyinfo.companyname\r\n youke_companrole = youkecompanyinfo.companyrole\r\n\r\n if youke_companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(youke_companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": youkecompanyid,\r\n \"companyname\": youke_companyname,\r\n \"companyrole\": youke_companrole,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n\r\n user_default_company_query = Opuser.query.filter_by(opuserid=userid, default='true').first()\r\n\r\n if user_default_company_query:\r\n user_oprole = user_default_company_query.oprole\r\n defaultcompanyid = user_default_company_query.opcompanyid\r\n default_companyinfo = Company.query.filter_by(companyid=defaultcompanyid).first()\r\n default_companyexpiredate = default_companyinfo.companyexpiredate\r\n default_companyname = default_companyinfo.companyname\r\n default_companrole = default_companyinfo.companyrole\r\n if default_companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(default_companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": defaultcompanyid,\r\n \"companyname\": default_companyname,\r\n \"companyrole\": default_companrole,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"查询成功\",\r\n \"oprole\": user_oprole,\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n else:\r\n user_default_allcompany_query = Opuser.query.filter_by(opuserid=userid).all()\r\n\r\n opcompany_list = []\r\n for opuser_company_query in user_default_allcompany_query:\r\n if opuser_company_query.oprole != '2':\r\n opcompany_dict = {}\r\n opcompanyid = opuser_company_query.opcompanyid\r\n opuserid = opuser_company_query.opuserid\r\n opusername = opuser_company_query.opusername\r\n opmobile = opuser_company_query.opmobile\r\n oprole = opuser_company_query.oprole\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opcompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n companyexpiredate = opcompanyinfo_query.companyexpiredate\r\n\r\n if companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n\r\n opcompany_dict['companyid'] = opcompanyid\r\n opcompany_dict['userid'] = opuserid\r\n opcompany_dict['username'] = opusername\r\n opcompany_dict['companyname'] = opcompanyname\r\n opcompany_dict['companyrole'] = opcompanyrole\r\n opcompany_dict['companyexpiredate'] = request_create_time_chuo\r\n opcompany_dict['mobile'] = opmobile\r\n opcompany_dict['oprole'] = oprole\r\n opcompany_list.append(opcompany_dict)\r\n db.session.close()\r\n return {'status': 0, 'msg': '查询成功', 'choice': {'status': 'false', 'companyinfo': opcompany_list}}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\r\n\r\n\"\"\"\r\ndef user_default_company(token, userid):\r\n\r\n try:\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n user_query = User.query.filter_by(userid=userid).first()\r\n\r\n mobile = user_query.mobile\r\n user_id = user_query.userid\r\n user_role = user_query.role\r\n user_name = user_query.username\r\n user_profile = user_query.profile\r\n if user_query.role == '1':\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n if user_query.role == '2':\r\n user_youke_company_query = Opuser.query.filter_by(opuserid=userid).first()\r\n youkecompanyid = user_youke_company_query.opcompanyid\r\n youkecompanyinfo = Company.query.filter_by(companyid=youkecompanyid).first()\r\n youke_companyexpiredate = youkecompanyinfo.companyexpiredate\r\n youke_companyname = youkecompanyinfo.companyname\r\n youke_companrole = youkecompanyinfo.companyrole\r\n\r\n if youke_companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(youke_companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": youkecompanyid,\r\n \"companyname\": youke_companyname,\r\n \"companyrole\": youke_companrole,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n\r\n # user_default_company_query = Opuser.query.filter_by(opuserid=userid, default='true').first()\r\n #\r\n # if user_default_company_query:\r\n # user_oprole = user_default_company_query.oprole\r\n # defaultcompanyid = user_default_company_query.opcompanyid\r\n # default_companyinfo = Company.query.filter_by(companyid=defaultcompanyid).first()\r\n # default_companyexpiredate = default_companyinfo.companyexpiredate\r\n # default_companyname = default_companyinfo.companyname\r\n # default_companrole = default_companyinfo.companyrole\r\n # if default_companyexpiredate:\r\n # request_create_time_chuo = int(time.mktime(default_companyexpiredate.timetuple()))\r\n # else:\r\n # request_create_time_chuo = None\r\n #\r\n # db.session.close()\r\n # return {\r\n # \"companyexpiredate\": request_create_time_chuo,\r\n # \"companyid\": defaultcompanyid,\r\n # \"companyname\": default_companyname,\r\n # \"companyrole\": default_companrole,\r\n # \"imageUrl\": user_profile,\r\n # \"mobile\": mobile,\r\n # \"msg\": \"查询成功\",\r\n # \"oprole\": user_oprole,\r\n # \"role\": user_role,\r\n # \"status\": 0,\r\n # \"userid\": user_id,\r\n # \"username\": user_name,\r\n # }\r\n\r\n user_default_company_query = Opuser.query.filter_by(opuserid=userid).all()\r\n if user_default_company_query:\r\n\r\n if len(user_default_company_query) == 1:\r\n user_oprole = user_default_company_query.oprole\r\n defaultcompanyid = user_default_company_query.opcompanyid\r\n default_companyinfo = Company.query.filter_by(companyid=defaultcompanyid).first()\r\n default_companyexpiredate = default_companyinfo.companyexpiredate\r\n default_companyname = default_companyinfo.companyname\r\n default_companrole = default_companyinfo.companyrole\r\n if default_companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(default_companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": defaultcompanyid,\r\n \"companyname\": default_companyname,\r\n \"companyrole\": default_companrole,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"查询成功\",\r\n \"oprole\": user_oprole,\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n else:\r\n user_default_allcompany_query = Opuser.query.filter_by(opuserid=userid).all()\r\n\r\n opcompany_list = []\r\n for opuser_company_query in user_default_allcompany_query:\r\n if opuser_company_query.oprole != '2':\r\n opcompany_dict = {}\r\n opcompanyid = opuser_company_query.opcompanyid\r\n opuserid = opuser_company_query.opuserid\r\n opusername = opuser_company_query.opusername\r\n opmobile = opuser_company_query.opmobile\r\n oprole = opuser_company_query.oprole\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opcompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n companyexpiredate = opcompanyinfo_query.companyexpiredate\r\n\r\n if companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n\r\n opcompany_dict['companyid'] = opcompanyid\r\n opcompany_dict['userid'] = opuserid\r\n opcompany_dict['username'] = opusername\r\n opcompany_dict['companyname'] = opcompanyname\r\n opcompany_dict['companyrole'] = opcompanyrole\r\n opcompany_dict['companyexpiredate'] = request_create_time_chuo\r\n opcompany_dict['mobile'] = opmobile\r\n opcompany_dict['oprole'] = oprole\r\n opcompany_list.append(opcompany_dict)\r\n db.session.close()\r\n return {'status': 0, 'msg': '查询成功', 'choice': {'status': 'false', 'companyinfo': opcompany_list}}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\"\"\"\r\n\r\n\"\"\"\r\ndef user_login(mobile, password):\r\n try:\r\n user_query = User.query.filter_by(mobile=mobile).first()\r\n\r\n if user_query is None:\r\n db.session.close()\r\n return {'status': 1, 'msg': '用户名或密码错误'}\r\n user_mark = user_query.mark\r\n if user_mark == \"userdisabled\":\r\n return {'status': 10, 'msg': '用户已被禁用'}\r\n \r\n user_password = user_query.password\r\n\r\n if user_password != password:\r\n return {'status': 1, 'msg': '用户名或密码错误'}\r\n\r\n user_id = user_query.userid\r\n user_role = user_query.role\r\n user_name = user_query.username\r\n user_profile = user_query.profile\r\n #当用户申请加入公司但是处于审核状态\r\n if user_query.role == '2':\r\n user_youke_company_query = Opuser.query.filter_by(opuserid=user_id).first()\r\n youkecompanyid = user_youke_company_query.opcompanyid\r\n youkecompanyinfo = Company.query.filter_by(companyid=youkecompanyid).first()\r\n youke_companyexpiredate = youkecompanyinfo.companyexpiredate\r\n if youke_companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(youke_companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n youke_companyname = youkecompanyinfo.companyname\r\n youke_companrole = youkecompanyinfo.companyrole\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": youkecompanyid,\r\n \"companyname\": youke_companyname,\r\n \"companyrole\": youke_companrole,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n opuser_company_default_querys = Opuser.query.filter_by(opmobile=mobile).first()\r\n #当用户未加入公司\r\n if opuser_company_default_querys is None:\r\n logintime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\r\n user_query.logintime = logintime\r\n db.session.commit()\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n opuser_company_default_querys = Opuser.query.filter_by(opmobile=mobile, default='true').first()\r\n #当用户已经加入公司,并且没有默认公司\r\n if opuser_company_default_querys is None:\r\n opuser_company_querys = Opuser.query.filter_by(opmobile=mobile).all()\r\n opcompany_list = []\r\n checkopcompany = []\r\n for opuser_company_query in opuser_company_querys:\r\n if opuser_company_query.oprole != '2':\r\n opcompany_dict = {}\r\n opcompanyid = opuser_company_query.opcompanyid\r\n opuserid = opuser_company_query.opuserid\r\n opusername = opuser_company_query.opusername\r\n opmobile = opuser_company_query.opmobile\r\n oprole = opuser_company_query.oprole\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opcompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n companyexpiredate = opcompanyinfo_query.companyexpiredate\r\n if companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n opcompany_dict['companyid'] = opcompanyid\r\n opcompany_dict['userid'] = opuserid\r\n opcompany_dict['username'] = opusername\r\n opcompany_dict['companyname'] = opcompanyname\r\n opcompany_dict['companyrole'] = opcompanyrole\r\n opcompany_dict['companyexpiredate'] = request_create_time_chuo\r\n opcompany_dict['mobile'] = opmobile\r\n opcompany_dict['oprole'] = oprole\r\n opcompany_list.append(opcompany_dict)\r\n else:\r\n checkopcompany.append('check')\r\n if len(opuser_company_querys) == len(checkopcompany):\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n else:\r\n db.session.close()\r\n return {'status': 0, 'msg': '登录成功','choice': {'status':'false', 'companyinfo': opcompany_list}, 'token':user_id + '-11111'}\r\n\r\n if opuser_company_default_querys:\r\n # 当用户已经加入公司,并且有默认公司\r\n print(opuser_company_default_querys.opmobile)\r\n opusercompanyid_default = opuser_company_default_querys.opcompanyid\r\n opuseremail_default = opuser_company_default_querys.opemail\r\n opusercompanyinfo_default = Company.query.filter_by(companyid=opusercompanyid_default).first()\r\n opusercompanyname_default = opusercompanyinfo_default.companyname\r\n opusercompanyrole_default = opusercompanyinfo_default.companyrole\r\n opusercompanyexpire_default = opusercompanyinfo_default.companyexpiredate\r\n\r\n if opusercompanyexpire_default:\r\n request_create_time_chuo = int(time.mktime(opusercompanyexpire_default.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n myloginopmobile = opuser_company_default_querys.opmobile\r\n myloginoprole = opuser_company_default_querys.oprole\r\n myloginopusername = opuser_company_default_querys.opusername\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": opusercompanyid_default,\r\n \"companyname\": opusercompanyname_default,\r\n \"companyrole\": opusercompanyrole_default,\r\n \"email\": opuseremail_default,\r\n \"imageUrl\": user_profile,\r\n \"opmobile\": myloginopmobile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"oprole\": myloginoprole,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n \"opusername\": myloginopusername,\r\n\r\n }\r\n #0 为 登录成功\r\n #1 为用户名或密码错误\r\n #2 为用户名或密码错误\r\n #3 为数据库连接错误\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接似乎出了问题'}\r\n\"\"\"\r\n\r\n\"\"\"\r\ndef user_login(mobile, password):\r\n try:\r\n user_query = User.query.filter_by(mobile=mobile).first()\r\n\r\n if user_query is None:\r\n db.session.close()\r\n return {'status': 1, 'msg': '用户名或密码错误'}\r\n user_mark = user_query.mark\r\n if user_mark == \"userdisabled\":\r\n return {'status': 10, 'msg': '用户已被禁用'}\r\n\r\n user_password = user_query.password\r\n\r\n if user_password != password:\r\n return {'status': 1, 'msg': '用户名或密码错误'}\r\n\r\n user_id = user_query.userid\r\n user_role = user_query.role\r\n user_name = user_query.username\r\n user_profile = user_query.profile\r\n # 当用户申请加入公司但是处于审核状态\r\n if user_query.role == '2':\r\n user_youke_company_query = Opuser.query.filter_by(opuserid=user_id).first()\r\n youkecompanyid = user_youke_company_query.opcompanyid\r\n youkecompanyinfo = Company.query.filter_by(companyid=youkecompanyid).first()\r\n youke_companyexpiredate = youkecompanyinfo.companyexpiredate\r\n if youke_companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(youke_companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n youke_companyname = youkecompanyinfo.companyname\r\n youke_companrole = youkecompanyinfo.companyrole\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": youkecompanyid,\r\n \"companyname\": youke_companyname,\r\n \"companyrole\": youke_companrole,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n opuser_company_default_querys = Opuser.query.filter_by(opmobile=mobile).first()\r\n # 当用户未加入公司\r\n if opuser_company_default_querys is None:\r\n logintime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\r\n user_query.logintime = logintime\r\n db.session.commit()\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n opuser_company_querys = Opuser.query.filter_by(opmobile=mobile).all()\r\n # 当用户加入公司\r\n if opuser_company_querys:\r\n opcompany_list = []\r\n checkopcompany = []\r\n for opuser_company_query in opuser_company_querys:\r\n if opuser_company_query.oprole != '2':\r\n opcompany_dict = {}\r\n opcompanyid = opuser_company_query.opcompanyid\r\n opuserid = opuser_company_query.opuserid\r\n opusername = opuser_company_query.opusername\r\n opmobile = opuser_company_query.opmobile\r\n oprole = opuser_company_query.oprole\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opcompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n companyexpiredate = opcompanyinfo_query.companyexpiredate\r\n if companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n opcompany_dict['companyid'] = opcompanyid\r\n opcompany_dict['userid'] = opuserid\r\n opcompany_dict['username'] = opusername\r\n opcompany_dict['companyname'] = opcompanyname\r\n opcompany_dict['companyrole'] = opcompanyrole\r\n opcompany_dict['companyexpiredate'] = request_create_time_chuo\r\n opcompany_dict['mobile'] = opmobile\r\n opcompany_dict['oprole'] = oprole\r\n opcompany_list.append(opcompany_dict)\r\n else:\r\n checkopcompany.append('check')\r\n if len(opuser_company_querys) == len(checkopcompany):\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n else:\r\n db.session.close()\r\n return {'status': 0, 'msg': '登录成功', 'choice': {'status': 'false', 'companyinfo': opcompany_list},\r\n 'token': user_id + '-11111'}\r\n\r\n\r\n # 0 为 登录成功\r\n # 1 为用户名或密码错误\r\n # 2 为用户名或密码错误\r\n # 3 为数据库连接错误\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status': 3, 'Oooops': '数据库连接似乎出了问题'}\r\n\"\"\"\r\n\r\n\"\"\"\r\nimport hashlib\r\ndef my_md5(s,salt=''): #加盐,盐的默认值是空\r\n s = s + salt\r\n news = str(s).encode() #先变成bytes类型才能加密\r\n m = hashlib.md5(news) #创建md5对象\r\n return m.hexdigest() #获取加密后的字符串\r\n\"\"\"\r\n\r\n\"\"\"\r\ndef user_login(mobile, password):\r\n try:\r\n user_query = User.query.filter_by(mobile=mobile).first()\r\n\r\n if user_query is None:\r\n db.session.close()\r\n return {'status': 1, 'msg': '用户名或密码错误'}\r\n user_mark = user_query.mark\r\n if user_mark == \"userdisabled\":\r\n return {'status': 10, 'msg': '用户已被禁用'}\r\n\r\n user_password = user_query.password\r\n \r\n\r\n if user_password != password:\r\n return {'status': 1, 'msg': '用户名或密码错误'}\r\n\r\n user_id = user_query.userid\r\n user_role = user_query.role\r\n user_name = user_query.username\r\n user_profile = user_query.profile\r\n # 当用户申请加入公司但是处于审核状态\r\n if user_query.role == '2':\r\n user_youke_company_query = Opuser.query.filter_by(opuserid=user_id).first()\r\n youkecompanyid = user_youke_company_query.opcompanyid\r\n youkecompanyinfo = Company.query.filter_by(companyid=youkecompanyid).first()\r\n youke_companyexpiredate = youkecompanyinfo.companyexpiredate\r\n if youke_companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(youke_companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n youke_companyname = youkecompanyinfo.companyname\r\n youke_companrole = youkecompanyinfo.companyrole\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": youkecompanyid,\r\n \"companyname\": youke_companyname,\r\n \"companyrole\": youke_companrole,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n opuser_company_default_querys = Opuser.query.filter_by(opmobile=mobile).first()\r\n # 当用户未加入公司\r\n if opuser_company_default_querys is None:\r\n logintime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\r\n user_query.logintime = logintime\r\n db.session.commit()\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n companycount = 0\r\n opuserlist = []\r\n opusers_query = Opuser.query.filter_by(opmobile=mobile).all()\r\n for opuser in opusers_query:\r\n opcompanyid = opuser.opcompanyid\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opcompanyid,disable=0).first()\r\n if opcompanyinfo_query:\r\n companycount += 1\r\n opuserlist.append(opuser)\r\n if companycount >= 2:\r\n opcompany_list = []\r\n checkopcompany = []\r\n for opuser_company_query in opuserlist:\r\n if opuser_company_query.oprole != '2':\r\n opcompany_dict = {}\r\n opcompanyid = opuser_company_query.opcompanyid\r\n opuserid = opuser_company_query.opuserid\r\n opusername = opuser_company_query.opusername\r\n opmobile = opuser_company_query.opmobile\r\n oprole = opuser_company_query.oprole\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opcompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n companyexpiredate = opcompanyinfo_query.companyexpiredate\r\n if companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n opcompany_dict['companyid'] = opcompanyid\r\n opcompany_dict['userid'] = opuserid\r\n opcompany_dict['username'] = opusername\r\n opcompany_dict['companyname'] = opcompanyname\r\n opcompany_dict['companyrole'] = opcompanyrole\r\n opcompany_dict['companyexpiredate'] = request_create_time_chuo\r\n opcompany_dict['mobile'] = opmobile\r\n opcompany_dict['oprole'] = oprole\r\n opcompany_list.append(opcompany_dict)\r\n else:\r\n checkopcompany.append('check')\r\n if len(opuserlist) == len(checkopcompany):\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n else:\r\n db.session.close()\r\n return {'status': 0, 'msg': '登录成功', 'choice': {'status': 'false', 'companyinfo': opcompany_list},\r\n 'token': user_id + '-11111'}\r\n elif companycount == 1:\r\n opuser_company_default_querys = opuserlist[0]\r\n opusercompanyid_default = opuser_company_default_querys.opcompanyid\r\n opusersdefault = Opuser.query.filter_by(opmobile=mobile).all()\r\n for opuserdefault in opusersdefault:\r\n if opuserdefault.opcompanyid == opusercompanyid_default:\r\n opuserdefault.default = \"true\"\r\n db.session.commit()\r\n else:\r\n opuserdefault.default = \"false\"\r\n db.session.commit()\r\n opuseremail_default = opuser_company_default_querys.opemail\r\n opusercompanyinfo_default = Company.query.filter_by(companyid=opusercompanyid_default).first()\r\n opusercompanyname_default = opusercompanyinfo_default.companyname\r\n opusercompanyrole_default = opusercompanyinfo_default.companyrole\r\n opusercompanyexpire_default = opusercompanyinfo_default.companyexpiredate\r\n\r\n if opusercompanyexpire_default:\r\n request_create_time_chuo = int(time.mktime(opusercompanyexpire_default.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n myloginopmobile = opuser_company_default_querys.opmobile\r\n myloginoprole = opuser_company_default_querys.oprole\r\n myloginopusername = opuser_company_default_querys.opusername\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": opusercompanyid_default,\r\n \"companyname\": opusercompanyname_default,\r\n \"companyrole\": opusercompanyrole_default,\r\n \"email\": opuseremail_default,\r\n \"imageUrl\": user_profile,\r\n \"opmobile\": myloginopmobile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"oprole\": myloginoprole,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n \"opusername\": myloginopusername,\r\n\r\n }\r\n else:\r\n\r\n\r\n # 当用户只加入一家公司且被禁用\r\n\r\n logintime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\r\n user_query.logintime = logintime\r\n oneopuser = Opuser.query.filter_by(opuserid=user_query.userid).first()\r\n user_query.role = \"1\"\r\n db.session.commit()\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n \r\n db.session.close()\r\n # 0 为 登录成功\r\n # 1 为用户名或密码错误\r\n # 2 为用户名或密码错误\r\n # 3 为数据库连接错误\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status': 3, 'Oooops': '数据库连接似乎出了问题'}\r\n\"\"\"\r\n\r\ndef user_login(mobile, password): \r\n try:\r\n user_query = User.query.filter_by(mobile=mobile).first()\r\n\r\n if user_query is None:\r\n db.session.close()\r\n return {'status': 1, 'msg': '用户名或密码错误'}\r\n \"\"\"\r\n user_mark = user_query.mark\r\n if user_mark == \"userdisabled\":\r\n return {'status': 10, 'msg': '用户已被禁用'}\r\n \"\"\"\r\n user_password = user_query.password\r\n \r\n \"\"\"\r\n salt = \"\"\r\n user_password = my_md5(user_password,salt=salt)\r\n \"\"\"\r\n\r\n if user_password != password:\r\n return {'status': 1, 'msg': '用户名或密码错误'}\r\n\r\n user_id = user_query.userid\r\n user_role = user_query.role\r\n user_name = user_query.username\r\n user_profile = user_query.profile\r\n # 当用户申请加入公司但是处于审核状态\r\n if user_query.role == '2':\r\n user_mark = user_query.mark\r\n if user_mark == \"userdisabled\":\r\n return {'status':10,'msg':\"用户已被禁用\"}\r\n user_youke_company_query = Opuser.query.filter_by(opuserid=user_id).first()\r\n youkecompanyid = user_youke_company_query.opcompanyid\r\n youkecompanyinfo = Company.query.filter_by(companyid=youkecompanyid).first()\r\n youke_companyexpiredate = youkecompanyinfo.companyexpiredate\r\n if youke_companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(youke_companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n youke_companyname = youkecompanyinfo.companyname\r\n youke_companrole = youkecompanyinfo.companyrole\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": youkecompanyid,\r\n \"companyname\": youke_companyname,\r\n \"companyrole\": youke_companrole,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n opuser_company_default_querys = Opuser.query.filter_by(opmobile=mobile).first()\r\n # 当用户未加入公司\r\n if opuser_company_default_querys is None:\r\n user_mark = user_query.mark\r\n if user_mark == \"userdisabled\":\r\n return {'status': 10, 'msg': \"用户已被禁用\"}\r\n logintime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\r\n user_query.logintime = logintime\r\n db.session.commit()\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n\r\n companycount = 0\r\n opuserlist = []\r\n opusers_query = Opuser.query.filter_by(opmobile=mobile,company_user_status=\"3\").all()\r\n for opuser in opusers_query:\r\n opcompanyid = opuser.opcompanyid\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opcompanyid,disable=0).first()\r\n if opcompanyinfo_query:\r\n companycount += 1\r\n opuserlist.append(opuser)\r\n if companycount >= 2:\r\n opcompany_list = []\r\n checkopcompany = []\r\n for opuser_company_query in opuserlist:\r\n if opuser_company_query.oprole != '2':\r\n opcompany_dict = {}\r\n opcompanyid = opuser_company_query.opcompanyid\r\n opuserid = opuser_company_query.opuserid\r\n opusername = opuser_company_query.opusername\r\n opmobile = opuser_company_query.opmobile\r\n oprole = opuser_company_query.oprole\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opcompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n companyexpiredate = opcompanyinfo_query.companyexpiredate\r\n if companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n opcompany_dict['companyid'] = opcompanyid\r\n opcompany_dict['userid'] = opuserid\r\n opcompany_dict['username'] = opusername\r\n opcompany_dict['companyname'] = opcompanyname\r\n opcompany_dict['companyrole'] = opcompanyrole\r\n opcompany_dict['companyexpiredate'] = request_create_time_chuo\r\n opcompany_dict['mobile'] = opmobile\r\n opcompany_dict['oprole'] = oprole\r\n opcompany_list.append(opcompany_dict)\r\n else:\r\n checkopcompany.append('check')\r\n if len(opuserlist) == len(checkopcompany):\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n else:\r\n db.session.close()\r\n return {'status': 0, 'msg': '登录成功', 'choice': {'status': 'false', 'companyinfo': opcompany_list},\r\n 'token': user_id + '-11111'}\r\n elif companycount == 1:\r\n opuser_company_default_querys = opuserlist[0]\r\n opusercompanyid_default = opuser_company_default_querys.opcompanyid\r\n opusersdefault = Opuser.query.filter_by(opmobile=mobile).all()\r\n for opuserdefault in opusersdefault:\r\n if opuserdefault.opcompanyid == opusercompanyid_default:\r\n opuserdefault.default = \"true\"\r\n db.session.commit()\r\n else:\r\n opuserdefault.default = \"false\"\r\n db.session.commit()\r\n opuseremail_default = opuser_company_default_querys.opemail\r\n opusercompanyinfo_default = Company.query.filter_by(companyid=opusercompanyid_default).first()\r\n opusercompanyname_default = opusercompanyinfo_default.companyname\r\n opusercompanyrole_default = opusercompanyinfo_default.companyrole\r\n opusercompanyexpire_default = opusercompanyinfo_default.companyexpiredate\r\n\r\n if opusercompanyexpire_default:\r\n request_create_time_chuo = int(time.mktime(opusercompanyexpire_default.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n myloginopmobile = opuser_company_default_querys.opmobile\r\n myloginoprole = opuser_company_default_querys.oprole\r\n myloginopusername = opuser_company_default_querys.opusername\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": request_create_time_chuo,\r\n \"companyid\": opusercompanyid_default,\r\n \"companyname\": opusercompanyname_default,\r\n \"companyrole\": opusercompanyrole_default,\r\n \"email\": opuseremail_default,\r\n \"imageUrl\": user_profile,\r\n \"opmobile\": myloginopmobile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"oprole\": myloginoprole,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n \"opusername\": myloginopusername,\r\n\r\n }\r\n else:\r\n\r\n\r\n # 当用户只加入一家公司且被禁用\r\n\r\n logintime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\r\n user_query.logintime = logintime\r\n oneopuser = Opuser.query.filter_by(opuserid=user_query.userid).first()\r\n user_query.role = \"1\"\r\n db.session.commit()\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": None,\r\n \"companyid\": None,\r\n \"companyname\": None,\r\n \"companyrole\": None,\r\n \"email\": None,\r\n \"imageUrl\": user_profile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": user_role,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n }\r\n \r\n db.session.close()\r\n # 0 为 登录成功\r\n # 1 为用户名或密码错误\r\n # 2 为用户名或密码错误\r\n # 3 为数据库连接错误\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status': 3, 'Oooops': '数据库连接似乎出了问题'}\r\n\r\n\r\ndef company_query(companyname, token):\r\n try:\r\n #2 代表邮箱为空\r\n #3 代表用户名为空\r\n #4 代表公司名称为空\r\n #5 该公司已经被注册\r\n\r\n if token != '11111':\r\n print(token)\r\n return {'status': 1, 'msg': 'token无效'}\r\n verification_company = Company.query.all()\r\n if verification_company:\r\n companylist = []\r\n for company in verification_company:\r\n companyinfo_dict = {}\r\n company_id = company.companyid\r\n print(company_id)\r\n admin_query = Opuser.query.filter_by(opcompanyid=company_id, oprole='4').first()\r\n admin_username = admin_query.opusername\r\n\r\n companyexpiredate = company.companyexpiredate\r\n\r\n if companyexpiredate:\r\n request_create_time_chuo = int(time.mktime(companyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n\r\n companyinfo_dict['admin'] = admin_username\r\n companyinfo_dict['companyname'] = company.companyname\r\n companyinfo_dict['companyid'] = company.companyid\r\n companyinfo_dict['companyrole'] = company.companyrole\r\n companyinfo_dict['companyexpiredate'] = request_create_time_chuo\r\n companylist.append(companyinfo_dict)\r\n if companyname is None:\r\n db.session.close()\r\n return {'status': 0, 'companys': companylist,'msg': \"查询成功\"}\r\n else:\r\n mohu_query_list = []\r\n for search_company in companylist:\r\n print(search_company)\r\n search_company_status = search_company['companyname']\r\n if search_company_status.find(companyname) != -1:\r\n print('hhhhhhhhhhhhhhhhh')\r\n mohu_query_list.append(search_company)\r\n # else:\r\n # return {'status':'2','msg':'公司未搜索到'}\r\n if len(mohu_query_list)==0:\r\n return {'status':'2','msg':'公司未搜索到'}\r\n db.session.close()\r\n return {'status': 0, 'companys': mohu_query_list, 'msg': \"查询成功\"}\r\n\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': '数据库连接似乎出了问题'}\r\n\r\n#这个接口是我新添的,没有暴露出来\r\ndef backstagecm1(userid, token, searchcompanyid):\r\n if token != '11111':\r\n return {'status':1, 'msg':'token不可用'}\r\n\r\n #公司总数量\r\n rs_query_list = []\r\n #companys_query = Company.query.all()\r\n\r\n companys_query = Company.query.filter_by(companyid=searchcompanyid).all()\r\n\r\n \r\n\r\n for company_query in companys_query:\r\n companyid = company_query.companyid\r\n companyname = company_query.companyname\r\n disable = company_query.disable\r\n companyexpire = company_query.companyexpiredate\r\n companyrole = company_query.companyrole\r\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\r\n totalcompanyusers = len(user_query)\r\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\r\n adminusername = adminuser_query.opusername\r\n adminuserid = adminuser_query.opuserid\r\n adminmobile = adminuser_query.opmobile\r\n defaultcompany = adminuser_query.default\r\n admimemail = company_query.companyemail\r\n companymark = company_query.companymark\r\n\r\n if companyexpire:\r\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\r\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,'adminuserid': adminuserid,\r\n 'adminmobile': adminmobile,'adminemail':admimemail,\r\n 'companyexpire': companyexpire,\"disable\":disable,\r\n 'companyrole':companyrole, 'members':totalcompanyusers,\r\n 'companymark': companymark,'defaultcompany':defaultcompany\r\n }\r\n rs_query_list.append(rs_query_dict)\r\n db.session.close()\r\n return {\"status\": 0, \"msg\":\"查询成功\",\"companyinfo\": rs_query_list}\r\n\r\ndef opusersinfo(userid, token, searchcompanyid):\r\n if token != '11111':\r\n return {'status':1, 'msg':'token不可用'}\r\n\r\n rs_query_list = []\r\n #companys_query = Company.query.all()\r\n\r\n company_query = Company.query.filter_by(companyid=searchcompanyid).first()\r\n companyid = company_query.companyid\r\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\r\n for opuser in user_query:\r\n if opuser.oprole == '4' or opuser.oprole == '6':\r\n rs_query_dict = {'opuserid': opuser.opuserid }\r\n rs_query_list.append(rs_query_dict)\r\n db.session.close()\r\n return {\"status\": 0, \"msg\":\"查询成功\",\"opuserinfo\": rs_query_list}\r\n\r\ndef hostinfo(userid, token, hostip):\r\n if token != '11111':\r\n return {'status':1,'msg':'token不可用'}\r\n print(\"兹纳库嚓嚓灿灿拿出拉开\"+hostip)\r\n rs_query_list = []\r\n host =Monitor.query.filter_by(zabbixhostip=\"10.0.60.175\").first()\r\n hostname = host.zabbixhostname\r\n rs_query_dict = {'hostname': hostname}\r\n rs_query_list.append(rs_query_dict)\r\n db.session.close()\r\n return {\"status\": 0, \"msg\":\"查询成功\",\"hostinfo\": rs_query_list}\r\n\r\n\r\n\"\"\"\r\ndef company_insert(email, username, companyname, userid, token):\r\n try:\r\n #2 代表邮箱为空\r\n #3 代表用户名为空\r\n #4 代表公司名称为空\r\n #5 该公司已经被注册\r\n\r\n print(len(companyname))\r\n\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n\r\n if len(companyname) > 50:\r\n return {'status': 6, 'msg': '公司名称不符合长度要求,公司名称应在50字以内'}\r\n #elif re.search(r'^([a-zA-Z0-9_\\\\-\\\\.]+)@((\\\\[[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.)|(([a-zA-Z0-9\\\\-]+\\\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\\\]?)$',companyname):\r\n #return {'status':'7','msg':'公司名称中不允许包含特殊字符,请重新输入'}\r\n elif len(email)== 0:\r\n return {'status': 2, 'msg': '请先填写邮箱'}\r\n elif re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\\.[com,cn,net]{1,3}$',email) is None:\r\n return {'status':'7','msg':'请输入有效邮箱地址'}\r\n elif len(username) == 0:\r\n return {'status': 3, 'msg': '请先填写用户名'}\r\n elif len(companyname) ==0:\r\n return {'status':4, 'msg':'请先填写公司名称'}\r\n verification_company = Company.query.filter_by(companyname=companyname).first()\r\n\r\n if verification_company:\r\n db.session.close()\r\n return {'status': 5, 'msg': '该公司已被注册'}\r\n else:\r\n companyid = 'c' + generate_random_str(24)\r\n user_query = User.query.filter_by(userid=userid).first()\r\n user_query.role = '0'\r\n user_mobile = user_query.mobile\r\n db.session.commit()\r\n\r\n insert_company = Company(companyid=companyid, companyname=companyname, companyrole='1')\r\n insert_opuser = Opuser(opusername=username, opuserid=userid,\r\n opmobile=user_mobile,opcompanyid=companyid,\r\n default='true', oprole='4', opemail=email,\r\n )\r\n db.session.add(insert_company)\r\n db.session.add(insert_opuser)\r\n db.session.commit()\r\n chatbotinfo = insert_chatbot(companyid)\r\n db.session.close()\r\n return {'status': 0, 'msg': '公司创建成功','chatbotinfo':chatbotinfo,\r\n 'companyid':companyid,'mobile':user_mobile,\r\n 'companyexpiredate':None,\r\n 'email': email, 'username': username,\r\n 'companyname': companyname,'companyrole':'1',\r\n 'oprole': '4','role': '0'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': '数据库连接似乎出了问题'}\r\n\"\"\"\r\n\r\n\r\n\r\n\r\ndef company_insert(email, username, companyname, userid, token):\r\n try:\r\n #2 代表邮箱为空\r\n #3 代表用户名为空\r\n #4 代表公司名称为空\r\n #5 该公司已经被注册\r\n\r\n print(len(companyname))\r\n\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n\r\n if len(companyname) > 50:\r\n return {'status': 6, 'msg': '公司名称不符合长度要求,公司名称应在50字以内'}\r\n #elif re.search(r'^([a-zA-Z0-9_\\\\-\\\\.]+)@((\\\\[[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.)|(([a-zA-Z0-9\\\\-]+\\\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\\\]?)$',companyname):\r\n #return {'status':'7','msg':'公司名称中不允许包含特殊字符,请重新输入'}\r\n elif len(email)== 0:\r\n return {'status': 2, 'msg': '请先填写邮箱'}\r\n elif re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\\.[com,cn,net]{1,3}$',email) is None:\r\n return {'status':'7','msg':'请输入有效邮箱地址'}\r\n elif len(username) == 0:\r\n return {'status': 3, 'msg': '请先填写用户名'}\r\n elif len(username) > 20:\r\n return {'status': 6, 'msg': '用户名称不符合长度要求,用户名称应在20字以内'}\r\n elif len(companyname) ==0:\r\n return {'status':4, 'msg':'请先填写公司名称'}\r\n verification_company = Company.query.filter_by(companyname=companyname).first()\r\n\r\n if verification_company:\r\n db.session.close()\r\n return {'status': 5, 'msg': '该公司已被注册'}\r\n else:\r\n companyid = 'c' + generate_random_str(24)\r\n user_query = User.query.filter_by(userid=userid).first()\r\n user_query.role = '0'\r\n user_mobile = user_query.mobile\r\n db.session.commit()\r\n\r\n insert_company = Company(companyid=companyid, companyname=companyname, companyrole='1',companyemail=email)\r\n insert_opuser = Opuser(opusername=username, opuserid=userid,\r\n opmobile=user_mobile,opcompanyid=companyid,\r\n default='true', oprole='4'\r\n )\r\n db.session.add(insert_company)\r\n db.session.add(insert_opuser)\r\n db.session.commit()\r\n chatbotinfo = insert_chatbot(companyid)\r\n\r\n #创建公司的时候顺便创建一台试用的zabbix服务器\r\n\r\n zabbixserverid = 'z' + generate_random_str()\r\n insert_zabbixserver = Zabbix(companyid=companyid, zabbixid=zabbixserverid,\r\n zabbixserver=\"http://testdemod.cdwintech.com\", zabbixuser=\"Admin\",\r\n zabbixpassword=\"zabbix\")\r\n db.session.add(insert_zabbixserver)\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '公司创建成功','chatbotinfo':chatbotinfo,\r\n 'companyid':companyid,'mobile':user_mobile,\r\n 'companyexpiredate':None,\r\n 'email': email, 'username': username,\r\n 'companyname': companyname,'companyrole':'1',\r\n 'oprole': '4','role': '0'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': '数据库连接似乎出了问题'}\r\n\r\n\r\n\r\ndef join_company(userid, companyid, username , token):\r\n try:\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token 不可用'}\r\n request_userid = userid\r\n join_company = User.query.filter_by(userid=request_userid).first()\r\n mobile = join_company.mobile\r\n join_exsitcheck = Topic.query.filter_by(request_userid=request_userid,companyid=companyid,request_username=username).first()\r\n\r\n if join_exsitcheck:\r\n join_exsitcheck_admin_action = join_exsitcheck.admin_action\r\n if join_exsitcheck_admin_action == '2' or join_exsitcheck_admin_action == '0':\r\n db.session.close()\r\n return {'status': '0', 'msg': '不能重复申请'}\r\n\r\n if join_exsitcheck_admin_action == '1' or join_exsitcheck_admin_action == '3':\r\n join_exsitcheck.admin_action = '2'\r\n check_user_role_query = User.query.filter_by(userid=userid).first()\r\n if check_user_role_query.role == '1' or check_user_role_query.role == '4':\r\n check_user_role_query.role = '2'\r\n\r\n admin_userid_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\r\n topic_admin_userid = admin_userid_query.opuserid\r\n\r\n msg = \"%s申请加入公司\" % username\r\n result1 = push_msg_to_android(topic_admin_userid, token, 'com.domain.operationrobot', '消息通知', msg, 0, 'payload')\r\n print(result1)\r\n result2 = push_msg_to_ios(topic_admin_userid, token, 'com.domain.operationrobot', '消息通知', msg, 'body')\r\n print(result2)\r\n insert_opuserinfo = Opuser(opusername=username, opcompanyid=companyid,\r\n opmobile=mobile, opuserid=request_userid,\r\n oprole='2')\r\n db.session.add(insert_opuserinfo)\r\n db.session.commit()\r\n db.session.close()\r\n return {'status':'0', 'msg': '已经再次发出请求'}\r\n\r\n check_opusername_list = []\r\n check_opusername_querys = Opuser.query.filter_by(opcompanyid=companyid).all()\r\n for check_opusername_query in check_opusername_querys:\r\n check_opusername = check_opusername_query.opusername\r\n check_opusername_list.append(check_opusername)\r\n\r\n init_username = username\r\n for i in range(1, 100):\r\n print(i)\r\n if username in check_opusername_list:\r\n username = init_username\r\n username = username + str(i)\r\n print('hehehe', username)\r\n else:\r\n break\r\n\r\n print(username)\r\n\r\n\r\n\r\n user_join_company = Opuser.query.filter_by(opuserid=request_userid, opcompanyid=companyid).first()\r\n if user_join_company:\r\n db.session.close()\r\n return {'status': '2', 'msg': '用户已存在'}\r\n else:\r\n if join_company.role == '1' or join_company.role == '4':\r\n join_company.role = '2'\r\n else:\r\n pass\r\n\r\n user_mobile_join_company = Opuser.query.filter_by(opmobile=mobile, opcompanyid=companyid).first()\r\n if user_mobile_join_company:\r\n user_mobile_join_company.opuserid = userid\r\n db.session.commit()\r\n else:\r\n insert_companyinfo = Opuser(opusername=username, opcompanyid=companyid,\r\n opmobile=mobile, opuserid=request_userid,\r\n oprole='2')\r\n db.session.add(insert_companyinfo)\r\n db.session.commit()\r\n \r\n admin_userid_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\r\n topic_admin_userid = admin_userid_query.opuserid\r\n\r\n msg = \"%s申请加入公司\" % username\r\n result1 = push_msg_to_android(topic_admin_userid, token, 'com.domain.operationrobot', '消息通知', msg, 0, 'payload')\r\n print(result1)\r\n result2 = push_msg_to_ios(topic_admin_userid, token, 'com.domain.operationrobot', '消息通知', msg, 'body')\r\n print(result2)\r\n admin_userid_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\r\n topic_admin_userid = admin_userid_query.opuserid\r\n insert_topic = Topic(admin_userid=topic_admin_userid, request_username=username,\r\n request_mobile=mobile,request_userid=request_userid,\r\n admin_action='2', companyid=companyid)\r\n db.session.add(insert_topic)\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': '0', 'msg': '申请成功', 'role': '2','oprole':'2'}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\n\r\n\"\"\"\r\n# 获取公司状态\r\ndef getCompanyStatus(companyid):\r\n \r\n if companyid:\r\n try:\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query:\r\n company_status = company_query.disable\r\n \r\n a = {'status': 0, 'msg': '获取状态成功', 'company_status':'1111'}\r\n return a\r\n else:\r\n a = {'status': 1, 'msg': '公司信息不存在'}\r\n return a\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status': 3, 'Oooops': '数据库连接出现错误'}\r\n else:\r\n return {'status': 1, 'msg': 'companyid 不能为空'}\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\ndef getCompanyStatus(companyid):\r\n \r\n if companyid:\r\n try:\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query:\r\n return {'status': '0', 'msg': '获取公司信息成功', 'company_status': company_query.disable}\r\n else:\r\n return {'status': '1', 'msg': '公司信息不存在'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status': '3', 'msg': '数据库连接出现错误'}\r\n else:\r\n return {'status': '1', 'msg': 'companyid不能为空'}\r\n\"\"\"\r\n\r\n\r\n# 获取用户公司状态\r\ndef getUserCompanyStatus(userid, companyid):\r\n if companyid:\r\n try:\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n # 公司信息存在\r\n if company_query:\r\n \r\n # 公司被禁用\r\n if company_query.disable == 1:\r\n return {'status': '0', 'msg': '获取信息成功', 'company_status': '1'}\r\n # 公司有效 查询公司中是否存在这个用户\r\n else:\r\n company_user_query = Opuser.query.filter_by(opcompanyid = companyid,\r\n opuserid = userid).first()\r\n \r\n # 在公司中查询到了这个用户\r\n if company_user_query :\r\n return {'status': '0', 'msg': '获取信息成功', 'company_status': '3'}\r\n # 公司中不存在这个用户\r\n else:\r\n return {'status': '0', 'msg': '获取信息成功', 'company_status': '2'}\r\n # 公司信息不存在\r\n else:\r\n return {'status': '1', 'msg': '公司信息不存在', 'company_status': '4'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status': '3', 'msg': '数据库连接出现错误'}\r\n else:\r\n user_query = User.query.filter_by(userid=userid).first()\r\n if user_query:\r\n if user_query.mark == \"userdisabled\":\r\n return {'status': '0', 'msg': '获取信息成功', 'company_status': '5'}\r\n else:\r\n return {'status': '0', 'msg': '获取信息成功', 'company_status': '6'}\r\n return {'status': '1', 'msg': 'companyid不能为空'}\r\n\r\n\r\ndef leave_company(usertoken, userid, companyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token 不可用'}\r\n leave_company_query = Opuser.query.filter_by(opuserid=userid, opcompanyid=companyid).first()\r\n leave_topic_query = Topic.query.filter_by(request_userid=userid, companyid=companyid).first()\r\n if leave_company_query:\r\n if leave_company_query.oprole != '4':\r\n leave_company_query.query.filter_by(opuserid=userid, opcompanyid=companyid).delete()\r\n if leave_topic_query:\r\n leave_topic_query.query.filter_by(request_userid=userid, companyid=companyid).delete()\r\n leave_company_query2 = Opuser.query.filter_by(opuserid=userid).first()\r\n if leave_company_query2 is None:\r\n leave_user_query2 = User.query.filter_by(userid=userid).first()\r\n leave_user_query2.role = 1\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '您已退出该公司'}\r\n else:\r\n db.session.close()\r\n return {'status': 2, 'msg': '管理员无法退出公司'}\r\n else:\r\n db.session.close()\r\n return {'status': 3, 'msg': '无法找到相关用户'}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\ndef join_info(userid, token, companyid):\r\n try:\r\n\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token 不可用'}\r\n join_info = Opuser.query.filter_by(opuserid=userid, opcompanyid=companyid).first()\r\n if join_info.oprole != '4':\r\n db.session.close()\r\n return {'status': 2, 'msg': '没有权限查看此页面'}\r\n else:\r\n admin_user_query = Topic.query.filter_by(admin_userid=userid, companyid=companyid).all()\r\n\r\n if admin_user_query:\r\n admin_user_list = []\r\n for admin_user in admin_user_query:\r\n admin_user_dict = {}\r\n print(admin_user.request_userid, userid)\r\n request_create_time = admin_user.createtime\r\n request_create_time_chuo = time.mktime(request_create_time.timetuple())\r\n admin_user_dict['request_username'] = admin_user.request_username\r\n admin_user_dict['request_mobile'] = admin_user.request_mobile\r\n admin_user_dict['request_id'] = admin_user.id\r\n admin_user_dict['request_userid'] = admin_user.request_userid\r\n admin_user_dict['request_companyid'] = admin_user.companyid\r\n request_user_request_img_query = User.query.filter_by(userid=admin_user.request_userid).first()\r\n if request_user_request_img_query:\r\n #print(request_user_request_img_query.mobile)\r\n request_user_request_imgurl = request_user_request_img_query.profile\r\n admin_user_dict['request_createtime'] = int(request_create_time_chuo)\r\n admin_user_dict['admin_action'] = admin_user.admin_action\r\n admin_user_dict['request_img'] = request_user_request_imgurl\r\n admin_user_list.append(admin_user_dict)\r\n\r\n admin_user_list1=sorted(admin_user_list,key=lambda keys:keys[\"request_createtime\"])\r\n print(admin_user_list1)\r\n daoxu_admin_user_list = admin_user_list1[::-1]\r\n db.session.close()\r\n return {'status': 0, 'msg': 'success', 'info': daoxu_admin_user_list}\r\n else:\r\n return {'status': 3, 'msg': '暂无申请记录。'}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\ndef sidebar_get(userid, token):\r\n try:\r\n\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token 不可用'}\r\n displaystatus = 1\r\n #用户为游客返回的数据\r\n sidebar_get = User.query.filter_by(userid=userid).first()\r\n user_mark = sidebar_get.mark\r\n if user_mark == \"userdisabled\":\r\n return {'status': 10, 'msg': '用户已被禁用'}\r\n query_role = sidebar_get.role\r\n query_mobile = sidebar_get.mobile\r\n query_username = sidebar_get.username\r\n #当期时间\r\n currenttime = datetime(datetime.today().year, datetime.today().month, datetime.today().day,\r\n datetime.today().hour, datetime.today().minute, datetime.today().second)\r\n #后台设置提醒时间的天数\r\n backstage_info = Backstage.query.first()\r\n date_inter0 = backstage_info.companyexpire\r\n date_inter = float(date_inter0)*3600*24\r\n if query_role == '1':\r\n check_action_role_query = Topic.query.filter_by(request_userid=userid, admin_action='1').first()\r\n if check_action_role_query:\r\n rolers = {'status': 0, 'msg': '查询成功', 'username': query_username,\r\n 'companyname': None, 'companyid': None,\r\n 'companyrole': None, 'mobile': query_mobile, 'role': '3','displaystatus':1}\r\n else:\r\n rolers = {'status': 0, 'msg': '查询成功','username': query_username,\r\n 'companyname':None,'companyid':None,\r\n 'companyrole': None,'mobile':query_mobile,'role':query_role,'displaystatus':1}\r\n db.session.close()\r\n return rolers\r\n #用户已申请公司返回的数据\r\n if query_role == '2':\r\n# check_action_allrole_list_query = Topic.query.filter_by(request_userid=userid).all()\r\n# for check_action_allrole_query in check_action_allrole_list_query:\r\n# if check_action_allrole_query.admin_action != '1':\r\n# print(check_action_allrole_query.companyid)\r\n# print(check_action_allrole_query.request_userid)\r\n# check_action_status = 'haveother'\r\n# check_action_status_companyid = check_action_allrole_query.companyid\r\n# break\r\n# else:\r\n# check_action_status = 'havenoone'\r\n\r\n# if check_action_status == 'haveother':\r\n# opusercompanyid = check_action_status_companyid\r\n# action_role = query_role\r\n# else:\r\n opuserinfo_list_query = Opuser.query.filter_by(opuserid=userid, oprole='2').first()\r\n if opuserinfo_list_query:\r\n opusercompanyid = opuserinfo_list_query.opcompanyid\r\n #check_action_allrole_list_query = Topic.query.filter_by(request_userid=userid, companyid=opusercompanyid).first()\r\n action_role = '2'\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opusercompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname \r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n query_oprole_query = Opuser.query.filter_by(opuserid=userid).first()\r\n query_oprole = query_oprole_query.oprole\r\n check_action_role_query = Topic.query.filter_by(companyid=opusercompanyid, request_userid=userid).first()\r\n #check_action_role = check_action_role_query.admin_action\r\n rs = {'status': 0, 'msg': '查询成功','username': query_username,\r\n 'companyname':opcompanyname,'companyid':opusercompanyid,\r\n 'companyrole': opcompanyrole,'mobile':query_mobile,\r\n 'oprole':query_oprole,'role':action_role,'displaystatus':1}\r\n else:\r\n rs = {'status': 0, 'msg': '查询成功', 'username': query_username,\r\n 'companyname': None, 'companyid': None,\r\n 'companyrole': None, 'mobile': query_mobile, 'role': '3','displaystatus':1}\r\n\r\n db.session.close()\r\n return rs\r\n \r\n if query_role == '4':\r\n return {'status': 0, 'msg': '查询成功', 'username': query_username,\r\n 'companyname': None, 'companyid': None,\r\n 'companyrole': None, 'mobile': query_mobile, 'role': query_role,'displaystatus':1}\r\n\r\n query_oprole_query = Opuser.query.filter_by(opuserid=userid, default='true').first()\r\n if query_oprole_query:\r\n query_oprole = query_oprole_query.oprole\r\n else:\r\n return {'status': 2, 'msg': '用户不存在默认公司,请先选择默认公司'}\r\n #用户是普通运维用户返回的数据\r\n if query_role == '0' and query_oprole == '3':\r\n opuserinfo_query = Opuser.query.filter_by(opuserid=userid, oprole='3', default='true').first()\r\n if opuserinfo_query:\r\n opusercompanyid = opuserinfo_query.opcompanyid\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opusercompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opusername = opuserinfo_query.opusername\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n opcompanyexpiredate = opcompanyinfo_query.companyexpiredate\r\n if opcompanyexpiredate:\r\n minus = (opcompanyexpiredate - currenttime).total_seconds()\r\n if minus > 0 and minus > date_inter:\r\n displaystatus = 0\r\n elif minus > 0 and minus < date_inter:\r\n displaystatus = 1\r\n elif minus < 0:\r\n pass\r\n db.session.commit()\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n if opcompanyrole:\r\n if minus < 0:\r\n opcompanyinfo_query.companyrole = '1'\r\n else:\r\n opcompanyinfo_query.companyrole = '2'\r\n db.session.commit()\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n if opcompanyexpiredate:\r\n request_create_time_chuo = int(time.mktime(opcompanyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n db.session.close()\r\n return {'status': 0, 'msg': '查询成功', 'username': query_username,\r\n 'companyname': opcompanyname, 'companyid': opusercompanyid,\r\n 'companyrole': opcompanyrole, 'mobile': query_mobile,'displaystatus':displaystatus,\r\n 'oprole':query_oprole,'role': query_role,'companyexpiredate':request_create_time_chuo}\r\n\r\n #用户是审核员返回的数据\r\n if query_role == '0' and query_oprole == '6':\r\n opuserinfo_query = Opuser.query.filter_by(opuserid=userid, oprole='6', default='true').first()\r\n if opuserinfo_query:\r\n opusercompanyid = opuserinfo_query.opcompanyid\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opusercompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opusername = opuserinfo_query.opusername\r\n opcompanyexpiredate = opcompanyinfo_query.companyexpiredate\r\n if opcompanyexpiredate:\r\n minus = (opcompanyexpiredate - currenttime).total_seconds()\r\n if minus > 0 and minus > date_inter:\r\n displaystatus = 0\r\n elif minus > 0 and minus < date_inter:\r\n displaystatus = 1\r\n elif minus < 0:\r\n pass\r\n db.session.commit()\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n if opcompanyrole:\r\n if minus < 0:\r\n opcompanyinfo_query.companyrole = '1'\r\n else:\r\n opcompanyinfo_query.companyrole = '2'\r\n db.session.commit()\r\n\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n if opcompanyexpiredate:\r\n request_create_time_chuo = int(time.mktime(opcompanyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n db.session.close()\r\n return {'status': 0, 'msg': '查询成功', 'username': query_username,\r\n 'companyname': opcompanyname, 'companyid': opusercompanyid,\r\n 'companyrole': opcompanyrole, 'mobile': query_mobile,'displaystatus':displaystatus,\r\n 'oprole':query_oprole,'role': query_role, 'companyexpiredate':request_create_time_chuo}\r\n else:\r\n db.session.close()\r\n return {'status': 2, 'msg': '用户不存在默认公司,请先选择默认公司'}\r\n\r\n\r\n #用户为管理员返回的数据\r\n if query_role == '0' and query_oprole == '4':\r\n opuserinfo_query = Opuser.query.filter_by(opuserid=userid, oprole='4', default='true').first()\r\n if opuserinfo_query:\r\n opusercompanyid = opuserinfo_query.opcompanyid\r\n opcompanyinfo_query = Company.query.filter_by(companyid=opusercompanyid).first()\r\n opcompanyname = opcompanyinfo_query.companyname\r\n opusername = opuserinfo_query.opusername\r\n opcompanyexpiredate = opcompanyinfo_query.companyexpiredate\r\n if opcompanyexpiredate:\r\n minus = (opcompanyexpiredate - currenttime).total_seconds()\r\n if minus > 0 and minus > date_inter:\r\n displaystatus = 0\r\n elif minus > 0 and minus < date_inter:\r\n displaystatus = 1\r\n elif minus < 0:\r\n pass\r\n db.session.commit()\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n if opcompanyrole:\r\n if minus < 0:\r\n opcompanyinfo_query.companyrole = '1'\r\n else:\r\n opcompanyinfo_query.companyrole = '2'\r\n db.session.commit()\r\n\r\n opcompanyrole = opcompanyinfo_query.companyrole\r\n if opcompanyexpiredate:\r\n request_create_time_chuo = int(time.mktime(opcompanyexpiredate.timetuple()))\r\n else:\r\n request_create_time_chuo = None\r\n admin_user_query = Topic.query.filter_by(admin_userid=userid).all()\r\n admin_user_list = []\r\n for admin_user in admin_user_query:\r\n if admin_user.admin_action == '2':\r\n admin_user_list.append(admin_user)\r\n admin_user_listlen = len(admin_user_list)\r\n companymember_query = Opuser.query.filter_by(opcompanyid=opusercompanyid).all()\r\n\r\n companymember_list = []\r\n for companymember in companymember_query:\r\n if companymember.oprole !='2' and companymember.oprole !='5':\r\n companymember_list.append(companymember)\r\n\r\n print(companymember_list)\r\n db.session.close()\r\n return {'status': 0, 'msg': 'success', 'username':query_username,\r\n 'companyname':opcompanyname,'companyid':opusercompanyid,'displaystatus':displaystatus,\r\n 'companyrole': opcompanyrole,'mobile':query_mobile,'role':query_role,\r\n 'oprole':query_oprole,'companyexpiredate':request_create_time_chuo,\r\n 'joinlist': admin_user_listlen, 'memberlist': len(companymember_list)}\r\n else:\r\n db.session.close()\r\n return {'status': 2, 'msg': '用户不存在默认公司,请先选择默认公司'}\r\n\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\ndef join_update(request_id,userid, token, request_userid, admin_action, request_companyid):\r\n try:\r\n\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'token 不可用'}\r\n opjoin_info = Opuser.query.filter_by(opuserid=userid,opcompanyid=request_companyid).first()\r\n\r\n if opjoin_info.oprole != '4':\r\n db.session.close()\r\n return {'status': 2, 'msg': '没有权限查看此页面'}\r\n\r\n join_info_query = Topic.query.filter_by(id=request_id).first()\r\n if admin_action == '1':\r\n join_info_query.admin_action = '1'\r\n check_user_role_query = User.query.filter_by(userid=request_userid).first()\r\n\r\n delete_reject_opuser_query = Opuser.query.filter_by(opuserid=request_userid, opcompanyid=request_companyid).first()\r\n if delete_reject_opuser_query:\r\n delete_reject_opuser_query.query.filter_by(opuserid=request_userid, opcompanyid=request_companyid).delete()\r\n\r\n check_opuser_role_query = Opuser.query.filter_by(opuserid=request_userid).first()\r\n if check_user_role_query.role == '2' and check_opuser_role_query is None:\r\n check_user_role_query.role = '1'\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '已经拒绝'}\r\n if admin_action == '0':\r\n join_info_query.admin_action = '0'\r\n request_userinfo = User.query.filter_by(userid=request_userid).first()\r\n if request_userinfo.role != '0':\r\n request_userinfo.role = '0'\r\n request_username = request_userinfo.username\r\n request_mobile = request_userinfo.mobile\r\n request_join_info = Opuser.query.filter_by(opuserid=request_userid, opcompanyid=request_companyid).first()\r\n if request_join_info:\r\n request_join_info.oprole = '3'\r\n request_join_info.default = 'true'\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '已经同意', 'request_username': request_username,\r\n 'request_mobile':request_mobile, 'admin_action':admin_action}\r\n else:\r\n return {'status': 4, 'msg': 'Ooooops , 无法识别状态码'}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\n\r\ndef commandstatus(userid, token, companyid):\r\n try:\r\n print(userid,companyid)\r\n if token != '11111':\r\n return {'status':1,'msg':'token不可用'}\r\n commands = CompanyCommandStatus.query.filter_by(companyid=companyid).all()\r\n commandstatus_list = []\r\n for command in commands:\r\n operacommand_dict = {}\r\n operacommand = OperaCommand.query.filter_by(command_id=command.command_id).first()\r\n operacommand_dict[\"command_displayname\"] = operacommand.command_displayname\r\n operacommand_dict['commandtype'] = operacommand.commandtype\r\n operacommand_dict[\"commandstatus\"] = command.commandstatus\r\n operacommand_dict['command_id'] = command.command_id\r\n commandstatus_list.append(operacommand_dict)\r\n\r\n db.session.close()\r\n return {'status': 0, 'msg': '查询成功', 'info': commandstatus_list}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n db.session.close()\r\n return {'status': 2, 'Oooops': 'There is a problem with the database'}\r\n\r\n\r\ndef updatecommandstatus(adminuserid, usertoken, companyid,commandstatus_list):\r\n\r\n try:\r\n if usertoken != '11111':\r\n return {'status':1,'msg':'Token无效'}\r\n admin_opuser_query = Opuser.query.filter_by(opuserid=adminuserid,opcompanyid=companyid,oprole='4').first()\r\n\r\n if admin_opuser_query is None:\r\n db.session.close()\r\n return {'status':2,'msg':'没有权限'}\r\n\r\n for status in commandstatus_list:\r\n commands = CompanyCommandStatus.query.filter_by(companyid=companyid).all()\r\n for command in commands:\r\n if command.command_id == status['command_id']:\r\n command.commandstatus = status['commandstatus']\r\n db.session.commit()\r\n db.session.close()\r\n\r\n return {'status':0,'msg':'修改成功'}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops':'There is a problem with the database'}\r\n\r\ndef opusers(userid, token, companyid):\r\n try:\r\n print(userid, companyid)\r\n if token != '11111':\r\n return {'status': 1, 'mgs': 'token不可用'}\r\n user_query = User.query.filter_by(userid=userid).first()\r\n\r\n user_role = user_query.role\r\n if user_role == '1' or user_role == '2':\r\n db.session.close()\r\n return {'status': 3, 'msg': \"\"}\r\n user_check_query = Opuser.query.filter_by(opuserid=userid, opcompanyid=companyid).first()\r\n if user_check_query is None:\r\n db.session.close()\r\n return {'status': 4, 'msg':\"用户id不能匹配用户公司id\"}\r\n if user_check_query.oprole == '2':\r\n db.session.close()\r\n return {'status': 3, 'msg': \"没有权限查看此页面\"}\r\n\r\n users_query = Opuser.query.filter_by(opcompanyid=companyid).all()\r\n opuser_list = []\r\n for user_query in users_query:\r\n opuser_dict = {}\r\n if user_query.oprole != '5' and user_query.oprole != '2':\r\n opuser_dict['oprole'] = user_query.oprole\r\n opusermobile = user_query.opmobile\r\n opuserinfo_query = User.query.filter_by(mobile=opusermobile).first()\r\n print('hahahahahahahahahahah')\r\n if opuserinfo_query:\r\n print(opuserinfo_query)\r\n opuserid = opuserinfo_query.userid\r\n opuser_dict['imageUrl'] = opuserinfo_query.profile\r\n opuser_dict['role'] = opuserinfo_query.role\r\n opuser_dict['opmobile'] = user_query.opmobile\r\n opuser_dict['opusername'] = user_query.opusername\r\n opuser_dict['userid'] = opuserid\r\n opuser_dict['opcompanyid'] = companyid\r\n opuser_dict['userstatus'] = user_query.userstatus\r\n opuser_list.append(opuser_dict)\r\n else:\r\n opuser_dict['imageUrl'] = 'http://139.196.107.14:6001/upload/2018-11-12/[email protected]'\r\n opuser_dict['role'] = '0'\r\n opuser_dict['opmobile'] = user_query.opmobile\r\n opuser_dict['opusername'] = user_query.opusername\r\n opuser_dict['userid'] = None\r\n opuser_dict['opcompanyid'] = companyid\r\n opuser_dict['userstatus'] = user_query.userstatus\r\n opuser_list.append(opuser_dict)\r\n\r\n db.session.close()\r\n return {'status': 0, 'msg': '查询成功', 'info': opuser_list}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n db.session.close()\r\n return {'status':5, 'Oooops': 'There is a problem with the database'}\r\n\r\ndef opuser(userid, token, username, companyid):\r\n try:\r\n if token != '11111':\r\n return {'status': 1, 'msg': 'Token无效'}\r\n user_query = User.query.filter_by(userid=userid).first()\r\n\r\n user_role = user_query.role\r\n if user_role == '1' or user_role == '2':\r\n db.session.close()\r\n return {'status': 3, 'msg': \"没有权限查看此页面\"}\r\n user_check_query = Opuser.query.filter_by(opuserid=userid, opcompanyid=companyid).first()\r\n if user_check_query is None:\r\n db.session.close()\r\n return {'status': 4, 'msg':\"用户id不能匹配用户公司id\"}\r\n if user_check_query.oprole == '2':\r\n db.session.close()\r\n return {'status': 3, 'msg': \"没有权限查看此页面\"}\r\n opusers_query = Opuser.query.filter_by(opcompanyid=companyid).all()\r\n opuser_list = []\r\n for opuser_query in opusers_query:\r\n opuser_dict = {}\r\n if opuser_query.oprole != '5' and opuser_query.oprole != '2':\r\n opuserrole = opuser_query.oprole\r\n opusername = opuser_query.opusername\r\n opuserid = opuser_query.opuserid\r\n opusercompanyid = opuser_query.opcompanyid\r\n user_query = User.query.filter_by(userid=opuserid).first()\r\n if opusername.find(username) != -1 and user_query:\r\n opuser_dict['opusername'] = opusername\r\n opuser_dict['imageUrl'] = user_query.profile\r\n opuser_dict['oprole'] = opuserrole\r\n opuser_dict['role'] = user_query.role\r\n opuser_dict['opmobile'] = opuser_query.opmobile\r\n opuser_dict['userid'] = opuserid\r\n opuser_dict['opcompanyid'] = companyid\r\n opuser_dict['userstatus'] = opuser_query.userstatus\r\n opuser_list.append(opuser_dict)\r\n if opusername.find(username) != -1 and user_query is None:\r\n opuser_dict['opusername'] = opusername\r\n opuser_dict['imageUrl'] = 'http://139.196.107.14:6001/upload/2018-11-12/[email protected]'\r\n opuser_dict['oprole'] = opuserrole\r\n opuser_dict['role'] = '1'\r\n opuser_dict['opmobile'] = opuser_query.opmobile\r\n opuser_dict['userid'] = None\r\n opuser_dict['opcompanyid'] = companyid\r\n opuser_dict['userstatus'] = opuser_query.userstatus\r\n opuser_list.append(opuser_dict)\r\n db.session.close()\r\n return {'status': 0, 'msg': '查询成功', 'info': opuser_list}\r\n\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n db.session.close()\r\n return {'status':3, 'Oooops': 'There is a problem with the database'}\r\n\r\n\r\ndef addopuser(adminuserid, usertoken, opusername, opmobile, admincompanyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'Token无效'}\r\n opuser_check_mobile = Opuser.query.filter_by(opmobile=opmobile,opcompanyid=admincompanyid).first()\r\n\r\n if opuser_check_mobile:\r\n db.session.close()\r\n return {'status': 6, 'msg': '手机号码已存在'}\r\n\r\n adminopuserquery = Opuser.query.filter_by(opuserid=adminuserid,opcompanyid=admincompanyid,oprole='4').first()\r\n\r\n if adminopuserquery is None:\r\n db.session.close()\r\n return {'status': 5, 'msg': '用户无权限'}\r\n\r\n if len(opusername) > 12:\r\n db.session.close()\r\n return {'status':4, 'msg':'用户名长度不符合要求,用户名应在12字以内'}\r\n elif opmobile == 'null':\r\n db.session.close()\r\n return {'status': 2, 'msg': '手机号码不能为空'}\r\n elif phonecheck(opmobile) == 'failure':\r\n db.session.close()\r\n return {'status': 3, 'msg': '请输入正确的手机号码'}\r\n\r\n addopusermobile_check = User.query.filter_by(mobile=opmobile).first()\r\n if addopusermobile_check:\r\n addopusermobile_check_userid = addopusermobile_check.userid\r\n insert_opuser = Opuser(opmobile=opmobile, oprole='3',opuserid=addopusermobile_check_userid,\r\n opusername=opusername, opcompanyid=admincompanyid,\r\n userstatus='register')\r\n addopusermobile_check.role = '0' \r\n else:\r\n insert_opuser = Opuser(opmobile=opmobile, oprole='3',\r\n opusername=opusername, opcompanyid=admincompanyid,\r\n userstatus='manual')\r\n\r\n db.session.add(insert_opuser)\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '添加成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n db.session.close()\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\n\r\ndef deleteopuser(adminuserid, usertoken, opmobile, admincompanyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'Token无效'}\r\n adminopuserquery = Opuser.query.filter_by(opuserid=adminuserid,opcompanyid=admincompanyid,oprole='4').first()\r\n\r\n if adminopuserquery is None:\r\n db.session.close()\r\n return {'status': 5, 'msg': '用户无权限'}\r\n else:\r\n adminmobile = adminopuserquery.opmobile\r\n if adminmobile == opmobile:\r\n db.session.close()\r\n return {'status': 3, 'msg': '无法删除管理员'}\r\n\r\n opuserinfo_query = Opuser.query.filter_by(opmobile=opmobile,opcompanyid=admincompanyid).first()\r\n if opuserinfo_query:\r\n opuserinfo_query.query.filter_by(opmobile=opmobile,opcompanyid=admincompanyid).delete()\r\n db.session.commit()\r\n db.session.close()\r\n else:\r\n db.session.close()\r\n return {'status': 2, 'msg': '找不到匹配用户'}\r\n\r\n opusercheck_query = Opuser.query.filter_by(opmobile=opmobile).first()\r\n if opusercheck_query:\r\n pass\r\n else:\r\n change_userrole = User.query.filter_by(mobile=opmobile).first()\r\n if change_userrole:\r\n change_userrole.role = '1'\r\n db.session.commit()\r\n join_exsitcheck = Topic.query.filter_by(admin_userid=adminuserid, request_mobile=opmobile,companyid=admincompanyid).delete()\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '删除成功'}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n db.session.close()\r\n return {'Oooops': 'There is a problem with the database'}\r\n# except:\r\n# db.session.rollback()\r\n# return {'status': 4, 'msg': 'something warong'}\r\n\r\n\r\n\"\"\"\r\ndef updateopuser(adminuserid, usertoken, opusername, opmobile, opuserid, opcompanyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'Token无效'}\r\n\r\n if len(opusername) > 12:\r\n return {'status': 5, 'msg':'用户名长度不符合要求,用户名应在12字以内'}\r\n\r\n\r\n if opmobile == 'null':\r\n return {'status': 2, 'msg': '手机号码不能为空'}\r\n elif phonecheck(opmobile) == 'failure':\r\n return {'status': 3, 'msg': '请输入正确的手机号码'}\r\n admin_opuser_query = Opuser.query.filter_by(opuserid=adminuserid, opcompanyid=opcompanyid, oprole='4').first()\r\n if admin_opuser_query is None:\r\n db.session.close()\r\n return {'status': 4, 'msg': '没有权限'}\r\n else:\r\n opuser_query = Opuser.query.filter_by(opmobile=opmobile, opcompanyid=opcompanyid).first()\r\n if opuser_query:\r\n opuser_query.opusername = opusername\r\n opuser_query.opmobile = opmobile\r\n else:\r\n opuser_query = Opuser.query.filter_by(opusername=opusername, opcompanyid=opcompanyid).first()\r\n opuser_query.opusername = opusername\r\n opuser_query.opmobile = opmobile\r\n\r\n opusercheck_query = Opuser.query.filter_by(opmobile=opmobile).first()\r\n if opusercheck_query:\r\n pass\r\n else:\r\n change_userrole = User.query.filter_by(mobile=opmobile).first()\r\n if change_userrole:\r\n change_userrole.role = '1'\r\n db.session.commit()\r\n\r\n\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '修改成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n db.session.close()\r\n return {'Oooops': 'There is a problem with the database'}\r\n\"\"\"\r\n\r\n\r\ndef updateopuser(adminuserid, usertoken, opusername, opmobile, opuserid, opcompanyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'Token无效'}\r\n\r\n if len(opusername) > 12:\r\n return {'status': 5, 'msg':'用户名长度不符合要求,用户名应在12字以内'}\r\n\r\n\r\n if opmobile == 'null':\r\n return {'status': 2, 'msg': '手机号码不能为空'}\r\n elif phonecheck(opmobile) == 'failure':\r\n return {'status': 3, 'msg': '请输入正确的手机号码'}\r\n admin_opuser_query = Opuser.query.filter_by(opuserid=adminuserid, opcompanyid=opcompanyid, oprole='4').first()\r\n if admin_opuser_query is None:\r\n db.session.close()\r\n return {'status': 4, 'msg': '没有权限'}\r\n else:\r\n opusers_query = Opuser.query.filter_by(opcompanyid=opcompanyid).all()\r\n opuserself = Opuser.query.filter_by(opcompanyid=opcompanyid,opuserid=opuserid).first()\r\n if opusers_query:\r\n for tempopuser in opusers_query:\r\n if tempopuser.opmobile == opmobile and tempopuser.opuserid != opuserself.opuserid:\r\n return {'status':'6','msg':'手机号码不能与其他用户重复'}\r\n opuser_query = Opuser.query.filter_by(opcompanyid=opcompanyid,opmobile=opmobile).first()\r\n if opuser_query:\r\n opuser_query.opusername = opusername\r\n opuser_query.opmobile = opmobile\r\n else:\r\n opuser_query = Opuser.query.filter_by(opusername=opusername, opcompanyid=opcompanyid).first()\r\n opuser_query.opusername = opusername\r\n opuser_query.opmobile = opmobile\r\n\r\n opusercheck_query = Opuser.query.filter_by(opmobile=opmobile).first()\r\n if opusercheck_query:\r\n pass\r\n else:\r\n change_userrole = User.query.filter_by(mobile=opmobile).first()\r\n if change_userrole:\r\n change_userrole.role = '1'\r\n db.session.commit()\r\n\r\n\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '修改成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n db.session.close()\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\ndef updateopuserrole(usertoken, adminuserid, opuserid, oprole, opcompanyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'Token无效'}\r\n admin_opuser_query = Opuser.query.filter_by(opuserid=adminuserid,opcompanyid=opcompanyid,oprole='4').first()\r\n\r\n if admin_opuser_query is None:\r\n db.session.close()\r\n return {'status': 3, 'msg': '没有权限'}\r\n\r\n if adminuserid == opuserid:\r\n db.session.close()\r\n return {'status': 4, 'msg': '无法更改管理员自身权限'}\r\n if opuserid is None:\r\n db.session.close()\r\n return {'status': 5, 'msg': '用户尚未关联公司,无法设置管理员或审核员权限'}\r\n\r\n if oprole == '6':\r\n companyusersrole6_query = Opuser.query.filter_by(opcompanyid=opcompanyid, oprole='6').all()\r\n\r\n companyusersrole6s = len(companyusersrole6_query)\r\n if companyusersrole6s >= 3:\r\n db.session.close()\r\n return {'status': 6, 'msg': '一个公司最多只能设置3个审核员'}\r\n else:\r\n opuserrole_change_query = Opuser.query.filter_by(opuserid=opuserid, opcompanyid=opcompanyid).first()\r\n if opuserrole_change_query:\r\n opuserrole_change_query.oprole = '6'\r\n db.session.commit()\r\n if oprole == '4':\r\n opuser_query = Opuser.query.filter_by(opuserid=opuserid, opcompanyid=opcompanyid).first()\r\n if opuser_query:\r\n opuser_query.oprole = '4'\r\n admin_opuser_query.oprole = '3'\r\n db.session.commit()\r\n if oprole == '3':\r\n opuser_query = Opuser.query.filter_by(opuserid=opuserid, opcompanyid=opcompanyid).first()\r\n if opuser_query:\r\n opuser_query.oprole = '3'\r\n db.session.commit()\r\n db.session.close()\r\n return {'status': 0, 'msg': '修改成功'}\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\ndef updateopuserdefaultcompany(usertoken, opuserid, opcompanyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'Token无效'}\r\n admin_opuser_query = Opuser.query.filter_by(opuserid=opuserid,opcompanyid=opcompanyid).first()\r\n if admin_opuser_query:\r\n admin_opuser_query.default = 'true'\r\n opuser_querys = Opuser.query.filter_by(opuserid=opuserid).all()\r\n if opuser_querys:\r\n for opuser in opuser_querys:\r\n if opuser.opcompanyid != opcompanyid:\r\n opuser.default = \"false\"\r\n opuser_company_default_querys = Opuser.query.filter_by(opuserid=opuserid, opcompanyid=opcompanyid, default='true').first()\r\n opusercompanyid_default = opuser_company_default_querys.opcompanyid\r\n opuseremail_default = opuser_company_default_querys.opemail\r\n opusercompanyinfo_default = Company.query.filter_by(companyid=opusercompanyid_default).first()\r\n opusercompanyname_default = opusercompanyinfo_default.companyname\r\n opusercompanyrole_default = opusercompanyinfo_default.companyrole\r\n opusercompanyexpire_default = opusercompanyinfo_default.companyexpiredate\r\n opmobile = opuser_company_default_querys.opmobile\r\n oprole = opuser_company_default_querys.oprole\r\n opusername = opuser_company_default_querys.opusername\r\n\r\n userinfo = User.query.filter_by(userid=opuserid).first()\r\n user_profile = userinfo.profile\r\n mobile = userinfo.mobile\r\n userinfo.role = '0'\r\n user_id = opuserid\r\n user_name = userinfo.username\r\n db.session.commit()\r\n db.session.close()\r\n return {\r\n \"companyexpiredate\": opusercompanyexpire_default,\r\n \"companyid\": opusercompanyid_default,\r\n \"companyname\": opusercompanyname_default,\r\n \"companyrole\": opusercompanyrole_default,\r\n \"email\": opuseremail_default,\r\n \"imageUrl\": user_profile,\r\n \"opmobile\": opmobile,\r\n \"mobile\": mobile,\r\n \"msg\": \"登录成功\",\r\n \"role\": '0',\r\n \"oprole\": oprole,\r\n \"status\": 0,\r\n \"token\": user_id + \"-11111\",\r\n \"userid\": user_id,\r\n \"username\": user_name,\r\n \"opusername\": opusername,\r\n\r\n }\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\ndef push_msg_to_android(userid,usertoken, package_name, title, description, pass_through,payload):\r\n APP_SecKey = r\"lsoNVMUZH69YvcsLR6SHNQ==\"\r\n result_code = 0\r\n try:\r\n\r\n\r\n # build android message\r\n message = PushMessage() \\\r\n .restricted_package_name(package_name) \\\r\n .title(title).description(description) \\\r\n .pass_through(pass_through).payload(payload) \\\r\n .extra({Constants.extra_param_notify_effect: Constants.notify_launcher_activity})\r\n\r\n except:\r\n print(\"get parameters value error ! \", sys.exc_info()[0])\r\n msg = \"get parameters value error \"\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n try:\r\n sender = APISender(APP_SecKey)\r\n recv = sender.send_to_user_account(message.message_dict(), userid)\r\n print(recv)\r\n\r\n except:\r\n print(\"send msg was failed ! \", sys.exc_info()[0])\r\n result_code = 1\r\n msg = \"send msg was failed \"\r\n finally:\r\n msg = \"succecss\"\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n\r\n\r\n\r\ndef push_msg_to_ios(userid,usertoken, package_name, title, subtitle, body):\r\n APP_SecKey = r\"XWd6+oOcSmliC4jJJsdrcw==\"\r\n result_code = 0\r\n try:\r\n message_ios10 = PushMessage() \\\r\n .restricted_package_name(package_name) \\\r\n .aps_title(title) \\\r\n .aps_subtitle(subtitle) \\\r\n .aps_body(body) \\\r\n .aps_mutable_content(\"1\") \\\r\n .sound_url(\"default\") \\\r\n .badge(1) \\\r\n .category(\"action\") \\\r\n .extra({\"key\": \"value\"})\r\n\r\n except:\r\n print(\"get parameters value error ! \", sys.exc_info()[0])\r\n result_code = 1\r\n msg = \"get parameters value error \"\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n try:\r\n sender = APISender(APP_SecKey)\r\n\r\n recv_ios = sender.send_to_user_account(message_ios10.message_dict_ios(), userid)\r\n print(recv_ios)\r\n\r\n\r\n tools = APITools(APP_SecKey)\r\n except:\r\n print(\"send msg was failed ! \", sys.exc_info()[0])\r\n result_code = 1\r\n msg = \"send msg was failed \"\r\n finally:\r\n msg = \"succecss\"\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n\r\n\"\"\"\r\n# 取消公司申请\r\ndef cancel_companyapplication(companyid, usertoken, userid):\r\n try:\r\n\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'Ooooops, token不可用'}\r\n\r\n application = Topic.query.filter_by(companyid=companyid, request_userid=userid).first()\r\n application.admin_action = '3'\r\n db.session.commit()\r\n db.session.close()\r\n\r\n return {'status': 0, 'msg': '取消公司申请成功'}\r\n\r\n except sqlalchemy.exc.OperationError:\r\n\r\n db.session.close()\r\n return {'Oooops': 'There is a problem with the database'}\r\n\"\"\"\r\n\r\n# 取消公司申请\r\ndef cancel_companyapplication(companyid, usertoken, userid):\r\n try:\r\n\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'Ooooops, token不可用'}\r\n\r\n opusers = Opuser.query.filter_by(opuserid=userid).all()\r\n\r\n if opusers:\r\n for opuser in opusers:\r\n if opuser.opcompanyid != companyid:\r\n user = User.query.filter_by(userid=userid).first()\r\n user.role = '0'\r\n application = Topic.query.filter_by(companyid=companyid,request_userid=userid).order_by(desc(Topic.id)).first()\r\n if application:\r\n\r\n application.admin_action = '3'\r\n\r\n myopuser = Opuser.query.filter_by(opuserid=userid,opcompanyid=companyid).delete()\r\n\r\n db.session.commit()\r\n db.session.close()\r\n \r\n result = {'status': 0, 'msg': '取消公司申请成功'}\r\n return result\r\n\r\n else:\r\n user = User.query.filter_by(userid=userid).first()\r\n user.role = '4'\r\n application = Topic.query.filter_by(companyid=companyid,request_userid=userid).order_by(desc(Topic.id)).first() \r\n if application:\r\n application.admin_action = '3'\r\n myopuser = Opuser.query.filter_by(opuserid=userid, opcompanyid=companyid).delete()\r\n db.session.commit()\r\n db.session.close()\r\n\r\n result= {'status': 0, 'msg': '取消公司申请成功'}\r\n return result\r\n\r\n except sqlalchemy.exc.OperationError:\r\n\r\n db.session.close()\r\n return {'Oooops': 'There is a problem with the database'}\r\n\r\n\r\n#搜索用户状态\r\ndef userstatus_search(usertoken, userid):\r\n try:\r\n\r\n user = User.query.filter_by(userid=userid).first()\r\n usermark = user.mark\r\n\r\n return {'status': 0, \"msg\": \"获取用户状态成功\", \"usermark\": usermark}\r\n\r\n except sqlalchemy.exc.OperationError:\r\n\r\n db.session.close()\r\n return {'Oooops': 'There is a problem with the database'}\r\n" }, { "alpha_fraction": 0.5337153077125549, "alphanum_fraction": 0.5391508936882019, "avg_line_length": 30.697114944458008, "blob_id": "46993c0c318d2bbafe14446ff58b3cb9cab51034", "content_id": "da03538791a55f0b3bc4c9a371595a84aa336526", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7369, "license_type": "no_license", "max_line_length": 116, "num_lines": 208, "path": "/chatapi/push_msg.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n\r\nfrom APISender import APISender\r\nfrom base.APIMessage import *\r\nfrom APITools import *\r\nfrom APISubscribe import *\r\nimport sys\r\n\r\n\r\ndef push_msg_to_android(userid,usertoken, send_packagename, send_title, send_msg, send_msg_desc, send_pass_through):\r\n APP_SecKey = r\"lsoNVMUZH69YvcsLR6SHNQ==\"\r\n result_code = 0\r\n try:\r\n\r\n #设置app的包名packageName\r\n #package_name = \"com.domain.operationrobot\"\r\n package_name = send_packagename\r\n #设置在通知栏展示的通知的标题\r\n title = send_title.replace(\"'\", '')\r\n #设置要发送的消息内容, 不允许全是空白字符\r\n msg = send_msg.replace(\"'\", '')\r\n #设置在通知栏展示的通知描述\r\n msg_desc = send_msg_desc.replace(\"'\", '')\r\n #1表示透传, 0表示通知栏, 默认通知栏\r\n pass_through = int(send_pass_through)\r\n\r\n # build android message\r\n message = PushMessage() \\\r\n .restricted_package_name(package_name) \\\r\n .title(title).description(msg_desc) \\\r\n .pass_through(pass_through).payload(msg) \\\r\n .extra({Constants.extra_param_notify_effect: Constants.notify_launcher_activity})\r\n\r\n except:\r\n print(\"get parameters value error ! \", sys.exc_info()[0])\r\n msg = \"get parameters value error \"\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n try:\r\n sender = APISender(APP_SecKey)\r\n recv = sender.send(message.message_dict(), userid)\r\n print(recv)\r\n tools = APITools(APP_SecKey)\r\n # 查询消息状态\r\n print(tools.query_message_status('msg_id').data)\r\n # 验证reg_id是否无效\r\n print(tools.validate_reg_ids(['reg_id1', 'reg_id2']))\r\n # 获取无效reg_id\r\n print(tools.query_invalid_reg_ids())\r\n # 获取无效alias\r\n print(tools.query_invalid_aliases())\r\n # 获取设备订阅topic\r\n print(tools.query_device_topics('package_name', 'reg_id'))\r\n print(tools.query_device_presence('package_name', ['reg_id1', 'reg_id2']))\r\n # 获取设备设置alias\r\n print(tools.query_device_aliases('package_name', 'reg_id'))\r\n # 检查定时任务是否存在\r\n print(tools.check_schedule_job_exist('msg_id'))\r\n except:\r\n print(\"send msg was failed ! \", sys.exc_info()[0])\r\n result_code = 1\r\n msg = \"send msg was failed \"\r\n finally:\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n\r\ndef push_msg_to_ios(userid,usertoken, send_packagename, send_title, send_key, send_value, send_msg_desc):\r\n APP_SecKey = r\"XWd6+oOcSmliC4jJJsdrcw==\"\r\n result_code = 0\r\n try:\r\n\r\n #设置app的包名packageName\r\n #package_name = \"com.domain.operationrobot\"\r\n package_name = send_packagename\r\n #设置在通知栏展示的通知的标题\r\n title = send_title.replace(\"'\", '')\r\n #自定义键值对, 控制客户端行为\r\n send_key = send_key.replace(\"'\", '')\r\n\r\n #设置在通知栏展示的通知描述\r\n msg_desc = send_msg_desc.replace(\"'\", '')\r\n except:\r\n print(\"get parameters value error ! \", sys.exc_info()[0])\r\n result_code = 1\r\n msg = \"get parameters value error \"\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n try:\r\n sender = APISender(APP_SecKey)\r\n message_ios = PushMessage() \\\r\n .description(msg_desc) \\\r\n .sound_url(\"default\") \\\r\n .badge(1) \\\r\n .extra({send_key: send_value})\r\n recv_ios = sender.send(message_ios.message_dict_ios(), userid)\r\n print(recv_ios)\r\n\r\n\r\n tools = APITools(APP_SecKey)\r\n # 查询消息状态\r\n print(tools.query_message_status('msg_id').data)\r\n # 验证reg_id是否无效\r\n print(tools.validate_reg_ids(['reg_id1', 'reg_id2']))\r\n # 获取无效reg_id\r\n print(tools.query_invalid_reg_ids())\r\n # 获取无效alias\r\n print(tools.query_invalid_aliases())\r\n # 获取设备订阅topic\r\n print(tools.query_device_topics('package_name', 'reg_id'))\r\n print(tools.query_device_presence('package_name', ['reg_id1', 'reg_id2']))\r\n # 获取设备设置alias\r\n print(tools.query_device_aliases('package_name', 'reg_id'))\r\n # 检查定时任务是否存在\r\n print(tools.check_schedule_job_exist('msg_id'))\r\n except:\r\n print(\"send msg was failed ! \", sys.exc_info()[0])\r\n result_code = 1\r\n msg = \"send msg was failed \"\r\n finally:\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\ndef push_msg_to_ios10(userid,usertoken, send_packagename, send_title, send_key, send_value, send_msg_desc):\r\n APP_SecKey = r\"XWd6+oOcSmliC4jJJsdrcw==\"\r\n result_code = 0\r\n message_ios10 = PushMessage() \\\r\n .aps_title(\"title\") \\\r\n .aps_subtitle(\"subtitle\") \\\r\n .aps_body(\"body\") \\\r\n .aps_mutable_content(\"1\") \\\r\n .sound_url(\"default\") \\\r\n .badge(1) \\\r\n .category(\"action\") \\\r\n .extra({\"key\": \"value\"})\r\n try:\r\n\r\n #设置app的包名packageName\r\n #package_name = \"com.domain.operationrobot\"\r\n package_name = send_packagename\r\n #设置在通知栏展示的通知的标题\r\n title = send_title.replace(\"'\", '')\r\n #自定义键值对, 控制客户端行为\r\n send_key = send_key.replace(\"'\", '')\r\n\r\n #设置在通知栏展示的通知描述\r\n msg_desc = send_msg_desc.replace(\"'\", '')\r\n except:\r\n print(\"get parameters value error ! \", sys.exc_info()[0])\r\n result_code = 1\r\n msg = \"get parameters value error \"\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n try:\r\n sender = APISender(APP_SecKey)\r\n message_ios = PushMessage() \\\r\n .description(msg_desc) \\\r\n .sound_url(\"default\") \\\r\n .badge(1) \\\r\n .extra({send_key: send_value})\r\n recv_ios = sender.send(message_ios.message_dict_ios(), userid)\r\n print(recv_ios)\r\n\r\n\r\n tools = APITools(APP_SecKey)\r\n # 查询消息状态\r\n print(tools.query_message_status('msg_id').data)\r\n # 验证reg_id是否无效\r\n print(tools.validate_reg_ids(['reg_id1', 'reg_id2']))\r\n # 获取无效reg_id\r\n print(tools.query_invalid_reg_ids())\r\n # 获取无效alias\r\n print(tools.query_invalid_aliases())\r\n # 获取设备订阅topic\r\n print(tools.query_device_topics('package_name', 'reg_id'))\r\n print(tools.query_device_presence('package_name', ['reg_id1', 'reg_id2']))\r\n # 获取设备设置alias\r\n print(tools.query_device_aliases('package_name', 'reg_id'))\r\n # 检查定时任务是否存在\r\n print(tools.check_schedule_job_exist('msg_id'))\r\n except:\r\n print(\"send msg was failed ! \", sys.exc_info()[0])\r\n result_code = 1\r\n msg = \"send msg was failed \"\r\n finally:\r\n result = {\r\n \"msg\": msg,\r\n \"status\": result_code\r\n }\r\n return result\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5050504803657532, "alphanum_fraction": 0.5262460708618164, "avg_line_length": 27.476415634155273, "blob_id": "6d9dc7eb91cdd6d5f415260159d008965d487d2b", "content_id": "d8a82acbb596c0df0eeb2d6c63bac0ddd622f3cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6351, "license_type": "no_license", "max_line_length": 117, "num_lines": 212, "path": "/chatbot-youke1/chatbot.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from socketIO_client import SocketIO, BaseNamespace\nimport requests, json\nimport threading\n\n#serverip = 'http://127.0.0.1:5000'\nserverip = 'http://nginx-server:5001'\nsocket = SocketIO('nginx-server',5001)\n\n#serverip = 'http://61.139.64.108:18080'\n#socket = SocketIO('http://61.139.64.108',18080)\n#socket = SocketIO('',5001)\napiurl = serverip + '/api/v1/login'\napigetmonitorurl = serverip + '/api/v1/zabbixmonitor'\n#payload = {\"password\": \"ppy6rQ3iAMKNzpDjpqYdP29g1STvoz6t0\", \"mobile\": \"c2YDSc5nIO7u0Bxjy7JHj0VOy\"}\npayload = {\"password\": \"i8Ts9fJeBa5Q3AU2Ift74g==\", \"mobile\": \"youke-chatbot\"}\nheader = {'Content-Type': 'application/json'}\n\nloginrs = requests.post(apiurl, data=json.dumps(payload), headers=header)\nprint(\"login...\")\ntoken = loginrs.json()['token']\nprint(token)\ncompanyid = None\nprint(companyid)\n\n#机器人登录\ndef botjoinroot(message):\n sendmsg = {'token': token,'role':'chatbot', 'companyid':companyid, 'msg': message}\n socket.emit('talk', sendmsg)\n\n\n#连接响应\ndef conn_response(*args):\n print(args[0])\n\n#谈论响应\ndef talk_response(*args):\n print('talk zzzzzzzzzzz')\n print(args[0])\n\n\n#机器人响应命令类型\ndef botsendmsgtype2(username):\n sendmsgtype2 = {'data': {'type': 2,'companyid':companyid, 'token': token, 'rootbean':\n {'msg': '你好,'+ username + ' 需要我帮你做点什么?', 'actions':\n [{'name': '查看主机CPU', 'type': '3'},\n {'name': '查看主机内存', 'type': '4'},\n {'name': '查看磁盘状态', 'type': '6'},\n {'name': '查看网络流量', 'type': '8'},\n {'name': '重启主机', 'type': '10'}\n ]}}}\n socket.emit('chatbot', sendmsgtype2)\n print('ooooooh yes')\n\n\n#发送查询cpu信息\ndef botsendmsgtype3(host):\n\n sendmsgtype3 = {\n \"data\": {\n \"type\": 3,\n \"token\": token,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + host + \")CPU运行情况:\",\n \"actions\": [\n {\n \"title\": \"CPU\",\n \"ratio\": '89',\n }\n ]}}}\n\n socket.emit('chatbot', sendmsgtype3)\n print('ooooooh yes')\n\n\n#发送查询内存消息\ndef botsendmsgtype4(host):\n sendmsgtype4 = {\n \"data\": {\n \"type\": 4,\n \"token\": token,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + host + \")内存运行情况:\",\n \"actions\": [\n {\n \"title\": \"内存\",\n \"ratio\": '66',\n }\n ]}}}\n\n socket.emit('chatbot', sendmsgtype4)\n print('ooooooh yes')\n\n#发送查询网络状况消息\ndef botsendmsgtype8(host):\n sendmsgtype8 = {\n \"data\": {\n \"type\": 8,\n \"token\": token,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + host + \")网络状况:\",\n \"actions\": [\n {\n \"netDrive\": \"eth0\",\n \"outNet\": \"55\",\n \"inNet\": '22',\n },\n {\n \"netDrive\": \"eth1\",\n \"outNet\": \"552\",\n \"inNet\": '223',\n }\n ]}}}\n\n socket.emit('chatbot', sendmsgtype8)\n print('ooooooh yes')\n\n\ndef botsendmsgtype6(host):\n sendmsgtype6 = {\n \"data\": {\n \"type\": 4,\n \"token\": token,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + host + \")磁盘运行情况:\",\n \"actions\": [\n {\n \"title\": \"磁盘\",\n \"ratio\": '24.36',\n }\n ]}}}\n\n socket.emit('chatbot', sendmsgtype6)\n print('ooooooh yes')\n\n#发送打招呼信息\ndef botsendmsgtype1(username):\n sendmsgtype1 = {'data': {'type':1, 'token': token,'companyid':companyid, 'rootbean':{'msg': '你好,'+ username}}}\n socket.emit('chatbot', sendmsgtype1)\n print('ooooooh yes')\n\n\n#机器人针对不同命令类型进行响应\ndef chatbot_response(*args):\n print('chatbot zzzzzzzzzzz')\n botmsgdict = args[0]\n print(botmsgdict)\n username = botmsgdict['data']['username']\n if username is None:\n username = '游客'\n\n if botmsgdict['data']['userid'] != 'youkechatbot' and botmsgdict['data']['type'] == 1:\n botsendmsgtype1(username)\n print('lalalalalalalalal')\n elif botmsgdict['data']['userid'] != 'youkechatbot' and botmsgdict['data']['type'] == 2:\n botsendmsgtype2(username)\n elif botmsgdict['data']['userid'] != 'youkechatbot' and botmsgdict['data']['commandType'] == 3:\n print(botmsgdict['data'])\n host = botmsgdict['data']['rootbean']['hostip']\n print(host)\n botsendmsgtype3(host)\n elif botmsgdict['data']['userid'] != 'youkechatbot' and botmsgdict['data']['commandType'] == 4:\n print(botmsgdict['data'])\n host = botmsgdict['data']['rootbean']['hostip']\n print(host)\n botsendmsgtype4(host)\n elif botmsgdict['data']['userid'] != 'youkechatbot' and botmsgdict['data']['commandType'] == 6:\n print(botmsgdict['data'])\n host = botmsgdict['data']['rootbean']['hostip']\n print(host)\n botsendmsgtype6(host)\n elif botmsgdict['data']['userid'] != 'youkechatbot' and botmsgdict['data']['commandType'] == 8:\n print(botmsgdict['data'])\n host = botmsgdict['data']['rootbean']['hostip']\n print(host)\n botsendmsgtype8(host)\n\n\n\n\n#监控chatbotstatus\ndef chatbots():\n while True:\n socket.on('chatbotstatus', chatbot_response)\n socket.wait(seconds=1)\n\n\ntada = threading.Thread(target=chatbots)\ntada.start()\n\n\n#监控constatus\ndef conn():\n print(\"hehe\")\n socket.emit('conn', 'test')\n botjoinroot('join room')\n socket.on('connstatus', conn_response)\n socket.wait(seconds=1)\n\n\ndef botsendmsgtypehello():\n sendmsgtype1 = {'data': {'type':1, 'token': token,'companyid': companyid, 'rootbean':{'msg': 'joinchatbotroom'}}}\n socket.emit('chatbot', sendmsgtype1)\n print('ooooooh yes')\n\n\nprint('ssss')\nconn()\nbotsendmsgtypehello()\n\n\n" }, { "alpha_fraction": 0.6646706461906433, "alphanum_fraction": 0.7485029697418213, "avg_line_length": 82.5, "blob_id": "455ba07914a1691c4dac211eac3663b8a60cf66a", "content_id": "0eccd10d4b7e5b5588b0da972698fb72bca28052", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 167, "license_type": "no_license", "max_line_length": 117, "num_lines": 2, "path": "/nginx/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/chatnginx . -f Dockerfile\n#docker run -d -p 6001:80 -p 5001:5001 -v /root/mychat/upload/upload:/data/upload --name=chatnginx mychat/chatnginx\n" }, { "alpha_fraction": 0.48745134472846985, "alphanum_fraction": 0.5030912756919861, "avg_line_length": 43.51804733276367, "blob_id": "8671f5e38d0c7ccb71c740de590e909a51082a9e", "content_id": "34a8c4d0eccbe1d8d674b3c6aff811af461764c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 69265, "license_type": "no_license", "max_line_length": 251, "num_lines": 1496, "path": "/chatapi/zabbix_quey.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n#coding=utf-8\r\nimport json\r\nimport requests\r\nfrom model import *\r\nimport sqlalchemy\r\nimport re\r\nimport random\r\nimport string\r\nimport os\r\nimport sys\r\nimport demjson\r\nimport fnmatch\r\nimport logging\r\nfrom logging.handlers import TimedRotatingFileHandler\r\n\r\n\r\n\r\nfmt_str = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'\r\nlogging.basicConfig()\r\nfilename_head = os.getcwd() + \"/logs/rebot.log\"\r\nfileshandle = logging.handlers.TimedRotatingFileHandler(filename_head, when=\"midnight\", interval=1, backupCount=30,\r\n encoding='utf-8', delay=False, utc=False)\r\nfileshandle.suffix = \"%Y-%m-%d\"\r\nformatter = logging.Formatter(fmt_str)\r\nfileshandle.setFormatter(formatter)\r\nlogger = logging.getLogger(\"zabbix_quey\")\r\nlogger.addHandler(fileshandle)\r\nlogger.setLevel(logging.INFO)\r\n\r\ndef generate_random_str(randomlength=16):\r\n \"\"\"\r\n 生成一个指定长度的随机字符串,其中\r\n string.digits=0123456789\r\n string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n \"\"\"\r\n str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]\r\n random_str = ''.join(str_list)\r\n return random_str\r\n\r\n\r\nheaders = {'Content-Type': 'application/json-rpc'}\r\n\r\ndef auth(zabbixusername, zabbixpassword, zabbixurl):\r\n\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"user.login\",\r\n \"params\": {\r\n \"user\": zabbixusername,\r\n \"password\": zabbixpassword\r\n },\r\n \"id\": 0\r\n })\r\n\r\n authrs = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n token = authrs.json()['result']\r\n return token\r\n\r\n\r\ndef hostgroups(zabbixtoken, zabbixurl):\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\":\"2.0\",\r\n \"method\":\"hostgroup.get\",\r\n \"params\":{\r\n \"output\":[\"groupid\",\"name\"],\r\n },\r\n \"auth\":zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\":1,\r\n })\r\n hostgroups = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n group_list = hostgroups.json()['result']\r\n return group_list\r\n\r\n\r\ndef zabbixserver_add(userid, usertoken, zabbixserver, zabbixusername, zabbixpassword):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n\r\n adminuserinfo_query = User.query.filter_by(userid=userid).first()\r\n adminuser_companyid = adminuserinfo_query.companyid\r\n adminuserrole = adminuserinfo_query.role\r\n if adminuserrole != '4':\r\n return {'status':2, 'msg':'没有权限'}\r\n\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=adminuser_companyid).first()\r\n if zabbixinfo_query:\r\n return {'status': 3, 'msg': 'zabbix服务器已经存在'}\r\n\r\n zabbixserverid = 'z' + generate_random_str()\r\n insert_zabbixserver = Zabbix(companyid=adminuser_companyid, zabbixid=zabbixserverid,zabbixserver=zabbixserver, zabbixuser=zabbixusername, zabbixpassword=zabbixpassword)\r\n db.session.add(insert_zabbixserver)\r\n db.session.commit()\r\n return {'status':0, 'msg': '添加成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status': 3, 'Oooops': '数据库连接出现错误'}\r\n\r\n\r\n\"\"\"\r\ndef query_hosts(userid, usertoken, companyid):\r\n try:\r\n print(usertoken)\r\n if usertoken != '11111':\r\n return {'status':1 ,'msg': 'token不可用'}\r\n \r\n \r\n user_youke_check = User.query.filter_by(userid=userid).first()\r\n if user_youke_check.role == '1' or user_youke_check.role == '2':\r\n db.session.close()\r\n return {\r\n \"inamount\": 2,\r\n \"inhosts\": [\r\n {\r\n \"host\": \"10.0.60.175\",\r\n \"hostid\": \"10254\",\r\n \"hoststatus\": \"in\",\r\n \"name\": \"10.0.60.175\"\r\n },\r\n {\r\n \"host\": \"Zabbix server\",\r\n \"hostid\": \"10084\",\r\n \"hoststatus\": \"in\",\r\n \"name\": \"Zabbix server\"\r\n }\r\n ],\r\n \"status\": 0,\r\n \"totalamount\": 5,\r\n \"totalhosts\": [\r\n {\r\n \"host\": \"Zabbix server\",\r\n \"hostid\": \"10084\",\r\n \"hoststatus\": \"in\",\r\n \"name\": \"Zabbix server\"\r\n },\r\n {\r\n \"host\": \"10.0.60.175\",\r\n \"hostid\": \"10254\",\r\n \"hoststatus\": \"in\",\r\n \"name\": \"10.0.60.175\"\r\n },\r\n {\r\n \"host\": \"10.0.60.176\",\r\n \"hostid\": \"10258\",\r\n \"hoststatus\": \"out\",\r\n \"name\": \"10.0.60.176\"\r\n },\r\n {\r\n \"host\": \"10.0.1.131\",\r\n \"hostid\": \"10259\",\r\n \"hoststatus\": \"out\",\r\n \"name\": \"10.0.1.131\"\r\n },\r\n {\r\n \"host\": \"10.0.60.187\",\r\n \"hostid\": \"10261\",\r\n \"hoststatus\": \"out\",\r\n \"name\": \"10.0.60.187-saltstack-test\"\r\n }\r\n ]\r\n }\r\n \r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid).first()\r\n if zabbixinfo_query is None:\r\n db.session.close()\r\n return {'status': 2, 'msg': '使用监控功能之前,需要先添加zabbix服务器'}\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n\r\n group_list = hostgroups(zabbixtoken, zabbixurl)\r\n print(group_list)\r\n hostinfo_list = []\r\n for group in group_list:\r\n #hostinfo_dict = {}\r\n hostinfo_list.append(group['groupid'])\r\n #groupid = group['groupid']\r\n #groupname = group['name']\r\n print(hostinfo_list)\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"host.get\",\r\n \"params\": {\r\n \"output\": [\"hostid\", \"name\", \"host\"],\r\n \"groupids\": hostinfo_list,\r\n },\r\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\": 1,\r\n })\r\n hosts = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n print(hosts)\r\n hosts_list = hosts.json()['result']\r\n print(hosts_list)\r\n checkhosts_list = []\r\n for checkhost_dict in hosts_list:\r\n\r\n checkhostid = checkhost_dict['hostid']\r\n checkhost_query = Monitor.query.filter_by(zabbixhostid=checkhostid,companyid=companyid).first()\r\n if checkhost_query:\r\n if checkhost_query.supervisor == True:\r\n checkhost_dict['hoststatus'] = 'in'\r\n else:\r\n checkhost_dict['hoststatus'] = 'out'\r\n checkhosts_list.append(checkhost_dict)\r\n\r\n allhostsnumber = len(checkhosts_list)\r\n inhostsnumber_query = Monitor.query.filter_by(companyid=companyid,supervisor=True).all()\r\n inhostsnumber = len(inhostsnumber_query)\r\n inhostinfo_list = []\r\n for inhost in inhostsnumber_query:\r\n inhostinfo_dict = {'hostid':inhost.zabbixhostid, 'host':inhost.zabbixhostip, 'name':inhost.zabbixhostname, 'hoststatus':'in'}\r\n inhostinfo_list.append(inhostinfo_dict)\r\n\r\n hosts_queryrs = {'status': 0, 'totalamount': allhostsnumber,\r\n 'inamount':inhostsnumber, 'totalhosts': checkhosts_list,\r\n 'inhosts':inhostinfo_list,\r\n }\r\n print(hosts_queryrs)\r\n db.session.close()\r\n return hosts_queryrs\r\n # host_list = hosts.json()['result']\r\n # if host_list:\r\n # hostinfo_dict['zabbixgroupid'] = groupid\r\n # hostinfo_dict['zabbixgroupname'] = groupname\r\n # hostinfo_dict['zabbixgrouphosts'] = host_list\r\n # hostinfo_list.append(hostinfo_dict)\r\n # response = {'result': hostinfo_list}\r\n # return response\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\"\"\"\r\n\r\ndef query_hosts(userid, usertoken, companyid):\r\n try:\r\n print(usertoken)\r\n if usertoken != '11111':\r\n return {'status':1 ,'msg': 'token不可用'}\r\n \r\n \"\"\"\r\n user_youke_check = User.query.filter_by(userid=userid).first()\r\n if user_youke_check.role == '1' or user_youke_check.role == '2':\r\n db.session.close()\r\n return {\r\n \"inamount\": 2,\r\n \"inhosts\": [\r\n {\r\n \"host\": \"10.0.60.175\",\r\n \"hostid\": \"10254\",\r\n \"hoststatus\": \"in\",\r\n \"name\": \"10.0.60.175\"\r\n },\r\n {\r\n \"host\": \"Zabbix server\",\r\n \"hostid\": \"10084\",\r\n \"hoststatus\": \"in\",\r\n \"name\": \"Zabbix server\"\r\n }\r\n ],\r\n \"status\": 0,\r\n \"totalamount\": 5,\r\n \"totalhosts\": [\r\n {\r\n \"host\": \"Zabbix server\",\r\n \"hostid\": \"10084\",\r\n \"hoststatus\": \"in\",\r\n \"name\": \"Zabbix server\"\r\n },\r\n {\r\n \"host\": \"10.0.60.175\",\r\n \"hostid\": \"10254\",\r\n \"hoststatus\": \"in\",\r\n \"name\": \"10.0.60.175\"\r\n },\r\n {\r\n \"host\": \"10.0.60.176\",\r\n \"hostid\": \"10258\",\r\n \"hoststatus\": \"out\",\r\n \"name\": \"10.0.60.176\"\r\n },\r\n {\r\n \"host\": \"10.0.1.131\",\r\n \"hostid\": \"10259\",\r\n \"hoststatus\": \"out\",\r\n \"name\": \"10.0.1.131\"\r\n },\r\n {\r\n \"host\": \"10.0.60.187\",\r\n \"hostid\": \"10261\",\r\n \"hoststatus\": \"out\",\r\n \"name\": \"10.0.60.187-saltstack-test\"\r\n }\r\n ]\r\n }\r\n \"\"\"\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query.companyrole == '1':\r\n\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid,official='1').first()\r\n elif company_query.companyrole == '2':\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\r\n if zabbixinfo_query is None:\r\n db.session.close()\r\n return {'status': 2, 'msg': '使用监控功能之前,需要先添加zabbix服务器'}\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n\r\n group_list = hostgroups(zabbixtoken, zabbixurl)\r\n print(group_list)\r\n hostinfo_list = []\r\n for group in group_list:\r\n #hostinfo_dict = {}\r\n hostinfo_list.append(group['groupid'])\r\n #groupid = group['groupid']\r\n #groupname = group['name']\r\n print(hostinfo_list)\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"host.get\",\r\n \"params\": {\r\n \"output\": [\"hostid\", \"name\", \"host\"],\r\n \"groupids\": hostinfo_list,\r\n },\r\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\": 1,\r\n })\r\n hosts = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n print(hosts)\r\n hosts_list = hosts.json()['result']\r\n print(hosts_list)\r\n checkhosts_list = []\r\n for checkhost_dict in hosts_list:\r\n\r\n checkhostid = checkhost_dict['hostid']\r\n checkhost_query = Monitor.query.filter_by(zabbixhostid=checkhostid,companyid=companyid).first()\r\n if checkhost_query:\r\n if checkhost_query.supervisor == True:\r\n checkhost_dict['hoststatus'] = 'in'\r\n else:\r\n checkhost_dict['hoststatus'] = 'out'\r\n checkhosts_list.append(checkhost_dict)\r\n\r\n allhostsnumber = len(checkhosts_list)\r\n inhostsnumber_query = Monitor.query.filter_by(companyid=companyid,supervisor=True).all()\r\n inhostsnumber = len(inhostsnumber_query)\r\n inhostinfo_list = []\r\n for inhost in inhostsnumber_query:\r\n inhostinfo_dict = {'hostid':inhost.zabbixhostid, 'host':inhost.zabbixhostip, 'name':inhost.zabbixhostname, 'hoststatus':'in'}\r\n inhostinfo_list.append(inhostinfo_dict)\r\n\r\n hosts_queryrs = {'status': 0, 'totalamount': allhostsnumber,\r\n 'inamount':inhostsnumber, 'totalhosts': checkhosts_list,\r\n 'inhosts':inhostinfo_list,\r\n }\r\n print(hosts_queryrs)\r\n db.session.close()\r\n return hosts_queryrs\r\n # host_list = hosts.json()['result']\r\n # if host_list:\r\n # hostinfo_dict['zabbixgroupid'] = groupid\r\n # hostinfo_dict['zabbixgroupname'] = groupname\r\n # hostinfo_dict['zabbixgrouphosts'] = host_list\r\n # hostinfo_list.append(hostinfo_dict)\r\n # response = {'result': hostinfo_list}\r\n # return response\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\r\ndef query_zabbixhost(userid, usertoken, searchname, companyid):\r\n try:\r\n\r\n if usertoken != '11111':\r\n return {'status':1 ,'msg': 'token不可用'}\r\n user_companyid = companyid\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n\r\n group_list = hostgroups(zabbixtoken, zabbixurl)\r\n hostinfo_list = []\r\n for group in group_list:\r\n hostinfo_list.append(group['groupid'])\r\n\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"host.get\",\r\n \"params\": {\r\n \"output\": [\"hostid\", \"name\", \"host\"],\r\n \"groupids\": hostinfo_list,\r\n },\r\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\": 1,\r\n })\r\n hosts = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n host_list = hosts.json()['result']\r\n\r\n searchhost_list = []\r\n hostinfo_dict = {}\r\n for query_hostidinfo in host_list:\r\n if query_hostidinfo['name'].find(searchname) != -1:\r\n searchhost_list.append(query_hostidinfo)\r\n\r\n hostinfo_dict['status'] = 0\r\n hostinfo_dict['result'] = searchhost_list\r\n db.session.close()\r\n return hostinfo_dict\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\r\n\"\"\"\r\ndef zabbixmonitor_add(userid, usertoken, hostinfo_list, companyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n\r\n user_youke_check = User.query.filter_by(userid=userid).first()\r\n # 生成zabbix token\r\n user_companyid = companyid\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n zabbixinfoall_query = Monitor.query.filter_by(companyid=user_companyid).first()\r\n if zabbixinfoall_query:\r\n zabbixinfoall_query.query.filter_by(companyid=user_companyid).delete()\r\n\r\n if hostinfo_list:\r\n for hostinfo in hostinfo_list:\r\n zabbixhostid = hostinfo['hostid']\r\n zabbixhostip = hostinfo['host']\r\n zabbixhostname = hostinfo['name']\r\n\r\n data = json.dumps({\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"itemid\", \"key_\"],\r\n \"hostids\": zabbixhostid,\r\n },\r\n \"auth\": zabbixtoken,\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n\r\n zabbixitemname_list = [\"system.cpu.util[,user]\", \"vfs.fs.size\", \"vm.memory.size[available]\", \"vm.memory.size[total]\", \"net.if.in\", \"net.if.out\"]\r\n\r\n itemid_list = []\r\n for itemid_response_value in items_response.json()['result']:\r\n for zabbixitemname in zabbixitemname_list:\r\n if itemid_response_value['key_'].find(zabbixitemname) != -1:\r\n itemid_list.append(itemid_response_value['itemid'])\r\n\r\n insert_zabbixmonitor = Monitor(companyid=user_companyid, zabbixhostid=zabbixhostid, zabbixhostip=zabbixhostip, zabbixhostname=zabbixhostname, zabbixitemname=str(zabbixitemname_list), zabbixitemid=str(itemid_list))\r\n db.session.add(insert_zabbixmonitor)\r\n db.session.commit()\r\n db.session.close()\r\n else:\r\n pass\r\n db.session.commit()\r\n db.session.close()\r\n return {'status':0, 'msg': '添加成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\ndef zabbixmonitor_add(userid, usertoken, hostinfo_list, companyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n\r\n user_youke_check = User.query.filter_by(userid=userid).first()\r\n \r\n if user_youke_check.role == '1' or user_youke_check.role == '2':\r\n db.session.close()\r\n return {'status': 2, 'msg': '游客或者待审核用户无法添加监控主机'}\r\n \r\n # 生成zabbix token\r\n user_companyid = companyid\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n zabbixinfoall_query = Monitor.query.filter_by(companyid=user_companyid).first()\r\n if zabbixinfoall_query:\r\n zabbixinfoall_query.query.filter_by(companyid=user_companyid).delete()\r\n\r\n if hostinfo_list:\r\n for hostinfo in hostinfo_list:\r\n zabbixhostid = hostinfo['hostid']\r\n zabbixhostip = hostinfo['host']\r\n zabbixhostname = hostinfo['name']\r\n supervisor = hostinfo['supervisor']\r\n\r\n data = json.dumps({\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"itemid\", \"key_\"],\r\n \"hostids\": zabbixhostid,\r\n },\r\n \"auth\": zabbixtoken,\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n\r\n zabbixitemname_list = [\"system.cpu.util[,user]\", \"vfs.fs.size\", \"vm.memory.size[available]\", \"vm.memory.size[total]\", \"net.if.in\", \"net.if.out\"]\r\n\r\n itemid_list = []\r\n for itemid_response_value in items_response.json()['result']:\r\n for zabbixitemname in zabbixitemname_list:\r\n if itemid_response_value['key_'].find(zabbixitemname) != -1:\r\n itemid_list.append(itemid_response_value['itemid'])\r\n\r\n insert_zabbixmonitor = Monitor(companyid=user_companyid, zabbixhostid=zabbixhostid, zabbixhostip=zabbixhostip, zabbixhostname=zabbixhostname, zabbixitemname=str(zabbixitemname_list), zabbixitemid=str(itemid_list),supervisor=supervisor)\r\n db.session.add(insert_zabbixmonitor)\r\n db.session.commit()\r\n db.session.close()\r\n else:\r\n pass\r\n db.session.commit()\r\n db.session.close()\r\n return {'status':0, 'msg': '添加成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\"\"\"\r\n\r\ndef zabbixmonitor_add(userid, usertoken, hostinfo_list, companyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n\r\n user_youke_check = User.query.filter_by(userid=userid).first()\r\n \"\"\"\r\n if user_youke_check.role == '1' or user_youke_check.role == '2':\r\n db.session.close()\r\n return {'status': 2, 'msg': '游客或者待审核用户无法添加监控主机'}\r\n \"\"\"\r\n # 生成zabbix token\r\n user_companyid = companyid\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query.companyrole == '1':\r\n\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid, official='1').first()\r\n elif company_query.companyrole == '2':\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\r\n #zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n zabbixinfoall_query = Monitor.query.filter_by(companyid=user_companyid).first()\r\n if zabbixinfoall_query:\r\n zabbixinfoall_query.query.filter_by(companyid=user_companyid).delete()\r\n\r\n if hostinfo_list:\r\n for hostinfo in hostinfo_list:\r\n zabbixhostid = hostinfo['hostid']\r\n zabbixhostip = hostinfo['host']\r\n zabbixhostname = hostinfo['name']\r\n supervisor = hostinfo['supervisor']\r\n\r\n data = json.dumps({\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"itemid\", \"key_\"],\r\n \"hostids\": zabbixhostid,\r\n },\r\n \"auth\": zabbixtoken,\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n\r\n zabbixitemname_list = [\"system.cpu.util[,user]\", \"vfs.fs.size\", \"vm.memory.size[available]\", \"vm.memory.size[total]\", \"net.if.in\", \"net.if.out\"]\r\n\r\n itemid_list = []\r\n for itemid_response_value in items_response.json()['result']:\r\n for zabbixitemname in zabbixitemname_list:\r\n if itemid_response_value['key_'].find(zabbixitemname) != -1:\r\n itemid_list.append(itemid_response_value['itemid'])\r\n\r\n insert_zabbixmonitor = Monitor(companyid=user_companyid, zabbixhostid=zabbixhostid, zabbixhostip=zabbixhostip, zabbixhostname=zabbixhostname, zabbixitemname=str(zabbixitemname_list), zabbixitemid=str(itemid_list),supervisor=supervisor)\r\n db.session.add(insert_zabbixmonitor)\r\n db.session.commit()\r\n db.session.close()\r\n else:\r\n pass\r\n db.session.commit()\r\n db.session.close()\r\n return {'status':0, 'msg': '添加成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\r\n\r\n\r\n\r\ndef zabbixallmonitor_add(userid, usertoken, hostinfo_list, companyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n\r\n user_youke_check = User.query.filter_by(userid=userid).first()\r\n \"\"\"\r\n if user_youke_check.role == '1' or user_youke_check.role == '2':\r\n db.session.close()\r\n return {'status': 2, 'msg': '游客或者待审核用户无法添加监控主机'}\r\n \"\"\"\r\n # 生成zabbix token\r\n user_companyid = companyid\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n\r\n if hostinfo_list:\r\n for hostinfo in hostinfo_list:\r\n zabbixhostid = hostinfo['hostid']\r\n zabbixhostip = hostinfo['host']\r\n zabbixhostname = hostinfo['name']\r\n\r\n data = json.dumps({\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"itemid\", \"key_\"],\r\n \"hostids\": zabbixhostid,\r\n },\r\n \"auth\": zabbixtoken,\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n\r\n zabbixitemname_list = [\"system.cpu.util[,user]\", \"vfs.fs.size\", \"vm.memory.size[available]\", \"vm.memory.size[total]\", \"net.if.in\", \"net.if.out\"]\r\n\r\n itemid_list = []\r\n for itemid_response_value in items_response.json()['result']:\r\n for zabbixitemname in zabbixitemname_list:\r\n if itemid_response_value['key_'].find(zabbixitemname) != -1:\r\n itemid_list.append(itemid_response_value['itemid'])\r\n\r\n insert_zabbixmonitor = Monitor(companyid=user_companyid, zabbixhostid=zabbixhostid, zabbixhostip=zabbixhostip,zabbixhostname=zabbixhostname, zabbixitemname=str(zabbixitemname_list), zabbixitemid=str(itemid_list))\r\n db.session.add(insert_zabbixmonitor)\r\n db.session.commit()\r\n db.session.close()\r\n db.session.close()\r\n return {'status':0, 'msg': '添加成功'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\r\ndef zabbixitem_query(userid, usertoken, companyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n #生成zabbix token\r\n user_companyid = companyid\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n zabbixinfo_querys = Monitor.query.filter_by(companyid=user_companyid).all()\r\n #zabbixitemid_list = eval(zabbixinfo_querys.zabbixitemid)\r\n #获取zabbix数据\r\n zabbixitems_list = []\r\n for zabbixinfo_query in zabbixinfo_querys:\r\n zabbixitem_host_dict = {}\r\n zabbixitemid = zabbixinfo_query.zabbixitemid\r\n zabbixhostid = zabbixinfo_query.zabbixhostid\r\n zabbixhostip = zabbixinfo_query.zabbixhostip\r\n zabbixhostname = zabbixinfo_query.zabbixhostname\r\n zabbixitemid_query_list = eval(zabbixitemid)\r\n zabbixitem_host_dict['hostid'] = zabbixhostid\r\n zabbixitem_host_dict['itemids'] = zabbixitemid_query_list\r\n zabbixitem_host_dict['host'] = zabbixhostip\r\n zabbixitem_host_dict['name'] = zabbixhostname\r\n zabbixitems_list.append(zabbixitem_host_dict)\r\n\r\n items_response_info_list = []\r\n for zabbixitems in zabbixitems_list:\r\n items_response_info_dict = {}\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"key_\", \"lastvalue\"],\r\n \"itemids\": zabbixitems['itemids'],\r\n #\"hostids\": ['10254', '10258'],\r\n },\r\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n items_response_info_dict['host'] = zabbixitems['host']\r\n items_response_info_dict['name'] = zabbixitems['name']\r\n items_response_info_dict['result'] = items_response.json()['result']\r\n items_response_info_list.append(items_response_info_dict)\r\n\r\n for chulihuansuan in items_response_info_list:\r\n\r\n for huansuanzhi in chulihuansuan['result']:\r\n if huansuanzhi['key_'].find('vm.memory.size') != -1:\r\n huansuanzhi['lastvalue'] = float(huansuanzhi['lastvalue'])/1024/1024/1024\r\n\r\n if huansuanzhi['key_'].find('vfs.fs.size') != -1:\r\n huansuanzhi['lastvalue'] = float(huansuanzhi['lastvalue']) / 1024 / 1024/ 1024\r\n if huansuanzhi['key_'].find('net') != -1:\r\n huansuanzhi['lastvalue'] = float(huansuanzhi['lastvalue']) / 1024\r\n\r\n\r\n\r\n for hehe in items_response_info_list:\r\n print(hehe['name'])\r\n for heheda in hehe['result']:\r\n print(heheda)\r\n\r\n db.session.close()\r\n return items_response_info_list\r\n\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\r\n\"\"\"\r\ndef hostmessageget( host, companyid):\r\n try:\r\n if companyid:\r\n zabbixinfo_query_hostid = Monitor.query.filter_by(companyid=companyid, zabbixhostid=host).first()\r\n zabbixinfo_query_hostip = Monitor.query.filter_by(companyid=companyid, zabbixhostip=host).first()\r\n zabbixinfo_query_hostname = Monitor.query.filter_by(companyid=companyid, zabbixhostname=host).first()\r\n else:\r\n zabbixinfo_query_hostid = Monitor.query.filter_by(zabbixhostid=host).first()\r\n zabbixinfo_query_hostip = Monitor.query.filter_by(zabbixhostip=host).first()\r\n zabbixinfo_query_hostname = Monitor.query.filter_by(zabbixhostname=host).first()\r\n\r\n if not zabbixinfo_query_hostid and not zabbixinfo_query_hostip and not zabbixinfo_query_hostname:\r\n\r\n return {'status': '2', 'msg': '没找到主机'}\r\n return {'status':'0','msg':'主机存在'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':'3', 'Oooops': '数据库连接出现错误'}\r\n\"\"\"\r\n\r\n\r\ndef hostmessageget( host, companyid):\r\n try:\r\n if companyid:\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query.companyrole == '1':\r\n zabbixinfo_query_hostid = Monitor.query.filter_by(companyid=\"terperantcompnayid\").first()\r\n zabbixinfo_query_hostip = Monitor.query.filter_by(companyid=\"terperantcompnayid\").first()\r\n zabbixinfo_query_hostname = Monitor.query.filter_by(companyid=\"terperantcompnayid\").first()\r\n elif company_query.companyrole == '2':\r\n\r\n zabbixinfo_query_hostid = Monitor.query.filter_by(companyid=companyid, zabbixhostid=host).first()\r\n zabbixinfo_query_hostip = Monitor.query.filter_by(companyid=companyid, zabbixhostip=host).first()\r\n zabbixinfo_query_hostname = Monitor.query.filter_by(companyid=companyid, zabbixhostname=host).first()\r\n else:\r\n zabbixinfo_query_hostid = Monitor.query.filter_by(zabbixhostid=host).first()\r\n zabbixinfo_query_hostip = Monitor.query.filter_by(zabbixhostip=host).first()\r\n zabbixinfo_query_hostname = Monitor.query.filter_by(zabbixhostname=host).first()\r\n\r\n if not zabbixinfo_query_hostid and not zabbixinfo_query_hostip and not zabbixinfo_query_hostname:\r\n\r\n return {'status': '2', 'msg': '没找到主机'}\r\n return {'status':'0','msg':'主机存在'}\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':'3', 'Oooops': '数据库连接出现错误'}\r\n\r\n\"\"\"\r\ndef zabbixitem_value_query(userid, usertoken, host, companyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n #生成zabbix token\r\n print(host)\r\n user_companyid = companyid\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n \r\n\r\n zabbixinfo_query_hostid = Monitor.query.filter_by(companyid=user_companyid, zabbixhostid=host).first()\r\n zabbixinfo_query_hostip = Monitor.query.filter_by(companyid=user_companyid, zabbixhostip=host).first()\r\n zabbixinfo_query_hostname = Monitor.query.filter_by(companyid=user_companyid, zabbixhostname=host).first()\r\n\r\n if not zabbixinfo_query_hostid and not zabbixinfo_query_hostip and not zabbixinfo_query_hostname:\r\n return {'status':2, 'msg': '没找到主机'}\r\n\r\n if zabbixinfo_query_hostid:\r\n zabbixinfo_query_item_queryinfo = zabbixinfo_query_hostid.zabbixitemid\r\n hostinfo = zabbixinfo_query_hostid.zabbixhostip\r\n elif zabbixinfo_query_hostip:\r\n zabbixinfo_query_item_queryinfo = zabbixinfo_query_hostip.zabbixitemid\r\n hostinfo = zabbixinfo_query_hostip.zabbixhostip\r\n elif zabbixinfo_query_hostname:\r\n zabbixinfo_query_item_queryinfo = zabbixinfo_query_hostname.zabbixitemid\r\n hostinfo = zabbixinfo_query_hostname.zabbixhostip\r\n print('1111111111')\r\n print(zabbixinfo_query_hostname)\r\n print(zabbixinfo_query_hostip)\r\n zabbixinfo_query_item_list = eval(zabbixinfo_query_item_queryinfo)\r\n print(zabbixinfo_query_item_list)\r\n\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"key_\", \"lastvalue\"],\r\n \"itemids\": zabbixinfo_query_item_list,\r\n #\"hostids\": ['10254', '10258'],\r\n },\r\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n\r\n\r\n\r\n memory_available_query_list = []\r\n memory_total_query_list = []\r\n disk_query_list = []\r\n net_in_query_list = []\r\n net_out_query_list = []\r\n cpu_query_list = []\r\n response_queryinfo = {}\r\n\r\n chulihuansuan_response_list = items_response.json()['result']\r\n for chulihuansuan in chulihuansuan_response_list:\r\n if chulihuansuan['key_'].find('vm.memory.size[available]') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue'])/1024/1024/1024\r\n memory_available_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('vm.memory.size[total]') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue'])/1024/1024/1024\r\n memory_total_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('vfs.fs.size') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue']) / 1024 / 1024/ 1024\r\n disk_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('net.if.in') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue']) / 1024\r\n net_in_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('net.if.out') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue']) / 1024\r\n net_out_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('system.cpu.util[,user]') != -1:\r\n cpu_query_list.append(chulihuansuan)\r\n\r\n\r\n print(memory_available_query_list)\r\n print(memory_total_query_list)\r\n print(disk_query_list)\r\n print(net_in_query_list)\r\n print(net_out_query_list)\r\n print(cpu_query_list)\r\n\r\n response_queryinfo['available_memory'] = memory_available_query_list\r\n response_queryinfo['total_memory'] = memory_total_query_list\r\n response_queryinfo['disk'] = disk_query_list\r\n response_queryinfo['in_network'] = net_in_query_list\r\n response_queryinfo['out_network'] = net_out_query_list\r\n response_queryinfo['cpu'] = cpu_query_list\r\n response_queryinfo['hostip'] = hostinfo\r\n\r\n db.session.commit()\r\n db.session.close()\r\n return response_queryinfo\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\"\"\"\r\n\r\n\r\ndef zabbixitem_value_query(userid, usertoken, host, companyid):\r\n try:\r\n if usertoken != '11111':\r\n return {'status': 1, 'msg': 'token不可用'}\r\n #生成zabbix token\r\n print(host)\r\n user_companyid = companyid\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query.companyrole == '1':\r\n\r\n #zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid, official='1').first()\r\n\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid,official='1').first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n\r\n zabbixinfo_query_hostid = Monitor.query.filter_by(companyid=\"terperantcompnayid\", zabbixhostid=host).first()\r\n zabbixinfo_query_hostip = Monitor.query.filter_by(companyid=\"terperantcompnayid\", zabbixhostip=host).first()\r\n zabbixinfo_query_hostname = Monitor.query.filter_by(companyid=\"terperantcompnayid\", zabbixhostname=host).first()\r\n elif company_query.companyrole == '2':\r\n\r\n #zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\r\n\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid,official='2').first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n\r\n zabbixinfo_query_hostid = Monitor.query.filter_by(companyid=user_companyid, zabbixhostid=host).first()\r\n zabbixinfo_query_hostip = Monitor.query.filter_by(companyid=user_companyid, zabbixhostip=host).first()\r\n zabbixinfo_query_hostname = Monitor.query.filter_by(companyid=user_companyid, zabbixhostname=host).first()\r\n\r\n if not zabbixinfo_query_hostid and not zabbixinfo_query_hostip and not zabbixinfo_query_hostname:\r\n return {'status':2, 'msg': '没找到主机'}\r\n\r\n if zabbixinfo_query_hostid:\r\n zabbixinfo_query_item_queryinfo = zabbixinfo_query_hostid.zabbixitemid\r\n hostinfo = zabbixinfo_query_hostid.zabbixhostip\r\n elif zabbixinfo_query_hostip:\r\n zabbixinfo_query_item_queryinfo = zabbixinfo_query_hostip.zabbixitemid\r\n hostinfo = zabbixinfo_query_hostip.zabbixhostip\r\n elif zabbixinfo_query_hostname:\r\n zabbixinfo_query_item_queryinfo = zabbixinfo_query_hostname.zabbixitemid\r\n hostinfo = zabbixinfo_query_hostname.zabbixhostip\r\n print('1111111111')\r\n print(zabbixinfo_query_hostname)\r\n print(zabbixinfo_query_hostip)\r\n zabbixinfo_query_item_list = eval(zabbixinfo_query_item_queryinfo)\r\n print(zabbixinfo_query_item_list)\r\n\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"key_\", \"lastvalue\"],\r\n \"itemids\": zabbixinfo_query_item_list,\r\n #\"hostids\": ['10254', '10258'],\r\n },\r\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\r\n\r\n\r\n\r\n memory_available_query_list = []\r\n memory_total_query_list = []\r\n disk_query_list = []\r\n net_in_query_list = []\r\n net_out_query_list = []\r\n cpu_query_list = []\r\n response_queryinfo = {}\r\n\r\n chulihuansuan_response_list = items_response.json()['result']\r\n for chulihuansuan in chulihuansuan_response_list:\r\n if chulihuansuan['key_'].find('vm.memory.size[available]') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue'])/1024/1024/1024\r\n memory_available_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('vm.memory.size[total]') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue'])/1024/1024/1024\r\n memory_total_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('vfs.fs.size') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue']) / 1024 / 1024/ 1024\r\n disk_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('net.if.in') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue']) / 1024\r\n net_in_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('net.if.out') != -1:\r\n chulihuansuan['lastvalue'] = float(chulihuansuan['lastvalue']) / 1024\r\n net_out_query_list.append(chulihuansuan)\r\n if chulihuansuan['key_'].find('system.cpu.util[,user]') != -1:\r\n cpu_query_list.append(chulihuansuan)\r\n\r\n\r\n print(memory_available_query_list)\r\n print(memory_total_query_list)\r\n print(disk_query_list)\r\n print(net_in_query_list)\r\n print(net_out_query_list)\r\n print(cpu_query_list)\r\n\r\n response_queryinfo['available_memory'] = memory_available_query_list\r\n response_queryinfo['total_memory'] = memory_total_query_list\r\n response_queryinfo['disk'] = disk_query_list\r\n response_queryinfo['in_network'] = net_in_query_list\r\n response_queryinfo['out_network'] = net_out_query_list\r\n response_queryinfo['cpu'] = cpu_query_list\r\n response_queryinfo['hostip'] = hostinfo\r\n\r\n db.session.commit()\r\n db.session.close()\r\n return response_queryinfo\r\n except sqlalchemy.exc.OperationalError:\r\n return {'status':3, 'Oooops': '数据库连接出现错误'}\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\ndef zabbix_get_complay_hosts(usertoken, companyid):\r\n all_host_monitor_value = []\r\n msg = \"\"\r\n status = 0\r\n\r\n #获取zabbix token\r\n headers_base = {\r\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\r\n 'Accept-Encoding': 'gzip, deflate, sdch',\r\n 'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2',\r\n 'Connection': 'keep-alive',\r\n 'User-Agent': 'Chrome/43.0.2357.130 Safari/10000',\r\n 'Content-Type': 'application/json-rpc',\r\n }\r\n\r\n try:\r\n user_companyid = companyid\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n except:\r\n\r\n msg = \"未找到与公司匹配的zabbix服务器信息,请联系系统管理员!\"\r\n logger.error(msg, companyid)\r\n logger.error(sys.exc_info()[0])\r\n status = -2\r\n result = {\r\n \"result\": all_host_monitor_value,\r\n \"msg\": msg,\r\n \"status\": status\r\n }\r\n return result\r\n\r\n #获取所属公司所有的监控信息\r\n try:\r\n zabbixinfo_querys = Monitor.query.filter_by(companyid=user_companyid,supervisor=True).all() \r\n print(len(zabbixinfo_querys))\r\n #获取所属公司的zabbix服务器信息\r\n zabbixitems_list = []\r\n for zabbixinfo_query in zabbixinfo_querys:\r\n zabbixitem_host_dict = {}\r\n zabbixitemid = zabbixinfo_query.zabbixitemid\r\n zabbixhostid = zabbixinfo_query.zabbixhostid\r\n zabbixhostip = zabbixinfo_query.zabbixhostip\r\n zabbixhostname = zabbixinfo_query.zabbixhostname\r\n zabbixitemid_query_list = eval(zabbixitemid)\r\n zabbixitem_host_dict['hostid'] = zabbixhostid\r\n #zabbixitem_host_dict['itemids'] = zabbixitemid_query_list\r\n zabbixitem_host_dict['host'] = zabbixhostip\r\n zabbixitem_host_dict['name'] = zabbixhostname\r\n zabbixitems_list.append(zabbixitem_host_dict)\r\n print(\"zabbixitems_list:\",zabbixitems_list)\r\n #查询zabbix监控\r\n result_temp = []\r\n for zabbixitems in zabbixitems_list:\r\n items_response_info_dict = {}\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"key_\", \"lastvalue\"],\r\n \"hostids\": zabbixitems['hostid'],\r\n # \"hostids\": ['10254', '10258'],\r\n },\r\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers_base)\r\n #items_response_info_dict['host'] = zabbixitems['host']\r\n items_response_info_dict['host'] = zabbixitems['name']\r\n items_response_info_dict[\"item\"] = demjson.decode(items_response.content)[\"result\"]\r\n result_temp.append(items_response_info_dict)\r\n\r\n #整理数据\r\n #print(result_temp)\r\n for host_value in result_temp:\r\n #获取所有主机的监控数据\r\n temp_raw = {\"host\": host_value[\"host\"]}\r\n i = 0\r\n temp_liebiao = []\r\n search_keys = (\"vfs.fs.size*pfree*\", \"net.if.in*ens*\", \"system.cpu.util*idle*\",\r\n \"vm.memory*\", \"net.if.in*Intel*Network Connection]\")\r\n for item in host_value[\"item\"]:\r\n #整理每个主机的数据\r\n item = dict(item)\r\n\r\n # if str(item[\"key_\"]).__contains__(\"net.if.in\"):\r\n # print(item[\"key_\"])\r\n\r\n for mykey in search_keys:\r\n #过滤需要的key\r\n #print(mykey, item[\"key_\"])\r\n temp_dict = dict()\r\n if fnmatch.fnmatch(item[\"key_\"], mykey):\r\n #print(mykey, item[\"key_\"])\r\n\r\n k = 0\r\n if item[\"key_\"].find(\"system.cpu.util\") != -1:\r\n temp_dict[\"key\"] = \"cpu\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"])\r\n temp_dict[\"total\"] = float(100)\r\n temp_liebiao.append(temp_dict)\r\n break\r\n elif fnmatch.fnmatch(item[\"key_\"], \"net.if.in*\"):\r\n \r\n temp_dict[\"key\"] = \"network\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"])/1024\r\n temp_dict[\"available\"] = float(100)-float(item[\"lastvalue\"]) / 1024\r\n temp_dict[\"total\"] = float(100)\r\n \r\n temp_liebiao.append(temp_dict)\r\n \r\n break\r\n elif item[\"key_\"].find(\"net.if.in[Intel(R) PRO/1000 MT Network Connection]\") != -1:\r\n temp_dict[\"key\"] = \"network\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"]) / 1024\r\n temp_dict[\"available\"] = float(100) - float(item[\"lastvalue\"]) / 1024\r\n temp_dict[\"total\"] = float(100)\r\n\r\n temp_liebiao.append(temp_dict)\r\n\r\n break\r\n elif item[\"key_\"].find(\"vm.memory.size[available]\") != -1:\r\n \r\n k = 1\r\n for j in temp_liebiao:\r\n if \"memory\" in j.values():\r\n \r\n network_value = dict()\r\n network_value.copy(j)\r\n temp_liebiao.remove(j)\r\n # 为已经存在的字典增加一个字段\r\n network_value[\"available\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n print(\"sfsfsfsdsdfsdfsdfsfsfsf*******************\")\r\n print(network_value[\"available\"])\r\n print(network_value[\"available\"])\r\n print(network_value[\"available\"])\r\n print(\"fsfsfsfsdfsfsfsfsfsfsfsf*******************\")\r\n # temp_liebiao[k][\"available\"] = float(item[\"lastvalue\"])/1024/1024/1024\r\n temp_liebiao.append(network_value)\r\n break\r\n\r\n if len(temp_liebiao) == k:\r\n # 否则新生成个字典\r\n temp_dict[\"key\"] = \"memory\"\r\n #temp_dict[\"available\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n print(\"12121212121212121211212*******************\")\r\n print(temp_dict[\"available\"])\r\n print(temp_dict[\"available\"])\r\n print(temp_dict[\"available\"])\r\n print(\"12121212121212121211212*******************\")\r\n temp_liebiao.append(temp_dict)\r\n break\r\n k += 1\r\n elif item[\"key_\"].find(\"vm.memory.size[free]\") != -1:\r\n k = 1\r\n for j in temp_liebiao:\r\n if \"memory\" in j.values():\r\n network_value = dict()\r\n network_value.copy(j)\r\n temp_liebiao.remove(j)\r\n # 为已经存在的字典增加一个字段\r\n network_value[\"available\"] = float(item[\"lastvalue\"])/1024/1024/1024\r\n #temp_liebiao[k][\"available\"] = float(item[\"lastvalue\"])/1024/1024/1024\r\n temp_liebiao.append(network_value)\r\n break\r\n\r\n if len(temp_liebiao) == k:\r\n #否则新生成个字典\r\n temp_dict[\"key\"] = \"memory\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"])/1024/1024/1024\r\n temp_liebiao.append(temp_dict)\r\n break\r\n k += 1\r\n\r\n #print(temp_dict)\r\n\r\n elif item[\"key_\"].find(\"vm.memory.size[total]\") != -1:\r\n k = 1\r\n #print(333)\r\n for j in temp_liebiao:\r\n if \"memory\" in j.values():\r\n network_value = j\r\n temp_liebiao.remove(j)\r\n network_value[\"total\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n temp_liebiao.append(network_value)\r\n break\r\n if len(temp_liebiao) == k:\r\n temp_dict[\"key\"] = \"memory\"\r\n temp_dict[\"total\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n temp_liebiao.append(temp_dict)\r\n break\r\n\r\n k += 1\r\n\r\n\r\n elif fnmatch.fnmatch(item[\"key_\"], \"vfs.fs.size*pfree]\"):\r\n temp_dict[\"key\"] = \"disk\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"])\r\n temp_dict[\"partition\"] = item[\"key_\"].split(\"[\")[1].split(\",\")[0]\r\n temp_dict[\"total\"] = float(100)\r\n temp_liebiao.append(temp_dict)\r\n break\r\n else:\r\n pass\r\n #temp_liebiao.append(temp_dict)\r\n\r\n i += 1\r\n temp_raw[\"item\"] = temp_liebiao\r\n\r\n\r\n # print(temp_raw)\r\n all_host_monitor_value.append(temp_raw)\r\n del temp_raw\r\n\r\n msg = \"successful\"\r\n\r\n except:\r\n\r\n msg = \"get zabbix monitor value error.\"\r\n logger.error(msg)\r\n logger.error(sys.exc_info()[0])\r\n status = -3\r\n finally:\r\n\r\n result = {\r\n \"result\": all_host_monitor_value,\r\n \"msg\": msg,\r\n \"status\": status\r\n }\r\n #print(demjson.encode(result))\r\n return result\r\n\"\"\"\r\n\r\ndef zabbix_get_complay_hosts(usertoken, companyid):\r\n all_host_monitor_value = []\r\n msg = \"\"\r\n status = 0\r\n\r\n #获取zabbix token\r\n headers_base = {\r\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\r\n 'Accept-Encoding': 'gzip, deflate, sdch',\r\n 'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2',\r\n 'Connection': 'keep-alive',\r\n 'User-Agent': 'Chrome/43.0.2357.130 Safari/10000',\r\n 'Content-Type': 'application/json-rpc',\r\n }\r\n\r\n try:\r\n user_companyid = companyid\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query.companyrole == '1':\r\n\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid, official='1').first()\r\n elif company_query.companyrole == '2':\r\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\r\n #zabbixinfo_query = Zabbix.query.filter_by(companyid=user_companyid).first()\r\n zabbixusername = zabbixinfo_query.zabbixuser\r\n zabbixpassword = zabbixinfo_query.zabbixpassword\r\n zabbixurl = zabbixinfo_query.zabbixserver\r\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\r\n except:\r\n\r\n msg = \"未找到与公司匹配的zabbix服务器信息,请联系系统管理员!\"\r\n logger.error(msg, companyid)\r\n logger.error(sys.exc_info()[0])\r\n status = -2\r\n result = {\r\n \"result\": all_host_monitor_value,\r\n \"msg\": msg,\r\n \"status\": status\r\n }\r\n return result\r\n\r\n #获取所属公司所有的监控信息\r\n try:\r\n company_query = Company.query.filter_by(companyid=companyid).first()\r\n if company_query.companyrole == '1':\r\n zabbixinfo_querys = Monitor.query.filter_by(companyid=\"terperantcompnayid\").all()\r\n elif company_query.companyrole == '2':\r\n zabbixinfo_querys = Monitor.query.filter_by(companyid=user_companyid, supervisor=True).all()\r\n #zabbixinfo_querys = Monitor.query.filter_by(companyid=user_companyid,supervisor=True).all() \r\n print(len(zabbixinfo_querys))\r\n #获取所属公司的zabbix服务器信息\r\n zabbixitems_list = []\r\n for zabbixinfo_query in zabbixinfo_querys:\r\n zabbixitem_host_dict = {}\r\n zabbixitemid = zabbixinfo_query.zabbixitemid\r\n zabbixhostid = zabbixinfo_query.zabbixhostid\r\n zabbixhostip = zabbixinfo_query.zabbixhostip\r\n zabbixhostname = zabbixinfo_query.zabbixhostname\r\n zabbixitemid_query_list = eval(zabbixitemid)\r\n zabbixitem_host_dict['hostid'] = zabbixhostid\r\n #zabbixitem_host_dict['itemids'] = zabbixitemid_query_list\r\n zabbixitem_host_dict['host'] = zabbixhostip\r\n zabbixitem_host_dict['name'] = zabbixhostname\r\n zabbixitems_list.append(zabbixitem_host_dict)\r\n print(\"zabbixitems_list:\",zabbixitems_list)\r\n #查询zabbix监控\r\n result_temp = []\r\n for zabbixitems in zabbixitems_list:\r\n items_response_info_dict = {}\r\n data = json.dumps(\r\n {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": \"item.get\",\r\n \"params\": {\r\n \"output\": [\"key_\", \"lastvalue\"],\r\n \"hostids\": zabbixitems['hostid'],\r\n # \"hostids\": ['10254', '10258'],\r\n },\r\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\r\n \"id\": 1,\r\n })\r\n items_response = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers_base)\r\n #items_response_info_dict['host'] = zabbixitems['host']\r\n items_response_info_dict['host'] = zabbixitems['name']\r\n items_response_info_dict[\"item\"] = demjson.decode(items_response.content)[\"result\"]\r\n result_temp.append(items_response_info_dict)\r\n\r\n #整理数据\r\n #print(result_temp)\r\n for host_value in result_temp:\r\n #获取所有主机的监控数据\r\n temp_raw = {\"host\": host_value[\"host\"]}\r\n i = 0\r\n temp_liebiao = []\r\n search_keys = (\"vfs.fs.size*pfree*\", \"net.if.in*ens*\", \"system.cpu.util*idle*\",\r\n \"vm.memory*\", \"net.if.in*Intel*Network Connection]\")\r\n for item in host_value[\"item\"]:\r\n #整理每个主机的数据\r\n item = dict(item)\r\n\r\n # if str(item[\"key_\"]).__contains__(\"net.if.in\"):\r\n # print(item[\"key_\"])\r\n\r\n for mykey in search_keys:\r\n #过滤需要的key\r\n #print(mykey, item[\"key_\"])\r\n temp_dict = dict()\r\n if fnmatch.fnmatch(item[\"key_\"], mykey):\r\n #print(mykey, item[\"key_\"])\r\n\r\n k = 0\r\n if item[\"key_\"].find(\"system.cpu.util\") != -1:\r\n temp_dict[\"key\"] = \"cpu\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"])\r\n temp_dict[\"total\"] = float(100)\r\n temp_liebiao.append(temp_dict)\r\n break\r\n elif fnmatch.fnmatch(item[\"key_\"], \"net.if.in*\"):\r\n \r\n temp_dict[\"key\"] = \"network\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"])/1024\r\n temp_dict[\"available\"] = float(100)-float(item[\"lastvalue\"]) / 1024\r\n temp_dict[\"total\"] = float(100)\r\n \r\n temp_liebiao.append(temp_dict)\r\n \r\n break\r\n elif item[\"key_\"].find(\"net.if.in[Intel(R) PRO/1000 MT Network Connection]\") != -1:\r\n temp_dict[\"key\"] = \"network\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"]) / 1024\r\n temp_dict[\"available\"] = float(100) - float(item[\"lastvalue\"]) / 1024\r\n temp_dict[\"total\"] = float(100)\r\n\r\n temp_liebiao.append(temp_dict)\r\n\r\n break\r\n elif item[\"key_\"].find(\"vm.memory.size[available]\") != -1:\r\n \r\n k = 1\r\n for j in temp_liebiao:\r\n if \"memory\" in j.values():\r\n \r\n network_value = dict()\r\n network_value.copy(j)\r\n temp_liebiao.remove(j)\r\n # 为已经存在的字典增加一个字段\r\n network_value[\"available\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n print(\"sfsfsfsdsdfsdfsdfsfsfsf*******************\")\r\n print(network_value[\"available\"])\r\n print(network_value[\"available\"])\r\n print(network_value[\"available\"])\r\n print(\"fsfsfsfsdfsfsfsfsfsfsfsf*******************\")\r\n # temp_liebiao[k][\"available\"] = float(item[\"lastvalue\"])/1024/1024/1024\r\n temp_liebiao.append(network_value)\r\n break\r\n\r\n if len(temp_liebiao) == k:\r\n # 否则新生成个字典\r\n temp_dict[\"key\"] = \"memory\"\r\n #temp_dict[\"available\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n print(\"12121212121212121211212*******************\")\r\n print(temp_dict[\"available\"])\r\n print(temp_dict[\"available\"])\r\n print(temp_dict[\"available\"])\r\n print(\"12121212121212121211212*******************\")\r\n temp_liebiao.append(temp_dict)\r\n break\r\n k += 1\r\n elif item[\"key_\"].find(\"vm.memory.size[free]\") != -1:\r\n k = 1\r\n for j in temp_liebiao:\r\n if \"memory\" in j.values():\r\n network_value = dict()\r\n network_value.copy(j)\r\n temp_liebiao.remove(j)\r\n # 为已经存在的字典增加一个字段\r\n network_value[\"available\"] = float(item[\"lastvalue\"])/1024/1024/1024\r\n #temp_liebiao[k][\"available\"] = float(item[\"lastvalue\"])/1024/1024/1024\r\n temp_liebiao.append(network_value)\r\n break\r\n\r\n if len(temp_liebiao) == k:\r\n #否则新生成个字典\r\n temp_dict[\"key\"] = \"memory\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"])/1024/1024/1024\r\n temp_liebiao.append(temp_dict)\r\n break\r\n k += 1\r\n\r\n #print(temp_dict)\r\n\r\n elif item[\"key_\"].find(\"vm.memory.size[total]\") != -1:\r\n k = 1\r\n #print(333)\r\n for j in temp_liebiao:\r\n if \"memory\" in j.values():\r\n network_value = j\r\n temp_liebiao.remove(j)\r\n network_value[\"total\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n temp_liebiao.append(network_value)\r\n break\r\n if len(temp_liebiao) == k:\r\n temp_dict[\"key\"] = \"memory\"\r\n temp_dict[\"total\"] = float(item[\"lastvalue\"]) / 1024 / 1024 / 1024\r\n temp_liebiao.append(temp_dict)\r\n break\r\n\r\n k += 1\r\n\r\n\r\n elif fnmatch.fnmatch(item[\"key_\"], \"vfs.fs.size*pfree]\"):\r\n temp_dict[\"key\"] = \"disk\"\r\n temp_dict[\"available\"] = float(item[\"lastvalue\"])\r\n temp_dict[\"partition\"] = item[\"key_\"].split(\"[\")[1].split(\",\")[0]\r\n temp_dict[\"total\"] = float(100)\r\n temp_liebiao.append(temp_dict)\r\n break\r\n else:\r\n pass\r\n #temp_liebiao.append(temp_dict)\r\n\r\n i += 1\r\n temp_raw[\"item\"] = temp_liebiao\r\n\r\n\r\n # print(temp_raw)\r\n all_host_monitor_value.append(temp_raw)\r\n del temp_raw\r\n\r\n msg = \"successful\"\r\n\r\n except:\r\n\r\n msg = \"get zabbix monitor value error.\"\r\n logger.error(msg)\r\n logger.error(sys.exc_info()[0])\r\n status = -3\r\n finally:\r\n\r\n result = {\r\n \"result\": all_host_monitor_value,\r\n \"msg\": msg,\r\n \"status\": status\r\n }\r\n #print(demjson.encode(result))\r\n return result\r\n" }, { "alpha_fraction": 0.5905464291572571, "alphanum_fraction": 0.5962870717048645, "avg_line_length": 45.21133041381836, "blob_id": "c3410202a7f3fbb5761ee098b53a0e6871e6b671", "content_id": "bced8c7b619bda01ac2cc263d8b3ba479e33d3bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 52508, "license_type": "no_license", "max_line_length": 254, "num_lines": 1112, "path": "/houtaiapi/company.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from model import *\nfrom datetime import datetime, timedelta\nimport time\nimport requests, json\nfrom urllib.parse import unquote\nimport math\nimport string\nimport re\nimport random\nimport sqlalchemy\nurl = apiserverurl + \"/api/v1/hosts?token=xxx-11111\"\n\n\n\nheaders = {'Content-Type': 'application/json-rpc'}\n\ndef auth(zabbixusername, zabbixpassword, zabbixurl):\n\n data = json.dumps(\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"user.login\",\n \"params\": {\n \"user\": zabbixusername,\n \"password\": zabbixpassword\n },\n \"id\": 0\n })\n\n authrs = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\n token = authrs.json()['result']\n return token\n\n\ndef hostgroups(zabbixtoken, zabbixurl):\n data = json.dumps(\n {\n \"jsonrpc\":\"2.0\",\n \"method\":\"hostgroup.get\",\n \"params\":{\n \"output\":[\"groupid\",\"name\"],\n },\n \"auth\":zabbixtoken, # theauth id is what auth script returns, remeber it is string\n \"id\":1,\n })\n hostgroups = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\n group_list = hostgroups.json()['result']\n return group_list\n\ndef zabbix_hosts_query(companyid):\n company_query = Company.query.filter_by(companyid=companyid).first()\n companyrole = company_query.companyrole\n if companyrole == '1':\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid,official='1').first()\n elif companyrole == '2':\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\n #zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid).first()\n if zabbixinfo_query is None:\n db.session.close()\n return {'status': 2, 'msg': '使用监控功能之前,需要先添加zabbix服务器'}\n zabbixusername = zabbixinfo_query.zabbixuser\n zabbixpassword = zabbixinfo_query.zabbixpassword\n zabbixurl = zabbixinfo_query.zabbixserver\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\n\n group_list = hostgroups(zabbixtoken, zabbixurl)\n print(group_list)\n hostinfo_list = []\n for group in group_list:\n #hostinfo_dict = {}\n hostinfo_list.append(group['groupid'])\n #groupid = group['groupid']\n #groupname = group['name']\n print(hostinfo_list)\n data = json.dumps(\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"host.get\",\n \"params\": {\n \"output\": [\"hostid\", \"name\", \"host\"],\n \"groupids\": hostinfo_list,\n },\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\n \"id\": 1,\n })\n hosts = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\n \n \n hosts_list = hosts.json()['result']\n checkhosts_list = []\n for checkhost_dict in hosts_list:\n\n checkhostid = checkhost_dict['hostid']\n checkhost_query = Monitor.query.filter_by(zabbixhostid=checkhostid).first()\n if checkhost_query:\n checkhost_dict['hoststatus'] = 'in'\n else:\n checkhost_dict['hoststatus'] = 'out'\n checkhosts_list.append(checkhost_dict)\n\n allhostsnumber = len(checkhosts_list)\n inhostsnumber_query = Monitor.query.all()\n inhostsnumber = len(inhostsnumber_query)\n inhostinfo_list = []\n for inhost in inhostsnumber_query:\n inhostinfo_dict = {'hostid':inhost.zabbixhostid, 'host':inhost.zabbixhostip, 'name':inhost.zabbixhostname, 'hoststatus':'in'}\n inhostinfo_list.append(inhostinfo_dict)\n\n hosts_queryrs = {'status': 0, 'totalamount': allhostsnumber,\n 'inamount':inhostsnumber, 'totalhosts': checkhosts_list,\n 'inhosts':inhostinfo_list,\n }\n db.session.close()\n return hosts_queryrs\n\ndef backstagecms(userid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #公司总数量\n rs_query_list = []\n page = int(page)\n\n companys_total_query = Company.query.all()\n companys_total = len(companys_total_query) / 15\n page_total = math.ceil(companys_total)\n\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n backstage_expiredate_query = Backstage.query.first()\n backstage_expiredate = backstage_expiredate_query.companyexpire\n expire_date = todays_datetime + timedelta(days=int(backstage_expiredate))\n companys_query_page = Company.query.order_by(Company.createtime.desc()).paginate(page, per_page=15, error_out=False)\n companys_query = companys_query_page.items\n for company_query in companys_query:\n companyid = company_query.companyid\n zabbixhostinfo = zabbix_hosts_query(companyid)\n if zabbixhostinfo['status'] != 2:\n totalhost = len(zabbixhostinfo['totalhosts'])\n else:\n totalhost = None\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n user_query = Opuser.query.filter(Opuser.opcompanyid==companyid, Opuser.oprole!=2).all()\n totalcompanyusers = int(len(user_query)) - 1\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n if companyrole == '1':\n zabbix_query = Zabbix.query.filter_by(companyid=companyid,official='1').first()\n elif companyrole == '2':\n zabbix_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\n #zabbix_query = Zabbix.query.filter_by(companyid=companyid).first()\n zabbix_exist = \"false\"\n if zabbix_query:\n zabbixid = zabbix_query.zabbixid\n zabbixserver = zabbix_query.zabbixserver\n zabbixuser = zabbix_query.zabbixuser\n zabbixpassword = zabbix_query.zabbixpassword\n zabbix_exist = \"true\"\n else:\n zabbixid = None\n zabbixserver = None\n zabbixuser = None\n zabbixpassword = None\n zabbix_exist = \"true\"\n adminusername = adminuser_query.opusername\n defaultcompany = adminuser_query.default\n adminmobile = adminuser_query.opmobile\n companyemail = company_query.companyemail\n companymark = company_query.companymark\n expirestring = \"\"\n if companyexpire:\n if companyexpire <= expire_date and companyexpire >= todays_datetime and disable == False:\n expirestring = \"即将到期\"\n elif companyexpire <= expire_date and companyexpire >= todays_datetime and disable == False:\n expirestring = \"即将到期\"\n elif companyexpire <= todays_datetime and disable== False:\n expirestring = \"试用中\"\n elif disable == True:\n expirestring = \"停用中\"\n elif companyexpire > expire_date and disable == False:\n expirestring = \"正常使用中\"\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n elif disable == 0 and companyexpire is None:\n expirestring = \"试用中\"\n elif disable == 1 and companyexpire is None:\n expirestring = \"停用中\"\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':companyemail,\"zabbixid\":zabbixid,\"zabbixserver\":zabbixserver,\"zabbixuser\":zabbixuser,\"zabbixpassword\":zabbixpassword,\n 'companyexpire': companyexpire,'totalhost':totalhost,\"zabbix_exist\":zabbix_exist,\"disable\":disable,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n 'companymark':companymark,'defaultcompany':defaultcompany,\"expirestring\":expirestring\n }\n rs_query_list.append(rs_query_dict)\n db.session.close()\n return {\"status\":0,\"msg\":\"查询成功\",'pagetotal':page_total,\"companyinfo\": rs_query_list}\n\n\ndef backstagecm(userid, token, urlsearchcompanyname, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n searchcompanyname = unquote(urlsearchcompanyname, 'utf-8')\n #公司总数量\n rs_query_list = []\n #companys_query = Company.query.all()\n page = int(page)\n\n companys_query = Company.query.filter(Company.companyname.like('%' + urlsearchcompanyname + '%')).order_by(Company.createtime.desc()).paginate(page, per_page=15, error_out=False)\n\n companys_page_query = companys_query.items\n companys_total = len(companys_page_query) / 15\n page_total = math.ceil(companys_total)\n\n for company_query in companys_page_query:\n companyid = company_query.companyid\n #zabbixhostinfo = zabbix_hosts_query(companyid)\n #if zabbixhostinfo['status'] != 2:\n # totalhost = len(zabbixhostinfo['totalhosts'])\n #else:\n # totalhost = None\n zabbixhosts = Monitor.query.filter_by(companyid=companyid).all()\n if zabbixhosts:\n totalhost = len(zabbixhosts)\n else:\n totalhost = None\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n if companyrole == '1':\n zabbix_query = Zabbix.query.filter_by(companyid=companyid,official='1').first()\n elif companyrole == '2':\n zabbix_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\n #zabbix_query = Zabbix.query.filter_by(companyid=companyid).first()\n zabbix_exist = \"false\"\n if zabbix_query:\n zabbixid = zabbix_query.zabbixid\n zabbixserver = zabbix_query.zabbixserver\n zabbixuser = zabbix_query.zabbixuser\n zabbixpassword = zabbix_query.zabbixpassword\n zabbix_exist = \"true\"\n else:\n zabbixid = None\n zabbixserver = None\n zabbixuser = None\n zabbixpassword = None\n zabbix_exist = \"false\"\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n defaultcompany = adminuser_query.default\n admimemail = company_query.companyemail\n companymark = company_query.companymark\n\n if companyexpire:\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\"zabbixid\":zabbixid,\"zabbixserver\":zabbixserver,\"zabbixuser\":zabbixuser,\"zabbixpassword\":zabbixpassword,\n 'companyexpire': companyexpire,'totalhost':totalhost,\"zabbix_exist\":zabbix_exist,\"disable\":disable,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n 'companymark': companymark,'defaultcompany':defaultcompany\n }\n rs_query_list.append(rs_query_dict)\n db.session.close()\n return {\"status\": 0, \"msg\":\"查询成功\", 'pagetotal':page_total,\"companyinfo\": rs_query_list}\n\n\n#这个接口是我新添的,没有暴露出来\ndef backstagecm1(userid, token, searchcompanyid, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #公司总数量\n rs_query_list = []\n #companys_query = Company.query.all()\n page = int(page)\n\n companys_query = Company.query.filter(companyid=searchcompanyid).order_by(Company.createtime.desc()).paginate(page, per_page=15, error_out=False)\n\n companys_page_query = companys_query.items\n\n\n companys_total = len(companys_page_query) / 15\n page_total = math.ceil(companys_total)\n\n for company_query in companys_page_query:\n companyid = company_query.companyid\n zabbixhostinfo = zabbix_hosts_query(companyid)\n if zabbixhostinfo['status'] != 2:\n totalhost = len(zabbixhostinfo['totalhosts'])\n else:\n totalhost = None\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n if companyrole == '1':\n zabbix_query = Zabbix.query.filter_by(companyid=companyid,official='1').first()\n elif companyrole == '2':\n zabbix_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\n #zabbix_query = Zabbix.query.filter_by(companyid=companyid).first()\n zabbix_exist = \"false\"\n if zabbix_query:\n zabbixid = zabbix_query.zabbixid\n zabbixserver = zabbix_query.zabbixserver\n zabbixuser = zabbix_query.zabbixuser\n zabbixpassword = zabbix_query.zabbixpassword\n zabbix_exist = \"true\"\n else:\n zabbixid = None\n zabbixserver = None\n zabbixuser = None\n zabbixpassword = None\n zabbix_exist = \"false\"\n adminusername = adminuser_query.opusername\n adminuserid = adminuser_query.opuserid\n adminmobile = adminuser_query.opmobile\n defaultcompany = adminuser_query.default\n admimemail = company_query.companyemail\n companymark = company_query.companymark\n\n if companyexpire:\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,'adminuserid':adminuserid,\n 'adminmobile': adminmobile,'adminemail':admimemail,\"zabbixid\":zabbixid,\"zabbixserver\":zabbixserver,\"zabbixuser\":zabbixuser,\"zabbixpassword\":zabbixpassword,\n 'companyexpire': companyexpire,'totalhost':totalhost,\"zabbix_exist\":zabbix_exist,\"disable\":disable,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n 'companymark': companymark,'defaultcompany':defaultcompany\n }\n rs_query_list.append(rs_query_dict)\n db.session.close()\n return {\"status\": 0, \"msg\":\"查询成功\", 'pagetotal':page_total,\"companyinfo\": rs_query_list}\n\n\ndef backstagetryouts(userid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n #试用公司\n rs_query_list = []\n page = int(page)\n companys_query = Company.query.filter_by(companyexpiredate=None).order_by(Company.createtime.desc()).paginate(page, per_page=15, error_out=False)\n companys_page_query = companys_query.items\n\n companys_total = len(companys_page_query) / 15\n page_total = math.ceil(companys_total)\n\n print(companys_page_query)\n\n #companys_query = Company.query.filter_by(companyrole='1').all()\n for company_query in companys_page_query:\n companyid = company_query.companyid\n zabbixhostinfo = zabbix_hosts_query(companyid)\n if zabbixhostinfo['status'] != 2:\n totalhost = len(zabbixhostinfo['totalhosts'])\n else:\n totalhost = None\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n # user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n # totalcompanyusers = len(user_query)\n user_query = Opuser.query.filter(Opuser.opcompanyid==companyid, Opuser.oprole!=2).all()\n totalcompanyusers = int(len(user_query)) - 1\n if companyrole == '1':\n zabbix_query = Zabbix.query.filter_by(companyid=companyid,official='1').first()\n elif companyrole == '2':\n zabbix_query = Zabbix.query.filter_by(companyid=companyid, official='2').first()\n #zabbix_query = Zabbix.query.filter_by(companyid=companyid).first()\n zabbix_exist = \"false\"\n if zabbix_query:\n zabbixid = zabbix_query.zabbixid\n zabbixserver = zabbix_query.zabbixserver\n zabbixuser = zabbix_query.zabbixuser\n zabbixpassword = zabbix_query.zabbixpassword\n zabbix_exist = \"true\"\n else:\n zabbixid = None\n zabbixserver = None\n zabbixuser = None\n zabbixpassword = None\n zabbix_exist = \"false\"\n\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = company_query.companyemail\n defaultcompany = adminuser_query.default\n companymark = company_query.companymark\n \n if companyexpire:\n if companyexpire <= todays_datetime:\n expirestring = \"试用公司\"\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n else:\n expirestring = \"试用中\"\n if disable == True:\n expirestring = \"停用中\"\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\"zabbixid\":zabbixid,\"zabbixserver\":zabbixserver,\"zabbixuser\":zabbixuser,\"zabbixpassword\":zabbixpassword,\n 'companyexpire': companyexpire,'totalhost':totalhost,\"zabbix_exist\":zabbix_exist,\"disable\":disable,\n 'companyrole':companyrole, 'members':totalcompanyusers,\"expirestring\":expirestring,\n 'companymark': companymark,'defaultcompany':defaultcompany\n }\n rs_query_list.append(rs_query_dict)\n db.session.close()\n return {\"status\": 0, \"msg\":\"查询成功\", 'pagetotal':page_total,\"companyinfo\": rs_query_list}\n\ndef backstageexpiring(userid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #即将过期\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n backstage_expiredate_query = Backstage.query.first()\n backstage_expiredate = backstage_expiredate_query.companyexpire\n expire_date = todays_datetime + timedelta(days=int(backstage_expiredate))\n page = int(page)\n\n try_expire_companys_query_page = Company.query.filter(Company.companyexpiredate <= expire_date, Company.companyexpiredate >= todays_datetime, Company.companyrole == '2').order_by(Company.createtime.desc()).paginate(page, per_page=15, error_out=False)\n try_expire_companys_query = try_expire_companys_query_page.items\n companys_total = len(try_expire_companys_query) / 15\n page_total = math.ceil(companys_total)\n\n\n if try_expire_companys_query is None:\n db.session.close()\n return {\"status\": 0, \"msg\":\"查询成功\", \"companyinfo\": []}\n rs_query_list = []\n for company_query in try_expire_companys_query:\n companyid = company_query.companyid\n zabbixhostinfo = zabbix_hosts_query(companyid)\n if zabbixhostinfo['status'] != 2:\n totalhost = len(zabbixhostinfo['totalhosts'])\n else:\n totalhost = None\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n #user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n #totalcompanyusers = len(user_query)\n user_query = Opuser.query.filter(Opuser.opcompanyid==companyid, Opuser.oprole!=2).all()\n totalcompanyusers = int(len(user_query)) - 1\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = company_query.companyemail\n defaultcompany = adminuser_query.default\n companymark = company_query.companymark\n\n if companyexpire:\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\"disable\":disable,\n 'companyexpire': companyexpire,'totalhost':totalhost,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n 'companymark': companymark,'defaultcompany':defaultcompany\n }\n rs_query_list.append(rs_query_dict)\n db.session.close()\n return {\"status\": 0, \"msg\":\"查询成功\",'pagetotal':page_total, \"companyinfo\": rs_query_list}\n\n\ndef backstageexpired(userid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #已过期\n page = int(page)\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n try_expire_companys_query_page = Company.query.filter(Company.companyexpiredate <= todays_datetime, Company.companyrole == '2').order_by(Company.createtime.desc()).paginate(page, per_page=15, error_out=False)\n try_expire_companys_query = try_expire_companys_query_page.items\n companys_total = len(try_expire_companys_query) / 15\n page_total = math.ceil(companys_total)\n\n if try_expire_companys_query is None:\n db.session.close()\n return {\"status\": 0, \"msg\": \"查询成功\", \"companyinfo\": []}\n rs_query_list = []\n for company_query in try_expire_companys_query:\n companyid = company_query.companyid\n zabbixhostinfo = zabbix_hosts_query(companyid)\n if zabbixhostinfo['status'] != 2:\n totalhost = len(zabbixhostinfo['totalhosts'])\n else:\n totalhost = None\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n #user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n #totalcompanyusers = len(user_quer\n user_query = Opuser.query.filter(Opuser.opcompanyid==companyid, Opuser.oprole!=2).all()\n totalcompanyusers = int(len(user_query)) - 1\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n defaultcompany = adminuser_query.default\n admimemail = company_query.companyemail\n companymark = company_query.companymark\n\n if companyexpire:\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\"disable\":disable,\n 'companyexpire': companyexpire,'totalhost':totalhost,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n 'companymark': companymark,'defaultcompany':defaultcompany\n }\n rs_query_list.append(rs_query_dict)\n db.session.close()\n return {\"status\": 0, \"msg\": \"查询成功\",'pagetotal':page_total, \"companyinfo\": rs_query_list}\n\ndef backstagenewcompanytoday(userid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #即将过期\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n print(todays_datetime)\n page = int(page)\n\n try_expire_companys_query_page = Company.query.filter(Company.createtime >= todays_datetime).order_by(Company.createtime.desc()).paginate(page, per_page=15, error_out=False)\n try_expire_companys_query = try_expire_companys_query_page.items\n companys_total = len(try_expire_companys_query) / 15\n page_total = math.ceil(companys_total)\n\n if try_expire_companys_query is None:\n db.session.close()\n return {\"status\": 0, \"msg\":\"查询成功\", \"companyinfo\": []}\n rs_query_list = []\n for company_query in try_expire_companys_query:\n companyid = company_query.companyid\n zabbixhostinfo = zabbix_hosts_query(companyid)\n if zabbixhostinfo['status'] != 2:\n totalhost = len(zabbixhostinfo['totalhosts'])\n else:\n totalhost = None\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n companyemail = company_query.companyemail\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = company_query.companyemail\n defaultcompany = adminuser_query.default\n companymark = company_query.companymark\n expirestring = \"\"\n if companyexpire:\n if companyexpire <= expire_date and companyexpire >= todays_datetime and disable == False:\n expirestring = \"即将到期\"\n elif companyexpire <= expire_date and companyexpire >= todays_datetime and disable == False:\n expirestring = \"即将到期\"\n elif companyexpire <= todays_datetime and disable== False:\n expirestring = \"试用中\"\n elif disable == True:\n expirestring = \"停用中\"\n elif companyexpire > expire_date and disable == False:\n expirestring = \"正常使用中\"\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n elif disable == 0 and companyexpire is None:\n expirestring = \"试用中\"\n elif disable == 1 and companyexpire is None:\n expirestring = \"停用中\"\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\"companyemail\":companyemail,\n 'companyexpire': companyexpire,'totalhost':totalhost,\"expirestring\":expirestring,\"disable\":disable,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n 'companymark': companymark,'defaultcompany':defaultcompany\n }\n rs_query_list.append(rs_query_dict)\n db.session.close()\n return {\"status\": 0, \"msg\":\"查询成功\", 'pagetotal':page_total,\"companyinfo\": rs_query_list}\n\ndef companymemberinfo(adminuserid, token, page, searchcompanyname):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n page = int(page)\n search_companyid_list = []\n companys_query_page = Company.query.filter(Company.companyname.like('%' + searchcompanyname + '%')).order_by(\n Company.createtime.desc()).paginate(page, per_page=20, error_out=False)\n companys_query = companys_query_page.items\n companys_total = len(companys_query) / 15\n page_total = math.ceil(companys_total)\n\n for company_query in companys_query:\n search_company_dict = {}\n search_company_dict['companyid'] = company_query.companyid\n search_company_dict['companyname'] = company_query.companyname\n\n search_companyid_list.append(search_company_dict)\n\n search_opuserid_list = []\n for searchcompanyidinfo in search_companyid_list:\n\n opusers_query = Opuser.query.filter_by(opcompanyid=searchcompanyidinfo['companyid']).all()\n for opuser_query in opusers_query:\n searchopuserid = opuser_query.opuserid\n searchopuserrole = opuser_query.oprole\n userstatus = opuser_query.userstatus\n if searchopuserrole != '5' and searchopuserrole != '2' and searchopuserid:\n searchopuser_dict = {\n \"companyname\": searchcompanyidinfo['companyname'],\n \"userallinfo\": {\n \"userid\": searchopuserid,\n \"oprole\": searchopuserrole,\n \"userstatus\": userstatus,\n }\n }\n search_opuserid_list.append(searchopuser_dict)\n lastuserinfo_list = []\n print(search_opuserid_list)\n for useridinfo in search_opuserid_list:\n\n queryuserid = useridinfo['userallinfo']['userid']\n userinfo_query = User.query.filter_by(userid=queryuserid).first()\n if userinfo_query:\n username = userinfo_query.username\n usermobile = userinfo_query.mobile\n userlogintime = userinfo_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n userrole = userinfo_query.role\n useridinfo['userallinfo']['username'] = username\n useridinfo['userallinfo']['mobile'] = usermobile\n useridinfo['userallinfo']['logintime'] = userlogintime\n useridinfo['userallinfo']['role'] = userrole\n\n lastuserinfo_list.append(useridinfo)\n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\", 'pagetotal':page_total,\"userinfo\": lastuserinfo_list}\n\ndef companyhostsinfo(adminuserid, token, page, companyname):\n if token != '11111':\n return {'status': 1, 'msg': 'token不可用'}\n else:\n companyid_query = Company.query.filter_by(companyname=companyname).first()\n\n if companyid_query is None:\n db.session.close()\n return {'status': 2, 'msg': '未找到相关公司'}\n companyid = companyid_query.companyid\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid).first()\n if zabbixinfo_query is None:\n db.session.close()\n return {'status': 3, 'msg': '使用监控功能之前,需要先添加zabbix服务器'}\n zabbixusername = zabbixinfo_query.zabbixuser\n zabbixpassword = zabbixinfo_query.zabbixpassword\n zabbixurl = zabbixinfo_query.zabbixserver\n zabbixtoken = auth(zabbixusername, zabbixpassword, zabbixurl)\n\n group_list = hostgroups(zabbixtoken, zabbixurl)\n print(group_list)\n hostinfo_list = []\n for group in group_list:\n # hostinfo_dict = {}\n hostinfo_list.append(group['groupid'])\n # groupid = group['groupid']\n # groupname = group['name']\n print(hostinfo_list)\n data = json.dumps(\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"host.get\",\n \"params\": {\n \"output\": [\"hostid\", \"name\", \"host\"],\n \"groupids\": hostinfo_list,\n },\n \"auth\": zabbixtoken, # theauth id is what auth script returns, remeber it is string\n \"id\": 1,\n })\n hosts = requests.post(zabbixurl + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\n hosts_list = hosts.json()['result']\n checkhosts_list = []\n for checkhost_dict in hosts_list:\n\n #checkhostid = checkhost_dict['hostid']\n checkhost = checkhost_dict['host']\n checkhost_query = Monitor.query.filter_by(zabbixhostip=checkhost).first()\n if checkhost_query:\n checkhost_dict['hoststatus'] = 'in'\n else:\n checkhost_dict['hoststatus'] = 'out'\n checkhosts_list.append(checkhost_dict)\n\n allhostsnumber = len(checkhosts_list)\n pagetotal = len(checkhosts_list)/5\n if pagetotal == 0:\n pagetotal = 1\n inhostsnumber_query = Monitor.query.all()\n inhostsnumber = len(inhostsnumber_query)\n inhostinfo_list = []\n for inhost in inhostsnumber_query:\n inhostinfo_dict = {'hostid': inhost.zabbixhostid, 'host': inhost.zabbixhostip,\n 'name': inhost.zabbixhostname, 'hoststatus': 'in'}\n inhostinfo_list.append(inhostinfo_dict)\n\n hosts_queryrs = {'status': 0, 'totalamount': allhostsnumber,\n 'inamount': inhostsnumber, 'totalhosts': checkhosts_list,\"pagetotal\":pagetotal,\n }\n db.session.close()\n return hosts_queryrs\n\n\ndef companyexpire(adminuserid, token, companyname, time_chuo):\n if token != '11111':\n return {'status': 1, 'msg': 'token不可用'}\n else:\n companyid_query = Company.query.filter_by(companyname=companyname).first()\n\n if companyid_query is None:\n db.session.close()\n return {'status': 2, 'msg': '未找到相关公司'}\n else:\n time_chuo_zhuan = int(time_chuo) / 1000\n userinfologintime = time.localtime(time_chuo_zhuan)\n userinfologintime_dt = time.strftime(\"%Y-%m-%d %H:%M:%S\", userinfologintime)\n companyid_query.companyexpiredate = userinfologintime_dt\n companyid_query.companyrole = 2\n db.session.commit()\n db.session.close()\n return {'status': 0, 'msg': '修改成功'}\n\ndef companypatch(userid, usertoken,oldcompanyname, newcompanyname,companyemail, mark, disable):\n if usertoken != '11111':\n return {'status': 1, 'msg': 'token不可用'}\n else:\n companyid_query = Company.query.filter_by(companyname=oldcompanyname).first()\n\n if companyid_query is None:\n db.session.close()\n return {'status': 2, 'msg': '未找到相关公司'}\n else:\n companyid_query.companyname = newcompanyname\n companyid_query.companyemail = companyemail\n #if len(companyemail) == 0:\n if companyemail is None:\n return {'status': 4, 'msg': '邮箱输入为空,请重新输入!!!'}\n elif re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\\.[com,cn,net]{1,3}$', companyemail) is None:\n return {'status': 3, 'msg': '您输入的邮箱地址无效,请重新输入!!!'}\n companyid_query.companymark = mark\n #companyid_query.companyrole = 2\n companyid_query.disable = disable\n #这个地方注意一下\n \"\"\"\n opusers_query = Opuser.query.filter_by(opcompanyid=companyid_query.companyid).all()\n for opuser in opusers_query:\n user_query = User.query.filter_by(userid=opuser.opuserid)\n if disable == 0:\n user_query.role = '0'\n elif disable == 1:\n user_query.role = '1'\n \"\"\"\n opusers_query = Opuser.query.filter_by(opcompanyid=companyid_query.companyid).all()\n for opuser in opusers_query:\n opuserid = opuser.opuserid\n companys = Opuser.query.filter(opuserid==opuserid,disable==0,Opuser.opcompanyid!=companyid_query.companyid).all() \n\n if companys:\n user_query = User.query.filter_by(userid=opuser.opuserid)\n if disable == 0:\n user_query.role = '0'\n elif disable == 1:\n user_query.role = '0'\n else:\n user_query = User.query.filter_by(userid=opuser.opuserid)\n if disable == 0:\n user_query.role = '0'\n elif disable == 1:\n user_query.role = '1'\n if disable == 0:\n opusers_query = Opuser.query.filter_by(opcompanyid=companyid_query.companyid).all()\n for opuser in opusers_query:\n user_query = User.query.filter_by(userid=opuser.opuserid).first()\n user_query.role = '0'\n db.session.commit()\n db.session.close()\n expirestring = \"\"\n\n if newcompanyname != None and newcompanyname !=\"\":\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n backstage_expiredate_query = Backstage.query.first()\n backstage_expiredate = backstage_expiredate_query.companyexpire\n expire_date = todays_datetime + timedelta(days=int(backstage_expiredate))\n company_query = Company.query.filter_by(companyname=newcompanyname).first()\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n companyemail = company_query.companyemail\n companyid = company_query.companyid\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = company_query.companyemail\n defaultcompany = adminuser_query.default\n companymark = company_query.companymark\n expirestring = \"\"\n if companyexpire:\n if companyexpire <= expire_date and companyexpire >= todays_datetime and disable == False:\n expirestring = \"即将到期\"\n elif companyexpire <= expire_date and companyexpire >= todays_datetime and disable == False:\n expirestring = \"即将到期\"\n elif companyexpire <= todays_datetime and disable== False:\n expirestring = \"试用中\"\n elif disable == True:\n expirestring = \"停用中\"\n elif companyexpire > expire_date and disable == False:\n expirestring = \"正常使用中\"\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n elif disable == 0 and companyexpire is None:\n expirestring = \"试用中\"\n elif disable == 1 and companyexpire is None:\n expirestring = \"停用中\"\n\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\"companyemail\":companyemail,\n 'companyexpire': companyexpire,\"disable\":disable,\n 'companyrole':companyrole,\"expirestring\":expirestring,\n 'companymark': companymark,'defaultcompany':defaultcompany }\n else:\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n backstage_expiredate_query = Backstage.query.first()\n backstage_expiredate = backstage_expiredate_query.companyexpire\n expire_date = todays_datetime + timedelta(days=int(backstage_expiredate))\n company_query = Company.query.filter_by(companyname=oldcompanyname).first()\n companyname = company_query.companyname\n disable = company_query.disable\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n companyemail = company_query.companyemail\n companyid = company_query.companyid\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = company_query.companyemail\n defaultcompany = adminuser_query.default\n companymark = company_query.companymark\n expirestring = \"\"\n if companyexpire:\n if companyexpire <= expire_date and companyexpire >= todays_datetime and disable == False:\n expirestring = \"即将到期\"\n elif companyexpire <= expire_date and companyexpire >= todays_datetime and disable == False:\n expirestring = \"即将到期\"\n elif companyexpire <= todays_datetime and disable== False:\n expirestring = \"试用中\"\n elif disable == True:\n expirestring = \"停用中\"\n elif companyexpire > expire_date and disable == False:\n expirestring = \"正常使用中\"\n companyexpire = int(round(time.mktime(companyexpire.timetuple()) * 1000))\n elif disable == 0 and companyexpire is None:\n expirestring = \"试用中\"\n elif disable == 1 and companyexpire is None:\n expirestring = \"停用中\"\n\n rs_query_dict = {'companyid':companyid, 'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\"companyemail\":companyemail,\n 'companyexpire': companyexpire,\"disable\":disable,\n 'companyrole':companyrole,\"expirestring\":expirestring,\n 'companymark': companymark,'defaultcompany':defaultcompany }\n return {'status': 0, 'msg': '修改成功',\"companyinfo\":rs_query_dict}\n\ndef companydelete(userid, usertoken,companyname):\n if usertoken != '11111':\n return {'status': 1, 'msg': 'token不可用'}\n company_query = Company.query.filter_by(companyname=companyname).first()\n opusers_query = Opuser.query.filter_by(opcompanyid=company_query.companyid).all()\n topic_query = Topic.query.filter_by(companyid=company_query.companyid).all()\n for opuser in opusers_query:\n companys_query = Opuser.query.filter_by(opuserid=opuser.opuserid).all()\n if len(companys_query) == 1:\n user_query = User.query.filter_by(userid=opuser.opuserid).first()\n if user_query:\n user_query.role = 1\n db.session.delete(opuser)\n db.session.delete(company_query)\n for tmp in topic_query:\n db.session.delete(tmp)\n db.session.commit()\n db.session.commit()\n db.session.close()\n return {'status': 0, 'msg': '删除成功'}\n\ndef generate_random_str(randomlength=16):\n \"\"\"\n 生成一个指定长度的随机字符串,其中\n string.digits=0123456789\n string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n \"\"\"\n str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]\n random_str = ''.join(str_list)\n return random_str\n\n\"\"\"\ndef zabbixserver_update(userid, usertoken, companyid, zabbixid, zabbixserver, zabbixusername, zabbixpassword):\n try:\n if usertoken != '11111':\n return {'status':1, 'msg': 'token不可用'}\n\n #adminuserinfo_query =Opuser.query.filter_by(opuserid=userid).first()\n #adminuserrole = adminuserinfo_query.oprole\n #if adminuserrole != '4':\n #return {'status': 2, 'msg': '没有权限'}\n\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid).first()\n if zabbixinfo_query:\n zabbixinfo_query.zabbixid = zabbixid\n zabbixinfo_query.zabbixserver = zabbixserver\n zabbixinfo_query.zabbixusername = zabbixusername\n zabbixinfo_query.zabbixpassword = zabbixpassword\n db.session.commit()\n return {'status':0, 'msg': '修改成功'}\n else:\n zabbixserverid = 'z' + generate_random_str()\n insert_zabbixserver = Zabbix(companyid=companyid, zabbixid=zabbixserverid,\n zabbixserver=zabbixserver, zabbixuser=zabbixusername,\n zabbixpassword=zabbixpassword)\n db.session.add(insert_zabbixserver)\n db.session.commit()\n return {'status': 0, 'msg': '添加成功'}\n except sqlalchemy.exc.OperationalError:\n return {'status': 3, 'Oooops': '数据库连接出现错误'}\n\"\"\"\n\n\n\"\"\"\ndef zabbixserver_update(userid, usertoken, companyid, zabbixid, zabbixserver, zabbixusername, zabbixpassword):\n try:\n if usertoken != '11111':\n return {'status':1, 'msg': 'token不可用'}\n\n #adminuserinfo_query =Opuser.query.filter_by(opuserid=userid).first()\n #adminuserrole = adminuserinfo_query.oprole\n #if adminuserrole != '4':\n #return {'status': 2, 'msg': '没有权限'}\n\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid).first()\n if zabbixinfo_query:\n zabbixinfo_query.zabbixid = zabbixid\n zabbixinfo_query.zabbixserver = zabbixserver\n zabbixinfo_query.zabbixusername = zabbixusername\n zabbixinfo_query.zabbixpassword = zabbixpassword\n\n data = json.dumps(\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"user.login\",\n \"params\": {\n \"user\": zabbixusername,\n \"password\": zabbixpassword\n },\n \"id\": 0\n })\n try: \n authrs = requests.post(zabbixserver + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\n except Exception as e:\n db.session.close()\n return {'status':4, 'msg':\"zabbix服务器地址配置不正确\"}\n if authrs.status_code == 200:\n try:\n token = authrs.json()[\"result\"]\n except:\n db.session.close()\n return {'status': 4, 'msg': \"zabbix服务器地址配置不正确\"}\n db.session.commit()\n return {'status': 0, 'msg': '修改成功'}\n else:\n db.session.close()\n return {'status':4, 'msg':\"zabbix服务器地址配置不正确\"}\n\n\n\n else:\n data = json.dumps(\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"user.login\",\n \"params\": {\n \"user\": zabbixusername,\n \"password\": zabbixpassword\n },\n \"id\": 0\n })\n try:\n authrs = requests.post(zabbixserver + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\n if authrs.status_code == 200:\n try:\n token = authrs.json()[\"result\"]\n except:\n db.session.close()\n return {'status': 4, 'msg': \"zabbix服务器地址配置不正确\"}\n zabbixserverid = 'z' + generate_random_str()\n insert_zabbixserver = Zabbix(companyid=companyid, zabbixid=zabbixserverid,\n zabbixserver=zabbixserver, zabbixuser=zabbixusername,\n zabbixpassword=zabbixpassword)\n db.session.add(insert_zabbixserver)\n db.session.commit()\n return {'status': 0, 'msg': '添加成功'}\n else:\n db.session.close()\n return {'status': 4, 'msg': \"zabbix服务器地址配置不正确\"}\n except:\n db.session.close()\n return {'status': 4, 'msg': \"zabbix服务器地址配置不正确\"}\n\n\n except sqlalchemy.exc.OperationalError:\n return {'status': 3, 'Oooops': '数据库连接出现错误'}\n\"\"\"\n\n\ndef zabbixserver_update(userid, usertoken, companyid, zabbixid, zabbixserver, zabbixusername, zabbixpassword):\n try:\n if usertoken != '11111':\n return {'status':1, 'msg': 'token不可用'}\n\n #adminuserinfo_query =Opuser.query.filter_by(opuserid=userid).first()\n #adminuserrole = adminuserinfo_query.oprole\n #if adminuserrole != '4':\n #return {'status': 2, 'msg': '没有权限'}\n company_query = Company.query.filter_by(companyid=companyid).first()\n if company_query.companyrole == '1':\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid,official='1').first()\n elif company_query.companyrole == '2':\n zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid,official='2').first()\n\n #zabbixinfo_query = Zabbix.query.filter_by(companyid=companyid).first()\n\n if zabbixinfo_query:\n zabbixinfo_query.zabbixid = zabbixid\n zabbixinfo_query.zabbixserver = zabbixserver\n zabbixinfo_query.zabbixusername = zabbixusername\n zabbixinfo_query.zabbixpassword = zabbixpassword\n\n data = json.dumps(\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"user.login\",\n \"params\": {\n \"user\": zabbixusername,\n \"password\": zabbixpassword\n },\n \"id\": 0\n })\n try: \n authrs = requests.post(zabbixserver + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\n except Exception as e:\n db.session.close()\n return {'status':4, 'msg':\"zabbix服务器地址配置不正确\"}\n if authrs.status_code == 200:\n try:\n token = authrs.json()[\"result\"]\n except:\n db.session.close()\n return {'status': 4, 'msg': \"zabbix服务器地址配置不正确\"}\n db.session.commit()\n return {'status': 0, 'msg': '修改成功'}\n else:\n db.session.close()\n return {'status':4, 'msg':\"zabbix服务器地址配置不正确\"}\n\n\n\n else:\n data = json.dumps(\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"user.login\",\n \"params\": {\n \"user\": zabbixusername,\n \"password\": zabbixpassword\n },\n \"id\": 0\n })\n try:\n authrs = requests.post(zabbixserver + '/zabbix/api_jsonrpc.php', data=data, headers=headers)\n if authrs.status_code == 200:\n try:\n token = authrs.json()[\"result\"]\n except:\n db.session.close()\n return {'status': 4, 'msg': \"zabbix服务器地址配置不正确\"}\n zabbixserverid = 'z' + generate_random_str()\n insert_zabbixserver = Zabbix(companyid=companyid, zabbixid=zabbixserverid,\n zabbixserver=zabbixserver, zabbixuser=zabbixusername,\n zabbixpassword=zabbixpassword)\n db.session.add(insert_zabbixserver)\n db.session.commit()\n return {'status': 0, 'msg': '添加成功'}\n else:\n db.session.close()\n return {'status': 4, 'msg': \"zabbix服务器地址配置不正确\"}\n except:\n db.session.close()\n return {'status': 4, 'msg': \"zabbix服务器地址配置不正确\"}\n\n\n except sqlalchemy.exc.OperationalError:\n return {'status': 3, 'Oooops': '数据库连接出现错误'}\n\n" }, { "alpha_fraction": 0.7159532904624939, "alphanum_fraction": 0.731517493724823, "avg_line_length": 24.700000762939453, "blob_id": "fdfce69a819173513ca80865a8e58c54a5f5353d", "content_id": "ae1454e5eb7f4044450e53085bdd1189fec355c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 265, "license_type": "no_license", "max_line_length": 99, "num_lines": 10, "path": "/nginx/Dockerfile", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "FROM nginx:1.15.6-alpine\nCOPY flask-socketio.conf /etc/nginx/conf.d\n\n\n#设置时区\nRUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone\n#RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime\n\n\n#CMD [\"nginx -t\"]\n" }, { "alpha_fraction": 0.6611102223396301, "alphanum_fraction": 0.6671646237373352, "avg_line_length": 31.61025619506836, "blob_id": "c62e54782e5b1619b61d35690bf713c912908b33", "content_id": "479ac5bd0b044378b06b48041aa4bfb3892f0c43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13148, "license_type": "no_license", "max_line_length": 123, "num_lines": 390, "path": "/houtaiapi/http_chat.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#coding=utf-8\nfrom flask import jsonify, request\nfrom user import *\nfrom company import *\nfrom index import *\nfrom setting import *\n\n\n#后台功能\[email protected]('/backstage/index', methods=['GET'])\ndef BackstageIndex():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n joininfors = backstage(userid, usertoken)\n return jsonify(joininfors)\n\n\n#获取所有公司\[email protected]('/backstage/companymanages', methods=['GET'])\ndef BackstageCm():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstagecms(userid, usertoken, page)\n return jsonify(joininfors)\n\n#根据公司名获取某家公司的信息\[email protected]('/backstage/companymanage/<string:companyname>', methods=['GET'])\ndef BackstageSearch(companyname):\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstagecm(userid, usertoken, companyname, page)\n return jsonify(joininfors)\n\n#根据公司id获取某家公司的信息\[email protected]('/backstage/companymanage/<string:companyid>', methods=['GET'])\ndef BackstageSearch1(companyid):\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstagecm1(userid, usertoken, companyid, page)\n return jsonify(joininfors)\n\n#获取处于试用中的公司\[email protected]('/backstage/tryouts', methods=['GET'])\ndef BackstageTryOut():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstagetryouts(userid, usertoken, page)\n return jsonify(joininfors)\n\n#获取即将过期公司\[email protected]('/backstage/expiringcompanys', methods=['GET'])\ndef BackstageExpireC():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstageexpiring(userid, usertoken, page)\n return jsonify(joininfors)\n\n#获取已过期公司\[email protected]('/backstage/expiredcompanys', methods=['GET'])\ndef BackstageExpired():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstageexpired(userid, usertoken, page)\n return jsonify(joininfors)\n\n#展示新创建的公司\[email protected]('/backstage/newcompanys', methods=['GET'])\ndef BackstageNewCompanys():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstagenewcompanytoday(userid, usertoken, page)\n return jsonify(joininfors)\n\n#获取公司成员\[email protected]('/backstage/companymembers', methods=['GET'])\ndef BackstageCompanyMember():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n companyname = request.args.get('companyname')\n searchcompanynamers = companymemberinfo(userid, usertoken, page, companyname)\n return jsonify(searchcompanynamers)\n\n#获取公司所有主机\[email protected]('/backstage/companyhosts', methods=['GET'])\ndef BackstageCompanyZabbix():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n companyname = request.args.get('companyname')\n searchcompanynamers = companyhostsinfo(userid, usertoken, page, companyname)\n return jsonify(searchcompanynamers)\n\n#修改公司有效期\[email protected]('/backstage/companyexpire', methods=['PATCH'])\ndef BackstageCompanyExpire():\n request_data = request.get_json()\n token = request_data['token']\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n time_chuo = request_data['expiredate']\n companyname = request_data['companyname']\n searchcompanynamers = companyexpire(userid, usertoken,companyname, time_chuo)\n return jsonify(searchcompanynamers)\n\n#修改公司相关信息\[email protected]('/backstage/companymanager', methods=['PATCH'])\ndef BackstageCompanyPatch():\n request_data = request.get_json()\n token = request_data['token']\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n oldcompanyname = request_data['oldcompanyname']\n newcompanyname = request_data['newcompanyname']\n companyemail = request_data['companyemail']\n mark = request_data['mark']\n disable = request_data['disable']\n\n searchcompanynamers = companypatch(userid, usertoken,oldcompanyname, newcompanyname,companyemail,mark, disable)\n return jsonify(searchcompanynamers)\n\n#删除公司\[email protected]('/backstage/companymanager', methods=['DELETE'])\ndef BackstageCompanyDelete():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n companyname = request.args.get('companyname')\n\n searchcompanynamers = companydelete(userid, usertoken,companyname)\n return jsonify(searchcompanynamers)\n\n\n#============\n#用户相关\[email protected]('/backstage/users', methods=['GET'])\ndef BackstageUsers():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstageusers(userid, usertoken, page)\n return jsonify(joininfors)\n\n#在后台展示今天加入的用户\[email protected]('/backstage/newusers', methods=['GET'])\ndef BackstageNewUsers():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstagenewusers(userid, usertoken, page)\n return jsonify(joininfors)\n\n#在后台根据公司名或者手机查询用户\[email protected]('/backstage/usersearch', methods=['GET'])\ndef BackstageUserSearch():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n searchcompanyname = request.args.get('companyname')\n searchmobile = request.args.get('mobile')\n\n print('lalalalla:',searchcompanyname, searchmobile)\n if searchcompanyname != \"\" and searchmobile == \"\":\n companyname = request.args.get('companyname')\n searchcompanynamers = backstagesearchuserscompany(userid, usertoken, page, companyname)\n return jsonify(searchcompanynamers)\n if searchmobile !=\"\" and searchcompanyname == \"\":\n mobile = request.args.get('mobile')\n joininfors = backstagesearchusersmobile(userid, usertoken, page, mobile)\n return jsonify(joininfors)\n #joininfors = backstagesearchusersmobile(userid, usertoken, page, companyname, mobile)\n if searchmobile != \"\" and searchcompanyname != \"\":\n mobile = request.args.get('mobile')\n companyname = request.args.get('companyname')\n searchallrs = backstagesearchusersall(userid, usertoken, page, mobile, companyname)\n return jsonify(searchallrs)\n if searchmobile == \"\" and searchcompanyname == \"\":\n print('lalal')\n joininfors = backstageusers(userid, usertoken, page)\n return jsonify(joininfors)\n\n#在后台展示所有游客用户\[email protected]('/backstage/tourist', methods=['GET'])\ndef BackstageTouristUsers():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstagetourist(userid, usertoken, page)\n return jsonify(joininfors)\n\n#在后台展示所有已被禁用的用户\[email protected]('/backstage/userstopped', methods=['GET'])\ndef BackstageUserstopped():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if request.args.get('page'):\n page = request.args.get('page')\n else:\n page = 1\n joininfors = backstageuserstopped(userid, usertoken, page)\n return jsonify(joininfors)\n\n\"\"\"\n#修改用户禁用/启用状态\[email protected]('/backstage/user', methods=['PATCH'])\ndef BackstagePatchUsers():\n request_data = request.get_json()\n token = request_data['token']\n adminuserid = token.split('-')[0]\n adminusertoken = token.split('-')[1]\n userstatus = request_data['userdisable']\n userid = request_data['userid']\n joininfors = userdisable(adminuserid, adminusertoken, userstatus, userid)\n return jsonify(joininfors)\n\n\[email protected]('/backstage/user', methods=['DELETE'])\ndef BackstageDeleteUsers():\n token = request.args.get('token')\n adminuserid = token.split('-')[0]\n adminusertoken = token.split('-')[1]\n userid = request.args.get('userid')\n joininfors = userdelete(adminuserid, adminusertoken, userid)\n return jsonify(joininfors)\n\"\"\"\n\n# 删除用户-运维用户\[email protected]('/backstage/user', methods=['DELETE'])\ndef BackstageDeleteUsers():\n token = request.args.get('token')\n adminuserid = token.split('-')[0]\n adminusertoken = token.split('-')[1]\n userid = request.args.get('userid')\n companyid = request_data['companyid']\n joininfors = userdelete(adminuserid, adminusertoken, userid, companyid)\n return jsonify(joininfors)\n\n# 用户停用、启用\[email protected]('/backstage/user', methods=['PATCH'])\ndef BackstagePatchUsers():\n request_data = request.get_json()\n token = request_data['token']\n adminuserid = token.split('-')[0]\n adminusertoken = token.split('-')[1]\n userstatus = request_data['userdisable']\n userid = request_data['userid']\n companyid = request_data['companyid']\n joininfors = userdisable(adminuserid, adminusertoken, userstatus, userid, companyid)\n return jsonify(joininfors)\n\n\n#==========\n#配置相关\[email protected]('/backstage/configs', methods=['GET'])\ndef BackstageConfigsGet():\n token = request.args.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n joininfors = configsGet(userid, usertoken)\n return jsonify(joininfors)\n\n#修改后台配置\[email protected]('/backstage/configs', methods=['POST'])\ndef BackstageConfigsChange():\n request_data = request.get_json()\n token = request_data['token']\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n if 'customerservice' in request_data:\n customerservice = request_data['customerservice']\n else:\n customerservice = None\n if 'expire' in request_data:\n expire = request_data['expire']\n else:\n expire = None\n if 'trydate' in request_data:\n trydate = request_data['trydate']\n else:\n trydate = None\n joininfors = configsChange(userid, usertoken, customerservice, expire, trydate)\n return jsonify(joininfors)\n\n\n#修改zabbix服务器配置\[email protected]('/backstage/updatezabbixserver',methods=['PATCH', 'PUT'])\ndef UpdateZabbixServer():\n request_data = request.get_json()\n token = request_data['token']\n\n companyid = request_data['companyid']\n zabbixid = request_data['zabbixid']\n zabbixserver = request_data['zabbixserver']\n zabbixusername = request_data['zabbixusername']\n zabbixpassword = request_data['zabbixpassword']\n\n adminuserid = token.split('-')[0]\n usertoken = token.split('-')[1]\n joininfors = zabbixserver_update(adminuserid,usertoken,companyid,zabbixid,zabbixserver, zabbixusername, zabbixpassword)\n return jsonify(joininfors)\n\n\n#=========\n#管理员相关\[email protected]('/backstage/login', methods=['POST'])\ndef AdminLogin():\n request_data = request.get_json()\n print(request_data)\n username = request_data['username']\n password = request_data['password']\n joininfors = AdminInfo(username, password)\n return jsonify(joininfors)\n\n#修改后台登录消息\[email protected]('/backstage/admin', methods=['PATCH'])\ndef AdminPatch():\n request_data = request.get_json()\n oldpassword = request_data['oldpassword']\n newpassword = request_data['newpassword']\n token = request_data['token']\n adminuserid = token.split('-')[0]\n admintoken = token.split('-')[1]\n joininfors = adminpatch(adminuserid, admintoken, oldpassword, newpassword)\n return jsonify(joininfors)\n\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=7000)\n" }, { "alpha_fraction": 0.7401574850082397, "alphanum_fraction": 0.7401574850082397, "avg_line_length": 20.16666603088379, "blob_id": "e0e855542e909e42117e147bb32646747d1eb199", "content_id": "456d88f4687477db4496e770db9107a8d9c66fd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 169, "license_type": "no_license", "max_line_length": 68, "num_lines": 6, "path": "/websocket/README.txt", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "# xmpush-python\n\n## 安装\n\n运行python setup.py sdist, 在本地生成${project-name}-${version}.tar.gz源码压缩包\n运行python setup.py install, 安装到本地\n" }, { "alpha_fraction": 0.6341093182563782, "alphanum_fraction": 0.6457489728927612, "avg_line_length": 33.28571319580078, "blob_id": "3934df803d6340c3ecf17e366d3607a012bb48ba", "content_id": "f9729cab3847112669822fdadc34afb4f21ef5eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2024, "license_type": "no_license", "max_line_length": 101, "num_lines": 56, "path": "/websocket/APIDemo.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\nfrom APISender import APISender\r\nfrom base.APIMessage import *\r\nfrom APITools import *\r\nfrom APISubscribe import *\r\n\r\n# push-demo\r\nsender = APISender('lsoNVMUZH69YvcsLR6SHNQ==')\r\n\r\n# build android message\r\nmessage = PushMessage() \\\r\n .restricted_package_name('PACKAGE_NAME') \\\r\n .title('这是一条测试消息').description('这是一条测试消息') \\\r\n .pass_through(0).payload('payload') \\\r\n .extra({Constants.extra_param_notify_effect: Constants.notify_launcher_activity})\r\n\r\n# build ios message\r\nmessage_ios = PushMessage() \\\r\n .description(\"这是一条ios测试消息\") \\\r\n .sound_url(\"default\") \\\r\n .badge(1) \\\r\n .category(\"action\") \\\r\n .extra({\"key\": \"value\"})\r\n\r\n# build ios message\r\nmessage_ios10 = PushMessage() \\\r\n .aps_title(\"title\") \\\r\n .aps_subtitle(\"subtitle\") \\\r\n .aps_body(\"body\") \\\r\n .aps_mutable_content(\"1\") \\\r\n .sound_url(\"default\") \\\r\n .badge(1) \\\r\n .category(\"action\") \\\r\n .extra({\"key\": \"value\"})\r\n\r\n# send message android\r\nrecv = sender.send(message.message_dict(), '1')\r\nprint (recv)\r\n\r\n# recv_ios = sender.send(message_ios10.message_dict_ios(), 'RED_ID_IOS')\r\n# print recv_ios\r\n\r\ntools = APITools('lsoNVMUZH69YvcsLR6SHNQ==')\r\n# print tools.query_message_status('msg_id').data\r\n# print tools.validate_reg_ids(['REG_ID', 'RED_ID1'])\r\n# print tools.query_invalid_reg_ids()\r\n# print tools.query_invalid_aliases()\r\n# print tools.query_device_topics('package_name', 'RED_ID')\r\n# print tools.query_device_presence('package_name', ['REG_ID', 'test'])\r\n# print tools.query_device_aliases('package_name', 'REG_ID')\r\n# print tools.check_schedule_job_exist('tcm111')\r\nsubscribe = APISubscribe('AlsoNVMUZH69YvcsLR6SHNQ==')\r\n# print subscribe.subscribe_topic('RED_ID', 'topic',\r\n# **{Constants.http_param_restricted_package_name: 'package_name'})\r\n# print subscribe.unsubscribe_topic('RED_ID', 'topic',\r\n# **{Constants.http_param_restricted_package_name: 'package_name'})\r\n" }, { "alpha_fraction": 0.688829779624939, "alphanum_fraction": 0.6928191781044006, "avg_line_length": 33.97674560546875, "blob_id": "c199a352ed1edf12ce6685f9ab6fd03cfe5296a8", "content_id": "e494da48cbe525740369d1fa1f8cf59a24114066", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1570, "license_type": "no_license", "max_line_length": 116, "num_lines": 43, "path": "/houtaiapi/setting.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from model import *\n\ndef configsGet(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #获取配置\n backstageinfo_query = Backstage.query.first()\n backstageinfo_expire = backstageinfo_query.companyexpire\n backstageinfo_tryoutdate = backstageinfo_query.tryoutdata\n backstageinfo_custom = backstageinfo_query.customerservicemobile\n rs = {'expire':backstageinfo_expire, 'trydate':backstageinfo_tryoutdate, 'customerservice':backstageinfo_custom}\n db.session.close()\n return rs\n\n\ndef configsChange(userid, token, customerservice, expire, trydate):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #修改后台配置\n backstageinfo_query = Backstage.query.first()\n if customerservice:\n backstageinfo_query.customerservicemobile = customerservice\n if expire:\n backstageinfo_query.companyexpire = expire\n if trydate:\n backstageinfo_query.tryoutdata = trydate\n db.session.commit()\n\n rs = {'status':0, 'msg':'设置成功','expire':expire, 'trydate':trydate, 'customerservice':customerservice}\n db.session.close()\n return rs\n\ndef coustomMobile(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #修改后台配置\n backstageinfo_query = Backstage.query.first()\n if backstageinfo_query:\n custommobile = backstageinfo_query.customerservicemobile\n\n rs = {'status':0, 'msg':'查询成功','customermobile':custommobile}\n db.session.close()\n return rs\n" }, { "alpha_fraction": 0.6349999904632568, "alphanum_fraction": 0.699999988079071, "avg_line_length": 12.333333015441895, "blob_id": "0fac6f93a06d4cfcc083c0e7206089b0a8959a86", "content_id": "22dabb3d21678d1ffcf8b2b023d895219df5af68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 200, "license_type": "no_license", "max_line_length": 30, "num_lines": 15, "path": "/upload/upload.ini", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "[uwsgi]\nmodule = http_chat:app\n\nmaster = true\nprocesses = 2 \nplugin = python\n\n#socket = /tmp/myproject2.sock\n#chmod-socket = 666\n#vacuum = true\n#die-on-term = true\n\n\nsocket=0.0.0.0:6000\nprotocol=http\n" }, { "alpha_fraction": 0.7213114500045776, "alphanum_fraction": 0.7494145035743713, "avg_line_length": 27.46666717529297, "blob_id": "9b28fc194a1ed872f9c989a20f9625f6158bd208", "content_id": "a3fef337367de206159af2c669014315b3094746", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 435, "license_type": "no_license", "max_line_length": 99, "num_lines": 15, "path": "/websocket/Dockerfile", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#FROM python:3.6.6-alpine3.8 \nFROM python:3.6.7-jessie\n\nWORKDIR /data\nRUN pip3 install -i https://pypi.douban.com/simple flask_socketio flask requests\nADD . /data\nRUN python3 setup.py sdist\nRUN python3 setup.py install\n\n#设置时区\nRUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone\n#RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime\n\n\nCMD [\"python3\", \"websocket_chat.py\"]\n" }, { "alpha_fraction": 0.6154449582099915, "alphanum_fraction": 0.6250196099281311, "avg_line_length": 35.40571594238281, "blob_id": "bee8156102f9d2c7bf71d2ebdcbdfbf38b779f7a", "content_id": "d21ba87478f6f49c6a7af826ec25e8e745ccbab4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6941, "license_type": "no_license", "max_line_length": 174, "num_lines": 175, "path": "/houtaiapi/index.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from model import *\nfrom socketIO_client import SocketIO, BaseNamespace\nfrom flask_socketio import SocketIO,emit\nimport sqlalchemy\nfrom datetime import datetime, timedelta\nimport time\nfrom urllib.parse import unquote\nfrom flask_socketio import join_room, leave_room\napp = Flask(__name__)\nsocketio = SocketIO(app)\n\ndef backstage(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #公司总数量\n companys_query = Company.query.all()\n totalcompanys = len(companys_query)\n\n #当天新增公司数量\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n #todays_datetime = '2018-10-30 00:00:00'\n newcompanys_query = Company.query.filter(Company.createtime >= todays_datetime).all()\n newcompanys = len(newcompanys_query)\n\n #试用中的公司\n num = 0\n try_companys_query = Company.query.all()\n for company in try_companys_query:\n if not company.companyexpiredate:\n num += 1\n try_companys = num\n\n #用户总数量\n users_query = User.query.filter(\n User.mobile.like('1%')).all()\n totalusers = len(users_query)\n\n #当天新增用户\n newusers_query = User.query.filter(User.createtime >= todays_datetime, User.mobile.like('1%')).all()\n newusers = len(newusers_query)\n\n backstage_expiredate_query = Backstage.query.first()\n backstage_expiredate = backstage_expiredate_query.companyexpire\n expire_date = todays_datetime + timedelta(days=int(backstage_expiredate))\n try_expire_companys_query = Company.query.filter(Company.companyexpiredate <= expire_date, Company.companyexpiredate >= todays_datetime, Company.companyrole == '2').all()\n expire_companys = len(try_expire_companys_query)\n rs = {'total_companys': totalcompanys, 'new_companys': newcompanys,\n 'try_companys': try_companys,'total_users':totalusers,\n 'new_users': newusers, 'expiring_companys':expire_companys,\n }\n db.session.close()\n return rs\n\ndef AdminInfo(username, password):\n #所有用户信息\n\n admin_query = Backstage.query.filter_by(rootname='root').first()\n adminpassword = admin_query.rootpassword\n if username == 'root' and password == adminpassword:\n db.session.close()\n return {'status':0, 'msg': '登录成功', 'token':'xxx-11111'}\n else:\n db.session.close()\n return {'status':1, 'msg':'用户名或密码错误'}\n\ndef adminpatch(adminuserid, admintoken, oldpassword, newpassword):\n #所有用户信息\n if admintoken != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n admin_query = Backstage.query.filter_by(rootname='root').first()\n adminpassword = admin_query.rootpassword\n if oldpassword == adminpassword:\n admin_query.rootpassword = newpassword\n db.session.commit()\n db.session.close()\n return {'status':0, 'msg': '修改成功'}\n else:\n db.session.close()\n return {'status':2, 'msg':'旧密码错误'}\n\"\"\"\ndef userdelete(adminuserid, adminusertoken, userid):\n try:\n if adminusertoken != '11111':\n return {'status':1, 'msg':'token不可用'}\n user_query = User.query.filter_by(userid=userid).first()\n db.session.delete(user_query)\n db.session.commit()\n return {'status':0, 'msg': '修改成功'}\n except sqlalchemy.exc.OperationalError:\n db.session.close()\n return {'Oooops': 'There is a problem with the database'}\n\ndef userdisable(adminuserid,adminusertoken,userstatus,userid):\n try:\n if adminusertoken != '11111':\n return {'status':1, 'msg':'token不可用'}\n user_query = User.query.filter_by(userid=userid).first()\n if userstatus:\n user_query.mark = userstatus\n db.session.commit()\n topic = Topic.query.filter_by(admin_userid=adminuserid).first()\n if topic:\n companyid = topic.companyid\n companyname = Company.query.filter_by(companyid=companyid).first()\n room = companyname\n join_room(room)\n socket.emit(\"talkstatus\",{\"type\":14,\"companyid\":companyid},room=room)\n return {'status':0, 'msg': '修改成功'}\n except sqlalchemy.exc.OperationalError:\n db.session.close()\n return {'Oooops': 'There is a problem with the database'}\n\"\"\"\n\n# 删除用户\n# 1、如果用户是游客直接删除账户\n# 2、如果用户有1家公司直接删除账户\n# 3、如果存在2家或者以上的公司,把用户从当前公司下删除(从 Opuser 中删除)\ndef userdelete(adminuserid, adminusertoken, userid, companyid):\n try:\n # 不存在公司(游客)直接删除账户\n if len(companyid) == 0:\n return deleteTouristAccount(adminusertoken, userid)\n # 用户存在几家公司\n companys = Opuser.query.filter_by(opuserid=userid)\n \n if companys:\n # 存在1家以下的公司直接删除账户\n if len(companys) <= 1:\n return deleteTouristAccount(adminusertoken, userid)\n # 删除当前选中公司中的当前运维用户\n else:\n opUser = Opuser.query.filter_by(opuserid=userid,opcompanyid=companyid).first()\n db.session.delete(opUser)\n db.session.commit()\n return {'status':0, 'msg': '修改成功'}\n # 公司不存在直接删除用户\n else:\n return deleteTouristAccount(adminusertoken, userid)\n \n except sqlalchemy.exc.OperationalError:\n db.session.close()\n return {'Oooops': 'There is a problem with the database'}\n\n# 用户禁用\n# 1、用户没有公司、直接禁用用户的账户\n# 2、有公司、禁用当前公司下的该用户 Opuser.company_user_status = '4'\ndef userdisable(adminuserid,adminusertoken,userstatus,userid, companyid):\n try:\n # 不存在公司(游客)账户被禁用\n if len(companyid) == 0:\n if adminusertoken != '11111':\n return {'status':1, 'msg':'token不可用'}\n user_query = User.query.filter_by(userid=userid).first()\n if userstatus:\n user_query.mark = userstatus\n db.session.commit()\n return {'status':0, 'msg': '修改成功'}\n \n # 禁用公司下的运维用户 Opuser company_user_status = '4'\n opUser = Opuser.query.filter_by(opuserid=userid,opcompanyid=companyid).first()\n if opUser:\n \n if userstatus=='userenabled':\n opUser.company_user_status = '3'\n else:\n opUser.company_user_status = '4'\n\n db.session.commit()\n return {'status':0, 'msg': '修改成功'}\n \n except sqlalchemy.exc.OperationalError:\n db.session.close()\n return {'Oooops': 'There is a problem with the database'}\n" }, { "alpha_fraction": 0.6336633563041687, "alphanum_fraction": 0.801980197429657, "avg_line_length": 49.25, "blob_id": "49764b38e8a157f1f8744526c745118170c7c956", "content_id": "f0296dcdaf1fdf021a38520867376401b3a7cfc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 98, "num_lines": 4, "path": "/chatapi/config.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#数据库连接配置\n\n#localdatabase = 'mysql+pymysql://chatbot:[email protected]:3306/chatbot?charset=utf8mb4'\nlocaldatabase = 'mysql+pymysql://chatbot:chatbot2515525@mysql:3306/chatbot?charset=utf8mb4'\n\n" }, { "alpha_fraction": 0.6792522072792053, "alphanum_fraction": 0.7027125954627991, "avg_line_length": 46.306358337402344, "blob_id": "4611ef5793b53f02ac5ce9a6cbb50c1cbc1d9572", "content_id": "c06b018663d41b1fa70ec3302ab8e27775d760b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9016, "license_type": "no_license", "max_line_length": 189, "num_lines": 173, "path": "/houtaiapi/model.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#from flask_sqlalchemy import SQLAlchemy\nfrom flask import Flask\nfrom config import *\nfrom flask_cors import CORS\n\nfrom flask_sqlalchemy import SQLAlchemy as SQLAlchemyBase\nfrom sqlalchemy.pool import NullPool\n\n\nclass SQLAlchemy(SQLAlchemyBase):\n def apply_driver_hacks(self, app, info, options):\n super(SQLAlchemy, self).apply_driver_hacks(app, info, options)\n options['poolclass'] = NullPool\n options.pop('pool_size', None)\n\n'''配置数据库'''\napp = Flask(__name__)\napp.config['SECRET_KEY'] ='hard to guess'\napp.config['SQLALCHEMY_DATABASE_URI'] = localdatabase\n\n#设置这一项是每次请求结束后都会自动提交数据库中的变动\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False\n#实例化\ndb = SQLAlchemy(app)\n\nCORS(app, origins=\"*\", allow_headers=[\n \"Content-Type\", \"Authorization\", \"Access-Control-Allow-Credentials\",\"Access-Control-Allow-Origin\"],\n supports_credentials=True)\n\n\nclass User(db.Model):\n # 定义表名\n __tablename__ = 'tbl_users'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(128), nullable=True, comment='用户名')\n userid = db.Column(db.String(128), nullable=True,unique=True, comment='用户名')\n role = db.Column(db.String(128), nullable=True, comment='用户状态')\n #password_hash = db.Column(db.String(64))\n password = db.Column(db.String(128), nullable=False, comment='用户密码')\n mobile = db.Column(db.String(128), nullable=False,unique=True, comment='用户手机号码')\n #1为游客,2为申请待同意用户,3为普通公司用户,4为公司管理员\n profile = db.Column(db.String(128), nullable=False, server_default='http://139.196.107.14:6001/upload/2018-11-12/[email protected]', comment='profile picture')\n mark = db.Column(db.String(128), nullable=True, comment='用户备注')\n logintime = db.Column(db.TIMESTAMP(True), nullable=False, comment='登录时间')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\nclass Opuser(db.Model):\n # 定义表名\n __tablename__ = 'tbl_opusers'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n opusername = db.Column(db.String(128), nullable=True, comment='用户名')\n opuserid = db.Column(db.String(128), nullable=True, comment='用户名')\n opmobile = db.Column(db.String(128), nullable=True, comment='用户手机号码')\n opcompanyid = db.Column(db.String(128), nullable=True, comment='公司id')\n default = db.Column(db.String(128), nullable=True, comment='是否是默认公司')\n oprole = db.Column(db.String(128), nullable=True, comment='用户状态')\n userstatus = db.Column(db.String(128), nullable=False,server_default='register', comment='用户渠道')\n company_user_status = db.Column(db.String(128), nullable=False,server_default='3', comment='公司用户状态')\n opemail = db.Column(db.String(128), nullable=True, comment='email')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\nclass Company(db.Model):\n # 定义表名\n __tablename__ = 'tbl_company'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n companyid = db.Column(db.String(128), nullable=True,unique=True, comment='公司id')\n companyname = db.Column(db.String(128), nullable=True, comment='公司名称')\n companyrole = db.Column(db.String(128), nullable=True, comment='公司角色')\n companyemail = db.Column(db.String(128), nullable=True, comment='公司email')\n companymark = db.Column(db.String(128), nullable=True, comment='公司备注')\n #disable = db.Column(db.String(128), nullable=True, default=\"true\", comment='公司开启禁用')\n disable = db.Column(db.Boolean, nullable=True, default=0, comment='公司开启禁用')\n companyexpiredate = db.Column(db.TIMESTAMP(True),nullable=True,comment='过期时间')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n \n\n\nclass Permission(db.Model):\n # 定义表名\n __tablename__ = 'tbl_permission'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.String(128), nullable=False, comment='管理员')\n user_role = db.Column(db.String(128), nullable=False, comment='申请人用户名')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\n\nclass Topic(db.Model):\n # 定义表名\n __tablename__ = 'tbl_topic'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n admin_userid = db.Column(db.String(128), nullable=False, comment='管理员')\n companyid = db.Column(db.String(128), nullable=False, comment='公司id')\n request_username = db.Column(db.String(128), nullable=False, comment='申请人用户名')\n request_mobile = db.Column(db.String(128), nullable=False, comment='申请人手机')\n request_userid = db.Column(db.String(128), nullable=False, comment='申请人用户id')\n admin_action = db.Column(db.String(128), nullable=True, comment='管理员动作')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\n\nclass Sms(db.Model):\n # 定义表名\n __tablename__ = 'tbl_sms'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n user_mobile = db.Column(db.String(128), nullable=False, comment='管理员')\n user_sms = db.Column(db.String(128), nullable=False, comment='申请人用户名')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\n\nclass Zabbix(db.Model):\n # 定义表名\n __tablename__ = 'tbl_zabbix'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n companyid = db.Column(db.String(128), nullable=False, comment='公司id')\n zabbixid = db.Column(db.String(128), nullable=False, comment='zabbix服务器id')\n zabbixserver = db.Column(db.String(128), nullable=False, comment='zabbix服务器地址')\n zabbixuser = db.Column(db.String(128), nullable=False, comment='zabbix用户')\n zabbixpassword = db.Column(db.String(128), nullable=False, comment='zabbix密码')\n official = db.Column(db.String(20), nullable=True, default='1', comment='zabbix服务器类型')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\nclass Monitor(db.Model):\n # 定义表名\n __tablename__ = 'tbl_monitor'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n companyid = db.Column(db.String(128), nullable=False, comment='公司id')\n zabbixhostid = db.Column(db.String(128), nullable=False, comment='zabbix服务器id')\n #zabbixgroupid = db.Column(db.String(128), nullable=False, comment='zabbix组id')\n zabbixhostip = db.Column(db.String(128), nullable=False, comment='zabbix hostip')\n zabbixhostname = db.Column(db.String(128), nullable=False, comment='zabbix hostname')\n zabbixitemid = db.Column(db.String(1280), nullable=True, comment='zabbix组id')\n zabbixitemname = db.Column(db.String(128), nullable=True, comment='zabbix组id')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\n\nclass Backstage(db.Model):\n # 定义表名\n __tablename__ = 'tbl_backstage'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n rootname = db.Column(db.String(128), nullable=False, comment='超级管理员名称')\n companyexpire = db.Column(db.String(128), nullable=False, comment='过期时间')\n tryoutdata = db.Column(db.String(128), nullable=False, comment='试用时间')\n customerservicemobile = db.Column(db.String(128), nullable=False, comment='客服电话')\n rootpassword = db.Column(db.String(1280), nullable=True, comment='超级管理员密码')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\n\nclass UserToken(db.Model):\n #定义表名\n __tablename__ = 'tbl_usertoken'\n id = db.Column(db.Integer, primary_key=True)\n token = db.Column(db.String(128), nullable=False, comment='用户token')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n\n#db.create_all()\n" }, { "alpha_fraction": 0.5995258688926697, "alphanum_fraction": 0.6049575209617615, "avg_line_length": 39.887115478515625, "blob_id": "37593a1800bf4c856a19a212d55ee1795e3cdbb3", "content_id": "66d0b8a31a33db69a76a9ce1314490e96b90abb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 33949, "license_type": "no_license", "max_line_length": 198, "num_lines": 815, "path": "/houtaiapi/user.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from model import *\nfrom datetime import datetime\nimport time\nimport math\n\n\n\n\"\"\"\ndef backstageusers(adminuserid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #所有用户信息\n page = int(page)\n rs_query_list = []\n\n users_query_page = User.query.filter(User.mobile.like('1%')).order_by(User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n users_query = users_query_page.items\n #users_total = len(users_query) / 15\n users_query_total = User.query.filter(User.mobile.like('1%')).order_by(User.createtime.desc()).all()\n users_total = len(users_query_total) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n userid = user_query.userid\n username = user_query.username\n usermobile = user_query.mobile\n userrole = user_query.role\n mark = user_query.mark\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n\n if username != 'chatbot' or usermobile.find('c') == -1:\n rs_query_dict = {'username': username, 'mobile': usermobile,\n 'role': userrole,'logintime':userlogintime,'userid':userid,\n 'mark':mark\n }\n rs_query_list.append(rs_query_dict)\n userinfo_list = []\n\n\n for userallinfo in rs_query_list:\n userinfo_dict = {}\n queryuserid = userallinfo['userid']\n companyinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n companyid_list = []\n for companyinfo_query in companyinfos_query:\n companyid = companyinfo_query.opcompanyid\n companyid_list.append(companyid)\n companyname_list = []\n for companyid in companyid_list:\n companyinfos_query = Company.query.filter_by(companyid=companyid).first()\n if companyinfos_query:\n companyname = companyinfos_query.companyname\n companyname_list.append(companyname)\n userinfo_dict['companynamelist'] = companyname_list\n userinfo_dict['userinfo'] = userallinfo\n userinfo_list.append(userinfo_dict)\n print(userinfo_list)\n\n\n userallinfo_list = []\n for userinfo in userinfo_list:\n userallinfo_dict = {}\n companyname_list = userinfo['companynamelist']\n userallinfo = userinfo['userinfo']\n if companyname_list:\n pass\n else:\n companyname_list = ['未关联公司']\n\n for companyname in companyname_list:\n userallinfo_dict['companyname'] = companyname\n userallinfo_dict['userallinfo'] = userallinfo\n\n userallinfo_list.append(userallinfo_dict)\n\n\n print(len(userallinfo_list))\n print(userallinfo_list)\n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\",'pagetotal':page_total, \"userinfo\": userallinfo_list}\n\n\ndef backstageusers(adminuserid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #所有用户信息\n page = int(page)\n rs_query_list = []\n\n users_query_page = User.query.filter(User.mobile.like('1%')).order_by(User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n users_query = users_query_page.items\n #users_total = len(users_query) / 15\n users_query_total = User.query.filter(User.mobile.like('1%')).order_by(User.createtime.desc()).all()\n users_total = len(users_query_total) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n userid = user_query.userid\n username = user_query.username\n usermobile = user_query.mobile\n userrole = user_query.role\n mark = user_query.mark\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n\n if username != 'chatbot' or usermobile.find('c') == -1:\n rs_query_dict = {'username': username, 'mobile': usermobile,\n 'role': userrole,'logintime':userlogintime,'userid':userid,\n 'mark':mark\n }\n rs_query_list.append(rs_query_dict)\n \n userallinfo_list = []\n\n for userallinfo in rs_query_list:\n #userinfo_dict = {}\n queryuserid = userallinfo['userid']\n opuserinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n\n if opuserinfos_query:\n for opuserinfo in opuserinfos_query:\n userinfo_dict = {}\n companyid = opuserinfo.opcompanyid\n companyinfo = Company.query.filter_by(companyid=companyid).first()\n # 运维用户状态\n company_user_status = opuserinfo.company_user_status\n \n # 修改用户的 mark 字段、设置成运维用户的状态、前端取的是mark 这样前端就不用修改了。\n # begin\n if company_user_status:\n if company_user_status == '3':\n userallinfo['mark'] = 'userenabled'\n elif company_user_status == '4':\n userallinfo['mark'] = 'userdisabled'\n # end\n\n if companyinfo:\n companyname = companyinfo.companyname\n companyid = companyinfo.companyid\n if companyid:\n userinfo_dict[\"companyid\"] = companyid\n else:\n userinfo_dict[\"companyid\"] = ''\n userinfo_dict[\"companyname\"] = companyname\n userinfo_dict[\"userallinfo\"] = userallinfo\n userallinfo_list.append(userinfo_dict)\n\n else:\n userinfo_dict = {}\n companyname = \"未关联公司\"\n userinfo_dict[\"companyid\"] = ''\n userinfo_dict[\"companyname\"] = companyname\n userinfo_dict[\"userallinfo\"] = userallinfo\n userallinfo_list.append(userinfo_dict)\n\n\n print(userallinfo_list)\n\n\n print(len(userallinfo_list))\n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\",'pagetotal':page_total, \"userinfo\": userallinfo_list}\n\"\"\"\n\ndef backstageusers(adminuserid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #所有用户信息\n page = int(page)\n rs_query_list = []\n\n users_query_page = User.query.filter(User.mobile.like('1%')).order_by(User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n users_query = users_query_page.items\n #users_total = len(users_query) / 15\n users_query_total = User.query.filter(User.mobile.like('1%')).order_by(User.createtime.desc()).all()\n users_total = len(users_query_total) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n userid = user_query.userid\n username = user_query.username\n usermobile = user_query.mobile\n userrole = user_query.role\n mark = user_query.mark\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n\n if username != 'chatbot' or usermobile.find('c') == -1:\n rs_query_dict = {'username': username, 'mobile': usermobile,\n 'role': userrole,'logintime':userlogintime,'userid':userid,\n 'mark':mark\n }\n rs_query_list.append(rs_query_dict)\n userinfo_list = []\n\n for userallinfo in rs_query_list:\n userinfo_dict = {}\n queryuserid = userallinfo['userid']\n companyinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n companyid_list = []\n for companyinfo_query in companyinfos_query:\n companyid = companyinfo_query.opcompanyid\n companyid_list.append(companyid)\n companyname_list = []\n companyid_list = []\n for companyid in companyid_list:\n companyinfos_query = Company.query.filter_by(companyid=companyid).first()\n if companyinfos_query:\n companyname = companyinfos_query.companyname\n companyname_list.append(companyname)\n companyid_list.append(companyinfos_query.companyid)\n \n opuserinfo = Opuser.query.filter_by(opuserid=queryuserid,opcompanyid=companyinfos_query.companyid).first()\n # 运维用户状态\n company_user_status = opuserinfo.company_user_status\n # 修改用户的 mark 字段、设置成运维用户的状态、前端取的是mark 这样前端就不用修改了。\n # begin\n if company_user_status:\n if company_user_status == '3':\n userallinfo['mark'] = 'userenabled'\n elif company_user_status == '4':\n userallinfo['mark'] = 'userdisabled'\n # end\n \n userinfo_dict['companyidlist'] = companyid_list\n userinfo_dict['companynamelist'] = companyname_list\n userinfo_dict['userinfo'] = userallinfo\n userinfo_list.append(userinfo_dict)\n\n userallinfo_list = []\n for userinfo in userinfo_list:\n userallinfo_dict = {}\n companyname_list = userinfo['companynamelist']\n companyid_list = userinfo['companyidlist']\n userallinfo = userinfo['userinfo']\n if companyname_list:\n pass\n else:\n companyname_list = ['未关联公司']\n \n for companyname in companyname_list:\n userallinfo_dict['companyname'] = companyname\n userallinfo_dict['userallinfo'] = userallinfo\n \n for companyid in companyid_list:\n userallinfo_dict['companyid'] = companyid\n userallinfo_list.append(userallinfo_dict)\n\n\n print(len(userallinfo_list))\n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\",'pagetotal':page_total, \"userinfo\": userallinfo_list}\n\ndef backstagenewusers(adminuserid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #所有用户信息\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n print(todays_datetime)\n page = int(page)\n rs_query_list = []\n\n users_query_page = User.query.filter(User.mobile.like('1%'), User.createtime >= todays_datetime).order_by(User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n users_query = users_query_page.items\n #users_total = len(users_query) / 15\n users_query_total = User.query.filter(User.mobile.like('1%'), User.createtime >= todays_datetime).order_by(User.createtime.desc()).all()\n users_total = len(users_query_total) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n userid = user_query.userid\n username = user_query.username\n usermobile = user_query.mobile\n userrole = user_query.role\n mark = user_query.mark\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n if username != 'chatbot' or usermobile.find('c') == -1:\n rs_query_dict = {'username': username, 'mobile': usermobile,\n 'role': userrole,'logintime':userlogintime,'userid':userid,\n 'mark':mark\n }\n rs_query_list.append(rs_query_dict)\n \"\"\"\n userinfo_list = []\n for userallinfo in rs_query_list:\n userinfo_dict = {}\n queryuserid = userallinfo['userid']\n companyinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n companyid_list = []\n for companyinfo_query in companyinfos_query:\n companyid = companyinfo_query.opcompanyid\n companyid_list.append(companyid)\n companyname_list = []\n for companyid in companyid_list:\n companyinfos_query = Company.query.filter_by(companyid=companyid).first()\n companyname = companyinfos_query.companyname\n companyname_list.append(companyname)\n userinfo_dict['companynamelist'] = companyname_list\n userinfo_dict['userinfo'] = userallinfo\n userinfo_list.append(userinfo_dict)\n \n userallinfo_list = []\n for userinfo in userinfo_list:\n\n userallinfo_dict = {}\n companyname_list = userinfo['companynamelist']\n userallinfo = userinfo['userinfo']\n if companyname_list:\n pass\n else:\n companyname_list = ['未关联公司']\n\n for companyname in companyname_list:\n userallinfo_dict['companyname'] = companyname\n userallinfo_dict['userallinfo'] = userallinfo\n\n userallinfo_list.append(userallinfo_dict)\n \"\"\"\n userallinfo_list = []\n\n for userallinfo in rs_query_list:\n #userinfo_dict = {}\n queryuserid = userallinfo['userid']\n opuserinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n\n if opuserinfos_query:\n for opuserinfo in opuserinfos_query:\n userinfo_dict = {}\n companyid = opuserinfo.opcompanyid\n companyinfo = Company.query.filter_by(companyid=companyid).first()\n if companyinfo:\n companyname = companyinfo.companyname\n userinfo_dict[\"companyname\"] = companyname\n userinfo_dict[\"userallinfo\"] = userallinfo\n userallinfo_list.append(userinfo_dict)\n\n else:\n userinfo_dict = {}\n companyname = \"未关联公司\"\n userinfo_dict[\"companyname\"] = companyname\n userinfo_dict[\"userallinfo\"] = userallinfo\n userallinfo_list.append(userinfo_dict)\n\n print(len(userallinfo_list))\n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\",'pagetotal':page_total, \"userinfo\": userallinfo_list}\n\n\"\"\"\ndef backstagesearchusersmobile(adminuserid, token, page, mobile):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #所有用户信息\n page = int(page)\n rs_query_list = []\n users_query_page = User.query.filter(User.mobile.like('%' + mobile + '%')).order_by(\n User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n users_query = users_query_page.items\n users_query1 = User.query.filter(User.mobile.like('%' + mobile + '%')).order_by(User.createtime.desc()).all()\n users_total = len(users_query1) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n userid = user_query.userid\n username = user_query.username\n usermobile = user_query.mobile\n userrole = user_query.role\n mark = user_query.mark\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n if username != 'chatbot' or usermobile.find('c') == -1:\n rs_query_dict = {'username': username, 'mobile': usermobile,\n 'role': userrole, 'logintime': userlogintime, 'userid': userid,\n 'mark':mark\n }\n rs_query_list.append(rs_query_dict)\n \n userinfo_list = []\n for userallinfo in rs_query_list:\n userinfo_dict = {}\n queryuserid = userallinfo['userid']\n companyinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n companyid_list = []\n for companyinfo_query in companyinfos_query:\n companyid = companyinfo_query.opcompanyid\n companyid_list.append(companyid)\n companyname_list = []\n for companyid in companyid_list:\n companyinfos_query = Company.query.filter_by(companyid=companyid).first()\n companyname = companyinfos_query.companyname\n companyname_list.append(companyname)\n userinfo_dict['companynamelist'] = companyname_list\n userinfo_dict['userinfo'] = userallinfo\n userinfo_list.append(userinfo_dict)\n\n userallinfo_list = []\n for userinfo in userinfo_list:\n\n userallinfo_dict = {}\n companyname_list = userinfo['companynamelist']\n userallinfo = userinfo['userinfo']\n if companyname_list:\n pass\n else:\n companyname_list = ['未关联公司']\n\n for companyname in companyname_list:\n userallinfo_dict['companyname'] = companyname\n userallinfo_dict['userallinfo'] = userallinfo\n\n userallinfo_list.append(userallinfo_dict)\n \n userallinfo_list = []\n\n for userallinfo in rs_query_list:\n #userinfo_dict = {}\n queryuserid = userallinfo['userid']\n opuserinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n\n if opuserinfos_query:\n for opuserinfo in opuserinfos_query:\n userinfo_dict = {}\n companyid = opuserinfo.opcompanyid\n companyinfo = Company.query.filter_by(companyid=companyid).first()\n if companyinfo:\n companyname = companyinfo.companyname\n userinfo_dict[\"companyname\"] = companyname\n userinfo_dict[\"userallinfo\"] = userallinfo\n userallinfo_list.append(userinfo_dict)\n\n else:\n userinfo_dict = {}\n companyname = \"未关联公司\"\n userinfo_dict[\"companyname\"] = companyname\n userinfo_dict[\"userallinfo\"] = userallinfo\n userallinfo_list.append(userinfo_dict)\n\n print(len(userallinfo_list))\n print(userallinfo_list)\n\n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\",'pagetotal':page_total, \"userinfo\": userallinfo_list}\n\"\"\"\n\n\ndef backstagesearchusersmobile(adminuserid, token, page, mobile):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #所有用户信息\n page = int(page)\n rs_query_list = []\n users_query_page = User.query.filter(User.mobile.like('%' + mobile + '%')).order_by(\n User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n #users_query = users_query_page.items\n users_query = User.query.filter(User.mobile.like('%' + mobile + '%')).order_by(User.createtime.desc()).all()\n users_total = len(users_query) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n userid = user_query.userid\n username = user_query.username\n usermobile = user_query.mobile\n userrole = user_query.role\n mark = user_query.mark\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n if username != 'chatbot' or usermobile.find('c') == -1:\n rs_query_dict = {'username': username, 'mobile': usermobile,\n 'role': userrole, 'logintime': userlogintime, 'userid': userid,\n 'mark':mark\n }\n rs_query_list.append(rs_query_dict)\n\n userallinfo_list = []\n\n for userallinfo in rs_query_list:\n #userinfo_dict = {}\n queryuserid = userallinfo['userid']\n opuserinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n\n if opuserinfos_query:\n for opuserinfo in opuserinfos_query:\n userinfo_dict = {}\n companyid = opuserinfo.opcompanyid\n companyinfo = Company.query.filter_by(companyid=companyid).first()\n \n\n userallinfocopy = {'username': userallinfo['username'],\n 'mobile': userallinfo['mobile'],\n 'role': userallinfo['role'],\n 'logintime': userallinfo['logintime'],\n 'userid': userallinfo['userid'],\n 'mark':userallinfo['mark'] }\n\n if opuserinfo.company_user_status == '3':\n userallinfocopy['mark'] = 'userenabled'\n elif opuserinfo.company_user_status == '4':\n userallinfocopy['mark'] = 'userdisabled'\n userinfo_dict[\"userallinfo\"] = userallinfocopy\n if companyinfo:\n companyname = companyinfo.companyname\n userinfo_dict[\"companyid\"] = companyinfo.companyid\n userinfo_dict[\"companyname\"] = companyname\n userallinfo_list.append(userinfo_dict)\n else:\n userinfo_dict = {}\n companyname = \"未关联公司\"\n userinfo_dict[\"companyid\"] = ''\n userinfo_dict[\"companyname\"] = companyname\n userinfo_dict[\"userallinfo\"] = userallinfo\n userallinfo_list.append(userinfo_dict)\n \n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\",'pagetotal':page_total, \"userinfo\": userallinfo_list}\n\n\n\n\n\n\n\"\"\"\ndef backstagesearchuserscompany(adminuserid, token, page, searchcompanyname):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n page = int(page)\n rs_query_list = []\n search_companyid_list = []\n companys_query_page = Company.query.filter(Company.companyname.like('%' + searchcompanyname + '%')).order_by(\n Company.createtime.desc()).paginate(page, per_page=20, error_out=False)\n companys_query = companys_query_page.items\n users_total = len(companys_query) / 15\n page_total = math.ceil(users_total)\n for company_query in companys_query:\n search_company_dict = {}\n search_company_dict['companyid'] = company_query.companyid\n search_company_dict['companyname'] = company_query.companyname\n\n search_companyid_list.append(search_company_dict)\n\n search_opuserid_list = []\n for searchcompanyidinfo in search_companyid_list:\n\n opusers_query = Opuser.query.filter_by(opcompanyid=searchcompanyidinfo['companyid']).all()\n for opuser_query in opusers_query:\n searchopuserid = opuser_query.opuserid\n searchopuserrole = opuser_query.oprole\n if searchopuserrole != '5' and searchopuserid:\n searchopuser_dict = {\n \"companyname\": searchcompanyidinfo['companyname'],\n \"userallinfo\": {\n \"userid\": searchopuserid,\n }\n }\n search_opuserid_list.append(searchopuser_dict)\n lastuserinfo_list = []\n print(search_opuserid_list)\n for useridinfo in search_opuserid_list:\n\n queryuserid = useridinfo['userallinfo']['userid']\n userinfo_query = User.query.filter_by(userid=queryuserid).first()\n username = userinfo_query.username\n usermobile = userinfo_query.mobile\n userlogintime = userinfo_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n userrole = userinfo_query.role\n mark = userinfo_query.mark\n useridinfo['userallinfo']['username'] = username\n useridinfo['userallinfo']['mobile'] = usermobile\n useridinfo['userallinfo']['logintime'] = userlogintime\n useridinfo['userallinfo']['role'] = userrole\n useridinfo['userallinfo']['mark'] = mark\n lastuserinfo_list.append(useridinfo)\n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\", 'pagetotal':page_total,\"userinfo\": lastuserinfo_list}\n\"\"\"\n\ndef backstagesearchuserscompany(adminuserid, token, page, searchcompanyname):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n page = int(page)\n rs_query_list = []\n search_companyid_list = []\n companys_query_page = Company.query.filter(Company.companyname.like('%' + searchcompanyname + '%')).order_by(\n Company.createtime.desc()).paginate(page, per_page=20, error_out=False)\n companys_query = companys_query_page.items\n users_total = len(companys_query) / 15\n page_total = math.ceil(users_total)\n for company_query in companys_query:\n search_company_dict = {}\n search_company_dict['companyid'] = company_query.companyid\n search_company_dict['companyname'] = company_query.companyname\n\n search_companyid_list.append(search_company_dict)\n\n search_opuserid_list = []\n for searchcompanyidinfo in search_companyid_list:\n\n opusers_query = Opuser.query.filter_by(opcompanyid=searchcompanyidinfo['companyid']).all()\n for opuser_query in opusers_query:\n searchopuserid = opuser_query.opuserid\n searchopuserrole = opuser_query.oprole\n if searchopuserrole != '5' and searchopuserid:\n searchopuser_dict = {\n \"companyid\": searchcompanyidinfo['companyid'],\n \"companyname\": searchcompanyidinfo['companyname'],\n \"userallinfo\": {\n \"userid\": searchopuserid,\n }\n }\n search_opuserid_list.append(searchopuser_dict)\n lastuserinfo_list = []\n print(search_opuserid_list)\n for useridinfo in search_opuserid_list:\n\n queryuserid = useridinfo['userallinfo']['userid']\n userinfo_query = User.query.filter_by(userid=queryuserid).first()\n username = userinfo_query.username\n usermobile = userinfo_query.mobile\n userlogintime = userinfo_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n userrole = userinfo_query.role\n mark = userinfo_query.mark\n useridinfo['userallinfo']['username'] = username\n useridinfo['userallinfo']['mobile'] = usermobile\n useridinfo['userallinfo']['logintime'] = userlogintime\n useridinfo['userallinfo']['role'] = userrole\n\n # 查询运维用户的状态 begin\n cpmpanyid = useridinfo['companyid']\n opuser = Opuser.query.filter_by(opuserid=queryuserid,opcompanyid=cpmpanyid).first()\n if opuser:\n if opuser.company_user_status == '3':\n useridinfo['userallinfo']['mark'] = 'userenabled'\n elif opuser.company_user_status == '4':\n useridinfo['userallinfo']['mark'] = 'userdisabled'\n # end\n\n lastuserinfo_list.append(useridinfo)\n db.session.close()\n return {\"status\":0, \"msg\": \"查询成功\", 'pagetotal':page_total,\"userinfo\": lastuserinfo_list}\n\"\"\"\ndef backstagesearchusersall(adminuserid, token, page, mobile, searchcompanyname):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n page = int(page)\n search_userinfo_list = []\n userss_query_page = db.session.query(User, Company).filter(User.mobile.like('%' + mobile + '%')).filter(Company.companyname.like('%' + searchcompanyname + '%')).order_by(\n User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n\n users_query = userss_query_page.items\n users_total = len(users_query) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n print(user_query)\n search_user_dict = {}\n userinfo = {}\n userinfo['userid'] = user_query[0].userid\n userinfo['username'] = user_query[0].username\n userinfo['mobile'] = user_query[0].mobile\n userlogintime = user_query[0].logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n userinfo['logintime'] = userlogintime\n userinfo['role'] = user_query[0].role\n userinfo['mark'] = user_query[0].mark\n search_user_dict['companyname'] = user_query[1].companyname\n search_user_dict['userallinfo'] = userinfo\n\n search_userinfo_list.append(search_user_dict)\n print(search_userinfo_list)\n db.session.close()\n return {\"status\": 0, \"msg\": \"查询成功\",'pagetotal':page_total, \"userinfo\": search_userinfo_list}\n\"\"\"\n\ndef backstagesearchusersall(adminuserid, token, page, mobile, searchcompanyname):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n page = int(page)\n search_userinfo_list = []\n userss_query_page = db.session.query(User, Company).filter(User.mobile.like('%' + mobile + '%')).filter(Company.companyname.like('%' + searchcompanyname + '%')).order_by(\n User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n userss_query = db.session.query(User, Company).filter(User.mobile.like('%' + mobile + '%')).filter(Company.companyname.like('%' + searchcompanyname + '%')).order_by(User.createtime.desc()).all()\n users_query = userss_query_page.items\n users_total = len(userss_query) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n print(user_query)\n search_user_dict = {}\n userinfo = {}\n userinfo['userid'] = user_query[0].userid\n userinfo['username'] = user_query[0].username\n userinfo['mobile'] = user_query[0].mobile\n userlogintime = user_query[0].logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n userinfo['logintime'] = userlogintime\n userinfo['role'] = user_query[0].role\n userinfo['mark'] = user_query[0].mark\n \n opuserinfo = Opuser.query.filter_by(opuserid=userinfo['userid'],opcompanyid=user_query[1].companyid).first()\n if opuserinfo:\n if opuserinfo.company_user_status == '3':\n userinfo['mark'] = 'userenabled'\n elif opuserinfo.company_user_status == '4':\n userinfo['mark'] = 'userdisabled'\n\n search_user_dict['companyid'] = user_query[1].companyid\n search_user_dict['companyname'] = user_query[1].companyname\n search_user_dict['userallinfo'] = userinfo\n\n search_userinfo_list.append(search_user_dict)\n print(search_userinfo_list)\n db.session.close()\n return {\"status\": 0, \"msg\": \"查询成功\",'pagetotal':page_total, \"userinfo\": search_userinfo_list}\n\n\ndef backstagetourist(adminuserid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n page = int(page)\n search_userinfo_list = []\n users_query_page = User.query.filter_by(role='1').order_by(\n User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n users_query = users_query_page.items\n users_total = len(users_query) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n search_user_dict = {}\n userinfo = {}\n userinfo['userid'] = user_query.userid\n userinfo['username'] = user_query.username\n userinfo['mobile'] = user_query.mobile\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n userinfo['logintime'] = userlogintime\n userinfo['role'] = user_query.role\n userinfo['mark'] = user_query.mark\n search_user_dict['companyname'] = None\n search_user_dict['userallinfo'] = userinfo\n\n search_userinfo_list.append(search_user_dict)\n print(search_userinfo_list)\n db.session.close()\n return {\"status\": 0, \"msg\": \"查询成功\", 'pagetotal':page_total,\"userinfo\": search_userinfo_list}\n\n\ndef backstageuserstopped(adminuserid, token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n page = int(page)\n search_userinfo_list = []\n users_query_page = User.query.filter_by(mark=\"userdisabled\").order_by(\n User.createtime.desc()).paginate(page, per_page=20, error_out=False)\n users_query = users_query_page.items\n users_total = len(users_query) / 15\n page_total = math.ceil(users_total)\n for user_query in users_query:\n opuser = Opuser.query.filter_by(opuserid=user_query.userid).first()\n if opuser:\n company = Company.query.filter_by(companyid=opuser.opcompanyid).first()\n search_user_dict = {}\n userinfo = {}\n userinfo['userid'] = user_query.userid\n userinfo['username'] = user_query.username\n userinfo['mobile'] = user_query.mobile\n userinfo['company'] = company.companyname\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(round(time.mktime(userlogintime.timetuple()) * 1000))\n userinfo['logintime'] = userlogintime\n userinfo['role'] = user_query.role\n userinfo['mark'] = user_query.mark\n search_user_dict['companyname'] = company.companyname\n search_user_dict['userallinfo'] = userinfo\n\n search_userinfo_list.append(search_user_dict)\n print(search_userinfo_list)\n db.session.close()\n return {\"status\": 0, \"msg\": \"查询成功\", 'pagetotal':page_total,\"userinfo\": search_userinfo_list}\n\n\n\n\n\"\"\"\ndef userdisable(adminuserid, token, userdisable, userid):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n\n return {\"status\": 0, \"msg\": \"暂未支持\"}\n\"\"\"\n\"\"\"\ndef userdelete(adminuserid, token, userid):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #所有用户信息\n\n return {\"status\": 0, \"msg\": \"暂未支持\"}\n\"\"\"\n" }, { "alpha_fraction": 0.6290155649185181, "alphanum_fraction": 0.6373056769371033, "avg_line_length": 32.877193450927734, "blob_id": "7a7dbe27897f378c64db859fed3537dd5e538c8a", "content_id": "c60e5cca4338bf3ef8ff9c5d462fdd02b1f8eaf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1996, "license_type": "no_license", "max_line_length": 97, "num_lines": 57, "path": "/upload/image.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from model import *\nimport sqlalchemy\nimport random\nimport string\n\n\ndef generate_random_str(randomlength=16):\n \"\"\"\n 生成一个指定长度的随机字符串,其中\n string.digits=0123456789\n string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n \"\"\"\n str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]\n random_str = ''.join(str_list)\n return random_str\n\n\ndef imageurl_update(usertoken, userid, imageurl):\n try:\n if usertoken != '11111':\n return {'status': 1, 'msg': 'token 不可用'}\n\n user_image_query = User.query.filter_by(userid=userid).first()\n user_image_query.profile = imageurl\n db.session.commit()\n\n print(user_image_query.mobile)\n username = user_image_query.username\n\n mobile = user_image_query.mobile\n role = user_image_query.role\n db.session.close()\n return {'status': 0, 'msg': '修改头像成功', 'mobile': mobile, 'username':username,\n 'userid': userid, 'role':role, 'imageUrl': imageurl}\n except sqlalchemy.exc.OperationalError:\n return {'Oooops': 'There is a problem with the database'}\n\ndef image_insert(usertoken, userid, imageurl):\n try:\n\n if usertoken != '11111':\n return {'status': 1, 'msg': 'token不可用'}\n\n insert_image = Upload(userid=userid, imageurl=imageurl)\n db.session.add(insert_image)\n db.session.commit()\n user_image_query = User.query.filter_by(userid=userid).first()\n username = user_image_query.username\n mobile = user_image_query.mobile\n role = user_image_query.role\n db.session.close()\n\n return {'status': 0, 'msg': '上传成功', 'mobile': mobile, 'username': username,\n 'userid': userid, 'role': role, 'uploadUrl': imageurl}\n\n except sqlalchemy.exc.OperationalError:\n return {'Oooops': 'There is a problem with the database'}" }, { "alpha_fraction": 0.7330096960067749, "alphanum_fraction": 0.7718446850776672, "avg_line_length": 50.25, "blob_id": "b72456eb9304bdbedbca28dc5aee72088e4a040a", "content_id": "a039afb734fe709ddac3b5550ee538d1418918a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 206, "license_type": "no_license", "max_line_length": 108, "num_lines": 4, "path": "/upload/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/chatupload . -f Dockerfile\n#docker stop chatupload\n#docker rm chatupload\n#docker run -d -p 6000:6000 -v /root/mychat/upload/upload:/data/upload --name=chatupload mychat/chatupload\n\n" }, { "alpha_fraction": 0.7317073345184326, "alphanum_fraction": 0.7560975551605225, "avg_line_length": 39, "blob_id": "ce078d9f43314842f5996dcc2c24dfa80ab19b07", "content_id": "21d6d1ecca29146b45460be88780c52afacbb2ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 41, "license_type": "no_license", "max_line_length": 39, "num_lines": 1, "path": "/chatbot-youke1/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/chatbot-youke1 .\n\n" }, { "alpha_fraction": 0.7599999904632568, "alphanum_fraction": 0.7599999904632568, "avg_line_length": 48, "blob_id": "2f406569039d6ab8abf8caa0b9b9beeb7767d892", "content_id": "854f406e4644b9dd1f278c4fa89d06146e0a01f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 50, "license_type": "no_license", "max_line_length": 48, "num_lines": 1, "path": "/houtaiapi/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/houtaiapi . -f Dockerfile\n\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7428571581840515, "avg_line_length": 33, "blob_id": "5aba0380dc0aefcf53049342317aa07e4dbddcfa", "content_id": "056a881d1bfb3e9ff848387beb21f3cac901ec3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 35, "license_type": "no_license", "max_line_length": 33, "num_lines": 1, "path": "/chatbot1/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/chatbot1 .\n\n" }, { "alpha_fraction": 0.7316561937332153, "alphanum_fraction": 0.7463312149047852, "avg_line_length": 42.3636360168457, "blob_id": "faede2eed9ce25156cfc3292b245340cc1cd0c4d", "content_id": "18512c6655fdede8aba54314880e096f3a99406c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 962, "license_type": "no_license", "max_line_length": 118, "num_lines": 22, "path": "/chatapi/Dockerfile", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "FROM python:3.6.7-jessie \n\n#RUN echo \"https://mirrors.aliyun.com/alpine/v3.8/main\" > /etc/apk/repositories\n#RUN echo \"https://mirrors.aliyun.com/alpine/v3.8/community\" >> /etc/apk/repositories \nWORKDIR /data\n#RUN apk update && apk add gcc libc-dev pcre pcre-dev libffi-dev openssl-dev \nRUN apt-get update && apt-get install curl -y\nRUN pip3 install -i https://pypi.douban.com/simple flask_socketio flask flask_sqlalchemy sqlalchemy pymysql requests \nRUN pip3 install -i https://pypi.douban.com/simple uwsgi\nRUN pip3 install -i https://pypi.douban.com/simple demjson\nRUN pip3 install -i https://pypi.douban.com/simple socketIO-client requests\n\n#设置时区\nRUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone\nRUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime\n\n\nADD . /data\n#CMD [\"python3\", \"http_chat.py\"]\nRUN python3 setup.py sdist\nRUN python3 setup.py install\nCMD [\"uwsgi\", \"--ini\", \"chatapi.ini\"]\n" }, { "alpha_fraction": 0.5389159321784973, "alphanum_fraction": 0.5552007555961609, "avg_line_length": 33.79722213745117, "blob_id": "0fbd8989640ae5a663a0292b50695490d7b69576", "content_id": "ce6a745f353363e52bf80d4a3d509d7fc39d17ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12793, "license_type": "no_license", "max_line_length": 152, "num_lines": 360, "path": "/websocket/websocket_chat.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "# coding=utf-8\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO, emit\nimport requests\nimport json\nimport random, string\n\n\n\nfrom APISender import APISender\nfrom base.APIMessage import *\nfrom base.APIConstants import *\nfrom APITools import *\nfrom APISubscribe import *\nimport sys\n\n#from push_msg import *\n\n\napp = Flask(__name__)\nsocketio = SocketIO(app)\nConstants.use_official() \nfrom flask_socketio import join_room, leave_room\n\n\n#apiserver = 'http://127.0.0.1:5000'\napiserver = 'http://chatapi:5000'\n#apiserver = 'http://139.196.107.14:5000'\nheader = {'Content-Type': 'application/json'}\n\n#生成一个随机字符串\ndef generate_random_str(randomlength=16):\n \"\"\"\n 生成一个指定长度的随机字符串,其中\n string.digits=0123456789\n string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n \"\"\"\n str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]\n random_str = ''.join(str_list)\n return random_str\n\n#监控conn\[email protected]('conn')\ndef on_connect(msg):\n print('msg is :', msg)\n emit('connstatus', {'data': 'Connected'})\n\n#监控talk\[email protected]('talk')\ndef talk_connect(msg):\n print(msg)\n print(msg)\n jieshoumessage = msg['msg']\n print(type(msg))\n if 'msgid' in msg:\n msgid = msg['msgid']\n else:\n msgid = None\n if \"ids\" in msg:\n ids = msg[\"ids\"]\n result = push_msg_to_android(ids[0],'jjjbbbkjjk', 'com.domain.operationrobot', '消息通知', '有人@你', 0,'payload')\n push_msg_to_android(\"uqJJFUhTHJC4nYlGut4v1hJCj\", 'jjjbbbkjjk', 'com.domain.operationrobot', '消息通知', '有人@你', 0, 'payload')\n push_msg_to_ios(ids[0],'dddasdadad', 'com.domain.operationrobot', '消息通知', '有人@你', 'body')\n print(\"推送结果:\",result)\n print(\"用户id\",ids)\n print(\"用户id\",ids)\n print(\"用户id\",ids)\n #else:\n #ids = None\n token = msg['token']\n companyid = msg['companyid']\n print('token is', token)\n if companyid:\n user_profile_rs = requests.get(apiserver + '/api/v1/user?token=' + token + '&companyid=' + companyid, headers=header)\n else:\n user_profile_rs = requests.get(apiserver + '/api/v1/youke?token=' + token,headers=header)\n\n print(user_profile_rs.json())\n\n user_role = user_profile_rs.json()['role']\n user_companyrole = user_profile_rs.json()['companyrole']\n if user_role == '1' or user_role == '2':\n room = generate_random_str(24)\n else:\n room = user_profile_rs.json()['companyname']\n\n msg['imageUrl'] = user_profile_rs.json()['imageUrl']\n msg['mobile'] = user_profile_rs.json()['mobile']\n msg['username'] = user_profile_rs.json()['opuser_name']\n msg['userid'] = user_profile_rs.json()['userid']\n del msg['token']\n join_room(room)\n print('room is:', room)\n if 'role' in msg or jieshoumessage == 'joinroom':\n print('ccccccccccccc')\n pass\n else:\n response = {'data': msg}\n print('uuuuuuuuuuuuu')\n\n if user_role != '1' and user_role != '2':\n if msgid:\n addlixianmessage_payload = {'token':token, 'companyid':companyid, 'msgid':msgid, 'message': msg}\n addlixianmessage_rs = requests.post(apiserver + '/api/v1/message',data=json.dumps(addlixianmessage_payload),\n headers=header)\n if addlixianmessage_rs.status_code == 200:\n pass\n else:\n print(\"Something worang\")\n\n emit('talkstatus', response, room=room)\n\n\n\n#监控机器人\[email protected]('chatbot')\ndef chatbot_connect(msg):\n print('chatbot msg', msg)\n print(\"$\"*100)\n print(\"6666666666666666666\")\n print(type(msg))\n print(type(msg))\n print(type(msg))\n print(type(msg))\n print(type(msg))\n print(type(msg))\n print(\"&\"*100)\n token = msg['data']['token']\n if 'companyid' in msg['data']:\n companyid = msg['data']['companyid']\n else:\n companyid = None\n #company_info_rs = requests.get(apiserver + '/backstage/companymanage/companyinfo?token=' + token + '&companyid=' + companyid,headers=header)\n #print(company_info_rs.json())\n\n if 'msgid' in msg['data']:\n msgid = msg['data']['msgid']\n else:\n msgid = None\n \"\"\" \n if 'type' in msg['data']:\n type = msg['data']['type']\n else:\n type = None\n \"\"\"\n chatbottype = msg['data']['type']\n if companyid:\n user_profile_rs = requests.get(apiserver + '/api/v1/user?token=' + token + '&companyid=' + companyid, headers=header)\n else:\n user_profile_rs = requests.get(apiserver + '/api/v1/youke?token=' + token,headers=header)\n print(user_profile_rs.json())\n print(user_profile_rs.json())\n if 'role' in user_profile_rs.json():\n role = user_profile_rs.json()['role']\n if 'oprole' in user_profile_rs.json():\n oprole = user_profile_rs.json()['oprole']\n user_companyrole = user_profile_rs.json()['companyrole']\n print(role)\n \n if chatbottype == 11:\n if companyid:\n \n company_info_rs = requests.get(apiserver + '/backstage/companymanage/opusersinfo?token=' + token + '&companyid=' + companyid,headers=header)\n company_info_rs = company_info_rs.json()\n print(company_info_rs)\n applyopusername = user_profile_rs.json()['opuser_name']\n host = msg[\"data\"][\"rootbean\"][\"hostip\"]\n msg1 = \"%s申请重启服务器%s\"%(applyopusername,host)\n print(msg1*10)\n #这个地方还要加上审核员\n for temp in company_info_rs[\"opuserinfo\"]:\n result1 = push_msg_to_android(temp[\"opuserid\"], token, 'com.domain.operationrobot', '消息通知', msg1, 0, 'payload')\n print(result1)\n result2 =push_msg_to_ios(temp[\"opuserid\"], token, 'com.domain.operationrobot', '消息通知', msg1, 'body')\n print(result2)\n \n if role == '1' or role == '2':\n room = 'chatbotyouke11111'\n else:\n room = user_profile_rs.json()['companyname']\n join_room(room)\n print('room is:', room)\n #chatbottype = msg['data']['type']\n if chatbottype == 1:\n print('11111111111111111')\n if 'rootbean' in msg['data'] and msg['data']['rootbean']['msg'] == 'joinchatbotroom':\n print('检查rootbean 是否存在', msg['data']['rootbean']['msg'])\n pass\n else:\n msg['data']['role'] = role\n msg['data']['oprole'] = oprole\n msg['data']['imageUrl'] = user_profile_rs.json()['imageUrl']\n msg['data']['mobile'] = user_profile_rs.json()['mobile']\n msg['data']['username'] = user_profile_rs.json()['opuser_name']\n msg['data']['userid'] = user_profile_rs.json()['userid']\n msg['data']['companyid'] = user_profile_rs.json()['companyid']\n del msg['data']['token']\n #response = {'data': {'type':1, 'rootbean':{'msg': '你好'}}}\n if role != '1' and role != '2':\n if msgid:\n print(\"到底有没有\")\n addlixianmessage_payload = {'token': token, 'companyid': companyid, 'msgid': msgid, 'message': msg}\n addlixianmessage_rs = requests.post(apiserver + '/api/v1/message',\n data=json.dumps(addlixianmessage_payload),\n headers=header)\n if addlixianmessage_rs.status_code == 200:\n pass\n else:\n print(\"Something worang\")\n print('发送数据中')\n emit('chatbotstatus', msg, room=room)\n elif chatbottype == 2:\n print('2222222222222')\n msg['data']['role'] = role\n msg['data']['oprole'] = oprole\n msg['data']['imageUrl'] = user_profile_rs.json()['imageUrl']\n msg['data']['mobile'] = user_profile_rs.json()['mobile']\n msg['data']['username'] = user_profile_rs.json()['opuser_name']\n msg['data']['userid'] = user_profile_rs.json()['userid']\n msg['data']\n del msg['data']['token']\n print(msg)\n print('msgid', msgid)\n if role != '1' and role != '2':\n if msgid:\n print(\"到底有没有\")\n addlixianmessage_payload = {'token':token, 'companyid':companyid, 'msgid':msgid, 'message': msg}\n addlixianmessage_rs = requests.post(apiserver + '/api/v1/message',data=json.dumps(addlixianmessage_payload),\n headers=header)\n if addlixianmessage_rs.status_code == 200:\n pass\n else:\n print(\"Something worang\")\n emit('chatbotstatus', msg, room=room)\n\n\n elif chatbottype >= 3:\n print('333333333')\n print(msg)\n print(\"$\"*100)\n print(type(msg))\n print(type(msg))\n print(type(msg))\n print(type(msg))\n print(type(msg))\n print(type(msg))\n print(\"&\"*100)\n msg['data']['role'] = role\n msg['data']['oprole'] = oprole\n msg['data']['imageUrl'] = user_profile_rs.json()['imageUrl']\n msg['data']['mobile'] = user_profile_rs.json()['mobile']\n msg['data']['username'] = user_profile_rs.json()['opuser_name']\n msg['data']['userid'] = user_profile_rs.json()['userid']\n del msg['data']['token']\n if role != '1' and role != '2':\n if msgid:\n addlixianmessage_payload = {'token':token, 'companyid':companyid, 'msgid':msgid, 'message': msg}\n addlixianmessage_rs = requests.post(apiserver + '/api/v1/message',data=json.dumps(addlixianmessage_payload),\n headers=header)\n if addlixianmessage_rs.status_code == 200:\n pass\n else:\n print(\"Something worang\")\n\n \n emit('chatbotstatus', msg, room=room)\n\n#推送安卓消息\ndef push_msg_to_android(userid,usertoken, package_name, title, description, pass_through,payload):\n APP_SecKey = r\"lsoNVMUZH69YvcsLR6SHNQ==\"\n result_code = 0\n try:\n\n\n # build android message\n message = PushMessage() \\\n .restricted_package_name(package_name) \\\n .title(title).description(description) \\\n .pass_through(pass_through).payload(payload) \\\n .extra({Constants.extra_param_notify_effect: Constants.notify_launcher_activity})\n\n except:\n print(\"get parameters value error ! \", sys.exc_info()[0])\n msg = \"get parameters value error \"\n result = {\n \"msg\": msg,\n \"status\": result_code\n }\n return result\n\n try:\n sender = APISender(APP_SecKey)\n recv = sender.send_to_user_account(message.message_dict(), userid)\n print(recv)\n\n except:\n print(\"send msg was failed ! \", sys.exc_info()[0])\n result_code = 1\n msg = \"send msg was failed \"\n finally:\n msg = \"succecss\"\n result = {\n \"msg\": msg,\n \"status\": result_code\n }\n return result\n\n\n\n#推送ios消息\ndef push_msg_to_ios(userid,usertoken, package_name, title, subtitle, body):\n APP_SecKey = r\"XWd6+oOcSmliC4jJJsdrcw==\"\n result_code = 0\n try:\n message_ios10 = PushMessage() \\\n .restricted_package_name(package_name) \\\n .aps_title(title) \\\n .aps_subtitle(subtitle) \\\n .aps_body(body) \\\n .aps_mutable_content(\"1\") \\\n .sound_url(\"default\") \\\n .badge(1) \\\n .category(\"action\") \\\n .extra({\"key\": \"value\"})\n\n except:\n print(\"get parameters value error ! \", sys.exc_info()[0])\n result_code = 1\n msg = \"get parameters value error \"\n result = {\n \"msg\": msg,\n \"status\": result_code\n }\n return result\n\n try:\n sender = APISender(APP_SecKey)\n\n recv_ios = sender.send_to_user_account(message_ios10.message_dict_ios(), userid)\n print(recv_ios)\n\n\n tools = APITools(APP_SecKey)\n except:\n print(\"send msg was failed ! \", sys.exc_info()[0])\n result_code = 1\n msg = \"send msg was failed \"\n finally:\n msg = \"succecss\"\n result = {\n \"msg\": msg,\n \"status\": result_code\n }\n return result\n\n#result = push_msg_to_android('uz1NFGfV0Kp64WloxTNq5zmCU','jjjbbbkjjk', 'com.domain.operationrobot', '消息通知', '有人@你', 0,'payload')\n#print(result)\n\nif __name__ == '__main__':\n socketio.run(app, host='0.0.0.0',port=5002)\n" }, { "alpha_fraction": 0.7152777910232544, "alphanum_fraction": 0.7708333134651184, "avg_line_length": 34.75, "blob_id": "3b785432667126ea3ae3a17d8c14e71875bce918", "content_id": "4e9d010aabea5406c7cc1c44875f0052de43e028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 144, "license_type": "no_license", "max_line_length": 62, "num_lines": 4, "path": "/websocket/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/chatroom .\n#docker stop chatsocket\n#docker rm chatsocket\n#docker run -d -p 5002:5002 --name=chatsocket mychat/chatroom\n\n" }, { "alpha_fraction": 0.6549977660179138, "alphanum_fraction": 0.6590499877929688, "avg_line_length": 38.13656234741211, "blob_id": "4f9d988581158c99f62b681de57859af346f3b96", "content_id": "2074afd3609a18f898d0963175cccd2f3a5ce21b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18124, "license_type": "no_license", "max_line_length": 174, "num_lines": 454, "path": "/chatapi/houtai.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from model import *\nimport sqlalchemy\nfrom datetime import datetime, timedelta\nimport time\nfrom urllib.parse import unquote\n\n\ndef backstage(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #公司总数量\n companys_query = Company.query.all()\n totalcompanys = len(companys_query)\n\n #当天新增公司数量\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n #todays_datetime = '2018-10-30 00:00:00'\n newcompanys_query = Company.query.filter(Company.createtime >= todays_datetime).all()\n newcompanys = len(newcompanys_query)\n\n #试用中的公司\n try_companys_query = Company.query.filter_by(companyrole='1').all()\n try_companys = len(try_companys_query)\n\n #用户总数量\n users_query = User.query.all()\n totalusers = len(users_query)\n\n #当天新增用户\n newusers_query = User.query.filter(User.createtime >= todays_datetime).all()\n newusers = len(newusers_query)\n\n backstage_expiredate_query = Backstage.query.first()\n backstage_expiredate = backstage_expiredate_query.companyexpire\n expire_date = todays_datetime + timedelta(days=int(backstage_expiredate))\n try_expire_companys_query = Company.query.filter(Company.companyexpiredate <= expire_date, Company.companyexpiredate >= todays_datetime, Company.companyrole == '2').all()\n expire_companys = len(try_expire_companys_query)\n rs = {'total_companys': totalcompanys, 'new_companys': newcompanys,\n 'try_companys': try_companys,'total_users':totalusers,\n 'new_users': newusers, 'expiring_companys':expire_companys,\n }\n return rs\n\n\ndef backstagecms(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #公司总数量\n rs_query_list = []\n rs_query_dict = {}\n companys_query = Company.query.all()\n for company_query in companys_query:\n companyid = company_query.companyid\n companyname = company_query.companyname\n companyexpire = company_query.companyexpiredate\n companymark = company_query.companymark\n companyrole = company_query.companyrole\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = adminuser_query.opemail\n\n if companyexpire:\n companyexpire = int(time.mktime(companyexpire.timetuple()))\n\n rs_query_dict = {'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\n 'companyexpire': companyexpire,'companymark':companymark,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n }\n rs_query_list.append(rs_query_dict)\n\n return rs_query_list\n\ndef backstagecm(userid, token, urlsearchcompanyname):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n searchcompanyname = unquote(urlsearchcompanyname, 'utf-8')\n #公司总数量\n rs_query_list = []\n rs_query_dict = {}\n companys_query = Company.query.all()\n for company_query in companys_query:\n companyid = company_query.companyid\n companyname = company_query.companyname\n if companyname.find(searchcompanyname) != -1:\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n companymark = company_query.companymark\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = adminuser_query.opemail\n\n if companyexpire:\n companyexpire = int(time.mktime(companyexpire.timetuple()))\n\n rs_query_dict = {'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\n 'companyexpire': companyexpire,'companymark':companymark,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n }\n rs_query_list.append(rs_query_dict)\n\n return rs_query_list\n\ndef backstagetryouts(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #试用公司\n rs_query_list = []\n rs_query_dict = {}\n companys_query = Company.query.filter_by(companyrole='1').all()\n for company_query in companys_query:\n companyid = company_query.companyid\n companyname = company_query.companyname\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = adminuser_query.opemail\n\n if companyexpire:\n companyexpire = int(time.mktime(companyexpire.timetuple()))\n\n rs_query_dict = {'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\n 'companyexpire': companyexpire,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n }\n rs_query_list.append(rs_query_dict)\n\n return rs_query_list\n\ndef backstagecmdelete(token,companyid):\n\n try:\n if token != '11111':\n return {'status': 1, 'msg': 'token不可用'}\n\n company_query = Company.query.filter_by(companyid=companyid).first()\n opusers_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n for opuser in opusers_query:\n companys_query = Opuser.query.filter_by(opuserid=opuser. opuserid).all()\n if len(companys_query) == 1:\n user_query = User.query.filter_by(userid=opuser.opuserid).first()\n user_query.role = 1\n db.session.delete(opuser)\n db.session.delete(company_query)\n db.session.commit()\n return {'status': 0, 'msg': '删除成功'}\n\n except sqlalchemy.exc.OperationalError:\n db.session.close()\n return {'Oooops': 'There is a problem with the database'}\n\ndef save_oper_log(username,companyid,exec_com,ip,hostname,exec_time):\n\n try:\n operation =OperaLog(username=username,companyid=companyid,exec_com=exec_com,ip=ip,hostname=hostname,exec_time=exec_time)\n db.session.add(operation)\n db.session.commit()\n\n return {'status': 0, 'msg': '操作日志保存成功'}\n\n except sqlalchemy.exc.OperationalError:\n db.session.close()\n return {'Oooops': 'There is a problem with the database'}\n\ndef backstageexpiring(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #即将过期\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n print(todays_datetime)\n backstage_expiredate_query = Backstage.query.first()\n backstage_expiredate = backstage_expiredate_query.companyexpire\n print(backstage_expiredate)\n expire_date = todays_datetime + timedelta(days=int(backstage_expiredate))\n print(expire_date)\n try_expire_companys_query = Company.query.filter(Company.companyexpiredate <= expire_date, Company.companyexpiredate >= todays_datetime, Company.companyrole == '2').all()\n print(try_expire_companys_query)\n if try_expire_companys_query is None:\n return []\n rs_query_list = []\n rs_query_dict = {}\n for company_query in try_expire_companys_query:\n companyid = company_query.companyid\n companyname = company_query.companyname\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = adminuser_query.opemail\n\n if companyexpire:\n companyexpire = int(time.mktime(companyexpire.timetuple()))\n\n rs_query_dict = {'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\n 'companyexpire': companyexpire,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n }\n rs_query_list.append(rs_query_dict)\n\n return rs_query_list\n\n\ndef backstageexpired(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #已过期\n todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)\n try_expire_companys_query = Company.query.filter(Company.companyexpiredate <= todays_datetime, Company.companyrole == '2').all()\n if try_expire_companys_query is None:\n return []\n rs_query_list = []\n rs_query_dict = {}\n for company_query in try_expire_companys_query:\n companyid = company_query.companyid\n companyname = company_query.companyname\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = adminuser_query.opemail\n\n if companyexpire:\n companyexpire = int(time.mktime(companyexpire.timetuple()))\n\n rs_query_dict = {'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\n 'companyexpire': companyexpire,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n }\n rs_query_list.append(rs_query_dict)\n\n return rs_query_list\n\n\ndef backstageusers(adminuserid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #所有用户信息\n rs_query_list = []\n users_query = User.query.all()\n for user_query in users_query:\n userid = user_query.userid\n username = user_query.username\n usermobile = user_query.mobile\n userrole = user_query.role\n mark = user_query.mark\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(time.mktime(userlogintime.timetuple()))\n if username != 'chatbot' or usermobile.find('c') == -1:\n rs_query_dict = {'username': username, 'mobile': usermobile,\n 'role': userrole,'logintime':userlogintime,'userid':userid,\n 'mark':mark\n }\n rs_query_list.append(rs_query_dict)\n userinfo_list = []\n for userallinfo in rs_query_list:\n userinfo_dict = {}\n queryuserid = userallinfo['userid']\n companyinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n companyid_list = []\n userallinfo_dict = {}\n for companyinfo_query in companyinfos_query:\n companyid = companyinfo_query.opcompanyid\n companyid_list.append(companyid)\n companyname_list = []\n for companyid in companyid_list:\n companyinfos_query = Company.query.filter_by(companyid=companyid).first()\n companyname = companyinfos_query.companyname\n companyname_list.append(companyname)\n userinfo_dict['companynamelist'] = companyname_list\n userinfo_dict['userinfo'] = userallinfo\n userinfo_list.append(userinfo_dict)\n print(userinfo_list)\n\n return userinfo_list\n\ndef disabledUser(userid, token, disabled):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #修改用户mark\n user_query = User.query.filter_by(userid=userid).first()\n if disabled:\n user_query.mark = disabled\n\n db.session.commit()\n\n rs = {'status':0, 'msg':'设置成功','disabled':disabled}\n return rs\n\ndef disabledCompany(companyid, token, disabled):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #修改用户mark\n company_query = Company.query.filter_by(companyid=companyid).first()\n if disabled:\n company_query.mark = disabled\n\n db.session.commit()\n\n rs = {'status':0, 'msg':'设置成功','disabled':disabled}\n return rs\n\ndef configsGet(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #获取配置\n backstageinfo_query = Backstage.query.first()\n backstageinfo_expire = backstageinfo_query.companyexpire\n backstageinfo_tryoutdate = backstageinfo_query.tryoutdata\n backstageinfo_custom = backstageinfo_query.customerservicemobile\n rs = {'expire':backstageinfo_expire, 'trydate':backstageinfo_tryoutdate, 'customerservice':backstageinfo_custom}\n return rs\n\n\ndef configsChange(userid, token, customerservice, expire, trydate):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #修改后台配置\n backstageinfo_query = Backstage.query.first()\n if customerservice:\n backstageinfo_query.customerservicemobile = customerservice\n if expire:\n backstageinfo_query.companyexpire = expire\n if trydate:\n backstageinfo_query.tryoutdata = trydate\n db.session.commit()\n\n rs = {'status':0, 'msg':'设置成功','expire':expire, 'trydate':trydate, 'customerservice':customerservice}\n return rs\n\ndef coustomMobile(userid, token):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n #修改后台配置\n backstageinfo_query = Backstage.query.first()\n if backstageinfo_query:\n custommobile = backstageinfo_query.customerservicemobile\n\n rs = {'status':0, 'msg':'查询成功','customermobile':custommobile}\n return rs\n\ndef pageUsers(token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n\n #所有用户信息\n rs_query_list = []\n #users_query = User.query.all()\n page = int(page)\n users_query = User.query.order_by(User.createtime.desc()).paginate(page, per_page=10, error_out = False)\n users_page_query = users_query.items\n for user_query in users_page_query:\n userid = user_query.userid\n username = user_query.username\n usermobile = user_query.mobile\n userrole = user_query.role\n userlogintime = user_query.logintime\n if userlogintime:\n userlogintime = int(time.mktime(userlogintime.timetuple()))\n if username != 'chatbot' or usermobile.find('c') == -1:\n rs_query_dict = {'username': username, 'mobile': usermobile,\n 'role': userrole,'logintime':userlogintime,'userid':userid,\n }\n rs_query_list.append(rs_query_dict)\n userinfo_list = []\n for userallinfo in rs_query_list:\n userinfo_dict = {}\n queryuserid = userallinfo['userid']\n companyinfos_query = Opuser.query.filter_by(opuserid=queryuserid).all()\n companyid_list = []\n userallinfo_dict = {}\n for companyinfo_query in companyinfos_query:\n companyid = companyinfo_query.opcompanyid\n companyid_list.append(companyid)\n companyname_list = []\n for companyid in companyid_list:\n companyinfos_query = Company.query.filter_by(companyid=companyid).first()\n companyname = companyinfos_query.companyname\n companyname_list.append(companyname)\n userinfo_dict['companynamelist'] = companyname_list\n userinfo_dict['userinfo'] = userallinfo\n userinfo_list.append(userinfo_dict)\n print(userinfo_list)\n\n return userinfo_list\n\n\n\ndef pageCompanys(token, page):\n if token != '11111':\n return {'status':1, 'msg':'token不可用'}\n rs_query_list = []\n page = int(page)\n companys_query = Company.query.order_by(Company.createtime.desc()).paginate(page, per_page=10, error_out = False)\n companys_page_query = companys_query.items\n for company_query in companys_page_query:\n companyid = company_query.companyid\n companyname = company_query.companyname\n companyexpire = company_query.companyexpiredate\n companyrole = company_query.companyrole\n user_query = Opuser.query.filter_by(opcompanyid=companyid).all()\n totalcompanyusers = len(user_query)\n adminuser_query = Opuser.query.filter_by(opcompanyid=companyid, oprole='4').first()\n adminusername = adminuser_query.opusername\n adminmobile = adminuser_query.opmobile\n admimemail = adminuser_query.opemail\n\n if companyexpire:\n companyexpire = int(time.mktime(companyexpire.timetuple()))\n rs_query_dict = {'companyname': companyname, 'adminusername': adminusername,\n 'adminmobile': adminmobile,'adminemail':admimemail,\n 'companyexpire': companyexpire,\n 'companyrole':companyrole, 'members':totalcompanyusers,\n }\n rs_query_list.append(rs_query_dict)\n\n return rs_query_list\n\n\ndef AdminInfo(username, password):\n #所有用户信息\n\n admin_query = Backstage.query.filter_by(rootname='root').first()\n adminpassword = admin_query.rootpassword\n if username == 'root' and password == adminpassword:\n return {'status':0, 'msg': '登录成功'}\n else:\n return {'status':1, 'msg':'用户名或密码错误'}\n" }, { "alpha_fraction": 0.6943699717521667, "alphanum_fraction": 0.707774817943573, "avg_line_length": 27.69230842590332, "blob_id": "a813ff75666c89f8ca6ecde934232fcde848348d", "content_id": "dfa95a46fba85fd7fd9be35f996ed3fb72d3e633", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 381, "license_type": "no_license", "max_line_length": 99, "num_lines": 13, "path": "/upload/Dockerfile", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "FROM python:3.6.7-jessie\n#FROM mychat/chatapi \nRUN rm -rf /data\nRUN pip3 install uwsgi -i https://pypi.douban.com/simple\n\n#设置时区\nRUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone\n#RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime\n\n\nADD . /data\n#CMD [\"python3\", \"http_chat.py\"]\nCMD [\"uwsgi\", \"--ini\", \"upload.ini\"]\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 46, "blob_id": "339fd24ac43364287e287d4ac5d28da7912ce083", "content_id": "15e7fde27f4bd6e90e7e54a1c271d1c2835932cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 48, "license_type": "no_license", "max_line_length": 46, "num_lines": 1, "path": "/chatapi/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/chatapi . -f Dockerfile\n\n" }, { "alpha_fraction": 0.6770833134651184, "alphanum_fraction": 0.6875, "avg_line_length": 23, "blob_id": "b90d44946ad3c60b7eb420b7ca5f9d563c1beae2", "content_id": "c03f387438d510252950f2d5b6f0be409a22ad6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 96, "license_type": "no_license", "max_line_length": 31, "num_lines": 4, "path": "/chatapi/Dockerfile.builder", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "FROM mychat/httpapi \nRUN apk update && apk add curl\nADD . /data\nCMD [\"python3\", \"http_chat.py\"]\n" }, { "alpha_fraction": 0.6582633256912231, "alphanum_fraction": 0.7366946935653687, "avg_line_length": 38.66666793823242, "blob_id": "9163a4323c4ab13cc03b63baa1606a103ad6ad8a", "content_id": "1ed7dc8f8037a1048d543273d16508df16e5460a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 357, "license_type": "no_license", "max_line_length": 123, "num_lines": 9, "path": "/chatapi/sms.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "message_subject_utf8=$1\nmessage_subject_gb2312=`iconv -t GB2312 -f UTF-8 << EOF\n$message_subject_utf8\nEOF`\n[ $? -eq 0 ] && message_subject=\"$message_subject_gb2312\" || message_subject=\"$message_subject_utf8\"\n\necho $message_subject \n\ncurl \"http://gateway.iems.net.cn/GsmsHttp?username=69828:admin&password=89523028&to=$2&content=$message_subject_gb2312\"\n" }, { "alpha_fraction": 0.5184829831123352, "alphanum_fraction": 0.5263295769691467, "avg_line_length": 40.32472229003906, "blob_id": "4a2ebb55a6daace11164c5f098e9e994716c3981", "content_id": "9c494a080b8dcbddc8ffe028ded74f01a0f9a89c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11676, "license_type": "no_license", "max_line_length": 144, "num_lines": 271, "path": "/chatapi/search_oper_log.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n#coding=utf-8\r\nfrom model import *\r\nimport sys\r\nfrom sqlalchemy import desc\r\nimport os\r\nimport logging\r\nfrom logging.handlers import TimedRotatingFileHandler\r\n\r\nfmt_str = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'\r\nlogging.basicConfig()\r\nfilename_head = os.getcwd() + \"/logs/rebot.log\"\r\nfileshandle = logging.handlers.TimedRotatingFileHandler(filename_head, when=\"midnight\", interval=1, backupCount=30,\r\n encoding='utf-8', delay=False, utc=False)\r\nfileshandle.suffix = \"%Y-%m-%d\"\r\nformatter = logging.Formatter(fmt_str)\r\nfileshandle.setFormatter(formatter)\r\nlogger = logging.getLogger(\"salt_exec\")\r\nlogger.addHandler(fileshandle)\r\nlogger.setLevel(logging.INFO)\r\n\r\nfmt_str = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'\r\nlogging.basicConfig()\r\nfilename_head = os.getcwd() + \"/logs/rebot.log\"\r\nfileshandle = logging.handlers.TimedRotatingFileHandler(filename_head, when=\"midnight\", interval=1, backupCount=30,\r\n encoding='utf-8', delay=False, utc=False)\r\nfileshandle.suffix = \"%Y-%m-%d\"\r\nformatter = logging.Formatter(fmt_str)\r\nfileshandle.setFormatter(formatter)\r\nlogger = logging.getLogger(\"salt_exec\")\r\nlogger.addHandler(fileshandle)\r\nlogger.setLevel(logging.INFO)\r\ndef search_oper_log(usertoken, companyid):\r\n status = 0\r\n #每次查询数量\r\n #count = 10\r\n all_page = 1\r\n\r\n result = {\r\n \"result\": [],\r\n \"status\": status\r\n }\r\n temp_result = []\r\n try:\r\n #c1 = OperaLog.query.filter_by(companyid=companyid).count()\r\n #all_page = math.ceil(int(c1)/count)\r\n # all_company_result = OperaLog.query.filter_by(companyid=companyid).order_by(desc(OperaLog.id)).limit(offset_begin).offset(count).all()\r\n\r\n all_company_result = OperaLog.query.filter_by(companyid=companyid).order_by(desc(OperaLog.id)).all()\r\n if len(all_company_result) == 0:\r\n #查询为空\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"未查找到符合条件的操作日志.\"\r\n result[\"status\"] = 1\r\n return result\r\n for item in all_company_result:\r\n\r\n sql = \"\"\"select b.id,b.command_id, b.command, b.command_displayname, b.remark from \r\n tbl_operacommand b where b.command like \"%{i}%\" ;\"\"\".format(i=item.exec_com)\r\n command_search_result = db.session.execute(sql).fetchall()\r\n if len(command_search_result) > 0:\r\n command_desc = command_search_result[0][\"command_displayname\"]\r\n else:\r\n command_desc = item.exec_com\r\n user_image = User.query.filter_by(username=item.username).limit(1).all()\r\n if len(user_image) == 0:\r\n image_url = \"null\"\r\n else:\r\n image_url = str(user_image[0].profile)\r\n msg = \" \" + item.hostname + \"( ip :\" + item.ip + \")\"\r\n one_record = {\"username\": item.username, \"user_image\": image_url,\r\n \"exec_time\": item.exec_time.strftime(\"%Y-%m-%d %H:%M:%S\"), \"operating_command\": command_desc,\r\n \"msg\": msg}\r\n temp_result.append(one_record)\r\n\r\n result[\"result\"] = temp_result\r\n except:\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"get operation log was failed ! pls connect admin\"\r\n result[\"status\"] = 1\r\n logger.error(result[\"msg\"])\r\n logger.error(sys.exc_info()[0])\r\n finally:\r\n result[\"all_page\"] = all_page\r\n return result\r\n\r\n\r\ndef operation_search_condition(usertoken, companyid, search_command=None, search_user=None):\r\n msg = \"successful\"\r\n status = 0\r\n\r\n result = {\r\n \"result\": [],\r\n \"status\": status,\r\n \"msg\": msg\r\n }\r\n if search_command == \"0\":\r\n\r\n try:\r\n all_command = OperaCommandGroup.query.all()\r\n all_groups = {\"\"}\r\n all_group_result = []\r\n\r\n for item in all_command:\r\n all_groups.add(item.command_group_id)\r\n\r\n\r\n one_group_result = dict()\r\n one_group_result[\"groupName\"] = item.command_group_displayname\r\n commands = []\r\n group_commands = OperaCommand.query.filter_by(command_group_id=item.command_group_id).order_by(desc(OperaCommand.id)).all()\r\n for com in group_commands:\r\n\r\n one_recode = dict()\r\n one_recode[\"orderId\"] = str(com.command_id)\r\n if one_recode[\"orderId\"] == \"1\":\r\n one_recode[\"type\"] = \"10\"\r\n elif one_recode[\"orderId\"] == \"3\":\r\n one_recode[\"type\"] = \"3\"\r\n elif one_recode[\"orderId\"] == \"4\":\r\n one_recode[\"type\"] = \"6\"\r\n elif one_recode[\"orderId\"] == \"5\":\r\n pass\r\n elif one_recode[\"orderId\"] == \"6\":\r\n one_recode[\"type\"] = \"4\"\r\n elif one_recode[\"orderId\"] == \"7\":\r\n one_recode[\"type\"] = \"8\"\r\n one_recode[\"name\"] = com.command_displayname\r\n commands.append(one_recode)\r\n one_group_result[\"orders\"] = commands\r\n all_group_result.append(one_group_result)\r\n #one_group_result.clear()\r\n result[\"result\"] = all_group_result\r\n except:\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"get operation command was failed ! pls connect admin\"\r\n result[\"status\"] = 1\r\n logger.error(result[\"msg\"])\r\n logger.error(sys.exc_info()[0])\r\n finally:\r\n return result\r\n\r\n elif search_user == \"0\":\r\n #查询companyid所有的用户名\r\n try:\r\n all_company_result = Opuser.query.filter_by(opcompanyid=companyid).order_by(desc(Opuser.id)).all()\r\n users = []\r\n templist = []\r\n for temp in all_company_result:\r\n if temp.oprole != '2' and temp.oprole !='5':\r\n templist.append(temp)\r\n all_company_result = templist\r\n if len(all_company_result) == 0:\r\n #查询为空\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"no anything user.\"\r\n result[\"status\"] = 1\r\n return result\r\n for item in all_company_result:\r\n one_recode = dict()\r\n user_image = User.query.filter_by(userid=item.opuserid).limit(1).all()\r\n if len(user_image) == 0:\r\n one_recode[\"operationImage\"] = \"null\"\r\n else:\r\n one_recode[\"operationImage\"] = str(user_image[0].profile)\r\n one_recode[\"operationId\"] = item.opuserid\r\n one_recode[\"operationName\"] = item.opusername\r\n users.append(one_recode)\r\n\r\n result[\"result\"] = users\r\n except:\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"get operation users was failed ! pls connect admin\"\r\n result[\"status\"] = 1\r\n logger.error(result[\"msg\"])\r\n logger.error(sys.exc_info()[0])\r\n finally:\r\n return result\r\n else:\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"未查找到符合条件的操作日志.\"\r\n result[\"status\"] = 1\r\n\r\n\r\ndef operation_search_with_condition(usertoken, companyid, search_command_id=None, search_user_id=None, starttime=None, endtime=None):\r\n status = 0\r\n all_page = 1\r\n\r\n result = {\r\n \"result\": [],\r\n \"status\": status\r\n }\r\n temp_result = []\r\n # 开始查询\r\n try:\r\n #根据用户userid\r\n if search_user_id != \"\":\r\n\r\n result_user = Opuser.query.filter_by(opuserid=search_user_id).limit(1).all()\r\n #result_user = Opuser.query.filter_by(opuserid=search_user_id).first()\r\n if len(result_user) == 0:\r\n result[\"msg\"] = \"can't find user info.\"\r\n result[\"status\"] = 1\r\n return result\r\n else:\r\n username = str(result_user[0].opusername)\r\n sql = \"\"\"select b.id,b.username,b.companyid, b.exec_com, b.ip, b.hostname, b.exec_time from tbl_operalog b\r\n where username='{u}' order by b.id desc \"\"\".format(u=username)\r\n #all_company_result = OperaLog.query.filter(companyid=companyid).filter(username=username).order_by(desc(OperaLog.id)).all()\r\n all_company_result = db.session.execute(sql).fetchall()\r\n\r\n elif starttime != \"\" and endtime != \"\":\r\n #根据时间查询\r\n sql = \"\"\"select b.id,b.username,b.companyid, b.exec_com, b.ip, b.hostname, b.exec_time from tbl_operalog b\r\n where companyid='{i}' and exec_time > '{s1} 00:00:01' and exec_time < '{t1} 23:59:59' order by b.id desc\"\"\".\\\r\n format(i=companyid,s1=starttime, t1=endtime)\r\n \r\n all_company_result = db.session.execute(sql).fetchall()\r\n\r\n elif search_command_id != \"\":\r\n sql = \"\"\"select b.id,b.command_id, b.command, b.command_displayname, b.remark from \r\n tbl_operacommand b where b.command_id={i}\"\"\".format(i=int(search_command_id))\r\n print(sql)\r\n all_commands = db.session.execute(sql).fetchall()\r\n sql = \"\"\"select b.id,b.username,b.companyid, b.exec_com, b.ip, b.hostname, b.exec_time from tbl_operalog b\r\n where companyid='{i}' and exec_com like \"%{j}%\" order by b.id desc\"\"\".format(i=companyid, j=all_commands[0].command)\r\n\r\n all_company_result = db.session.execute(sql).fetchall()\r\n else:\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"未查找到符合条件的操作日志\"\r\n result[\"status\"] = 1\r\n\r\n\r\n if len(all_company_result) == 0:\r\n # 查询为空\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"未查找到符合条件的操作日志\"\r\n result[\"status\"] = 1\r\n return result\r\n for item in all_company_result:\r\n\r\n #后续需要优化,减少查询\r\n sql = \"\"\"select b.id,b.command_id, b.command, b.command_displayname, b.remark from \r\n tbl_operacommand b where b.command like \"%{i}%\" order by b.id desc;\"\"\".format(i=item.exec_com.rstrip())\r\n command_desc = db.session.execute(sql).fetchall()\r\n if len(command_desc) == 0:\r\n cmd_desc = item.exec_com.rstrip()\r\n else:\r\n cmd_desc = command_desc[0].command_displayname\r\n user_image = User.query.filter_by(username=item.username).limit(1).all()\r\n if len(user_image) == 0:\r\n image_url = \"null\"\r\n else:\r\n image_url = str(user_image[0].profile)\r\n msg = \" \" + item.hostname + \"( ip :\" + item.ip + \")\"\r\n one_record = {\"username\": item.username, \"user_image\": image_url,\r\n \"exec_time\": item.exec_time.strftime(\"%Y-%m-%d %H:%M:%S\"),\r\n \"operating_command\": cmd_desc, \"msg\": msg}\r\n temp_result.append(one_record)\r\n\r\n result[\"result\"] = temp_result\r\n except:\r\n result[\"result\"] = []\r\n result[\"msg\"] = \"get operation log was failed ! pls connect admin\"\r\n result[\"status\"] = 1\r\n logger.error(result[\"msg\"])\r\n logger.error(sys.exc_info()[0])\r\n finally:\r\n result[\"all_page\"] = all_page\r\n return result\r\n" }, { "alpha_fraction": 0.6277056336402893, "alphanum_fraction": 0.7792207598686218, "avg_line_length": 45, "blob_id": "4d3ac7d294d1172361cde3869870ab44f1dc1c0d", "content_id": "c8dbc4f5128a8f8a2cfa3c78658b1f83cb4dcfae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "no_license", "max_line_length": 91, "num_lines": 5, "path": "/houtaiapi/config.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#数据库连接配置\n\n#localdatabase = 'mysql+pymysql://root:[email protected]:3306/chatbot?charset=utf8mb4'\nlocaldatabase = 'mysql+pymysql://chatbot:chatbot2515525@mysql:3306/chatbot?charset=utf8mb4'\napiserverurl = \"http://nginx-server:5001\"\n\n" }, { "alpha_fraction": 0.6892655491828918, "alphanum_fraction": 0.7161017060279846, "avg_line_length": 40.66666793823242, "blob_id": "a9a3c5ac35d66d9c42519c75d1458882b6c6620f", "content_id": "3898629f85f2efec9050473b0fc2aa1e7de4567d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2368, "license_type": "no_license", "max_line_length": 187, "num_lines": 51, "path": "/upload/model.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom config import *\n\nfrom flask_sqlalchemy import SQLAlchemy as SQLAlchemyBase\nfrom sqlalchemy.pool import NullPool\n\nclass SQLAlchemy(SQLAlchemyBase):\n def apply_driver_hacks(self, app, info, options):\n super(SQLAlchemy, self).apply_driver_hacks(app, info, options)\n options['poolclass'] = NullPool\n options.pop('pool_size', None)\n\n'''配置数据库'''\napp = Flask(__name__)\napp.config['SECRET_KEY'] ='hard to guess'\napp.config['SQLALCHEMY_DATABASE_URI'] = localdatabase\n\n#设置这一项是每次请求结束后都会自动提交数据库中的变动\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False\n#实例化\ndb = SQLAlchemy(app)\n\nclass User(db.Model):\n # 定义表名\n __tablename__ = 'tbl_users'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(128), nullable=True, comment='用户名')\n userid = db.Column(db.String(128), nullable=True,unique=True, comment='用户名')\n role = db.Column(db.String(128), nullable=True, comment='用户状态')\n #password_hash = db.Column(db.String(64))\n password = db.Column(db.String(128), nullable=False, comment='用户密码')\n mobile = db.Column(db.String(128), nullable=False,unique=True, comment='用户手机号码')\n #1为游客,2为申请待同意用户,3为普通公司用户,4为公司管理员\n profile = db.Column(db.String(128), nullable=False, server_default='http://139.196.107.14:6001/upload/2018-11-12/[email protected]', comment='profile picture')\n logintime = db.Column(db.TIMESTAMP(True), nullable=False, comment='登录时间')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\n\n\nclass Upload(db.Model):\n # 定义表名\n __tablename__ = 'tbl_uploads'\n # 定义列对象\n id = db.Column(db.Integer, primary_key=True)\n userid = db.Column(db.String(128), nullable=True,comment='用户名')\n imageurl = db.Column(db.String(128), nullable=False, comment='upload image picture')\n createtime = db.Column(db.TIMESTAMP(True), nullable=False,comment='创建时间')\n updatetime = db.Column(db.TIMESTAMP(True), nullable=False, comment='更新时间')\ndb.create_all()" }, { "alpha_fraction": 0.595061719417572, "alphanum_fraction": 0.6067901253700256, "avg_line_length": 25.557376861572266, "blob_id": "5ff5bae4c211277edd1f7542ace03df11c1bab01", "content_id": "129736b6de9cb03f1cfdb64b37e4d867bb25917d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1680, "license_type": "no_license", "max_line_length": 59, "num_lines": 61, "path": "/upload/http_chat.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#coding=utf-8\nfrom flask import jsonify, request\nfrom image import *\nimport os, datetime\nfrom config import *\n\n#聊天上传图片\[email protected]('/api/v1/uploads', methods=['POST'])\ndef upload_file():\n token = request.form.get('token')\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n today = str(datetime.date.today())\n print(today)\n\n if os.path.exists('upload/' + today): # 判断文件夹是否存在\n pass\n else:\n os.mkdir('upload/' + today)\n\n file = request.files['image']\n print(file.filename)\n\n hash_value = generate_random_str(24)\n\n filename = hash_value + '-' + file.filename\n file.save(os.path.join('upload/' + today,filename))\n file_url = url + '/upload/' + today + '/' + filename\n\n rs = image_insert(usertoken, userid, file_url)\n\n return jsonify(rs)\n\n\n#聊天上传头像\[email protected]('/api/v1/headp', methods=['POST'])\ndef upload_head():\n token = request.form.get('token')\n print(token)\n file = request.files['image']\n print(file.filename)\n userid = token.split('-')[0]\n usertoken = token.split('-')[1]\n\n today = str(datetime.date.today())\n if os.path.exists('upload/' + today): # 判断文件夹是否存在\n pass\n else:\n os.mkdir('upload/' + today)\n file = request.files['image']\n hash_value = generate_random_str(24)\n\n filename = hash_value + '-' + file.filename\n file.save(os.path.join('upload/' + today,filename))\n file_url = url + '/upload/' + today + '/' + filename\n rs = imageurl_update(usertoken, userid, file_url)\n return jsonify(rs)\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=6000)\n" }, { "alpha_fraction": 0.5387507081031799, "alphanum_fraction": 0.5503734350204468, "avg_line_length": 35.8959846496582, "blob_id": "fddace61e63c4374208c08493f58a163d30e87fc", "content_id": "b0984749e47fca37afa94387616a3baaaf076971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21199, "license_type": "no_license", "max_line_length": 175, "num_lines": 548, "path": "/chatbot/chatbot.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from socketIO_client import SocketIO, BaseNamespace\nfrom datetime import datetime\nimport threading\nimport requests\nimport json\nimport time\nimport random\nimport string\n\n#serverip = 'http://127.0.0.1:5000'\nserverip = 'http://nginx-server:5001'\nsocket = SocketIO('nginx-server',5001)\napiurl = serverip + '/api/v1/login'\napigetmonitorurl = serverip + '/api/v1/zabbixmonitor'\n#apiurl = 'http://139.196.107.14:5000/api/v1/login'\n#payload = {\"password\": \"ppy6rQ3iAMKNzpDjpqYdP29g1STvoz6t0\", \"mobile\": \"c2YDSc5nIO7u0Bxjy7JHj0VOy\"}\npayload = {\"password\": \"i8Ts9fJeBa5Q3AU2Ift74g==\", \"mobile\": \"cUjAwVDIbBtd4hKtbYZbLHz7s\"}\nheader = {'Content-Type': 'application/json'}\n\n#产生一个随机字符串\ndef generate_random_str(randomlength=16):\n \"\"\"\n 生成一个指定长度的随机字符串,其中\n string.digits=0123456789\n string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n \"\"\"\n str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]\n random_str = ''.join(str_list)\n return random_str\n\n\nloginrs = requests.post(apiurl, data=json.dumps(payload), headers=header)\nprint(\"login...\")\nprint(loginrs.json())\ntoken = loginrs.json()['token']\ncompanyid = loginrs.json()['companyid']\n\n#机器人登录\ndef botjoinroot(message):\n msgid = generate_random_str(48)\n sendmsg = {'token': token,'role':'chatbot', 'companyid':companyid, 'msg': message, 'msgid':msgid}\n socket.emit('talk', sendmsg)\n\n#发送消息\ndef sendmsg(message):\n msgid = generate_random_str(48)\n sendmsg = {'token': token, 'companyid':companyid, 'msg': message, 'msgid':msgid}\n socket.emit('talk', sendmsg)\n\n\n#连接响应\ndef conn_response(*args):\n print(args[0])\n\n\n#talk响应\ndef talk_response(*args):\n print('talk zzzzzzzzzzz')\n print(args[0])\n\n#发送消息类型2\ndef botsendmsgtype2(username):\n msgid = generate_random_str(48)\n sendmsgtype2 = {'data': {'type': 2,'companyid':companyid,'msgid':msgid, 'token': token, 'rootbean':\n {'msg': '你好,'+ username + ' 需要我帮你做点什么?', 'actions':\n [{'name': '查看主机CPU', 'type': '3'},\n {'name': '查看主机内存', 'type': '4'},\n {'name': '查看磁盘状态', 'type': '6'},\n {'name': '查看网络流量', 'type': '8'},\n {'name': '重启主机', 'type': '10'}\n # {'name': '查看磁盘读写', 'type': '12'},\n ]}}}\n socket.emit('chatbot', sendmsgtype2)\n print('ooooooh yes')\n\n\n#发送查询主机cpu消息\ndef botsendmsgtype3(host):\n msgid = generate_random_str(48)\n getinfo = requests.get(apigetmonitorurl + '/' + host + '?token=' + token + '&companyid=' + companyid, headers=header)\n if getinfo.status_code != 200:\n print(\"你们先过了我这一关!!!!!\")\n else:\n print('hhhhhhhhhhh', getinfo.json())\n if 'status' in getinfo.json():\n print('不存在host', host)\n #sendmsgtype3 = {\n # 'data': {'type': 1, 'token': token,'msgid':msgid, 'companyid': companyid, 'rootbean':\n # {'msg': \"Ooops,未找到此主机:\" + host + \",请检查输入的hostid/hostname/hostip\"}}}\n sendmsgtype3 = {\n 'data': {'type': 1, 'token': token,'msgid':msgid, 'companyid': companyid, 'rootbean':\n {'msg': \"没有查询到相关信息、请检查输入信息是否正确。\"}}}\n\n else:\n if getinfo.json()['cpu']:\n lastvalue_str = getinfo.json()['cpu'][0]['lastvalue']\n else:\n lastvalue_str = 0.0\n lastvalue_float = float(lastvalue_str)\n lastvalue_float2 = round(lastvalue_float, 2)\n hostip = getinfo.json()['hostip']\n\n sendmsgtype3 = {\n \"data\": {\n \"type\": 3,\n \"msgid\":msgid,\n \"token\": token,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + hostip + \")CPU运行情况:\",\n \"actions\": [\n {\n \"title\": \"CPU\",\n \"ratio\": lastvalue_float2,\n }\n ]}}}\n\n socket.emit('chatbot', sendmsgtype3)\n\n print('ooooooh yes')\n\n\n#发送查询主机内存消息\ndef botsendmsgtype4(host):\n msgid = generate_random_str(48)\n getinfo = requests.get(apigetmonitorurl + '/' + host + '?token=' + token + '&companyid=' + companyid, headers=header)\n print('hhhhhhhhhhh', getinfo.json())\n if 'status' in getinfo.json():\n print('不存在host', host)\n \"\"\"\n sendmsgtype4 = {\n 'data': {'type': 1, 'token': token, 'msgid':msgid,'companyid': companyid, 'rootbean':\n {'msg': \"Ooops,未找到此主机:\" + host + \",请检查输入的hostid/hostname/hostip\"}}}\n \"\"\"\n sendmsgtype4 = {\n 'data': {'type': 1, 'token': token,'msgid':msgid, 'companyid': companyid, 'rootbean':\n {'msg': \"没有查询到相关信息、请检查输入信息是否正确。\"}}}\n else:\n total_memory_lastvalue = getinfo.json()['total_memory'][0]['lastvalue']\n if getinfo.json()['available_memory']:\n available_memory_lastvalue = getinfo.json()['available_memory'][0]['lastvalue']\n else:\n available_memory_lastvalue = 0.0\n used_memory_lastvalue = total_memory_lastvalue - available_memory_lastvalue\n print(total_memory_lastvalue)\n print(available_memory_lastvalue)\n if total_memory_lastvalue == 0.0:\n ratiolastvalue_float = 0\n else:\n ratiolastvalue_float = used_memory_lastvalue / total_memory_lastvalue * 100\n ratiolastvalue = round(ratiolastvalue_float, 2)\n hostip = getinfo.json()['hostip']\n\n sendmsgtype4 = {\n \"data\": {\n \"type\": 4,\n \"token\": token,\n \"msgid\":msgid,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + hostip + \")内存运行情况:\",\n \"actions\": [\n {\n \"title\": \"内存\",\n \"ratio\": ratiolastvalue,\n }\n ]}}}\n\n socket.emit('chatbot', sendmsgtype4)\n print('ooooooh yes')\n\n\n#发送查询主机网络消息\ndef botsendmsgtype8(host):\n msgid = generate_random_str(48)\n getinfo = requests.get(apigetmonitorurl + '/' + host + '?token=' + token + '&companyid=' + companyid, headers=header)\n print('hhhhhhhhhhh', getinfo.json())\n if 'status' in getinfo.json():\n print('不存在host', host)\n sendmsgtype8 = {\n 'data': {'type': 1, 'token': token,'msgid':msgid, 'companyid': companyid, 'rootbean':\n {'msg': \"没有查询到相关信息、请检查输入信息是否正确。\"}}}\n else:\n monitorinfo = getinfo.json()\n hostip = getinfo.json()['hostip']\n innetworkinfo_list = monitorinfo['in_network']\n outnetworkinfo_list = monitorinfo['out_network']\n print(innetworkinfo_list)\n print(outnetworkinfo_list)\n\n allinnetworkinfo_list = []\n for innetworkinfo in innetworkinfo_list:\n allinnetworkinfo_dict = {}\n drivename_source = innetworkinfo['key_']\n wangkalastvalue = innetworkinfo['lastvalue']\n drivename = drivename_source.strip('net.if.in').strip('[').strip(']')\n allinnetworkinfo_dict['netDrive'] = drivename\n allinnetworkinfo_dict['inNet'] = wangkalastvalue\n allinnetworkinfo_list.append(allinnetworkinfo_dict)\n\n alloutnetworkinfo_list = []\n for outnetworkinfo in outnetworkinfo_list:\n alloutnetworkinfo_dict = {}\n outdrivename_source = outnetworkinfo['key_']\n outwangkalastvalue = outnetworkinfo['lastvalue']\n outdrivename = outdrivename_source.strip('net.if.out').strip('[').strip(']')\n alloutnetworkinfo_dict['netDrive'] = outdrivename\n alloutnetworkinfo_dict['outNet'] = outwangkalastvalue\n alloutnetworkinfo_list.append(alloutnetworkinfo_dict)\n\n print(alloutnetworkinfo_list)\n print(allinnetworkinfo_list)\n\n allnetworkinfo_list = []\n for networkinfo in allinnetworkinfo_list:\n innetworkdrivename = networkinfo['netDrive']\n for outnetworkinfo_check in alloutnetworkinfo_list:\n if outnetworkinfo_check['netDrive'] == innetworkdrivename:\n print('1111111', outnetworkinfo_check)\n\n print('networkinfo', networkinfo)\n print('outnetworkinfo_check[outNet]', outnetworkinfo_check['outNet'])\n outnetvalue = outnetworkinfo_check['outNet']\n networkinfo['outNet'] = outnetvalue\n allnetworkinfo_list.append(networkinfo)\n\n print(allnetworkinfo_list)\n sendmsgtype8 = {\n \"data\": {\n \"type\": 8,\n \"token\": token,\n \"msgid\":msgid,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + hostip + \")网络状况:\",\n \"actions\": allnetworkinfo_list\n }}}\n\n socket.emit('chatbot', sendmsgtype8)\n print('ooooooh yes')\n\n#发送查询主机磁盘状态消息\ndef botsendmsgtype6(host):\n msgid = generate_random_str(48)\n getinfo = requests.get(apigetmonitorurl + '/' + host + '?token=' + token + '&companyid=' + companyid, headers=header)\n print('hhhhhhhhhhh', getinfo.json())\n hostip = getinfo.json()['hostip']\n if 'status' in getinfo.json():\n print('不存在host', host)\n sendmsgtype6 = {\n 'data': {'type': 1, 'token': token,'msgid':msgid, 'companyid': companyid, 'rootbean':\n {'msg': \"没有查询到相关信息、请检查输入信息是否正确。\"}}}\n else:\n monitorinfo = getinfo.json()\n diskinfo_list = monitorinfo['disk']\n print(diskinfo_list)\n useddiskinfo_list = []\n for diskinfo in diskinfo_list:\n useddiskinfo_dict = {}\n drivename_source = diskinfo['key_']\n drivename = drivename_source.strip('vfs.fs.size').strip('[').strip(']')\n diskdrivename = drivename.split(',')\n\n if drivename.find('used') != -1:\n diskuseddrivelastvalue = diskinfo['lastvalue']\n useddiskinfo_dict['usedSize'] = diskuseddrivelastvalue\n useddiskinfo_dict['title'] = diskdrivename[0]\n useddiskinfo_list.append(useddiskinfo_dict)\n\n totaldiskinfo_list = []\n for totaldiskinfo in diskinfo_list:\n totaldiskinfo_dict = {}\n totaldrivename_source = totaldiskinfo['key_']\n totaldrivename = totaldrivename_source.strip('vfs.fs.size').strip('[').strip(']')\n diskdrivename = totaldrivename.split(',')\n if totaldrivename.find('total') != -1:\n disktotaldrivelastvalue = totaldiskinfo['lastvalue']\n totaldiskinfo_dict['totalSize'] = disktotaldrivelastvalue\n totaldiskinfo_dict['title'] = diskdrivename[0]\n totaldiskinfo_list.append(totaldiskinfo_dict)\n\n alldisknfo_list = []\n for lastuseddiskinfo in useddiskinfo_list:\n lastuseddiskdrivename = lastuseddiskinfo['title']\n for lasttotaldiskinfo_check in totaldiskinfo_list:\n if lasttotaldiskinfo_check['title'] == lastuseddiskdrivename:\n\n alldiskvalue = lasttotaldiskinfo_check['totalSize']\n useddiskvalue = lastuseddiskinfo['usedSize']\n if alldiskvalue == 0.0:\n diskratio = 0\n else:\n diskratio = useddiskvalue / alldiskvalue * 100\n\n int_diskratio = int(diskratio)\n float_alldiskvalue = '%.2f' % alldiskvalue\n float_useddiskvalue = '%.2f' % useddiskvalue\n\n totalSize = str(float_alldiskvalue) + 'G'\n usedSize = str(float_useddiskvalue) + 'G'\n lastuseddiskinfo['ratio'] = int_diskratio\n lastuseddiskinfo['totalSize'] = totalSize\n lastuseddiskinfo['usedSize'] = usedSize\n alldisknfo_list.append(lastuseddiskinfo)\n\n print(alldisknfo_list)\n\n sendmsgtype6 = {\n \"data\": {\n \"type\": 6,\n \"token\": token,\n \"msgid\": msgid,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + hostip + \")磁盘状况:\",\n \"actions\": alldisknfo_list\n }}}\n\n socket.emit('chatbot', sendmsgtype6)\n print('ooooooh yes')\n\ndef botsendmsgtype1(username):\n msgid = generate_random_str(48)\n sendmsgtype1 = {'data': {'type':1, 'token': token,'msgid':msgid,'companyid':companyid, 'rootbean':{'msg': '你好,'+ username}}}\n socket.emit('chatbot', sendmsgtype1)\n print('ooooooh yes')\n\n\n\n#审核不同类型的消息\ndef botsendmsgtype11(host ,role, oprole, action, commandType):\n msgid = generate_random_str(32)\n \n if role == '8':\n botjoinroot(\"Oooops, 用户已被禁用Oooops\")\n\n elif oprole == '4' or oprole == '6' or oprole == '3':\n if action == 'agree' or action == 'request':\n if commandType == 10:\n print('重启执行中...')\n\n rebooturl = serverip + '/api/v1/salt/command'\n usertoken = token.split('-')[1]\n userid = token.split('-')[0]\n payload = {\"usertoken\": usertoken,\n \"userid\":userid,\n \"clientip\":host,\n \"command\":\"reboot\",\n \"companyid\":companyid}\n\n rebootrs = requests.post(url=rebooturl, data=json.dumps(payload), headers=header)\n\n if rebootrs.status_code == 200:\n rebootrs_dict_str = rebootrs.json()\n print(rebootrs_dict_str)\n rebootrs_dict = eval(rebootrs_dict_str)\n #rebootrs_dict = rebootrs.json()\n status = rebootrs_dict['status']\n if status == 0:\n sendmsg(host + \" 重启成功!\")\n else:\n sendmsg(host + \" 重启失败!, \" + rebootrs_dict['result'])\n elif commandType == 3:\n\n print('查看主机cpu执行中...')\n print(host)\n botsendmsgtype3(host)\n print('主机cpu执行完成')\n elif commandType == 4:\n print('查看主机内存执行中...')\n print(host)\n botsendmsgtype4(host)\n elif commandType == 6:\n print(host)\n botsendmsgtype6(host)\n elif commandType == 8:\n print('查看主机网络流量执行中...')\n print(host)\n botsendmsgtype8(host)\n\n else:\n print('已拒绝...')\n if commandType == 10:\n sendmsg(host + \" : 此主机重启申请已被拒绝!\")\n elif commandType == 3:\n sendmsg(host + \" : 查看此主机CPU已被拒绝!\")\n elif commandType == 4:\n sendmsg(host + \" : 查看此主机内存已被拒绝\")\n elif commandType == 6:\n sendmsg(host + \" : 查看此主机磁盘状态已被拒绝!\")\n elif commandType == 8:\n sendmsg(host + \" : 查看此主机网络流量已被拒绝!\")\n\n\n print('ooooooh yes')\n\n\ndef botsendmsgtype12(host, role, oprole):\n msgid = generate_random_str(48)\n getinfo = requests.get(apigetmonitorurl + '/' + host + '?token=' + token + '&companyid=' + companyid, headers=header)\n print('hhhhhhhhhhh', getinfo.json())\n if 'status' in getinfo.json():\n print('不存在host', host)\n sendmsgtype12 = {\n 'data': {'type': 1, 'token': token,'msgid':msgid, 'companyid': companyid, 'rootbean':\n {'msg': \"没有查询到相关信息、请检查输入信息是否正确。\"}}}\n else:\n hostip = getinfo.json()['hostip']\n #\n # if action == 'agree' or action == 'request':\n print('执行中...')\n diskperformanceurl = serverip + '/api/v1/salt/diskperformance'\n data = {\n\n \"token\": token,\n \"oprole\": oprole,\n \"role\": role,\n \"clientip\": host,\n \"commandid\": \"4\",\n \"companyid\": companyid\n }\n\n diskperformance_request = requests.post(url=diskperformanceurl, data=json.dumps(data), headers=header)\n\n assert diskperformance_request.status_code == 200\n command_result = diskperformance_request.json()\n print(command_result)\n if command_result[\"status\"] == 0:\n result_temp = command_result[\"result\"][\"command_result\"]\n socket.emit('chatbot', result_temp)\n else:\n result_temp = command_result[\"msg\"]\n socket.emit('chatbot', result_temp)\n\n sendmsgtype12 = {\n \"data\": {\n \"type\": 12,\n \"token\": token,\n \"msgid\": msgid,\n 'companyid': companyid,\n \"rootbean\": {\n \"msg\": \"当前\" + host + \"(ip:\" + hostip + \")磁盘IO:\",\n \"actions\": result_temp\n }}}\n print(sendmsgtype12)\n socket.emit('chatbot', sendmsgtype12)\n print('ooooooh yes')\n\n\n#机器人响应\ndef chatbot_response(*args):\n try:\n print('chatbot zzzzzzzzzzz')\n botmsgdict = args[0]\n print(botmsgdict)\n username = botmsgdict['data']['username']\n\n\n if botmsgdict['data']['oprole'] != '5' and botmsgdict['data']['type'] == 1:\n botsendmsgtype1(username)\n elif botmsgdict['data']['oprole'] != '5' and botmsgdict['data']['type'] == 2:\n botsendmsgtype2(username)\n elif botmsgdict['data']['oprole'] != '5' and botmsgdict['data']['type'] == 10:\n host = botmsgdict['data']['rootbean']['hostip']\n role = botmsgdict['data']['role']\n oprole = botmsgdict['data']['oprole']\n action = botmsgdict['data']['rootbean']['action']\n commandType = botmsgdict['data']['commandType']\n print(host, role, oprole, action,commandType)\n botsendmsgtype11(host,role, oprole, action,commandType)\n\n #保存操作记录\n if commandType == 3:\n exec_com = \"cpu\"\n elif commandType == 4:\n exec_com = \"memory\"\n elif commandType == 6:\n exec_com = \"iostat -d |egrep -v '$^|Linux' |awk '{print $1,$3,$4}'\"\n elif commandType == 8:\n exec_com = \"network\"\n elif commandType == 10:\n exec_com = \"reboot\"\n ip = host\n hostname = host\n exec_time = datetime(datetime.today().year, datetime.today().month, datetime.today().day,datetime.today().hour,datetime.today().minute,datetime.today().second)\n exec_time = exec_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n addoperation_payload = {\"username\":username,\"companyid\":companyid,\"exec_com\":exec_com,\"ip\":ip,\"hostname\":hostname,\"exec_time\":exec_time}\n url_s = serverip + '/api/v1/operation/operation_log_save'\n saveoperation_rs = requests.post(url=url_s, data=json.dumps(addoperation_payload), headers=header)\n\n except Exception as e:\n print(e)\n print(\"Ooops, somethings waring\")\n\n#监控constatus消息\ndef conn():\n socket.emit('conn', 'test')\n botjoinroot('join room')\n socket.on('connstatus', conn_response)\n socket.wait(seconds=1)\n\ndef onlyconn():\n socket.emit('conn', 'test')\n socket.on('connstatus', conn_response)\n socket.wait(seconds=1)\n\ndef chatbots():\n while True:\n socket.on('chatbotstatus', chatbot_response)\n socket.wait(seconds=1)\n\ndef talks():\n while True:\n socket.on('talkstatus', talk_response)\n socket.wait(seconds=1)\n\ndef botjoinroot(message):\n msgid = generate_random_str(48)\n sendmsg = {'token': token,'role':'chatbot', 'companyid':companyid, 'msg': message, 'msgid':msgid}\n socket.emit('talk', sendmsg)\n\ndef sendmsg(message):\n msgid = generate_random_str(48)\n sendmsg = {'token': token, 'companyid':companyid, 'msg': message, 'msgid':msgid}\n socket.emit('talk', sendmsg)\n\n\ndef conn_response(*args):\n print(args[0])\n\n\ndef talk_response(*args):\n print('talk zzzzzzzzzzz')\n print(args[0])\n\ntada = threading.Thread(target=chatbots)\ntada.start()\n\ntalk_thread = threading.Thread(target=talks)\ntalk_thread.start()\n\nconn()\ndef connthreading():\n while True:\n time.sleep(2)\n onlyconn()\nconnth = threading.Thread(target=connthreading)\nconnth.start()\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 38, "blob_id": "faab5f5679fde16f73cb00ed722eb77f0e102c64", "content_id": "850f8a74e98cd9e78b0cf11893c88d38b8cd9311", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 40, "license_type": "no_license", "max_line_length": 38, "num_lines": 1, "path": "/chatbot-youke/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/chatbot-youke .\n\n" }, { "alpha_fraction": 0.5070449709892273, "alphanum_fraction": 0.5181635022163391, "avg_line_length": 32.546356201171875, "blob_id": "1b366e0ed08648ac73896c952af17be39d5b0662", "content_id": "2c48dc43719ef59234cc8b43d740676b80517846", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10687, "license_type": "no_license", "max_line_length": 139, "num_lines": 302, "path": "/chatapi/salt_exec.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# _*_ coding:utf-8 _*_\r\n\r\nfrom model import *\r\nimport requests\r\nimport json\r\ntry:\r\n import cookielib\r\nexcept:\r\n import http.cookiejar as cookielib\r\nimport ssl\r\nimport urllib3\r\nimport sys\r\nfrom datetime import datetime\r\nfrom concurrent.futures import ThreadPoolExecutor\r\nimport os\r\nimport logging\r\nfrom logging.handlers import TimedRotatingFileHandler\r\n\r\n\r\n\r\nfmt_str = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'\r\nlogging.basicConfig()\r\nfilename_head = os.getcwd() + \"/logs/rebot.log\"\r\nfileshandle = logging.handlers.TimedRotatingFileHandler(filename_head, when=\"midnight\", interval=1, backupCount=30,\r\n encoding='utf-8', delay=False, utc=False)\r\nfileshandle.suffix = \"%Y-%m-%d\"\r\nformatter = logging.Formatter(fmt_str)\r\nfileshandle.setFormatter(formatter)\r\nlogger = logging.getLogger(\"salt_exec\")\r\nlogger.addHandler(fileshandle)\r\nlogger.setLevel(logging.INFO)\r\n\r\ncontext = ssl._create_unverified_context()\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\nsalt_api = \"https://testsaltapi.wintruelife.com/\"\r\n\r\n\r\nclass SaltApi:\r\n \"\"\"\r\n 定义salt api接口的类\r\n 初始化获得token\r\n \"\"\"\r\n def __init__(self, url):\r\n self.url = url\r\n self.username = \"saltapi\"\r\n self.password = \"Xdhg002539\"\r\n self.headers = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36\",\r\n \"Content-type\": \"application/json\"\r\n }\r\n self.params = {'client': 'local', 'fun': '', 'tgt': ''}\r\n # self.params = {'client': 'local', 'fun': '', 'tgt': '', 'arg': ''}\r\n self.login_url = salt_api + \"login\"\r\n self.login_params = {'username': self.username, 'password': self.password, 'eauth': 'pam'}\r\n self.token = self.get_data(self.login_url, self.login_params)['token']\r\n self.headers['X-Auth-Token'] = self.token\r\n \"\"\"\r\n def get_data(self, url, params):\r\n send_data = json.dumps(params)\r\n \r\n request = requests.post(url, data=send_data, headers=self.headers, verify=False,timeout=5)\r\n try:\r\n if request.status_code != 200:\r\n # result = {\r\n # \"result\": \"salt服务\" + salt_api + \"连接失败。 http code: \" + str(request.status_code),\r\n # \"status\": 1\r\n # }\r\n logger.error(\"salt服务\" + salt_api + \"连接失败。 http code: \" + str(request.status_code))\r\n print(\"salt服务\" + salt_api + \"连接失败。 http code: \" + str(request.status_code))\r\n #return result\r\n \r\n assert request.status_code == 200\r\n\r\n\r\n response = request.json()\r\n result = dict(response)\r\n return result['return'][0]\r\n except Exception:\r\n response = request.json()\r\n result = dict(response)\r\n return result['return'][0]\r\n \"\"\"\r\n\r\n\r\n def get_data(self, url, params):\r\n send_data = json.dumps(params)\r\n try:\r\n request = requests.post(url, data=send_data, headers=self.headers, verify=False,timeout=10)\r\n except Exception:\r\n\r\n result = {\r\n \"result\": \"重启失败\",\r\n \"status\": 1\r\n }\r\n\r\n return result\r\n if request.status_code != 200:\r\n # result = {\r\n # \"result\": \"salt服务\" + salt_api + \"连接失败。 http code: \" + str(request.status_code),\r\n # \"status\": 1\r\n # }\r\n #logger.error(\"salt服务\" + salt_api + \"连接失败。 http code: \" + str(request.status_code))\r\n print(\"salt服务\" + salt_api + \"连接失败。 http code: \" + str(request.status_code))\r\n #return result\r\n try:\r\n assert request.status_code == 200\r\n response = request.json()\r\n result = dict(response)\r\n return result['return'][0]\r\n\r\n except Exception:\r\n\r\n response = request.json()\r\n result = dict(response)\r\n return result['return'][0]\r\n def salt_command(self, tgt, method, arg=None):\r\n \"\"\"远程执行命令,相当于salt 'client1' cmd.run 'free -m'\"\"\"\r\n if arg:\r\n params = {'client': 'local', 'fun': method, 'tgt': tgt, 'arg': arg}\r\n else:\r\n params = {'client': 'local', 'fun': method, 'tgt': tgt}\r\n result = self.get_data(self.url, params)\r\n return result\r\n\r\ndef main(username, usertoken, clientip, command, companyid, hostname):\r\n\r\n status = 0\r\n msg = \"\"\r\n result = dict()\r\n salt = SaltApi(salt_api)\r\n #salt_client = '10.0.60.187'\r\n salt_client = clientip\r\n salt_test = 'test.ping'\r\n salt_method = 'cmd.run'\r\n salt_params = command\r\n\r\n try:\r\n\r\n result_test = salt.salt_command(salt_client, salt_test)\r\n # for i in result_test.keys():\r\n # print(i, ': ', result_test[i])\r\n\r\n if not bool(result_test[salt_client]):\r\n msg = \"can not connect desc server.\"\r\n logger.error(msg)\r\n status = 1\r\n result = {\r\n \"result\": msg,\r\n \"status\": status\r\n }\r\n return json.dumps(result)\r\n except:\r\n msg = \"can not connect desc server.\"\r\n logger.error(msg)\r\n logger.error(sys.exc_info()[0])\r\n status = 1\r\n result = {\r\n \"result\": msg,\r\n \"status\": status\r\n }\r\n return json.dumps(result)\r\n\r\n #执行输入的命令\r\n \r\n try:\r\n with ThreadPoolExecutor(2) as executor:\r\n cmd_result = executor.submit(salt.salt_command, salt_client, salt_method, salt_params)\r\n result2 = cmd_result.result()\r\n #result2 = salt.salt_command(salt_client, salt_method, salt_params)\r\n for i in result2.keys():\r\n cur_time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n #print(username, clientip, command, cur_time, companyid)\r\n insert_log = OperaLog(username=str(username), ip=str(clientip), hostname=hostname, exec_com=str(command),\r\n exec_time=cur_time, companyid=str(companyid))\r\n\r\n db.session.add(insert_log)\r\n db.session.commit()\r\n msg = result2[i]\r\n status = 0\r\n # msg = result2[i]\r\n except:\r\n msg = \"the \" + clientip + \" exec command '\" + command + \"' has failed.\"\r\n logger.error(msg)\r\n logger.error(sys.exc_info()[0])\r\n status = 1\r\n finally:\r\n db.session.close()\r\n result = {\r\n 'result': msg,\r\n 'status': status\r\n }\r\n #return result\r\n return json.dumps(result)\r\n\r\n\r\ndef exec_passport(username, usertoken, clientip, commandid, companyid):\r\n status = 0\r\n msg = \"successful\"\r\n result = dict()\r\n salt = SaltApi(salt_api)\r\n #salt_client = '10.0.60.187'\r\n salt_client = clientip\r\n salt_test = 'test.ping'\r\n salt_method = 'cmd.run'\r\n try:\r\n monitor_host = Monitor.query.filter_by(zabbixhostip=clientip).first()\r\n\r\n if not monitor_host:\r\n status = 1\r\n result = {\r\n \"result\": [],\r\n \"msg\": \"没找到服务器,请重新输入.\",\r\n \"status\": status\r\n }\r\n return result\r\n\r\n except:\r\n status = 1\r\n result = {\r\n \"result\": [],\r\n \"msg\": \"没找到服务器,请重新输入.\",\r\n \"status\": status\r\n }\r\n logger.error(\"没找到服务器,请重新输入.\")\r\n logger.error(sys.exc_info()[0])\r\n return result\r\n\r\n\r\n salt_params = OperaCommand.query.filter_by(command_id=commandid).limit(1).all()\r\n try:\r\n\r\n result_test = salt.salt_command(salt_client, salt_test)\r\n if not bool(result_test[salt_client]):\r\n print(\"can not connect desc server.\")\r\n msg = \"can not connect desc server.\"\r\n status = 1\r\n result = {\r\n \"result\": [],\r\n \"msg\": msg,\r\n \"status\": status\r\n }\r\n return result\r\n except:\r\n msg = \"can not connect desc server.\"\r\n print(msg, sys.exc_info()[0])\r\n status = 1\r\n result = {\r\n \"result\": [],\r\n \"msg\": msg,\r\n \"status\": status\r\n }\r\n return result\r\n\r\n #执行输入的命令\r\n try:\r\n with ThreadPoolExecutor(2) as executor:\r\n cmd_result = executor.submit(salt.salt_command, salt_client, salt_method, salt_params)\r\n result2 = cmd_result.result()\r\n #result2 = salt.salt_command(salt_client, salt_method, salt_params[0].command)\r\n for i in result2.keys():\r\n command_result = dict()\r\n command_result_list = []\r\n\r\n cur_time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n #print(username, clientip, command, cur_time, companyid)\r\n insert_log = OperaLog(username=str(username), ip=str(clientip), hostname=monitor_host.zabbixhostname,\r\n exec_com=str(salt_params[0].command), exec_time=cur_time, companyid=str(companyid))\r\n\r\n db.session.add(insert_log)\r\n db.session.commit()\r\n command_result[\"name\"] = monitor_host.zabbixhostname\r\n command_result[\"host\"] = monitor_host.zabbixhostip\r\n for item1 in result2[i].split(\"\\n\"):\r\n if item1.find(\"Blk_read\") > 0:\r\n continue\r\n item_result = dict()\r\n temp_list = item1.split(\" \")\r\n\r\n item_result[\"Device\"] = temp_list[0]\r\n item_result[\"Blk_read\"] = temp_list[1]\r\n item_result[\"Blk_wrtn\"] = temp_list[2]\r\n\r\n command_result_list.append(item_result)\r\n\r\n command_result[\"command_result\"] = command_result_list\r\n result['result'] = command_result\r\n msg = \"当前 \" + monitor_host.zabbixhostname + \" (ip:\"+clientip + \") 磁盘IO\"\r\n status = 0\r\n # msg = result2[i]\r\n except:\r\n msg = \"the \" + clientip + \" exec command '\" + salt_params + \"' has failed.\"\r\n logger.error(msg)\r\n logger.error(sys.exc_info()[0])\r\n status = 1\r\n finally:\r\n db.session.close()\r\n result['msg'] = msg\r\n result['status'] = status\r\n\r\n return result\r\n" }, { "alpha_fraction": 0.7352941036224365, "alphanum_fraction": 0.7352941036224365, "avg_line_length": 32, "blob_id": "3d43f02a986ba3afd3b4bdd0ea6ec8f61e6e0433", "content_id": "deebad055927fd2820f2ee07f2c677ef782db2c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 34, "license_type": "no_license", "max_line_length": 32, "num_lines": 1, "path": "/chatbot/start.sh", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "docker build -t mychat/chatbot .\n\n" }, { "alpha_fraction": 0.5349645018577576, "alphanum_fraction": 0.5562584400177002, "avg_line_length": 33.38163757324219, "blob_id": "6dd47842f6091be39103f944984910b29c954bc1", "content_id": "9eb69606591862a925280b60e8b600b5e52c12a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48515, "license_type": "no_license", "max_line_length": 134, "num_lines": 1318, "path": "/chatapi/http_chat.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#coding=utf-8\r\nfrom flask import jsonify, request\r\nfrom user import *\r\nimport zabbix_quey\r\nimport houtai\r\nimport usermessage\r\nfrom concurrent.futures import ThreadPoolExecutor\r\nimport push_msg\r\nimport salt_exec\r\nimport search_oper_log\r\nimport demjson\r\nfrom model import *\r\n#获取短信通知\r\[email protected]('/api/v1/sms', methods=['POST'])\r\ndef SmsVC():\r\n request_data = request.get_json()\r\n mobile = request_data['mobile']\r\n smsinfo = smsvc(mobile)\r\n return jsonify(smsinfo)\r\n#忘记密码短信验证接口\r\[email protected]('/api/v1/forgetsms', methods=['POST'])\r\ndef ForgetSmsVC():\r\n request_data = request.get_json()\r\n mobile = request_data['mobile']\r\n smsinfo = forget_smsvc(mobile)\r\n return jsonify(smsinfo)\r\n\r\n\r\n#查询用户信息\r\[email protected]('/api/v1/user', methods=['GET'])\r\ndef UserInfoGet():\r\n token = request.args.get('token')\r\n companyid = request.args.get('companyid')\r\n usertoken = token.split('-')[1]\r\n userid = token.split('-')[0]\r\n userinfo = user_info(userid, usertoken, companyid)\r\n return jsonify(userinfo)\r\n\r\n#获取游客信息\r\[email protected]('/api/v1/youke', methods=['GET'])\r\ndef YoukeInfoGet():\r\n token = request.args.get('token')\r\n print(token)\r\n #token = \"youkechatbot-11111\"\r\n usertoken = token.split('-')[1]\r\n userid = token.split('-')[0]\r\n userinfo = user_info(userid, usertoken, None)\r\n return jsonify(userinfo)\r\n\r\n#注册用户\r\[email protected]('/api/v1/user', methods=['POST'])\r\ndef UserRegistry():\r\n request_data = request.get_json()\r\n mobile = request_data['mobile']\r\n password = request_data['password']\r\n smsvc = request_data['smsvc']\r\n registryrs = mobile_insert(smsvc, password, mobile)\r\n return jsonify(registryrs)\r\n\r\n#校验密码\r\[email protected]('/api/v1/password', methods=['POST'])\r\ndef Password():\r\n request_data = request.get_json()\r\n password = request_data['password']\r\n token = request_data['token']\r\n usertoken = token.split('-')[1]\r\n userid = token.split('-')[0]\r\n\r\n registryrs = password_jiaoyan(usertoken, userid, password)\r\n return jsonify(registryrs)\r\n\r\n#修改密码\r\[email protected]('/api/v1/password', methods=['PATCH', 'PUT'])\r\ndef ChangePassword():\r\n request_data = request.get_json()\r\n oldpassword = request_data['oldpassword']\r\n newpassword = request_data['newpassword']\r\n token = request_data['token']\r\n usertoken = token.split('-')[1]\r\n userid = token.split('-')[0]\r\n registryrs = change_password(usertoken, userid, newpassword, oldpassword)\r\n return jsonify(registryrs)\r\n\r\n\r\n#修改用户信息\r\[email protected]('/api/v1/user', methods=['PATCH', 'PUT'])\r\ndef ForgetPassword():\r\n request_data = request.get_json()\r\n #action = ['password', 'username', 'mobile']\r\n action = request_data['action']\r\n if action == 'password':\r\n mobile = request_data['mobile']\r\n newpassword = request_data['newpassword']\r\n smsvc = request_data['smsvc']\r\n registryrs = user_forget_password(smsvc, newpassword, mobile)\r\n return jsonify(registryrs)\r\n\r\n elif action == 'username':\r\n token = request_data['token']\r\n usertoken = token.split('-')[1]\r\n userid = token.split('-')[0]\r\n newusername = request_data['newusername']\r\n registryrs = user_update_username(usertoken,userid, newusername)\r\n return jsonify(registryrs)\r\n\r\n elif action == 'mobile':\r\n token = request_data['token']\r\n usertoken = token.split('-')[1]\r\n userid = token.split('-')[0]\r\n newmobile = request_data['newmobile']\r\n smsvc = request_data['smsvc']\r\n registryrs = user_update_mobile(smsvc, usertoken, userid, newmobile)\r\n return jsonify(registryrs)\r\n else:\r\n return jsonify({'status': '999', 'msg': 'Oooops, cant not do this'})\r\n\r\n\r\n#查询用户是否存在默认公司\r\[email protected]('/api/v1/default', methods=['GET'])\r\ndef UserDefaultCompany():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n queryrs = user_default_company(usertoken, userid)\r\n return jsonify(queryrs)\r\n\r\n\r\n#登录接口\r\[email protected]('/api/v1/login', methods=['POST'])\r\ndef UserLogin():\r\n request_data = request.get_json()\r\n print(request_data)\r\n mobile = request_data['mobile']\r\n password = request_data['password']\r\n loginrs = user_login(mobile, password)\r\n return jsonify(loginrs)\r\n\r\n#查询所有公司信息\r\[email protected]('/api/v1/companys', methods=['GET'])\r\ndef CompanysGet():\r\n token = request.args.get('token')\r\n usertoken = token.split('-')[1]\r\n companyrs = company_query(None, usertoken)\r\n return jsonify(companyrs)\r\n\r\n#查询某个公司信息\r\[email protected]('/api/v1/company/<string:companyname>', methods=['GET'])\r\ndef CompanyGet(companyname):\r\n token = request.args.get('token')\r\n usertoken = token.split('-')[1]\r\n companyrs = company_query(companyname, usertoken)\r\n return jsonify(companyrs)\r\n\r\n#创建公司\r\[email protected]('/api/v1/company', methods=['POST'])\r\ndef CompanyAdd():\r\n request_data = request.get_json()\r\n email = request_data['email']\r\n username = request_data['username']\r\n companyname = request_data['companyname']\r\n token = request_data['token']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyrs = company_insert(email, username, companyname, userid, usertoken)\r\n return jsonify(companyrs)\r\n\r\n#修改公司信息\r\[email protected]('/api/v1/company', methods=['PATCH', 'PUT'])\r\ndef UpdateOpUserDefaultCompany():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request_data['companyid']\r\n joininfors = updateopuserdefaultcompany(usertoken, userid, companyid)\r\n return jsonify(joininfors)\r\n\r\n#创建公司成员\r\[email protected]('/api/v1/member', methods=['POST'])\r\ndef MemberAdd():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n companyname = request_data['companyid']\r\n username = request_data['username']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n\r\n memberrs = join_company(userid, companyname, username, usertoken)\r\n return jsonify(memberrs)\r\n\r\n#删除公司成员\r\[email protected]('/api/v1/member', methods=['DELETE'])\r\ndef MemberDel():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n memberrs = leave_company(usertoken, userid, companyid)\r\n return jsonify(memberrs)\r\n\r\n#获取某个公司的申请信息\r\[email protected]('/api/v1/joininfo', methods=['GET'])\r\ndef JoinInfo():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n joininfors = join_info(userid, usertoken, companyid)\r\n return jsonify(joininfors)\r\n\r\n#获取app侧边栏信息\r\[email protected]('/api/v1/sidebar', methods=['GET'])\r\ndef SidebarInfo():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = sidebar_get(userid, usertoken)\r\n return jsonify(joininfors)\r\n\r\n#申请加入某个公司\r\[email protected]('/api/v1/joininfo', methods=['POST'])\r\ndef JoinUpdate():\r\n request_data = request.get_json()\r\n print(request_data)\r\n token = request_data['token']\r\n admin_action = request_data['admin_action']\r\n request_userid = request_data['request_userid']\r\n request_id = request_data['request_id']\r\n request_companyid = request_data['request_companyid']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = join_update(request_id,userid, usertoken,request_userid, admin_action, request_companyid)\r\n return jsonify(joininfors)\r\n\r\n#获取某个公司的成员信息\r\[email protected]('/api/v1/opusers', methods=['GET'])\r\ndef OpUsers():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n joininfors = opusers(userid, usertoken, companyid)\r\n return jsonify(joininfors)\r\n\r\n#查询公司某个成员的信息\r\[email protected]('/api/v1/opuser/<string:username>', methods=['GET'])\r\ndef OpUser(username):\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n joininfors = opuser(userid, usertoken, username, companyid)\r\n return jsonify(joininfors)\r\n\r\n#获取某个公司命令审核情况\r\[email protected]('/api/v1/commandstatus', methods=['GET'])\r\ndef CommandStatus():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n joininfors = commandstatus(userid, usertoken, companyid)\r\n return jsonify(joininfors)\r\n\r\n#修改某个公司的命令审核状态\r\[email protected]('/api/v1/commandstatus', methods=['PATCH', 'PUT'])\r\ndef UpdateCommandStatus():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n adminuserid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request_data['companyid']\r\n commandstatus_list = request_data['commandstatus_list']\r\n joininfors = updatecommandstatus(adminuserid, usertoken, companyid,commandstatus_list)\r\n return jsonify(joininfors)\r\n\r\n#添加运维用户\r\[email protected]('/api/v1/opuser', methods=['POST'])\r\ndef AddOpUser():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n username = request_data['opusername']\r\n mobile = request_data['opmobile']\r\n companyid = request_data['companyid']\r\n adminuserid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = addopuser(adminuserid, usertoken, username, mobile, companyid)\r\n return jsonify(joininfors)\r\n\r\n#编辑运维用户\r\[email protected]('/api/v1/opuser', methods=['PATCH', 'PUT'])\r\ndef UpdateOpUser():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n adminuserid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n print(request_data)\r\n if 'oprole' in request_data:\r\n opuserid = request_data['opuserid']\r\n oprole = request_data['oprole']\r\n opcompanyid = request_data['opcompanyid']\r\n joininfors = updateopuserrole(usertoken, adminuserid, opuserid, oprole, opcompanyid)\r\n return jsonify(joininfors)\r\n else:\r\n opuserid = request_data['opuserid']\r\n opusername = request_data['opusername']\r\n opmobile = request_data['opmobile']\r\n opcompanyid = request_data['opcompanyid']\r\n joininfors = updateopuser(adminuserid, usertoken, opusername, opmobile, opuserid, opcompanyid)\r\n return jsonify(joininfors)\r\n\r\n\r\n#删除运维用户\r\[email protected]('/api/v1/opuser', methods=['DELETE'])\r\ndef DeleteOpUser():\r\n token = request.args.get('token')\r\n opuserid = request.args.get('opmobile')\r\n companyid = request.args.get('companyid')\r\n adminuserid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = deleteopuser(adminuserid, usertoken, opuserid, companyid)\r\n return jsonify(joininfors)\r\n\r\n#删除后台公司\r\[email protected]('/backstage/companydelete', methods=['DELETE'])\r\ndef CompanyDelete():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n joininfors = houtai.backstagecmdelete(usertoken, companyid)\r\n return jsonify(joininfors)\r\n\r\n#获取客服电话\r\[email protected]('/api/v1/custommobile', methods=['GET'])\r\ndef CustomMobile():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n rs = houtai.coustomMobile(userid, usertoken)\r\n return jsonify(rs)\r\n\r\n#添加zabbix服务器\r\[email protected]('/api/v1/zabbixserver', methods=['POST'])\r\ndef AddZabbixServer():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n zabbixserver = request_data['zabbixserver']\r\n zabbixusername = request_data['zabbixusername']\r\n zabbixpassword = request_data['zabbixpassword']\r\n\r\n adminuserid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = zabbix_quey.zabbixserver_add(adminuserid, usertoken, zabbixserver, zabbixusername,zabbixpassword)\r\n return jsonify(joininfors)\r\n\r\n#查询zabbix所有主机信息\r\[email protected]('/api/v1/hosts', methods=['GET'])\r\ndef ZabbixHosts():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n joininfors = zabbix_quey.query_hosts(userid, usertoken, companyid)\r\n return jsonify(joininfors)\r\n\r\n#搜索某台主机的信息\r\[email protected]('/api/v1/host/<string:searchname>', methods=['GET'])\r\ndef ZabbixHost(searchname):\r\n token = request.args.get('token')\r\n #zabbixhostid = request.args.get('hostid')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n joininfors = zabbix_quey.query_zabbixhost(userid, usertoken, searchname, companyid)\r\n return jsonify(joininfors)\r\n\r\n\r\n#添加zabbix服务器监控项到机器人\r\[email protected]('/api/v1/zabbixmonitor', methods=['POST'])\r\ndef AddZabbixMonitor():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n hostinfo_list = request_data['hostinfo']\r\n print(hostinfo_list)\r\n companyid = request_data['companyid']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = zabbix_quey.zabbixmonitor_add(userid, usertoken, hostinfo_list, companyid)\r\n return jsonify(joininfors)\r\n\r\n\r\n#添加所有zabbix服务器\r\[email protected]('/api/v1/zabbixallmonitor', methods=['POST'])\r\ndef AddZabbixAllMonitor():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n hostinfo_list = request_data['hostinfo']\r\n companyid = request_data['companyid']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = zabbix_quey.zabbixallmonitor_add(userid, usertoken, hostinfo_list, companyid)\r\n return jsonify(joininfors)\r\n\r\n\r\n\r\n#查询zabbix所有主机信息\r\[email protected]('/api/v1/zabbixmonitors', methods=['GET'])\r\ndef ZabbixMonitors():\r\n token = request.args.get('token')\r\n companyid = request.args.get('companyid')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = zabbix_quey.zabbixitem_query(userid, usertoken, companyid)\r\n return jsonify(joininfors)\r\n\r\n\r\n#查询zabbix所有主机信息\r\[email protected]('/api/v1/zabbixmonitor/<string:host>', methods=['GET'])\r\ndef ZabbixMonitor(host):\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n joininfors = zabbix_quey.zabbixitem_value_query(userid, usertoken, host, companyid)\r\n return jsonify(joininfors)\r\n\r\n#后台功能\r\[email protected]('/backstage/index', methods=['GET'])\r\ndef BackstageIndex():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = houtai.backstage(userid, usertoken)\r\n return jsonify(joininfors)\r\n\r\n#在web前端页面显示所有公司信息\r\[email protected]('/backstage/companymanages', methods=['GET'])\r\ndef BackstageCm():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = houtai.backstagecms(userid, usertoken)\r\n return jsonify(joininfors)\r\n\r\n\r\n#在web前端页面搜索某个公司的信息\r\[email protected]('/backstage/companymanage/<string:companyname>', methods=['GET'])\r\ndef BackstageSearch(companyname):\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = houtai.backstagecm(userid, usertoken, companyname)\r\n return jsonify(joininfors)\r\n\r\n\r\n#在web前端页面显示某个公司的信息\r\[email protected]('/backstage/companymanage/companyinfo', methods=['GET'])\r\ndef BackstageSearch1():\r\n companyid = request.args.get(\"companyid\")\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = backstagecm1(userid, usertoken, companyid)\r\n return jsonify(joininfors)\r\n\r\n\r\n#在前端页面展示某个公司的成员情况\r\[email protected]('/backstage/companymanage/opusersinfo', methods=['GET'])\r\ndef Opusersinfo():\r\n companyid = request.args.get(\"companyid\")\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = opusersinfo(userid, usertoken, companyid)\r\n return jsonify(joininfors)\r\n\r\n\r\n#获取某台主机的信息\r\[email protected]('/api/v1/hostinfo', methods=['GET'])\r\ndef Hostinfo():\r\n hostip = request.args.get(\"hostip\")\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = hostinfo(userid, usertoken, hostip)\r\n return jsonify(joininfors)\r\n\r\n\r\n#获取host/hostid/hostname是否存在\r\[email protected]('/api/v1/hostmessage', methods=['GET'])\r\ndef HostmessageGet():\r\n\r\n host = request.args.get(\"host\")\r\n companyid = request.args.get('companyid')\r\n joininfors = zabbix_quey.hostmessageget(host, companyid)\r\n return jsonify(joininfors)\r\n\r\n\r\n#获取处于试用期中的公司\r\[email protected]('/backstage/tryouts', methods=['GET'])\r\ndef BackstageTryOut():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = houtai.backstagetryouts(userid, usertoken)\r\n return jsonify(joininfors)\r\n\r\n\r\n#获取即将过期的公司\r\[email protected]('/backstage/expiringcompanys', methods=['GET'])\r\ndef BackstageExpireC():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = houtai.backstageexpiring(userid, usertoken)\r\n return jsonify(joininfors)\r\n\r\n\r\n#获取已经过期的公司\r\[email protected]('/backstage/expiredcompanys', methods=['GET'])\r\ndef BackstageExpired():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = houtai.backstageexpired(userid, usertoken)\r\n return jsonify(joininfors)\r\n\r\n#获取所有用户信息\r\[email protected]('/backstage/users', methods=['GET'])\r\ndef BackstageUsers():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = houtai.backstageusers(userid, usertoken)\r\n return jsonify(joininfors)\r\n\r\n\r\n#禁用某个用户\r\[email protected]('/backstage/disableduser', methods=['POST'])\r\ndef DisabledUser():\r\n \r\n request_data = request.get_json()\r\n token = request_data['token']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n if 'disabled' in request_data:\r\n disabled = request_data['disabled']\r\n else:\r\n disabled = None\r\n joininfors = houtai.disabledUser(userid, usertoken, disabled)\r\n return jsonify(joininfors)\r\n\r\n#禁用某家公司\r\[email protected]('/backstage/disabledcompany', methods=['POST'])\r\ndef DisabledCompany():\r\n\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n companyid = request_data[\"companyid\"]\r\n usertoken = token.split('-')[1]\r\n if 'disabled' in request_data:\r\n disabled = request_data['disabled']\r\n else:\r\n disabled = None\r\n joininfors = houtai.disabledCompany(companyid, usertoken, disabled)\r\n return jsonify(joininfors)\r\n\r\n\r\n#获取后台配置信息\r\[email protected]('/backstage/configs', methods=['GET'])\r\ndef BackstageConfigsGet():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n joininfors = houtai.configsGet(userid, usertoken)\r\n return jsonify(joininfors)\r\n\r\n#更改后台配置信息\r\[email protected]('/backstage/configs', methods=['POST'])\r\ndef BackstageConfigsChange():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n if 'customerservice' in request_data:\r\n customerservice = request_data['customerservice']\r\n else:\r\n customerservice = None\r\n if 'expire' in request_data:\r\n expire = request_data['expire']\r\n else:\r\n expire = None\r\n if 'trydate' in request_data:\r\n trydate = request_data['trydate']\r\n else:\r\n trydate = None\r\n joininfors = houtai.configsChange(userid, usertoken, customerservice, expire, trydate)\r\n return jsonify(joininfors)\r\n\r\n#以分页的形式展示所有用户\r\[email protected]('/backstage/pageusers', methods=['GET'])\r\ndef PageUsers():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n page = request.args.get('page')\r\n joininfors = houtai.pageUsers(usertoken, page)\r\n return jsonify(joininfors)\r\n\r\n#以分页的形式展示所有公司\r\[email protected]('/backstage/pagecompanys', methods=['GET'])\r\ndef PageCompanys():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n page = request.args.get('page')\r\n joininfors = houtai.pageCompanys(usertoken, page)\r\n return jsonify(joininfors)\r\n\r\n#修改后台账户和密码\r\[email protected]('/backstage/admin', methods=['POST'])\r\ndef AdminInfo():\r\n\r\n request_data = request.get_json()\r\n username = request_data['username']\r\n password = request_data['password']\r\n joininfors = houtai.AdminInfo(username, password)\r\n return jsonify(joininfors)\r\n\r\n#创建消息\r\[email protected]('/api/v1/message', methods=['POST'])\r\ndef MessageAdd():\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request_data['companyid']\r\n usernewmessage = request_data['message']\r\n usermsgid = request_data['msgid']\r\n joininfors = usermessage.usermessage_insert(usertoken, userid, companyid, usernewmessage, usermsgid)\r\n return jsonify(joininfors)\r\n\r\n#获取消息\r\[email protected]('/api/v1/message', methods=['GET'])\r\ndef MessageGet():\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request.args.get('companyid')\r\n if request.args.get('msgid'):\r\n msgid = request.args.get('msgid')\r\n else:\r\n msgid = None\r\n joininfors = usermessage.usermessage_query(usertoken, userid, companyid, msgid)\r\n return jsonify(joininfors)\r\n\r\n\r\n\r\n# 查询zabbix所有主机信息\r\n\r\[email protected]('/api/v1/zabbixmonitor/getcompanyallhostvalue', methods=['POST'])\r\ndef getcomplanyallhostvalue():\r\n try:\r\n result = dict()\r\n request_data = request.get_json()\r\n print(request_data)\r\n usertoken = request_data['usertoken']\r\n companyid = request_data['companyid']\r\n role = request_data['role']\r\n\r\n\r\n except:\r\n print(\"我错了,dbnszbdnydkysxzjdmx\")\r\n result = {\r\n \"result\": [],\r\n \"msg\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n company_status = Company.query.filter_by(companyid=companyid).first()\r\n if company_status:\r\n company_role = company_status.companyrole\r\n else:\r\n #游客,设置和试用中公司项目的角色\r\n company_role = \"2\"\r\n \r\n #if role == \"0\" and companyid != \"\" and company_role != \"1\":\r\n if role == \"0\" and companyid != \"\":\r\n #合法用户\r\n #with ThreadPoolExecutor(2) as executor:\r\n #all_host_values = executor.submit(zabbix_quey.zabbix_get_complay_hosts, usertoken, companyid)\r\n # result = all_host_values.result()\r\n #result = zabbix_quey.zabbix_get_complay_hosts(usertoken, companyid)\r\n result = zabbix_quey.zabbix_get_complay_hosts(usertoken,companyid)\r\n else:\r\n #游客/待审核用户\r\n result = {\"msg\": \"successful\", \"result\":\r\n [{\"host\": \"192.168.1.100\", \"item\": [{\"available\": 89.1668, \"key\": \"cpu\", \"total\": 100.0},\r\n {\"free\": 12.7165, \"key\": \"disk\", \"partition\": \"/\", \"total\": 100.0},\r\n {\"free\": 31.4891, \"key\": \"disk\", \"partition\": \"/boot\", \"total\": 100.0},\r\n {\"available\": 20.8195, \"key\": \"memory\", \"total\": 31.4851},\r\n {\"available\": 95.9, \"key\": \"network\", \"total\": 100.0}]}], \"status\": 0}\r\n print(result) \r\n #result = zabbix_quey.zabbix_get_complay_hosts(usertoken,companyid)\r\n return jsonify(result)\r\n\r\n\r\n#推送消息给安卓手机\r\[email protected]('/api/v1/msg_push/android', methods=['POST'])\r\ndef push_msg_to_android():\r\n try:\r\n\r\n request_data = request.get_json()\r\n usertoken = request_data['usertoken']\r\n userid = request_data[\"userid\"]\r\n send_packagename = request_data['send_packagename']\r\n send_title = request_data['send_title']\r\n send_msg = request_data['send_msg']\r\n send_msg_desc = request_data['send_msg_desc']\r\n send_pass_through = request_data['send_pass_through']\r\n except:\r\n print(\"parameter error\")\r\n result = {\r\n \"result\": [],\r\n \"msg\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n\r\n result = push_msg.push_msg_to_android(usertoken=usertoken, userid=userid, send_packagename=send_packagename,\r\n send_msg=send_msg, send_title=send_title, send_msg_desc=send_msg_desc,\r\n send_pass_through=send_pass_through)\r\n return jsonify(result)\r\n\r\n#推送消息给ios手机\r\[email protected]('/api/v1/msg_push/ios', methods=['POST'])\r\ndef push_msg_to_ios():\r\n try:\r\n\r\n request_data = request.get_json()\r\n usertoken = request_data['usertoken']\r\n userid = request_data['userid']\r\n send_packagename = request_data['send_packagename']\r\n send_title = request_data['send_title']\r\n send_msg_desc = request_data['send_msg_desc']\r\n send_key = request_data['send_key']\r\n send_value = request_data['send_value']\r\n except:\r\n result = {\r\n \"result\": [],\r\n \"msg\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n\r\n result = push_msg.push_msg_to_ios(userid=userid, usertoken=usertoken, send_packagename=send_packagename,\r\n send_title=send_title, send_msg_desc=send_msg_desc, send_key=send_key,\r\n send_value=send_value)\r\n return result\r\n\r\n#执行salt命令\r\[email protected]('/api/v1/salt/command', methods=['POST'])\r\ndef exec_command():\r\n try:\r\n request_data = request.get_json()\r\n print(request_data)\r\n usertoken = request_data['usertoken']\r\n userid = request_data['userid']\r\n clientip = request_data['clientip']\r\n command = request_data['command']\r\n companyid = request_data['companyid']\r\n hostinfo = Monitor.query.filter_by(zabbixhostname=clientip).first()\r\n clientip = hostinfo.zabbixhostip\r\n hostname = hostinfo.zabbixhostname\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n username = User.query.filter_by(userid=userid).first()\r\n result = salt_exec.main(usertoken=usertoken, username=username.username, clientip=clientip, command=command,\r\n companyid=companyid, hostname=hostname)\r\n\r\n return jsonify(result)\r\n\r\n#搜索操作日志\r\[email protected]('/api/v1/operation/operation_log', methods=['POST'])\r\ndef search_operation_log():\r\n try:\r\n request_data = request.get_json()\r\n usertoken = request_data['usertoken']\r\n companyid = request_data['companyid']\r\n role = request_data['role']\r\n oprole = request_data['oprole']\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n company_status = Company.query.filter_by(companyid=companyid).first()\r\n if company_status:\r\n company_role = company_status.companyrole\r\n else:\r\n # 游客,设置和试用中公司项目的角色\r\n company_role = \"2\"\r\n if role == \"0\" and companyid != \"\" and oprole != \"\" and company_role == \"2\":\r\n result = search_oper_log.search_oper_log(usertoken=usertoken, companyid=companyid)\r\n else:\r\n result = {\r\n \"result\": [\r\n {\r\n \"username\":\"tom\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\":\"2018-12-12 09:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\":\" ( ip :10.0.60.187)\"\r\n },\r\n {\r\n \"username\":\"tom\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\":\"2018-12-10 11:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\":\" ( ip :10.0.60.187)\"\r\n },\r\n {\r\n \"username\":\"jerry\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\":\"2018-12-10 06:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\":\" ( ip :10.0.60.187)\"\r\n }\r\n ],\r\n \"status\": 0\r\n}\r\n return demjson.encode(result)\r\n\r\n#创建操作日志\r\[email protected]('/api/v1/operation/operation_log_save', methods=['POST'])\r\ndef operation_log_save():\r\n try:\r\n request_data = request.get_json()\r\n companyid = request_data['companyid']\r\n username = request_data['username']\r\n exec_com = request_data['exec_com']\r\n ip = request_data['ip']\r\n hostname = request_data['hostname']\r\n exec_time = request_data['exec_time']\r\n print(\"有人吗,有人吗,有人吗,有人吗,有人吗,有人吗\")\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n\r\n result = houtai.save_oper_log(username=username,companyid=companyid,exec_com=exec_com,ip=ip,hostname=hostname,exec_time=exec_time)\r\n return demjson.encode(result)\r\n\r\n#取消某个公司的申请\r\[email protected]('/api/v1/companyapplication_cancel', methods=['POST'])\r\ndef cancel_company_application():\r\n try:\r\n request_data = request.get_json()\r\n token = request_data[\"token\"]\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n companyid = request_data[\"companyid\"]\r\n\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n\r\n result = cancel_companyapplication(companyid=companyid,usertoken=usertoken,userid=userid)\r\n return jsonify(result)\r\n\r\n#获取用户禁用/启用状态\r\[email protected]('/api/v1/userstatus',methods=['GET'])\r\ndef search_userstaus():\r\n try:\r\n token = request.args.get('token')\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n\r\n result = userstatus_search(usertoken=usertoken,userid=userid)\r\n return jsonify(result)\r\n\r\n\r\n#不带条件查询所有的机器人操作日志\r\n#@app.route('/api/v1/operation/search_operation_log', methods=['POST'])\r\ndef search_operation_log_condition(token, companyid, role, oprole):\r\n # try:\r\n # request_data = request.get_json()\r\n # usertoken = request_data['usertoken']\r\n # companyid = request_data['companyid']\r\n # role = request_data['role']\r\n # oprole = request_data['oprole']\r\n # except:\r\n # result = {\r\n # \"result\": \"parameter error\",\r\n # \"status\": -1\r\n # }\r\n # return jsonify(result)\r\n company_status = Company.query.filter_by(companyid=companyid).first()\r\n if company_status:\r\n company_role = company_status.companyrole\r\n else:\r\n # 游客,设置和试用中公司项目的角色\r\n company_role = \"2\"\r\n if role == \"0\" and companyid != \"\" and oprole != \"\" and company_role == \"2\":\r\n result = search_oper_log.search_oper_log(usertoken=token, companyid=companyid)\r\n else:\r\n result = {\r\n \"result\": [\r\n {\r\n \"username\":\"tom\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\":\"2018-12-12 09:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\":\" ( ip :10.0.60.187)\"\r\n },\r\n {\r\n \"username\":\"tom\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\":\"2018-12-10 11:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\":\" ( ip :10.0.60.187)\"\r\n },\r\n {\r\n \"username\":\"jerry\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\":\"2018-12-10 06:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\":\" ( ip :10.0.60.187)\"\r\n }\r\n ],\r\n \"status\": 0\r\n}\r\n return result\r\n\r\n\r\n\"\"\"\r\n#提供过滤日志的条件\r\[email protected]('/api/v1/operation/search_condition', methods=['POST'])\r\ndef search_operation_search_condition():\r\n try:\r\n request_data = request.get_json()\r\n usertoken = request_data['usertoken']\r\n companyid = request_data['companyid']\r\n role = request_data['role']\r\n oprole = request_data['oprole']\r\n search_command = request_data['search_command']\r\n search_user = request_data['search_user']\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n company_status = Company.query.filter_by(companyid=companyid).first()\r\n if company_status:\r\n company_role = company_status.companyrole\r\n else:\r\n # 游客,设置和试用中公司项目的角色\r\n company_role = \"2\"\r\n if role == \"0\" and companyid != \"\" and oprole != \"\" and company_role == \"2\":\r\n result = search_oper_log.operation_search_condition(usertoken=usertoken, companyid=companyid,\r\n search_user=search_user, search_command=search_command)\r\n else:\r\n if search_command == \"0\":\r\n result = {\r\n \"result\": [\r\n {\r\n \"groupName\": \"监控项目\",\r\n \"orders\":[\r\n {\r\n \"name\":\"查看主机CPU\",\r\n \"orderId\":\"10\",\r\n \"type\":\"3\"\r\n },\r\n {\r\n \"name\":\"查看主机内存\",\r\n \"orderId\":\"11\",\r\n \"type\":\"4\"\r\n },\r\n {\r\n \"name\":\"查看网络流量\",\r\n \"orderId\":\"12\",\r\n \"type\":\"8\"\r\n },\r\n {\r\n \"name\":\"查看磁盘空间\",\r\n \"orderId\":\"13\",\r\n \"type\":\"6\"\r\n },\r\n {\r\n \"name\":\"查看磁盘读写\",\r\n \"orderId\":\"4\",\r\n \"type\":\"12\"\r\n },\r\n {\r\n \"name\":\"查看端口连接数\",\r\n \"orderId\":\"4\"\r\n }\r\n ]},\r\n {\r\n \"groupName\": \"重启项目\",\r\n \"orders\":[\r\n {\r\n \"name\":\"服务器重启\",\r\n \"orderId\":\"20\",\r\n \"type\":\"10\"\r\n },\r\n {\r\n \"name\":\"重启tomcat应用\",\r\n \"orderId\":\"21\"\r\n },\r\n {\r\n \"name\":\"重启mysql数据库服务\",\r\n \"orderId\":\"22\"\r\n }]\r\n },\r\n #{\r\n # \"groupName\": \"数据库查询\",\r\n # \"orders\":[\r\n # {\r\n # \"name\":\"查询数据库表空间\",\r\n # \"orderId\":\"30\"\r\n # },\r\n # {\r\n # \"name\":\"查询单表空间\",\r\n # \"orderId\":\"31\"\r\n # },\r\n # {\r\n # \"name\":\"查询数据库锁\",\r\n # \"orderId\":\"32\"\r\n # },\r\n # {\r\n # \"name\":\"查询数据库会话数\",\r\n # \"orderId\":\"32\"\r\n # }]\r\n # },\r\n\t\t\t\t\t{\r\n \"groupName\": \"命令操作日志\",\r\n \"orders\":[\r\n {\r\n \"name\":\"查看命令操作日志\",\r\n \"orderId\":\"40\"\r\n }]\r\n\r\n\t\t\t\t\t}],\r\n \"msg\": \"successful\",\r\n \"status\": 0\r\n }\r\n else:\r\n result = {\r\n \"result\": [{\"operationId\":\"u2LPwkUyAGfOUIovJrCC1\",\r\n \"operationImage\":\"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"operationName\":\"tom\"},\r\n {\"operationId\":\"u2LPwkUyAGfOUIovJrCC1\",\r\n \"operationImage\":\"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"operationName\":\"jerry\"},\r\n {\"operationId\":\"u2LPwkUyAGfOUIovJrCC1\",\r\n \"operationImage\":\"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"operationName\":\"\\u5f20\\u4e09\"}],\r\n \"msg\": \"successful\",\r\n \"status\": 0\r\n }\r\n\r\n return demjson.encode(result)\r\n\"\"\"\r\n\r\n#提供过滤日志的条件\r\[email protected]('/api/v1/operation/search_condition', methods=['POST'])\r\ndef search_operation_search_condition():\r\n try:\r\n request_data = request.get_json()\r\n print(request_data)\r\n usertoken = request_data['usertoken']\r\n companyid = request_data['companyid']\r\n role = request_data['role']\r\n oprole = request_data['oprole']\r\n search_command = request_data['search_command']\r\n search_user = request_data['search_user']\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n company_status = Company.query.filter_by(companyid=companyid).first()\r\n if company_status:\r\n company_role = company_status.companyrole\r\n else:\r\n # 游客,设置和试用中公司项目的角色\r\n company_role = \"2\"\r\n if role == \"0\" and companyid != \"\" and oprole != \"\" and company_role == \"2\":\r\n result = search_oper_log.operation_search_condition(usertoken=usertoken, companyid=companyid,\r\n search_user=search_user, search_command=search_command)\r\n else:\r\n if search_command == \"0\":\r\n result = {\r\n \"result\": [\r\n {\r\n \"groupName\": \"监控项目\",\r\n \"orders\":[\r\n {\r\n \"name\":\"查看主机CPU\",\r\n \"orderId\":\"10\",\r\n \"type\":\"3\"\r\n },\r\n {\r\n \"name\":\"查看主机内存\",\r\n \"orderId\":\"11\",\r\n \"type\":\"4\"\r\n },\r\n {\r\n \"name\":\"查看网络流量\",\r\n \"orderId\":\"12\",\r\n \"type\":'8'\r\n\r\n },\r\n {\r\n \"name\":\"查看磁盘状态\",\r\n \"orderId\":\"13\",\r\n \"type\":'6'\r\n }\r\n ]},\r\n {\r\n \"groupName\": \"重启项目\",\r\n \"orders\":[\r\n {\r\n \"name\":\"服务器重启\",\r\n \"orderId\":\"20\",\r\n \"type\":\"10\"\r\n }]\r\n },\r\n #{\r\n # \"groupName\": \"数据库查询\",\r\n # \"orders\":[\r\n # \r\n #]\r\n #},\r\n\t\t {\r\n \"groupName\": \"命令操作日志\",\r\n \"orders\":[\r\n {\r\n \"name\":\"查看命令操作日志\",\r\n \"orderId\":\"5\"\r\n }]\r\n\r\n\t\t\t\t\t}],\r\n \"msg\": \"successful\",\r\n \"status\": 0\r\n }\r\n else:\r\n result = {\r\n \"result\": [{\"operationId\":\"u2LPwkUyAGfOUIovJrCC1\",\r\n \"operationImage\":\"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"operationName\":\"tom\"},\r\n {\"operationId\":\"u2LPwkUyAGfOUIovJrCC1\",\r\n \"operationImage\":\"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"operationName\":\"jerry\"},\r\n {\"operationId\":\"u2LPwkUyAGfOUIovJrCC1\",\r\n \"operationImage\":\"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"operationName\":\"\\u5f20\\u4e09\"}],\r\n \"msg\": \"successful\",\r\n \"status\": 0\r\n }\r\n\r\n return demjson.encode(result)\r\n\r\n#带条件搜索机器人操作日志\r\[email protected]('/api/v1/operation/search_operation_log_condition', methods=['POST'])\r\ndef search_operation_with_condition():\r\n try:\r\n request_data = request.get_json()\r\n print(request_data)\r\n usertoken = request_data['usertoken']\r\n companyid = request_data['companyid']\r\n role = request_data['role']\r\n oprole = request_data['oprole']\r\n search_command_id = request_data[\"orderid\"]\r\n search_userid = request_data[\"operatorid\"]\r\n starttime = request_data['starttime']\r\n endtime = request_data['endtime']\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return jsonify(result)\r\n company_status = Company.query.filter_by(companyid=companyid).first()\r\n if company_status:\r\n company_role = company_status.companyrole\r\n else:\r\n # 游客,设置和试用中公司项目的角色\r\n company_role = \"2\"\r\n if role == \"0\" and companyid != \"\" and oprole != \"\" and company_role == \"2\":\r\n #执行不需要在服务器上执行的命令\r\n if search_command_id == \"5\":\r\n result = search_operation_log_condition(token=usertoken, companyid=companyid, role=role, oprole=oprole)\r\n else:\r\n result = search_oper_log.operation_search_with_condition(usertoken=usertoken, companyid=companyid,\r\n search_command_id=search_command_id,\r\n search_user_id=search_userid,\r\n starttime=starttime, endtime=endtime)\r\n else:\r\n result = {\r\n \"result\": [\r\n {\r\n \"username\": \"tom\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\": \"2018-12-12 09:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\": \" ( ip :10.0.60.187)\"\r\n },\r\n {\r\n \"username\": \"tom\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\": \"2018-12-10 11:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\": \" ( ip :10.0.60.187)\"\r\n },\r\n {\r\n \"username\": \"jerry\",\r\n \"user_image\": \"http://139.196.107.14:6001/upload/2018-11-12/[email protected]\",\r\n \"exec_time\": \"2018-12-10 06:28:53\",\r\n \"operating_command\": \"重启服务器 \",\r\n \"msg\": \" ( ip :10.0.60.187)\"\r\n }\r\n ],\r\n \"status\": 0\r\n }\r\n\r\n return demjson.encode(result)\r\n\r\n\"\"\"\r\n#获取公司状态\r\[email protected]('/api/v1/companyStatus', methods=['GET'])\r\ndef CompanyStatus():\r\n companyid = request.args.get('companyid')\r\n companyStatus = getCompanyStatus(companyid)\r\n return jsonify(companyStatus)\r\n\"\"\"\r\n\r\n# 获取用户公司状态\r\[email protected]('/api/v1/userCompanyStatus', methods=['GET'])\r\ndef UserCompanyStatus():\r\n \r\n token = request.args.get('token')\r\n companyid = request.args.get('companyid')\r\n userid = token.split('-')[0]\r\n userCompanyStatus = getUserCompanyStatus(userid, companyid)\r\n return jsonify(userCompanyStatus)\r\n\r\n\r\n#获取目标主机磁盘性能\r\[email protected]('/api/v1/salt/diskperformance', methods=['POST'])\r\ndef user_exec_command():\r\n try:\r\n request_data = request.get_json()\r\n token = request_data['token']\r\n userid = token.split('-')[0]\r\n usertoken = token.split('-')[1]\r\n clientip = request_data['clientip']\r\n commandid = int(request_data['commandid'])\r\n companyid = request_data['companyid']\r\n oprole = request_data['oprole']\r\n role = request_data['role']\r\n except:\r\n result = {\r\n \"result\": \"parameter error\",\r\n \"status\": -1\r\n }\r\n return demjson.encode(result)\r\n company_status = Company.query.filter_by(companyid=companyid).first()\r\n if company_status:\r\n company_role = company_status.companyrole\r\n else:\r\n # 游客,设置和试用中公司项目的角色\r\n company_role = \"2\"\r\n if role == \"0\" and companyid != \"\" and oprole != \"\" and company_role == \"2\":\r\n username = User.query.filter_by(userid=userid).first()\r\n with ThreadPoolExecutor(2) as executor:\r\n cmd_result = executor.submit(salt_exec.exec_passport, username.username, usertoken, clientip,\r\n commandid, companyid)\r\n result = cmd_result.result()\r\n # result = salt_exec.exec_passport(usertoken=usertoken, username=username.username, clientip=clientip,\r\n # commandid=commandid, companyid=companyid)\r\n else:\r\n result = {\"msg\":\"successful\",\r\n \"result\":{\"command_result\":[{\"Blk_read\":\"7.26\",\"Blk_wrtn\":\"534.83\",\"Device\":\"sda\"}],\r\n \"server\":\"192.168.1.1\"},\"status\":0}\r\n\r\n return demjson.encode(result)\r\n\r\[email protected]('/api/v1/md5', methods=['POST'])\r\ndef UserRegistr111y():\r\n\r\n registryrs = md5_password()\r\n return jsonify(registryrs)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debugTrue, host='0.0.0.0', port=5000)\r\n" }, { "alpha_fraction": 0.7251184582710266, "alphanum_fraction": 0.7381516695022583, "avg_line_length": 43.421051025390625, "blob_id": "cd44a0cf356d47019a8e104a96ec82d4fef7ec77", "content_id": "ce1be281a0e2aa5d6d94c278c746ee48b5a416e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 852, "license_type": "no_license", "max_line_length": 118, "num_lines": 19, "path": "/houtaiapi/Dockerfile", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "FROM python:3.6.7-jessie \n\n#RUN echo \"https://mirrors.aliyun.com/alpine/v3.8/main\" > /etc/apk/repositories\n#RUN echo \"https://mirrors.aliyun.com/alpine/v3.8/community\" >> /etc/apk/repositories \nWORKDIR /data\n#RUN apk update && apk add gcc libc-dev pcre pcre-dev libffi-dev openssl-dev \nRUN apt-get update && apt-get install curl -y\nRUN pip3 install -i https://pypi.douban.com/simple flask_socketio flask flask_sqlalchemy sqlalchemy pymysql requests \nRUN pip3 install -i https://pypi.douban.com/simple uwsgi socketIO-client\nRUN pip3 install -i https://pypi.douban.com/simple flask_cors\n\n\n#设置时区\nRUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone\n#RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime\n \nADD . /data\n#CMD [\"python3\", \"http_chat.py\"]\nCMD [\"uwsgi\", \"--ini\", \"houtaiapi.ini\"]\n" }, { "alpha_fraction": 0.5243865847587585, "alphanum_fraction": 0.5300717949867249, "avg_line_length": 41.03773498535156, "blob_id": "8b72c542f10c94599cb7b796403b191420639c20", "content_id": "24b0e889552f77937ecf44ce645005eafc734840", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6816, "license_type": "no_license", "max_line_length": 114, "num_lines": 159, "path": "/chatapi/usermessage.py", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "from model import *\nimport sqlalchemy\n\n\ndef usermessage_insert(usertoken, userid, companyid, usernewmessage, usermsgid):\n try:\n if usertoken != '11111':\n return {'status': 1, 'msg': 'Ooooops, token不可用'}\n\n usernewmessage = str(usernewmessage)\n\n insert_mobile = Talkmsg(msgid=usermsgid, msguserid=userid, msgcompanyid=companyid, message=usernewmessage)\n db.session.add(insert_mobile)\n db.session.commit()\n db.session.close()\n return {'status':0, 'msg': 'ok'}\n except sqlalchemy.exc.OperationalError:\n return {'Oooops': '数据库连接似乎出了问题'}\n\n\n\n\"\"\"\ndef usermessage_query(usertoken, userid, companyid, usermsgid):\n try:\n if usertoken != '11111':\n return {'status': 1, 'msg': 'Ooooops, token不可用'}\n\n check_user_role_query = User.query.filter_by(userid=userid).first()\n user_role = check_user_role_query.role\n if user_role == '1' or user_role == '2':\n db.session.close()\n return {'status': 2, 'msg': ''}\n\n if usermsgid:\n\n message_create_time_query = Talkmsg.query.filter_by(msgid=usermsgid, msgcompanyid=companyid).first()\n\n print(message_create_time_query)\n message_create_time = message_create_time_query.createtime\n message_database_id = message_create_time_query.id\n user_message_query_page = Talkmsg.query.filter(Talkmsg.createtime >= message_create_time,\n Talkmsg.msgcompanyid==companyid,\n Talkmsg.msgid != usermsgid,\n Talkmsg.id > message_database_id).all()\n\n user_message_query_page_total = len(user_message_query_page)\n\n if user_message_query_page_total > 300:\n\n user_message_query_page = Talkmsg.query.filter(Talkmsg.msgcompanyid == companyid).order_by(\n Talkmsg.createtime.desc()).paginate(1, per_page=300, error_out=False)\n\n rs = user_message_query_page.items\n msg_rs_list = []\n for user_message in rs:\n if user_message.msgid != usermsgid:\n return_message = eval(user_message.message)\n msg_rs_list.append(return_message)\n db.session.close()\n return {'status': 0, 'msg':'查询成功', 'data':msg_rs_list}\n else:\n msg_rs_list = []\n for user_message in user_message_query_page:\n if user_message.msgid != usermsgid:\n return_message = eval(user_message.message)\n msg_rs_list.append(return_message)\n db.session.close()\n return {'status': 0, 'msg':'查询成功', 'data':msg_rs_list}\n\n\n else:\n user_message_query_page = Talkmsg.query.filter(Talkmsg.msgcompanyid == companyid).order_by(\n Talkmsg.createtime.desc()).paginate(1, per_page=300, error_out=False)\n\n\n\n rs = user_message_query_page.items\n\n msg_rs_list = []\n for user_message in rs:\n if user_message.msgid != usermsgid:\n return_message = eval(user_message.message)\n msg_rs_list.append(return_message)\n db.session.close()\n return {'status': 0, 'msg': '查询成功', 'data': msg_rs_list}\n\n except sqlalchemy.exc.OperationalError:\n return {'Oooops': '数据库连接似乎出了问题'}\n\"\"\"\n\n\n\ndef usermessage_query(usertoken, userid, companyid, usermsgid):\n try:\n if usertoken != '11111':\n return {'status': 1, 'msg': 'Ooooops, token不可用'}\n\n check_user_role_query = User.query.filter_by(userid=userid).first()\n user_role = check_user_role_query.role\n if user_role == '1' or user_role == '2':\n db.session.close()\n return {'status': 2, 'msg': ''}\n\n if usermsgid:\n\n message_create_time_query = Talkmsg.query.filter_by(msgid=usermsgid, msgcompanyid=companyid).first()\n\n print(message_create_time_query)\n if message_create_time_query:\n message_create_time = message_create_time_query.createtime\n message_database_id = message_create_time_query.id\n user_message_query_page = Talkmsg.query.filter(Talkmsg.createtime >= message_create_time,\n Talkmsg.msgcompanyid==companyid,\n Talkmsg.msgid != usermsgid,\n Talkmsg.id > message_database_id).all()\n\n user_message_query_page_total = len(user_message_query_page)\n\n if user_message_query_page_total > 100:\n\n user_message_query_page = Talkmsg.query.filter(Talkmsg.msgcompanyid == companyid).order_by(\n Talkmsg.createtime.desc()).paginate(1, per_page=100, error_out=False)\n\n rs = user_message_query_page.items\n msg_rs_list = []\n for user_message in rs:\n if user_message.msgid != usermsgid:\n return_message = eval(user_message.message)\n msg_rs_list.append(return_message)\n db.session.close()\n return {'status': 0, 'msg':'查询成功', 'data':msg_rs_list}\n else:\n msg_rs_list = []\n for user_message in user_message_query_page:\n if user_message.msgid != usermsgid:\n return_message = eval(user_message.message)\n msg_rs_list.append(return_message)\n db.session.close()\n return {'status': 0, 'msg':'查询成功', 'data':msg_rs_list}\n\n\n else:\n user_message_query_page = Talkmsg.query.filter(Talkmsg.msgcompanyid == companyid).order_by(\n Talkmsg.createtime.desc()).paginate(1, per_page=100, error_out=False)\n\n\n\n rs = user_message_query_page.items\n\n msg_rs_list = []\n for user_message in rs:\n if user_message.msgid != usermsgid:\n return_message = eval(user_message.message)\n msg_rs_list.append(return_message)\n db.session.close()\n return {'status': 0, 'msg': '查询成功', 'data': msg_rs_list}\n\n except sqlalchemy.exc.OperationalError:\n return {'Oooops': '数据库连接似乎出了问题'}\n" }, { "alpha_fraction": 0.7094972133636475, "alphanum_fraction": 0.7374301552772522, "avg_line_length": 28.83333396911621, "blob_id": "71b657018fc65eabdb170d592ac463ce6519e403", "content_id": "638d8abd1f72c2a25290ba3807a1c687044d11af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 366, "license_type": "no_license", "max_line_length": 99, "num_lines": 12, "path": "/chatbot-youke1/Dockerfile", "repo_name": "biaogelaile/yqjqr", "src_encoding": "UTF-8", "text": "#FROM python:3.6.6-alpine3.8 \nFROM python:3.6.7-jessie\n\nWORKDIR /data\nRUN pip3 install -i https://pypi.douban.com/simple socketIO-client requests\n\n#设置时区\nRUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone\n#RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime\n\nADD . /data\nCMD [\"python3\", \"chatbot.py\"]\n" } ]
42
EPFL-LAP/fpga19-MOMS
https://github.com/EPFL-LAP/fpga19-MOMS
751290e66eb735a1c35150d25e9684fbe0cd7059
67e563fc7fa626c8fcbefdf845f235977438651e
0df4365fa101246176b7bc76b561cb14b499c42b
refs/heads/master
2023-01-28T17:48:00.954883
2019-07-12T12:34:31
2019-07-12T12:34:31
318,141,721
9
4
null
null
null
null
null
[ { "alpha_fraction": 0.7024024724960327, "alphanum_fraction": 0.7133731245994568, "avg_line_length": 38.344261169433594, "blob_id": "850154bd852f69747b6964ad09b5c00e5c8f3e73", "content_id": "acc1b5674c117e42c9e7962808f469e8848f46c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7201, "license_type": "permissive", "max_line_length": 119, "num_lines": 183, "path": "/spmv/TopLevel/TopLevel.srcs/sources_1/ip/spmv_mult_axis_0_1/drivers/spmv_mult_axis_v1_0/src/xspmv_mult_axis.c", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "// ==============================================================\n// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC\n// Version: 2017.4\n// Copyright (C) 1986-2017 Xilinx, Inc. All Rights Reserved.\n// \n// ==============================================================\n\n/***************************** Include Files *********************************/\n#include \"xspmv_mult_axis.h\"\n\n/************************** Function Implementation *************************/\n#ifndef __linux__\nint XSpmv_mult_axis_CfgInitialize(XSpmv_mult_axis *InstancePtr, XSpmv_mult_axis_Config *ConfigPtr) {\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(ConfigPtr != NULL);\n\n InstancePtr->Axilites_BaseAddress = ConfigPtr->Axilites_BaseAddress;\n InstancePtr->IsReady = XIL_COMPONENT_IS_READY;\n\n return XST_SUCCESS;\n}\n#endif\n\nvoid XSpmv_mult_axis_Start(XSpmv_mult_axis *InstancePtr) {\n u32 Data;\n\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL) & 0x80;\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL, Data | 0x01);\n}\n\nu32 XSpmv_mult_axis_IsDone(XSpmv_mult_axis *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL);\n return (Data >> 1) & 0x1;\n}\n\nu32 XSpmv_mult_axis_IsIdle(XSpmv_mult_axis *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL);\n return (Data >> 2) & 0x1;\n}\n\nu32 XSpmv_mult_axis_IsReady(XSpmv_mult_axis *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL);\n // check ap_start to see if the pcore is ready for next input\n return !(Data & 0x1);\n}\n\nvoid XSpmv_mult_axis_EnableAutoRestart(XSpmv_mult_axis *InstancePtr) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL, 0x80);\n}\n\nvoid XSpmv_mult_axis_DisableAutoRestart(XSpmv_mult_axis *InstancePtr) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL, 0);\n}\n\nvoid XSpmv_mult_axis_Set_val_size(XSpmv_mult_axis *InstancePtr, u32 Data) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_VAL_SIZE_DATA, Data);\n}\n\nu32 XSpmv_mult_axis_Get_val_size(XSpmv_mult_axis *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_VAL_SIZE_DATA);\n return Data;\n}\n\nvoid XSpmv_mult_axis_Set_output_size(XSpmv_mult_axis *InstancePtr, u32 Data) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_OUTPUT_SIZE_DATA, Data);\n}\n\nu32 XSpmv_mult_axis_Get_output_size(XSpmv_mult_axis *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_OUTPUT_SIZE_DATA);\n return Data;\n}\n\nvoid XSpmv_mult_axis_Set_vect_mem(XSpmv_mult_axis *InstancePtr, u32 Data) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_VECT_MEM_DATA, Data);\n}\n\nu32 XSpmv_mult_axis_Get_vect_mem(XSpmv_mult_axis *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_VECT_MEM_DATA);\n return Data;\n}\n\nvoid XSpmv_mult_axis_InterruptGlobalEnable(XSpmv_mult_axis *InstancePtr) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_GIE, 1);\n}\n\nvoid XSpmv_mult_axis_InterruptGlobalDisable(XSpmv_mult_axis *InstancePtr) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_GIE, 0);\n}\n\nvoid XSpmv_mult_axis_InterruptEnable(XSpmv_mult_axis *InstancePtr, u32 Mask) {\n u32 Register;\n\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Register = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_IER);\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_IER, Register | Mask);\n}\n\nvoid XSpmv_mult_axis_InterruptDisable(XSpmv_mult_axis *InstancePtr, u32 Mask) {\n u32 Register;\n\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Register = XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_IER);\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_IER, Register & (~Mask));\n}\n\nvoid XSpmv_mult_axis_InterruptClear(XSpmv_mult_axis *InstancePtr, u32 Mask) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XSpmv_mult_axis_WriteReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_ISR, Mask);\n}\n\nu32 XSpmv_mult_axis_InterruptGetEnabled(XSpmv_mult_axis *InstancePtr) {\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n return XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_IER);\n}\n\nu32 XSpmv_mult_axis_InterruptGetStatus(XSpmv_mult_axis *InstancePtr) {\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n return XSpmv_mult_axis_ReadReg(InstancePtr->Axilites_BaseAddress, XSPMV_MULT_AXIS_AXILITES_ADDR_ISR);\n}\n\n" }, { "alpha_fraction": 0.5406484007835388, "alphanum_fraction": 0.5900249481201172, "avg_line_length": 41.63829803466797, "blob_id": "78783b155b9e23cc1e143ce53a46bff705b3709e", "content_id": "f5ccacec2ddda3f9f9a9022a45fb2182a3e9bdf7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2005, "license_type": "permissive", "max_line_length": 90, "num_lines": 47, "path": "/spmv/TopLevel/TopLevel.srcs/sources_1/ip/spmv_mult_axis_0_2/drivers/spmv_mult_axis_v1_0/src/xspmv_mult_axis_hw.h", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "// ==============================================================\n// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC\n// Version: 2017.4\n// Copyright (C) 1986-2017 Xilinx, Inc. All Rights Reserved.\n// \n// ==============================================================\n\n// AXILiteS\n// 0x00 : Control signals\n// bit 0 - ap_start (Read/Write/COH)\n// bit 1 - ap_done (Read/COR)\n// bit 2 - ap_idle (Read)\n// bit 3 - ap_ready (Read)\n// bit 7 - auto_restart (Read/Write)\n// others - reserved\n// 0x04 : Global Interrupt Enable Register\n// bit 0 - Global Interrupt Enable (Read/Write)\n// others - reserved\n// 0x08 : IP Interrupt Enable Register (Read/Write)\n// bit 0 - Channel 0 (ap_done)\n// bit 1 - Channel 1 (ap_ready)\n// others - reserved\n// 0x0c : IP Interrupt Status Register (Read/TOW)\n// bit 0 - Channel 0 (ap_done)\n// bit 1 - Channel 1 (ap_ready)\n// others - reserved\n// 0x10 : Data signal of val_size\n// bit 31~0 - val_size[31:0] (Read/Write)\n// 0x14 : reserved\n// 0x18 : Data signal of output_size\n// bit 31~0 - output_size[31:0] (Read/Write)\n// 0x1c : reserved\n// 0x20 : Data signal of vect_mem\n// bit 31~0 - vect_mem[31:0] (Read/Write)\n// 0x24 : reserved\n// (SC = Self Clear, COR = Clear on Read, TOW = Toggle on Write, COH = Clear on Handshake)\n\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL 0x00\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_GIE 0x04\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_IER 0x08\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_ISR 0x0c\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_VAL_SIZE_DATA 0x10\n#define XSPMV_MULT_AXIS_AXILITES_BITS_VAL_SIZE_DATA 32\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_OUTPUT_SIZE_DATA 0x18\n#define XSPMV_MULT_AXIS_AXILITES_BITS_OUTPUT_SIZE_DATA 32\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_VECT_MEM_DATA 0x20\n#define XSPMV_MULT_AXIS_AXILITES_BITS_VECT_MEM_DATA 32\n\n" }, { "alpha_fraction": 0.6578654646873474, "alphanum_fraction": 0.6798221468925476, "avg_line_length": 32.00917434692383, "blob_id": "ec1d73bdd115145c6ea1e3e26281d7f14a564011", "content_id": "0a3e024069d0e4273d8f3e6dc30720a549a70c79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3598, "license_type": "permissive", "max_line_length": 87, "num_lines": 109, "path": "/spmv/RTLFullyPipelinedSpMV/RTLFullyPipelinedSpMV.srcs/sources_1/ip/len_stream_0/drivers/len_stream_v1_0/src/xlen_stream.h", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "// ==============================================================\n// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC\n// Version: 2017.4\n// Copyright (C) 1986-2017 Xilinx, Inc. All Rights Reserved.\n// \n// ==============================================================\n\n#ifndef XLEN_STREAM_H\n#define XLEN_STREAM_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/***************************** Include Files *********************************/\n#ifndef __linux__\n#include \"xil_types.h\"\n#include \"xil_assert.h\"\n#include \"xstatus.h\"\n#include \"xil_io.h\"\n#else\n#include <stdint.h>\n#include <assert.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/mman.h>\n#include <unistd.h>\n#include <stddef.h>\n#endif\n#include \"xlen_stream_hw.h\"\n\n/**************************** Type Definitions ******************************/\n#ifdef __linux__\ntypedef uint8_t u8;\ntypedef uint16_t u16;\ntypedef uint32_t u32;\n#else\ntypedef struct {\n u16 DeviceId;\n u32 Axilites_BaseAddress;\n} XLen_stream_Config;\n#endif\n\ntypedef struct {\n u32 Axilites_BaseAddress;\n u32 IsReady;\n} XLen_stream;\n\n/***************** Macros (Inline Functions) Definitions *********************/\n#ifndef __linux__\n#define XLen_stream_WriteReg(BaseAddress, RegOffset, Data) \\\n Xil_Out32((BaseAddress) + (RegOffset), (u32)(Data))\n#define XLen_stream_ReadReg(BaseAddress, RegOffset) \\\n Xil_In32((BaseAddress) + (RegOffset))\n#else\n#define XLen_stream_WriteReg(BaseAddress, RegOffset, Data) \\\n *(volatile u32*)((BaseAddress) + (RegOffset)) = (u32)(Data)\n#define XLen_stream_ReadReg(BaseAddress, RegOffset) \\\n *(volatile u32*)((BaseAddress) + (RegOffset))\n\n#define Xil_AssertVoid(expr) assert(expr)\n#define Xil_AssertNonvoid(expr) assert(expr)\n\n#define XST_SUCCESS 0\n#define XST_DEVICE_NOT_FOUND 2\n#define XST_OPEN_DEVICE_FAILED 3\n#define XIL_COMPONENT_IS_READY 1\n#endif\n\n/************************** Function Prototypes *****************************/\n#ifndef __linux__\nint XLen_stream_Initialize(XLen_stream *InstancePtr, u16 DeviceId);\nXLen_stream_Config* XLen_stream_LookupConfig(u16 DeviceId);\nint XLen_stream_CfgInitialize(XLen_stream *InstancePtr, XLen_stream_Config *ConfigPtr);\n#else\nint XLen_stream_Initialize(XLen_stream *InstancePtr, const char* InstanceName);\nint XLen_stream_Release(XLen_stream *InstancePtr);\n#endif\n\nvoid XLen_stream_Start(XLen_stream *InstancePtr);\nu32 XLen_stream_IsDone(XLen_stream *InstancePtr);\nu32 XLen_stream_IsIdle(XLen_stream *InstancePtr);\nu32 XLen_stream_IsReady(XLen_stream *InstancePtr);\nvoid XLen_stream_EnableAutoRestart(XLen_stream *InstancePtr);\nvoid XLen_stream_DisableAutoRestart(XLen_stream *InstancePtr);\n\nvoid XLen_stream_Set_val_size(XLen_stream *InstancePtr, u32 Data);\nu32 XLen_stream_Get_val_size(XLen_stream *InstancePtr);\nvoid XLen_stream_Set_output_size(XLen_stream *InstancePtr, u32 Data);\nu32 XLen_stream_Get_output_size(XLen_stream *InstancePtr);\nvoid XLen_stream_Set_offset(XLen_stream *InstancePtr, u32 Data);\nu32 XLen_stream_Get_offset(XLen_stream *InstancePtr);\n\nvoid XLen_stream_InterruptGlobalEnable(XLen_stream *InstancePtr);\nvoid XLen_stream_InterruptGlobalDisable(XLen_stream *InstancePtr);\nvoid XLen_stream_InterruptEnable(XLen_stream *InstancePtr, u32 Mask);\nvoid XLen_stream_InterruptDisable(XLen_stream *InstancePtr, u32 Mask);\nvoid XLen_stream_InterruptClear(XLen_stream *InstancePtr, u32 Mask);\nu32 XLen_stream_InterruptGetEnabled(XLen_stream *InstancePtr);\nu32 XLen_stream_InterruptGetStatus(XLen_stream *InstancePtr);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.5274725556373596, "alphanum_fraction": 0.5472527742385864, "avg_line_length": 41.924530029296875, "blob_id": "33fa9c9b9407767a20f83aba1488d96d0a4e3c72", "content_id": "863580abc4bce11b8f4e4c78ec34b36c51b18b12", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2275, "license_type": "permissive", "max_line_length": 53, "num_lines": 53, "path": "/src/main/resources/axi4.py", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "__port_map = {\n 'AWID' : 'io_{0}_writeAddr_bits_id',\n 'AWADDR' : 'io_{0}_writeAddr_bits_addr',\n 'AWLEN' : 'io_{0}_writeAddr_bits_burst_len',\n 'AWSIZE' : 'io_{0}_writeAddr_bits_burst_size',\n 'AWBURST' : 'io_{0}_writeAddr_bits_burst_burst',\n 'AWLOCK' : 'io_{0}_writeAddr_bits_lock_lock',\n 'AWCACHE' : 'io_{0}_writeAddr_bits_cache_cache',\n 'AWPROT' : 'io_{0}_writeAddr_bits_prot_prot',\n 'AWQOS' : 'io_{0}_writeAddr_bits_qos',\n 'AWREGION' : 'io_{0}_writeAddr_bits_region',\n 'AWUSER' : 'io_{0}_writeAddr_bits_user',\n 'AWVALID' : 'io_{0}_writeAddr_valid',\n 'AWREADY' : 'io_{0}_writeAddr_ready',\n 'WID' : 'io_{0}_writeData_bits_id',\n 'WDATA' : 'io_{0}_writeData_bits_data',\n 'WSTRB' : 'io_{0}_writeData_bits_strb_strb',\n 'WLAST' : 'io_{0}_writeData_bits_last',\n 'WUSER' : 'io_{0}_writeData_bits_user',\n 'WVALID' : 'io_{0}_writeData_valid',\n 'WREADY' : 'io_{0}_writeData_ready',\n 'BID' : 'io_{0}_writeResp_bits_bid',\n 'BRESP' : 'io_{0}_writeResp_bits_bresp',\n 'BUSER' : 'io_{0}_writeResp_bits_buser',\n 'BVALID' : 'io_{0}_writeResp_valid',\n 'BREADY' : 'io_{0}_writeResp_ready',\n 'ARID' : 'io_{0}_readAddr_bits_id',\n 'ARADDR' : 'io_{0}_readAddr_bits_addr',\n 'ARLEN' : 'io_{0}_readAddr_bits_burst_len',\n 'ARSIZE' : 'io_{0}_readAddr_bits_burst_size',\n 'ARBURST' : 'io_{0}_readAddr_bits_burst_burst',\n 'ARLOCK' : 'io_{0}_readAddr_bits_lock_lock',\n 'ARCACHE' : 'io_{0}_readAddr_bits_cache_cache',\n 'ARPROT' : 'io_{0}_readAddr_bits_prot_prot',\n 'ARQOS' : 'io_{0}_readAddr_bits_qos',\n 'ARREGION' : 'io_{0}_readAddr_bits_region',\n 'ARUSER' : 'io_{0}_readAddr_bits_user',\n 'ARVALID' : 'io_{0}_readAddr_valid',\n 'ARREADY' : 'io_{0}_readAddr_ready',\n 'RID' : 'io_{0}_readData_bits_id',\n 'RDATA' : 'io_{0}_readData_bits_data',\n 'RRESP' : 'io_{0}_readData_bits_resp',\n 'RLAST' : 'io_{0}_readData_bits_last',\n 'RUSER' : 'io_{0}_readData_bits_user',\n 'RVALID' : 'io_{0}_readData_valid',\n 'RREADY' : 'io_{0}_readData_ready'\n}\n\ndef get_port_dict(name):\n retdict = {}\n for k, v in __port_map.items():\n retdict[k] = v.format(name)\n return retdict\n" }, { "alpha_fraction": 0.7002481818199158, "alphanum_fraction": 0.7117827534675598, "avg_line_length": 36.4207649230957, "blob_id": "183715488ee95f37636fce936f2ca471f3453fed", "content_id": "e597700e9157f97057caa9c5fd236353f36f56d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6849, "license_type": "permissive", "max_line_length": 111, "num_lines": 183, "path": "/spmv/RTLFullyPipelinedSpMV/RTLFullyPipelinedSpMV.srcs/sources_1/ip/len_stream_0/drivers/len_stream_v1_0/src/xlen_stream.c", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "// ==============================================================\n// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC\n// Version: 2017.4\n// Copyright (C) 1986-2017 Xilinx, Inc. All Rights Reserved.\n// \n// ==============================================================\n\n/***************************** Include Files *********************************/\n#include \"xlen_stream.h\"\n\n/************************** Function Implementation *************************/\n#ifndef __linux__\nint XLen_stream_CfgInitialize(XLen_stream *InstancePtr, XLen_stream_Config *ConfigPtr) {\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(ConfigPtr != NULL);\n\n InstancePtr->Axilites_BaseAddress = ConfigPtr->Axilites_BaseAddress;\n InstancePtr->IsReady = XIL_COMPONENT_IS_READY;\n\n return XST_SUCCESS;\n}\n#endif\n\nvoid XLen_stream_Start(XLen_stream *InstancePtr) {\n u32 Data;\n\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_AP_CTRL) & 0x80;\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_AP_CTRL, Data | 0x01);\n}\n\nu32 XLen_stream_IsDone(XLen_stream *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_AP_CTRL);\n return (Data >> 1) & 0x1;\n}\n\nu32 XLen_stream_IsIdle(XLen_stream *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_AP_CTRL);\n return (Data >> 2) & 0x1;\n}\n\nu32 XLen_stream_IsReady(XLen_stream *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_AP_CTRL);\n // check ap_start to see if the pcore is ready for next input\n return !(Data & 0x1);\n}\n\nvoid XLen_stream_EnableAutoRestart(XLen_stream *InstancePtr) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_AP_CTRL, 0x80);\n}\n\nvoid XLen_stream_DisableAutoRestart(XLen_stream *InstancePtr) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_AP_CTRL, 0);\n}\n\nvoid XLen_stream_Set_val_size(XLen_stream *InstancePtr, u32 Data) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_VAL_SIZE_DATA, Data);\n}\n\nu32 XLen_stream_Get_val_size(XLen_stream *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_VAL_SIZE_DATA);\n return Data;\n}\n\nvoid XLen_stream_Set_output_size(XLen_stream *InstancePtr, u32 Data) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_OUTPUT_SIZE_DATA, Data);\n}\n\nu32 XLen_stream_Get_output_size(XLen_stream *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_OUTPUT_SIZE_DATA);\n return Data;\n}\n\nvoid XLen_stream_Set_offset(XLen_stream *InstancePtr, u32 Data) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_OFFSET_DATA, Data);\n}\n\nu32 XLen_stream_Get_offset(XLen_stream *InstancePtr) {\n u32 Data;\n\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Data = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_OFFSET_DATA);\n return Data;\n}\n\nvoid XLen_stream_InterruptGlobalEnable(XLen_stream *InstancePtr) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_GIE, 1);\n}\n\nvoid XLen_stream_InterruptGlobalDisable(XLen_stream *InstancePtr) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_GIE, 0);\n}\n\nvoid XLen_stream_InterruptEnable(XLen_stream *InstancePtr, u32 Mask) {\n u32 Register;\n\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Register = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_IER);\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_IER, Register | Mask);\n}\n\nvoid XLen_stream_InterruptDisable(XLen_stream *InstancePtr, u32 Mask) {\n u32 Register;\n\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n Register = XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_IER);\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_IER, Register & (~Mask));\n}\n\nvoid XLen_stream_InterruptClear(XLen_stream *InstancePtr, u32 Mask) {\n Xil_AssertVoid(InstancePtr != NULL);\n Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n XLen_stream_WriteReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_ISR, Mask);\n}\n\nu32 XLen_stream_InterruptGetEnabled(XLen_stream *InstancePtr) {\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n return XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_IER);\n}\n\nu32 XLen_stream_InterruptGetStatus(XLen_stream *InstancePtr) {\n Xil_AssertNonvoid(InstancePtr != NULL);\n Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);\n\n return XLen_stream_ReadReg(InstancePtr->Axilites_BaseAddress, XLEN_STREAM_AXILITES_ADDR_ISR);\n}\n\n" }, { "alpha_fraction": 0.5362318754196167, "alphanum_fraction": 0.5942028760910034, "avg_line_length": 30.846153259277344, "blob_id": "6f170a33494633d03a61688f30e056971955b674", "content_id": "158639b4cf1555e53bfbdf2f8bcb2beb6767c9f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 828, "license_type": "permissive", "max_line_length": 214, "num_lines": 26, "path": "/spmv/TopLevel/TopLevel.sim/sim_1/behav/xsim/simulate.sh", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "#!/bin/bash -f\n# ****************************************************************************\n# Vivado (TM) v2017.4 (64-bit)\n#\n# Filename : simulate.sh\n# Simulator : Xilinx Vivado Simulator\n# Description : Script for simulating the design by launching the simulator\n#\n# Generated by Vivado on Wed Jul 04 10:47:10 CEST 2018\n# SW Build 2086221 on Fri Dec 15 20:54:30 MST 2017\n#\n# Copyright 1986-2017 Xilinx, Inc. All Rights Reserved.\n#\n# usage: simulate.sh\n#\n# ****************************************************************************\nExecStep()\n{\n\"$@\"\nRETVAL=$?\nif [ $RETVAL -ne 0 ]\nthen\nexit $RETVAL\nfi\n}\nExecStep xsim TopLevelTB_behav -key {Behavioral:sim_1:Functional:TopLevelTB} -tclbatch TopLevelTB.tcl -view /home/asiatici/epfl/memory-coalescer/vivado/spmv/spmv-hls/TopLevel/TopLevelTB_behav.wcfg -log simulate.log\n" }, { "alpha_fraction": 0.6101992726325989, "alphanum_fraction": 0.6159144043922424, "avg_line_length": 48.810218811035156, "blob_id": "0a6306ca90e07ec36d74293c87bab575b9ad0995", "content_id": "0d4b41ccfd25de0b5022908f346c13d4635fb244", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6824, "license_type": "permissive", "max_line_length": 230, "num_lines": 137, "path": "/util/mm_matrix_to_csr.py", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "import scipy.sparse\nimport scipy.io\nimport numpy\nimport os\nimport pickle\n\n\nimport struct\nimport argparse\n\ndef crange(modulo):\n i = 0\n while True:\n yield i\n i += 1\n if i == modulo:\n i = 0\n\ndef splitters(num_els, num_parts):\n avg = num_els / float(num_parts)\n last = 0.0\n while last < num_els:\n yield int(last)\n last += avg\n yield num_els\n\nparser = argparse.ArgumentParser(description='Convert a MatrixMarket matrix (from e.g. sparse.tamu.edu) into binary files for execution on FPGA.')\nparser.add_argument('-v', '--vec', action='store_true', help='Also generate a random vector with as many rows as the columns of the matrix')\nparser.add_argument('-a', '--acc', type=str, help='Number of accelerators among which the matrix is partitioned. Use a..b (ex. 1..4) to generate for a range of accelerator numbers (both start and end inclusive).', default='1')\nparser.add_argument('-i', '--interleaved', action='store_true', help='Partition rows across accelerators in an interleaved manner. If disabled, rows are partitioned in blocks (contiguous rows are given to the same accelerator).')\nparser.add_argument('-s', '--split', action='store_true', help='Split val and col_ind into two separate files', default=False)\nparser.add_argument('input_file', help='Input MatrixMarket file (*.mtx or as a CSR *.pickle)')\nargs=parser.parse_args()\n\nfile_name_no_ext = os.path.splitext(args.input_file)[0]\nfile_ext = os.path.splitext(args.input_file)[1]\nif file_ext == '.mtx':\n matrix = scipy.io.mmread(args.input_file).tocsr()\n pickle_file = file_name_no_ext + '.pickle'\n with open(pickle_file, 'wb') as fh:\n pickle.dump(matrix, fh)\nelif file_ext == '.pickle':\n with open(args.input_file, 'rb') as f:\n matrix = pickle.load(f)\nelse:\n raise RuntimeError('input_file must either be an .mtx or a .pickle file.')\nprint(\"Imported {} matrix with {} non-zero elements\\n\".format(matrix.shape, len(matrix.data)))\nif args.interleaved:\n root_folder_name = os.path.splitext(os.path.basename(args.input_file))[0][0:8]\nelse:\n root_folder_name = os.path.splitext(os.path.basename(args.input_file))[0][0:7] + 'b'\nacc_range = [int(x) for x in args.acc.split('..')]\nif len(acc_range) == 0:\n acc_range.append(acc_range[0])\nfor acc_count in range(acc_range[0], acc_range[1]+1):\n full_folder_path = os.path.join(root_folder_name, str(acc_count))\n os.makedirs(full_folder_path, exist_ok=True)\n print(\"Creating folder {}\\n\".format(full_folder_path))\n\n interleaved_rowptr = [[0] for i in range(acc_count)]\n interleaved_data = [[] for i in range(acc_count)]\n interleaved_col_ind = [[] for i in range(acc_count)]\n\n data_list = matrix.data.tolist()\n indices_list = matrix.indices.tolist()\n\n if args.interleaved:\n for curr_acc, start, end in zip(crange(acc_count), matrix.indptr, matrix.indptr[1:]):\n count = end - start\n interleaved_rowptr[curr_acc].append(interleaved_rowptr[curr_acc][-1] + count)\n interleaved_data[curr_acc] += data_list[start:end]\n interleaved_col_ind[curr_acc] += indices_list[start:end]\n else:\n spl = [x for x in splitters(len(matrix.indptr), acc_count)]\n interleaved_rowptr = [matrix.indptr[x:y + 1] for x, y in zip(spl, spl[1:])]\n interleaved_data = [matrix.data[x[0]:x[-1]] for x in interleaved_rowptr]\n interleaved_col_ind = [matrix.indices[x[0]:x[-1]] for x in interleaved_rowptr]\n\n interleaved_rowptr = [[val-row[0] for val in row] for row in interleaved_rowptr]\n vect = numpy.random.rand(matrix.shape[1])\n\n res = matrix * vect\n\n split_matrices = [scipy.sparse.csr_matrix((numpy.array(interleaved_data[i]), numpy.array(interleaved_col_ind[i]), numpy.array(interleaved_rowptr[i])), (len(interleaved_rowptr[i])-1, matrix.shape[1])) for i in range(acc_count)]\n\n for acc, this_rowptr, this_data, this_cols in zip(range(acc_count), interleaved_rowptr, interleaved_data, interleaved_col_ind):\n if args.split:\n val_file_name = '{}.val'.format(acc)\n print(\"Creating file {}\\n\".format(os.path.join(full_folder_path, val_file_name)))\n with open(os.path.join(full_folder_path, val_file_name), 'wb') as f:\n f.write(struct.pack(\"I\", len(this_data)))\n for val in this_data:\n f.write(struct.pack(\"f\", val))\n col_file_name = '{}.col'.format(acc)\n print(\"Creating file {}\\n\".format(os.path.join(full_folder_path, col_file_name)))\n with open(os.path.join(full_folder_path, col_file_name), 'wb') as f:\n f.write(struct.pack(\"I\", len(this_data)))\n for col in this_cols:\n f.write(struct.pack(\"I\", col))\n else:\n val_col_file_name = '{}.dat'.format(acc)\n print(\"Creating file {}\\n\".format(os.path.join(full_folder_path, val_col_file_name)))\n with open(os.path.join(full_folder_path, val_col_file_name), 'wb') as f:\n f.write(struct.pack(\"I\", len(this_data)))\n for val, col in zip(this_data, this_cols):\n # f.write('{:x}'.format(struct.unpack(\"I\", struct.pack(\"f\", val))[0]) + ' ' + str(col) + '\\n')\n f.write(struct.pack(\"fI\", val, col))\n\n row_ptr_file_name = '{}.row'.format(acc)\n print(\"Creating file {}\\n\".format(os.path.join(full_folder_path, row_ptr_file_name)))\n with open(os.path.join(full_folder_path, row_ptr_file_name), 'wb') as f:\n f.write(struct.pack(\"I\", len(this_rowptr)))\n for rowptr in this_rowptr:\n # f.write(str(rowptr) + '\\n')\n f.write(struct.pack(\"I\", rowptr))\n\n if args.vec:\n print(\"Generating random vector of size {}\\n\".format(matrix.shape[1]))\n vect = numpy.random.rand(matrix.shape[1])\n\n vect_file_name = '{}.vec'.format(root_folder_name)\n print(\"Creating file {}\\n\".format(os.path.join(full_folder_path, vect_file_name)))\n with open(os.path.join(full_folder_path, vect_file_name), 'wb') as f:\n f.write(struct.pack(\"I\", matrix.shape[1]))\n for val in vect:\n # f.write('{:x}'.format(struct.unpack(\"I\", struct.pack(\"f\", val))[0]) + '\\n')\n f.write(struct.pack(\"f\", val))\n\n res = matrix * vect\n split_res = [mat * vect for mat in split_matrices]\n for acc, this_res in enumerate(split_res):\n res_file_name = '{}.exp'.format(acc)\n print(\"Creating file {}\\n\".format(os.path.join(full_folder_path, res_file_name)))\n with open(os.path.join(full_folder_path, res_file_name), 'wb') as f:\n f.write(struct.pack(\"I\", len(this_res)))\n for val in this_res:\n f.write(struct.pack(\"f\", val))\n" }, { "alpha_fraction": 0.5121951103210449, "alphanum_fraction": 0.6116322875022888, "avg_line_length": 40, "blob_id": "452a0d0e1cf6292442d4473f259f1a27ebcb682d", "content_id": "fc345c78b4816276545b31d602a9f4a7f552e348", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1066, "license_type": "permissive", "max_line_length": 467, "num_lines": 26, "path": "/spmv/TopLevel/TopLevel.sim/sim_1/behav/xsim/elaborate.sh", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "#!/bin/bash -f\n# ****************************************************************************\n# Vivado (TM) v2017.4 (64-bit)\n#\n# Filename : elaborate.sh\n# Simulator : Xilinx Vivado Simulator\n# Description : Script for elaborating the compiled design\n#\n# Generated by Vivado on Wed Jul 04 10:46:56 CEST 2018\n# SW Build 2086221 on Fri Dec 15 20:54:30 MST 2017\n#\n# Copyright 1986-2017 Xilinx, Inc. All Rights Reserved.\n#\n# usage: elaborate.sh\n#\n# ****************************************************************************\nExecStep()\n{\n\"$@\"\nRETVAL=$?\nif [ $RETVAL -ne 0 ]\nthen\nexit $RETVAL\nfi\n}\nExecStep xelab -wto 8a2aa20f85844b9094fe626fb0f968f9 --incr --debug typical --relax --mt 8 -L xil_defaultlib -L xbip_utils_v3_0_8 -L axi_utils_v2_0_4 -L xbip_pipe_v3_0_4 -L xbip_dsp48_wrapper_v3_0_4 -L xbip_dsp48_addsub_v3_0_4 -L xbip_dsp48_multadd_v3_0_4 -L xbip_bram18k_v3_0_4 -L mult_gen_v12_0_13 -L floating_point_v7_1_5 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot TopLevelTB_behav xil_defaultlib.TopLevelTB xil_defaultlib.glbl -log elaborate.log\n" }, { "alpha_fraction": 0.6294925212860107, "alphanum_fraction": 0.6431622505187988, "avg_line_length": 34.32595443725586, "blob_id": "53e7d0e7c993ed0e3c6a120b4eeeb1cdad05fda0", "content_id": "e31228fe0b99722e14808f2b9cd8c3261183d7b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17557, "license_type": "permissive", "max_line_length": 206, "num_lines": 497, "path": "/sw/zynq_code_simple.c", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "#define DEBUG_DATA_READ 0\n#define DEBUG_DMA 0\n#define DEBUG_CHECK_RESULTS 0\n\n// ## removes the preceding comma when there are 0 arguments in __VA_ARGS__\n#define debug_printf(fmt, debug_cond, ...) do { if (debug_cond) xil_printf(fmt, ## __VA_ARGS__); } while (0)\n#define debug_data_read_printf(fmt, ...) debug_printf(fmt, DEBUG_DATA_READ, ## __VA_ARGS__)\n#define debug_dma_printf(fmt, ...) debug_printf(fmt, DEBUG_DMA, ## __VA_ARGS__)\n#define debug_check_results_printf(fmt, ...) debug_printf(fmt, DEBUG_CHECK_RESULTS, ## __VA_ARGS__)\n\n#include <stdio.h>\n#include <stdlib.h>\n#include \"xil_printf.h\"\n#include \"xstatus.h\"\n#include \"xfully_pipelined_spmv.h\"\n#include \"xil_exception.h\"\n#include \"xtmrctr.h\"\n#include \"xaxidma.h\"\n#include \"ff.h\"\n#include \"inttypes.h\"\n#include \"fpgamshr.h\"\n\nu32 nnz[NUM_SPMV];\nu32 rows[NUM_SPMV];\nu32 cols;\n\nfloat* val_mem[NUM_SPMV] = {NULL};\nunsigned* col_mem[NUM_SPMV] = {NULL};\nu32* rowptr_mem[NUM_SPMV] = {NULL};\nfloat* vect_mem = (float*)MEM_BASE_ADDR;\nfloat* ref_output_mem[NUM_SPMV] = {NULL};\nfloat* output_mem[NUM_SPMV];\n\n#define NUM_BENCHMARKS EDIT_ME\n\nchar* benchmarks[NUM_BENCHMARKS] = {EDIT ME};\n\n//#define NUM_BENCHMARKS 14\n//char* benchmarks[NUM_BENCHMARKS] = {\"pds-80\", \"amazon-2\", \"cnr-2000\", \"dblp-201\", \"enron\", \"eu-2005\", \"flickr\",\n//\t\t\"in-2004\", \"internet\",\"ljournal\", \"rail4284\", \"webbase-\", \"youtube\", \"bcspwr01\"};\n\nXAxiDma row_dma[NUM_SPMV];\nXAxiDma_Config *row_dma_cfg[NUM_SPMV];\nXAxiDma val_dma[NUM_SPMV];\nXAxiDma_Config *val_dma_cfg[NUM_SPMV];\nXAxiDma col_dma[NUM_SPMV];\nXAxiDma_Config *col_dma_cfg[NUM_SPMV];\n\n#define NUM_DMAS 3\n\nu32 spmv_base_addrs[] = {\n\t\tXPAR_FULLYPIPELINEDSPMVRTL_0_BASEADDR,\n\t\tXPAR_FULLYPIPELINEDSPMVRTL_1_BASEADDR,\n\t\tXPAR_FULLYPIPELINEDSPMVRTL_2_BASEADDR,\n\t\tXPAR_FULLYPIPELINEDSPMVRTL_3_BASEADDR\n};\n\nu32 row_dma_device_id[] = {\n\t\tXPAR_AXI_DMA_0_DEVICE_ID,\n\t\tXPAR_AXI_DMA_3_DEVICE_ID,\n\t\tXPAR_AXI_DMA_6_DEVICE_ID,\n\t\tXPAR_AXI_DMA_9_DEVICE_ID\n};\n\nu32 col_dma_device_id[] = {\n\t\tXPAR_AXI_DMA_1_DEVICE_ID,\n\t\tXPAR_AXI_DMA_4_DEVICE_ID,\n\t\tXPAR_AXI_DMA_7_DEVICE_ID,\n\t\tXPAR_AXI_DMA_10_DEVICE_ID\n};\n\n\nu32 val_dma_device_id[] = {\n\t\tXPAR_AXI_DMA_2_DEVICE_ID,\n\t\tXPAR_AXI_DMA_5_DEVICE_ID,\n\t\tXPAR_AXI_DMA_8_DEVICE_ID,\n\t\tXPAR_AXI_DMA_11_DEVICE_ID\n};\n\n\n\nXTmrCtr spmv_axis_timer;\n\nvolatile int timer_val;\nvolatile int irq_flag = 0;\n\nint Init_dma(){\n\tint i;\n\tfor(i = 0; i < NUM_SPMV; i++) {\n\t\trow_dma_cfg[i] = XAxiDma_LookupConfig(row_dma_device_id[i]);\n\t\tif (row_dma_cfg[i]) {\n\t\t\tint status = XAxiDma_CfgInitialize(&row_dma[i], row_dma_cfg[i]);\n\t\t\tif (status != XST_SUCCESS) {\n\t\t\t\tprintf(\"Error initializing AxiDMA core %d\\n\\r\", i);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tval_dma_cfg[i] = XAxiDma_LookupConfig(val_dma_device_id[i]);\n\t\tif (val_dma_cfg[i]) {\n\t\t\tint status = XAxiDma_CfgInitialize(&val_dma[i], val_dma_cfg[i]);\n\t\t\tif (status != XST_SUCCESS) {\n\t\t\t\tprintf(\"Error initializing AxiDMA core %d\\n\\r\", i);\n\t\t\t\treturn -2;\n\t\t\t}\n\t\t}\n\t\tcol_dma_cfg[i] = XAxiDma_LookupConfig(col_dma_device_id[i]);\n\t\tif (col_dma_cfg[i]) {\n\t\t\tint status = XAxiDma_CfgInitialize(&col_dma[i], col_dma_cfg[i]);\n\t\t\tif (status != XST_SUCCESS) {\n\t\t\t\tprintf(\"Error initializing AxiDMA core %d\\n\\r\", i);\n\t\t\t\treturn -2;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define MAX_TRANSFER_SIZE_BYTES (8*1024*1024 - 8)\n\nint Test_spmv_mult_axis(int num_spmv){\n\n\ttypedef struct {\n\t\tu32 next_start_addr;\n\t\tu32 bytes_left;\n\t} dma_state_t;\n\n\ttypedef struct {\n\t\tdma_state_t val;\n\t\tdma_state_t col;\n\t\tdma_state_t rowptr;\n\t\tdma_state_t output;\n\t} spmv_dma_state_t;\n\n\tspmv_dma_state_t dma_state[num_spmv];\n\n\tint i;\n\n\tfor(i = 0; i < num_spmv; i++) {\n\t\tdma_state[i].val.next_start_addr = (u32)val_mem[i];\n\t\tdma_state[i].val.bytes_left = nnz[i] * sizeof(float);\n\t\tdma_state[i].col.next_start_addr = (u32)col_mem[i];\n\t\tdma_state[i].col.bytes_left = nnz[i] * sizeof(unsigned);\n\n\t\tdma_state[i].rowptr.next_start_addr = (u32)rowptr_mem[i];\n\t\tdma_state[i].rowptr.bytes_left = (rows[i] + 1)*sizeof(int);\n\n\t\tdma_state[i].output.next_start_addr = (u32)output_mem[i];\n\t\tdma_state[i].output.bytes_left = rows[i] * sizeof(float);\n\n\t\tXil_DCacheFlushRange((u32)val_mem[i], nnz[i] * sizeof(float));\n\t\tXil_DCacheFlushRange((u32)col_mem[i], nnz[i] * sizeof(unsigned));\n\t\tXil_DCacheFlushRange((u32)rowptr_mem[i], (rows[i] + 1) * sizeof(u32));\n\t\tXil_DCacheInvalidateRange((u32)output_mem[i], rows[i] * sizeof(float));\n\t\tXSpmv_mult_axis_Set_val_size(i, (u32)nnz[i]);\n\t\tXSpmv_mult_axis_Set_output_size(i, (u32)rows[i]);\n\t\tXSpmv_mult_axis_Set_vect_mem(i, (u32)vect_mem);\n\n\t\tdebug_dma_printf(\"i=%d, curr_nnz=%d, curr_row_num=%d\\n\\r\", i, nnz[i], rows[i]);\n\t}\n\n\tint ret_val;\n\tfor(i = 0; i < num_spmv; i++)\n\t{\n\t\tint bytes_to_send = dma_state[i].val.bytes_left > MAX_TRANSFER_SIZE_BYTES ? MAX_TRANSFER_SIZE_BYTES : dma_state[i].val.bytes_left;\n\t\tdebug_dma_printf(\"Sending %d bytes from addr 0x%08X on val[%d]\\n\\r\", bytes_to_send, dma_state[i].val.next_start_addr, i);\n\t\tif((ret_val = XAxiDma_SimpleTransfer(&val_dma[i], dma_state[i].val.next_start_addr, bytes_to_send, XAXIDMA_DMA_TO_DEVICE)) != XST_SUCCESS) {\n\t\t\txil_printf(\"Error starting val_dma[%d] (code %d)\\n\\r\", i, ret_val);\n\t\t\treturn XST_FAILURE;\n\t\t}\n\t\tdma_state[i].val.next_start_addr += bytes_to_send;\n\t\tdma_state[i].val.bytes_left -= bytes_to_send;\n\n\t\tbytes_to_send = dma_state[i].col.bytes_left > MAX_TRANSFER_SIZE_BYTES ? MAX_TRANSFER_SIZE_BYTES : dma_state[i].col.bytes_left;\n\t\tdebug_dma_printf(\"Sending %d bytes from addr 0x%08X on col[%d]\\n\\r\", bytes_to_send, dma_state[i].col.next_start_addr, i);\n\t\tif((ret_val = XAxiDma_SimpleTransfer(&col_dma[i], dma_state[i].col.next_start_addr, bytes_to_send, XAXIDMA_DMA_TO_DEVICE)) != XST_SUCCESS) {\n\t\t\txil_printf(\"Error starting col_dma[%d] (code %d)\\n\\r\", i, ret_val);\n\t\t\treturn XST_FAILURE;\n\t\t}\n\t\tdma_state[i].col.next_start_addr += bytes_to_send;\n\t\tdma_state[i].col.bytes_left -= bytes_to_send;\n\n\t\tbytes_to_send = dma_state[i].rowptr.bytes_left > MAX_TRANSFER_SIZE_BYTES ? MAX_TRANSFER_SIZE_BYTES : dma_state[i].rowptr.bytes_left;\n\t\tdebug_dma_printf(\"Sending %d bytes from addr 0x%08X on rowptr[%d]\\n\\r\", bytes_to_send, dma_state[i].rowptr.next_start_addr, i);\n\t\tif((ret_val = XAxiDma_SimpleTransfer(&row_dma[i], dma_state[i].rowptr.next_start_addr, bytes_to_send, XAXIDMA_DMA_TO_DEVICE)) != XST_SUCCESS) {\n\t\t\txil_printf(\"Error starting row_dma[%d] (code %d)\\n\\r\", i, ret_val);\n\t\t\treturn XST_FAILURE;\n\t\t}\n\t\tdma_state[i].rowptr.next_start_addr += bytes_to_send;\n\t\tdma_state[i].rowptr.bytes_left -= bytes_to_send;\n\n\t\tbytes_to_send = dma_state[i].output.bytes_left > MAX_TRANSFER_SIZE_BYTES ? MAX_TRANSFER_SIZE_BYTES : dma_state[i].output.bytes_left;\n\t\tdebug_dma_printf(\"Sending %d bytes to addr 0x%08X from output[%d]\\n\\r\", bytes_to_send, dma_state[i].output.next_start_addr, i);\n\t\tif((ret_val = XAxiDma_SimpleTransfer(&row_dma[i], dma_state[i].output.next_start_addr, bytes_to_send, XAXIDMA_DEVICE_TO_DMA)) != XST_SUCCESS) {\n\t\t\txil_printf(\"Error starting output_dma[%d] (code %d)\\n\\r\", i, ret_val);\n\t\t\treturn XST_FAILURE;\n\t\t}\n\t\tdma_state[i].output.next_start_addr += bytes_to_send;\n\t\tdma_state[i].output.bytes_left -= bytes_to_send;\n\t}\n\n XTmrCtr_SetResetValue(&spmv_axis_timer, 0, 0);\n XTmrCtr_Start(&spmv_axis_timer, 0);\n for(i = 0; i < num_spmv; i++)\n {\n\t\tXSpmv_mult_axis_Start(i);\n\t}\n\n int any_transfers_pending = 1;\n while(any_transfers_pending) {\n \tany_transfers_pending = 0;\n\t\tfor(i = 0; i < num_spmv; i++)\n\t\t{\n\t\t\tif(dma_state[i].val.bytes_left > 0) {\n\t\t\t\tany_transfers_pending = 1;\n\t\t\t\tif(!XAxiDma_Busy(&val_dma[i], XAXIDMA_DMA_TO_DEVICE)) {\n\t\t\t\t\tint bytes_to_send = dma_state[i].val.bytes_left > MAX_TRANSFER_SIZE_BYTES ? MAX_TRANSFER_SIZE_BYTES : dma_state[i].val.bytes_left;\n\t\t\t\t\tdebug_dma_printf(\"Sending %d bytes from addr 0x%08X on val[%d]\\n\\r\", bytes_to_send, dma_state[i].val.next_start_addr, i);\n\t\t\t\t\tif((ret_val = XAxiDma_SimpleTransfer(&val_dma[i], dma_state[i].val.next_start_addr, bytes_to_send, XAXIDMA_DMA_TO_DEVICE)) != XST_SUCCESS) {\n\t\t\t\t\t\txil_printf(\"Error starting val_dma[%d] (code %d)\\n\\r\", i, ret_val);\n\t\t\t\t\t\treturn XST_FAILURE;\n\t\t\t\t\t}\n\t\t\t\t\tdma_state[i].val.next_start_addr += bytes_to_send;\n\t\t\t\t\tdma_state[i].val.bytes_left -= bytes_to_send;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(dma_state[i].col.bytes_left > 0) {\n\t\t\t\tany_transfers_pending = 1;\n\t\t\t\tif(!XAxiDma_Busy(&col_dma[i], XAXIDMA_DMA_TO_DEVICE)) {\n\t\t\t\t\tint bytes_to_send = dma_state[i].col.bytes_left > MAX_TRANSFER_SIZE_BYTES ? MAX_TRANSFER_SIZE_BYTES : dma_state[i].col.bytes_left;\n\t\t\t\t\tdebug_dma_printf(\"Sending %d bytes from addr 0x%08X on col[%d]\\n\\r\", bytes_to_send, dma_state[i].col.next_start_addr, i);\n\t\t\t\t\tif((ret_val = XAxiDma_SimpleTransfer(&col_dma[i], dma_state[i].col.next_start_addr, bytes_to_send, XAXIDMA_DMA_TO_DEVICE)) != XST_SUCCESS) {\n\t\t\t\t\t\txil_printf(\"Error starting col_dma[%d] (code %d)\\n\\r\", i, ret_val);\n\t\t\t\t\t\treturn XST_FAILURE;\n\t\t\t\t\t}\n\t\t\t\t\tdma_state[i].col.next_start_addr += bytes_to_send;\n\t\t\t\t\tdma_state[i].col.bytes_left -= bytes_to_send;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(dma_state[i].rowptr.bytes_left > 0) {\n\t\t\t\tany_transfers_pending = 1;\n\t\t\t\tif(!XAxiDma_Busy(&row_dma[i], XAXIDMA_DMA_TO_DEVICE)) {\n\t\t\t\t\tint bytes_to_send = dma_state[i].rowptr.bytes_left > MAX_TRANSFER_SIZE_BYTES ? MAX_TRANSFER_SIZE_BYTES : dma_state[i].rowptr.bytes_left;\n\t\t\t\t\tdebug_dma_printf(\"Sending %d bytes from addr 0x%08X on rowptr[%d]\\n\\r\", bytes_to_send, dma_state[i].rowptr.next_start_addr, i);\n\t\t\t\t\tif((ret_val = XAxiDma_SimpleTransfer(&row_dma[i], dma_state[i].rowptr.next_start_addr, bytes_to_send, XAXIDMA_DMA_TO_DEVICE)) != XST_SUCCESS) {\n\t\t\t\t\t\txil_printf(\"Error starting row_dma[%d] (code %d)\\n\\r\", i, ret_val);\n\t\t\t\t\t\treturn XST_FAILURE;\n\t\t\t\t\t}\n\t\t\t\t\tdma_state[i].rowptr.next_start_addr += bytes_to_send;\n\t\t\t\t\tdma_state[i].rowptr.bytes_left -= bytes_to_send;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(dma_state[i].output.bytes_left > 0) {\n\t\t\t\tany_transfers_pending = 1;\n\t\t\t\tif(!XAxiDma_Busy(&row_dma[i], XAXIDMA_DEVICE_TO_DMA)) {\n\t\t\t\t\tint bytes_to_send = dma_state[i].output.bytes_left > MAX_TRANSFER_SIZE_BYTES ? MAX_TRANSFER_SIZE_BYTES : dma_state[i].output.bytes_left;\n\t\t\t\t\tdebug_dma_printf(\"Sending %d bytes to addr 0x%08X from output[%d]\\n\\r\", bytes_to_send, dma_state[i].output.next_start_addr, i);\n\t\t\t\t\tif((ret_val = XAxiDma_SimpleTransfer(&row_dma[i], dma_state[i].output.next_start_addr, bytes_to_send, XAXIDMA_DEVICE_TO_DMA)) != XST_SUCCESS) {\n\t\t\t\t\t\txil_printf(\"Error starting output_dma[%d] (code %d)\\n\\r\", i, ret_val);\n\t\t\t\t\t\treturn XST_FAILURE;\n\t\t\t\t\t}\n\t\t\t\t\tdma_state[i].output.next_start_addr += bytes_to_send;\n\t\t\t\t\tdma_state[i].output.bytes_left -= bytes_to_send;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n }\n\n\tint all_idle = 0;\n\twhile(!all_idle)\n\t{\n\t\tall_idle = 1;\n\t\tfor(i = 0; i < num_spmv; i++)\n\t\t{\n\t\t\tall_idle &= XSpmv_mult_axis_IsIdle(i);\n\t\t}\n\t}\n irq_flag = 0;\n XTmrCtr_Stop(&spmv_axis_timer, 0);\n\n all_idle = 0;\n while(!all_idle)\n {\n \tall_idle = 1;\n\t\tfor(i = 0; i < num_spmv; i++)\n\t\t{\n\t\t\tall_idle &= !XAxiDma_Busy(&row_dma[i], XAXIDMA_DEVICE_TO_DMA);\n\t\t}\n }\n\n xil_printf(\"%u \", XTmrCtr_GetValue(&spmv_axis_timer, 0));\n\n for(i = 0; i < num_spmv; i++)\n \tXil_DCacheInvalidateRange((u32)output_mem[i], rows[i] * sizeof(float));\n return XST_SUCCESS;\n}\n\nvoid Compare_result(int num_spmv){\n\n\tdebug_check_results_printf(\"Result verification: \\n\\r\");\n\n\tunsigned i, acc;\n\tfor(acc = 0; acc < num_spmv; acc++)\n\t{\n\t\tfor(i = 0; i < rows[acc]; i++){\n\t\t\t//printf(\"%d: %lf %lf\\n\\r\", i, output_mem[i], ref_output_mem[i]);\n\t\t\tif((ref_output_mem[acc][i] > 1e-5) && (((((int32_t*)ref_output_mem[acc])[i] - ((int32_t*)output_mem[acc])[i]) > 167772) || (((int32_t*)output_mem[acc])[i] - ((int32_t*)ref_output_mem[acc])[i]) > 167772))\n\t\t\t{\n\t\t\t\tprintf(\"%d %d: %lf %lf\\n\\r\", acc, i, output_mem[acc][i], ref_output_mem[acc][i]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(i == rows[acc])\n\t\t{\n\t\t\tdebug_check_results_printf(\"Pass\\n\\r\");\n\t\t}\n\t\telse\n\t\t\txil_printf(\"Fail\\n\\r\");\n\t}\n}\n\nvoid mem_test()\n{\n\tint* arr = (int*)MEM_BASE_ADDR;\n\tfor(int i = 0; i < 1024; i++) {\n\t\tarr[i] = i;\n\t}\n\tfor(int i = 0; i < 1024; i++) {\n\t\tif(arr[i] != i)\n\t\t\txil_printf(\"Error at loc %d: found %d\\n\", i, arr[i]);\n\t}\n}\n\nint Read_single_vector(const char* full_file_name, u32* vec_size, size_t vec_elem_size, void** vec) {\n\tstatic FIL fp;\t // File instance\n\tunsigned int bytes_read;\n\tFRESULT result;\n\n\tresult = f_open(&fp, full_file_name, FA_READ);\n\tif (result!= 0) {\n\t\txil_printf(\"f_open of %s returned %d\\n\\r\", full_file_name, result);\n\t\treturn XST_FAILURE;\n\t}\n\n\tresult = f_read(&fp, (void*)vec_size, sizeof(u32), &bytes_read);\n\tif (result!= 0) {\n\t\txil_printf(\"First f_read on .dat file returned %d\\n\\r\", result);\n\t\treturn XST_FAILURE;\n\t}\n\tdebug_data_read_printf(\"vec size from %s=%d\\n\\r\", full_file_name, *vec_size);\n\n\tif(*vec == NULL)\n\t\t*vec = malloc((*vec_size)*vec_elem_size);\n\tif (*vec == NULL) {\n\t\txil_printf(\"Unable to allocate vector from %s\\n\\r\", full_file_name);\n\t\treturn XST_FAILURE;\n\t}\n\tresult = f_read(&fp, (void*)(*vec), (*vec_size)*vec_elem_size, &bytes_read);\n\tif (result!=0) {\n\t\txil_printf(\"Bulk f_read of %s returned %d\\n\\r\", full_file_name, result);\n\t\treturn XST_FAILURE;\n\t}\n\n\tresult = f_close(&fp);\n\tif (result!=0) {\n\t\txil_printf(\"f_close of %s returned %d\\n\\r\", full_file_name, result);\n\t\treturn XST_FAILURE;\n\t}\n\n\treturn XST_SUCCESS;\n}\n\nint Read_data(const char* folder_name, const int num_spmv) {\n\n\tchar full_file_name[50];\n\n\tFATFS fs; // File System instance\n\n\tFRESULT result;\n\tif(strlen(folder_name) > 8) {\n\t\txil_printf(\"Folder name is limited to 8 characters\\n\\r\");\n\t\treturn XST_FAILURE;\n\t}\n\n\tresult = f_mount(&fs, \"0:/\", 1);\n\tif (result != 0) {\n\t\txil_printf(\"f_mount returned %d\\n\\r\", result);\n\t\treturn XST_FAILURE;\n\t}\n\n\tint i;\n\n\tsprintf(full_file_name, \"%s/%d/%s.vec\", folder_name, num_spmv, folder_name);\n\tif(Read_single_vector(full_file_name, &cols, sizeof(float), (void**)&vect_mem) != XST_SUCCESS)\n\t\treturn XST_FAILURE;\n\tif(((u32)vect_mem + cols*sizeof(float)) > MEMORY_SPAN + MEM_BASE_ADDR) {\n\t\txil_printf(\"Vector does not fit in the memory region accessible by the FPGAMSHR (max addr=0x%08X), aborting\", (u32)vect_mem + cols*sizeof(float));\n\t\treturn XST_FAILURE;\n\t}\n\n\tfor(i = 0; i < num_spmv; i++) {\n\t\tsprintf(full_file_name, \"%s/%d/%d.val\", folder_name, num_spmv, i);\n\t\tif(Read_single_vector(full_file_name, &nnz[i], sizeof(float), (void**)&(val_mem[i])) != XST_SUCCESS)\n\t\t\treturn XST_FAILURE;\n\t\tsprintf(full_file_name, \"%s/%d/%d.col\", folder_name, num_spmv, i);\n\t\tif(Read_single_vector(full_file_name, &nnz[i], sizeof(unsigned), (void**)&(col_mem[i])) != XST_SUCCESS)\n\t\t\treturn XST_FAILURE;\n\n\t\tsprintf(full_file_name, \"%s/%d/%d.row\", folder_name, num_spmv, i);\n\t\tif(Read_single_vector(full_file_name, &rows[i], sizeof(u32), (void**)&(rowptr_mem[i])) != XST_SUCCESS)\n\t\t\treturn XST_FAILURE;\n\t\trows[i]--; // rowptr size is rows + 1\n\n\t\tsprintf(full_file_name, \"%s/%d/%d.exp\", folder_name, num_spmv, i);\n\t\tif(Read_single_vector(full_file_name, &rows[i], sizeof(float), (void**)&(ref_output_mem[i])) != XST_SUCCESS)\n\t\t\treturn XST_FAILURE;\n\t\toutput_mem[i] = (float*)malloc(rows[i]*sizeof(float));\n\t}\n\treturn XST_SUCCESS;\n}\n\nint main()\n{\n XTmrCtr_Initialize(&spmv_axis_timer, XPAR_AXI_TIMER_0_DEVICE_ID);\n\tXTmrCtr_SetOptions(&spmv_axis_timer, 0, XTC_CAPTURE_MODE_OPTION);\n\n if(Init_dma() != 0)\n return -1;\n\n int num_spmv, cache_divider, benchmark_idx, mshr_count_idx;\n#if FPGAMSHR_EXISTS\n xil_printf(\"benchmark numAcc robDepth mshrHashTables mshrPerHashTable ldBufPerRow ldBufRows cacheWays cacheSize totalCycles \");\n#else\n xil_printf(\"benchmark numAcc cacheSize totalCycles \");\n#endif\n FPGAMSHR_Get_stats_header();\n\n for(benchmark_idx = 0; benchmark_idx < NUM_BENCHMARKS; benchmark_idx++) { // for each benchmark\n\t for(num_spmv = 1; num_spmv <= 4; num_spmv++) { // for all numbers of accelerators (num_spmv always 4 in the paper)\n // we statically partition the matrix rows across accelerators in the\n // input data, so we need to read the right set of sparse vector\n // depending on num_spmv\n\t\t debug_data_read_printf(\"Reading data...\\r\\n\");\n\t\t\t if(Read_data(benchmarks[benchmark_idx], num_spmv) != XST_SUCCESS)\n\t\t\t\t return XST_FAILURE;\n\t\t\t debug_data_read_printf(\"...done\\r\\n\");\n#if FPGAMSHR_EXISTS\n // we iterate over all possible cache size values\n // effective_cache_size = total_cache_size / (2 ^ cache_divider)\n\t\t\tfor(cache_divider = 0; cache_divider <= CACHE_SIZE_REDUCTION_VALUES; cache_divider++) {\n\t\t\t\t\tFPGAMSHR_Clear_stats();\n\t\t\t\t\tFPGAMSHR_Invalidate_cache();\n\t\t\t\t\tif(cache_divider == CACHE_SIZE_REDUCTION_VALUES)\n\t\t\t\t\t\tFPGAMSHR_Disable_cache();\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tFPGAMSHR_Enable_cache();\n\t\t\t\t\t\tFPGAMSHR_SetCacheDivider(cache_divider);\n\t\t\t\t\t}\n#else\n\t\t\t\t cache_divider = CACHE_SIZE_REDUCTION_VALUES + 1;\n#endif\n#if FPGAMSHR_EXISTS\n // run parameters\n\t\t\t\t\txil_printf(\"\\r\\n%s %d %d %d %d %d %d %d %d \", benchmarks[benchmark_idx], num_spmv,\n ROB_DEPTH, MSHR_HASH_TABLES, MSHR_PER_HASH_TABLE, SE_BUF_ENTRIES_PER_ROW, SE_BUF_ROWS, CACHE_WAYS,\n cache_divider == CACHE_SIZE_REDUCTION_VALUES ? 0 : CACHE_SIZE >> cache_divider);\n#else\n\t\t\t\t\txil_printf(\"\\r\\n%s %d 0 \", benchmarks[benchmark_idx], num_spmv);\n#endif\n\t\t\t\t\tif(Test_spmv_mult_axis(num_spmv) != XST_SUCCESS)\n\t\t\t\t\t\treturn XST_FAILURE;\n\t\t\t\t\tCompare_result(num_spmv);\n\n // Uncomment to get a full dump of the internal performance registers\n\t\t\t\t\t// FPGAMSHR_Get_stats_pretty();\n#if FPGAMSHR_EXISTS\n\t\t\t\t\tFPGAMSHR_Get_stats_row();\n\t\t\t\t\t}\n#endif\n\t\t\t\tint i;\n\t\t\t\tfor(i = 0; i < num_spmv; i++) {\n\t\t\t\t\tfree(val_mem[i]);\n\t\t\t\t\tval_mem[i] = NULL;\n\t\t\t\t\tfree(col_mem[i]);\n\t\t\t\t\tcol_mem[i] = NULL;\n\n\t\t\t\t\tfree(rowptr_mem[i]);\n\t\t\t\t\trowptr_mem[i] = NULL;\n\t\t\t\t\tfree(ref_output_mem[i]);\n\t\t\t\t\tref_output_mem[i] = NULL;\n\t\t\t\t\tfree(output_mem[i]);\n\t\t\t\t\toutput_mem[i] = NULL;\n\t\t\t\t}\n\t\t\t}\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.6282749772071838, "alphanum_fraction": 0.7475371956825256, "avg_line_length": 59.2018928527832, "blob_id": "e70983ebcc8ca75e907e30f8deb3360d5794357c", "content_id": "0ae45b4ae1a474c523be53dafb123dd6f30b230b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 19084, "license_type": "permissive", "max_line_length": 90, "num_lines": 317, "path": "/spmv/TopLevel/TopLevel.sim/sim_1/behav/xsim/xsim.ini", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "std=$RDI_DATADIR/xsim/vhdl/std\nieee=$RDI_DATADIR/xsim/vhdl/ieee\nieee_proposed=$RDI_DATADIR/xsim/vhdl/ieee_proposed\nvl=$RDI_DATADIR/xsim/vhdl/vl\nsynopsys=$RDI_DATADIR/xsim/vhdl/synopsys\nsecureip=$RDI_DATADIR/xsim/verilog/secureip\nunisim=$RDI_DATADIR/xsim/vhdl/unisim\nunimacro=$RDI_DATADIR/xsim/vhdl/unimacro\nunifast=$RDI_DATADIR/xsim/vhdl/unifast\nunisims_ver=$RDI_DATADIR/xsim/verilog/unisims_ver\nunimacro_ver=$RDI_DATADIR/xsim/verilog/unimacro_ver\nunifast_ver=$RDI_DATADIR/xsim/verilog/unifast_ver\nsimprims_ver=$RDI_DATADIR/xsim/verilog/simprims_ver\nbsip_v1_1_0=$RDI_DATADIR/xsim/ip/bsip_v1_1_0\nxbip_bram18k_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_bram18k_v3_0_4\nv_vcresampler_v1_0_9=$RDI_DATADIR/xsim/ip/v_vcresampler_v1_0_9\ntsn_endpoint_ethernet_mac_v1_0_1=$RDI_DATADIR/xsim/ip/tsn_endpoint_ethernet_mac_v1_0_1\nrs_encoder_v9_0_12=$RDI_DATADIR/xsim/ip/rs_encoder_v9_0_12\nprocessing_system7_vip_v1_0_3=$RDI_DATADIR/xsim/ip/processing_system7_vip_v1_0_3\nuhdsdi_gt_v1_0_0=$RDI_DATADIR/xsim/ip/uhdsdi_gt_v1_0_0\ngtwizard_ultrascale_v1_5_4=$RDI_DATADIR/xsim/ip/gtwizard_ultrascale_v1_5_4\nmipi_csi2_rx_ctrl_v1_0_7=$RDI_DATADIR/xsim/ip/mipi_csi2_rx_ctrl_v1_0_7\nv_ccm_v6_0_14=$RDI_DATADIR/xsim/ip/v_ccm_v6_0_14\nv_frmbuf_rd_v2_0_1=$RDI_DATADIR/xsim/ip/v_frmbuf_rd_v2_0_1\nxbip_utils_v3_0_8=$RDI_DATADIR/xsim/ip/xbip_utils_v3_0_8\naxis_register_slice_v1_1_15=$RDI_DATADIR/xsim/ip/axis_register_slice_v1_1_15\ngigantic_mux=$RDI_DATADIR/xsim/ip/gigantic_mux\nfc32_rs_fec_v1_0_5=$RDI_DATADIR/xsim/ip/fc32_rs_fec_v1_0_5\nxfft_v7_2_6=$RDI_DATADIR/xsim/ip/xfft_v7_2_6\ndft_v4_0_14=$RDI_DATADIR/xsim/ip/dft_v4_0_14\nhdcp_keymngmt_blk_v1_0_0=$RDI_DATADIR/xsim/ip/hdcp_keymngmt_blk_v1_0_0\ntcc_decoder_3gppmm_v2_0_15=$RDI_DATADIR/xsim/ip/tcc_decoder_3gppmm_v2_0_15\nhbm_v1_0_0=$RDI_DATADIR/xsim/ip/hbm_v1_0_0\nv_tpg_v7_0_9=$RDI_DATADIR/xsim/ip/v_tpg_v7_0_9\nxbip_counter_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_counter_v3_0_4\naxi_hwicap_v3_0_19=$RDI_DATADIR/xsim/ip/axi_hwicap_v3_0_19\naxi_protocol_checker_v1_1_16=$RDI_DATADIR/xsim/ip/axi_protocol_checker_v1_1_16\naxis_protocol_checker_v1_1_15=$RDI_DATADIR/xsim/ip/axis_protocol_checker_v1_1_15\naxi_amm_bridge_v1_0_5=$RDI_DATADIR/xsim/ip/axi_amm_bridge_v1_0_5\nxbip_dsp48_wrapper_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_dsp48_wrapper_v3_0_4\naxi_dwidth_converter_v2_1_15=$RDI_DATADIR/xsim/ip/axi_dwidth_converter_v2_1_15\nvid_edid_v1_0_0=$RDI_DATADIR/xsim/ip/vid_edid_v1_0_0\nxlconstant_v1_1_3=$RDI_DATADIR/xsim/ip/xlconstant_v1_1_3\nutil_vector_logic_v2_0_1=$RDI_DATADIR/xsim/ip/util_vector_logic_v2_0_1\ncmac_usplus_v2_3_2=$RDI_DATADIR/xsim/ip/cmac_usplus_v2_3_2\nlte_3gpp_mimo_encoder_v4_0_12=$RDI_DATADIR/xsim/ip/lte_3gpp_mimo_encoder_v4_0_12\nfloating_point_v7_1_5=$RDI_DATADIR/xsim/ip/floating_point_v7_1_5\nc_mux_bit_v12_0_4=$RDI_DATADIR/xsim/ip/c_mux_bit_v12_0_4\njtag_axi=$RDI_DATADIR/xsim/ip/jtag_axi\naxi_fifo_mm_s_v4_1_12=$RDI_DATADIR/xsim/ip/axi_fifo_mm_s_v4_1_12\ngtwizard_ultrascale_v1_6_8=$RDI_DATADIR/xsim/ip/gtwizard_ultrascale_v1_6_8\naxi_ethernetlite_v3_0_13=$RDI_DATADIR/xsim/ip/axi_ethernetlite_v3_0_13\nibert_lib_v1_0_4=$RDI_DATADIR/xsim/ip/ibert_lib_v1_0_4\naxi_register_slice_v2_1_15=$RDI_DATADIR/xsim/ip/axi_register_slice_v2_1_15\naxi_master_burst_v2_0_7=$RDI_DATADIR/xsim/ip/axi_master_burst_v2_0_7\nsystem_cache_v4_0_3=$RDI_DATADIR/xsim/ip/system_cache_v4_0_3\npl4_v13_0_11=$RDI_DATADIR/xsim/ip/pl4_v13_0_11\nmicroblaze_v10_0_5=$RDI_DATADIR/xsim/ip/microblaze_v10_0_5\ntmr_comparator_v1_0_1=$RDI_DATADIR/xsim/ip/tmr_comparator_v1_0_1\nfir_compiler_v5_2_4=$RDI_DATADIR/xsim/ip/fir_compiler_v5_2_4\ncompact_gt_v1_0_1=$RDI_DATADIR/xsim/ip/compact_gt_v1_0_1\naxi_epc_v2_0_18=$RDI_DATADIR/xsim/ip/axi_epc_v2_0_18\nhdcp22_rng_v1_0_1=$RDI_DATADIR/xsim/ip/hdcp22_rng_v1_0_1\naxi_protocol_converter_v2_1_15=$RDI_DATADIR/xsim/ip/axi_protocol_converter_v2_1_15\nbs_mux_v1_0_0=$RDI_DATADIR/xsim/ip/bs_mux_v1_0_0\nlte_ul_channel_decoder_v4_0_13=$RDI_DATADIR/xsim/ip/lte_ul_channel_decoder_v4_0_13\ng709_fec_v2_3_1=$RDI_DATADIR/xsim/ip/g709_fec_v2_3_1\nc_compare_v12_0_4=$RDI_DATADIR/xsim/ip/c_compare_v12_0_4\naxis_broadcaster_v1_1_15=$RDI_DATADIR/xsim/ip/axis_broadcaster_v1_1_15\nlte_dl_channel_encoder_v3_0_13=$RDI_DATADIR/xsim/ip/lte_dl_channel_encoder_v3_0_13\nmailbox_v2_1_8=$RDI_DATADIR/xsim/ip/mailbox_v2_1_8\nv_demosaic_v1_0_1=$RDI_DATADIR/xsim/ip/v_demosaic_v1_0_1\naxi4stream_vip_v1_0_3=$RDI_DATADIR/xsim/ip/axi4stream_vip_v1_0_3\naxi_chip2chip_v5_0_1=$RDI_DATADIR/xsim/ip/axi_chip2chip_v5_0_1\naxi_mm2s_mapper_v1_1_14=$RDI_DATADIR/xsim/ip/axi_mm2s_mapper_v1_1_14\nvid_phy_controller_v2_1_1=$RDI_DATADIR/xsim/ip/vid_phy_controller_v2_1_1\nin_system_ibert_v1_0_5=$RDI_DATADIR/xsim/ip/in_system_ibert_v1_0_5\nspdif_v2_0_18=$RDI_DATADIR/xsim/ip/spdif_v2_0_18\nxbip_accum_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_accum_v3_0_4\nc_mux_bus_v12_0_4=$RDI_DATADIR/xsim/ip/c_mux_bus_v12_0_4\nc_counter_binary_v12_0_11=$RDI_DATADIR/xsim/ip/c_counter_binary_v12_0_11\naxi_datamover_v5_1_17=$RDI_DATADIR/xsim/ip/axi_datamover_v5_1_17\nv_csc_v1_0_9=$RDI_DATADIR/xsim/ip/v_csc_v1_0_9\ntmr_sem_v1_0_3=$RDI_DATADIR/xsim/ip/tmr_sem_v1_0_3\nv_vid_sdi_tx_bridge_v2_0_0=$RDI_DATADIR/xsim/ip/v_vid_sdi_tx_bridge_v2_0_0\nv_gamma_lut_v1_0_1=$RDI_DATADIR/xsim/ip/v_gamma_lut_v1_0_1\nv_hdmi_tx_v3_0_0=$RDI_DATADIR/xsim/ip/v_hdmi_tx_v3_0_0\ncic_compiler_v4_0_12=$RDI_DATADIR/xsim/ip/cic_compiler_v4_0_12\ngig_ethernet_pcs_pma_v16_1_2=$RDI_DATADIR/xsim/ip/gig_ethernet_pcs_pma_v16_1_2\nlib_pkg_v1_0_2=$RDI_DATADIR/xsim/ip/lib_pkg_v1_0_2\naxi_interconnect_v1_7_13=$RDI_DATADIR/xsim/ip/axi_interconnect_v1_7_13\nxlconcat_v2_1_1=$RDI_DATADIR/xsim/ip/xlconcat_v2_1_1\ntmr_voter_v1_0_1=$RDI_DATADIR/xsim/ip/tmr_voter_v1_0_1\ng709_rs_decoder_v2_2_5=$RDI_DATADIR/xsim/ip/g709_rs_decoder_v2_2_5\naxis_clock_converter_v1_1_16=$RDI_DATADIR/xsim/ip/axis_clock_converter_v1_1_16\ncmac_usplus_v2_4_1=$RDI_DATADIR/xsim/ip/cmac_usplus_v2_4_1\nc_addsub_v12_0_11=$RDI_DATADIR/xsim/ip/c_addsub_v12_0_11\nxfft_v9_0_14=$RDI_DATADIR/xsim/ip/xfft_v9_0_14\nv_tc_v6_1_12=$RDI_DATADIR/xsim/ip/v_tc_v6_1_12\naxi_mcdma_v1_0_1=$RDI_DATADIR/xsim/ip/axi_mcdma_v1_0_1\nduc_ddc_compiler_v3_0_13=$RDI_DATADIR/xsim/ip/duc_ddc_compiler_v3_0_13\naxi_perf_mon_v5_0_17=$RDI_DATADIR/xsim/ip/axi_perf_mon_v5_0_17\nrxaui_v4_4_2=$RDI_DATADIR/xsim/ip/rxaui_v4_4_2\nlte_3gpp_channel_estimator_v2_0_14=$RDI_DATADIR/xsim/ip/lte_3gpp_channel_estimator_v2_0_14\nxbip_pipe_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_pipe_v3_0_4\nmipi_csi2_tx_ctrl_v1_0_3=$RDI_DATADIR/xsim/ip/mipi_csi2_tx_ctrl_v1_0_3\nviterbi_v9_1_8=$RDI_DATADIR/xsim/ip/viterbi_v9_1_8\nconvolution_v9_0_12=$RDI_DATADIR/xsim/ip/convolution_v9_0_12\naxi_usb2_device_v5_0_16=$RDI_DATADIR/xsim/ip/axi_usb2_device_v5_0_16\naxi_cdma_v4_1_15=$RDI_DATADIR/xsim/ip/axi_cdma_v4_1_15\nzynq_ultra_ps_e_vip_v1_0_1=$RDI_DATADIR/xsim/ip/zynq_ultra_ps_e_vip_v1_0_1\nv_letterbox_v1_0_9=$RDI_DATADIR/xsim/ip/v_letterbox_v1_0_9\nv_mix_v2_0_1=$RDI_DATADIR/xsim/ip/v_mix_v2_0_1\nlmb_bram_if_cntlr_v4_0_14=$RDI_DATADIR/xsim/ip/lmb_bram_if_cntlr_v4_0_14\ndds_compiler_v6_0_15=$RDI_DATADIR/xsim/ip/dds_compiler_v6_0_15\nhdcp_v1_0_3=$RDI_DATADIR/xsim/ip/hdcp_v1_0_3\naxis_protocol_checker_v1_2_1=$RDI_DATADIR/xsim/ip/axis_protocol_checker_v1_2_1\naxi_traffic_gen_v2_0_16=$RDI_DATADIR/xsim/ip/axi_traffic_gen_v2_0_16\nieee802d3_rs_fec_v1_0_11=$RDI_DATADIR/xsim/ip/ieee802d3_rs_fec_v1_0_11\naxi_gpio_v2_0_17=$RDI_DATADIR/xsim/ip/axi_gpio_v2_0_17\naxis_switch_v1_1_15=$RDI_DATADIR/xsim/ip/axis_switch_v1_1_15\npci64_v5_0_9=$RDI_DATADIR/xsim/ip/pci64_v5_0_9\nv_cfa_v7_0_13=$RDI_DATADIR/xsim/ip/v_cfa_v7_0_13\nv_enhance_v8_0_14=$RDI_DATADIR/xsim/ip/v_enhance_v8_0_14\nxsdbm_v3_0_0=$RDI_DATADIR/xsim/ip/xsdbm_v3_0_0\nemc_common_v3_0_5=$RDI_DATADIR/xsim/ip/emc_common_v3_0_5\nlib_bmg_v1_0_10=$RDI_DATADIR/xsim/ip/lib_bmg_v1_0_10\nsem_ultra_v3_1_6=$RDI_DATADIR/xsim/ip/sem_ultra_v3_1_6\nblk_mem_gen_v8_4_1=$RDI_DATADIR/xsim/ip/blk_mem_gen_v8_4_1\necc_v2_0_12=$RDI_DATADIR/xsim/ip/ecc_v2_0_12\nv_smpte_sdi_v3_0_8=$RDI_DATADIR/xsim/ip/v_smpte_sdi_v3_0_8\naxi_timer_v2_0_17=$RDI_DATADIR/xsim/ip/axi_timer_v2_0_17\naxi_ethernet_buffer_v2_0_17=$RDI_DATADIR/xsim/ip/axi_ethernet_buffer_v2_0_17\npc_cfr_v6_0_6=$RDI_DATADIR/xsim/ip/pc_cfr_v6_0_6\nv_axi4s_vid_out_v4_0_8=$RDI_DATADIR/xsim/ip/v_axi4s_vid_out_v4_0_8\nten_gig_eth_mac_v15_1_4=$RDI_DATADIR/xsim/ip/ten_gig_eth_mac_v15_1_4\nvfb_v1_0_9=$RDI_DATADIR/xsim/ip/vfb_v1_0_9\naxi_jtag_v1_0_0=$RDI_DATADIR/xsim/ip/axi_jtag_v1_0_0\nsmartconnect_v1_0=$RDI_DATADIR/xsim/ip/smartconnect_v1_0\nquadsgmii_v3_4_2=$RDI_DATADIR/xsim/ip/quadsgmii_v3_4_2\nv_smpte_uhdsdi_v1_0_5=$RDI_DATADIR/xsim/ip/v_smpte_uhdsdi_v1_0_5\nfloating_point_v7_0_14=$RDI_DATADIR/xsim/ip/floating_point_v7_0_14\nxxv_ethernet_v2_3_1=$RDI_DATADIR/xsim/ip/xxv_ethernet_v2_3_1\nxbip_dsp48_multacc_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_dsp48_multacc_v3_0_4\ntcc_decoder_3gpplte_v3_0_6=$RDI_DATADIR/xsim/ip/tcc_decoder_3gpplte_v3_0_6\naxi_ahblite_bridge_v3_0_13=$RDI_DATADIR/xsim/ip/axi_ahblite_bridge_v3_0_13\naxis_dwidth_converter_v1_1_14=$RDI_DATADIR/xsim/ip/axis_dwidth_converter_v1_1_14\nmdm_v3_2=$RDI_DATADIR/xsim/ip/mdm_v3_2\nlte_3gpp_mimo_decoder_v3_0_13=$RDI_DATADIR/xsim/ip/lte_3gpp_mimo_decoder_v3_0_13\nutil_idelay_ctrl_v1_0_1=$RDI_DATADIR/xsim/ip/util_idelay_ctrl_v1_0_1\naxi_mmu_v2_1_13=$RDI_DATADIR/xsim/ip/axi_mmu_v2_1_13\naxi_pcie_v2_8_7=$RDI_DATADIR/xsim/ip/axi_pcie_v2_8_7\nv_hdmi_tx_v2_0_0=$RDI_DATADIR/xsim/ip/v_hdmi_tx_v2_0_0\nprc_v1_2_1=$RDI_DATADIR/xsim/ip/prc_v1_2_1\naxi_uartlite_v2_0_19=$RDI_DATADIR/xsim/ip/axi_uartlite_v2_0_19\ntcc_encoder_3gpplte_v4_0_13=$RDI_DATADIR/xsim/ip/tcc_encoder_3gpplte_v4_0_13\naxi_timebase_wdt_v3_0_7=$RDI_DATADIR/xsim/ip/axi_timebase_wdt_v3_0_7\ncan_v5_0_18=$RDI_DATADIR/xsim/ip/can_v5_0_18\nv_vid_in_axi4s_v4_0_7=$RDI_DATADIR/xsim/ip/v_vid_in_axi4s_v4_0_7\naxi_vfifo_ctrl_v2_0_17=$RDI_DATADIR/xsim/ip/axi_vfifo_ctrl_v2_0_17\ndiv_gen_v5_1_12=$RDI_DATADIR/xsim/ip/div_gen_v5_1_12\nxsdbs_v1_0_2=$RDI_DATADIR/xsim/ip/xsdbs_v1_0_2\ntmr_inject_v1_0_1=$RDI_DATADIR/xsim/ip/tmr_inject_v1_0_1\nfir_compiler_v7_2_10=$RDI_DATADIR/xsim/ip/fir_compiler_v7_2_10\ninterrupt_control_v3_1_4=$RDI_DATADIR/xsim/ip/interrupt_control_v3_1_4\naxis_combiner_v1_1_14=$RDI_DATADIR/xsim/ip/axis_combiner_v1_1_14\nxbip_dsp48_addsub_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_dsp48_addsub_v3_0_4\nlte_pucch_receiver_v2_0_13=$RDI_DATADIR/xsim/ip/lte_pucch_receiver_v2_0_13\nv_hdmi_rx_v2_0_0=$RDI_DATADIR/xsim/ip/v_hdmi_rx_v2_0_0\nv_rgb2ycrcb_v7_1_12=$RDI_DATADIR/xsim/ip/v_rgb2ycrcb_v7_1_12\nv_gamma_v7_0_14=$RDI_DATADIR/xsim/ip/v_gamma_v7_0_14\nltlib_v1_0_0=$RDI_DATADIR/xsim/ip/ltlib_v1_0_0\nlut_buffer_v2_0_0=$RDI_DATADIR/xsim/ip/lut_buffer_v2_0_0\nblk_mem_gen_v8_3_6=$RDI_DATADIR/xsim/ip/blk_mem_gen_v8_3_6\nfit_timer_v2_0_8=$RDI_DATADIR/xsim/ip/fit_timer_v2_0_8\nfifo_generator_v13_0_6=$RDI_DATADIR/xsim/ip/fifo_generator_v13_0_6\nmutex_v2_1_8=$RDI_DATADIR/xsim/ip/mutex_v2_1_8\nieee802d3_200g_rs_fec_v1_0_1=$RDI_DATADIR/xsim/ip/ieee802d3_200g_rs_fec_v1_0_1\nxilinx_vip=$RDI_DATADIR/xsim/ip/xilinx_vip\naxi_infrastructure_v1_1_0=$RDI_DATADIR/xsim/ip/axi_infrastructure_v1_1_0\nxil_common_vip_v1_0_0=$RDI_DATADIR/xsim/ip/xil_common_vip_v1_0_0\nlib_cdc_v1_0_2=$RDI_DATADIR/xsim/ip/lib_cdc_v1_0_2\namm_axi_bridge_v1_0_1=$RDI_DATADIR/xsim/ip/amm_axi_bridge_v1_0_1\ndisplayport_v7_0_7=$RDI_DATADIR/xsim/ip/displayport_v7_0_7\nvideoaxi4s_bridge_v1_0_5=$RDI_DATADIR/xsim/ip/videoaxi4s_bridge_v1_0_5\ngmii_to_rgmii_v4_0_5=$RDI_DATADIR/xsim/ip/gmii_to_rgmii_v4_0_5\ndist_mem_gen_v8_0_12=$RDI_DATADIR/xsim/ip/dist_mem_gen_v8_0_12\nxbip_dsp48_multadd_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_dsp48_multadd_v3_0_4\nrs_decoder_v9_0_13=$RDI_DATADIR/xsim/ip/rs_decoder_v9_0_13\nxdma_v4_0_1=$RDI_DATADIR/xsim/ip/xdma_v4_0_1\nv_sdi_rx_vid_bridge_v2_0_0=$RDI_DATADIR/xsim/ip/v_sdi_rx_vid_bridge_v2_0_0\nmicroblaze_v9_5_4=$RDI_DATADIR/xsim/ip/microblaze_v9_5_4\naxi_traffic_gen_v3_0_1=$RDI_DATADIR/xsim/ip/axi_traffic_gen_v3_0_1\ncanfd_v1_0_8=$RDI_DATADIR/xsim/ip/canfd_v1_0_8\nl_ethernet_v2_3_1=$RDI_DATADIR/xsim/ip/l_ethernet_v2_3_1\ntri_mode_ethernet_mac_v9_0_10=$RDI_DATADIR/xsim/ip/tri_mode_ethernet_mac_v9_0_10\nv_ycrcb2rgb_v7_1_12=$RDI_DATADIR/xsim/ip/v_ycrcb2rgb_v7_1_12\nrst_vip_v1_0_0=$RDI_DATADIR/xsim/ip/rst_vip_v1_0_0\nvideo_frame_crc_v1_0_0=$RDI_DATADIR/xsim/ip/video_frame_crc_v1_0_0\nlte_rach_detector_v3_1_1=$RDI_DATADIR/xsim/ip/lte_rach_detector_v3_1_1\naxi_pcie3_v3_0_5=$RDI_DATADIR/xsim/ip/axi_pcie3_v3_0_5\ncpri_v8_8_1=$RDI_DATADIR/xsim/ip/cpri_v8_8_1\naxi_msg_v1_0_1=$RDI_DATADIR/xsim/ip/axi_msg_v1_0_1\nmult_gen_v12_0_13=$RDI_DATADIR/xsim/ip/mult_gen_v12_0_13\nv_hscaler_v1_0_9=$RDI_DATADIR/xsim/ip/v_hscaler_v1_0_9\naxi_vip_v1_1_1=$RDI_DATADIR/xsim/ip/axi_vip_v1_1_1\nflexo_100g_rs_fec_v1_0_5=$RDI_DATADIR/xsim/ip/flexo_100g_rs_fec_v1_0_5\naxi_tft_v2_0_19=$RDI_DATADIR/xsim/ip/axi_tft_v2_0_19\nv_cresample_v4_0_13=$RDI_DATADIR/xsim/ip/v_cresample_v4_0_13\npr_decoupler_v1_0_5=$RDI_DATADIR/xsim/ip/pr_decoupler_v1_0_5\npci32_v5_0_9=$RDI_DATADIR/xsim/ip/pci32_v5_0_9\nmipi_dsi_tx_ctrl_v1_0_5=$RDI_DATADIR/xsim/ip/mipi_dsi_tx_ctrl_v1_0_5\njesd204c_v2_0_1=$RDI_DATADIR/xsim/ip/jesd204c_v2_0_1\nhdcp22_cipher_v1_0_2=$RDI_DATADIR/xsim/ip/hdcp22_cipher_v1_0_2\nc_shift_ram_v12_0_11=$RDI_DATADIR/xsim/ip/c_shift_ram_v12_0_11\nv_vscaler_v1_0_9=$RDI_DATADIR/xsim/ip/v_vscaler_v1_0_9\nfifo_generator_v13_2_1=$RDI_DATADIR/xsim/ip/fifo_generator_v13_2_1\ng975_efec_i7_v2_0_16=$RDI_DATADIR/xsim/ip/g975_efec_i7_v2_0_16\nv_hdmi_rx_v3_0_0=$RDI_DATADIR/xsim/ip/v_hdmi_rx_v3_0_0\nlib_fifo_v1_0_10=$RDI_DATADIR/xsim/ip/lib_fifo_v1_0_10\nv_deinterlacer_v4_0_12=$RDI_DATADIR/xsim/ip/v_deinterlacer_v4_0_12\nxlslice_v1_0_1=$RDI_DATADIR/xsim/ip/xlslice_v1_0_1\nfec_5g_common_v1_0_0=$RDI_DATADIR/xsim/ip/fec_5g_common_v1_0_0\noddr_v1_0_0=$RDI_DATADIR/xsim/ip/oddr_v1_0_0\naxi_quad_spi_v3_2_14=$RDI_DATADIR/xsim/ip/axi_quad_spi_v3_2_14\nxbip_dsp48_mult_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_dsp48_mult_v3_0_4\nahblite_axi_bridge_v3_0_13=$RDI_DATADIR/xsim/ip/ahblite_axi_bridge_v3_0_13\nten_gig_eth_pcs_pma_v6_0_11=$RDI_DATADIR/xsim/ip/ten_gig_eth_pcs_pma_v6_0_11\naxis_data_fifo_v1_1_16=$RDI_DATADIR/xsim/ip/axis_data_fifo_v1_1_16\niomodule_v3_1_3=$RDI_DATADIR/xsim/ip/iomodule_v3_1_3\ninterlaken_v2_3_1=$RDI_DATADIR/xsim/ip/interlaken_v2_3_1\ntmr_manager_v1_0_2=$RDI_DATADIR/xsim/ip/tmr_manager_v1_0_2\ntimer_sync_1588_v1_2_4=$RDI_DATADIR/xsim/ip/timer_sync_1588_v1_2_4\naxi_utils_v2_0_4=$RDI_DATADIR/xsim/ip/axi_utils_v2_0_4\nv_osd_v6_0_15=$RDI_DATADIR/xsim/ip/v_osd_v6_0_15\nbs_switch_v1_0_0=$RDI_DATADIR/xsim/ip/bs_switch_v1_0_0\npcie_jtag_v1_0_0=$RDI_DATADIR/xsim/ip/pcie_jtag_v1_0_0\naxi_protocol_checker_v2_0_1=$RDI_DATADIR/xsim/ip/axi_protocol_checker_v2_0_1\naxis_accelerator_adapter_v2_1_12=$RDI_DATADIR/xsim/ip/axis_accelerator_adapter_v2_1_12\ntcc_encoder_3gpp_v5_0_12=$RDI_DATADIR/xsim/ip/tcc_encoder_3gpp_v5_0_12\ng975_efec_i4_v1_0_14=$RDI_DATADIR/xsim/ip/g975_efec_i4_v1_0_14\nxbip_dsp48_acc_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_dsp48_acc_v3_0_4\nldpc_v1_0_1=$RDI_DATADIR/xsim/ip/ldpc_v1_0_1\nhigh_speed_selectio_wiz_v3_2_3=$RDI_DATADIR/xsim/ip/high_speed_selectio_wiz_v3_2_3\naxi4svideo_bridge_v1_0_8=$RDI_DATADIR/xsim/ip/axi4svideo_bridge_v1_0_8\nieee802d3_25g_rs_fec_v1_0_7=$RDI_DATADIR/xsim/ip/ieee802d3_25g_rs_fec_v1_0_7\nc_accum_v12_0_11=$RDI_DATADIR/xsim/ip/c_accum_v12_0_11\nc_gate_bit_v12_0_4=$RDI_DATADIR/xsim/ip/c_gate_bit_v12_0_4\nieee802d3_400g_rs_fec_v1_0_1=$RDI_DATADIR/xsim/ip/ieee802d3_400g_rs_fec_v1_0_1\nv_smpte_uhdsdi_rx_v1_0_0=$RDI_DATADIR/xsim/ip/v_smpte_uhdsdi_rx_v1_0_0\nlmb_bram_if_cntlr_v4_0=$RDI_DATADIR/xsim/ip/lmb_bram_if_cntlr_v4_0\naxi_vdma_v6_3_3=$RDI_DATADIR/xsim/ip/axi_vdma_v6_3_3\nlmb_v10_v3_0_9=$RDI_DATADIR/xsim/ip/lmb_v10_v3_0_9\naxi_firewall_v1_0_3=$RDI_DATADIR/xsim/ip/axi_firewall_v1_0_3\naxi_uart16550_v2_0_17=$RDI_DATADIR/xsim/ip/axi_uart16550_v2_0_17\ncordic_v6_0_13=$RDI_DATADIR/xsim/ip/cordic_v6_0_13\naxi_emc_v3_0_15=$RDI_DATADIR/xsim/ip/axi_emc_v3_0_15\naxi_dma_v7_1_16=$RDI_DATADIR/xsim/ip/axi_dma_v7_1_16\nxbip_dsp48_macro_v3_0_15=$RDI_DATADIR/xsim/ip/xbip_dsp48_macro_v3_0_15\naxis_interconnect_v1_1_14=$RDI_DATADIR/xsim/ip/axis_interconnect_v1_1_14\nmdm_v3_2_12=$RDI_DATADIR/xsim/ip/mdm_v3_2_12\nieee802d3_50g_rs_fec_v1_0_7=$RDI_DATADIR/xsim/ip/ieee802d3_50g_rs_fec_v1_0_7\naxi_lite_ipif_v3_0_4=$RDI_DATADIR/xsim/ip/axi_lite_ipif_v3_0_4\naxi_lite_ipif_v3_0=$RDI_DATADIR/xsim/ip/axi_lite_ipif_v3_0\nxbip_addsub_v3_0_4=$RDI_DATADIR/xsim/ip/xbip_addsub_v3_0_4\nsem_v4_1_10=$RDI_DATADIR/xsim/ip/sem_v4_1_10\niomodule_v3_0=$RDI_DATADIR/xsim/ip/iomodule_v3_0\nv_hcresampler_v1_0_9=$RDI_DATADIR/xsim/ip/v_hcresampler_v1_0_9\ncmpy_v6_0_14=$RDI_DATADIR/xsim/ip/cmpy_v6_0_14\naxi_data_fifo_v2_1_14=$RDI_DATADIR/xsim/ip/axi_data_fifo_v2_1_14\nethernet_1_10_25g_v1_0_1=$RDI_DATADIR/xsim/ip/ethernet_1_10_25g_v1_0_1\nmipi_dphy_v4_0_1=$RDI_DATADIR/xsim/ip/mipi_dphy_v4_0_1\nswitch_core_top_v1_0_4=$RDI_DATADIR/xsim/ip/switch_core_top_v1_0_4\nsid_v8_0_11=$RDI_DATADIR/xsim/ip/sid_v8_0_11\nutil_reduced_logic_v2_0_3=$RDI_DATADIR/xsim/ip/util_reduced_logic_v2_0_3\naxis_subset_converter_v1_1_15=$RDI_DATADIR/xsim/ip/axis_subset_converter_v1_1_15\naxi_bram_ctrl_v4_0_13=$RDI_DATADIR/xsim/ip/axi_bram_ctrl_v4_0_13\nv_frmbuf_wr_v2_0_1=$RDI_DATADIR/xsim/ip/v_frmbuf_wr_v2_0_1\nlte_fft_v2_0_15=$RDI_DATADIR/xsim/ip/lte_fft_v2_0_15\nlut_buffer_v1_0_0=$RDI_DATADIR/xsim/ip/lut_buffer_v1_0_0\nfifo_generator_v13_1_4=$RDI_DATADIR/xsim/ip/fifo_generator_v13_1_4\nclk_vip_v1_0_0=$RDI_DATADIR/xsim/ip/clk_vip_v1_0_0\naxi_sg_v4_1_8=$RDI_DATADIR/xsim/ip/axi_sg_v4_1_8\ngtwizard_ultrascale_v1_7_2=$RDI_DATADIR/xsim/ip/gtwizard_ultrascale_v1_7_2\naxi_vip_v1_0_4=$RDI_DATADIR/xsim/ip/axi_vip_v1_0_4\nmicroblaze_mcs_v2_3_6=$RDI_DATADIR/xsim/ip/microblaze_mcs_v2_3_6\nxpm=$RDI_DATADIR/xsim/ip/xpm\nmii_to_rmii_v2_0_17=$RDI_DATADIR/xsim/ip/mii_to_rmii_v2_0_17\ncmac_v2_3_1=$RDI_DATADIR/xsim/ip/cmac_v2_3_1\naxi_intc_v4_1_10=$RDI_DATADIR/xsim/ip/axi_intc_v4_1_10\npc_cfr_v6_1_2=$RDI_DATADIR/xsim/ip/pc_cfr_v6_1_2\nproc_sys_reset_v5_0_12=$RDI_DATADIR/xsim/ip/proc_sys_reset_v5_0_12\nxbip_multadd_v3_0_11=$RDI_DATADIR/xsim/ip/xbip_multadd_v3_0_11\nxaui_v12_3_2=$RDI_DATADIR/xsim/ip/xaui_v12_3_2\ngeneric_baseblocks_v2_1_0=$RDI_DATADIR/xsim/ip/generic_baseblocks_v2_1_0\nav_pat_gen_v1_0_0=$RDI_DATADIR/xsim/ip/av_pat_gen_v1_0_0\njesd204_v7_2_1=$RDI_DATADIR/xsim/ip/jesd204_v7_2_1\nlmb_v10_v3_0=$RDI_DATADIR/xsim/ip/lmb_v10_v3_0\naxi_iic_v2_0_18=$RDI_DATADIR/xsim/ip/axi_iic_v2_0_18\nc_reg_fd_v12_0_4=$RDI_DATADIR/xsim/ip/c_reg_fd_v12_0_4\nv_dual_splitter_v1_0_8=$RDI_DATADIR/xsim/ip/v_dual_splitter_v1_0_8\naxi_apb_bridge_v3_0_13=$RDI_DATADIR/xsim/ip/axi_apb_bridge_v3_0_13\naxi_crossbar_v2_1_16=$RDI_DATADIR/xsim/ip/axi_crossbar_v2_1_16\nv_deinterlacer_v5_0_9=$RDI_DATADIR/xsim/ip/v_deinterlacer_v5_0_9\ntsn_temac_v1_0_2=$RDI_DATADIR/xsim/ip/tsn_temac_v1_0_2\nv_smpte_uhdsdi_tx_v1_0_0=$RDI_DATADIR/xsim/ip/v_smpte_uhdsdi_tx_v1_0_0\nxhmc_v1_0_5=$RDI_DATADIR/xsim/ip/xhmc_v1_0_5\nlib_srl_fifo_v1_0_2=$RDI_DATADIR/xsim/ip/lib_srl_fifo_v1_0_2\ng709_rs_encoder_v2_2_4=$RDI_DATADIR/xsim/ip/g709_rs_encoder_v2_2_4\naxis_infrastructure_v1_1_0=$RDI_DATADIR/xsim/ip/axis_infrastructure_v1_1_0\nusxgmii_v1_0_1=$RDI_DATADIR/xsim/ip/usxgmii_v1_0_1\nrs_toolbox_v9_0_4=$RDI_DATADIR/xsim/ip/rs_toolbox_v9_0_4\nsrio_gen2_v4_1_2=$RDI_DATADIR/xsim/ip/srio_gen2_v4_1_2\naxi_clock_converter_v2_1_14=$RDI_DATADIR/xsim/ip/axi_clock_converter_v2_1_14\nxsdbm_v2_0_0=$RDI_DATADIR/xsim/ip/xsdbm_v2_0_0\naxi4stream_vip_v1_1_1=$RDI_DATADIR/xsim/ip/axi4stream_vip_v1_1_1\nxil_defaultlib=xsim.dir/xil_defaultlib\n" }, { "alpha_fraction": 0.6975030899047852, "alphanum_fraction": 0.7249283790588379, "avg_line_length": 34.40579605102539, "blob_id": "bc79c57ff368f93eca88723c230560fe9a28c9fa", "content_id": "152aaa2ee6131457dc23b97854ecc44281bee14d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2443, "license_type": "permissive", "max_line_length": 116, "num_lines": 69, "path": "/sw/xfully_pipelined_spmv.h", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "/*\n * xfully_pipelined_spmv.h\n *\n * Created on: Jul 3, 2018\n * Author: asiatici\n */\n\n#ifndef SRC_XFULLY_PIPELINED_SPMV_H_\n#define SRC_XFULLY_PIPELINED_SPMV_H_\n#include \"xil_io.h\"\n\n#define SPLIT_INPUT_VECTORS\n\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL 0x00\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_GIE 0x04\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_IER 0x08\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_ISR 0x0c\n#define XSPMV_MULT_AXIS_AXILITES_BITS_VAL_SIZE_DATA 32\n#define XSPMV_MULT_AXIS_AXILITES_BITS_OUTPUT_SIZE_DATA 32\n#define XSPMV_MULT_AXIS_AXILITES_BITS_VECT_MEM_DATA 32\n#ifdef SPLIT_INPUT_VECTORS\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_VAL_SIZE_DATA 0x4\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_OUTPUT_SIZE_DATA 0x8\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_VECT_MEM_DATA 0xC\n#else\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_VAL_SIZE_DATA 0x10\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_OUTPUT_SIZE_DATA 0x18\n#define XSPMV_MULT_AXIS_AXILITES_ADDR_VECT_MEM_DATA 0x20\n#endif\n\nextern u32 spmv_base_addrs[];\n\n#define XSpmv_mult_axis_ReadReg(BaseAddress, RegOffset) \\\n Xil_In32((BaseAddress) + (RegOffset))\n\n#define XSpmv_mult_axis_WriteReg(BaseAddress, RegOffset, Data) \\\n Xil_Out32((BaseAddress) + (RegOffset), (u32)(Data))\n\nu32 XSpmv_mult_axis_IsIdle(int instance_index) {\n u32 Data;\n\n Data = XSpmv_mult_axis_ReadReg(spmv_base_addrs[instance_index], XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL);\n#ifdef SPLIT_INPUT_VECTORS\n return Data & 0x1;\n#else\n return (Data >> 2) & 0x1;\n#endif\n}\n\nvoid XSpmv_mult_axis_Set_val_size(int instance_index, u32 Data) {\n XSpmv_mult_axis_WriteReg(spmv_base_addrs[instance_index], XSPMV_MULT_AXIS_AXILITES_ADDR_VAL_SIZE_DATA, Data);\n}\n\nvoid XSpmv_mult_axis_Set_output_size(int instance_index, u32 Data) {\n XSpmv_mult_axis_WriteReg(spmv_base_addrs[instance_index], XSPMV_MULT_AXIS_AXILITES_ADDR_OUTPUT_SIZE_DATA, Data);\n}\n\nvoid XSpmv_mult_axis_Set_vect_mem(int instance_index, u32 Data) {\n XSpmv_mult_axis_WriteReg(spmv_base_addrs[instance_index], XSPMV_MULT_AXIS_AXILITES_ADDR_VECT_MEM_DATA, Data);\n}\n\nvoid XSpmv_mult_axis_Start(int instance_index) {\n u32 Data;\n\n Data = XSpmv_mult_axis_ReadReg(spmv_base_addrs[instance_index], XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL) & 0x80;\n XSpmv_mult_axis_WriteReg(spmv_base_addrs[instance_index], XSPMV_MULT_AXIS_AXILITES_ADDR_AP_CTRL, Data | 0x01);\n}\n\n#endif /* SRC_XFULLY_PIPELINED_SPMV_H_ */\n" }, { "alpha_fraction": 0.663275957107544, "alphanum_fraction": 0.6838810443878174, "avg_line_length": 34.174312591552734, "blob_id": "2988c441491b4c45938c6c1344883ca2465674ab", "content_id": "cd09a5c36198596d648ee92a1d0fe60f2c048068", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3834, "license_type": "permissive", "max_line_length": 99, "num_lines": 109, "path": "/spmv/TopLevel/TopLevel.srcs/sources_1/ip/spmv_mult_axis_0_1/drivers/spmv_mult_axis_v1_0/src/xspmv_mult_axis.h", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "// ==============================================================\n// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC\n// Version: 2017.4\n// Copyright (C) 1986-2017 Xilinx, Inc. All Rights Reserved.\n// \n// ==============================================================\n\n#ifndef XSPMV_MULT_AXIS_H\n#define XSPMV_MULT_AXIS_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/***************************** Include Files *********************************/\n#ifndef __linux__\n#include \"xil_types.h\"\n#include \"xil_assert.h\"\n#include \"xstatus.h\"\n#include \"xil_io.h\"\n#else\n#include <stdint.h>\n#include <assert.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/mman.h>\n#include <unistd.h>\n#include <stddef.h>\n#endif\n#include \"xspmv_mult_axis_hw.h\"\n\n/**************************** Type Definitions ******************************/\n#ifdef __linux__\ntypedef uint8_t u8;\ntypedef uint16_t u16;\ntypedef uint32_t u32;\n#else\ntypedef struct {\n u16 DeviceId;\n u32 Axilites_BaseAddress;\n} XSpmv_mult_axis_Config;\n#endif\n\ntypedef struct {\n u32 Axilites_BaseAddress;\n u32 IsReady;\n} XSpmv_mult_axis;\n\n/***************** Macros (Inline Functions) Definitions *********************/\n#ifndef __linux__\n#define XSpmv_mult_axis_WriteReg(BaseAddress, RegOffset, Data) \\\n Xil_Out32((BaseAddress) + (RegOffset), (u32)(Data))\n#define XSpmv_mult_axis_ReadReg(BaseAddress, RegOffset) \\\n Xil_In32((BaseAddress) + (RegOffset))\n#else\n#define XSpmv_mult_axis_WriteReg(BaseAddress, RegOffset, Data) \\\n *(volatile u32*)((BaseAddress) + (RegOffset)) = (u32)(Data)\n#define XSpmv_mult_axis_ReadReg(BaseAddress, RegOffset) \\\n *(volatile u32*)((BaseAddress) + (RegOffset))\n\n#define Xil_AssertVoid(expr) assert(expr)\n#define Xil_AssertNonvoid(expr) assert(expr)\n\n#define XST_SUCCESS 0\n#define XST_DEVICE_NOT_FOUND 2\n#define XST_OPEN_DEVICE_FAILED 3\n#define XIL_COMPONENT_IS_READY 1\n#endif\n\n/************************** Function Prototypes *****************************/\n#ifndef __linux__\nint XSpmv_mult_axis_Initialize(XSpmv_mult_axis *InstancePtr, u16 DeviceId);\nXSpmv_mult_axis_Config* XSpmv_mult_axis_LookupConfig(u16 DeviceId);\nint XSpmv_mult_axis_CfgInitialize(XSpmv_mult_axis *InstancePtr, XSpmv_mult_axis_Config *ConfigPtr);\n#else\nint XSpmv_mult_axis_Initialize(XSpmv_mult_axis *InstancePtr, const char* InstanceName);\nint XSpmv_mult_axis_Release(XSpmv_mult_axis *InstancePtr);\n#endif\n\nvoid XSpmv_mult_axis_Start(XSpmv_mult_axis *InstancePtr);\nu32 XSpmv_mult_axis_IsDone(XSpmv_mult_axis *InstancePtr);\nu32 XSpmv_mult_axis_IsIdle(XSpmv_mult_axis *InstancePtr);\nu32 XSpmv_mult_axis_IsReady(XSpmv_mult_axis *InstancePtr);\nvoid XSpmv_mult_axis_EnableAutoRestart(XSpmv_mult_axis *InstancePtr);\nvoid XSpmv_mult_axis_DisableAutoRestart(XSpmv_mult_axis *InstancePtr);\n\nvoid XSpmv_mult_axis_Set_val_size(XSpmv_mult_axis *InstancePtr, u32 Data);\nu32 XSpmv_mult_axis_Get_val_size(XSpmv_mult_axis *InstancePtr);\nvoid XSpmv_mult_axis_Set_output_size(XSpmv_mult_axis *InstancePtr, u32 Data);\nu32 XSpmv_mult_axis_Get_output_size(XSpmv_mult_axis *InstancePtr);\nvoid XSpmv_mult_axis_Set_vect_mem(XSpmv_mult_axis *InstancePtr, u32 Data);\nu32 XSpmv_mult_axis_Get_vect_mem(XSpmv_mult_axis *InstancePtr);\n\nvoid XSpmv_mult_axis_InterruptGlobalEnable(XSpmv_mult_axis *InstancePtr);\nvoid XSpmv_mult_axis_InterruptGlobalDisable(XSpmv_mult_axis *InstancePtr);\nvoid XSpmv_mult_axis_InterruptEnable(XSpmv_mult_axis *InstancePtr, u32 Mask);\nvoid XSpmv_mult_axis_InterruptDisable(XSpmv_mult_axis *InstancePtr, u32 Mask);\nvoid XSpmv_mult_axis_InterruptClear(XSpmv_mult_axis *InstancePtr, u32 Mask);\nu32 XSpmv_mult_axis_InterruptGetEnabled(XSpmv_mult_axis *InstancePtr);\nu32 XSpmv_mult_axis_InterruptGetStatus(XSpmv_mult_axis *InstancePtr);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.7414358854293823, "alphanum_fraction": 0.7625641226768494, "avg_line_length": 63.144737243652344, "blob_id": "656209d446d2efd1d31cb8a035626b43281ee1e3", "content_id": "aef9b1e7c75172dd89d7f6eaee98c1594d6bb0f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9755, "license_type": "permissive", "max_line_length": 566, "num_lines": 152, "path": "/README.md", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "# Stop Crying Over Your Cache Miss Rate: Handling Efficiently Thousands of Outstanding Misses in FPGAs\n\nThis repository contains the full Chisel source code of a highly flexible, FPGA-optimized, multi-banked non-blocking cache. The block RAM-based MSHRs (miss status holding registers) can support tens of thousands of outstanding misses, minimizing pipeline stalls due to the memory system and increasing the performance of bandwidth-bound, latency insensitive accelerators.\n\nFull details are provided in the [wiki](https://github.com/m-asiatici/MSHR-rich/wiki) and in our paper:\n\n[Mikhail Asiatici and Paolo Ienne. 2019. Stop Crying Over Your Cache Miss\nRate:, Handling Efficiently Thousands of Outstanding Misses in FPGAs. In\nThe 2019 ACM/SIGDA International Symposium on Field-Programmable Gate\nArrays (FPGA ’19), February 24–26, 2019, Seaside, CA, USA.](https://doi.org/10.1145/3289602.3293901)\n\nPlease cite that paper when using this hardware module.\n\n## Overview\n![System block diagram](doc/system.svg)\n\nThe full pipeline is as follows:\n1) **Validation and generation of the configuration file**. Use our System Configurator GUI to generate a valid configuration for the non-blocking cache. Refer to the Wiki for the full documentation on the parameters.\n2) **Chisel build**, which generates a set of Verilog and `.hex` files (for BRAM initialization).\n3) **IP-XACT packaging**. Based on [Jens Korinth's scripts](https://github.com/jkorinth/chisel-packaging) which use Vivado to automatically infer the AXI4 interfaces.\n4) **Vivado project generation.** A `.tcl` script creates a Vivado project which integrates the non-blocking cache with four simple sparse matrix-vector multiplication accelerators.\n\nThe full pipeline has been tested with **Vivado 2017.4** and on a **Zynq ZC706** board. However, step 1) and 2) should be device- and vendor-agnostic -- please open an issue if you find an incompatibility\n\n## Requirements\n\nThe flow has been tested on Ubuntu 18.04.\n\n### [Chisel 3](https://github.com/freechipsproject/chisel3)\n1) Install Java:\n```\nsudo apt-get install default-jdk\n```\n2) Install [sbt](https://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html):\n```\necho \"deb https://dl.bintray.com/sbt/debian /\" | sudo tee -a /etc/apt/sources.list.d/sbt.list\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 642AC823\nsudo apt-get update\nsudo apt-get install sbt\n```\n3) Verilator is NOT required.\n\n### Vivado\nMake sure that Vivado is properly configured and that the `vivado` executable is in `PATH`. An easy way to achieve this is to source `settings64.sh` in the Vivado installation folder.\n\n### Python\nUbuntu 18.04 should already have at least Python 2, but just in case:\n`sudo apt-get install python3 python`\n\n## Chisel build (GUI)\n1) Launch `MSHR_configurator`\n2) Either create a new configuration file (File -> New) or open an existing one (File -> Open)\n3) Once you completed your configuration, click on Check under Configuration Status to verify its validity\n4) If the configuration is valid, click on Generate Vivado IP to generate the memory system as an IP-XACT compatible with the Vivado IP integrator. The IP will be in `output/ip`.\n5) If you get `[error] (run-main-0) java.lang.RuntimeException: Nonzero exit value: 1`, make sure that `vivado` is in `PATH` and that its license is properly set up. We recommend to run the `MSHR_configurator` from a terminal after configuring Vivado as described in **Requirements/Vivado** instead of double clicking on it from the Linux GUI.\n\n## Chisel build (manual)\n1) Create a configuration file, either with the `MSHR_configurator` or fully manually (not recommended unless you really know what you are doing). configuration. If you don't validate the configuration with the `MSHR_configurator`, be prepared to go through the source code in case one of the Chisel `require()` that validate the parameters fails.\n2) From the root of the repository, run:\n - `sbt \"test:runMain fpgamshr.main.FPGAMSHRIpBuilder [path to the configuration file]\"` to generate Verilog, `.hex` and package them in an IP-XACT compatible with the Vivado IP Integrator.\n - `sbt \"test:runMain fpgamshr.main.FPGAMSHRVerilog [path to the configuration file]\"` to only generate the Verilog and `.hex` files.\n\n## Replication of the results from the [FPGA'19 paper](https://doi.org/10.1145/3289602.3293901)\nWe provide scripts to generate a sample Vivado project that replicates the results discussed in our [FPGA'19 paper](https://doi.org/10.1145/3289602.3293901). The system contains a non-blocking cache with four input ports, connected to four sparse matrix-vector accelerators. The ARM processor:\n1) reads the input data -- sparse matrices and dense vectors -- from the SD card\n2) writes it to the DDR (vector to the PL DDR, all the rest to the PS DDR)\n3) manages the DMAs\n4) starts the accelerators\n5) polls the accelerators and the DMAs\n6) collects data from the profiling registers of the non-blocking cache\n\n### Input data generation\n\nAll the matrices we used in the paper are on [SuiteSparse](https://sparse.tamu.edu/). The `util/mm_matrix_to_csr.py` Python script converts a matrix in MatrixMarket format to the binary format expected by the C code for the ARM processor.\nExample invocation:\n```\nmkdir matrices\ncd matrices\npython3 ../util/mm_matrix_to_csr.py -a 1..4 -i -s -v matrix.mtx\n```\nThe script generates a folder structure that should be copied as it is to an SD card formatted with FAT file system. In the example above, you should copy all the *content* of the `matrices` folder to the SD card, except for the `.mtx` and `.pickle` files. In other words, the root of the SD card should contain one folder per benchmark, each containing one folder per possible number of parallel accelerators (1 to 4 in the example above).\n\n### Vivado project generation\n\n1) Create an IP package as described in **Chisel build**. In the paper, we used the following parameters:\n - 4 inputs\n - input address width: 27\n - input data width: 32\n - input ROB depth: 8192\n - 4 banks\n - 4-way set-associative cache\n - last pointer cache size: 8\n - subentries per row: 3\n - external memory address width: 32\n - external memory address offset: 0x80000000\n - external memory data width: 512\n - external memory max outstanding requests: 64\n The other parameters have been swept depending on the design point.\n2) Either click on Generate Script from the `MSHR_configurator`, or run `sbt \"test:runMain fpgamshr.main.FPGAMSHRVivadoBuilder [path to configuration file]\"`. This will also generate the orchestration software (see next section).\n3) Generate and compile the system:\n```\ncd output/vivado\nvivado -mode batch -source generator.tcl # Remove `-mode batch` to get Vivado to run in GUI mode during system generation and compilation\n```\n\nAfter compilation:\n1) Open the Vivado project in `output/vivado/spmv_mult_design/spmv_mult_design.xpr`\n2) File -> Export -> Export hardware -> OK\n3) File -> Launch SDK -> OK\n\n### Xilinx SDK project creation\nFrom the Xilinx SDK:\n1) File -> New -> Application Project\n2) Choose a project name, use the default values for all the rest:\n - Check Use default location\n - OS Platform: standalone\n - Target Hardware Platform: design_1_wrapper_hw_platform_0,\n - Processor: ps7_cortexa9_0\n - Language: C\n - Create new Board Support Package\n3) Click on Next\n4) Select Empty Application, click on Finish\n5) In the Project Explorer, normally on the left hand side of Xilinx SDK, right click on the BSP project (yourProjectName_bsp) -> Board Support Package Settings\n6) Under Supported Libraries, check `xilffs`. We will use this library to read the input matrices and vectors from the SD card.\n7) In the Project Explorer, expand your project and right click on the `src` folder -> Import... ->\n8) General -> File System -> Next\n9) Browse... -> Navigate to `output/sw` -> Select all files -> Check Overwrite existing resources without warning (we will overwrite the default loader script)\n10) In `zynq_code.c`, add the benchmarks that you want to run to the `benchmarks` array and update `NUM_BENCHMARKS` accordingly. Use the same names as the respective folder in the SD card (see **Input data generation**)\n\n### Running the ARM software\nThe software has a triple nested for loop for the experiments:\n```\nforeach benchmark in benchmarks:\n foreach num_acc in 1..4:\n foreach cache_size_divider in 0..CACHE_SIZE_REDUCTION_VALUES:\n execute benchmark on num_acc accelerators with a cache size of CACHE_SIZE/(2 ^ cache_size_divider)\n execute benchmark on num_acc accelerators with no cache\n```\n(check the wiki for additional information on CACHE_SIZE_REDUCTION_VALUES)\nThe ARM prints out debug and performance information via UART (8 data bits, no parity, no flow control, 1 stop bit, baud rate **921600** bps). By default, the code prints out the parameters of each run (benchmark, number of accelerators, cache size) as well as the performance measurements (runtime and a number of internal performance counters) in a table format that can be easily copy-pasted as it is for data analysis. Uncomment the call to `FPGAMSHR_Get_stats_pretty()` to print out a much more verbose dump of all internal performance registers after each run.\n\n## License\n\n- in general¸ `LICENSE` in the repository root applies\n- `src/main/scala/packaging/LICENSE` applies to:\n - `src/main/resources/axi4.py`\n - `src/main/resources/package.py`\n - `src/main/scala/packaging`\n- header of `src/main/scala/util/ResettableRRArbiter.scala` applies to the rest of the file\n\n## Contact\nIf you find any bugs please open an issue. For all other questions, including getting access to the development branch, please contact Mikhail Asiatici (firstname dot lastname at epfl dot ch).\n" }, { "alpha_fraction": 0.686342179775238, "alphanum_fraction": 0.7122368812561035, "avg_line_length": 52.59786605834961, "blob_id": "a465f865c278ae3f6d151bc4a2fb16d484eae1fb", "content_id": "7793d8ada15458b5df1cdaf873995756aefd9eae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15061, "license_type": "permissive", "max_line_length": 176, "num_lines": 281, "path": "/sw/fpgamshr.h", "repo_name": "EPFL-LAP/fpga19-MOMS", "src_encoding": "UTF-8", "text": "/*\n * fpgamshr.h\n *\n * Created on: Jul 5, 2018\n * Author: asiatici\n */\n\n#ifndef FPGAMSHR_H_\n#define FPGAMSHR_H_\n\n#include <limits.h>\n#include \"math.h\"\n#include \"params.h\"\n\n#define NUM_SPMV 4\n#define NUM_INPUTS 4\n\n#define MEMORY_SPAN (1 << ADDR_BITS)\n#define CACHE_SIZE_REDUCTION_VALUES (1 << CACHE_SIZE_REDUCTION_WIDTH)\n\n#if FPGAMSHR_EXISTS\n#define FPGAMSHR_BASEADDR XPAR_FPGAMSHR_0_BASEADDR\n#define FPGAMSHR_BASE_ADDR ((volatile u64*)(XPAR_FPGAMSHR_0_BASEADDR))\n#define CACHE_RECV_REQS_OFFSET (0)\n#define CACHE_HITS_OFFSET (1)\n#define CACHE_CYCLES_OUT_MISSES_STALL_OFFSET (2)\n#define CACHE_CYCLES_OUT_DATA_STALL_OFFSET (3)\n#define MSHR_CURRENTLY_USED_OFFSET (REGS_PER_REQ_HANDLER_MODULE)\n#define MSHR_MAX_USED_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 1)\n#define MSHR_COLLISION_TRIGGER_COUNT_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 2)\n#define TRAD_MSHR_CYCLES_MSHR_FULL (REGS_PER_REQ_HANDLER_MODULE + 2)\n#define MSHR_CYCLES_IN_COLLISION_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 3)\n#define TRAD_MSHR_CYCLES_SE_BUF_FULL (REGS_PER_REQ_HANDLER_MODULE + 3)\n#define MSHR_STALL_TRIGGER_COUNT_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 4)\n#define MSHR_CYCLES_IN_STALL_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 5)\n#define MSHR_ACCEPTED_ALLOCS_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 6)\n#define MSHR_ACCEPTED_DEALLOCS_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 7)\n#define MSHR_CYCLES_ALLOCS_STALLED_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 8)\n#define MSHR_CYCLES_DEALLOCS_STALLED_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 9)\n#define MSHR_ENQUEUED_MEM_REQS_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 10)\n#define MSHR_CYCLES_OUT_SE_BUF_NOT_READY_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 11)\n#define MSHR_ACCUM_USED_MSHR_OFFSET (REGS_PER_REQ_HANDLER_MODULE + 12)\n#define SE_BUF_MAX_USED_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 1)\n#define SE_BUF_MAX_USED_ROWS_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 3)\n#define SE_BUF_MAX_ROWS_WITH_NEXT_PTR_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 5)\n#define SE_BUF_CYCLES_IN_FW_STALL_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 6)\n#define SE_BUF_CYCLES_RESP_GEN_STALL_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 7)\n#define SE_BUF_CYCLES_WRITE_PIPELINE_STALL_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 8)\n#define SE_BUF_CYCLES_VALID_NEXT_PTR_STALL_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 9)\n#define SE_BUF_ACCUM_USED_ENTRIES_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 10)\n#define SE_BUF_ACCUM_USED_ROWS_OFFSET (2*REGS_PER_REQ_HANDLER_MODULE + 11)\n#define RESP_GEN_ACCEPTED_INPUTS_OFFSET (3*REGS_PER_REQ_HANDLER_MODULE)\n#define RESP_GEN_RESP_SENT_OUT_OFFSET (3*REGS_PER_REQ_HANDLER_MODULE + 1)\n#define RESP_GEN_CYCLES_OUT_NOT_READY_OFFSET (3*REGS_PER_REQ_HANDLER_MODULE + 2)\n#define ROB_RECEIVED_REQS (0)\n#define ROB_RECEIVED_RESP (1)\n#define ROB_CURR_USED_ENTRIES (2)\n#define ROB_MAX_USED_ENTRIES (3)\n#define ROB_SENT_RESP (4)\n#define ROB_CYCLES_FULL_STALLED (5)\n#define ROB_CYCLES_REQS_IN_STALLED (6)\n#define ROB_CYCLES_REQS_OUT_STALLED (7)\n#define ROB_CYCLES_RESP_OUT_STALLED (8)\n#define GET_REG_ADDR(x) (FPGAMSHR_BASE_ADDR + x)\n#endif\n\nvoid FPGAMSHR_Clear_stats() {\n#if FPGAMSHR_EXISTS\n\t*(volatile u32*)FPGAMSHR_BASEADDR = 1;\n#endif\n}\n\nvoid FPGAMSHR_Profiling_snapshot() {\n#if FPGAMSHR_EXISTS\n\t*(volatile u32*)FPGAMSHR_BASEADDR = 2;\n#endif\n}\n\nvoid FPGAMSHR_Get_stats_pretty() {\n#if FPGAMSHR_EXISTS\n\t// get snapshot\n\tFPGAMSHR_Profiling_snapshot();\n\tint i;\n\tfor(i = 0; i < NUM_REQ_HANDLERS; i++) {\n\t\tprintf(\"Bank %d\\n\\r\", i);\n\t\tvolatile u64 recv_reqs = *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER);\n\t\tvolatile u64 hits = *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 1);\n\t\tprintf(\"Cache: received requests: %\"PRIu64\"\\n\\r\", recv_reqs);\n\t\tprintf(\"Cache: hits: %\"PRIu64\" (hit rate=%f)\\n\\r\", hits, (float)hits/recv_reqs);\n\t\tprintf(\"Cache: cyclesOutMissesStall: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2));\n\t\tprintf(\"Cache: cyclesOutDataStall: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 3));\n#if MSHR_PER_HASH_TABLE > 0\n\t\tprintf(\"MSHR: currentlyUsedMSHR: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE));\n\t\tprintf(\"MSHR: maxUsedMSHR: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 1));\n#if MSHR_HASH_TABLES > 0\n\t\tprintf(\"MSHR: collisonTriggerCount: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 2));\n\t\tprintf(\"MSHR: cyclesSpentHandlingCollisons: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 3));\n#else // MSHR_HASH_TABLES > 0\n\t\tprintf(\"MSHR: cyclesMSHRFull: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 2));\n\t\tprintf(\"MSHR: cyclesLdBufFull: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 3));\n#endif // MSHR_HASH_TABLES > 0\n\t\tprintf(\"MSHR: stallTriggerCount: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 4));\n\t\tprintf(\"MSHR: cyclesSpentStalling: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 5));\n\t\tprintf(\"MSHR: acceptedAllocsCount: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 6));\n\t\tprintf(\"MSHR: acceptedDeallocsCount: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 7));\n\t\tprintf(\"MSHR: cyclesAllocsStalled: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 8));\n\t\tprintf(\"MSHR: cyclesDeallocsStalled: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 9));\n\t\tprintf(\"MSHR: enqueuedMemReqsCount: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 10));\n\t\tprintf(\"MSHR: cyclesOutLdBufNotReady: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 11));\n\t\tprintf(\"MSHR: accumUsedMSHR: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + REGS_PER_REQ_HANDLER_MODULE + 12));\n\t\tprintf(\"Subentry buffer: snapshotUsedEntries: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE));\n\t\tprintf(\"Subentry buffer: maxUsedEntries: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 1));\n\t\tprintf(\"Subentry buffer: currentlyUsedRows: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 2));\n\t\tprintf(\"Subentry buffer: maxUsedRows: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 3));\n\t\tprintf(\"Subentry buffer: snapshotRowsWithNextRowPtrValid: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 4));\n\t\tprintf(\"Subentry buffer: maxRowsWithNextRowPtrValid: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 5));\n\t\tprintf(\"Subentry buffer: cyclesRespGenStall: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 6));\n\t\tprintf(\"Subentry buffer: cyclesWritePipelineStall: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 7));\n\t\tprintf(\"Subentry buffer: cyclesValidNextPtrInputStall: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 8));\n\t\tprintf(\"Subentry buffer: nextPtrCacheHits: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 9));\n\t\tprintf(\"Subentry buffer: accumUsedEntries: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 10));\n\t\tprintf(\"Subentry buffer: accumUsedRows: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 2*REGS_PER_REQ_HANDLER_MODULE + 11));\n\t\tprintf(\"RespGen: acceptedInputsCount: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 3*REGS_PER_REQ_HANDLER_MODULE));\n\t\tprintf(\"RespGen: responsesSentOutCount: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 3*REGS_PER_REQ_HANDLER_MODULE + 1));\n\t\tprintf(\"RespGen: cyclesOutNotReady: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + i*REGS_PER_REQ_HANDLER + 3*REGS_PER_REQ_HANDLER_MODULE + 2));\n#endif // MSHR_PER_HASH_TABLE > 0\n\t}\n\tfor(i = 0; i < NUM_INPUTS; i++) {\n\t\tprintf(\"Input %d\\n\\r\", i);\n\t\tprintf(\"ROB: receivedRequests: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER));\n\t\tprintf(\"ROB: receivedResponses: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER + 1));\n\t\tprintf(\"ROB: currentlyUsedEntries: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER + 2));\n\t\tprintf(\"ROB: maxUsedEntries: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER + 3));\n\t\tprintf(\"ROB: sentResponses: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER + 4));\n\t\tprintf(\"ROB: cyclesFullStalled: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER + 5));\n\t\tprintf(\"ROB: cyclesReqsInStalled: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER + 6));\n\t\tprintf(\"ROB: cyclesReqsOutStalled: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER + 7));\n\t\tprintf(\"ROB: cyclesRespOutStalled: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + i)*REGS_PER_REQ_HANDLER + 8));\n\t}\n\tvolatile u64 cycles = *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_INPUTS + NUM_REQ_HANDLERS)*REGS_PER_REQ_HANDLER);\n\tprintf(\"Total cycles: %\"PRIu64\"\\n\\r\", cycles);\n\tprintf(\"extMem not ready: %\"PRIu64\"\\n\\r\", *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_INPUTS + NUM_REQ_HANDLERS)*REGS_PER_REQ_HANDLER + 1));\n#endif\n}\n\n\nu64 FPGAMSHR_Get_extMemCyclesNotReady() {\n#if FPGAMSHR_EXISTS\n\treturn *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + NUM_INPUTS)*REGS_PER_REQ_HANDLER + 1);\n#endif\n}\n\nu64 FPGAMSHR_Get_totalCycles() {\n#if FPGAMSHR_EXISTS\n\treturn *((volatile u64*)(FPGAMSHR_BASEADDR) + (NUM_REQ_HANDLERS + NUM_INPUTS)*REGS_PER_REQ_HANDLER);\n#endif\n}\n\nvoid FPGAMSHR_Get_stats_header() {\n\txil_printf(\"extMemNotReady \");\n\txil_printf(\"receivedRequests \");\n\txil_printf(\"hits \");\n\txil_printf(\"numMemRequests \");\n\txil_printf(\"cyclesOutMissesStall \");\n#if MSHR_PER_HASH_TABLE > 0\n\txil_printf(\"maxUsedMSHR \");\n#if MSHR_HASH_TABLES > 0\n\txil_printf(\"cyclesInCollision \");\n\txil_printf(\"cyclesInStall \");\n#else // MSHR_HASH_TABLES > 0\n\txil_printf(\"cyclesMSHRFull \");\n\txil_printf(\"cyclesLdBufFull \");\n#endif // MSHR_HASH_TABLES > 0\n\txil_printf(\"cyclesOutLdBufNotReady \");\n\txil_printf(\"maxUsedLdBufEntries \");\n\txil_printf(\"maxUsedLdBufRows \");\n\txil_printf(\"maxRowsWithNextRowPtrValid \");\n\txil_printf(\"cyclesRespGenStall \");\n\txil_printf(\"cyclesWritePipelineStall \");\n\txil_printf(\"cyclesValidNextPtrInputStall \");\n\txil_printf(\"nextPtrCacheHits \");\n\txil_printf(\"respGenCyclesOutNotReady \");\n\txil_printf(\"robMaxUsedEntries \");\n\txil_printf(\"robCyclesFullStalled \");\n\txil_printf(\"robReqOutStalled \");\n\txil_printf(\"robRespOutStalled \");\n\txil_printf(\"accumUsedMSHR \");\n\txil_printf(\"accumUsedSubentries \");\n\txil_printf(\"accumUsedRows\\n\\r\");\n#endif // MSHR_PER_HASH_TABLE > 0\n}\n\nvoid print_profiling_reg(volatile u64* regOffset) {\n\tdouble mean = 0;\n\tfor(int i = 0; i < NUM_REQ_HANDLERS; i++) {\n\t\tu64 val = *(regOffset + i*REGS_PER_REQ_HANDLER);\n\t\tdouble delta = val - mean;\n\t\tmean += delta / (i + 1);\n\t}\n\tprintf(\"%\"PRIu64\" \", (u64)mean);\n}\n\nvoid print_rob_profiling_reg(volatile u64* regOffset) {\n\tdouble mean = 0;\n\tfor(int i = 0; i < NUM_INPUTS; i++) {\n\t\tu64 val = *(regOffset + (NUM_REQ_HANDLERS+i)*REGS_PER_REQ_HANDLER);\n\t\tdouble delta = val - mean;\n\t\tmean += delta / (i + 1);\n\t}\n\tprintf(\"%\"PRIu64\" \", (u64)mean);\n}\n\nvoid FPGAMSHR_Get_stats_row() {\n#if FPGAMSHR_EXISTS\n\tFPGAMSHR_Profiling_snapshot();\n\tprintf(\"%\"PRIu64\" \", FPGAMSHR_Get_extMemCyclesNotReady());\n\tprint_profiling_reg(GET_REG_ADDR(CACHE_RECV_REQS_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(CACHE_HITS_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(MSHR_ACCEPTED_DEALLOCS_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(CACHE_CYCLES_OUT_MISSES_STALL_OFFSET));\n#if MSHR_PER_HASH_TABLE > 0\n\tprint_profiling_reg(GET_REG_ADDR(MSHR_MAX_USED_OFFSET));\n#if MSHR_HASH_TABLES > 0\n\tprint_profiling_reg(GET_REG_ADDR(MSHR_CYCLES_IN_COLLISION_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(MSHR_CYCLES_IN_STALL_OFFSET));\n#else // MSHR_HASH_TABLES > 0\n\tprint_profiling_reg(GET_REG_ADDR(TRAD_MSHR_CYCLES_MSHR_FULL));\n\tprint_profiling_reg(GET_REG_ADDR(TRAD_MSHR_CYCLES_SE_BUF_FULL));\n#endif // MSHR_HASH_TABLES > 0\n\tprint_profiling_reg(GET_REG_ADDR(MSHR_CYCLES_OUT_SE_BUF_NOT_READY_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_MAX_USED_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_MAX_USED_ROWS_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_MAX_ROWS_WITH_NEXT_PTR_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_CYCLES_IN_FW_STALL_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_CYCLES_RESP_GEN_STALL_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_CYCLES_WRITE_PIPELINE_STALL_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_CYCLES_VALID_NEXT_PTR_STALL_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(RESP_GEN_CYCLES_OUT_NOT_READY_OFFSET));\n\tprint_rob_profiling_reg(GET_REG_ADDR(ROB_MAX_USED_ENTRIES));\n\tprint_rob_profiling_reg(GET_REG_ADDR(ROB_CYCLES_FULL_STALLED));\n\tprint_rob_profiling_reg(GET_REG_ADDR(ROB_CYCLES_REQS_OUT_STALLED));\n\tprint_rob_profiling_reg(GET_REG_ADDR(ROB_CYCLES_RESP_OUT_STALLED));\n\tprint_profiling_reg(GET_REG_ADDR(MSHR_ACCUM_USED_MSHR_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_ACCUM_USED_ENTRIES_OFFSET));\n\tprint_profiling_reg(GET_REG_ADDR(SE_BUF_ACCUM_USED_ROWS_OFFSET));\n#endif // MSHR_PER_HASH_TABLE > 0\t\n\tfflush(stdout);\n#endif\n}\n\nvoid FPGAMSHR_Invalidate_cache() {\n#if FPGAMSHR_EXISTS\n\t*(volatile u32*)FPGAMSHR_BASEADDR = 4;\n#endif\n}\n\nvoid FPGAMSHR_Disable_cache() {\n#if FPGAMSHR_EXISTS\n\t*(volatile u32*)FPGAMSHR_BASEADDR = 16;\n#endif\n}\n\nvoid FPGAMSHR_Enable_cache() {\n#if FPGAMSHR_EXISTS\n\t*(volatile u32*)FPGAMSHR_BASEADDR = 8;\n#endif\n}\n\nvoid FPGAMSHR_SetMaxMSHR(u32 mshr) {\n#if FPGAMSHR_EXISTS\n\t*(volatile u32*)(FPGAMSHR_BASEADDR + 16) = mshr;\n#endif\n}\n\nvoid FPGAMSHR_SetCacheDivider(u32 div) {\n#if FPGAMSHR_EXISTS\n\t*(volatile u32*)(FPGAMSHR_BASEADDR + 8) = div;\n#endif\n}\n\n#endif /* FPGAMSHR_H_ */\n" } ]
14
Jestin1702/Face-Recognition-and-Attendence-Management
https://github.com/Jestin1702/Face-Recognition-and-Attendence-Management
48b447e989ced667c7d63fab1f50f7a475c59920
803918d57d087646e2db54ac08b2a3071a796bd6
7e90e3b69754385c3f55e4746f2e5e7cebbc3470
refs/heads/master
2023-04-25T07:22:33.614645
2021-05-14T13:34:13
2021-05-14T13:34:13
365,737,694
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6105769276618958, "alphanum_fraction": 0.6899038553237915, "avg_line_length": 20.894737243652344, "blob_id": "35a319c54ee7c3bbfb286c715fd4081735c2090c", "content_id": "89d8a2f5685dfdd96d7e67e40f1e3e3760bdcc04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 40, "num_lines": 19, "path": "/define_constants.py", "repo_name": "Jestin1702/Face-Recognition-and-Attendence-Management", "src_encoding": "UTF-8", "text": "PEOPLE_DIR = \"people\"\nCSV_FILE_PATH = \"results/attendence.csv\"\n\ntext_to_speech = True\n\nn_camera = 0\n\nface_recognition_threshold = 0.5\nn_face_encoding_jitters = 50\ndefault_face_box_color = (255,0,0)\nsuccess_face_box_color = (0,255,0)\nunknown_face_box_color = (0,0,255)\ntext_in_frame_color = (0,0,0)\n\nn_min_eye_blink = 2\nn_max_eye_blink = 3\neye_color = (255, 0, 0)\nEAR_ratio_threshold = 0.3\nmin_frames_eyes_closed = 2\n" }, { "alpha_fraction": 0.8045976758003235, "alphanum_fraction": 0.8084291219711304, "avg_line_length": 64.25, "blob_id": "0c8d46c9a0f9079d6e219e66512ebbbe5f67b469", "content_id": "0aabcde1705c8ab98c357eec120640ef44678399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 261, "license_type": "no_license", "max_line_length": 109, "num_lines": 4, "path": "/README.md", "repo_name": "Jestin1702/Face-Recognition-and-Attendence-Management", "src_encoding": "UTF-8", "text": "# Face-Recognition-and-Attendence-Management\nThis project is solely made in python 3. \n Just open the project and install the necessary Dependencies.\n Add images in the peoples folder and run encode.py followed by Attendence.py to run the project sucessfully.\n" }, { "alpha_fraction": 0.5598410367965698, "alphanum_fraction": 0.5729312896728516, "avg_line_length": 38.98130798339844, "blob_id": "fb8a2ac779385ccac3557497c1adc653666e3ae4", "content_id": "e3fb3c2b555ba326010b4a31f28da171bd48254e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4278, "license_type": "no_license", "max_line_length": 118, "num_lines": 107, "path": "/attendence_project.py", "repo_name": "Jestin1702/Face-Recognition-and-Attendence-Management", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport face_recognition as fr\nfrom glob import glob\nimport pickle\nimport utility\nimport random\nimport define_constants as const\n\nprint('-----------------------------------------------------\\n')\n\nwith open('assets/pickles/n_people.pk', 'rb') as pickle_file:\n n_people_in_pickle = pickle.load(pickle_file)\nprint(f\"Number of files that should be in '{const.PEOPLE_DIR}' directory : {n_people_in_pickle}\")\npeople = glob(const.PEOPLE_DIR + '/*.*')\nprint(f\"Number of files in '{const.PEOPLE_DIR}' directory : {len(people)}\")\n\nif n_people_in_pickle == len(people):\n\n names = list(map(utility.get_names, people))\n\n face_encode = np.load('assets/face_encodings/data.npy')\n\n print(\"\\nInitiating camera...\\n\")\n cap = cv2.VideoCapture(const.n_camera)\n\n eye_blink_counter = 0\n eye_blink_total = 0\n random_blink_number = random.randint(const.n_min_eye_blink, const.n_max_eye_blink)\n frame_current_name = None\n\n while cap.isOpened():\n\n ret, frame = cap.read()\n\n frame_face_loc = fr.face_locations(frame)\n frame_face_landmarks = fr.face_landmarks(frame, frame_face_loc)\n frame_face_encode = fr.face_encodings(frame, frame_face_loc)\n\n for index, (loc, encode, landmark) in enumerate(zip(frame_face_loc, frame_face_encode, frame_face_landmarks)):\n\n score = fr.face_distance(face_encode, encode)\n index_match = np.argmin(score)\n\n if np.min(score) < const.face_recognition_threshold:\n\n temp_name = frame_current_name\n frame_current_name = names[index_match]\n else:\n frame_current_name = \"Unknown\"\n\n if not frame_current_name == \"Unknown\":\n\n left_eye_points = np.array(landmark['left_eye'], dtype=np.int32)\n right_eye_points = np.array(landmark['right_eye'], dtype=np.int32)\n\n EAR_avg = (utility.get_EAR_ratio(left_eye_points) + utility.get_EAR_ratio(right_eye_points)) / 2\n\n if EAR_avg < const.EAR_ratio_threshold:\n eye_blink_counter += 1\n else:\n if eye_blink_counter >= const.min_frames_eyes_closed:\n eye_blink_total += 1\n\n eye_blink_counter = 0\n\n if temp_name != frame_current_name:\n eye_blink_total = 0\n random_blink_number = random.randint(const.n_min_eye_blink, const.n_max_eye_blink)\n\n blink_message = f\"Blink {random_blink_number} times, blinks:{eye_blink_total}\"\n\n if utility.check_is_name_recorded(frame_current_name):\n\n attendence_message = \"Next Person\"\n else:\n attendence_message = \" \"\n face_box_color = const.default_face_box_color\n\n if random_blink_number == eye_blink_total:\n\n if np.min(score) < const.face_recognition_threshold:\n utility.record_attendence(frame_current_name)\n face_box_color = const.success_face_box_color\n random_blink_number = random.randint(const.n_min_eye_blink, const.n_max_eye_blink)\n eye_blink_total = 0\n eye_blink_counter = 0\n\n cv2.polylines(frame, [left_eye_points], True, const.eye_color, 1)\n cv2.polylines(frame, [right_eye_points], True, const.eye_color, 1)\n cv2.putText(frame, blink_message, (10, 50), cv2.FONT_HERSHEY_PLAIN, 1.5, const.text_in_frame_color, 2)\n cv2.putText(frame, attendence_message, (20, 450), cv2.FONT_HERSHEY_PLAIN, 1.5,\n const.text_in_frame_color, 2)\n else:\n\n face_box_color = const.unknown_face_box_color\n\n cv2.rectangle(frame, (loc[3], loc[0]), (loc[1], loc[2]), face_box_color, 2)\n cv2.putText(frame, frame_current_name, (loc[3], loc[0] - 3), cv2.FONT_HERSHEY_PLAIN, 1.5,\n const.text_in_frame_color, 2)\n\n cv2.imshow(\"Webcam (Press q to quit)\", frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\nelse:\n print(f\"Run encode_faces.py to encode all faces in '{const.PEOPLE_DIR}' directory...\")\n" } ]
3
agrabowski5/OpenMDAOExamples
https://github.com/agrabowski5/OpenMDAOExamples
aa926bd54e861ba21eaf06860756e309c758a529
555e258ab8a52ee303b30d2faa2ff1d9da3b2249
c8e585a31c0fed308f37c35ce278ef1a207f3bb5
refs/heads/main
2023-02-05T19:07:39.296988
2020-12-20T02:43:07
2020-12-20T02:43:07
322,975,152
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5456035137176514, "alphanum_fraction": 0.5521572828292847, "avg_line_length": 24.042856216430664, "blob_id": "7f7712b5a68dc40de4d3771a2448fe1e52919bf6", "content_id": "c6a2a3d5a480e313ae4a76caf70ea46cce6ebcf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1831, "license_type": "no_license", "max_line_length": 69, "num_lines": 70, "path": "/openMDAOTest.py", "repo_name": "agrabowski5/OpenMDAOExamples", "src_encoding": "UTF-8", "text": "import openmdao.api as om\r\nimport numpy as np\r\n\r\n#assign each variable it's own component\r\n\r\n# Independent Variable\r\nxComp = om.IndepVarComp('x')\r\n\r\n#Implicit Variable created with a component\r\nclass yComp(om.ImplicitComponent):\r\n def setup(self):\r\n self.add_input('x',val = 1)\r\n self.add_input('z',val = 1)\r\n self.add_output('y',val = 1)\r\n def setup_partials(self):\r\n self.declare_partials(of='*',wrt='*')\r\n def apply_nonlinear(self, inputs, outputs, residuals):\r\n x = inputs['x']\r\n z = inputs['z']\r\n y = outputs['y']\r\n residuals['y'] = np.cos(x*y) - z*y\r\n\r\n#Explicit Variable created with a component\r\nclass zComp(om.ExplicitComponent):\r\n def setup(self):\r\n self.add_input('y')\r\n self.add_output('z')\r\n\r\n def setup_partials(self):\r\n self.declare_partials('*', '*')\r\n\r\n def compute(self, inputs, outputs):\r\n y = inputs['y']\r\n outputs['z'] = np.sin(y)\r\n\r\nif __name__ == '__main__':\r\n \r\n model = om.Group()\r\n model.add_subsystem('z', zComp())\r\n model.add_subsystem('y', yComp())\r\n model.add_subsystem('x', xComp)\r\n model.connect('y.y','z.y')\r\n model.connect('z.z','y.z')\r\n\r\n \r\n #model.linear_solver = om.DirectSolver()\r\n\r\n model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True)\r\n model.nonlinear_solver.options['maxiter'] = 100\r\n model.nonlinear_solver.options['iprint'] = 2\r\n\r\n prob = om.Problem(model)\r\n prob.setup()\r\n\r\n prob.run_model()\r\n\r\n x = prob['y.x']\r\n y = prob['y.y']\r\n z = prob['y.z']\r\n\r\n print(\"X Value:\", x)\r\n print(\"Y Value:\", y)\r\n print(\"Z Value:\", z)\r\n\r\n myAns = np.cos(x*y) -z*y \r\n\r\n if (prob['y.z'] == np.sin(prob['y.y'])) & (abs(myAns) <= .00001):\r\n print('Passed') \r\n else:\r\n print('Not Passed')\r\n \r\n\r\n" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.5, "avg_line_length": 14, "blob_id": "4c8a5b5eeccf64c2866400ec058985ec6c205cde", "content_id": "0d8e67cf82591a9cc79a0df53f4017801790a7c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38, "license_type": "no_license", "max_line_length": 19, "num_lines": 2, "path": "/myFirstClass.py", "repo_name": "agrabowski5/OpenMDAOExamples", "src_encoding": "UTF-8", "text": "class myFirstClass:\r\n x = 5\r\n\r\n " }, { "alpha_fraction": 0.6491228342056274, "alphanum_fraction": 0.6491228342056274, "avg_line_length": 30.571428298950195, "blob_id": "bea8c1be084ac7dd657e03882b6224f2ffe0a6f6", "content_id": "7fc0b1d3e302bb322b8b4163a41ac3d4a260ad86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 228, "license_type": "no_license", "max_line_length": 83, "num_lines": 7, "path": "/stockProfile.py", "repo_name": "agrabowski5/OpenMDAOExamples", "src_encoding": "UTF-8", "text": "class stockProfile:\r\n\r\n def __init__(self, ticker):\r\n self.ticker = ticker\r\n \r\n #def grabTickerInformation(self, ticker):\r\n # This is where we should grab data from the internet to populate stock profile\r\n" }, { "alpha_fraction": 0.8041236996650696, "alphanum_fraction": 0.8041236996650696, "avg_line_length": 22.75, "blob_id": "6c3c792b5d92c2c4b43b5720cdb90cfcca59efb7", "content_id": "6dea3da9d72bb2a0572401aff0ac3fa737661abb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 97, "license_type": "no_license", "max_line_length": 41, "num_lines": 4, "path": "/main.py", "repo_name": "agrabowski5/OpenMDAOExamples", "src_encoding": "UTF-8", "text": "clclfrom stockProfile import stockProfile\r\n\r\nmyStock = stockProfile(\"SPY\")\r\nprint(myStock.ticker)" }, { "alpha_fraction": 0.6495327353477478, "alphanum_fraction": 0.6693925261497498, "avg_line_length": 21.189189910888672, "blob_id": "57ace0990150b4a80b5a0bc9aabb0481f0895d95", "content_id": "950048e42d56c7e66a3b10e62f14c93c17c7d22e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 856, "license_type": "no_license", "max_line_length": 89, "num_lines": 37, "path": "/testopenMDAO.py", "repo_name": "agrabowski5/OpenMDAOExamples", "src_encoding": "UTF-8", "text": "import openmdao.api as om\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\n# build the model \r\nprob = om.Problem() \r\n\r\nprob.model.add_subsystem('paraboloid', om.ExecComp('f = (x-3)**2 + x*y + (y+4)**2 - 3')) \r\n\r\n# plot the equation\r\n\r\n\r\n\r\n# setup the optimization \r\nprob.driver = om.ScipyOptimizeDriver() \r\nprob.driver.options['optimizer'] = 'SLSQP' \r\n\r\nprob.model.add_design_var('paraboloid.x', lower=-50, upper=50) \r\nprob.model.add_design_var('paraboloid.y', lower=-50, upper=50) \r\nprob.model.add_objective('paraboloid.f') \r\n\r\nprob.setup() \r\n\r\n# set initial values \r\nprob.set_val('paraboloid.x', 3.0) \r\nprob.set_val('paraboloid.y', -4.0)\r\n\r\n# run the optimization\r\nprob.run_driver() \r\n\r\n# minimum value \r\nprint(prob.get_val('paraboloid.f'))\r\n\r\n# location of the minimum \r\nprint(prob.get_val('paraboloid.x')) \r\nprint(prob.get_val('paraboloid.y'))" }, { "alpha_fraction": 0.6350148320198059, "alphanum_fraction": 0.6617210507392883, "avg_line_length": 15.736842155456543, "blob_id": "f443a486f3c03663a2e57e5f384ee213b82120b1", "content_id": "95170a2011abac9123516269c4746c6b485f67e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 337, "license_type": "no_license", "max_line_length": 38, "num_lines": 19, "path": "/3dPlot.py", "repo_name": "agrabowski5/OpenMDAOExamples", "src_encoding": "UTF-8", "text": "#%matplotlib inline\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfig = plt.figure()\r\nax = plt.axes(projection='3d')\r\n\r\nzline = np.linspace(0, 15, 1000)\r\nxline = np.sin(zline)\r\nyline = np.cos(zline)\r\n\r\nmyMean = xline.mean()\r\nax.plot3D(xline, yline, zline, 'gray')\r\n\r\nax.set_title('MyFirstTitle')\r\n\r\n\r\nplt.show()\r\nplt.legend()\r\n" } ]
6
murilospina/Siraj-Challenge
https://github.com/murilospina/Siraj-Challenge
a4e139981630226e84ced9265989083baa47cfea
857ebf258a7bf6767cc695da54b7be311430e133
d4cbf2688ee633dfc7a63e3e2db59d318a91fd32
refs/heads/master
2020-04-15T03:05:02.134145
2019-01-06T23:37:09
2019-01-06T23:37:09
164,335,453
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7062991857528687, "alphanum_fraction": 0.7196850180625916, "avg_line_length": 27.534883499145508, "blob_id": "7d590c731577e2864192ec2972080ee88afa523a", "content_id": "7a5d021c91ca2f53be750f08fdaacd94f9db56d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1274, "license_type": "no_license", "max_line_length": 112, "num_lines": 43, "path": "/Siraj-2.py", "repo_name": "murilospina/Siraj-Challenge", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 6 18:29:39 2019\r\n\r\n@author: Murilo S. Spina\r\n\"\"\"\r\n\r\nfrom textblob import TextBlob as tb #modulo para tokenizar palavras\r\nimport tweepy #API do twitter\r\nimport numpy as np\r\n\r\n\r\n#regstro dos tokens para login na API(twitter)\r\nconsumer_key = 'pGmGmb7zsXRJvi6P5Qcr7i0fm'\r\nconsumer_secret = '4XPDR8ztLURs1BDgCRb3GVMIWFfrRfrUhQKt2q6AYXdoSw7t6R'\r\n\r\naccess_token = '66722263-fdBbcy0COuLWF7hFnrj9fzip1b8THeV3uMNFGXuwg'\r\naccess_token_secret = 'jJTnXQbCEbppmNHJcuAIFXikf5VnF2RQ18azREyDsNdye'\r\n\r\n#Acessao à API(twitter)\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\n\r\n#chamando API\r\napi = tweepy.API(auth)\r\n\r\n#procura por tweets\r\npublic_tweets = api.search('NFL')\r\n\r\n#registrando a variável com \"none\" para usar posteriormente\r\nanalysis = None \r\n\r\n#Loop para cada tweet e sentimento identificado\r\ntweets = []\r\nfor tweet in public_tweets:\r\n print(tweet.text) #imprime o texto dos tweets\r\n analysis = tb(tweet.text)#analisa o sentimento do tweet\r\n print(analysis.sentiment)#imprime o sentimento identificado e o subject(o quanto de opinião existe no tweet)\r\n polarity = analysis.sentiment.polarity\r\n tweets.append(polarity)#acumula a polaridade(sentimentos) dos tweets\r\n \r\n#Imprime a média de sentimento dos tweets analisados\r\nprint('SENTIMENT AVERAGE: ' + str(np.mean(tweets)))\r\n" }, { "alpha_fraction": 0.6645541191101074, "alphanum_fraction": 0.705296516418457, "avg_line_length": 34.11475372314453, "blob_id": "0f6a7d85f50726a8d2d07d2b8ab10de727d6c5c2", "content_id": "1462d1af9e78dfe806bba35ec5cecfb2a39f2c95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2224, "license_type": "no_license", "max_line_length": 82, "num_lines": 61, "path": "/Siraj-1.py", "repo_name": "murilospina/Siraj-Challenge", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Murilo Spina\r\n\"\"\"\r\n\r\nfrom sklearn import tree\r\n#from sklearn import svm\r\nfrom sklearn.linear_model import Perceptron\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.naive_bayes import GaussianNB\r\nimport numpy as np\r\n\r\nX = [[181,80,44], [177,70,43], [160,60,38], [154,54,37],\r\n [166,65,40], [190,90,47], [175,64,39], [177,70,40],\r\n [159,55,37], [171,75,42], [181,85,43]]\r\nY = ['male', 'female', 'female', 'female', 'male', 'male', \r\n 'male', 'female', 'male', 'female', 'male']\r\n\r\n#classificadores\r\nclassificador_tree = tree.DecisionTreeClassifier()\r\nclassificador_KNN = KNeighborsClassifier()\r\nclassificador_perc = Perceptron()\r\nclassificador_gau = GaussianNB()\r\n\r\n#Treinando classificadores\r\nclassificador_tree = classificador_tree.fit(X,Y)\r\nclassificador_KNN = classificador_KNN.fit(X, Y)\r\nclassificador_perc = classificador_perc.fit(X, Y)\r\nclassificador_gau = classificador_gau.fit(X,Y)\r\n\r\n#teste Arvore de decisão\r\nprediction_tree = classificador_tree.predict(X)\r\naccuracy_tree = accuracy_score(Y, prediction_tree) * 100\r\n\r\n#teste KNN\r\nprediction_KNN = classificador_KNN.predict(X)\r\naccuracy_KNN = accuracy_score(Y, prediction_KNN) * 100\r\n\r\n#Teste Perceptron\r\nprediction_perc = classificador_perc.predict(X)\r\naccuracy_perc = accuracy_score(Y, prediction_perc) * 100\r\n\r\n#Teste Gaussian\r\nprediction_gau = classificador_gau.predict(X)\r\naccuracy_gau = accuracy_score(Y, prediction_perc) * 100\r\n\r\nif accuracy_tree > accuracy_KNN:\r\n print('Método Árvore de Decisão é mais preciso com {}%'.format(accuracy_tree))\r\nelif accuracy_KNN > accuracy_perc:\r\n print('Método KNN é mais preciso com {}%'.format(accuracy_KNN))\r\nelif accuracy_perc > accuracy_gau:\r\n print('Método Perceptron é mais preciso com {}%'.format(accuracy_perc))\r\nelif accuracy_gau > accuracy_tree:\r\n print('Método GaussianNB é mais preciso com {}%'.format(accuracy_gau))\r\n \r\n\r\nprint('Precisão para DecisionTree: {}%'.format(accuracy_tree))\r\nprint('Precisão para KNN: {}%'.format(accuracy_KNN))\r\nprint('Precisão para Perceptron: {}%'.format(accuracy_perc))\r\nprint('Precisão para GaussianNB: {}%'.format(accuracy_gau))\r\n\r\n\r\n\r\n" } ]
2
Lshoemake/CSC346Project2
https://github.com/Lshoemake/CSC346Project2
caa05da3afd1208e988302d25362f951930effd6
b6321c9af8edb23d38552f7c95ba25aad829741c
2c7b23605e07b8efce894ec71d641524b86a3f8a
refs/heads/master
2020-04-29T05:39:43.317662
2019-04-29T21:49:14
2019-04-29T21:49:14
175,890,424
0
1
null
2019-03-15T20:59:51
2019-03-21T18:55:09
2019-03-21T21:23:57
HTML
[ { "alpha_fraction": 0.6549561023712158, "alphanum_fraction": 0.6549561023712158, "avg_line_length": 43.27777862548828, "blob_id": "a39b4795d9f1eca83b91a6a799d8730db47e5d48", "content_id": "7063dc86fba2966203cd1295cce7307505b371ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 797, "license_type": "no_license", "max_line_length": 67, "num_lines": 18, "path": "/corgi_store/urls.py", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "from django.urls import include, path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('corgi/<int:corgi_id>/', views.detail, name='detail'),\n path('corgi/all/', views.browse_corgis, name='browse_corgis'),\n path('corgi/buy/', views.buy_corgi, name='buy_corgi'),\n path('list_corgi/', views.list_corgi, name='list_corgi'),\n path('sign_up/', views.sign_up, name='sign_up'),\n path('favorite/', views.favorite_corgi, name='favorite'),\n path('user_profile/', views.user_profile, name='user_profile'),\n path('user_profile/close', views.close, name='close'),\n path('corgi/all/filter', views.all_filter, name='all_filter'),\n path('corgi/buy/filter', views.buy_filter, name='buy_filter'),\n path('webhook/', views.webhook, name='webhook')\n]\n" }, { "alpha_fraction": 0.5889967679977417, "alphanum_fraction": 0.6213592290878296, "avg_line_length": 37.625, "blob_id": "f153c358e1347a0b519162b82c86794706765ae1", "content_id": "11332a7eca99946979fb82d280b8ef647beb3f5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 309, "license_type": "no_license", "max_line_length": 112, "num_lines": 8, "path": "/sql/buy_filter.sql", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "select * from (corgi_store_listing join corgi_store_corgi on corgi_store_listing.corgi_id=corgi_store_corgi.id) \n where corgi_store_listing.open=1 and\n gender='M' and\n coloring='Red-Headed Tricolor' and\n state ='AZ' and\n age < 3\n price >= 1000 and\n price <= 2000;\n" }, { "alpha_fraction": 0.6136363744735718, "alphanum_fraction": 0.6212121248245239, "avg_line_length": 25.200000762939453, "blob_id": "c3e85e0f3dc7a5a40005b01c9404c0787edfeefd", "content_id": "849edf92ec5b2caaa2a523d97b0f147b52ba2554", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 132, "license_type": "no_license", "max_line_length": 38, "num_lines": 5, "path": "/sql/browse_corgis.sql", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "select * from corgi_store_corgi where \n gender='M' and \n coloring='Red-Headed Tricolor' and\n state ='AZ' and\n age < 3;\n\n" }, { "alpha_fraction": 0.6112484335899353, "alphanum_fraction": 0.6126390695571899, "avg_line_length": 28.153152465820312, "blob_id": "18b329d8279d0a538bf6c86d91dee18260d9cda0", "content_id": "53b1d41689a279ad1e00499be71b9b5261ac5853", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6472, "license_type": "no_license", "max_line_length": 183, "num_lines": 222, "path": "/corgi_store/views.py", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.db import IntegrityError\nfrom .models import *\nimport git, os, subprocess, json\n\n# Create your views here.\ndef home(request):\n return render(request, 'home.html')\n\n# change to be just users listings\ndef user_profile(request):\n\treturn render(request, 'user_profile.html', {'listings': Listing.objects.filter(user__id=request.user.id, open=True), 'favorites': Favorite.objects.filter(user__id=request.user.id)})\n\ndef detail(request, corgi_id):\n return render(request, 'browse.html', {'corgis': [Corgi.objects.get(id=corgi_id)]})\n\ndef browse_corgis(request):\n favorites = [fav.corgi.id for fav in Favorite.objects.filter(user=request.user)] if request.user.is_authenticated else []\n return render(request, 'browse.html', {\n 'corgis': Corgi.objects.all(),\n 'user': request.user,\n 'favorites': favorites\n })\n\ndef buy_corgi(request):\n return render(request, 'buy.html', {'listings': Listing.objects.filter(open=True)})\n\ndef list_corgi(request):\n if request.method == \"POST\":\n user = request.user\n params = request.POST\n corgi = Corgi.objects.create(\n name=params['name'],\n age_years=params['age_years'],\n age_months=params['age_months'],\n gender=params['gender'],\n coloring=params['coloring'],\n city=params['city'],\n state=params['state'],\n description=params['description']\n )\n # TODO: I can do this once 'listradio' is fixed\n # corgi = Corgi.objects.create(**params, owner=user)\n if int(params['price']):\n listing = Listing.objects.create(\n user=user,\n corgi=corgi,\n price=params['price'],\n contact=params['contact']\n )\n return redirect('browse_corgis')\n\n if request.user.is_authenticated:\n \treturn render(request, 'list_corgi.html')\n else:\n \tform = AuthenticationForm()\n \treturn render(request, 'registration/login.html', {'modal_message': 'Please login to list a corgi','form':form})\n\ndef sign_up(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n username = form.cleaned_data.get('email')\n try:\n form.save()\n except IntegrityError:\n return render(request, 'sign_up.html', {'form': form, 'integrity_error': 'Email {} already in use.'.format(username)})\n raw_password = form.cleaned_data.get('password1')\n user = authenticate(username=username, password=raw_password)\n user.username = username\n user.save()\n login(request, user)\n return redirect('home')\n else:\n form = SignUpForm()\n return render(request, 'sign_up.html', {'form': form})\n\ndef favorite_corgi(request):\n if request.method == 'POST':\n corgi = Corgi.objects.get(id=request.POST.get('corgi'))\n fav = Favorite.objects.filter(user=request.user, corgi=corgi)\n if not fav:\n Favorite.objects.create(user=request.user, corgi=corgi)\n else:\n fav[0].delete()\n return redirect('browse_corgis')\n\ndef close(request):\n if request.method == \"POST\":\n params = request.POST\n id = params['corgi_id']\n corgi = Listing.objects.get(corgi__id=id)\n corgi.open = False\n corgi.save()\n return redirect('user_profile')\n\ndef all_filter(request):\n\tif request.method == 'POST':\n\t\tparams = request.POST\n\t\tgender = params['filter-gender']\n\t\tcoloring = params['filter-coloring']\n\t\tstate = params['filter-state']\n\t\trelation = params['filter-age']\n\t\tage = params['filter-year']\n\n\t\twhere_flag = False;\n\n\t\tquery = \"select * from corgi_store_corgi\"\n\t\tif(gender != \"Any gender\"):\n\t\t\tquery+= \" where gender ='\"\n\t\t\tquery+= gender\n\t\t\tquery+=\"'\"\n\t\t\twhere_flag=True\n\n\t\tif(coloring != \"Any coloring\"):\n\t\t\tif(where_flag):\n\t\t\t\tquery+=\" and \"\n\t\t\telse:\n\t\t\t\tquery+=\" where \"\n\t\t\t\twhere_flag=True\n\t\t\tquery+=\"coloring='\"\n\t\t\tquery+=coloring\n\t\t\tquery+=\"'\"\n\n\t\tif(state != \"Any state\"):\n\t\t\tif(where_flag):\n\t\t\t\tquery+=\" and \"\n\t\t\telse:\n\t\t\t\tquery+=\" where \"\n\t\t\t\twhere_flag = True\n\t\t\tquery+=\"state='\"\n\t\t\tquery+=state\n\t\t\tquery+=\"'\"\n\n\t\tif(relation == \"Greater than\"):\n\t\t\tif(where_flag):\n\t\t\t\tquery+=\" and \"\n\t\t\telse:\n\t\t\t\tquery+=\" where \"\n\t\t\t\twhere_flag = True\n\t\t\tquery+=\"age_years >='\"\n\n\t\telif(relation == \"Less than\"):\n\t\t\tif(where_flag):\n\t\t\t\tquery+=\" and \"\n\t\t\telse:\n\t\t\t\tquery+=\" where \"\n\t\t\t\twhere_flag = True\n\t\t\tquery+=\"age_years <'\"\n\n\t\telse:\n\t\t\tif(where_flag):\n\t\t\t\tquery+=\" and \"\n\t\t\telse:\n\t\t\t\tquery+=\" where \"\n\t\t\t\twhere_flag = True\n\t\t\tquery+=\"age_years ='\"\n\n\t\tquery+=age\n\t\tquery+=\"'\"\n\n\t\treturn render(request, 'browse.html', {'corgis': Corgi.objects.raw(query)})\n\ndef buy_filter(request):\n\tif request.method == 'POST':\n\t\tparams = request.POST\n\t\tgender = params['filter-gender']\n\t\tcoloring = params['filter-coloring']\n\t\tstate = params['filter-state']\n\t\trelation = params['filter-age']\n\t\tage = params['filter-year']\n\t\tlowPrice = params['filter-low-price']\n\t\thighPrice = params['filter-high-price']\n\n\t\tquery = \"select * from (corgi_store_listing join corgi_store_corgi on corgi_store_listing.corgi_id=corgi_store_corgi.id) where open=1\"\n\t\tif(gender != \"Any gender\"):\n\t\t\tquery+= \" and gender ='\"\n\t\t\tquery+= gender\n\t\t\tquery+=\"'\"\n\t\t\twhere_flag=True\n\n\t\tif(coloring != \"Any coloring\"):\n\t\t\tquery+=\" and coloring='\"\n\t\t\tquery+=coloring\n\t\t\tquery+=\"'\"\n\n\t\tif(state != \"Any state\"):\n\t\t\tquery+=\" and state='\"\n\t\t\tquery+=state\n\t\t\tquery+=\"'\"\n\n\t\tif(relation == \"Greater than\"):\n\t\t\tquery+=\" and age_years >='\"\n\n\t\telif(relation == \"Less than\"):\n\t\t\tquery+=\" and age_years <'\"\n\n\t\telse:\n\t\t\tquery+=\" and age_years ='\"\n\n\t\tquery+=age\n\t\tquery+=\"'\"\n\n\t\tquery+=\" and price >= '\"\n\t\tquery+= lowPrice\n\t\tquery+=\"' and price <='\"\n\t\tquery+= highPrice\n\t\tquery+= \"'\"\n\n\t\treturn render(request, 'buy.html', {'listings': Listing.objects.raw(query)})\n\ndef webhook(request):\n repo = git.Repo(\"/root/CSC346Project2\")\n payload = json.loads(request.POST['payload'])\n if request.method == 'POST' and 'ref' in payload.keys():\n if payload['ref'] == \"refs/heads/{}\".format(repo.active_branch.name):\n repo.git.pull()\n return HttpResponse(\"Success\")\n" }, { "alpha_fraction": 0.8017241358757019, "alphanum_fraction": 0.8017241358757019, "avg_line_length": 22.200000762939453, "blob_id": "a256b4c4b7907d6ef38264e5c4308724ff8f51a1", "content_id": "5c2441102829397d83d0d5a8c5d497466d82affb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/corgi_store/admin.py", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Corgi\n\n# Register your models here.\nadmin.site.register(Corgi)\n" }, { "alpha_fraction": 0.6183986663818359, "alphanum_fraction": 0.6490630507469177, "avg_line_length": 40.92856979370117, "blob_id": "9f5360d60d9db01f47ee2e121a6ad30c6f572fd8", "content_id": "6e3e71805aabbe85069cc167de7eb143adefcfab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1174, "license_type": "no_license", "max_line_length": 119, "num_lines": 28, "path": "/sql/insert_data.sql", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "use csc346;\n\ninsert into users (first_name, last_name, email, pw_hash)\n values('Morgan', 'Henry', '[email protected]', '1234');\n\ninsert into users (first_name, last_name, email, pw_hash)\n values('Laura', 'Shoemake', '[email protected]', '1234');\n\ninsert into users (first_name, last_name, email, pw_hash)\n values('Calvin', 'McLean', '[email protected]', '1234');\n\ninsert into users (first_name, last_name, email, pw_hash)\n values('Lindsy', 'Henry', '[email protected]', '1234');\n\n\ninsert into dog(name, gender, age, color, city, state, description)\n values ('Sammi', 'Female', 15, 'red', 'Chico' , 'CA', 'loving dog who hates to cuddle');\n\ninsert into dog(name, gender, age, color, city, state, description)\n values ('Fluffy', 'Male', 1, 'Stable', 'Phoenix' , 'AZ', 'Shy pupper, but loves to play when he gets to know you');\n\ninsert into listing (owner_id, dog_id, price, contact)\n values((select id from users where first_name=\"Morgan\"),\n (select id from dog where name=\"Sammi\"), 1200, 'email: [email protected], phone: 555-555-5555');\n\ninsert into favorite (user_id, dog_id)\n values ((select id from users where first_name='Calvin'),\n (select id from dog where name='Fluffy'));\n" }, { "alpha_fraction": 0.7730496525764465, "alphanum_fraction": 0.8014184236526489, "avg_line_length": 27.200000762939453, "blob_id": "c762eba981749ce3425e1a1b7b0175ca9f5f6f7e", "content_id": "695a9783a47b594f4207dbeb7837d792a0bca277", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 141, "license_type": "no_license", "max_line_length": 67, "num_lines": 5, "path": "/Dockerfile", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "FROM python\nRUN pip install django mysqlclient social-auth-app-django gitpython\nEXPOSE 8000\nWORKDIR /root\nENTRYPOINT [\"python\", \"manage.py\"]\n" }, { "alpha_fraction": 0.5601093173027039, "alphanum_fraction": 0.6120218634605408, "avg_line_length": 16.428571701049805, "blob_id": "852310a20dae324a398978366ebf5cc217db5e15", "content_id": "891d80f874571282d295278232d13e1936727b44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 732, "license_type": "no_license", "max_line_length": 38, "num_lines": 42, "path": "/sql/create_tables.sql", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "use csc346;\n\ncreate table users\n(\n id int(6) NOT NULL AUTO_INCREMENT,\n first_name varchar(64),\n last_name varchar(64),\n email varchar(128),\n pw_hash varchar(255),\n PRIMARY KEY (id)\n);\n\ncreate table dog\n(\n id int(6) NOT NULL AUTO_INCREMENT,\n owner_id int(6),\n name varchar(64),\n gender varchar(12),\n age int(6),\n color varchar(64),\n city varchar(64),\n state varchar(64),\n description varchar(255),\n PRIMARY KEY (id)\n);\n\ncreate table listing\n(\n owner_id int(6) NOT NULL,\n dog_id int(6) NOT NULL,\n price int(6),\n contact varchar(255),\n PRIMARY KEY (owner_id, dog_id)\n\n);\n\ncreate table favorite\n(\n user_id int(6),\n dog_id int(6),\n PRIMARY KEY (user_id, dog_id)\n);\n" }, { "alpha_fraction": 0.6921299695968628, "alphanum_fraction": 0.7015247344970703, "avg_line_length": 62.656864166259766, "blob_id": "7d2fa9cb7758a7b813601a73ff3608361d921dab", "content_id": "18a802e72776ce570dc0805571bc964f29dd0c4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6493, "license_type": "no_license", "max_line_length": 478, "num_lines": 102, "path": "/django.md", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "# Django\n\n\nDjango is a Python framework designed for creating web applications from front to back. It is free and open source.\nIt takes care of most of the annoying and complicated parts of a website such as database design and management, handling HTTP requests, and rendering HTML pages with information from the back-end.\n\nThe Django Project provides a great tutorial: https://docs.djangoproject.com/en/2.1/intro/\n\nA Django application consists of four main parts:\n 1. Models\n - These are like objects and directly correspond to database tables\n - Django manages the database through automatically generated 'migrations'. This allows the developer to use it with any database technology (MySQL, PostgreSQL, SQLite) by simply changing the settings and running migrations\n - Django provides built-in methods for dealing with models such as:\n ```python\n Corgi.objects.create(**kwargs) # Create a Corgi using keyword args for its attributes\n Corgi.objects.all() # Get all Corgi objects from the database\n Listing.objects.raw('SELECT * FROM corgi_store_corgi WHERE age_years > 3') # Get all corgis older than 3\n ```\n - By extending Django's built-in Model object, these three lines can be used to enable creation, deletion, and searching Favorites ([link](https://github.com/Lshoemake/CSC346Project2/blob/master/corgi_store/models.py#L59-L61)):\n ```python\n class Favorite(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n corgi = models.ForeignKey(Corgi, on_delete=models.CASCADE)\n ```\n - Django also provides built-in user sign-up, authentication, and sessions as well as an Admin dashboard for managing users and database entries\n\n 2. URLs\n - By simply providing a list of 'paths', a developer can easily manage all of the valid paths on the website and connect the paths of views which will render a template\n - The following URLs provide paths for the homepage, a page for viewing all corgis, and a page for buying corgis ([link](https://github.com/Lshoemake/CSC346Project2/blob/master/corgi_store/urls.py#L5-L17)):\n ```python\n urlpatterns = [\n path('', views.home, name='home'),\n path('corgi/all/', views.browse_corgis, name='browse_corgis'),\n path('corgi/buy/', views.buy_corgi, name='buy_corgi'),\n ]\n ```\n\n 3. Views\n - Views are just methods that are run when a user visits the URL that points to that view\n - A view can perform some operations and must return a HttpResponse object by either rendering an HTML template or redirecting to a different URL\n - For example, the `corgi/buy/` URL above calls this view which renders the `buy.html` template with all corgis that are for sale ([link](https://github.com/Lshoemake/CSC346Project2/blob/master/corgi_store/views.py#L28-L29)):\n ```python\n def buy_corgi(request):\n return render(request, 'buy.html', {'listings': Listing.objects.filter(open=True)})\n ```\n\n 4. Templates\n - Templates are used by the `render` function in views. They are HTML pages that contain some Jinja2 syntax for templating with variables from Django\n - The following excerpt of `buy.html` shows templating variables into an HTML page showing corgi information ([link](https://github.com/Lshoemake/CSC346Project2/blob/master/corgi_store/templates/buy.html#L132-L134)):\n ```html\n <b>Name: </b>{{ listing.corgi.name }}<br>\n <b>Gender: </b>{{ listing.corgi.gender }} <br>\n <b>Age: </b>{{ listing.corgi.age_years }} years, {{ listing.corgi.age_months }} months <br>\n ```\n - Templates can also implement control structures such as loops and if-else statements\n\n\nBasically, when a user visits a URL, Django compares that URL to the paths in `urls.py` which can include regex. Once a match is found, Django uses the view specified by the URL to perform an action such as creating or favoriting a corgi. The view then returns an HttpResponse object by using `render()` with a template and some variables to populate the template with (called 'context') or by redirecting to a different URL using `redirect()` and the new URL's name (not path).\n\n\nSimple example:\n - User clicks 'Buy a Corgi' in menu bar which contains `href=\"{% url 'buy_corgi' %}\"`\n - Django finds the 'buy_corgi' URL from `urls.py` and calls `buy_corgi()` view:\n ```python\n def buy_corgi(request):\n return render(request, 'buy.html', {'listings': Listing.objects.filter(open=True)})\n ```\n - This view simply returns the HttpResponse object created by rendering the `buy.html` template with all open listings\n\n\nFor a slightly more complicated example, consider favoriting a corgi (demonstrate this in browser):\n - When a logged-in user clicks the empty heart by a corgi on the browse page, the following Javascript is run ([link](https://github.com/Lshoemake/CSC346Project2/blob/master/corgi_store/templates/browse.html#L141-L153)):\n ```javascript\n function favorite(id)\n {\n \tvar heart = document.getElementById(\"favorite\"+id);\n \theart.innerHTML = '<span class=\"glyphicon glyphicon-heart\" style=\"color:red;\" onclick=\"unfavorite('+id+')\"></span>'\n console.log(\"ajax\");\n $.post({\n url: '/favorite/',\n data: {\n corgi: id\n },\n dataType: 'json',\n });\n }\n ```\n - This will send a POST request to `/favorite/` with JSON data containing the corgi's ID\n - The `/favorite` URL will call the `favorite_corgi` view ([link](https://github.com/Lshoemake/CSC346Project2/blob/master/corgi_store/views.py#L81-L89)):\n ```python\n def favorite_corgi(request):\n if request.method == 'POST':\n corgi = Corgi.objects.get(id=request.POST.get('corgi'))\n fav = Favorite.objects.filter(user=request.user, corgi=corgi)\n if not fav:\n Favorite.objects.create(user=request.user, corgi=corgi)\n else:\n fav[0].delete()\n return redirect('browse_corgis')\n ```\n - If this view receives a POST request, it will load the corgi object specified by the ID, then determine if the corgi is already favorited. If not, then it will create the Favorite object in the table. Otherwise, it will delete the existing favorite object.\n - It always returns `redirect('browse_corgis')` to re-render the browse page since we do not want the user to be redirected to the `/favorite/` URL which is just an API end point\n" }, { "alpha_fraction": 0.5363636612892151, "alphanum_fraction": 0.5763636231422424, "avg_line_length": 29.55555534362793, "blob_id": "8ee6b4fe5a56591435548c577ad6df47666c057c", "content_id": "28009a772774d521708c9290903d2a6e6a750c9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 220, "num_lines": 18, "path": "/corgi_store/migrations/0002_auto_20190328_2117.py", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-28 21:17\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('corgi_store', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='corgi',\n name='coloring',\n field=models.CharField(choices=[('red', 'Red'), ('rh-tc', 'Red-Headed Tricolor'), ('bh-tc', 'Black-Headed Tricolor'), ('sable', 'Sable'), ('fawn', 'Fawn'), ('other', 'Other')], default='red', max_length=120),\n ),\n ]\n" }, { "alpha_fraction": 0.7582417726516724, "alphanum_fraction": 0.791208803653717, "avg_line_length": 17.200000762939453, "blob_id": "e83c2bc5807e80924042f7ac3a5403d51ffd4fcc", "content_id": "3c3bcc17305db1f169a63a0f959a075593c3d2b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 91, "license_type": "no_license", "max_line_length": 21, "num_lines": 5, "path": "/sql/delete_data.sql", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "use csc346;\nDELETE FROM dog;\nDELETE FROM users;\nDELETE FROM favorite;\nDELETE FROM listing;\n" }, { "alpha_fraction": 0.4956521689891815, "alphanum_fraction": 0.5673912763595581, "avg_line_length": 24.55555534362793, "blob_id": "021f62827f2bf73f72bc0fbde51b25f402fe0b52", "content_id": "e6d40c9b4f4e64a39318034d752e5ff69537b8a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "no_license", "max_line_length": 121, "num_lines": 18, "path": "/corgi_store/migrations/0003_auto_20190328_2201.py", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-28 22:01\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('corgi_store', '0002_auto_20190328_2117'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='corgi',\n name='gender',\n field=models.CharField(choices=[('M', 'Male'), ('F', 'Female'), ('X', 'Other')], default='X', max_length=10),\n ),\n ]\n" }, { "alpha_fraction": 0.6378887295722961, "alphanum_fraction": 0.649754524230957, "avg_line_length": 39.065574645996094, "blob_id": "7e03c87d280396da8601e3732797fcb7742d4156", "content_id": "9189f59198b234d6b2820161e3b2727855428447", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2444, "license_type": "no_license", "max_line_length": 128, "num_lines": 61, "path": "/corgi_store/models.py", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django import forms\nfrom django.contrib.auth.forms import UserCreationForm\n\nclass SignUpForm(UserCreationForm):\n first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')\n last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')\n email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')\n\n def save(self, commit=True):\n user = super(SignUpForm, self).save(commit=False)\n user.set_password(self.cleaned_data[\"password1\"])\n user.username = user.email\n if commit:\n user.save()\n return user\n\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'email', 'password1', 'password2', )\n\nclass CorgiManager(models.Manager):\n def create_corgi(self, name, **kwargs):\n return self.create(name, **kwargs)\n\nclass Corgi(models.Model):\n COLOR_CHOICES = [\n ('red', 'Red'),\n ('rh-tc', 'Red-Headed Tricolor'),\n ('bh-tc', 'Black-Headed Tricolor'),\n ('sable', 'Sable'),\n ('fawn', 'Fawn'),\n ('other', 'Other')\n ]\n name = models.CharField(max_length=120)\n age_years = models.IntegerField(default=0)\n age_months = models.IntegerField(default=0)\n gender = models.CharField(max_length=10, choices=[('M', 'Male'), ('F', 'Female'), ('X', 'Other')], default='X')\n coloring = models.CharField(max_length=120, choices=COLOR_CHOICES, default='red')\n city = models.CharField(max_length=120)\n state = models.CharField(max_length=120)\n description = models.CharField(max_length=300)\n objects = CorgiManager()\n\n def __str__(self):\n return \"This is {}, a {} year, {} month old {} Corgi.\".format(self.name, self.age_years, self.age_months, self.coloring)\n\n def __repr__(self):\n return \"<Corgi: {}>\".format(' '.join([\"{}='{}'\".format(k,v) for k,v in vars(self).items() if k != '_state']))\n\nclass Listing(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n corgi = models.ForeignKey(Corgi, on_delete=models.CASCADE)\n price = models.IntegerField()\n contact = models.CharField(max_length=300)\n open = models.BooleanField(default=True)\n\nclass Favorite(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n corgi = models.ForeignKey(Corgi, on_delete=models.CASCADE)\n" }, { "alpha_fraction": 0.7595610022544861, "alphanum_fraction": 0.7838377356529236, "avg_line_length": 42.5797119140625, "blob_id": "a8f40f51efd44a0bdbceb95b52dcd316c49e0479", "content_id": "0a0c74aa4a2c323cabfaedf4210786d13e4b01a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3007, "license_type": "no_license", "max_line_length": 631, "num_lines": 69, "path": "/README.md", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "# C46Project2\n\n\nDjango:\n```shell\npip3 install django\nsudo apt-get install python3-dev libmysqlclient-dev\npip3 install mysqlclient\npython3 manage.py makemigrations\npython3 manage.py migrate\npython3 manage.py runserver\npython3 manage.py shell # to interact with REPL\n```\n\n\n\n```\ndocker build -t csc346 .\ndocker run --name csc346 -p 80:8000 -v `pwd`:/root -td csc346:latest runserver 0.0.0.0:8000\n```\n\n\nhttps://fosstack.com/how-to-add-google-authentication-in-django/\n\n\n\n### Project 03\nNew features:\n- Github OAuth for login\n- Github webhooks to automatically checkout new pushes\n- Run using Docker. The Dockerfile in this project uses the official Python Docker image and installs our dependencies in it so it can easily be run in any cloud environment\n\nNew ec2 instance: http://ec2-3-86-254-204.compute-1.amazonaws.com\n\n#### How to use webhook:\nFirst you will need my fork of the repo since I needed permission to setup the webhook:\n\n```shell\ngit clone https://github.com/calvinmclean/CSC346Project2.git\n# or if you already have Laura's repo:\ngit remote add calvin https://github.com/calvinmclean/CSC346Project2.git\n```\n\nDemonstrate by:\n\n1. making a small change on your local computer\n - I would edit `corgi_store/templates/home.html` and change the `<h1>` contents\n2. commit and push:\n```shell\ngit commit -am \"edit title for webhook\"\ngit push\n# or if you added a remote:\ngit push calvin master\n```\n3. Wait about 5-10 seconds before refreshing the browser page\n\n\n#### How the webhook works\nOn Github, I was able to create a webhook for this repository that will trigger whenever new code is pushed to the repository. This webhook will send a payload to http://ec2-3-86-254-204.compute-1.amazonaws.com/webhook/ whenever this event occurs. This payload is a large JSON object containing all of the information about the repository and commit that was pushed.\n\n\nOn the server-side, a django endpoint is used to listen for the payload. This uses an important Python module:\n- GitPython: used to perform all kinds of git operations including fetching, pulling, and cloning\n\n\nThis webhook is employed to enable a popular development technique that is enabled by cloud technologies: Continuous Integration or Continuous Development (CI/CD). The purpose of this is to automate the process of deploying new code to servers in testing or production environments. It allows developers to make changes to code without worrying about manually installing and testing their code on a cloud instance. CI/CD can be used to automatically run unit tests on pull requests, then merge the changes into master branch after the tests pass, and automatically deploy any changes on the master branch to the production servers.\n\n\nThe webhook code started by using [this example](https://pygithub.readthedocs.io/en/latest/examples/Webhook.html) and was modified to run inside Django. I only implemented the webhook for pushes since it is easier to demonstrate than pull requests, but the same can easily be done for a pull request.\n" }, { "alpha_fraction": 0.7604166865348816, "alphanum_fraction": 0.7604166865348816, "avg_line_length": 18.200000762939453, "blob_id": "6b4488487697a71850b181ceb6b3b50e4a46d924", "content_id": "28ff72a7de982efe3fe2d467f0cedb74b2a07db3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/corgi_store/apps.py", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass CorgiStoreConfig(AppConfig):\n name = 'corgi_store'\n" }, { "alpha_fraction": 0.7386363744735718, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 13.666666984558105, "blob_id": "fbd0e9cc7c90b0ec1943c49e640d6db843d6c682", "content_id": "6b1c54d836559c132e729bf4b0b2543090e0ff26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 88, "license_type": "no_license", "max_line_length": 20, "num_lines": 6, "path": "/sql/drop_tables.sql", "repo_name": "Lshoemake/CSC346Project2", "src_encoding": "UTF-8", "text": "use csc346;\n\nDROP TABLE dog;\nDROP TABLE users;\nDROP TABLE listing;\nDROP Table favorite;\n" } ]
16
itsraghz/piy
https://github.com/itsraghz/piy
f0e5633a539e11d04810f7236c3ee64e8e7a3fe4
2cb4946dd29286936bdb7ef7f955c1b164208085
f84a7244032c8428bf2eb9d76b54f8f1fd157617
refs/heads/master
2021-12-02T20:37:50.930283
2013-01-11T15:11:57
2013-01-11T15:11:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.534246563911438, "alphanum_fraction": 0.5821917653083801, "avg_line_length": 25.454545974731445, "blob_id": "8c8457a4b79ab3ea1b041e2d135df08bf4a23617", "content_id": "71c3973be01a767958f8b5c59aacea33ece75955", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "permissive", "max_line_length": 63, "num_lines": 11, "path": "/piy/__init__.py", "repo_name": "itsraghz/piy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom piy import transform_pom_yaml_to_xml\n\n__version__ = \"0.0.2\"\n__authors__ = \"Sergio Fernández\"\n__license__ = \"GNU General Public License v3 or later (GPLv3+)\"\n__url__ = \"http://github.com/wikier/piy\"\n__contact__ = \"[email protected]\"\n__date__ = \"2012-11-11\"\n\n" }, { "alpha_fraction": 0.4928571283817291, "alphanum_fraction": 0.4979591965675354, "avg_line_length": 21.76744270324707, "blob_id": "cc2b1904d50662db28c68bbd010ccc2b87bcdae3", "content_id": "9f0937711ab25e2674db1863cd5951d8ae39a1fe", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 980, "license_type": "permissive", "max_line_length": 56, "num_lines": 43, "path": "/setup.py", "repo_name": "itsraghz/piy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport piy\nfrom setuptools import setup\n\nsetup(\n name = \"piy\",\n version = piy.__version__,\n description = \"POM in YAML\",\n author = piy.__authors__,\n author_email = piy.__contact__,\n long_description = open(\"README.md\", \"r\").read(),\n url = piy.__url__,\n packages = [\n \"piy\"\n ],\n requires = [\n \"pyyaml\",\n \"hutools\"\n ],\n install_requires = [\n \"pyyaml\",\n \"hutools >= 0.64\"\n ],\n package_data = {\n \"rubber\": []\n },\n classifiers = [\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: \" + piy.__license__,\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Topic :: Utilities\"\n ],\n entry_points = {\n \"console_scripts\" : [\n \"piy = piy:transform_pom_yaml_to_xml\"\n ]\n }\n)\n\n" }, { "alpha_fraction": 0.5141903162002563, "alphanum_fraction": 0.5158597826957703, "avg_line_length": 30.473684310913086, "blob_id": "2307dca2bd3ca7c85e2a298b72f54b8b0f217b52", "content_id": "229dfe40ab82a7e177396144da45e2b20779c2c0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "permissive", "max_line_length": 92, "num_lines": 19, "path": "/tests.py", "repo_name": "itsraghz/piy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nfrom piy import transform_pom_yaml_to_xml\n\nif __name__ == \"__main__\":\n root = os.getcwd() + os.sep + \"tests\"\n tests = [ name for name in os.listdir(root) if os.path.isdir(os.path.join(root, name)) ]\n tests.sort()\n sys.path.append(os.getcwd())\n for test in tests:\n path = root + os.sep + test\n print\n print \"Running tests with file '%s/pom.yaml'\" % path\n print \"---------------------------------------------------------------------\"\n transform_pom_yaml_to_xml(path=path)\n print\n\n" }, { "alpha_fraction": 0.6106483340263367, "alphanum_fraction": 0.6193408370018005, "avg_line_length": 33.074073791503906, "blob_id": "729633fabfc94237046f6c69ba06fa4ea089c6db", "content_id": "7def6778a8d1ee0e417e1159136b1b8b4b2dd0b5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2761, "license_type": "permissive", "max_line_length": 310, "num_lines": 81, "path": "/README.md", "repo_name": "itsraghz/piy", "src_encoding": "UTF-8", "text": "# piy\n\n\n\"POM in YAML\" is a simple tool to write [Maven](http://maven.apache.org) POM files using [YAML](http://www.yaml.org/). Because many times XML can be too verbose...\n\n## Status\n\n**The tools is still in alpha!** All feedback and bug reports are welcome.\n\n## Installation\n\nFrom the code:\n\n python setup.py install\n\nFrom PyPI:\n\n easy_install piy\n\n## Usage\n\nOnce you have written your pom.yaml file, just execute:\n\n piy\n\nThis will show the generated pom.xml in the standard output. When you'd be happy with the result, you can save it by running:\n\n piy > pom.xml\n\nAs a geneal rule, I strongly recomment that generated files must not be managed by the source control systems (git, hg, svn or whatever). And this case is not an exception; so, please, don't commit the pom.xml file to your project if you want to avoid synchronization issues with other users/developers.\n\n## How does it work\n\nThe tools pre-processes the pom.yaml file at the current directory, and generates a proper pom.xml. Then you can use Maven as usual.\n\nAlthougt with the same goal, the approach is completelly different to [Maven3 polyglot](http://polyglot.sonatype.org/), which adds to Maven3 the ability to work with pom files written in non-XML notations. \n\n## Syntax\n\nBasically it's a translation of the current XML tree to YAML.\n\n project:\n\n modelVersion: 4.0.0\n groupId: com.foo\n artifactId: bar\n version: 1.0-SNAPSHOT\n packaging: jar\n\n build:\n plugins:\n plugin:\n groupId: org.apache.maven.plugins\n artifactId: maven-compiler-plugin\n version: 2.5.1 \n configuration:\n source: 1.6\n target: 1.6\n\n dependencies:\n dependency:\n groupId: com.bar\n artifactId: foo\n version: 1.0-SNAPSHOT\n\nThis will be transformed to a normal pom.xml file.\n\nAlthough not very common in POMs, sometimes attributes are necessary in POM files. Since YAML doesn't support attributes, for adding attributes you'd need to start the name of the node with the underline symbol. See for instance the following example to configure the port with the Jetty plugin using such way:\n\n project:\n build:\n plugins:\n plugin:\n groupId: org.mortbay.jetty\n artifactId: maven-jetty-plugin\n version: 6.1.10\n configuration:\n connectors:\n connector:\n _implementation: org.mortbay.jetty.nio.SelectChannelConnector\n port: 8080\n\n" }, { "alpha_fraction": 0.5796610116958618, "alphanum_fraction": 0.5892655253410339, "avg_line_length": 35.85416793823242, "blob_id": "f241f609c37f650d0e940f237ffc52a9bb5a3d6d", "content_id": "9543cc009e77bf42d6ad6a032406fa7bf34770bd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1770, "license_type": "permissive", "max_line_length": 167, "num_lines": 48, "path": "/piy/piy.py", "repo_name": "itsraghz/piy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport yaml\nfrom huTools.structured import dict2et \nfrom xml.etree import ElementTree\nfrom xml.dom import minidom\n\ndef __preprocess_attributes(node):\n if type(node) == dict:\n node2 = {}\n for k, v in node.items():\n if str(k).startswith(\"_\"):\n k = \"@\" + str(k)[1:]\n node2[k] = __preprocess_attributes(v) \n return node2\n else:\n return node\n\ndef transform_pom_yaml_to_xml(path=None, fileName=\"pom.yaml\", modelVersion=\"4.0.0\", indent=\" \", encoding=\"utf-8\"):\n if path == None:\n path = os.getcwd()\n path = path + os.sep + fileName \n try:\n with open(path, \"r\") as f:\n content = f.read()\n except IOError:\n sys.exit(\"POM not fount at '%s'\" % path)\n pom = yaml.load(content)\n if not \"project\" in pom:\n sys.exit(\"'project' root node not found\")\n else:\n pom = __preprocess_attributes(pom)\n if not \"modelVersion\" in pom[\"project\"]:\n pom[\"project\"][\"modelVersion\"] = modelVersion\n elif not pom[\"project\"][\"modelVersion\"] == modelVersion:\n sys.exit(\"Unsupported modelVersion \" + pom[\"project\"][\"modelVersion\"])\n pom[\"project\"][\"@xmlns\"] = \"http://maven.apache.org/POM/%s\" % modelVersion\n pom[\"project\"][\"@xmlns:xsi\"] = \"http://www.w3.org/2001/XMLSchema-instance\"\n pom[\"project\"][\"@xsi:schemaLocation\"] = \"http://maven.apache.org/POM/%s http://maven.apache.org/maven-v%s.xsd\" % (modelVersion, modelVersion.replace(\".\", \"_\"))\n xml = dict2et(pom)\n dom = minidom.parseString(ElementTree.tostring(xml[0], encoding))\n print dom.toprettyxml(indent)\n\nif __name__ == \"__main__\":\n transform_pom_yaml_to_xml()\n\n" } ]
5
cristian-programmer/skift
https://github.com/cristian-programmer/skift
1eedaec88ba1c09518b7c11110fa4b96a2b2b0eb
189df9d043ce79b8376ab35aac3f5665a565d6ac
9c83c88b5b60d28e1d43c7f6cdc264a4bb2a424b
refs/heads/main
2021-06-14T17:02:38.612380
2021-03-01T14:35:49
2021-03-01T14:35:49
162,073,493
1
0
MIT
2018-12-17T04:15:16
2018-12-16T15:17:15
2018-12-16T15:17:14
null
[ { "alpha_fraction": 0.568791925907135, "alphanum_fraction": 0.5805369019508362, "avg_line_length": 18.899999618530273, "blob_id": "e438ecb4a4905cddd1320003df622785f36c724d", "content_id": "b7f52ae069bd2525448d1f70a04e664e613493ff", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 596, "license_type": "permissive", "max_line_length": 55, "num_lines": 30, "path": "/libraries/libsystem/io/Reader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libutils/RefPtr.h>\n\nclass Writer;\nclass Reader\n{\npublic:\n virtual size_t length() = 0;\n virtual size_t position() = 0;\n\n virtual size_t read(void *buffer, size_t size) = 0;\n\n virtual uint8_t read_byte()\n {\n uint8_t result;\n assert(read(&result, 1));\n return result;\n };\n\n virtual void read_all(void **buffer, size_t *size)\n {\n *buffer = new uint8_t[length()];\n *size = length();\n assert(read(*buffer, length()) == length());\n }\n\n virtual void copy_to(Writer &writer);\n};" }, { "alpha_fraction": 0.5579491853713989, "alphanum_fraction": 0.5592417120933533, "avg_line_length": 24.2391300201416, "blob_id": "8b0d35327a243647b64c65178ee5b23bcc7902a1", "content_id": "8e29dafa82e7219715f540c5c89feba13700dae5", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2321, "license_type": "permissive", "max_line_length": 98, "num_lines": 92, "path": "/libraries/libfilepicker/widgets/Breadcrumb.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n\n#include <libwidget/Button.h>\n#include <libwidget/IconPanel.h>\n#include <libwidget/Spacer.h>\n#include <libwidget/Window.h>\n\n#include <libfilepicker/widgets/Breadcrumb.h>\n\nnamespace filepicker\n{\n\nBreadcrumb::Breadcrumb(Widget *parent, RefPtr<Navigation> navigation, RefPtr<Bookmarks> bookmarks)\n : Widget(parent),\n _navigation(navigation),\n _bookmarks(bookmarks)\n{\n layout(HFLOW(0));\n\n _icon_computer = Icon::get(\"laptop\");\n _icon_expand = Icon::get(\"chevron-right\");\n _icon_bookmark = Icon::get(\"bookmark\");\n _icon_bookmark_outline = Icon::get(\"bookmark-outline\");\n\n _navigation_observer = _navigation->observe([this](auto &) {\n render();\n });\n\n if (_bookmarks != nullptr)\n {\n _bookmarks_observer = _bookmarks->observe([this](auto &) {\n render();\n });\n }\n\n render();\n}\n\nvoid Breadcrumb::render()\n{\n clear_children();\n\n auto &path = _navigation->current();\n\n auto computer_button = new Button(this, Button::TEXT, _icon_computer);\n\n computer_button->on(Event::ACTION, [this](auto) {\n _navigation->navigate(\"/\");\n });\n\n for (size_t i = 0; i < path.length(); i++)\n {\n new IconPanel(this, _icon_expand);\n\n auto button = new Button(this, Button::TEXT, path[i]);\n button->min_width(0);\n\n button->on(Event::ACTION, [this, i](auto) {\n _navigation->navigate(_navigation->current().parent(i), Navigation::BACKWARD);\n });\n }\n\n new Spacer(this);\n\n if (_bookmarks)\n {\n if (_bookmarks->has(_navigation->current()))\n {\n auto remove_bookmark = new Button(this, Button::TEXT, _icon_bookmark);\n\n remove_bookmark->on(Event::ACTION, [this](auto) {\n _bookmarks->remove(_navigation->current());\n });\n }\n else\n {\n auto add_bookmark = new Button(this, Button::TEXT, _icon_bookmark_outline);\n\n add_bookmark->on(Event::ACTION, [this](auto) {\n Bookmark bookmark{\n _navigation->current().basename(),\n Icon::get(\"folder\"),\n _navigation->current(),\n };\n\n _bookmarks->add(move(bookmark));\n });\n }\n }\n}\n\n} // namespace filepicker" }, { "alpha_fraction": 0.557106614112854, "alphanum_fraction": 0.5691624283790588, "avg_line_length": 21.19718360900879, "blob_id": "76122974323554f7e74fbcebc087722c233a9776", "content_id": "0fabd41722f7fad769faa41dd3c820d2fe9de90e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1576, "license_type": "permissive", "max_line_length": 77, "num_lines": 71, "path": "/libraries/libwidget/Graph.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libgraphic/Painter.h>\n#include <libsystem/Logger.h>\n#include <libwidget/Graph.h>\n\nGraph::Graph(Widget *parent, size_t data_size, Color data_color)\n : Widget(parent)\n{\n _data = (float *)calloc(data_size, sizeof(float));\n _data_size = data_size;\n _color = data_color;\n _current = 0;\n}\n\nGraph::~Graph()\n{\n free(_data);\n}\n\nvoid Graph::paint(Painter &painter, const Recti &)\n{\n int height = bound().height();\n int width = bound().width();\n\n auto distance = [](float from, float to, int size) {\n if (from > to)\n {\n from -= size;\n }\n\n return fabsf(to - from) / (float)size;\n };\n\n auto graph_sample = [&](float where) {\n assert(where >= 0 && where <= 1);\n\n return _data[(size_t)(_data_size * where)];\n };\n\n float cursor_position = (_current % _data_size) / (float)_data_size;\n\n for (int i = 0; i < width; i++)\n {\n float where = i / (float)width;\n float data = graph_sample(where);\n\n Recti bar{i, (int)(height * (1.0 - data)), 1, height};\n\n float dist = (1 - distance(where, cursor_position, 1));\n\n painter.fill_rectangle(bar, _color.with_alpha((dist * dist) * 0.50));\n painter.plot(bar.position(), _color);\n }\n\n Recti cursor{(int)(width * cursor_position), 0, 1, height};\n\n painter.fill_rectangle(cursor, color(THEME_BORDER));\n}\n\nVec2i Graph::size()\n{\n return Vec2i(_data_size, 100);\n}\n\nvoid Graph::record(float data)\n{\n _data[_current % _data_size] = data;\n _current++;\n\n should_repaint();\n}\n" }, { "alpha_fraction": 0.6687334179878235, "alphanum_fraction": 0.6705048680305481, "avg_line_length": 27.225000381469727, "blob_id": "8ea8855770dad1bf18178df9762bed4910385a2e", "content_id": "c8b8abc37a129bb49d44b2eb9a0efefd7a572254", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1129, "license_type": "permissive", "max_line_length": 106, "num_lines": 40, "path": "/libraries/libsystem/Result.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/Logger.h>\n#include <libsystem/Result.h>\n#include <libsystem/io/Stream.h>\n#include <libsystem/process/Process.h>\n\n#define RESULT_ENUM_ENTRY_STRING(__entry, __description) #__entry,\n#define RESULT_ENUM_ENTRY_STRING_WITH_VALUE(__entry, __value, __description) #__entry,\n\nconst char *RESULT_NAMES[] = {RESULT_ENUM(RESULT_ENUM_ENTRY_STRING, RESULT_ENUM_ENTRY_STRING_WITH_VALUE)};\nconst char *RESULT_DESCRIPTIONS[] = {\n#define RESULT_ENUM_ENTRY(__name, __description) __description,\n#define RESULT_ENUM_ENTRY_WITH_VALUE(__name, __value, __description) __description,\n RESULT_ENUM(RESULT_ENUM_ENTRY, RESULT_ENUM_ENTRY_WITH_VALUE)\n#undef RESULT_ENUM_ENTRY\n#undef RESULT_ENUM_ENTRY_WITH_VALUE\n};\n\nconst char *result_to_string(Result error)\n{\n if (error < __RESULT_COUNT && error >= 0)\n {\n return RESULT_NAMES[error];\n }\n else\n {\n return \"INVALID_RESULT_CODE\";\n }\n}\n\nconst char *get_result_description(Result result)\n{\n if (result < __RESULT_COUNT && result >= 0)\n {\n return RESULT_DESCRIPTIONS[result];\n }\n else\n {\n return \"INVALID_RESULT_CODE\";\n }\n}" }, { "alpha_fraction": 0.7564102411270142, "alphanum_fraction": 0.7564102411270142, "avg_line_length": 18.5, "blob_id": "ec8e55c1d25e9469a257359def4fd89a691e10ee", "content_id": "a9b6b4e9918de921c44af2afc57e8bff24439303", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 78, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/apps/about/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += ABOUT\n\nABOUT_NAME = about\nABOUT_LIBS = widget settings markup graphic\n" }, { "alpha_fraction": 0.6570783853530884, "alphanum_fraction": 0.6630005836486816, "avg_line_length": 25.46268653869629, "blob_id": "3ca5479619398fbcc3cfd66bdf2dbaac014c3b2f", "content_id": "859fb338f55bba8cddd573cc895973cde59632d6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3546, "license_type": "permissive", "max_line_length": 102, "num_lines": 134, "path": "/libraries/libgraphic/Painter.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Trans2.h>\n\n#include <libgraphic/Bitmap.h>\n#include <libgraphic/Font.h>\n#include <libgraphic/Icon.h>\n#include <libgraphic/vector/Path.h>\n\n#define STATESTACK_SIZE 32\n\nstruct PainterState\n{\n Vec2i origin;\n Recti clip;\n};\n\nstruct SourceDestionation\n{\n Recti source;\n Recti destination;\n\n bool is_empty()\n {\n return destination.is_empty();\n }\n};\n\nclass Painter\n{\nprivate:\n RefPtr<Bitmap> _bitmap;\n int _state_stack_top = 0;\n PainterState _state_stack[STATESTACK_SIZE];\n\npublic:\n Painter(RefPtr<Bitmap> bitmap);\n\n /* --- context ---------------------------------------------------------- */\n\n void push();\n\n void pop();\n\n void clip(Recti rectangle);\n\n void transform(Vec2i offset);\n\n Recti apply(Recti rectangle);\n\n SourceDestionation apply(Recti source, Recti destination);\n\n /* --- Drawing ---------------------------------------------------------- */\n\n void plot(Vec2i position, Color color);\n\n void blit(Bitmap &bitmap, Recti source, Recti destination);\n\n void blit(Bitmap &bitmap, BitmapScaling scaling, Recti destionation);\n\n void blit_no_alpha(Bitmap &bitmap, Recti source, Recti destination);\n\n void blit(Icon &icon, IconSize size, Recti destination, Color color);\n\n void blit_rounded(Bitmap &bitmap, Recti source, Recti destination, int radius);\n\n void blit_rounded_no_alpha(Bitmap &bitmap, Recti source, Recti destination, int radius);\n\n void clear(Color color);\n\n void clear(Recti rectangle, Color color);\n\n void fill_rectangle(Recti rectangle, Color color);\n\n void fill_insets(Recti rectangle, Insetsi insets, Color color);\n\n void fill_rectangle_rounded(Recti bound, int radius, Color color);\n\n void fill_checkboard(Recti bound, int cell_size, Color fg_color, Color bg_color);\n\n void draw_line(Vec2i from, Vec2i to, Color color);\n\n void draw_rectangle(Recti rectangle, Color color);\n\n void draw_triangle(Vec2i p0, Vec2i p1, Vec2i p2, Color color);\n\n void draw_path(const graphic::Path &path, Vec2f pos, Trans2f transform, Color color);\n\n void draw_rectangle_rounded(Recti bound, int radius, int thickness, Color color);\n\n void draw_glyph(Font &font, const Glyph &glyph, Vec2i position, Color color);\n\n void draw_string(Font &font, const char *str, Vec2i position, Color color);\n\n void draw_string_within(Font &font, const char *str, Recti container, Anchor anchor, Color color);\n\n /* --- Effects ---------------------------------------------------------- */\n\n void blur(Recti rectangle, int radius);\n\n void saturation(Recti rectangle, float value);\n\n void noise(Recti rectangle, float opacity);\n\n void acrylic(Recti rectangle);\n\n void sepia(Recti rectangle, float value);\n\n void tint(Recti rectangle, Color color);\n\n Recti clip() const\n {\n return _state_stack[_state_stack_top].clip;\n }\n\nprivate:\n Vec2i origin() const { return _state_stack[_state_stack_top].origin; };\n\n Recti apply_clip(Recti rectangle);\n\n Recti apply_transform(Recti rectangle);\n\n void blit_fast(Bitmap &bitmap, Recti source, Recti destination);\n\n void blit_scaled(Bitmap &bitmap, Recti source, Recti destination);\n\n void blit_fast_no_alpha(Bitmap &bitmap, Recti source, Recti destination);\n\n void blit_scaled_no_alpha(Bitmap &bitmap, Recti source, Recti destination);\n\n void blit_colored(Bitmap &src, Recti source, Recti destination, Color color);\n\n void draw_circle_helper(Recti bound, Vec2i center, int radius, int thickness, Color color);\n};\n" }, { "alpha_fraction": 0.6561797857284546, "alphanum_fraction": 0.6696628928184509, "avg_line_length": 20.238094329833984, "blob_id": "c17923be86a3c305d623b950b1313feb3b7c5cb2", "content_id": "58590a213a8406a474e77d3e8171a5add43fe1f3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 445, "license_type": "permissive", "max_line_length": 65, "num_lines": 21, "path": "/libraries/libsystem/io/Writer.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libutils/RefPtr.h>\n\nclass Reader;\nclass SeekableReader;\nclass Writer\n{\npublic:\n virtual size_t length() = 0;\n virtual size_t position() = 0;\n\n virtual void flush() = 0;\n\n virtual size_t write(const void *buffer, size_t size) = 0;\n virtual size_t write_byte(uint8_t v) { return write(&v, 1); }\n\n void copy_from(Reader &reader);\n void copy_from(SeekableReader &reader);\n};" }, { "alpha_fraction": 0.7322834730148315, "alphanum_fraction": 0.7322834730148315, "avg_line_length": 13.11111068725586, "blob_id": "ccb2f5a07c42ba8ffb87ef54fe3c2362579a8d39", "content_id": "eaa23ee290f704b98c674fba307cec39c5be9ca6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 127, "license_type": "permissive", "max_line_length": 36, "num_lines": 9, "path": "/archs/x86_32/kernel/LAPIC.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nvoid lapic_found(uintptr_t address);\n\nvoid lapic_initialize();\n\nvoid lapic_ack();\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 11.923076629638672, "blob_id": "c0a663368f908a7aebb4b63f0bf1e3bed17690ce", "content_id": "6c572dfba60ed4a8536a215e1be9bf6d55f83c35", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 168, "license_type": "permissive", "max_line_length": 46, "num_lines": 13, "path": "/libraries/libutils/New.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <stddef.h>\n\ninline void *operator new(size_t, void *ptr)\n{\n return ptr;\n}\n\ninline void *operator new[](size_t, void *ptr)\n{\n return ptr;\n}\n" }, { "alpha_fraction": 0.3595505654811859, "alphanum_fraction": 0.4018191695213318, "avg_line_length": 17.323530197143555, "blob_id": "3a194b6ca95496b0cd8b5b5355586232ecc4f986", "content_id": "8b3822dac4059ee223da54ca6cff7d7a231a67d9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1869, "license_type": "permissive", "max_line_length": 80, "num_lines": 102, "path": "/libraries/libsystem/math/Bresenham.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libutils/Vec2.h>\n#include <libutils/Vector.h>\n\n#include <math.h>\n\ntemplate <typename TCallback>\nvoid bresenhamLow(int x0, int y0, int x1, int y1, int size, TCallback callback)\n{\n int dx, dy, i, p, x, y = 0;\n dx = x1 - x0;\n dy = y1 - y0;\n i = 1;\n if (dy < 0)\n {\n i = -1;\n dy = -dy;\n }\n x = x0;\n y = y0;\n\n p = 2 * dy - dx;\n\n while (x < x1)\n {\n callback(Vec2(x, y) - Vec2i(size / 2), Vec2i(size, size));\n if (p >= 0)\n {\n y += i;\n p = p + 2 * dy - 2 * dx;\n }\n else\n {\n p = p + 2 * dy;\n }\n x++;\n }\n}\n\ntemplate <typename TCallback>\nvoid bresenhamHigh(int x0, int y0, int x1, int y1, int size, TCallback callback)\n{\n int dx, dy, i, p, x, y = 0;\n dx = x1 - x0;\n dy = y1 - y0;\n i = 1;\n if (dx < 0)\n {\n i = -1;\n dx = -dx;\n }\n x = x0;\n y = y0;\n\n p = 2 * dx - dy;\n\n while (y < y1)\n {\n callback(Vec2(x, y) - Vec2i(size / 2), Vec2i(size, size));\n if (p >= 0)\n {\n x += i;\n p = p + 2 * dx - 2 * dy;\n }\n else\n {\n p = p + 2 * dx;\n }\n y++;\n }\n}\n\ntemplate <typename TCallback>\nvoid bresenham(Vec2i start, Vec2i end, int size, TCallback callback)\n{\n int x0 = start.x();\n int y0 = start.y();\n int x1 = end.x();\n int y1 = end.y();\n\n if (abs(y1 - y0) < abs(x1 - x0))\n {\n if (x0 > x1)\n {\n bresenhamLow(x1, y1, x0, y0, size, callback);\n }\n else\n {\n bresenhamLow(x0, y0, x1, y1, size, callback);\n }\n }\n else\n {\n if (y0 > y1)\n {\n bresenhamHigh(x1, y1, x0, y0, size, callback);\n }\n else\n {\n bresenhamHigh(x0, y0, x1, y1, size, callback);\n }\n }\n}\n" }, { "alpha_fraction": 0.35687732696533203, "alphanum_fraction": 0.6728624701499939, "avg_line_length": 25.899999618530273, "blob_id": "1ada10189c21b3867414967e79fb9344ffb84815", "content_id": "cca33c5505ed514ee2a3fcf68c589172f282fcb0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 269, "license_type": "permissive", "max_line_length": 58, "num_lines": 10, "path": "/libraries/libsystem/bits/pi.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define PI (3.14159265358979323846264338327f)\n#define M_PI PI\n#define M_PI_2 (M_PI / 2.0)\n#define M_PI_4 (M_PI / 4.0)\n\n#define M_1_PI 0.31830988618379067154 /* 1/pi */\n#define M_2_PI (M_PI * 2.0)\n#define M_2_SQRTPI 1.12837916709551257390 /* 2/sqrt(pi) */\n" }, { "alpha_fraction": 0.6869918704032898, "alphanum_fraction": 0.7113820910453796, "avg_line_length": 13.470588684082031, "blob_id": "2bc3a62a8a72eca0343a9615d027749f305f468f", "content_id": "2a416dd460d085ed30302d129d0163d85ce24fac", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 246, "license_type": "permissive", "max_line_length": 41, "num_lines": 17, "path": "/apps/panel/windows/QuickSettingsWindow.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Window.h>\n\nnamespace panel\n{\n\nclass QuickSettingsWindow : public Window\n{\npublic:\n static constexpr int WIDTH = 320;\n static constexpr int HEIGHT = 320;\n\n QuickSettingsWindow();\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.7755101919174194, "alphanum_fraction": 0.7755101919174194, "avg_line_length": 15.333333015441895, "blob_id": "ec7af829c516c4107578b04b17722db5d18af412", "content_id": "a36c70ff001a9d4f665424198153a21d9f35a22f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 49, "license_type": "permissive", "max_line_length": 28, "num_lines": 3, "path": "/libraries/libfilepicker/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += FILEPICKER\n\nFILEPICKER_NAME = filepicker\n" }, { "alpha_fraction": 0.5820289850234985, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 19.05813980102539, "blob_id": "3ac927a500a5ba3d2a0e6225b6d7af706088c0bd", "content_id": "f467d4dfc9316272b7cb0067a446760f311a72d0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1725, "license_type": "permissive", "max_line_length": 86, "num_lines": 86, "path": "/libraries/libsystem/utils/Slice.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <assert.h>\n\nstruct Slice\n{\n unsigned char *data;\n int cursor;\n int size;\n};\n\n#define SLICE_NULL ((Slice){nullptr, 0, 0})\n\nstatic inline Slice slice_create(const void *p, size_t size)\n{\n return (Slice){\n .data = (uint8_t *)p,\n .cursor = 0,\n .size = (int)size,\n };\n}\n\nstatic inline Slice slice_range(const Slice *slice, int offset, int size)\n{\n if (offset < 0 || size < 0 || offset > slice->size || size > slice->size - offset)\n {\n return SLICE_NULL;\n }\n else\n {\n return slice_create(slice->data + offset, size);\n }\n}\n\nstatic inline Slice slice_sub_slice(Slice slice, int offset, int size)\n{\n return slice_create(slice.data + offset, size);\n}\n\nstatic inline bool slice_is_empty(Slice slice)\n{\n return slice.size == 0;\n}\n\n#define slice_get32(b) slice_get((b), 4)\n#define slice_get16(b) slice_get((b), 2)\nstatic inline uint8_t slice_get8(Slice *slice)\n{\n if (slice->cursor >= slice->size)\n return 0;\n\n return slice->data[slice->cursor++];\n}\n\nstatic inline uint32_t slice_get(Slice *slice, int n)\n{\n assert(n >= 1 && n <= 4);\n\n uint32_t value = 0;\n\n for (int i = 0; i < n; i++)\n {\n value = (value << 8) | slice_get8(slice);\n }\n\n return value;\n}\n\nstatic inline uint8_t slice_peek8(Slice *slice)\n{\n if (slice->cursor >= slice->size)\n return 0;\n\n return slice->data[slice->cursor];\n}\n\nstatic inline void slice_seek(Slice *slice, int offset)\n{\n assert(!(offset > slice->size || offset < 0));\n slice->cursor = (offset > slice->size || offset < 0) ? slice->size : offset;\n}\n\nstatic inline void slice_skip(Slice *slice, int offset)\n{\n slice_seek(slice, slice->cursor + offset);\n}\n" }, { "alpha_fraction": 0.6606315970420837, "alphanum_fraction": 0.6631578803062439, "avg_line_length": 26.61627960205078, "blob_id": "5703478421edf25c5fa55272b6923dce55b5d5fc", "content_id": "cdbd7553badc5e48a521a5c77638f6939743131f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2375, "license_type": "permissive", "max_line_length": 109, "num_lines": 86, "path": "/libraries/libsystem/utils/List.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libutils/Iteration.h>\n\n#define list_foreach(__type, __item, __list) \\\n for (ListItem *__i = __list->_head; __i != nullptr; __i = __i->next) \\\n for (__type *__item = (__type *)__i->value, *__loop_once = (__type *)1; __loop_once; __loop_once = 0)\n\n#define list_foreach_reversed(__type, __item, __list) \\\n for (ListItem *__i = __list->_tail; __i != nullptr; __i = __i->prev) \\\n for (__type *__item = (__type *)__i->value, *__loop_once = (__type *)1; __loop_once; __loop_once = 0)\n\nstruct ListItem\n{\n void *value;\n\n struct ListItem *prev;\n struct ListItem *next;\n};\n\nstruct List\n{\n int _count;\n ListItem *_head;\n ListItem *_tail;\n\n auto empty() { return _count == 0; }\n\n auto any() { return _count > 0; }\n\n auto count() { return _count; }\n};\n\ntypedef bool (*ListCompareElementCallback)(void *left, void *right);\ntypedef void (*ListDestroyElementCallback)(void *element);\n\nList *list_create();\n\nvoid list_destroy(List *list);\n\nvoid list_destroy_with_callback(List *list, ListDestroyElementCallback callback);\n\nvoid list_clear(List *list);\n\nvoid list_clear_with_callback(List *list, ListDestroyElementCallback callback);\n\nList *list_clone(List *list);\n\nvoid list_insert_sorted(List *list, void *value, ListCompareElementCallback comparator);\n\nvoid *list_peek(List *list);\n\nbool list_peek_and_pushback(List *list, void **value);\n\nvoid *list_peekback(List *list);\n\nbool list_peekat(List *list, int index, void **value);\n\nint list_indexof(List *list, void *value);\n\nvoid list_insert(List *list, int index, void *value);\n\nvoid list_push(List *list, void *value);\n\nvoid list_pushback(List *list, void *value);\n\nvoid list_pushback_copy(List *list, void *value, size_t size);\n\nbool list_pop(List *list, void **value);\n\nbool list_popback(List *list, void **value);\n\nbool list_contains(List *list, void *value);\n\nbool list_remove(List *list, void *value);\n\nbool list_remove_with_callback(List *list, void *value, ListDestroyElementCallback callback);\n\nbool list_remove_at(List *list, int index);\n\nbool list_remove_at_with_callback(List *list, int index, ListDestroyElementCallback callback);\n\ntypedef Iteration (*ListIterationCallback)(void *target, void *value);\n\nbool list_iterate(List *list, void *target, ListIterationCallback callback);\n" }, { "alpha_fraction": 0.6979866027832031, "alphanum_fraction": 0.7114093899726868, "avg_line_length": 17.625, "blob_id": "b0bf5d35b951d28da40a3ea5383849a3f2dc040c", "content_id": "dc839b077eedd5a414f994bf0d7b2fb1f541377f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 298, "license_type": "permissive", "max_line_length": 59, "num_lines": 16, "path": "/libraries/libwidget/Separator.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n#include <libwidget/Separator.h>\n\nSeparator::Separator(Widget *parent) : Widget(parent)\n{\n}\n\nvoid Separator::paint(Painter &painter, const Recti &dirty)\n{\n painter.fill_rectangle(dirty, color(THEME_BORDER));\n}\n\nVec2i Separator::size()\n{\n return Vec2i(1, 1);\n}\n" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.707317054271698, "avg_line_length": 10.714285850524902, "blob_id": "05bd3adf2edabf4247dff1389307155cbd4b4af0", "content_id": "08ec1436c76b05f9ec1f58bdb0d1601e3a749dd8", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 164, "license_type": "permissive", "max_line_length": 32, "num_lines": 14, "path": "/apps/panel/widgets/UserAccount.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Label.h>\n\nnamespace panel\n{\n\nclass UserAccount : public Label\n{\npublic:\n UserAccount(Widget *parent);\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.6310160160064697, "alphanum_fraction": 0.6310160160064697, "avg_line_length": 16.090909957885742, "blob_id": "cb5724cdfc130b4b8439f2d5c368a10788c53f0e", "content_id": "a4df92dc5bd2022ce7c0ff12f76c05d007d32a55", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 187, "license_type": "permissive", "max_line_length": 51, "num_lines": 11, "path": "/libraries/libwidget/Spacer.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nstruct Spacer : public Widget\n{\n Spacer(Widget *parent) : Widget(parent)\n {\n flags(Widget::FILL | Widget::NO_MOUSE_HIT);\n }\n};" }, { "alpha_fraction": 0.5877193212509155, "alphanum_fraction": 0.588394045829773, "avg_line_length": 19.027027130126953, "blob_id": "a75551c5d02e4a8d51670fc66fd84c88f2ca0047", "content_id": "e95e1c37507dd0532576eadec9ef0b564ec6e17d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1482, "license_type": "permissive", "max_line_length": 81, "num_lines": 74, "path": "/libraries/libmedia/ipc/Protocol.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libsystem/io/Connection.h>\n\n#include <libutils/Optional.h>\n#include <libutils/ResultOr.h>\n#include <libutils/Slice.h>\n\nnamespace media\n{\n\nstruct Protocol\n{\n enum class Type : uint8_t\n {\n INVALID,\n ACK,\n GREETINGS,\n AUDIODATA,\n DISCONNECT,\n };\n\n struct Message\n {\n Type type;\n Optional<Slice> data;\n };\n\n struct SerializedMessageHeader\n {\n Type type;\n size_t payload;\n };\n\n ResultOr<Message> decode_message(Connection *connection)\n {\n SerializedMessageHeader header;\n\n connection_receive(connection, &header, sizeof(SerializedMessageHeader));\n\n if (handle_has_error(connection))\n {\n return handle_get_error(connection);\n }\n\n if (!header.payload)\n {\n return Message{header.type};\n }\n\n auto storage = make<SliceStorage>(header.payload);\n connection_receive(connection, storage->start(), header.payload);\n\n if (handle_has_error(connection))\n {\n return handle_get_error(connection);\n }\n\n return Message{header.type, Slice{storage}};\n }\n\n Result encode_message(Connection *connection, const Message &message)\n {\n SerializedMessageHeader header = {message.type};\n\n if (message.data)\n {\n header.payload = message.data->size();\n }\n }\n};\n\n} // namespace media\n" }, { "alpha_fraction": 0.68544602394104, "alphanum_fraction": 0.68544602394104, "avg_line_length": 13.199999809265137, "blob_id": "2a14508db8b06cbe0d5516bcee59b42972a0f00b", "content_id": "af597b0177ff525f5dc9a1bcfefb156bfe029a58", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 213, "license_type": "permissive", "max_line_length": 33, "num_lines": 15, "path": "/libraries/libsystem/bits/abs.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n__BEGIN_HEADER\n\nint abs(int x);\nlong labs(long j);\nlong long llabs(long long x);\n\ndouble fabs(double x);\nfloat fabsf(float x);\nlong double fabsl(long double x);\n\n__END_HEADER;\n" }, { "alpha_fraction": 0.654916524887085, "alphanum_fraction": 0.6604823470115662, "avg_line_length": 19, "blob_id": "7b55943122bdd1ad25343feb9c2fb5b271d01503", "content_id": "3f8e490c3320f8455bf9eee903c9ee2fadc6eb4a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 539, "license_type": "permissive", "max_line_length": 67, "num_lines": 27, "path": "/libraries/libsystem/io/MemoryWriter.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/io/Stream.h>\n#include <libsystem/io/Writer.h>\n#include <libutils/Path.h>\n\nclass MemoryWriter final : public Writer\n{\npublic:\n MemoryWriter(size_t reserve = 0);\n\n virtual size_t length() override;\n virtual size_t position() override;\n\n virtual void flush() override;\n virtual size_t write(const void *buffer, size_t size) override;\n\n void clear();\n void pop_front(size_t size);\n\n const Vector<uint8_t> &data()\n {\n return _data;\n }\n\nprivate:\n Vector<uint8_t> _data;\n};" }, { "alpha_fraction": 0.5653594732284546, "alphanum_fraction": 0.5713507533073425, "avg_line_length": 19.629213333129883, "blob_id": "182397f2da67722b2d9158f52be373e49a763d11", "content_id": "c5415239265847179b668ea954d072eb705d6202", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1836, "license_type": "permissive", "max_line_length": 67, "num_lines": 89, "path": "/libraries/libwidget/Event.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Keyboard.h>\n\n#include <libutils/Rect.h>\n\n#include <libutils/unicode/Codepoint.h>\n#include <libutils/Callback.h>\n\n#define MOUSE_NO_BUTTON (0)\n#define MOUSE_BUTTON_LEFT (1 << 1)\n#define MOUSE_BUTTON_RIGHT (1 << 2)\n#define MOUSE_BUTTON_MIDDLE (1 << 3)\n\ntypedef unsigned int MouseButton;\n\nstruct MouseEvent\n{\n int scroll;\n\n Vec2i position;\n Vec2i old_position;\n\n Vec2i position_on_screen;\n Vec2i old_position_on_screen;\n\n MouseButton button;\n MouseButton buttons;\n};\n\nstruct KeyboardEvent\n{\n Key key;\n KeyModifier modifiers;\n Codepoint codepoint;\n};\n\nstruct Event\n{\n enum Type\n {\n VALUE_CHANGE,\n ACTION,\n\n GOT_FOCUS,\n LOST_FOCUS,\n\n WINDOW_CLOSING,\n WINDOW_RESIZED,\n\n WIDGET_DISABLE,\n WIDGET_ENABLE,\n\n MOUSE_MOVE,\n MOUSE_SCROLL,\n MOUSE_ENTER,\n MOUSE_LEAVE,\n\n MOUSE_BUTTON_PRESS,\n MOUSE_BUTTON_RELEASE,\n MOUSE_DOUBLE_CLICK,\n\n KEYBOARD_KEY_PRESS,\n KEYBOARD_KEY_RELEASE,\n KEYBOARD_KEY_TYPED,\n\n DISPLAY_SIZE_CHANGED,\n\n __COUNT,\n };\n\n Type type;\n bool accepted;\n\n MouseEvent mouse;\n KeyboardEvent keyboard;\n};\n\nusing EventType = Event::Type;\nusing EventHandler = Callback<void(Event *)>;\n\n#define is_mouse_event(__event) \\\n (((Event *)(__event))->type == Event::MOUSE_MOVE || \\\n ((Event *)(__event))->type == Event::MOUSE_SCROLL || \\\n ((Event *)(__event))->type == Event::MOUSE_ENTER || \\\n ((Event *)(__event))->type == Event::MOUSE_LEAVE || \\\n ((Event *)(__event))->type == Event::MOUSE_BUTTON_PRESS || \\\n ((Event *)(__event))->type == Event::MOUSE_BUTTON_RELEASE || \\\n ((Event *)(__event))->type == Event::MOUSE_DOUBLE_CLICK)\n" }, { "alpha_fraction": 0.6071428656578064, "alphanum_fraction": 0.6071428656578064, "avg_line_length": 8.333333015441895, "blob_id": "f3fcdee0b6080054f986dc20ef88335e4486b63e", "content_id": "c37f2ef7b3e8bafa4ed8cdc6befcec98ea7bb84c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 28, "license_type": "permissive", "max_line_length": 14, "num_lines": 3, "path": "/libraries/libipc/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += IPC\n\nIPC_NAME = ipc\n" }, { "alpha_fraction": 0.6466244459152222, "alphanum_fraction": 0.6719409227371216, "avg_line_length": 28.625, "blob_id": "5c45d3350539dea8ae22da04575530867124b261", "content_id": "7f8b365ca08d8d9612eb43ae94e7a9256f2db737", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 948, "license_type": "permissive", "max_line_length": 93, "num_lines": 32, "path": "/apps/media-player/widgets/Cover.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"media-player/widgets/Cover.h\"\n\n#include <libgraphic/Painter.h>\n\nnamespace media_player\n{\n\nCover::Cover(Widget *parent, RefPtr<Bitmap> bitmap)\n : Widget(parent), _cover(bitmap)\n{\n _backdrop = *Bitmap::create_shared(64, 64);\n\n Painter painter(_backdrop);\n\n painter.blit(*_cover, _cover->bound(), _cover->bound().cover(_backdrop->bound()));\n painter.saturation(_backdrop->bound(), 1);\n painter.blur(_backdrop->bound(), 4);\n\n painter.fill_rectangle(_backdrop->bound(), Colors::BLACK.with_alpha(0.5));\n}\n\nvoid Cover::paint(Painter &painter, const Recti &)\n{\n painter.blit_no_alpha(*_backdrop, _backdrop->bound(), _backdrop->bound().cover(bound()));\n\n auto cover_bound = Recti{0, 0, 256, 256}.centered_within(bound());\n\n painter.blit_rounded_no_alpha(*_cover, _cover->bound(), cover_bound, 12);\n painter.draw_rectangle_rounded(cover_bound, 12, 1, Colors::WHITE.with_alpha(0.25));\n}\n\n} // namespace media_player\n" }, { "alpha_fraction": 0.5995566844940186, "alphanum_fraction": 0.6076837778091431, "avg_line_length": 22.955751419067383, "blob_id": "d17906d94b2f8b577447a4d8b4f6a1b65601634f", "content_id": "f977845c448c9a8cf47858eb6d90c61822bae7f2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2707, "license_type": "permissive", "max_line_length": 120, "num_lines": 113, "path": "/apps/terminal/Common.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Theme.h>\n\n#include \"terminal/Common.h\"\n\nRefPtr<Font> font()\n{\n static RefPtr<Font> font = nullptr;\n\n if (font == nullptr)\n {\n font = Font::get(\"mono\").take_value();\n }\n\n return font;\n}\n\nstatic ThemeColorRole _color_to_role[terminal::_COLOR_COUNT] = {\n [terminal::BLACK] = THEME_ANSI_BLACK,\n [terminal::RED] = THEME_ANSI_RED,\n [terminal::GREEN] = THEME_ANSI_GREEN,\n [terminal::YELLOW] = THEME_ANSI_YELLOW,\n [terminal::BLUE] = THEME_ANSI_BLUE,\n [terminal::MAGENTA] = THEME_ANSI_MAGENTA,\n [terminal::CYAN] = THEME_ANSI_CYAN,\n [terminal::GREY] = THEME_ANSI_WHITE,\n [terminal::BRIGHT_BLACK] = THEME_ANSI_BRIGHT_BLACK,\n [terminal::BRIGHT_RED] = THEME_ANSI_BRIGHT_RED,\n [terminal::BRIGHT_GREEN] = THEME_ANSI_BRIGHT_GREEN,\n [terminal::BRIGHT_YELLOW] = THEME_ANSI_BRIGHT_YELLOW,\n [terminal::BRIGHT_BLUE] = THEME_ANSI_BRIGHT_BLUE,\n [terminal::BRIGHT_MAGENTA] = THEME_ANSI_BRIGHT_MAGENTA,\n [terminal::BRIGHT_CYAN] = THEME_ANSI_BRIGHT_CYAN,\n [terminal::BRIGHT_GREY] = THEME_ANSI_BRIGHT_WHITE,\n [terminal::FOREGROUND] = THEME_ANSI_FOREGROUND,\n [terminal::BACKGROUND] = THEME_ANSI_BACKGROUND,\n};\n\nColor color(terminal::Color terminal_color)\n{\n return theme_get_color(_color_to_role[terminal_color]);\n}\n\nstatic Vec2i _cell_size = Vec2i(7, 16);\n\nRecti cell_bound(int x, int y)\n{\n return {\n Vec2i(x, y) * _cell_size,\n _cell_size,\n };\n}\n\nVec2i cell_size()\n{\n return _cell_size;\n}\n\nvoid render_cell(\n Painter &painter,\n int x,\n int y,\n Codepoint codepoint,\n terminal::Color foreground,\n terminal::Color background,\n terminal::Attributes attributes)\n{\n Recti bound = cell_bound(x, y);\n\n if (attributes.invert)\n {\n swap(foreground, background);\n }\n\n if (background != terminal::BACKGROUND)\n {\n painter.clear(bound, color(background));\n }\n\n if (attributes.underline)\n {\n painter.draw_line(\n bound.position() + Vec2i(0, 14),\n bound.position() + Vec2i(bound.width(), 14),\n color(foreground));\n }\n\n if (codepoint == U' ')\n {\n return;\n }\n\n auto &glyph = font()->glyph(codepoint);\n\n painter.draw_glyph(\n *font(),\n glyph,\n bound.position() + Vec2i(0, 13),\n color(foreground));\n\n if (attributes.bold)\n {\n painter.draw_glyph(\n *font(),\n glyph,\n bound.position() + Vec2i(1, 13),\n color(foreground));\n }\n}\n\nvoid render_cell(Painter &painter, int x, int y, terminal::Cell cell)\n{\n render_cell(painter, x, y, cell.codepoint, cell.attributes.foreground, cell.attributes.background, cell.attributes);\n}\n" }, { "alpha_fraction": 0.6769230961799622, "alphanum_fraction": 0.7153846025466919, "avg_line_length": 20.83333396911621, "blob_id": "2f75f57a6eb497b1118e97509c7b989560f9d626", "content_id": "af28b99cae141d38c684327cef0ad725dbad33c2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 130, "license_type": "permissive", "max_line_length": 33, "num_lines": 6, "path": "/libraries/abi/Memory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define MEMORY_NONE (0)\n#define MEMORY_USER (1 << 0)\n#define MEMORY_CLEAR (1 << 1)\ntypedef unsigned int MemoryFlags;" }, { "alpha_fraction": 0.33645954728126526, "alphanum_fraction": 0.35638922452926636, "avg_line_length": 10.513513565063477, "blob_id": "7a96474d0b5de1ce5616bb868b57a1402d429fb6", "content_id": "10690bbc3a9d555b00164c7431de03ed35e2adcc", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 853, "license_type": "permissive", "max_line_length": 87, "num_lines": 74, "path": "/libraries/libc/ctype.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <ctype.h>\n\nint isprint(int c)\n{\n if (c >= 0x20 && c <= 0x7e)\n {\n return 1;\n }\n\n return 0;\n}\n\nint islower(int c)\n{\n if (c >= 'a' && c <= 'z')\n {\n return 1;\n }\n\n return 0;\n}\n\nint isupper(int c)\n{\n if (c >= 'A' && c <= 'Z')\n {\n return 1;\n }\n\n return 0;\n}\n\nint isalpha(int c)\n{\n if (islower(c) || isupper(c))\n {\n return 1;\n }\n\n return 0;\n}\n\nint isdigit(int c)\n{\n if (c >= '0' && c <= '9')\n {\n return 1;\n }\n\n return 0;\n}\n\nint toupper(int c)\n{\n if (c >= 'a' && c <= 'z')\n {\n return c - 'a' + 'A';\n }\n return c;\n}\n\nint tolower(int c)\n{\n if (c >= 'A' && c <= 'Z')\n {\n return c - 'A' + 'a';\n }\n return c;\n}\n\nint isspace(int c)\n{\n return (c == '\\f' || c == '\\n' || c == '\\r' || c == '\\t' || c == '\\v' || c == ' ');\n}\n" }, { "alpha_fraction": 0.4384615421295166, "alphanum_fraction": 0.4384615421295166, "avg_line_length": 77, "blob_id": "7936f5a72e7331af93c528448ff64b99b9a1bb6a", "content_id": "053533642767e30eeedd9cc6a1b84dc42884a568", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 780, "license_type": "permissive", "max_line_length": 95, "num_lines": 10, "path": "/libraries/libutils/Enum.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define __enum_flags(__type) \\\n inline __type operator~(__type a) { return (__type) ~(int)a; } \\\n inline __type operator|(__type a, __type b) { return (__type)((int)a | (int)b); } \\\n inline __type operator&(__type a, __type b) { return (__type)((int)a & (int)b); } \\\n inline __type operator^(__type a, __type b) { return (__type)((int)a ^ (int)b); } \\\n inline __type &operator|=(__type &a, __type b) { return (__type &)((int &)a |= (int)b); } \\\n inline __type &operator&=(__type &a, __type b) { return (__type &)((int &)a &= (int)b); } \\\n inline __type &operator^=(__type &a, __type b) { return (__type &)((int &)a ^= (int)b); }\n" }, { "alpha_fraction": 0.4291044771671295, "alphanum_fraction": 0.44664180278778076, "avg_line_length": 18.007091522216797, "blob_id": "89b8affdd9647bf7a140e43aae5316e449e5e7cf", "content_id": "ad11e4319d2801038ff83781b5faf8ef2053aa2b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2680, "license_type": "permissive", "max_line_length": 99, "num_lines": 141, "path": "/apps/utilities/grep.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <string.h>\n#include <libsystem/io/Stream.h>\n\nint matchstar(int c, char *re, char *text);\n\n// matchhere: search for re at beginning of text\nint matchhere(char *re, char *text)\n{\n if (re[0] == '\\0')\n {\n return 1;\n }\n\n if (re[1] == '*')\n {\n return matchstar(re[0], re + 2, text);\n }\n\n if (re[0] == '$' && re[1] == '\\0')\n {\n return *text == '\\0';\n }\n\n if (*text != '\\0' && (re[0] == '.' || re[0] == *text))\n {\n return matchhere(re + 1, text + 1);\n }\n\n return 0;\n}\n\n// matchstar: search for c*re at beginning of text\nint matchstar(int c, char *re, char *text)\n{\n do\n {\n // a * matches zero or more instances\n if (matchhere(re, text))\n {\n return 1;\n }\n } while (*text != '\\0' && (*text++ == c || c == '.'));\n\n return 0;\n}\n\nint match(char *re, char *text)\n{\n if (re[0] == '^')\n {\n return matchhere(re + 1, text);\n }\n\n do\n {\n // must look at empty string\n if (matchhere(re, text))\n {\n return 1;\n }\n } while (*text++ != '\\0');\n\n return 0;\n}\n\nvoid grep(char *pattern, Stream *stream)\n{\n char *q;\n\n char buffer[1024];\n size_t file_offset = 0;\n size_t text_read = stream_read(stream, buffer + file_offset, sizeof(buffer) - file_offset - 1);\n\n while (text_read > 0)\n {\n file_offset += text_read;\n buffer[file_offset] = '\\0';\n char *p = buffer;\n\n while ((q = strchr(p, '\\n')) != 0)\n {\n *q = 0;\n\n if (match(pattern, p))\n {\n *q = '\\n';\n stream_write(out_stream, p, q + 1 - p);\n }\n\n p = q + 1;\n }\n\n if (p == buffer)\n {\n file_offset = 0;\n }\n\n if (file_offset > 0)\n {\n file_offset -= p - buffer;\n memmove(buffer, p, file_offset);\n }\n\n text_read = stream_read(stream, buffer + file_offset, sizeof(buffer) - file_offset - 1);\n }\n}\n\nint main(int argc, char *argv[])\n{\n if (argc <= 1)\n {\n stream_format(err_stream, \"usage: grep pattern [file ...]\\n\");\n return 0;\n }\n\n char *pattern = argv[1];\n\n if (argc <= 2)\n {\n grep(pattern, in_stream);\n return 0;\n }\n\n for (int i = 2; i < argc; i++)\n {\n Stream *stream = stream_open(argv[i], OPEN_READ);\n\n if (handle_has_error(stream))\n {\n handle_printf_error(stream, \"grep: cannot open %s\", argv[i]);\n stream_close(stream);\n\n return -1;\n }\n\n grep(pattern, stream);\n stream_close(stream);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.625363826751709, "alphanum_fraction": 0.625363826751709, "avg_line_length": 14.221518516540527, "blob_id": "c63b2b69ce1b5a0f3fdf977bcaf279ae0a1013f2", "content_id": "86ad81720b40aa7ab0bdfc0e5661257da49e4632", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2405, "license_type": "permissive", "max_line_length": 55, "num_lines": 158, "path": "/kernel/scheduling/Blocker.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <skift/Time.h>\n\n#include <libutils/Vector.h>\n\n#include \"kernel/node/Handle.h\"\n#include \"kernel/system/System.h\"\n\nstruct Task;\n\nenum BlockerResult\n{\n BLOCKER_UNBLOCKED,\n BLOCKER_TIMEOUT,\n};\n\nstruct Blocker\n{\n BlockerResult _result;\n TimeStamp _timeout;\n\n virtual ~Blocker() {}\n\n virtual bool can_unblock(struct Task *task)\n {\n __unused(task);\n return true;\n }\n\n virtual void on_unblock(struct Task *task)\n {\n __unused(task);\n }\n\n virtual void on_timeout(struct Task *task)\n {\n __unused(task);\n }\n};\n\nclass BlockerAccept : public Blocker\n{\nprivate:\n RefPtr<FsNode> _node;\n\npublic:\n BlockerAccept(RefPtr<FsNode> node) : _node(node)\n {\n }\n\n bool can_unblock(struct Task *task);\n\n void on_unblock(struct Task *task);\n};\n\nclass BlockerConnect : public Blocker\n{\nprivate:\n RefPtr<FsNode> _connection;\n\npublic:\n BlockerConnect(RefPtr<FsNode> connection)\n : _connection(connection)\n {\n }\n\n bool can_unblock(struct Task *task);\n};\n\nclass BlockerRead : public Blocker\n{\nprivate:\n FsHandle &_handle;\n\npublic:\n BlockerRead(FsHandle &handle)\n : _handle{handle}\n {\n }\n\n bool can_unblock(Task *task);\n\n void on_unblock(Task *task);\n};\n\nstruct Selected\n{\n int handle_index;\n RefPtr<FsHandle> handle;\n PollEvent events;\n};\n\nclass BlockerSelect : public Blocker\n{\nprivate:\n Vector<Selected> &_handles;\n Optional<Selected> _selected;\n\npublic:\n Optional<Selected> selected() { return _selected; }\n\n BlockerSelect(Vector<Selected> &handles)\n : _handles{handles}\n {\n }\n\n bool can_unblock(Task *task);\n\n void on_unblock(Task *task);\n};\n\nclass BlockerTime : public Blocker\n{\nprivate:\n Tick _wakeup_tick;\n\npublic:\n BlockerTime(Tick wakeup_tick)\n : _wakeup_tick(wakeup_tick)\n {\n }\n\n bool can_unblock(Task *task);\n};\n\nclass BlockerWait : public Blocker\n{\nprivate:\n Task *_task;\n int *_exit_value;\n\npublic:\n BlockerWait(Task *task, int *exit_value)\n : _task(task), _exit_value(exit_value)\n {\n }\n\n bool can_unblock(Task *task);\n\n void on_unblock(Task *task);\n};\n\nclass BlockerWrite : public Blocker\n{\nprivate:\n FsHandle &_handle;\n\npublic:\n BlockerWrite(FsHandle &handle)\n : _handle{handle}\n {\n }\n\n bool can_unblock(Task *task);\n\n void on_unblock(Task *task);\n};\n" }, { "alpha_fraction": 0.5654186606407166, "alphanum_fraction": 0.6048711538314819, "avg_line_length": 39.39024353027344, "blob_id": "4cba7912ebd6bea7e3ebb3303c08b708c268040c", "content_id": "2cfbf2a07cc921c8ae06bfd3c881d89f26dcf0f8", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4968, "license_type": "permissive", "max_line_length": 134, "num_lines": 123, "path": "/archs/x86_64/kernel/Paging.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nstruct __packed PageMappingLevel4Entry\n{\n bool present : 1; // Must be 1 to reference a PML-1\n bool writable : 1; // If 0, writes may not be allowed.\n bool user : 1; // If 0, user-mode accesses are not allowed\n bool write_thought : 1; // Page-level write-through\n bool cache : 1; // Page-level cache disable\n bool accessed : 1; // Indicates whether this entry has been used\n int zero0 : 6; // Ignored\n uint64_t physical_address : 36; // Physical address of a 4-KByte aligned PLM-1\n int zero1 : 15; // Ignored\n bool execute_disabled : 1; // If IA32_EFER.NXE = 1, Execute-disable\n};\n\nstruct __packed PageMappingLevel4\n{\n PageMappingLevel4Entry entries[512];\n};\n\nstatic inline size_t pml4_index(uintptr_t address)\n{\n return (address >> 39) & 0x1FF;\n}\n\nstatic_assert(sizeof(PageMappingLevel4Entry) == sizeof(uint64_t));\nstatic_assert(sizeof(PageMappingLevel4) == 4096);\n\nstruct __packed PageMappingLevel3Entry\n{\n bool present : 1; // Must be 1 to reference a PML-1\n bool writable : 1; // If 0, writes may not be allowed.\n bool user : 1; // If 0, user-mode accesses are not allowed\n bool write_thought : 1; // Page-level write-through\n bool cache : 1; // Page-level cache disable\n bool accessed : 1; // Indicates whether this entry has been used\n int zero0 : 1; // Ignored\n int size : 1; // Must be 0 otherwise, this entry maps a 1-GByte page.\n int zero1 : 4; // Ignored\n uint64_t physical_address : 36; // Physical address of a 4-KByte aligned PLM-1\n int zero2 : 15; // Ignored\n bool execute_disabled : 1; // If IA32_EFER.NXE = 1, Execute-disable\n};\n\nstruct __packed PageMappingLevel3\n{\n PageMappingLevel3Entry entries[512];\n};\n\nstatic inline size_t pml3_index(uintptr_t address)\n{\n return (address >> 30) & 0x1FF;\n}\n\nstatic_assert(sizeof(PageMappingLevel3Entry) == sizeof(uint64_t));\nstatic_assert(sizeof(PageMappingLevel3) == 4096);\n\nstruct __packed PageMappingLevel2Entry\n{\n bool present : 1; // Must be 1 to reference a PML-1\n bool writable : 1; // If 0, writes may not be allowed.\n bool user : 1; // If 0, user-mode accesses are not allowed\n bool write_thought : 1; // Page-level write-through\n bool cache : 1; // Page-level cache disable\n bool accessed : 1; // Indicates whether this entry has been used\n int zero0 : 1; // Ignored\n int size : 1; // Must be 0 otherwise, this entry maps a 2-MByte page.\n int zero1 : 4; // Ignored\n uint64_t physical_address : 36; // Physical address of a 4-KByte aligned PLM-1\n int zero2 : 15; // Ignored\n bool execute_disabled : 1; // If IA32_EFER.NXE = 1, Execute-disable\n};\n\nstruct __packed PageMappingLevel2\n{\n PageMappingLevel3Entry entries[512];\n};\n\nstatic inline size_t pml2_index(uintptr_t address)\n{\n return (address >> 21) & 0x1FF;\n}\n\nstatic_assert(sizeof(PageMappingLevel2Entry) == sizeof(uint64_t));\nstatic_assert(sizeof(PageMappingLevel2) == 4096);\n\nstruct __packed PageMappingLevel1Entry\n{\n bool present : 1; // Must be 1 to reference a PML-1\n bool writable : 1; // If 0, writes may not be allowed.\n bool user : 1; // If 0, user-mode accesses are not allowed\n bool write_thought : 1; // Page-level write-through\n bool cache : 1; // Page-level cache disable\n bool accessed : 1; // Indicates whether this entry has been used\n int dirty : 1; // Indicates whether software has accessed the 4-KByte page referenced by this entry\n int memory_type : 1; // Indirectly determines the memory type used to access the 4-KByte page referenced by this entry.\n int global : 1; // If CR4.PGE = 1, determines whether the translation is global.\n int zero0 : 3; // Ignored\n uint64_t physical_address : 36; // Physical address of a 4-KByte aligned PLM-1\n int zero1 : 10; // Ignored\n bool protection_key : 5; // If CR4.PKE = 1, determines the protection key of the page.\n bool execute_disabled : 1; // If IA32_EFER.NXE = 1, Execute-disable\n};\n\nstruct __packed PageMappingLevel1\n{\n PageMappingLevel3Entry entries[512];\n};\n\nstatic inline size_t pml1_index(uintptr_t address)\n{\n return (address >> 12) & 0x1FF;\n}\n\nstatic_assert(sizeof(PageMappingLevel1Entry) == sizeof(uint64_t));\nstatic_assert(sizeof(PageMappingLevel1) == 4096);\n\nextern \"C\" void paging_load_directory(uintptr_t directory);\n\nextern \"C\" void paging_invalidate_tlb();\n" }, { "alpha_fraction": 0.6327683329582214, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 21.125, "blob_id": "4371d28103f7babc41c253e85f49728fd6472c19", "content_id": "40b59a8b00799d1850b8582268cc5b2b314fad04", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 531, "license_type": "permissive", "max_line_length": 65, "num_lines": 24, "path": "/archs/x86_32/kernel/Interrupts.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nstruct __packed InterruptStackFrame\n{\n uint32_t gs, fs, es, ds;\n uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax;\n uint32_t intno, err;\n uint32_t eip, cs, eflags;\n};\n\nstruct __packed UserInterruptStackFrame\n{\n uint32_t gs, fs, es, ds;\n uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax;\n uint32_t intno, err;\n uint32_t eip, cs, eflags;\n uint32_t user_esp, ss;\n};\n\nvoid interrupts_dump_stackframe(InterruptStackFrame *stackframe);\n\nvoid interrupts_initialize();\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 11, "blob_id": "19d67587bed441893d66b1088cbed73cf3c0b150", "content_id": "89c6b5d07c8243ae37bb4b48d44a661e55ae5bd4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 60, "license_type": "permissive", "max_line_length": 23, "num_lines": 5, "path": "/archs/x86/kernel/RTC.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <skift/Time.h>\n\nTimeStamp rtc_now();\n" }, { "alpha_fraction": 0.42186087369918823, "alphanum_fraction": 0.47515809535980225, "avg_line_length": 26.674999237060547, "blob_id": "ddf281378a0f26080dc4c624e67013cbb8279b7d", "content_id": "f6991bb78f3059a2524c3ec6d869f89d6a652fc5", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1107, "license_type": "permissive", "max_line_length": 65, "num_lines": 40, "path": "/archs/x86_32/kernel/IDT.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libsystem/Logger.h>\n\n#define INTGATE 0x8e\n#define TRAPGATE 0xeF\n\n#define IDT_USER 0b01100000\n\n#define IDT_ENTRY_COUNT 256\n\nstruct __packed IDTDescriptor\n{\n uint16_t size;\n uint32_t offset;\n};\n\nstruct __packed IDTEntry\n{\n uint16_t offset0_15; // offset bits 0..15\n uint16_t selector; // a code segment selector in GDT or LDT\n uint8_t zero;\n uint8_t type_attr; // type and attributes\n uint16_t offset16_31; // offset bits 16..31\n};\n\n#define IDT_ENTRY(__offset, __selector, __type) \\\n (IDTEntry) \\\n { \\\n .offset0_15 = (uint16_t)((__offset)&0xffff), \\\n .selector = (__selector), \\\n .zero = 0, \\\n .type_attr = (__type), \\\n .offset16_31 = (uint16_t)(((__offset) >> 16) & 0xffff), \\\n }\n\nextern \"C\" void idt_flush(uint32_t);\n\nvoid idt_initialize();\n" }, { "alpha_fraction": 0.44117647409439087, "alphanum_fraction": 0.5036764740943909, "avg_line_length": 19.399999618530273, "blob_id": "681bc41249c4bed0a6b620d3eb302ac02f0edd22", "content_id": "5cca3edd73b62bfc5fff4b48c28619dfe95fef19", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 816, "license_type": "permissive", "max_line_length": 81, "num_lines": 40, "path": "/apps/utilities/uptime.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Syscalls.h>\n\n#include <libsystem/io/Stream.h>\n\n#include <stdio.h>\n\nint main(int argc, char const *argv[])\n{\n __unused(argc);\n __unused(argv);\n\n SystemStatus status{};\n hj_system_status(&status);\n\n ElapsedTime seconds = status.uptime;\n\n printf(\"Up \");\n\n if (seconds / 86400 > 0)\n {\n printf(\"%d day%s, \", seconds / 86400, (seconds / 86400) == 1 ? \"\" : \"s\");\n seconds %= 86400;\n }\n\n if (seconds / 3600 > 0)\n {\n printf(\"%d hour%s, \", seconds / 3600, (seconds / 3600) == 1 ? \"\" : \"s\");\n seconds %= 3600;\n }\n\n if (seconds / 60 > 0)\n {\n printf(\"%d minute%s, \", seconds / 60, (seconds / 60) == 1 ? \"\" : \"s\");\n seconds %= 60;\n }\n\n printf(\"%d second%s\\n\", seconds, seconds == 1 ? \"\" : \"s\");\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6821516156196594, "alphanum_fraction": 0.6821516156196594, "avg_line_length": 15.359999656677246, "blob_id": "6a00bbe02edc06b2c6529deae07d4d2b57442c6a", "content_id": "3cf1762abdb4ea68500d2ffaea8e08ef880f557b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 409, "license_type": "permissive", "max_line_length": 51, "num_lines": 25, "path": "/apps/panel/model/MenuEntry.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Icon.h>\n#include <libutils/String.h>\n#include <libutils/Vector.h>\n#include <libutils/json/Json.h>\n\nnamespace panel\n{\n\nstruct MenuEntry\n{\n String id;\n String name;\n String comment;\n RefPtr<Icon> icon;\n RefPtr<Bitmap> image;\n String command;\n\n MenuEntry(String id, const json::Value &value);\n\n static Vector<MenuEntry> load();\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 27.5, "blob_id": "130cfb21ad97d9d808eca39d3cc978202f0e80c1", "content_id": "7fc8e6fa20caff037de3578b01b0a64df8d1ae53", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 114, "license_type": "permissive", "max_line_length": 51, "num_lines": 4, "path": "/contribs/ffmpeg/install-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\ncp sources/ffprobe $SKIFT_SYSROOT/System/Utilities/\ncp sources/ffmpeg $SKIFT_SYSROOT/System/Utilities/\n" }, { "alpha_fraction": 0.6769230961799622, "alphanum_fraction": 0.692307710647583, "avg_line_length": 15.25, "blob_id": "0b174b0921cbf0424dbb73f0b628bbe1752f2183", "content_id": "e6264064c744fc86dbfa27ebb12050046ee42398", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 65, "license_type": "permissive", "max_line_length": 29, "num_lines": 4, "path": "/libraries/libc/errno.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <errno.h>\n#include <libsystem/Result.h>\n\nint errno = 0;\n" }, { "alpha_fraction": 0.6243094205856323, "alphanum_fraction": 0.6252301931381226, "avg_line_length": 19.129629135131836, "blob_id": "a11d125167d820bb37d2c7753358ce92ba2b243b", "content_id": "9706540eac5f9137dde5efe51b4b26be91aecf1d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1086, "license_type": "permissive", "max_line_length": 65, "num_lines": 54, "path": "/libraries/libsystem/io_new/Directory.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io_new/Directory.h>\n\nnamespace System\n{\n\nvoid Directory::read_entries()\n{\n DirectoryEntry entry;\n\n auto read_result = _handle.read(&entry, sizeof(entry));\n while (read_result.success() && *read_result > 0)\n {\n _entries.push_back({entry.name, entry.stat});\n read_result = _handle.read(&entry, sizeof(entry));\n }\n\n _entries.sort([](auto &left, auto &right) {\n return strcmp(left.name.cstring(), right.name.cstring());\n });\n}\n\nDirectory::Directory(const char *path)\n : _handle(path, OPEN_READ | OPEN_DIRECTORY),\n _path{Path::parse(path)}\n{\n read_entries();\n}\n\nDirectory::Directory(String path)\n : _handle(path, OPEN_READ | OPEN_DIRECTORY),\n _path{Path::parse(path)}\n{\n read_entries();\n}\n\nDirectory::Directory(const Path &path)\n : _handle(path.string(), OPEN_READ | OPEN_DIRECTORY),\n _path{path}\n{\n read_entries();\n}\n\nDirectory::Directory(System::Handle &&handle)\n : _handle{move(handle)}\n{\n read_entries();\n}\n\nbool Directory::exist()\n{\n return _handle.valid();\n}\n\n} // namespace System" }, { "alpha_fraction": 0.7570754885673523, "alphanum_fraction": 0.7570754885673523, "avg_line_length": 23.941177368164062, "blob_id": "2543d623d3d7d5ffb6946bb0ebc410e9268a6c03", "content_id": "d0b20ec43170ae1b5d11e6f6c55f3d180e8cd76b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 424, "license_type": "permissive", "max_line_length": 59, "num_lines": 17, "path": "/libraries/abi/Paths.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define DEVICE_PATH \"/Devices\"\n\n#define KEYBOARD_DEVICE_PATH DEVICE_PATH \"/keyboard\"\n\n#define MOUSE_DEVICE_PATH DEVICE_PATH \"/mouse\"\n\n#define TEXTMODE_DEVICE_PATH DEVICE_PATH \"/textmode\"\n\n#define FRAMEBUFFER_DEVICE_PATH DEVICE_PATH \"/framebuffer\"\n\n#define NETWORK_DEVICE_PATH DEVICE_PATH \"/network\"\n\n#define SERIAL_DEVICE_PATH DEVICE_PATH \"/serial\"\n\n#define UNIX_DEVICE_PATH(__device) DEVICE_PATH \"/\" __device\n" }, { "alpha_fraction": 0.5621970891952515, "alphanum_fraction": 0.5638126134872437, "avg_line_length": 21.527273178100586, "blob_id": "015e53fa94a74a80f664057ef8af017de0c54431", "content_id": "6089d98dee8e8da7a903e8b3479cd2d92cba5793", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1238, "license_type": "permissive", "max_line_length": 77, "num_lines": 55, "path": "/libraries/libwidget/VScroll.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Container.h>\n#include <libwidget/ScrollBar.h>\n#include <libwidget/Widget.h>\n\nclass VScroll : public Widget\n{\nprivate:\n Container *_host = nullptr;\n ScrollBar *_scrollbar = nullptr;\n\npublic:\n Container *host() { return _host; }\n\n VScroll(Widget *parent) : Widget(parent)\n {\n _host = new Container(this);\n\n _scrollbar = new ScrollBar(this);\n _scrollbar->flags(Widget::NOT_AFFECTED_BY_SCROLL);\n\n _scrollbar->on(Event::VALUE_CHANGE, [this](auto) {\n scroll({scroll().x(), _scrollbar->value()});\n should_repaint();\n });\n }\n\n ~VScroll()\n {\n }\n\n void do_layout() override\n {\n int content_height = _host->size().y();\n\n _host->container(content().take_top(content_height));\n _scrollbar->container(content().take_right(ScrollBar::SIZE));\n _scrollbar->update(content_height, content().height(), scroll().x());\n }\n\n void event(Event *event) override\n {\n if (event->type == Event::MOUSE_SCROLL)\n {\n event->accepted = true;\n _scrollbar->dispatch_event(event);\n }\n }\n\n Vec2i size() override\n {\n return {_host->size().x(), 0};\n }\n};" }, { "alpha_fraction": 0.6257941722869873, "alphanum_fraction": 0.6318297386169434, "avg_line_length": 22.147058486938477, "blob_id": "59f6750c859903987150772b7fae928389869730", "content_id": "7d077d7dfee528e0b7d28fae402b98efe5f187e0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3148, "license_type": "permissive", "max_line_length": 88, "num_lines": 136, "path": "/libraries/libsystem/unicode/UnicodeString.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <string.h>\n\n#include <libsystem/Logger.h>\n#include <libsystem/math/MinMax.h>\n#include <libsystem/unicode/UnicodeString.h>\n#include <libsystem/utils/BufferBuilder.h>\n\nstatic void unicode_string_ensure_capacity(UnicodeString *string, size_t size)\n{\n size = MAX(16, size);\n\n if (string->allocated >= size)\n {\n return;\n }\n\n if (string->buffer)\n {\n string->buffer = (Codepoint *)realloc(string->buffer, size * sizeof(Codepoint));\n }\n else\n {\n string->buffer = (Codepoint *)calloc(size, sizeof(Codepoint));\n }\n\n string->allocated = size;\n}\n\nUnicodeString *unicode_string_create(size_t size)\n{\n UnicodeString *string = __create(UnicodeString);\n\n unicode_string_ensure_capacity(string, size);\n string->used = 0;\n\n return string;\n}\n\nvoid unicode_string_destroy(UnicodeString *string)\n{\n free(string->buffer);\n free(string);\n}\n\nUnicodeString *unicode_string_clone(UnicodeString *original)\n{\n UnicodeString *string = __create(UnicodeString);\n\n unicode_string_ensure_capacity(string, original->used);\n memcpy(string->buffer, original->buffer, original->used * sizeof(Codepoint));\n string->used = original->used;\n\n return string;\n}\n\nvoid unicode_string_copy(UnicodeString *source, UnicodeString *destination)\n{\n unicode_string_ensure_capacity(destination, source->used);\n memcpy(destination->buffer, source->buffer, source->used * sizeof(Codepoint));\n destination->used = source->used;\n}\n\nbool unicode_string_equals(UnicodeString *left, UnicodeString *right)\n{\n if (left->used != right->used)\n {\n return false;\n }\n\n for (size_t i = 0; i < left->used; i++)\n {\n if (left->buffer[i] != right->buffer[i])\n {\n return false;\n }\n }\n\n return true;\n}\n\nvoid unicode_string_insert(UnicodeString *string, Codepoint codepoint, size_t where)\n{\n size_t needed = MAX(string->used, where) + 1;\n\n if (needed > string->allocated)\n {\n size_t new_allocated = MAX(string->allocated + string->allocated / 4, needed);\n unicode_string_ensure_capacity(string, new_allocated);\n }\n\n for (size_t i = needed - 1; i > where; i--)\n {\n string->buffer[i] = string->buffer[i - 1];\n }\n\n string->buffer[where] = codepoint;\n\n string->used = needed;\n}\n\nvoid unicode_string_remove(UnicodeString *string, size_t where)\n{\n if (string->used > 0)\n {\n for (size_t i = where; i < string->used; i++)\n {\n string->buffer[i] = string->buffer[i + 1];\n }\n\n string->used--;\n }\n}\n\nsize_t unicode_string_length(UnicodeString *string)\n{\n return string->used;\n}\n\nchar *unicode_string_as_cstring(UnicodeString *string)\n{\n BufferBuilder *builder = buffer_builder_create(string->used + string->used / 4);\n\n for (size_t i = 0; i < string->used; i++)\n {\n uint8_t utf8[5];\n size_t size = codepoint_to_utf8(string->buffer[i], utf8);\n buffer_builder_append_str_size(builder, (const char *)utf8, size);\n }\n\n return buffer_builder_finalize(builder);\n}\n\nvoid unicode_string_clear(UnicodeString *string)\n{\n string->used = 0;\n}\n" }, { "alpha_fraction": 0.618852436542511, "alphanum_fraction": 0.6577869057655334, "avg_line_length": 16.122806549072266, "blob_id": "53db054f7429e816b0cb620c7175820a74652c35", "content_id": "96c0cc47337b2ad83951024b714893aa26652849", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 976, "license_type": "permissive", "max_line_length": 32, "num_lines": 57, "path": "/libraries/abi/Filesystem.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\n#define FILE_NAME_LENGTH (64)\n#define PATH_LENGTH (512)\n#define PATH_DEPTH (16)\n#define PATH_SEPARATOR '/'\n\nenum Whence\n{\n WHENCE_START,\n WHENCE_HERE,\n WHENCE_END,\n};\n\nenum FileType\n{\n FILE_TYPE_UNKNOWN,\n\n FILE_TYPE_REGULAR,\n FILE_TYPE_DEVICE,\n FILE_TYPE_DIRECTORY,\n FILE_TYPE_PIPE,\n FILE_TYPE_SOCKET,\n FILE_TYPE_CONNECTION,\n FILE_TYPE_TERMINAL,\n};\n\n#define OPEN_READ (1 << 0)\n#define OPEN_WRITE (1 << 1)\n#define OPEN_CREATE (1 << 2)\n#define OPEN_APPEND (1 << 3)\n#define OPEN_TRUNC (1 << 4)\n#define OPEN_BUFFERED (1 << 5)\n#define OPEN_STREAM (1 << 6)\n#define OPEN_DIRECTORY (1 << 7)\n#define OPEN_SOCKET (1 << 8)\n#define OPEN_CLIENT (1 << 9)\n#define OPEN_SERVER (1 << 10)\n\ntypedef unsigned int OpenFlag;\n\ntypedef uint64_t size64_t;\ntypedef int64_t ssize64_t;\n\nstruct FileState\n{\n size_t size;\n FileType type;\n};\n\nstruct DirectoryEntry\n{\n char name[FILE_NAME_LENGTH];\n FileState stat;\n};\n" }, { "alpha_fraction": 0.5926400423049927, "alphanum_fraction": 0.6281582117080688, "avg_line_length": 25.77450942993164, "blob_id": "3c1db62e7a11db52409824be89b2d3021e292073", "content_id": "50633b27f3d8733ffad39cf13c574b7a237c4c04", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5462, "license_type": "permissive", "max_line_length": 163, "num_lines": 204, "path": "/archs/x86_32/kernel/x86_32.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/core/Plugs.h>\n\n#include \"archs/VirtualMemory.h\"\n#include \"archs/x86/kernel/COM.h\"\n#include \"archs/x86/kernel/CPUID.h\"\n#include \"archs/x86/kernel/FPU.h\"\n#include \"archs/x86/kernel/PIC.h\"\n#include \"archs/x86/kernel/PIT.h\"\n#include \"archs/x86/kernel/RTC.h\"\n#include \"archs/x86_32/kernel/ACPI.h\"\n#include \"archs/x86_32/kernel/GDT.h\"\n#include \"archs/x86_32/kernel/IDT.h\"\n#include \"archs/x86_32/kernel/Interrupts.h\"\n#include \"archs/x86_32/kernel/LAPIC.h\"\n#include \"archs/x86_32/kernel/Power.h\"\n#include \"archs/x86_32/kernel/x86_32.h\"\n\n#include \"kernel/firmware/SMBIOS.h\"\n#include \"kernel/graphics/EarlyConsole.h\"\n#include \"kernel/graphics/Graphics.h\"\n#include \"kernel/system/System.h\"\n\nvoid arch_disable_interrupts() { cli(); }\n\nvoid arch_enable_interrupts() { sti(); }\n\nvoid arch_halt() { hlt(); }\n\nvoid arch_yield() { asm(\"int $127\"); }\n\nvoid arch_save_context(Task *task)\n{\n fpu_save_context(task);\n}\n\nvoid arch_load_context(Task *task)\n{\n fpu_load_context(task);\n set_kernel_stack((uintptr_t)task->kernel_stack + PROCESS_STACK_SIZE);\n}\n\nvoid arch_task_go(Task *task)\n{\n if (task->user)\n {\n UserInterruptStackFrame stackframe = {};\n\n stackframe.user_esp = task->user_stack_pointer;\n\n stackframe.eflags = 0x202;\n stackframe.eip = (uintptr_t)task->entry_point;\n stackframe.ebp = 0;\n\n stackframe.cs = 0x1b;\n stackframe.ds = 0x23;\n stackframe.es = 0x23;\n stackframe.fs = 0x23;\n stackframe.gs = 0x23;\n stackframe.ss = 0x23;\n\n task_kernel_stack_push(task, &stackframe, sizeof(UserInterruptStackFrame));\n }\n else\n {\n InterruptStackFrame stackframe = {};\n\n stackframe.eflags = 0x202;\n stackframe.eip = (uintptr_t)task->entry_point;\n stackframe.ebp = 0;\n\n stackframe.cs = 0x08;\n stackframe.ds = 0x10;\n stackframe.es = 0x10;\n stackframe.fs = 0x10;\n stackframe.gs = 0x10;\n\n task_kernel_stack_push(task, &stackframe, sizeof(InterruptStackFrame));\n }\n}\n\nsize_t arch_debug_write(const void *buffer, size_t size) { return com_write(COM1, buffer, size); }\n\nTimeStamp arch_get_time() { return rtc_now(); }\n\nextern \"C\" void arch_main(void *info, uint32_t magic)\n{\n __plug_initialize();\n\n com_initialize(COM1);\n com_initialize(COM2);\n com_initialize(COM3);\n com_initialize(COM4);\n\n auto handover = handover_initialize(info, magic);\n\n graphic_early_initialize(handover);\n\n if (handover->memory_usable < 127 * 1024)\n {\n system_panic(\"No enough memory (%uKio)!\", handover->memory_usable / 1024);\n }\n\n gdt_initialize();\n idt_initialize();\n pic_initialize();\n fpu_initialize();\n pit_initialize(1000);\n\n acpi_initialize(handover);\n //lapic_initialize();\n // smbios::EntryPoint *smbios_entrypoint = smbios::find({0xF0000, 65536});\n //\n // if (smbios_entrypoint)\n // {\n // logger_info(\"Found SMBIOS entrypoint at %08x (Version %d.%02d)\", smbios_entrypoint, smbios_entrypoint->major_version, smbios_entrypoint->major_version);\n //\n // smbios_entrypoint->iterate([&](smbios::Header *table) {\n // logger_info(\" - %s (Type=%d, StringCount=%d) \", table->name(), table->type, table->string_table_lenght());\n //\n // for (size_t i = 1; i < table->string_table_lenght(); i++)\n // {\n // logger_info(\" - %s\", table->string(i));\n // }\n //\n // return Iteration::CONTINUE;\n // });\n // }\n\n system_main(handover);\n}\n\n__no_return void arch_reboot()\n{\n early_console_enable();\n logger_info(\"Rebooting...\");\n\n x86::reboot_8042();\n x86::reboot_triple_fault();\n\n logger_info(\"Failed to reboot: Halting!\");\n system_stop();\n}\n\n__no_return void arch_shutdown()\n{\n early_console_enable();\n logger_info(\"Shutting down...\");\n\n x86::shutdown_virtual_machines();\n x86::shutdown_acpi();\n\n logger_error(\"Failed to shutdown: Halting!\");\n system_stop();\n}\n\nvoid arch_panic_dump()\n{\n cpuid_dump();\n}\n\nstruct Stackframe\n{\n Stackframe *ebp;\n uint32_t eip;\n};\n\nvoid backtrace_internal(uint32_t ebp)\n{\n bool empty = true;\n Stackframe *stackframe = reinterpret_cast<Stackframe *>(ebp);\n\n while (stackframe)\n {\n empty = false;\n stream_format(log_stream, \"\\t%08x\\n\", stackframe->eip);\n stackframe = stackframe->ebp;\n }\n\n if (empty)\n {\n stream_format(log_stream, \"\\t[EMPTY]\\n\");\n }\n}\n\nvoid arch_dump_stack_frame(void *sf)\n{\n auto stackframe = reinterpret_cast<InterruptStackFrame *>(sf);\n\n stream_format(out_stream, \"\\tCS=%04x DS=%04x ES=%04x FS=%04x GS=%04x\\n\", stackframe->cs, stackframe->ds, stackframe->es, stackframe->fs, stackframe->gs);\n stream_format(out_stream, \"\\tEAX=%08x EBX=%08x ECX=%08x EDX=%08x\\n\", stackframe->eax, stackframe->ebx, stackframe->ecx, stackframe->edx);\n stream_format(out_stream, \"\\tEDI=%08x ESI=%08x EBP=%08x ESP=%08x\\n\", stackframe->edi, stackframe->esi, stackframe->ebp, stackframe->esp);\n stream_format(out_stream, \"\\tINT=%08x ERR=%08x EIP=%08x FLG=%08x\\n\", stackframe->intno, stackframe->err, stackframe->eip, stackframe->eflags);\n\n stream_format(out_stream, \"\\tCR0=%08x CR2=%08x CR3=%08x CR4=%08x\\n\", CR0(), CR2(), CR3(), CR4());\n\n stream_format(out_stream, \"\\n\\tBacktrace:\\n\");\n backtrace_internal(stackframe->ebp);\n}\n\nvoid arch_backtrace()\n{\n backtrace_internal(EBP());\n}\n" }, { "alpha_fraction": 0.6721311211585999, "alphanum_fraction": 0.6918032765388489, "avg_line_length": 29.5, "blob_id": "4f81ef441cf490d0ed548877e5db2e6466572989", "content_id": "dcab7a474b678b586048bae68be48b7b6c0211b3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 305, "license_type": "permissive", "max_line_length": 81, "num_lines": 10, "path": "/contribs/ffmpeg/build-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\ncd sources\nsysroot=\"$PWD/../../build/sysroot\"\nexport CPPFLAGS=\"-I$sysroot/System/Includes\"\nexport LDFLAGS=\"-L$sysroot/System/Libraries -static -lc\"\n./configure \\\n --enable-cross-compile --target-os=minix \\\n --cross_prefix=i686-pc-skift- --arch=i686 --prefix=./install && make -j $(nproc)\ncd ..\n" }, { "alpha_fraction": 0.48806774616241455, "alphanum_fraction": 0.5134719014167786, "avg_line_length": 31.475000381469727, "blob_id": "87594e87260472f7f10e1dfe3c34f8fca62ae5de", "content_id": "4362c600370828089aa715f5f9dab751a7b8402d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1299, "license_type": "permissive", "max_line_length": 113, "num_lines": 40, "path": "/apps/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "define APP_TEMPLATE =\n\n$(1)_BINARY = $(BUILD_DIRECTORY_APPS)/$($(1)_NAME)/$($(1)_NAME)\n\n$(1)_SOURCES = $$(wildcard apps/$($(1)_NAME)/*.cpp) \\\n\t\t\t $$(wildcard apps/$($(1)_NAME)/*/*.cpp)\n\n$(1)_ASSETS := $$(wildcard apps/$($(1)_NAME)/*.markup) \\\n\t\t\t $$(wildcard apps/$($(1)_NAME)/*.json) \\\n\t\t\t $$(wildcard apps/$($(1)_NAME)/*.png)\n\n$(1)_ASSETS := $$(patsubst apps/$($(1)_NAME)/%, $(BUILD_DIRECTORY_APPS)/$($(1)_NAME)/%, $$($(1)_ASSETS))\n\n$(1)_OBJECTS = $$(patsubst apps/%.cpp, $$(CONFIG_BUILD_DIRECTORY)/apps/%.o, $$($(1)_SOURCES))\n\nTARGETS += $$($(1)_BINARY) $$($(1)_ASSETS)\nOBJECTS += $$($(1)_OBJECTS)\n\n$(BUILD_DIRECTORY_APPS)/$($(1)_NAME)/%: apps/$($(1)_NAME)/%\n\t$$(DIRECTORY_GUARD)\n\tcp $$< $$@\n\n$$($(1)_BINARY): $$($(1)_OBJECTS) $$(patsubst %, $$(BUILD_DIRECTORY_LIBS)/lib%.a, $$($(1)_LIBS) system c) $(CRTS)\n\t$$(DIRECTORY_GUARD)\n\t@echo [$(1)] [LD] $($(1)_NAME)\n\t@$(CXX) $(LDFLAGS) -o $$@ $$($(1)_OBJECTS) $$(patsubst %, -l%, $$($(1)_LIBS)) -lsystem\n\t@if $(CONFIG_STRIP); then \\\n\t\techo [$(1)] [STRIP] $($(1)_NAME); \\\n\t\t$(STRIP) $$@; \\\n\tfi\n\n$$(CONFIG_BUILD_DIRECTORY)/apps/$$($(1)_NAME)/%.o: apps/$$($(1)_NAME)/%.cpp\n\t$$(DIRECTORY_GUARD)\n\t@echo [$(1)] [CXX] $$<\n\t@$(CXX) $(CXXFLAGS) -c -o $$@ $$<\n\nendef\n\n-include apps/*/.build.mk\n$(foreach app, $(APPS), $(eval $(call APP_TEMPLATE,$(app))))\n" }, { "alpha_fraction": 0.4576951265335083, "alphanum_fraction": 0.45988330245018005, "avg_line_length": 20.146530151367188, "blob_id": "c39c56724095c23bd9fcda597cf9a80dadfba088", "content_id": "520a2ea3017d12a381bd45a4f64d202d6010444f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8226, "license_type": "permissive", "max_line_length": 93, "num_lines": 389, "path": "/libraries/libutils/Path.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Filesystem.h>\n\n#include <libutils/Scanner.h>\n#include <libutils/String.h>\n#include <libutils/StringBuilder.h>\n#include <libutils/Vector.h>\n\nstruct Path\n{\nprivate:\n bool _absolute = false;\n Vector<String> _elements{};\n\npublic:\n static constexpr int PARENT_SHORTHAND = 1; // .... -> ../../..\n\n bool absolute() const { return _absolute; }\n\n bool relative() const { return !_absolute; }\n\n size_t length() const { return _elements.count(); }\n\n static Path parse(const String &string, int flags = 0)\n {\n return parse(string.cstring(), string.length(), flags);\n }\n\n static Path parse(const char *path, int flags = 0)\n {\n return parse(path, strlen(path), flags);\n }\n\n static Path parse(const char *path, size_t size, int flags)\n {\n StringScanner scan{path, size};\n\n bool absolute = false;\n\n if (scan.skip(PATH_SEPARATOR))\n {\n absolute = true;\n }\n\n auto parse_element = [](auto &scan) {\n StringBuilder builder{};\n\n while (!scan.skip(PATH_SEPARATOR) &&\n scan.do_continue())\n {\n builder.append(scan.current());\n scan.foreward();\n }\n\n return builder.finalize();\n };\n\n auto parse_shorthand = [](auto &scan) {\n Vector<String> elements{};\n\n scan.skip_word(\"..\");\n elements.push(\"..\");\n\n while (scan.skip('.'))\n {\n elements.push(\"..\");\n }\n\n scan.skip('/');\n\n return move(elements);\n };\n\n Vector<String> elements{};\n\n while (scan.do_continue())\n {\n if ((flags & PARENT_SHORTHAND) && scan.current_is_word(\"..\"))\n {\n elements.push_back_many(parse_shorthand(scan));\n }\n else\n {\n auto el = parse_element(scan);\n\n if (el.length() > 0)\n {\n elements.push_back(move(el));\n }\n }\n }\n\n return {absolute, move(elements)};\n }\n\n static Path join(String left, String right)\n {\n return join(parse(left), parse(right));\n }\n\n static Path join(Path &&left, String right)\n {\n return join(left, parse(right));\n }\n\n static Path join(String left, Path &&right)\n {\n return join(parse(left), right);\n }\n\n static Path join(Path &left, String right)\n {\n return join(left, parse(right));\n }\n\n static Path join(String left, Path &right)\n {\n return join(parse(left), right);\n }\n\n static Path join(Path &&left, Path &&right)\n {\n return join(left, right);\n }\n\n static Path join(Path &left, Path &&right)\n {\n return join(left, right);\n }\n\n static Path join(Path &&left, Path &right)\n {\n return join(left, right);\n }\n\n static Path join(Path &left, Path &right)\n {\n Vector<String> combined_elements{};\n\n combined_elements.push_back_many(left._elements);\n combined_elements.push_back_many(right._elements);\n\n return {left.absolute(), move(combined_elements)};\n }\n\n Path()\n {\n }\n\n Path(const Path &other) : _absolute{other.absolute()}, _elements{other._elements}\n {\n }\n\n Path(bool absolute, Vector<String> &&elements) : _absolute(absolute), _elements(elements)\n {\n }\n\n Path(Path &&other)\n {\n swap(_absolute, other._absolute);\n swap(_elements, other._elements);\n }\n\n Path &operator=(const Path &other)\n {\n if (this != &other)\n {\n _absolute = other.absolute();\n _elements = other._elements;\n }\n\n return *this;\n }\n\n Path &operator=(Path &&other)\n {\n if (this != &other)\n {\n swap(_absolute, other._absolute);\n swap(_elements, other._elements);\n }\n\n return *this;\n }\n\n String operator[](size_t index) const\n {\n return _elements[index];\n }\n\n bool operator!=(const Path &other) const\n {\n return !(*this == other);\n }\n\n bool operator==(const Path &other) const\n {\n if (this == &other)\n {\n return true;\n }\n\n if (_absolute != other._absolute)\n {\n return false;\n }\n\n return _elements == other._elements;\n }\n\n Path normalized()\n {\n Vector<String> stack{};\n\n _elements.foreach ([&](auto &element) {\n if (element == \"..\" && stack.count() > 0)\n {\n stack.pop_back();\n }\n else if (_absolute && element == \"..\")\n {\n if (stack.count() > 0)\n {\n stack.pop_back();\n }\n }\n else if (element != \".\")\n {\n stack.push_back(element);\n }\n\n return Iteration::CONTINUE;\n });\n\n return {_absolute, move(stack)};\n }\n\n String basename() const\n {\n if (length() > 0)\n {\n return _elements.peek_back();\n }\n else\n {\n if (_absolute)\n {\n return \"/\";\n }\n else\n {\n return \"\";\n }\n }\n }\n\n String basename_without_extension() const\n {\n StringBuilder builder{basename().length()};\n\n StringScanner scan{basename().cstring(), basename().length()};\n\n // It's not a file extention it's an hidden file.\n if (scan.current_is(\".\"))\n {\n builder.append(scan.current());\n scan.foreward();\n }\n\n while (!scan.current_is(\".\") && scan.do_continue())\n {\n builder.append(scan.current());\n scan.foreward();\n }\n\n return builder.finalize();\n }\n\n String dirname() const\n {\n StringBuilder builder{};\n\n if (_absolute)\n {\n builder.append(PATH_SEPARATOR);\n }\n else if (_elements.count() <= 1)\n {\n builder.append(\".\");\n }\n\n if (_elements.count() >= 2)\n {\n for (size_t i = 0; i < _elements.count() - 1; i++)\n {\n builder.append(_elements[i]);\n\n if (i != _elements.count() - 2)\n {\n builder.append(PATH_SEPARATOR);\n }\n }\n }\n\n return builder.finalize();\n }\n\n Path dirpath() const\n {\n Vector<String> stack{};\n\n if (length() > 0)\n {\n for (size_t i = 0; i < length() - 1; i++)\n {\n stack.push_back(_elements[i]);\n }\n }\n\n return {_absolute, move(stack)};\n }\n\n String extension() const\n {\n auto filename = basename();\n\n StringBuilder builder{filename.length()};\n\n StringScanner scan{filename.cstring(), filename.length()};\n\n // It's not a file extention it's an hidden file.\n if (scan.current_is(\".\"))\n {\n scan.foreward();\n }\n\n while (!scan.current_is(\".\") &&\n scan.do_continue())\n {\n scan.foreward();\n }\n\n while (scan.do_continue())\n {\n builder.append(scan.current());\n scan.foreward();\n }\n\n return builder.finalize();\n }\n\n Path parent(size_t index) const\n {\n Vector<String> stack{};\n\n if (index <= length())\n {\n for (size_t i = 0; i <= index; i++)\n {\n stack.push_back(_elements[i]);\n }\n }\n\n return {_absolute, move(stack)};\n }\n\n String string() const\n {\n StringBuilder builder{};\n\n if (_absolute)\n {\n builder.append(PATH_SEPARATOR);\n }\n\n for (size_t i = 0; i < _elements.count(); i++)\n {\n builder.append(_elements[i]);\n\n if (i != _elements.count() - 1)\n {\n builder.append(PATH_SEPARATOR);\n }\n }\n\n return builder.finalize();\n }\n};\n" }, { "alpha_fraction": 0.5642057061195374, "alphanum_fraction": 0.5777075290679932, "avg_line_length": 22.052980422973633, "blob_id": "71542bd623e57c315a5502b74f1170e7556ca3fe", "content_id": "7d8fd3fbcff1675405e53d31a7f18668ff8a6ba2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3481, "license_type": "permissive", "max_line_length": 96, "num_lines": 151, "path": "/libraries/libwidget/Button.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n\n#include <libwidget/Button.h>\n#include <libwidget/IconPanel.h>\n#include <libwidget/Image.h>\n#include <libwidget/Label.h>\n\nvoid Button::paint(Painter &painter, const Recti &rectangle)\n{\n __unused(rectangle);\n\n if (enabled())\n {\n if (_style == OUTLINE)\n {\n painter.draw_rectangle_rounded(bound(), 4, 1, color(THEME_BORDER));\n }\n else if (_style == FILLED)\n {\n painter.fill_rectangle_rounded(bound(), 4, color(THEME_ACCENT));\n }\n\n if (_mouse_over)\n {\n painter.fill_rectangle_rounded(bound(), 4, color(THEME_FOREGROUND).with_alpha(0.1));\n }\n\n if (_mouse_press)\n {\n painter.fill_rectangle_rounded(bound(), 4, color(THEME_FOREGROUND).with_alpha(0.1));\n }\n }\n}\n\nvoid Button::event(Event *event)\n{\n if (event->type == Event::MOUSE_ENTER)\n {\n _mouse_over = true;\n\n should_repaint();\n event->accepted = true;\n }\n else if (event->type == Event::MOUSE_LEAVE)\n {\n _mouse_over = false;\n\n should_repaint();\n event->accepted = true;\n }\n else if (event->type == Event::MOUSE_BUTTON_PRESS)\n {\n _mouse_press = true;\n\n should_repaint();\n event->accepted = true;\n }\n else if (event->type == Event::MOUSE_BUTTON_RELEASE)\n {\n _mouse_press = false;\n\n Event action_event = {};\n action_event.type = Event::ACTION;\n dispatch_event(&action_event);\n\n should_repaint();\n event->accepted = true;\n }\n else if (event->type == Event::WIDGET_DISABLE)\n {\n _mouse_over = false;\n _mouse_press = false;\n }\n}\n\nButton::Button(Widget *parent, Style style)\n : Widget(parent),\n _style(style)\n{\n layout(HFLOW(0));\n insets(Insetsi(0, 6));\n min_height(32);\n flags(Widget::GREEDY);\n}\n\nButton::Button(Widget *parent, Style style, RefPtr<Icon> icon)\n : Button(parent, style)\n{\n layout(STACK());\n insets(Insetsi(6));\n min_width(32);\n flags(Widget::GREEDY | Widget::SQUARE);\n\n auto icon_panel = new IconPanel(this, icon);\n\n if (style == FILLED)\n {\n icon_panel->color(THEME_FOREGROUND, Colors::WHITE);\n }\n}\n\nButton::Button(Widget *parent, Style style, String text)\n : Button(parent, style)\n{\n layout(STACK());\n insets(Insetsi(0, 6));\n min_width(64);\n\n auto label = new Label(this, text, Anchor::CENTER);\n if (style == FILLED)\n {\n label->color(THEME_FOREGROUND, Colors::WHITE);\n }\n}\n\nButton::Button(Widget *parent, Style style, RefPtr<Icon> icon, String text)\n : Button(parent, style)\n{\n insets(Insetsi(0, 0, 6, 10));\n min_width(64);\n\n auto icon_panel = new IconPanel(this, icon);\n icon_panel->insets(Insetsi(0, 0, 0, 4));\n\n auto label = new Label(this, text);\n\n if (style == FILLED)\n {\n label->color(THEME_FOREGROUND, Colors::WHITE);\n icon_panel->color(THEME_FOREGROUND, Colors::WHITE);\n }\n}\n\nButton::Button(Widget *parent, Style style, RefPtr<Bitmap> image, String text)\n : Button(parent, style)\n{\n insets(Insetsi(4, 4, 6, 10));\n min_width(64);\n\n auto image_panel = new Image(this, image, BitmapScaling::FIT);\n image_panel->outsets(Insetsi(0, 0, 0, 8));\n image_panel->min_width(36);\n image_panel->min_height(36);\n\n auto label = new Label(this, text);\n\n if (style == FILLED)\n {\n label->color(THEME_FOREGROUND, Colors::WHITE);\n }\n}\n" }, { "alpha_fraction": 0.5838022828102112, "alphanum_fraction": 0.5865607261657715, "avg_line_length": 20.074419021606445, "blob_id": "4add1ea910fdd837d376a6c9da51c819317efdca", "content_id": "84c1b23313c2cfbdacf90f4512762db909e97840", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9063, "license_type": "permissive", "max_line_length": 100, "num_lines": 430, "path": "/libraries/libsystem/io/Stream.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <assert.h>\n#include <skift/Printf.h>\n#include <string.h>\n\n#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Stream.h>\n#include <libsystem/io/Stream_internal.h>\n#include <libsystem/math/MinMax.h>\n\nStream *_in_stream = nullptr;\nStream *_out_stream = nullptr;\nStream *_err_stream = nullptr;\nStream *_log_stream = nullptr;\n\nStream *__stream_get_in_stream()\n{\n if (_in_stream == nullptr)\n {\n _in_stream = stream_open_handle(0, OPEN_READ);\n }\n\n return _in_stream;\n}\n\nStream *__stream_get_out_stream()\n{\n if (_out_stream == nullptr)\n {\n _out_stream = stream_open_handle(1, OPEN_WRITE | OPEN_BUFFERED);\n }\n\n return _out_stream;\n}\n\nStream *__stream_get_err_stream()\n{\n if (_err_stream == nullptr)\n {\n _err_stream = stream_open_handle(2, OPEN_WRITE | OPEN_BUFFERED);\n }\n\n return _err_stream;\n}\n\nStream *__stream_get_log_stream()\n{\n if (_log_stream == nullptr)\n {\n _log_stream = stream_open_handle(3, OPEN_WRITE | OPEN_BUFFERED);\n }\n\n return _log_stream;\n}\n\nstatic void stream_initialize(Stream *stream)\n{\n if (handle_has_flags(stream, OPEN_BUFFERED | OPEN_WRITE))\n {\n stream->write_mode = STREAM_BUFFERED_LINE;\n stream->write_buffer = malloc(STREAM_BUFFER_SIZE);\n }\n\n if (handle_has_flags(stream, OPEN_BUFFERED | OPEN_READ))\n {\n stream->read_mode = STREAM_BUFFERED_BLOCK;\n stream->read_buffer = malloc(STREAM_BUFFER_SIZE);\n }\n}\n\nStream *stream_open(const char *path, OpenFlag flags)\n{\n Stream *stream = __create(Stream);\n\n __plug_handle_open(HANDLE(stream), path, flags | OPEN_STREAM);\n\n stream_initialize(stream);\n\n return stream;\n}\n\nStream *stream_open_handle(int handle_id, OpenFlag flags)\n{\n Stream *stream = __create(Stream);\n\n HANDLE(stream)->id = handle_id;\n HANDLE(stream)->flags = flags | OPEN_STREAM;\n HANDLE(stream)->result = SUCCESS;\n\n stream_initialize(stream);\n\n return stream;\n}\n\nResult stream_create_term(Stream **server, Stream **client)\n{\n *server = nullptr;\n *client = nullptr;\n\n int server_handle = HANDLE_INVALID_ID;\n int client_handle = HANDLE_INVALID_ID;\n\n Result result = __plug_create_term(&server_handle, &client_handle);\n\n if (result == SUCCESS)\n {\n *server = stream_open_handle(server_handle, OPEN_READ | OPEN_WRITE);\n *client = stream_open_handle(client_handle, OPEN_READ | OPEN_WRITE);\n }\n\n return result;\n}\n\nvoid stream_close(Stream *stream)\n{\n stream_flush(stream);\n\n if (stream->write_buffer)\n {\n free(stream->write_buffer);\n }\n\n if (stream->read_buffer)\n {\n free(stream->read_buffer);\n }\n\n __plug_handle_close(HANDLE(stream));\n\n free(stream);\n}\n\nvoid stream_cleanup(Stream **stream)\n{\n if (*stream)\n {\n stream_close(*stream);\n *stream = nullptr;\n }\n}\n\nvoid stream_set_read_buffer_mode(Stream *stream, StreamBufferMode mode)\n{\n if (mode == STREAM_BUFFERED_NONE)\n {\n if (stream->read_buffer)\n {\n free(stream->read_buffer);\n }\n }\n else\n {\n if (!stream->read_buffer)\n {\n stream->read_buffer = malloc(STREAM_BUFFER_SIZE);\n }\n }\n\n stream->read_mode = mode;\n}\n\nvoid stream_set_write_buffer_mode(Stream *stream, StreamBufferMode mode)\n{\n stream_flush(stream);\n\n if (mode == STREAM_BUFFERED_NONE)\n {\n if (stream->write_buffer)\n {\n free(stream->write_buffer);\n }\n }\n else\n {\n if (!stream->write_buffer)\n {\n stream->write_buffer = malloc(STREAM_BUFFER_SIZE);\n }\n }\n\n stream->write_mode = mode;\n}\n\nint stream_fill(Stream *stream)\n{\n\n stream->read_used = __plug_handle_read(HANDLE(stream), stream->read_buffer, STREAM_BUFFER_SIZE);\n stream->read_head = 0;\n\n return stream->read_used;\n}\n\nint stream_read_buffered(Stream *stream, void *buffer, size_t size)\n{\n size_t data_left = size;\n char *data_to_read = (char *)buffer;\n\n while (data_left != 0)\n {\n // Fill the buffer with data\n if (stream->read_head == stream->read_used)\n {\n if (stream_fill(stream) == 0)\n {\n // Look like we have no more data to read\n return size - data_left;\n }\n }\n\n // How many data can we copy from the buffer\n size_t used_space = stream->read_used - stream->read_head;\n size_t data_added = MIN(used_space, data_left);\n\n // Copy the data from the buffer\n memcpy(data_to_read, ((char *)stream->read_buffer) + stream->read_head, data_added);\n\n // Update the amount read\n data_left -= data_added;\n stream->read_head += data_added;\n }\n\n return size - data_left;\n}\n\nsize_t stream_read(Stream *stream, void *buffer, size_t size)\n{\n if (!stream)\n {\n return 0;\n }\n\n size_t result = 0;\n\n if (stream->has_unget && size >= 1)\n {\n ((char *)buffer)[0] = stream->unget_char;\n stream->has_unget = false;\n buffer = &((char *)buffer)[1];\n size--;\n\n result = 1;\n }\n\n if (stream->read_mode == STREAM_BUFFERED_NONE)\n {\n result = __plug_handle_read(HANDLE(stream), buffer, size);\n }\n else\n {\n result = stream_read_buffered(stream, buffer, size);\n }\n\n if (result == 0)\n {\n stream->is_end_of_file = true;\n }\n\n return result;\n}\n\nstatic size_t stream_write_linebuffered(Stream *stream, const void *buffer, size_t size)\n{\n for (size_t i = 0; i < size; i++)\n {\n char c = ((char *)buffer)[i];\n\n // Append to the buffer\n ((char *)stream->write_buffer)[stream->write_used] = c;\n stream->write_used++;\n\n // Flush if this is a new line or the end of the buffer\n if (c == '\\n' || stream->write_used == STREAM_BUFFER_SIZE)\n {\n stream_flush(stream);\n }\n }\n\n return size;\n}\n\nstatic size_t stream_write_buffered(Stream *stream, const void *buffer, size_t size)\n{\n int data_left = size;\n\n char *data_to_write = (char *)buffer;\n\n while (data_left > 0)\n {\n // Append the data to the buffer\n int free_space = STREAM_BUFFER_SIZE - stream->write_used;\n int data_added = MIN(free_space, data_left);\n\n // Copy the data to the buffer\n memcpy(((char *)(stream->write_buffer)) + stream->write_used, data_to_write, data_added);\n stream->write_used += data_added;\n data_left -= data_added;\n data_to_write += data_added;\n\n // flush the data if buffer is full\n if (stream->write_used == STREAM_BUFFER_SIZE)\n {\n stream_flush(stream);\n }\n }\n\n return size;\n}\n\nsize_t stream_write(Stream *stream, const void *buffer, size_t size)\n{\n if (!stream)\n {\n return 0;\n }\n\n switch (stream->write_mode)\n {\n case STREAM_BUFFERED_NONE:\n return __plug_handle_write(HANDLE(stream), buffer, size);\n\n case STREAM_BUFFERED_LINE:\n return stream_write_linebuffered(stream, buffer, size);\n\n case STREAM_BUFFERED_BLOCK:\n return stream_write_buffered(stream, buffer, size);\n\n default:\n ASSERT_NOT_REACHED();\n }\n}\n\nvoid stream_flush(Stream *stream)\n{\n if (!stream)\n {\n return;\n }\n\n if (stream->write_buffer != nullptr && stream->write_used > 0)\n {\n __plug_handle_write(HANDLE(stream), stream->write_buffer, stream->write_used);\n stream->write_used = 0;\n }\n}\n\nResult stream_call(Stream *stream, IOCall request, void *arg)\n{\n return __plug_handle_call(HANDLE(stream), request, arg);\n}\n\nint stream_seek(Stream *stream, int offset, Whence whence)\n{\n return __plug_handle_seek(HANDLE(stream), offset, whence);\n}\n\nint stream_tell(Stream *stream)\n{\n return __plug_handle_tell(HANDLE(stream));\n}\n\nvoid stream_stat(Stream *stream, FileState *stat)\n{\n stat->type = FILE_TYPE_UNKNOWN;\n stat->size = 0;\n\n __plug_handle_stat(HANDLE(stream), stat);\n}\n\nint stream_putchar(Stream *stream, char c)\n{\n if (stream_write(stream, &c, sizeof(char)) != sizeof(c))\n {\n return -1;\n }\n\n return c;\n}\n\nchar stream_getchar(Stream *stream)\n{\n char c;\n\n if (stream_read(stream, &c, sizeof(char)) != sizeof(char))\n {\n return -1;\n }\n\n return c;\n}\n\nint stream_ungetchar(Stream *stream, char c)\n{\n stream->has_unget = true;\n stream->unget_char = c;\n\n return 0;\n}\n\nvoid stream_format_append(printf_info_t *info, char c)\n{\n stream_write((Stream *)info->output, &c, 1);\n}\n\nint stream_format(Stream *stream, const char *fmt, ...)\n{\n va_list va;\n va_start(va, fmt);\n\n int result = stream_vprintf(stream, fmt, va);\n\n va_end(va);\n\n return result;\n}\n\nint stream_vprintf(Stream *stream, const char *fmt, va_list va)\n{\n printf_info_t info = {};\n\n info.format = fmt;\n info.append = stream_format_append;\n info.output = (void *)stream;\n info.allocated = -1;\n\n return __printf(&info, va);\n}\n\nbool stream_is_end_file(Stream *stream)\n{\n return stream->is_end_of_file;\n}\n" }, { "alpha_fraction": 0.6761565804481506, "alphanum_fraction": 0.6761565804481506, "avg_line_length": 17.733333587646484, "blob_id": "0b91e7410075807a5ffa1df59f0b0623b8d7077b", "content_id": "e2738e381249d0f145685512eca7e0d5cde37810", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 281, "license_type": "permissive", "max_line_length": 43, "num_lines": 15, "path": "/apps/media-player/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Application.h>\n#include <libwidget/Markup.h>\n\n#include \"media-player/windows/Main.h\"\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n auto window = new media_player::Main();\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.7355555295944214, "alphanum_fraction": 0.7400000095367432, "avg_line_length": 17, "blob_id": "8cc593d6ab8979ab7bfde996fee827b1aea25841", "content_id": "948982e3a7046c53e4d8f98ec328daf4046b6388", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 450, "license_type": "permissive", "max_line_length": 46, "num_lines": 25, "path": "/apps/panel/windows/PanelWindow.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Window.h>\n\n#include \"panel/windows/DateAndTimeWindow.h\"\n#include \"panel/windows/MenuWindow.h\"\n#include \"panel/windows/QuickSettingsWindow.h\"\n\nnamespace panel\n{\n\nclass PanelWindow : public Window\n{\nprivate:\n OwnPtr<MenuWindow> _menu;\n OwnPtr<DateAndTimeWindow> _datetime;\n OwnPtr<QuickSettingsWindow> _quicksetting;\n\npublic:\n static constexpr int HEIGHT = 38;\n\n PanelWindow();\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.6513158082962036, "alphanum_fraction": 0.6513158082962036, "avg_line_length": 10.692307472229004, "blob_id": "348196826ce378092672c9052b37c2cc549f6b89", "content_id": "b78e53d9bbba300d3949c7fa2888f2d9b06ef691", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 152, "license_type": "permissive", "max_line_length": 32, "num_lines": 13, "path": "/libraries/libsystem/io/Pipe.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/io/Stream.h>\n\nstruct Pipe\n{\n Stream *in;\n Stream *out;\n};\n\nPipe *pipe_create();\n\nvoid pipe_destroy(Pipe *pipe);\n" }, { "alpha_fraction": 0.7884615659713745, "alphanum_fraction": 0.7884615659713745, "avg_line_length": 16.33333396911621, "blob_id": "931cf0aec1a9bedbc4901949880f46a8d4c6d0d0", "content_id": "a844efe11e71493e785612cb1a66b251cad52f7e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 52, "license_type": "permissive", "max_line_length": 37, "num_lines": 3, "path": "/kernel/filesystem/DevicesFileSystem.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nvoid devices_filesystem_initialize();\n" }, { "alpha_fraction": 0.5976331233978271, "alphanum_fraction": 0.6568047404289246, "avg_line_length": 17.88888931274414, "blob_id": "0042e24b38cecd1f8e26c6c33fbd7b823a0e2c08", "content_id": "4cadec4b45d8dd99e41c3767e228ba0d0f730930", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 169, "license_type": "permissive", "max_line_length": 56, "num_lines": 9, "path": "/libraries/libsystem/compression/Common.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n// See https://tools.ietf.org/html/rfc1951#section-3.2.3\nenum BlockType\n{\n BT_UNCOMPRESSED = 0,\n BT_FIXED_HUFFMAN = 1,\n BT_DYNAMIC_HUFFMAN = 2,\n};" }, { "alpha_fraction": 0.6314814686775208, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 22.478260040283203, "blob_id": "fa2c32433aae57ee7a5aa9917b735f5c0f6d0dc0", "content_id": "d84f2b252cc317306887ece486c1aecbbf8a6b54", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 540, "license_type": "permissive", "max_line_length": 106, "num_lines": 23, "path": "/apps/panel/widgets/DateAndTime.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Label.h>\n#include <stdio.h>\n\n#include \"panel/widgets/DateAndTime.h\"\n\nnamespace panel\n{\n\nDateAndTime::DateAndTime(Widget *parent) : Button(parent, Button::TEXT)\n{\n auto label = new Label(this, \"\");\n\n _timer = own<Timer>(1000, [this, label]() {\n TimeStamp timestamp = timestamp_now();\n DateTime datetime = timestamp_to_datetime(timestamp);\n\n label->text(String::format(\"{02d}:{02d}:{02d}\", datetime.hour, datetime.minute, datetime.second));\n });\n\n _timer->start();\n}\n\n} // namespace panel\n" }, { "alpha_fraction": 0.63431316614151, "alphanum_fraction": 0.6468847990036011, "avg_line_length": 33.01886749267578, "blob_id": "336f05689ae862dc06ab0dba759df0e1f2324192", "content_id": "a2a7027cb8f67241292a0fadd52ec3878f85c05f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5409, "license_type": "permissive", "max_line_length": 114, "num_lines": 159, "path": "/libraries/abi/Syscalls.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libc/__libc__.h>\n\n#include <libsystem/Common.h>\n#include <libsystem/Result.h>\n\n#include <abi/Handle.h>\n#include <abi/IOCall.h>\n#include <abi/Launchpad.h>\n#include <abi/System.h>\n\n#define SYSCALL_LIST(__ENTRY) \\\n __ENTRY(HJ_PROCESS_THIS) \\\n __ENTRY(HJ_PROCESS_NAME) \\\n __ENTRY(HJ_PROCESS_LAUNCH) \\\n __ENTRY(HJ_PROCESS_CLONE) \\\n __ENTRY(HJ_PROCESS_EXEC) \\\n __ENTRY(HJ_PROCESS_EXIT) \\\n __ENTRY(HJ_PROCESS_CANCEL) \\\n __ENTRY(HJ_PROCESS_SLEEP) \\\n __ENTRY(HJ_PROCESS_WAIT) \\\n __ENTRY(HJ_MEMORY_ALLOC) \\\n __ENTRY(HJ_MEMORY_MAP) \\\n __ENTRY(HJ_MEMORY_FREE) \\\n __ENTRY(HJ_MEMORY_INCLUDE) \\\n __ENTRY(HJ_MEMORY_GET_HANDLE) \\\n __ENTRY(HJ_FILESYSTEM_LINK) \\\n __ENTRY(HJ_FILESYSTEM_UNLINK) \\\n __ENTRY(HJ_FILESYSTEM_RENAME) \\\n __ENTRY(HJ_FILESYSTEM_MKPIPE) \\\n __ENTRY(HJ_FILESYSTEM_MKDIR) \\\n __ENTRY(HJ_SYSTEM_INFO) \\\n __ENTRY(HJ_SYSTEM_STATUS) \\\n __ENTRY(HJ_SYSTEM_TIME) \\\n __ENTRY(HJ_SYSTEM_TICKS) \\\n __ENTRY(HJ_SYSTEM_REBOOT) \\\n __ENTRY(HJ_SYSTEM_SHUTDOWN) \\\n __ENTRY(HJ_HANDLE_OPEN) \\\n __ENTRY(HJ_HANDLE_CLOSE) \\\n __ENTRY(HJ_HANDLE_REOPEN) \\\n __ENTRY(HJ_HANDLE_COPY) \\\n __ENTRY(HJ_HANDLE_POLL) \\\n __ENTRY(HJ_HANDLE_READ) \\\n __ENTRY(HJ_HANDLE_WRITE) \\\n __ENTRY(HJ_HANDLE_CALL) \\\n __ENTRY(HJ_HANDLE_SEEK) \\\n __ENTRY(HJ_HANDLE_STAT) \\\n __ENTRY(HJ_HANDLE_CONNECT) \\\n __ENTRY(HJ_HANDLE_ACCEPT) \\\n __ENTRY(HJ_CREATE_PIPE) \\\n __ENTRY(HJ_CREATE_TERM)\n\n#define SYSCALL_ENUM_ENTRY(__entry) __entry,\n\nenum Syscall\n{\n SYSCALL_LIST(SYSCALL_ENUM_ENTRY) __SYSCALL_COUNT\n};\n\nstatic Result __syscall(Syscall syscall, uintptr_t p1, uintptr_t p2, uintptr_t p3, uintptr_t p4, uintptr_t p5)\n{\n Result __ret = ERR_FUNCTION_NOT_IMPLEMENTED;\n\n#if defined(__x86_64__)\n\n asm volatile(\"push %%rbx; movq %2,%%rbx; int $0x80; pop %%rbx\"\n : \"=a\"(__ret)\n : \"a\"(syscall), \"r\"(p1), \"c\"(p2), \"d\"(p3), \"S\"(p4), \"D\"(p5)\n : \"memory\");\n\n#elif defined(__i386__)\n\n asm volatile(\"push %%ebx; movl %2,%%ebx; int $0x80; pop %%ebx\"\n : \"=a\"(__ret)\n : \"0\"(syscall), \"r\"(p1), \"c\"(p2), \"d\"(p3), \"S\"(p4), \"D\"(p5)\n : \"memory\");\n#endif\n\n return __ret;\n}\n\n#ifdef __cplusplus\n\nstatic inline Result __syscall(Syscall syscall, uintptr_t p1, uintptr_t p2, uintptr_t p3, uintptr_t p4)\n{\n return __syscall(syscall, p1, p2, p3, p4, 0);\n}\n\nstatic inline Result __syscall(Syscall syscall, uintptr_t p1, uintptr_t p2, uintptr_t p3)\n{\n return __syscall(syscall, p1, p2, p3, 0, 0);\n}\n\nstatic inline Result __syscall(Syscall syscall, uintptr_t p1, uintptr_t p2)\n{\n return __syscall(syscall, p1, p2, 0, 0, 0);\n}\n\nstatic inline Result __syscall(Syscall syscall, uintptr_t p1)\n{\n return __syscall(syscall, p1, 0, 0, 0, 0);\n}\n\nstatic inline Result __syscall(Syscall syscall)\n{\n return __syscall(syscall, 0, 0, 0, 0, 0);\n}\n\n#endif\n\n__BEGIN_HEADER\n\nResult hj_process_this(int *pid);\nResult hj_process_name(char *name, size_t size);\nResult hj_process_launch(Launchpad *launchpad, int *pid);\nResult hj_process_clone(int *pid);\nResult hj_process_exec(Launchpad *launchpad);\nResult hj_process_exit(int exit_code);\nResult hj_process_cancel(int pid);\nResult hj_process_sleep(int time);\nResult hj_process_wait(int tid, int *user_exit_value);\n\nResult hj_memory_alloc(size_t size, uintptr_t *out_address);\nResult hj_memory_map(uintptr_t address, size_t size, int flags);\nResult hj_memory_free(uintptr_t address);\nResult hj_memory_include(int handle, uintptr_t *out_address, size_t *out_size);\nResult hj_memory_get_handle(uintptr_t address, int *out_handle);\n\nResult hj_filesystem_mkdir(const char *raw_path, size_t size);\nResult hj_filesystem_mkpipe(const char *raw_path, size_t size);\nResult hj_filesystem_link(const char *raw_old_path, size_t old_size, const char *raw_new_path, size_t new_size);\nResult hj_filesystem_unlink(const char *raw_path, size_t size);\nResult hj_filesystem_rename(const char *raw_old_path, size_t old_size, const char *raw_new_path, size_t new_size);\n\nResult hj_system_info(SystemInfo *info);\nResult hj_system_status(SystemStatus *status);\nResult hj_system_time(TimeStamp *timestamp);\nResult hj_system_tick(uint32_t *tick);\nResult hj_system_reboot();\nResult hj_system_shutdown();\n\nResult hj_create_pipe(int *reader_handle, int *writer_handle);\nResult hj_create_term(int *server_handle, int *client_handle);\n\nResult hj_handle_open(int *handle, const char *raw_path, size_t size, OpenFlag flags);\nResult hj_handle_close(int handle);\nResult hj_handle_reopen(int handle, int *reopened);\nResult hj_handle_copy(int source, int destination);\nResult hj_handle_poll(HandleSet *handles_set, int *selected, PollEvent *selected_events, Timeout timeout);\nResult hj_handle_read(int handle, void *buffer, size_t size, size_t *read);\nResult hj_handle_write(int handle, const void *buffer, size_t size, size_t *written);\nResult hj_handle_call(int handle, IOCall request, void *args);\nResult hj_handle_seek(int handle, int offset, Whence whence, int *result);\nResult hj_handle_stat(int handle, FileState *state);\nResult hj_handle_connect(int *handle, const char *raw_path, size_t size);\nResult hj_handle_accept(int handle, int *connection_handle);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 21.125, "blob_id": "8e0afeade53e236faf4f23b81138e89bd1bef4d9", "content_id": "457142435e1ebdd64e6d8a05379c26a72a179851", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 177, "license_type": "permissive", "max_line_length": 44, "num_lines": 8, "path": "/apps/utilities/env.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io_new/Streams.h>\n#include <skift/Environment.h>\n\nint main(int, char const *[])\n{\n System::outln(\"{}\", environment_copy());\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.805084764957428, "alphanum_fraction": 0.805084764957428, "avg_line_length": 28.5, "blob_id": "6284744a088127667164e5c2f14e03a0c80d4c10", "content_id": "6b8ef992968ea51bce370cdf1195131da8dc3144", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 118, "license_type": "permissive", "max_line_length": 56, "num_lines": 4, "path": "/apps/widget-factory/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += WIDGET_FACTORY\n\nWIDGET_FACTORY_NAME = widget-factory\nWIDGET_FACTORY_LIBS = filepicker widget settings graphic\n" }, { "alpha_fraction": 0.7472527623176575, "alphanum_fraction": 0.7472527623176575, "avg_line_length": 29.33333396911621, "blob_id": "3d1e32464d27e78a90feda99d5010d874821ae52", "content_id": "c9f5c0532571638514599fe793184cf3598d4223", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 91, "license_type": "permissive", "max_line_length": 56, "num_lines": 3, "path": "/libraries/libwidget/Container.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Container.h>\n\nContainer::Container(Widget *parent) : Widget(parent){};\n" }, { "alpha_fraction": 0.6689976453781128, "alphanum_fraction": 0.6713286638259888, "avg_line_length": 14.321428298950195, "blob_id": "6d7e70ed80df5d106553270df74c55c7d14b7946", "content_id": "004384932627d6e85f4d2fa5705b716d156f676e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 429, "license_type": "permissive", "max_line_length": 41, "num_lines": 28, "path": "/apps/neko/states/Surpised.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Screen.h>\n\n#include \"neko/graphics/Animations.h\"\n#include \"neko/model/Neko.h\"\n#include \"neko/states/ChaseMouse.h\"\n#include \"neko/states/Surprised.h\"\n\nnamespace neko\n{\n\nSurprised::Surprised()\n{\n}\n\nvoid Surprised::update(Neko &neko)\n{\n if (neko.tick() > 2)\n {\n neko.behavior(own<ChaseMouse>());\n }\n}\n\nAnimation Surprised::animation(Neko &)\n{\n return Animations::AWAKE;\n}\n\n} // namespace neko\n" }, { "alpha_fraction": 0.5355704426765442, "alphanum_fraction": 0.5409395694732666, "avg_line_length": 16.325580596923828, "blob_id": "500948dddf20c127a3670b672271ac858e1dc974", "content_id": "523fe463a0fa082ba236a0bbcaf903ffc08b5eb6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 745, "license_type": "permissive", "max_line_length": 74, "num_lines": 43, "path": "/apps/utilities/yes.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/Stream.h>\n#include <libutils/StringBuilder.h>\n\n#include <stdio.h>\n\nString concat(int argc, char **argv)\n{\n int i;\n StringBuilder builder;\n\n for (i = 1; i < argc - 1; i++)\n {\n builder.append(argv[i]);\n builder.append(\" \");\n }\n\n builder.append(argv[i]);\n\n return builder.finalize();\n}\n\nint main(int argc, char **argv)\n{\n String output = \"yes\";\n\n if (argc > 1)\n {\n output = concat(argc, argv);\n }\n\n while (1)\n {\n printf(\"%s\\n\", output.cstring());\n\n if (handle_has_error(out_stream))\n {\n handle_printf_error(out_stream, \"Couldn't write to stdout\\n\");\n return PROCESS_FAILURE;\n }\n }\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6925133466720581, "alphanum_fraction": 0.6925133466720581, "avg_line_length": 19.77777862548828, "blob_id": "fea998e21f3fd0ad73ae840e62d161b1d84229cc", "content_id": "ad86eb561eb74467974e03128011144dac83c89d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 748, "license_type": "permissive", "max_line_length": 53, "num_lines": 36, "path": "/apps/terminal/TerminalWidget.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Font.h>\n#include <libsystem/eventloop/Notifier.h>\n#include <libsystem/eventloop/Timer.h>\n#include <libsystem/io/Stream.h>\n#include <libterminal/Terminal.h>\n#include <libwidget/Widget.h>\n\nclass TerminalWidget : public Widget\n{\nprivate:\n OwnPtr<terminal::Terminal> _terminal;\n bool _cursor_blink;\n\n Stream *_server_stream;\n Stream *_client_stream;\n\n OwnPtr<Timer> _cursor_blink_timer;\n OwnPtr<Notifier> _server_notifier;\n\npublic:\n void blink() { _cursor_blink = !_cursor_blink; };\n\n TerminalWidget(Widget *parent);\n\n ~TerminalWidget();\n\n void handle_read();\n\n void paint(Painter &, const Recti &) override;\n\n void event(Event *event) override;\n\n void do_layout() override;\n};\n" }, { "alpha_fraction": 0.6850393414497375, "alphanum_fraction": 0.6850393414497375, "avg_line_length": 13.11111068725586, "blob_id": "cbeacaad01290d17a0aa1566d75ce5d279c724bc", "content_id": "d70ce98376ae8a907eedcd3bd0c86e3fa9b91336", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 127, "license_type": "permissive", "max_line_length": 83, "num_lines": 9, "path": "/manual/10-utilities/cd.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# cd\n\n```sh\ncd [PATH]\n```\n\n## Description\n\ncd is shell builtin that changes the directory. cd is short for \"Change Directory\".\n" }, { "alpha_fraction": 0.4720229506492615, "alphanum_fraction": 0.48015302419662476, "avg_line_length": 20.55670166015625, "blob_id": "93263221d7d13bfced66e66ca64fbbfc1c8b6a6b", "content_id": "d744fe06411ac9e8b2187b335f145570a6e3c569", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2091, "license_type": "permissive", "max_line_length": 70, "num_lines": 97, "path": "/libraries/libutils/json/Prettifier.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <skift/NumberFormatter.h>\n\n#include <libutils/Prettifier.h>\n#include <libutils/Scanner.h>\n#include <libutils/String.h>\n#include <libutils/json/Value.h>\n\nnamespace json\n{\ninline void prettify(Prettifier &pretty, const Value &value)\n{\n if (value.is(STRING))\n {\n pretty.append('\"');\n pretty.append(value.as_string());\n pretty.append('\"');\n }\n else if (value.is(INTEGER))\n {\n char buffer[128];\n format_int(FORMAT_DECIMAL, value.as_integer(), buffer, 128);\n pretty.append(buffer);\n }\n#ifndef __KERNEL__\n else if (value.is(DOUBLE))\n {\n char buffer[128];\n format_double(FORMAT_DECIMAL, value.as_double(), buffer, 128);\n pretty.append(buffer);\n }\n#endif\n else if (value.is(OBJECT))\n {\n pretty.append('{');\n\n if (value.length() > 0)\n {\n pretty.push_ident();\n\n value.as_object().foreach ([&](auto &key, auto &value) {\n pretty.ident();\n\n pretty.color_depth();\n\n pretty.append('\"');\n pretty.append(key.cstring());\n pretty.append('\"');\n\n pretty.color_clear();\n\n pretty.append(\": \");\n prettify(pretty, value);\n pretty.append(',');\n\n return Iteration::CONTINUE;\n });\n\n pretty.rewind(1);\n\n pretty.pop_ident();\n }\n\n pretty.ident();\n pretty.append('}');\n }\n else if (value.is(ARRAY))\n {\n pretty.append('[');\n\n if (value.length() > 0)\n {\n pretty.push_ident();\n\n for (size_t i = 0; i < value.length(); i++)\n {\n pretty.ident();\n prettify(pretty, value.get(i));\n pretty.append(',');\n }\n\n pretty.rewind(1); // remove the last \",\"\n\n pretty.pop_ident();\n }\n\n pretty.ident();\n pretty.append(']');\n }\n else\n {\n pretty.append(value.as_string());\n }\n}\n\n} // namespace json\n" }, { "alpha_fraction": 0.6259711384773254, "alphanum_fraction": 0.6348501443862915, "avg_line_length": 18.586956024169922, "blob_id": "7bb76cd825edcdf8713a9772d47ab60578900ad9", "content_id": "bb4c28320ec5045bf4b99c8e6c045ff8f07a0385", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 901, "license_type": "permissive", "max_line_length": 52, "num_lines": 46, "path": "/apps/device-manager/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libutils/Path.h>\n\n#include <libsystem/eventloop/Timer.h>\n#include <libsystem/system/System.h>\n\n#include <libwidget/Application.h>\n#include <libwidget/Table.h>\n#include <libwidget/TitleBar.h>\n\n#include \"device-manager/DeviceModel.h\"\n\nclass DeviceManagerWindow : public Window\n{\nprivate:\n Widget *_table;\n\npublic:\n DeviceManagerWindow() : Window(WINDOW_RESIZABLE)\n {\n icon(Icon::get(\"expansion-card-variant\"));\n title(\"Device Manager\");\n size(Vec2i(700, 500));\n\n root()->layout(VFLOW(0));\n\n new TitleBar(root());\n\n auto model = make<DeviceModel>();\n\n model->update();\n\n _table = new Table(root(), model);\n _table->flags(Widget::FILL);\n }\n};\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n auto window = new DeviceManagerWindow();\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 41, "blob_id": "ec2da8caeeec2a3ceb78cf9d9160b1480f5219fb", "content_id": "8376f8ab99d31b3f40dc7fdf77b55528cc14ce79", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 42, "license_type": "permissive", "max_line_length": 41, "num_lines": 1, "path": "/kernel/drivers/VirtioConsole.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"kernel/drivers/VirtioConsole.h\"\n" }, { "alpha_fraction": 0.6466684341430664, "alphanum_fraction": 0.6600304841995239, "avg_line_length": 29.05929946899414, "blob_id": "5f24928ee6c76607ebd7c229e5d383b152e09278", "content_id": "b5abf2129536755f7639577ca834e40369cd5f45", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11151, "license_type": "permissive", "max_line_length": 133, "num_lines": 371, "path": "/libraries/libfile/ZipArchive.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libfile/ZipArchive.h>\n#include <libsystem/Logger.h>\n#include <libsystem/compression/Deflate.h>\n#include <libsystem/compression/Inflate.h>\n#include <libsystem/io/BinaryReader.h>\n#include <libsystem/io/FileReader.h>\n#include <libsystem/io/FileWriter.h>\n#include <libsystem/io/MemoryReader.h>\n#include <libsystem/io/MemoryWriter.h>\n#include <libsystem/io/ScopedReader.h>\n#include <libutils/Endian.h>\n#include <stdio.h>\n\n// Central header\n#define ZIP_END_OF_CENTRAL_DIR_HEADER_SIG 0x06054b50\n#define ZIP_CENTRAL_DIR_HEADER_SIG 0x02014b50\n\n// Local header\n#define ZIP_LOCAL_DIR_HEADER_SIG 0x04034b50\n\nenum ExtraFieldType : uint16_t\n{\n EFT_ZIP64 = 0x0001,\n EFT_EXTENDED_TIMESTAMP = 0x5455,\n EFT_NEW_UNIX = 0x7875,\n};\n\nusing le_eft = LittleEndian<ExtraFieldType>;\n\nenum EntryFlags : uint16_t\n{\n EF_NONE = 0,\n EF_ENCRYPTED = 1 << 0,\n EF_COMPRESSION_OPTION = 1 << 1,\n EF_COMPRESSION_OPTION2 = 1 << 2,\n EF_DATA_DESCRIPTOR = 1 << 3,\n};\n\nusing le_flags = LittleEndian<EntryFlags>;\n\nenum CompressionMethod : uint16_t\n{\n CM_UNCOMPRESSED = 0,\n CM_SHRUNK = 1,\n CM_DEFLATED = 8,\n};\n\nusing le_compression = LittleEndian<CompressionMethod>;\n\nstruct __packed CentralDirectoryFileHeader\n{\n le_uint32_t signature;\n le_uint16_t version;\n le_uint16_t version_required;\n le_flags flags;\n le_compression compression;\n le_uint16_t mod_time;\n le_uint16_t mod_date;\n le_uint32_t crc;\n le_uint32_t compressed_size;\n le_uint32_t uncompressed_size;\n le_uint16_t len_filename;\n le_uint16_t len_extrafield;\n le_uint16_t len_comment;\n le_uint16_t disk_start;\n le_uint16_t internal_attr;\n le_uint32_t external_attr;\n le_uint32_t local_header_offset;\n};\n\nstruct __packed CentralDirectoryEndRecord\n{\n le_uint32_t signature;\n le_uint16_t disk1;\n le_uint16_t disk2;\n le_uint16_t disk_entries;\n le_uint16_t total_entries;\n le_uint32_t central_dir_size;\n le_uint32_t central_dir_offset;\n le_uint16_t len_comment;\n};\n\nstruct __packed LocalHeader\n{\n le_uint32_t signature;\n le_uint16_t version;\n le_flags flags;\n le_compression compression;\n le_uint16_t mod_time;\n le_uint16_t mod_date;\n le_uint32_t crc;\n le_uint32_t compressed_size;\n le_uint32_t uncompressed_size;\n le_uint16_t len_filename;\n le_uint16_t len_extrafield;\n};\n\nstatic_assert(sizeof(LocalHeader) == 30, \"LocalHeader has invalid size!\");\n\nstruct __packed DataDescriptor\n{\n le_uint32_t crc;\n le_uint32_t compressed_size;\n le_uint32_t uncompressed_size;\n};\n\nstatic_assert(sizeof(DataDescriptor) == 12, \"DataDescriptor has invalid size!\");\n\nZipArchive::ZipArchive(Path path, bool read) : Archive(path)\n{\n if (read)\n {\n read_archive();\n }\n}\n\nvoid ZipArchive::read_local_headers(BinaryReader &reader)\n{\n // Read all local file headers and data descriptors\n while (reader.position() < (reader.length() - sizeof(LocalHeader)))\n {\n logger_trace(\"Read local header: '%s'\", _path.string().cstring());\n auto local_header = reader.peek<LocalHeader>();\n\n // Check if this is a local header\n if (local_header.signature() != ZIP_LOCAL_DIR_HEADER_SIG)\n {\n logger_trace(\"Invalid signature: %u\", local_header.signature());\n break;\n }\n\n auto &entry = _entries.emplace_back();\n reader.skip(sizeof(LocalHeader));\n\n // Get the uncompressed & compressed sizes\n entry.uncompressed_size = local_header.uncompressed_size();\n entry.compressed_size = local_header.compressed_size();\n entry.compression = local_header.compression();\n\n // Read the filename of this entry\n entry.name = reader.get_fixed_len_string(local_header.len_filename());\n logger_trace(\"Found local header: '%s'\", entry.name.cstring());\n\n // Read extra fields\n auto end_position = reader.position() + local_header.len_extrafield();\n while (reader.position() < end_position)\n {\n le_eft extra_field_type(reader.get<ExtraFieldType>());\n le_uint16_t extra_field_size(reader.get<uint16_t>());\n\n // TODO: parse the known extra field types\n reader.skip(extra_field_size());\n }\n\n // Skip the compressed data for now\n entry.archive_offset = reader.position();\n reader.skip(entry.compressed_size);\n\n if (local_header.flags() & EF_DATA_DESCRIPTOR)\n {\n auto data_descriptor = reader.get<DataDescriptor>();\n entry.uncompressed_size = data_descriptor.uncompressed_size();\n entry.compressed_size = data_descriptor.compressed_size();\n }\n }\n}\n\nResult ZipArchive::read_central_directory(BinaryReader &reader)\n{\n // Central directory starts here\n while (reader.position() < (reader.length() - sizeof(CentralDirectoryFileHeader)))\n {\n logger_trace(\"Read central directory header: '%s'\", _path.string().cstring());\n auto cd_file_header = reader.peek<CentralDirectoryFileHeader>();\n\n // Check if this is a central directory file header\n if (cd_file_header.signature() != ZIP_CENTRAL_DIR_HEADER_SIG)\n {\n break;\n }\n\n // Read the central directory entry\n reader.skip(sizeof(CentralDirectoryFileHeader));\n\n String name = reader.get_fixed_len_string(cd_file_header.len_filename());\n logger_trace(\"Found central directory header: '%s'\", name.cstring());\n\n reader.skip(cd_file_header.len_extrafield());\n reader.skip(cd_file_header.len_comment());\n }\n\n // End of file\n le_uint32_t central_dir_end_sig(reader.get<uint32_t>());\n if (central_dir_end_sig() != ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)\n {\n logger_error(\"Missing 'central directory end record' signature!\");\n return Result::ERR_INVALID_DATA;\n }\n\n return Result::SUCCESS;\n}\n\nvoid ZipArchive::read_archive()\n{\n _valid = false;\n\n File archive_file = File(_path);\n\n // Archive does not exist\n if (!archive_file.exist())\n {\n logger_error(\"Archive does not exist: %s\", _path.string().cstring());\n return;\n }\n\n logger_trace(\"Opening file: '%s'\", _path.string().cstring());\n\n FileReader file_reader(_path);\n\n // A valid zip must atleast contain a \"CentralDirectoryEndRecord\"\n if (file_reader.length() < sizeof(CentralDirectoryEndRecord))\n {\n logger_error(\"Archive is too small to be a valid .zip: %s %u\", _path.string().cstring(), (unsigned int)file_reader.length());\n return;\n }\n\n BinaryReader binary_reader(file_reader);\n\n read_local_headers(binary_reader);\n Result result = read_central_directory(binary_reader);\n\n if (result != Result::SUCCESS)\n {\n return;\n }\n\n _valid = true;\n}\n\nvoid ZipArchive::write_entry(const Entry &entry, BinaryWriter &writer, Reader &compressed)\n{\n LocalHeader header;\n header.flags = EF_NONE;\n header.compressed_size = compressed.length();\n header.compression = CM_DEFLATED;\n header.uncompressed_size = entry.uncompressed_size;\n header.len_filename = entry.name.length();\n header.len_extrafield = 0;\n header.signature = ZIP_LOCAL_DIR_HEADER_SIG;\n\n // Write data\n writer.put(header);\n writer.put_fixed_len_string(entry.name);\n writer.copy_from(compressed);\n}\n\nvoid ZipArchive::write_central_directory(BinaryWriter &writer)\n{\n auto start = writer.position();\n for (const auto &entry : _entries)\n {\n logger_trace(\"Write central directory header: '%s'\", entry.name.cstring());\n CentralDirectoryFileHeader header;\n header.flags = EF_NONE;\n header.compressed_size = entry.compressed_size;\n header.compression = CM_DEFLATED;\n header.uncompressed_size = entry.uncompressed_size;\n header.local_header_offset = entry.archive_offset - sizeof(LocalHeader) - entry.name.length();\n header.len_filename = entry.name.length();\n header.len_extrafield = 0;\n header.len_comment = 0;\n header.signature = ZIP_CENTRAL_DIR_HEADER_SIG;\n writer.put(header);\n writer.put_fixed_len_string(entry.name);\n }\n auto end = writer.position();\n\n CentralDirectoryEndRecord end_record;\n end_record.signature = ZIP_END_OF_CENTRAL_DIR_HEADER_SIG;\n end_record.central_dir_size = end - start;\n end_record.central_dir_offset = start;\n end_record.disk_entries = _entries.count();\n end_record.total_entries = _entries.count();\n end_record.len_comment = 0;\n writer.put(end_record);\n writer.flush();\n}\n\nResult ZipArchive::extract(unsigned int entry_index, const char *dest_path)\n{\n // Read the compressed data from the entry\n const auto &entry = _entries[entry_index];\n\n if (entry.compression != CM_DEFLATED)\n {\n logger_error(\"ZipArchive: Unsupported compression: %u\\n\", entry.compression);\n return Result::ERR_FUNCTION_NOT_IMPLEMENTED;\n }\n\n Inflate inf;\n\n // Get a reader to the uncompressed data\n FileReader file_reader(_path);\n file_reader.seek(entry.archive_offset, WHENCE_START);\n ScopedReader scoped_reader(file_reader, entry.uncompressed_size);\n\n // Get a writer to the output\n FileWriter file_writer(dest_path);\n\n return inf.perform(scoped_reader, file_writer);\n}\n\nResult ZipArchive::insert(const char *entry_name, const char *src_path)\n{\n File src_file(src_path);\n\n if (!src_file.exist())\n {\n return Result::ERR_NO_SUCH_FILE_OR_DIRECTORY;\n }\n\n // TODO: create a new entry and write it to the output file\n MemoryWriter memory_writer;\n BinaryWriter binary_writer(memory_writer);\n\n // Write local headers\n for (const auto &entry : _entries)\n {\n FileReader file_reader(_path);\n file_reader.seek(entry.archive_offset, WHENCE_START);\n ScopedReader scoped_reader(file_reader, entry.compressed_size);\n logger_trace(\"Write existing local header: '%s'\", entry.name.cstring());\n write_entry(entry, binary_writer, scoped_reader);\n }\n\n // Get a reader to the original file\n FileReader src_reader(src_path);\n MemoryWriter compressed_writer;\n\n // Perform deflate on the data\n Deflate def(5);\n auto def_result = def.perform(src_reader, compressed_writer);\n if (def_result != Result::SUCCESS)\n {\n return def_result;\n }\n\n // Write our new entry\n logger_trace(\"Write new local header: '%s'\", entry_name);\n\n auto &new_entry = _entries.emplace_back();\n new_entry.name = String(entry_name);\n new_entry.compressed_size = compressed_writer.length();\n new_entry.compression = CM_DEFLATED;\n new_entry.uncompressed_size = src_reader.length();\n new_entry.archive_offset = memory_writer.length() + sizeof(LocalHeader) + new_entry.name.length();\n\n MemoryReader compressed_reader(compressed_writer.data());\n write_entry(new_entry, binary_writer, compressed_reader);\n\n // Write central directory\n write_central_directory(binary_writer);\n\n // Do this properly...\n FileWriter file_writer(_path);\n MemoryReader memory_reader(memory_writer.data());\n file_writer.copy_from(memory_reader);\n\n return Result::SUCCESS;\n}" }, { "alpha_fraction": 0.6213017702102661, "alphanum_fraction": 0.692307710647583, "avg_line_length": 20.125, "blob_id": "145e2f0dcf4c2629a93cd21ba9a34ffa0aad670c", "content_id": "9340de5bfb4a50db585dfc18cb55ef7b2251dbae", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 169, "license_type": "permissive", "max_line_length": 54, "num_lines": 8, "path": "/archs/x86_32/kernel/boot/Stivale2.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Common.h>\n\nextern \"C\" void arch_main(void *info, uint32_t magic);\n\nextern \"C\" void _kstart_stivale2(void *info)\n{\n arch_main(info, 0x73747632);\n}\n" }, { "alpha_fraction": 0.5662805438041687, "alphanum_fraction": 0.5752895474433899, "avg_line_length": 24.032258987426758, "blob_id": "1087a6c889737f3423c07391c99e7eef706c6f30", "content_id": "cb7c6c38552f062e56d44095133fdeafd6cda956", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 777, "license_type": "permissive", "max_line_length": 111, "num_lines": 31, "path": "/apps/utilities/dstart.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n/* dstart.c: start a process as a daemon */\n\n#include <libsystem/io/Stream.h>\n#include <libsystem/process/Launchpad.h>\n\nint main(int argc, char const *argv[])\n{\n if (argc == 1)\n {\n stream_format(err_stream, \"dstart: No executable specified!\\n\");\n return PROCESS_FAILURE;\n }\n\n Launchpad *launchpad = launchpad_create(argv[1], argv[1]);\n\n for (int i = 1; i < argc; i++)\n {\n launchpad_argument(launchpad, argv[i]);\n }\n\n int pid = -1;\n Result result = launchpad_launch(launchpad, &pid);\n\n if (result < 0)\n {\n stream_format(err_stream, \"dstart: Failed to start %s: %s\\n\", argv[1], get_result_description(result));\n return PROCESS_FAILURE;\n }\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6212121248245239, "alphanum_fraction": 0.6333333253860474, "avg_line_length": 22.5, "blob_id": "5e9acf10b1701ecceb8abe5b350b21cc4996cb3f", "content_id": "b0c76c4e048c0b98eec365d38fec29f59aa8b8fa", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 330, "license_type": "permissive", "max_line_length": 71, "num_lines": 14, "path": "/apps/utilities/link.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libraries/libsystem/io/Filesystem.h>\n#include <libsystem/Result.h>\n#include <libsystem/io/Stream.h>\n\nint main(int argc, char **argv)\n{\n if (argc == 1)\n {\n stream_format(err_stream, \"%s: no eough arguments\\n\", argv[0]);\n return PROCESS_FAILURE;\n }\n\n return filesystem_link(argv[1], argv[2]);\n}\n" }, { "alpha_fraction": 0.5496358871459961, "alphanum_fraction": 0.5507857203483582, "avg_line_length": 25.09000015258789, "blob_id": "dc9b6687f3c688c751660e6be7aefa13f8f80bd7", "content_id": "c3fcb8584dc373139a8b2f3e4bfb7a913f08aed3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2609, "license_type": "permissive", "max_line_length": 120, "num_lines": 100, "path": "/apps/utilities/rmdir.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/cmdline/CMDLine.h>\n#include <libsystem/io/Filesystem.h>\n#include <libsystem/io_new/Directory.h>\n#include <libsystem/io_new/Streams.h>\n#include <libutils/Path.h>\n#include <stdio.h>\n\nstatic bool force = false;\nstatic bool remove_parents = false;\nstatic bool verbose = false;\n\nstatic const char *usages[] = {\n \"DIRECTORIES...\"\n \"OPTIONS... DIRECTORIES...\",\n nullptr,\n};\n\nstatic CommandLineOption options[] = {\n COMMANDLINE_OPT_HELP,\n\n COMMANDLINE_OPT_BOOL(\"force\", 'f', force,\n \"ignore non-existent files and arguments\",\n COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"parents\", 'p', remove_parents,\n \"remove DIRECTORY and its ancestors; e.g., 'rmdir -p a/b/c' is similar to 'rmdir a/b/c a/b a'\",\n COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"verbose\", 'v', verbose,\n \"output a diagnostic for every directory processed\",\n COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_END,\n};\n\nstatic CommandLine cmdline = CMDLINE(\n usages,\n options,\n \"Remove the DIRECTORY(ies), if they are empty.\",\n \"Options can be combined.\");\n\nResult rmdir(String path)\n{\n System::Directory directory{path};\n\n if (!force && directory.entries().any())\n {\n return ERR_DIRECTORY_NOT_EMPTY;\n }\n\n Result unlink_result = filesystem_unlink(path.cstring());\n\n if (unlink_result != SUCCESS)\n {\n System::errln(\"rmdir: successfully removed '{}': {}\", path, get_result_description(unlink_result));\n }\n else if (verbose)\n {\n System::errln(\"rmdir: successfully removed '{}': {}\", path, get_result_description(unlink_result));\n }\n\n return unlink_result;\n}\n\nint main(int argc, char **argv)\n{\n argc = cmdline_parse(&cmdline, argc, argv);\n\n if (argc == 1)\n {\n printf(\"rmdir: missing operand\\nTry 'rmdir --help' for more information.\\n\");\n return PROCESS_FAILURE;\n }\n\n for (int i = 1; i < argc; i++)\n {\n if (!remove_parents)\n {\n if (rmdir(argv[i]) != SUCCESS)\n {\n return PROCESS_FAILURE;\n }\n }\n else\n {\n auto path = Path::parse(argv[i]);\n\n while (path.length() > 0)\n {\n auto result = rmdir(path.string().cstring());\n\n if (result != SUCCESS)\n {\n return PROCESS_FAILURE;\n }\n\n path = path.dirpath();\n }\n }\n }\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.7674418687820435, "alphanum_fraction": 0.7674418687820435, "avg_line_length": 13.333333015441895, "blob_id": "226705246665b1e0fd47fc6d9e1f65c143b1d3ed", "content_id": "4136ed11734a9e7191924dbae730408850cf0931", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 43, "license_type": "permissive", "max_line_length": 28, "num_lines": 3, "path": "/kernel/tasking/Userspace.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nvoid userspace_initialize();\n" }, { "alpha_fraction": 0.7473683953285217, "alphanum_fraction": 0.7473683953285217, "avg_line_length": 18, "blob_id": "c9fb30e70595142ad020190832a1b5156790e1dd", "content_id": "df301e3279bf36648423c1a8e07d71d30035cfdc", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 95, "license_type": "permissive", "max_line_length": 42, "num_lines": 5, "path": "/kernel/Configs.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#ifndef CONFIG_KEYBOARD_LAYOUT\n# define CONFIG_KEYBOARD_LAYOUT \"en_us\"\n#endif\n" }, { "alpha_fraction": 0.6471990346908569, "alphanum_fraction": 0.6555423140525818, "avg_line_length": 21.70270347595215, "blob_id": "7754a3d72eb1c6cf1e3b4d0cfa6d17d26fa2ac9d", "content_id": "0fb0c7e8bc36a4a97edb4ed7dae9060f7f63d8aa", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 839, "license_type": "permissive", "max_line_length": 88, "num_lines": 37, "path": "/libraries/libsystem/io_new/Writer.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/ResultOr.h>\n#include <libutils/unicode/Codepoint.h>\n\n#include <libsystem/io_new/Seek.h>\n\nnamespace System\n{\n\nclass Writer\n{\npublic:\n virtual ~Writer() { flush(); }\n\n virtual ResultOr<size_t> write(const void *buffer, size_t size) = 0;\n\n virtual ResultOr<size_t> write(char v) { return write(&v, 1); }\n\n virtual ResultOr<size_t> write(uint8_t v) { return write(&v, 1); }\n\n ResultOr<size_t> write(const char *buffer) { return write(buffer, strlen(buffer)); }\n\n virtual Result flush() { return SUCCESS; }\n\n ResultOr<size_t> write(Codepoint cp)\n {\n char buffer[5];\n codepoint_to_utf8(cp, (uint8_t *)buffer);\n return write(buffer);\n }\n};\n\ntemplate <typename T>\nconcept SeekableWriter = IsBaseOf<Writer, T>::value &&IsBaseOf<Seek, T>::value;\n\n} // namespace System" }, { "alpha_fraction": 0.6203703880310059, "alphanum_fraction": 0.6203703880310059, "avg_line_length": 8.909090995788574, "blob_id": "eb1a5c45fcd72de3a1b73028ca04efda580c1e35", "content_id": "3d635675579b07cc821b506cfec1e14d0258f58e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 108, "license_type": "permissive", "max_line_length": 14, "num_lines": 11, "path": "/toolchain/dump-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\necho \"\"\ngcc --version\necho \"\"\nld --version\necho \"\"\nnasm --version\necho \"\"\nas --version\necho \"\"\nenv" }, { "alpha_fraction": 0.5180831551551819, "alphanum_fraction": 0.5189873576164246, "avg_line_length": 16.838708877563477, "blob_id": "fc8032b5370f687553a2c4dc7c35fcea7186a635", "content_id": "45768d79a605dd37ea29f4a3cde03137d137270d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1106, "license_type": "permissive", "max_line_length": 57, "num_lines": 62, "path": "/libraries/libmarkup/Prettify.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libmarkup/Markup.h>\n#include <libutils/StringBuilder.h>\n\nnamespace markup\n{\n\nvoid prettify(Prettifier &pretty, Node &node)\n{\n pretty.append('<');\n\n pretty.color_depth();\n pretty.append(node.type());\n pretty.color_clear();\n\n node.foreach_attributes([&](auto &key, auto &value) {\n pretty.append(' ');\n pretty.append(key);\n\n if (value != \"\")\n {\n pretty.append('=');\n pretty.append('\"');\n pretty.append(value);\n pretty.append('\"');\n }\n\n return Iteration::CONTINUE;\n });\n\n if (node.count_child() == 0)\n {\n pretty.append(\"/>\");\n return;\n }\n else\n {\n pretty.append('>');\n }\n\n node.foreach_child([&](auto &child) {\n pretty.push_ident();\n pretty.ident();\n\n prettify(pretty, child);\n\n pretty.pop_ident();\n\n return Iteration::CONTINUE;\n });\n\n pretty.ident();\n\n pretty.append(\"</\");\n\n pretty.color_depth();\n pretty.append(node.type());\n pretty.color_clear();\n\n pretty.append('>');\n}\n\n} // namespace markup\n" }, { "alpha_fraction": 0.5738953948020935, "alphanum_fraction": 0.5799898505210876, "avg_line_length": 23.012195587158203, "blob_id": "3711f46abeda9bdb0ffc247ea83edd424f32e46a", "content_id": "f767f26243dc790eabd4cd00bb1a3ddf56f4ac56", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1969, "license_type": "permissive", "max_line_length": 101, "num_lines": 82, "path": "/libraries/libwidget/Slider.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Slider.h>\n\nRecti Slider::track_bound()\n{\n return Recti{\n (bound().width() - THUMP_SIZE),\n bound().height(),\n }\n .with_height(TRACK_HEIGHT)\n .centered_within(bound());\n}\n\nRecti Slider::value_bound()\n{\n return track_bound()\n .take_left(track_bound().width() * _value);\n}\n\nRecti Slider::thumb_bound()\n{\n int posx = value_bound().right() - THUMP_SIZE / 2;\n\n return {\n posx,\n bound().height() / 2 - THUMP_SIZE / 2,\n THUMP_SIZE,\n THUMP_SIZE,\n };\n}\n\nvoid Slider::slide_to(Vec2i position)\n{\n Vec2i pos = position - bound().position();\n _value = pos.x() / (double)bound().width();\n _value = clamp(_value, 0, 1);\n\n Event event_value_changed = {};\n event_value_changed.type = Event::VALUE_CHANGE;\n dispatch_event(&event_value_changed);\n\n should_repaint();\n should_relayout();\n}\n\nSlider::Slider(Widget *parent) : Widget(parent)\n{\n min_width(160);\n}\n\nvoid Slider::event(Event *event)\n{\n if (is_mouse_event(event))\n {\n MouseEvent mouse_event = event->mouse;\n\n if (event->type == Event::MOUSE_MOVE && mouse_event.buttons & MOUSE_BUTTON_LEFT)\n {\n slide_to(mouse_event.position);\n event->accepted = true;\n }\n else if (event->type == Event::MOUSE_BUTTON_PRESS)\n {\n slide_to(mouse_event.position);\n event->accepted = true;\n }\n }\n}\n\nvoid Slider::paint(Painter &painter, const Recti &)\n{\n if (window()->focused())\n {\n painter.fill_rectangle(track_bound(), color(THEME_BORDER));\n painter.fill_rectangle(value_bound(), color(THEME_ACCENT));\n painter.fill_rectangle_rounded(thumb_bound(), bound().height() / 2, color(THEME_ACCENT));\n }\n else\n {\n painter.fill_rectangle(value_bound(), color(THEME_BACKGROUND));\n painter.fill_rectangle_rounded(thumb_bound(), bound().height() / 2, color(THEME_BACKGROUND));\n }\n}\n" }, { "alpha_fraction": 0.510138750076294, "alphanum_fraction": 0.5208110809326172, "avg_line_length": 16.370370864868164, "blob_id": "1a4a502cd8e86347be82d3958087de0029af4248", "content_id": "28c66c391d244dd82a741aa6f788e0cf1bc57978", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 937, "license_type": "permissive", "max_line_length": 63, "num_lines": 54, "path": "/libraries/libc/stdio/tempnam.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n// TODO: read this from system settings & env variable whatever\n#define TEMP_DIR \"/Temp/\"\n\nchar *tmpnam(const char *pfx)\n{\n return tempnam(NULL, pfx);\n}\n\nchar *tempnam(const char *dir, const char *pfx)\n{\n int plen;\n if (pfx == NULL || !pfx[0])\n {\n pfx = \"file\";\n plen = 4;\n }\n else\n {\n plen = strlen(pfx);\n if (plen > 5)\n {\n plen = 5;\n }\n }\n\n if (dir == NULL)\n {\n dir = TEMP_DIR;\n }\n else\n {\n assert(false);\n }\n\n // Unique number\n static unsigned int num = 0;\n char num_buf[6];\n snprintf(num_buf, 6, \"%u\", num);\n num++;\n\n char out_path[256];\n // First append the directory\n strcat(out_path, TEMP_DIR);\n // Then the prefix\n strcat(out_path, pfx);\n // then the unique number\n strcat(out_path, num_buf);\n\n return strdup(out_path);\n}" }, { "alpha_fraction": 0.5754923224449158, "alphanum_fraction": 0.5937272310256958, "avg_line_length": 30.88372039794922, "blob_id": "4a69964f79c16eb886ccd38ffd42637848d902f1", "content_id": "e66aa678ae2696884eda455906a907a797ee42b6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1371, "license_type": "permissive", "max_line_length": 79, "num_lines": 43, "path": "/libraries/libsystem/Macros.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define __packed __attribute__((packed))\n\n#define __aligned(__align) __attribute__((aligned(__align)))\n\n#define __unused(__stuff) (void)(__stuff)\n\n#define __create(__type) ((__type *)calloc(1, sizeof(__type)))\n\n#define __no_return __attribute__((noreturn))\n\n#define __cleanup(__function) __attribute__((__cleanup__(__function)))\n\n#define __cleanup_malloc __attribute__((__cleanup__(malloc_cleanup)))\n\n#define __flatten __attribute__((flatten))\n\n// Align the nearest _lower_ aligned address\n// ex: 8 with align = 8 -> 8\n// ex: 9 with align = 8 -> 16\n// ex: 7 with align = 8 -> 0\n#define __align_down(__addr, __align) ((__addr) & ~((__align)-1))\n\n// Align the nearest _upper_ aligned address\n// ex: 8 with align = 8 -> 8\n// ex: 9 with align = 8 -> 16\n// ex: 7 with align = 8 -> 8\n#define __align_up(__addr, __align) (((__addr) + (__align)-1) & ~((__align)-1))\n\n#define __array_length(__array) (sizeof(__array) / sizeof(__array[0]))\n\n#define __noncopyable(__class_name) \\\n __class_name(const __class_name &) = delete; \\\n __class_name &operator=(const __class_name &) = delete;\n\n#define __nonmovable(__class_name) \\\n __class_name(const __class_name &&) = delete; \\\n __class_name &operator=(const __class_name &&) = delete;\n\n#ifndef __always_inline\n# define __always_inline inline __attribute__((always_inline))\n#endif\n" }, { "alpha_fraction": 0.6652360558509827, "alphanum_fraction": 0.667382001876831, "avg_line_length": 13.121212005615234, "blob_id": "e13ccb12ec0fb2a34e42833b7a250f9be68ade4c", "content_id": "a38cf87c80a5a8a6c80201c3f94c6c9621fda52c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 932, "license_type": "permissive", "max_line_length": 34, "num_lines": 66, "path": "/libraries/abi/IOCall.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Network.h>\n\nstruct IOCallTerminalSizeArgs\n{\n int width;\n int height;\n};\n\nstruct IOCallDisplayModeArgs\n{\n int width;\n int height;\n};\n\nstruct IOCallDisplayBlitArgs\n{\n uint32_t *buffer;\n int buffer_width;\n int buffer_height;\n\n int blit_x;\n int blit_y;\n int blit_width;\n int blit_height;\n};\n\nstruct IOCallKeyboardSetKeymapArgs\n{\n void *keymap;\n size_t size;\n};\n\nstruct IOCallTextModeStateArgs\n{\n int width;\n int height;\n int cursor_x;\n int cursor_y;\n};\n\nstruct IOCallNetworkSateAgs\n{\n MacAddress mac_address;\n};\n\nenum IOCall\n{\n IOCALL_TERMINAL_GET_SIZE,\n IOCALL_TERMINAL_SET_SIZE,\n\n IOCALL_DISPLAY_GET_MODE,\n IOCALL_DISPLAY_SET_MODE,\n IOCALL_DISPLAY_BLIT,\n\n IOCALL_KEYBOARD_SET_KEYMAP,\n IOCALL_KEYBOARD_GET_KEYMAP,\n\n IOCALL_TEXTMODE_GET_STATE,\n IOCALL_TEXTMODE_SET_STATE,\n\n IOCALL_NETWORK_GET_STATE,\n\n __IOCALL_COUNT,\n};\n" }, { "alpha_fraction": 0.6459627151489258, "alphanum_fraction": 0.6645962595939636, "avg_line_length": 23.393939971923828, "blob_id": "1f6aa09d620e7f254b4575f603ad418edec5cda0", "content_id": "38355fdd5ba531fffbee3abe000f12e1ef039936", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 805, "license_type": "permissive", "max_line_length": 78, "num_lines": 33, "path": "/apps/terminal/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Application.h>\n#include <libwidget/ScrollBar.h>\n#include <libwidget/TitleBar.h>\n#include <libwidget/Window.h>\n\n#include \"terminal/TerminalWidget.h\"\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n theme_set_color(THEME_BACKGROUND, theme_get_color(THEME_ANSI_BACKGROUND));\n\n Window *window = new Window(WINDOW_RESIZABLE | WINDOW_ACRYLIC);\n\n window->icon(Icon::get(\"console-line\"));\n window->title(\"Terminal\");\n window->size(Vec2i(700, 500));\n window->opacity(0.85);\n\n window->root()->layout(VFLOW(0));\n\n new TitleBar(window->root());\n\n auto widget = new TerminalWidget(window->root());\n widget->focus();\n widget->flags(Widget::FILL);\n widget->outsets({0, 6, 6, 6});\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.701694905757904, "alphanum_fraction": 0.701694905757904, "avg_line_length": 18.66666603088379, "blob_id": "3568fcd349281c97afb2a52473949dd0f3b37cd0", "content_id": "d5c01f10f84973073da57d622918eb22a9269c6f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 295, "license_type": "permissive", "max_line_length": 94, "num_lines": 15, "path": "/libraries/libc/iconv.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n#include <stddef.h>\n\n__BEGIN_HEADER\n\ntypedef void *iconv_t;\n\niconv_t iconv_open(const char *tocode, const char *fromcode);\nsize_t iconv(iconv_t, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);\nint iconv_close(iconv_t);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.6707317233085632, "alphanum_fraction": 0.6707317233085632, "avg_line_length": 17.923076629638672, "blob_id": "be3c0793a941386525563345f34f8b0f192db57f", "content_id": "ba43a140aa26206e37197c57b4e51a4e63583360", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 246, "license_type": "permissive", "max_line_length": 41, "num_lines": 13, "path": "/apps/neko/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Application.h>\n\n#include \"neko/windows/MainWindow.h\"\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n auto window = new neko::MainWindow();\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.633004903793335, "alphanum_fraction": 0.6453201770782471, "avg_line_length": 21.58333396911621, "blob_id": "dcc2a512208f616bc45afed97f2df2e488c70b30", "content_id": "25de978dc7ff4ccd0fc3dd028d52bfdbd7ccc676", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 812, "license_type": "permissive", "max_line_length": 84, "num_lines": 36, "path": "/libraries/libsystem/io/Writer.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/Reader.h>\n#include <libsystem/io/SeekableReader.h>\n#include <libsystem/io/Writer.h>\n#include <libutils/Array.h>\n\n#define COPY_CHUNK_SIZE 4096\n\nvoid Writer::copy_from(Reader &reader)\n{\n assert(reader.position() == 0);\n\n Array<uint8_t, COPY_CHUNK_SIZE> copy_chunk;\n size_t chunk_size = 0;\n\n while ((chunk_size = reader.read(copy_chunk.raw_storage(), copy_chunk.count())))\n {\n write(copy_chunk.raw_storage(), chunk_size);\n }\n\n flush();\n}\n\nvoid Writer::copy_from(SeekableReader &reader)\n{\n reader.seek(0, WHENCE_START);\n\n Array<uint8_t, COPY_CHUNK_SIZE> copy_chunk;\n size_t chunk_size = 0;\n\n while ((chunk_size = reader.read(copy_chunk.raw_storage(), copy_chunk.count())))\n {\n write(copy_chunk.raw_storage(), chunk_size);\n }\n\n flush();\n}" }, { "alpha_fraction": 0.5633145570755005, "alphanum_fraction": 0.5656487345695496, "avg_line_length": 17.97047996520996, "blob_id": "eb8f424702b678983417380dab6c991980591e59", "content_id": "eec5931f13ba9770e5005d86bf0e7aa4be10c389", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5141, "license_type": "permissive", "max_line_length": 80, "num_lines": 271, "path": "/libraries/libsystem/eventloop/EventLoop.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <assert.h>\n#include <libsystem/Logger.h>\n#include <libsystem/eventloop/EventLoop.h>\n#include <libsystem/eventloop/Invoker.h>\n#include <libsystem/eventloop/Notifier.h>\n#include <libsystem/eventloop/Timer.h>\n#include <libsystem/math/MinMax.h>\n#include <libsystem/system/System.h>\n#include <libsystem/utils/List.h>\n#include <libutils/Vector.h>\n\nnamespace EventLoop\n{\n\n/* --- Notifiers ------------------------------------------------------------ */\n\nstatic size_t _handles_count;\nstatic Handle *_handles[PROCESS_HANDLE_COUNT];\nstatic PollEvent _events[PROCESS_HANDLE_COUNT];\n\nstatic Vector<Notifier *> _notifiers;\n\nvoid update_notifier()\n{\n for (size_t i = 0; i < _notifiers.count(); i++)\n {\n _handles[i] = _notifiers[i]->handle();\n _events[i] = _notifiers[i]->events();\n }\n\n _handles_count = _notifiers.count();\n}\n\nvoid register_notifier(Notifier *notifier)\n{\n\n _notifiers.push_back(notifier);\n\n update_notifier();\n}\n\nvoid unregister_notifier(Notifier *notifier)\n{\n _notifiers.remove_all_value(notifier);\n\n update_notifier();\n}\n\nvoid update_notifier(Handle *handle, PollEvent event)\n{\n for (size_t i = 0; i < _notifiers.count(); i++)\n {\n if (_notifiers[i]->handle() == handle &&\n _notifiers[i]->events() & event)\n {\n _notifiers[i]->invoke();\n }\n }\n}\n\n/* --- Timers --------------------------------------------------------------- */\n\nstatic Vector<Timer *> _timers;\n\nvoid register_timer(Timer *timer)\n{\n _timers.push_back(timer);\n}\n\nvoid unregister_timer(Timer *timer)\n{\n _timers.remove_value(timer);\n}\n\nvoid update_timers()\n{\n TimeStamp current_fire = system_get_ticks();\n\n auto timers_list_copy = _timers;\n\n timers_list_copy.foreach ([&](auto timer) {\n if (timer->running() && timer->scheduled() <= current_fire)\n {\n timer->trigger();\n timer->schedule(current_fire + timer->interval());\n }\n\n return Iteration::CONTINUE;\n });\n}\n\n/* --- Invokers ------------------------------------------------------------- */\n\nstatic Vector<Invoker *> _invoker;\n\nvoid register_invoker(Invoker *invoker)\n{\n _invoker.push_back(invoker);\n}\n\nvoid unregister_invoker(Invoker *invoker)\n{\n _invoker.remove_value(invoker);\n}\n\nvoid update_invoker()\n{\n _invoker.foreach ([](Invoker *invoker) {\n if (invoker->should_be_invoke_later())\n {\n invoker->invoke();\n }\n\n return Iteration::CONTINUE;\n });\n}\n\n/* --- Loop ----------------------------------------------------------------- */\n\nstatic bool _is_running = false;\nstatic bool _is_initialize = false;\nstatic int _exit_value = PROCESS_SUCCESS;\n\nstatic bool _nested_is_running = false;\nstatic int _nested_exit_value = 0;\n\nstatic Vector<AtExitHook> _atexit_hooks;\n\nvoid initialize()\n{\n assert(!_is_initialize);\n\n _is_initialize = true;\n}\n\nvoid uninitialize()\n{\n assert(_is_initialize);\n\n for (size_t i = 0; i < _atexit_hooks.count(); i++)\n {\n _atexit_hooks[i]();\n }\n\n _atexit_hooks.clear();\n\n _is_initialize = false;\n}\n\nstatic Timeout get_timeout()\n{\n Timeout timeout = UINT32_MAX;\n\n TimeStamp current_tick = system_get_ticks();\n\n _timers.foreach ([&](auto timer) {\n if (!timer->running() || timer->interval() == 0)\n {\n return Iteration::CONTINUE;\n }\n\n if (timer->scheduled() < current_tick)\n {\n timeout = 0;\n return Iteration::CONTINUE;\n }\n\n Timeout remaining = timer->scheduled() - current_tick;\n\n if (remaining <= timeout)\n {\n timeout = remaining;\n }\n\n return Iteration::CONTINUE;\n });\n\n return timeout;\n}\n\nvoid atexit(AtExitHook hook)\n{\n _atexit_hooks.push_back(hook);\n}\n\nvoid pump(bool pool)\n{\n assert(_is_initialize);\n\n Timeout timeout = 0;\n\n if (!pool)\n {\n timeout = get_timeout();\n }\n\n Handle *selected = nullptr;\n PollEvent selected_events = 0;\n\n Result result = handle_poll(\n &_handles[0],\n &_events[0],\n _handles_count,\n &selected,\n &selected_events,\n timeout);\n\n if (result_is_error(result))\n {\n logger_error(\"Failed to select : %s\", result_to_string(result));\n exit(PROCESS_FAILURE);\n }\n\n update_timers();\n\n update_notifier(selected, selected_events);\n\n update_invoker();\n}\n\nint run()\n{\n assert(_is_initialize);\n assert(!_is_running);\n\n _is_running = true;\n\n while (_is_running)\n {\n pump(false);\n }\n\n uninitialize();\n\n return _exit_value;\n}\n\nvoid exit(int exit_value)\n{\n assert(_is_initialize);\n\n _is_running = false;\n _exit_value = exit_value;\n}\n\nint run_nested()\n{\n assert(_is_initialize);\n assert(_is_running);\n assert(!_nested_is_running);\n\n _nested_is_running = true;\n\n while (_nested_is_running)\n {\n pump(false);\n }\n\n return _nested_exit_value;\n}\n\nvoid exit_nested(int exit_value)\n{\n assert(_is_initialize);\n assert(_nested_is_running);\n\n _nested_is_running = false;\n _nested_exit_value = exit_value;\n}\n\n} // namespace EventLoop" }, { "alpha_fraction": 0.6854838728904724, "alphanum_fraction": 0.6854838728904724, "avg_line_length": 15.533333778381348, "blob_id": "6604233fbc3215490b71c63d4e3646114addaf24", "content_id": "b97b841a3cecdc9a5fdd61d9382f6462cc8b1233", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 248, "license_type": "permissive", "max_line_length": 50, "num_lines": 15, "path": "/libraries/libwidget/Placeholder.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nclass Placeholder : public Widget\n{\nprivate:\n String _text;\n RefPtr<Icon> _alert_icon;\n\npublic:\n Placeholder(Widget *parent, String text);\n\n void paint(Painter &, const Recti &) override;\n};\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 13.666666984558105, "blob_id": "f6dac3af13cc41c34f3f211b8b1c3d922d7e1690", "content_id": "4ae398fec566479138d0f0c7c18227fa266dc21c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 44, "license_type": "permissive", "max_line_length": 29, "num_lines": 3, "path": "/kernel/storage/Partitions.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nvoid partitions_initialize();\n" }, { "alpha_fraction": 0.7153846025466919, "alphanum_fraction": 0.7153846025466919, "avg_line_length": 12, "blob_id": "37310ab31697684ee0564b1d4a2c5bb61d7bff36", "content_id": "5ffd12b4f709dd1c51a07c4ebe2ce9494f30890d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 130, "license_type": "permissive", "max_line_length": 31, "num_lines": 10, "path": "/libraries/libwidget/Container.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nclass Container : public Widget\n{\nprivate:\npublic:\n Container(Widget *parent);\n};\n" }, { "alpha_fraction": 0.6861090064048767, "alphanum_fraction": 0.6861090064048767, "avg_line_length": 21.44827651977539, "blob_id": "60f40eb45b0c5bb10a88f354a188b7731194d1b2", "content_id": "4755949a55f1cfad0b28e66358e72bcc469bae3d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1303, "license_type": "permissive", "max_line_length": 98, "num_lines": 58, "path": "/libraries/libsystem/io/Socket.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Connection.h>\n#include <libsystem/io/Socket.h>\n#include <libsystem/utils/List.h>\n\nstruct Socket\n{\n Handle handle;\n List *connections;\n};\n\nSocket *socket_open(const char *path, OpenFlag flags)\n{\n Socket *socket = __create(Socket);\n\n __plug_handle_open(HANDLE(socket), path, flags | OPEN_SOCKET);\n\n socket->connections = list_create();\n\n return socket;\n}\n\nvoid socket_close(Socket *socket)\n{\n list_destroy_with_callback(socket->connections, (ListDestroyElementCallback)connection_close);\n __plug_handle_close(HANDLE(socket));\n free(socket);\n}\n\nConnection *socket_connect(const char *path)\n{\n Handle handle = {};\n __plug_handle_connect(&handle, path);\n return connection_create(nullptr, handle);\n}\n\nConnection *socket_accept(Socket *socket)\n{\n Handle handle = {};\n __plug_handle_accept(HANDLE(socket), &handle);\n return connection_create(socket, handle);\n}\n\nvoid socket_did_connection_open(Socket *socket, struct Connection *connection)\n{\n if (socket)\n {\n list_pushback(socket->connections, connection);\n }\n}\n\nvoid socket_did_connection_close(Socket *socket, struct Connection *connection)\n{\n if (socket != nullptr)\n {\n list_remove(socket->connections, connection);\n }\n}\n" }, { "alpha_fraction": 0.5520833134651184, "alphanum_fraction": 0.6185897588729858, "avg_line_length": 16.095890045166016, "blob_id": "36a55c100d25d056a27dc9096b9c9d4a0cf250a6", "content_id": "651a4154df00b9f6b4b644632f169e967366b5e6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1248, "license_type": "permissive", "max_line_length": 62, "num_lines": 73, "path": "/libraries/libc/skift/Time.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\n#define EPOCH_YEAR 1970\n\n#define SECONDS_PER_MINUTE (60)\n#define SECONDS_PER_HOURS (SECONDS_PER_MINUTE * 60)\n#define SECONDS_PER_DAY (SECONDS_PER_HOURS * 24)\n#define MONTH_PER_YEAR 12\n\nstatic const int DAYS_PER_MONTH[2][MONTH_PER_YEAR] = {\n {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},\n {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},\n};\n\nstatic const int DAYS_PER_YEAR[2] = {365, 366};\n\n#define IS_LEAP_YEAR(__year) \\\n ((!((__year) % 4) && (__year) % 100) || !((__year) % 400))\n\ntypedef uint32_t ElapsedTime;\n\ntypedef uint32_t TimeStamp;\n\ntypedef uint32_t Timeout;\n\ntypedef uint32_t Tick;\n\nstruct Time\n{\n int second;\n int minute;\n int hour;\n};\n\nstruct Date\n{\n int day;\n int month;\n int year;\n};\n\nunion DateTime\n{\n struct\n {\n Time time;\n Date date;\n };\n\n struct\n {\n int second;\n int minute;\n int hour;\n int day;\n int month;\n int year;\n };\n};\n\nTimeStamp timestamp_now();\n\nTime timestamp_to_time(TimeStamp timestamp);\n\nDate timestamp_to_date(TimeStamp timestamp);\n\nDateTime timestamp_to_datetime(TimeStamp timestamp);\n\nTimeStamp datetime_to_timestamp(DateTime datetime);\n\nDateTime datetime_now();\n" }, { "alpha_fraction": 0.4563547372817993, "alphanum_fraction": 0.4685754179954529, "avg_line_length": 18.616437911987305, "blob_id": "b3ea83bccd1a7871f1ee6aba46861d6ce3497b72", "content_id": "d7ac4b1f30cb2979b2732767731769873444707e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2864, "license_type": "permissive", "max_line_length": 70, "num_lines": 146, "path": "/libraries/libutils/NumberFormat.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <math.h>\n#include <string.h>\n\n#include <libsystem/io_new/Writer.h>\n#include <libutils/Strings.h>\n\nstruct NumberFormat\n{\n int _base;\n int _precision;\n bool _capitalized;\n\n static NumberFormat binary()\n {\n return {2, 4, false};\n }\n\n static NumberFormat octal()\n {\n return {8, 4, false};\n }\n\n static NumberFormat decimal()\n {\n return {10, 4, false};\n }\n\n static NumberFormat hexadecimal()\n {\n return {16, 4, false};\n }\n\n NumberFormat capitalized()\n {\n NumberFormat copy = *this;\n copy._capitalized = true;\n return copy;\n }\n\n ResultOr<size_t> format(System::Writer &writer, int64_t value)\n {\n bool is_negative = value < 0;\n\n if (is_negative)\n {\n writer.write('-');\n value = -value;\n }\n\n auto format_result = format(writer, (uint64_t)value);\n\n if (format_result)\n {\n return *format_result + is_negative ? 1 : 0;\n }\n else\n {\n return format_result;\n }\n }\n\n ResultOr<size_t> format(System::Writer &writer, uint64_t value)\n {\n if (value == 0)\n {\n auto zero_result = writer.write('0');\n\n if (zero_result == SUCCESS)\n {\n return 1;\n }\n\n return zero_result;\n }\n\n size_t i = 0;\n char buffer[64] = {};\n\n while (value != 0)\n {\n if (_capitalized)\n {\n buffer[i] = Strings::LOWERCASE_XDIGITS[value % _base];\n }\n else\n {\n buffer[i] = Strings::UPPERCASE_XDIGITS[value % _base];\n }\n\n value /= _base;\n i++;\n }\n\n strrvs(buffer);\n\n return writer.write(buffer, i);\n }\n\n ResultOr<size_t> format(System::Writer &writer, float value)\n {\n return format(writer, (double)value);\n }\n\n ResultOr<size_t> format(System::Writer &writer, double value)\n {\n size_t written = 0;\n\n int64_t ipart = (int64_t)value;\n double fpart = value - (double)ipart;\n\n auto ipart_result = format(writer, ipart);\n\n if (!ipart_result)\n {\n return ipart_result;\n }\n\n written += *ipart_result;\n\n if (_precision > 0)\n {\n auto dot_result = writer.write('.');\n\n if (dot_result != SUCCESS)\n {\n return dot_result;\n }\n\n written += 1;\n\n int64_t ifpart = fpart * pow(_base, _precision);\n auto ifpart_result = format(writer, ifpart);\n\n if (!ifpart_result)\n {\n return ifpart_result;\n }\n\n written += *ipart_result;\n }\n\n return written;\n }\n};\n" }, { "alpha_fraction": 0.6061269044876099, "alphanum_fraction": 0.6586433053016663, "avg_line_length": 18.869565963745117, "blob_id": "50e00de010c42bf7a14973bea256c6c4354fc273", "content_id": "2e7153aa55d44321971e81d17f733879d79d3543", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 457, "license_type": "permissive", "max_line_length": 51, "num_lines": 23, "path": "/archs/x86_32/kernel/IOAPIC.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Logger.h>\n\n#include \"archs/x86_32/kernel/IOAPIC.h\"\n\nstatic volatile uint32_t *ioapic = nullptr;\n\nvoid ioapic_found(uintptr_t address)\n{\n ioapic = reinterpret_cast<uint32_t *>(address);\n logger_info(\"IOAPIC found at %08x\", ioapic);\n}\n\nuint32_t ioapic_read(uint32_t reg)\n{\n ioapic[0] = (reg & 0xff);\n return ioapic[4];\n}\n\nvoid ioapic_write(uint32_t reg, uint32_t value)\n{\n ioapic[0] = (reg & 0xff);\n ioapic[4] = value;\n}\n" }, { "alpha_fraction": 0.6757764220237732, "alphanum_fraction": 0.6770186424255371, "avg_line_length": 17.744186401367188, "blob_id": "df2ec10d6e3692f989da58483bc959379d78622f", "content_id": "66134e540035af026ac31e40ac1e796068896562", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 805, "license_type": "permissive", "max_line_length": 90, "num_lines": 43, "path": "/libraries/libsystem/compression/DeflateWriter.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/compression/DeflateWriter.h>\n#include <libsystem/io/MemoryReader.h>\n#include <libsystem/io/MemoryWriter.h>\n\n#define MAX_BLOCK_SIZE 0xFFFF\n\nDeflateWriter::DeflateWriter(Writer &writer, int level) : _deflate(level), _writer(writer)\n{\n}\n\nDeflateWriter::~DeflateWriter()\n{\n flush();\n}\n\nsize_t DeflateWriter::length()\n{\n return _writer.length();\n}\n\nsize_t DeflateWriter::position()\n{\n return _writer.position();\n}\n\nvoid DeflateWriter::flush()\n{\n MemoryReader mem_reader(_mem_buffer.data());\n _deflate.perform(mem_reader, _writer);\n _mem_buffer.clear();\n}\n\nsize_t DeflateWriter::write(const void *buffer, size_t size)\n{\n size_t written = _mem_buffer.write(buffer, size);\n\n if (_mem_buffer.length() > MAX_BLOCK_SIZE)\n {\n flush();\n }\n\n return written;\n}" }, { "alpha_fraction": 0.669658899307251, "alphanum_fraction": 0.6795332431793213, "avg_line_length": 22.20833396911621, "blob_id": "acbc742933f196b67915219d7496f87fc1711921", "content_id": "7ab83d19dc359f036b3a5b64d418efaf396daece", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1114, "license_type": "permissive", "max_line_length": 81, "num_lines": 48, "path": "/libraries/libfilepicker/dialogs/FilePicker.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Spacer.h>\n#include <libwidget/TitleBar.h>\n\n#include <libfilepicker/dialogs/FilePicker.h>\n#include <libfilepicker/widgets/DirectoryBrowser.h>\n#include <libfilepicker/widgets/ToolBar.h>\n\nnamespace filepicker\n{\n\nDialog::Dialog()\n{\n _navigation = make<Navigation>();\n _navigation->go_home_dont_record_history();\n buttons(DialogButton::OK | DialogButton::CANCEL);\n title(\"File picker\");\n}\n\nDialog::~Dialog()\n{\n}\n\nvoid Dialog::render(Window *window)\n{\n window->size(Vec2i(600, 400));\n window->root()->layout(VFLOW(0));\n\n new TitleBar(window->root());\n\n new ToolBar(window->root(), _navigation, nullptr, ToolBar::NO_OPEN_TERMINAL);\n\n auto browser = new DirectoryBrowser(window->root(), _navigation);\n browser->on_element_selected = [this](String &path) {\n _selected_file = path;\n close(DialogResult::OK);\n };\n\n auto action_container = new Panel(window->root());\n\n action_container->layout(HFLOW(4));\n action_container->insets(Insetsi(4, 4));\n\n new Spacer(action_container);\n\n create_buttons(action_container);\n}\n\n} // namespace filepicker\n" }, { "alpha_fraction": 0.588652491569519, "alphanum_fraction": 0.6085106134414673, "avg_line_length": 20.363636016845703, "blob_id": "def9b059bd04559eb344b8399eaea1f8ec11b17e", "content_id": "64ac45c288b314da154353a0f7330e5ea04fd07e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 705, "license_type": "permissive", "max_line_length": 75, "num_lines": 33, "path": "/apps/demo/DemoWidget.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/eventloop/Timer.h>\n#include <libwidget/Application.h>\n\n#include \"demo/DemoWidget.h\"\n\nvoid demo_widget_on_timer_tick(DemoWidget *widget)\n{\n widget->tick();\n widget->should_repaint();\n}\n\nDemoWidget::DemoWidget(Widget *parent)\n : Widget(parent)\n{\n _demo = nullptr;\n _timer = own<Timer>(1000 / 60, [this]() {\n tick();\n should_repaint();\n });\n\n _timer->start();\n}\n\nvoid DemoWidget::paint(Painter &painter, const Recti &)\n{\n if (_demo)\n {\n _demo->callback(painter, bound(), _time);\n }\n\n painter.draw_string(*font(), _demo->name, Vec2i(9, 17), Colors::BLACK);\n painter.draw_string(*font(), _demo->name, Vec2i(8, 16), Colors::WHITE);\n}\n" }, { "alpha_fraction": 0.6504854559898376, "alphanum_fraction": 0.655339777469635, "avg_line_length": 17.636363983154297, "blob_id": "a609f3157f51e698fa81c450a2299b38224c22f0", "content_id": "f09709e9910885fd7739d66ee887be32fb31002c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 206, "license_type": "permissive", "max_line_length": 47, "num_lines": 11, "path": "/libraries/libsystem/plugs/__plug_system.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <abi/Syscalls.h>\n\n#include <assert.h>\n#include <libsystem/core/Plugs.h>\n\nTick __plug_system_get_ticks()\n{\n Tick result = 0;\n assert(hj_system_tick(&result) == SUCCESS);\n return result;\n}\n" }, { "alpha_fraction": 0.6144578456878662, "alphanum_fraction": 0.6144578456878662, "avg_line_length": 9.375, "blob_id": "f1da0542abf4433de380da155b18bebef65e01b0", "content_id": "ffccbb518079d7d6d486e4c9c5be47462c011554", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 83, "license_type": "permissive", "max_line_length": 16, "num_lines": 8, "path": "/kernel/bus/UNIXAddress.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nenum UNIXAddress\n{\n UNIX_ZERO,\n UNIX_NULL,\n UNIX_RANDOM,\n};\n" }, { "alpha_fraction": 0.566135585308075, "alphanum_fraction": 0.567926824092865, "avg_line_length": 21.859912872314453, "blob_id": "453db8eeb39f776f66fcd7e267973a44c7c82b4a", "content_id": "6c91f7d6c2039956c80db6b388780b2550f0d6c2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10607, "license_type": "permissive", "max_line_length": 130, "num_lines": 464, "path": "/libraries/libwidget/Application.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/Logger.h>\n#include <libsystem/eventloop/EventLoop.h>\n#include <libsystem/eventloop/Notifier.h>\n#include <libsystem/io/Connection.h>\n#include <libsystem/io/Socket.h>\n#include <libsystem/process/Process.h>\n#include <libsystem/utils/Hexdump.h>\n#include <stdio.h>\n#include <string.h>\n\n#include <libsettings/Setting.h>\n\n#include <libwidget/Application.h>\n#include <libwidget/Screen.h>\n\n#include \"compositor/Protocol.h\"\n\nnamespace Application\n{\n\n/* --- Context -------------------------------------------------------------- */\n\nenum class State\n{\n UNINITIALIZED,\n RUNNING,\n EXITING,\n};\n\nVector<Window *> _windows;\nState _state = State::UNINITIALIZED;\nConnection *_connection;\nOwnPtr<Notifier> _connection_notifier;\nbool _wireframe = false;\n\n/* --- IPC ------------------------------------------------------------------ */\n\nvoid send_message(CompositorMessage message)\n{\n connection_send(_connection, &message, sizeof(CompositorMessage));\n}\n\nvoid do_message(const CompositorMessage &message)\n{\n if (message.type == COMPOSITOR_MESSAGE_EVENT_WINDOW)\n {\n Window *window = get_window(message.event_window.id);\n\n if (window)\n {\n Event copy = message.event_window.event;\n window->dispatch_event(&copy);\n }\n }\n else if (message.type == COMPOSITOR_MESSAGE_CHANGED_RESOLUTION)\n {\n Screen::bound(message.changed_resolution.resolution);\n\n for (size_t i = 0; i < _windows.count(); i++)\n {\n Event e = {\n .type = Event::DISPLAY_SIZE_CHANGED,\n .accepted = false,\n .mouse = {},\n .keyboard = {},\n };\n\n _windows[i]->dispatch_event(&e);\n }\n }\n else\n {\n logger_error(\"Got an invalid message from compositor (%d)!\", message.type);\n hexdump(&message, sizeof(CompositorMessage));\n Application::exit(PROCESS_FAILURE);\n }\n}\n\nResultOr<CompositorMessage> wait_for_message(CompositorMessageType expected_message)\n{\n Vector<CompositorMessage> pendings;\n\n CompositorMessage message{};\n connection_receive(_connection, &message, sizeof(CompositorMessage));\n\n if (handle_has_error(_connection))\n {\n return handle_get_error(_connection);\n }\n\n while (message.type != expected_message)\n {\n pendings.push_back(move(message));\n connection_receive(_connection, &message, sizeof(CompositorMessage));\n\n if (handle_has_error(_connection))\n {\n pendings.foreach ([&](auto &message) {\n do_message(message);\n return Iteration::CONTINUE;\n });\n\n return handle_get_error(_connection);\n }\n }\n\n pendings.foreach ([&](auto &message) {\n do_message(message);\n return Iteration::CONTINUE;\n });\n\n return message;\n}\n\nvoid wait_for_ack()\n{\n wait_for_message(COMPOSITOR_MESSAGE_ACK);\n}\n\nbool show_wireframe()\n{\n return _wireframe;\n}\n\nvoid show_window(Window *window)\n{\n assert(_state >= State::RUNNING);\n assert(_windows.contains(window));\n\n CompositorMessage message = {\n .type = COMPOSITOR_MESSAGE_CREATE_WINDOW,\n .create_window = {\n .id = window->handle(),\n .flags = window->flags(),\n .type = window->type(),\n .frontbuffer = window->frontbuffer_handle(),\n .frontbuffer_size = window->frontbuffer_size(),\n .backbuffer = window->backbuffer_handle(),\n .backbuffer_size = window->backbuffer_size(),\n .bound = window->bound_on_screen(),\n },\n };\n\n send_message(message);\n}\n\nvoid exit_if_all_windows_are_closed();\n\nvoid hide_window(Window *window)\n{\n assert(_windows.contains(window));\n\n CompositorMessage message = {\n .type = COMPOSITOR_MESSAGE_DESTROY_WINDOW,\n .destroy_window = {\n .id = window->handle(),\n },\n };\n\n send_message(message);\n exit_if_all_windows_are_closed();\n}\n\nvoid flip_window(Window *window, Recti dirty)\n{\n assert(_windows.contains(window));\n\n CompositorMessage message = {\n .type = COMPOSITOR_MESSAGE_FLIP_WINDOW,\n .flip_window = {\n .id = window->handle(),\n .frontbuffer = window->frontbuffer_handle(),\n .frontbuffer_size = window->frontbuffer_size(),\n .backbuffer = window->backbuffer_handle(),\n .backbuffer_size = window->backbuffer_size(),\n .dirty = dirty,\n .bound = window->bound_on_screen(),\n },\n };\n\n send_message(message);\n wait_for_ack();\n}\n\nvoid move_window(Window *window, Vec2i position)\n{\n assert(_windows.contains(window));\n\n CompositorMessage message = {\n .type = COMPOSITOR_MESSAGE_MOVE_WINDOW,\n .move_window = {\n .id = window->handle(),\n .position = position,\n },\n };\n\n send_message(message);\n}\n\nvoid window_change_cursor(Window *window, CursorState state)\n{\n assert(_windows.contains(window));\n\n CompositorMessage message = {\n .type = COMPOSITOR_MESSAGE_CURSOR_WINDOW,\n .cursor_window = {\n .id = window->handle(),\n .state = state,\n },\n };\n\n send_message(message);\n}\n\nVec2i mouse_position()\n{\n CompositorMessage message = {\n .type = COMPOSITOR_MESSAGE_GET_MOUSE_POSITION,\n .mouse_position = {},\n };\n\n send_message(message);\n\n auto result_or_mouse_position = wait_for_message(COMPOSITOR_MESSAGE_MOUSE_POSITION);\n\n if (result_or_mouse_position)\n {\n auto mouse_position = *result_or_mouse_position;\n\n return mouse_position.mouse_position.position;\n }\n else\n {\n return Vec2i::zero();\n }\n}\n\nvoid goodbye()\n{\n CompositorMessage m = {\n .type = COMPOSITOR_MESSAGE_GOODBYE,\n .mouse_position = {},\n };\n\n send_message(m);\n\n wait_for_ack();\n}\n\n/* --- Windows -------------------------------------------------------------- */\n\nvoid hide_all_windows()\n{\n for (size_t i = 0; i < _windows.count(); i++)\n {\n _windows[i]->hide();\n }\n}\n\nvoid exit_if_all_windows_are_closed()\n{\n if (_state == State::EXITING)\n {\n return;\n }\n\n bool should_close = true;\n\n for (size_t i = 0; i < _windows.count(); i++)\n {\n if (_windows[i]->visible())\n {\n should_close = false;\n break;\n }\n }\n\n if (should_close)\n {\n exit(PROCESS_SUCCESS);\n }\n}\n\nvoid add_window(Window *window)\n{\n assert(_state >= State::RUNNING);\n\n _windows.push_back(window);\n}\n\nvoid remove_window(Window *window)\n{\n _windows.push_back(window);\n exit_if_all_windows_are_closed();\n}\n\nWindow *get_window(int id)\n{\n assert(_state >= State::RUNNING);\n\n for (size_t i = 0; i < _windows.count(); i++)\n {\n if (_windows[i]->handle() == id)\n {\n return _windows[i];\n }\n }\n\n return nullptr;\n}\n\n/* --- Application ---------------------------------------------------------- */\n\nvoid hide_all_windows();\nvoid uninitialized();\n\nstatic OwnPtr<Settings::Setting> _setting_theme;\nstatic OwnPtr<Settings::Setting> _setting_wireframe;\n\nResult initialize(int argc, char **argv)\n{\n assert(_state == State::UNINITIALIZED);\n\n _setting_theme = own<Settings::Setting>(\n \"appearance:widgets.theme\",\n [](const json::Value &value) {\n auto new_theme = value.as_string();\n\n char buffer[256];\n snprintf(buffer, 256, \"/Files/Themes/%s.json\", new_theme.cstring());\n theme_load(buffer);\n\n for (size_t i = 0; i < _windows.count(); i++)\n {\n _windows[i]->should_repaint(_windows[i]->bound());\n }\n });\n\n _setting_wireframe = own<Settings::Setting>(\n \"appearance:widgets.wireframe\",\n [](const json::Value &value) {\n _wireframe = value.as_bool();\n for (size_t i = 0; i < _windows.count(); i++)\n {\n _windows[i]->should_repaint(_windows[i]->bound());\n }\n });\n\n for (int i = 0; i < argc; i++)\n {\n if (strcmp(argv[i], \"--wireframe\") == 0)\n {\n _wireframe = true;\n }\n }\n\n _connection = socket_connect(\"/Session/compositor.ipc\");\n\n if (handle_has_error(_connection))\n {\n logger_error(\"Failed to connect to the compositor: %s\", handle_error_string(_connection));\n\n Result result = handle_get_error(_connection);\n connection_close(_connection);\n _connection = nullptr;\n\n return result;\n }\n\n EventLoop::initialize();\n\n _connection_notifier = own<Notifier>(HANDLE(_connection), POLL_READ, []() {\n CompositorMessage message = {};\n memset((void *)&message, 0xff, sizeof(CompositorMessage));\n size_t message_size = connection_receive(_connection, &message, sizeof(CompositorMessage));\n\n if (handle_has_error(_connection))\n {\n logger_error(\"Connection to the compositor closed %s!\", handle_error_string(_connection));\n Application::exit(PROCESS_FAILURE);\n }\n\n if (message_size != sizeof(CompositorMessage))\n {\n logger_error(\"Got a message with an invalid size from compositor %u != %u!\", sizeof(CompositorMessage), message_size);\n hexdump(&message, message_size);\n Application::exit(PROCESS_FAILURE);\n }\n\n do_message(message);\n });\n\n _state = State::RUNNING;\n\n EventLoop::atexit(uninitialized);\n\n auto result_or_greetings = wait_for_message(COMPOSITOR_MESSAGE_GREETINGS);\n\n if (result_or_greetings.success())\n {\n auto greetings = result_or_greetings.take_value();\n\n Screen::bound(greetings.greetings.screen_bound);\n }\n\n return SUCCESS;\n}\n\nvoid uninitialized()\n{\n _state = State::UNINITIALIZED;\n}\n\nint run()\n{\n assert(_state == State::RUNNING);\n\n return EventLoop::run();\n}\n\nint run_nested()\n{\n assert(_state == State::RUNNING);\n\n return EventLoop::run_nested();\n}\n\nint pump()\n{\n assert(_state == State::RUNNING);\n\n EventLoop::pump(true);\n\n return 0;\n}\n\nvoid exit(int exit_value)\n{\n if (_state == State::EXITING)\n {\n return;\n }\n\n assert(_state == State::RUNNING);\n _state = State::EXITING;\n\n hide_all_windows();\n\n goodbye();\n\n _connection_notifier = nullptr;\n connection_close(_connection);\n\n EventLoop::exit(exit_value);\n}\n\nvoid exit_nested(int exit_value)\n{\n assert(_state == State::RUNNING);\n EventLoop::exit_nested(exit_value);\n}\n\n} // namespace Application\n" }, { "alpha_fraction": 0.6985294222831726, "alphanum_fraction": 0.6985294222831726, "avg_line_length": 11.952381134033203, "blob_id": "7be730f75a6dceb0cd6306a6be8aba795b5389a0", "content_id": "6a07b1b7ae4679d1f4f5af237a8c4663644316e2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 272, "license_type": "permissive", "max_line_length": 41, "num_lines": 21, "path": "/apps/panel/widgets/ApplicationListing.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/VScroll.h>\n\nnamespace panel\n{\n\nclass ApplicationListing : public VScroll\n{\nprivate:\n String _filter;\n\npublic:\n ApplicationListing(Widget *parent);\n\n void filter(const String &filter);\n\n void render();\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.5677603483200073, "alphanum_fraction": 0.5677603483200073, "avg_line_length": 14.931818008422852, "blob_id": "e679d9dd98ab69bfb773977cc1b77f63c1719c93", "content_id": "ba645d4b461c8497955adabbf183b42081243db2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 701, "license_type": "permissive", "max_line_length": 60, "num_lines": 44, "path": "/libraries/libsystem/eventloop/Invoker.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/eventloop/EventLoop.h>\n#include <libutils/Callback.h>\n#include <libutils/RefCounted.h>\n\nclass Invoker\n{\nprivate:\n bool _invoke_later = false;\n Callback<void()> _callback;\n\npublic:\n Invoker(Callback<void()> callback) : _callback(callback)\n {\n EventLoop::register_invoker(this);\n }\n\n ~Invoker()\n {\n EventLoop::unregister_invoker(this);\n }\n\n bool should_be_invoke_later()\n {\n return _invoke_later;\n }\n\n void invoke()\n {\n _invoke_later = false;\n _callback();\n }\n\n void invoke_later()\n {\n _invoke_later = true;\n }\n\n void cancel()\n {\n _invoke_later = false;\n }\n};\n" }, { "alpha_fraction": 0.7443181872367859, "alphanum_fraction": 0.7443181872367859, "avg_line_length": 16.600000381469727, "blob_id": "73dc765df157c2e31156bd422bd9dc845707233e", "content_id": "4ee776515f26f1ab22e2170fbb12deab01574212", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 176, "license_type": "permissive", "max_line_length": 42, "num_lines": 10, "path": "/libraries/libc/skift/Environment.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/json/Json.h>\n#include <libutils/String.h>\n\nvoid environment_load(const char *buffer);\n\njson::Value &environment();\n\nString environment_copy();\n" }, { "alpha_fraction": 0.711240291595459, "alphanum_fraction": 0.711240291595459, "avg_line_length": 21.478260040283203, "blob_id": "e31349569888f8e4be5335c483015f91fa7b62a7", "content_id": "6676869c5ec78de43492cd1ed232487b91ba2963", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 516, "license_type": "permissive", "max_line_length": 60, "num_lines": 23, "path": "/libraries/libsystem/io/FileReader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Handle.h>\n#include <libsystem/io/SeekableReader.h>\n\n#include <libutils/Path.h>\n\nclass FileReader final : public SeekableReader\n{\nprivate:\n System::Handle _handle;\n\npublic:\n FileReader(const char *path);\n FileReader(Path &path);\n FileReader(System::Handle &&handle);\n\n virtual size_t length() override;\n virtual size_t position() override;\n\n virtual size_t read(void *buffer, size_t size) override;\n virtual size_t seek(size_t pos, Whence whence) override;\n};" }, { "alpha_fraction": 0.7051281929016113, "alphanum_fraction": 0.7051281929016113, "avg_line_length": 10.142857551574707, "blob_id": "ced308c6d6c660cce11a7ea098b0c64a385ce59b", "content_id": "10eeb3769531e47019ccebca5682b2626f94d54a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 156, "license_type": "permissive", "max_line_length": 32, "num_lines": 14, "path": "/apps/settings/windows/MainWindow.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Window.h>\n\nnamespace Settings\n{\n\nclass MainWindow : public Window\n{\npublic:\n MainWindow();\n};\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.7107843160629272, "alphanum_fraction": 0.75, "avg_line_length": 21.66666603088379, "blob_id": "10e807af7446bb7d1c1cc478a923a3b32f6e3283", "content_id": "92f444e8412e3ffeb58846ff2b85d6db5d87febb", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 204, "license_type": "permissive", "max_line_length": 66, "num_lines": 9, "path": "/archs/x86_32/kernel/IOAPIC.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nvoid ioapic_found(uintptr_t address);\n\nuint32_t apic_read(void *ioapicaddr, uint32_t reg);\n\nvoid ioapic_write(void *ioapicaddr, uint32_t reg, uint32_t value);\n" }, { "alpha_fraction": 0.44260913133621216, "alphanum_fraction": 0.44935107231140137, "avg_line_length": 22.633466720581055, "blob_id": "a45b2d94f9c8d1a448f2ebbb2a2c6c90189e9814", "content_id": "579ca09dbdb78a9defdcae9d7eb3bdf6bfd0e32a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5933, "license_type": "permissive", "max_line_length": 96, "num_lines": 251, "path": "/libraries/libsystem/cmdline/CMDLine.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n/* cmdline.c: skiftOS command line application utils */\n\n#include <assert.h>\n#include <libsystem/cmdline/CMDLine.h>\n#include <libsystem/io/Stream.h>\n#include <libsystem/process/Process.h>\n#include <libutils/NumberParser.h>\n#include <stdio.h>\n\n/* --- Private functions ---------------------------------------------------- */\n\nCommandLineOption *get_long_option(CommandLine *cmdline, const char *name)\n{\n for (int i = 0; cmdline->options[i].type != COMMANDLINE_END; i++)\n {\n if (strcmp(cmdline->options[i].long_name, name) == 0)\n {\n return &cmdline->options[i];\n }\n }\n\n return nullptr;\n}\n\nCommandLineOption *get_short_option(CommandLine *cmdline, const char name)\n{\n for (int i = 0; cmdline->options[i].type != COMMANDLINE_END; i++)\n {\n if (cmdline->options[i].short_name == name)\n {\n return &cmdline->options[i];\n }\n }\n\n return nullptr;\n}\n\nvoid do_option(CommandLine *cmdline, CommandLineOption *option, int i, int argc, char **argv)\n{\n if (option->value != nullptr)\n {\n switch (option->type)\n {\n case COMMANDLINE_BOOLEAN:\n *((bool *)option->value) = true;\n break;\n\n case COMMANDLINE_STRING:\n if (i + 1 < argc && argv[i + 1] != nullptr)\n {\n *((char **)option->value) = argv[i + 1];\n argv[i + 1] = nullptr;\n }\n break;\n\n case COMMANDLINE_INTEGER:\n if (i + 1 < argc && argv[i + 1] != nullptr)\n {\n *((int *)option->value) = parse_int_inline(PARSER_DECIMAL, argv[i + 1], 0);\n argv[i + 1] = nullptr;\n }\n break;\n\n default:\n ASSERT_NOT_REACHED();\n }\n }\n\n if (option->callback)\n {\n option->callback(cmdline, option);\n }\n}\n\nsize_t cmdline_option_padding(CommandLineOption *options)\n{\n size_t maximal_length = 0;\n\n for (int i = 0; options[i].type != COMMANDLINE_END; i++)\n {\n CommandLineOption *opt = &options[i];\n size_t long_length = strlen(opt->long_name);\n\n if (long_length > maximal_length)\n {\n maximal_length = long_length;\n }\n }\n\n return maximal_length + 1;\n}\n\nvoid cmdline_callback_help(CommandLine *cmdline, CommandLineOption *option)\n{\n __unused(option);\n\n if (cmdline->prologue)\n {\n printf(\"%s\\n\\n\", cmdline->prologue);\n }\n\n if (cmdline->usages != nullptr)\n {\n printf(\"\\e[1mUsages:\\e[0m \");\n\n for (int i = 0; cmdline->usages[i]; i++)\n {\n printf(\"%s %s\\n\\t\", cmdline->name, cmdline->usages[i]);\n }\n\n printf(\"\\n\");\n }\n\n size_t padding = cmdline_option_padding(cmdline->options);\n\n printf(\"\\e[1mOptions:\\e[0m\");\n for (int i = 0; cmdline->options[i].type != COMMANDLINE_END; i++)\n {\n CommandLineOption *opt = &cmdline->options[i];\n if (opt->type == COMMANDLINE_SEPARATOR)\n {\n //printf(\"\\n\");\n }\n else if (opt->type == COMMANDLINE_SECTION)\n {\n printf(\"\\e[1m%s:\\e[0m\", opt->long_name);\n }\n else\n {\n if (opt->short_name != '\\0')\n {\n printf(\" -%c\", opt->short_name);\n }\n else\n {\n printf(\" \");\n }\n\n if (opt->long_name != nullptr)\n {\n printf(\", --%s\", opt->long_name);\n }\n else\n {\n printf(\" \");\n }\n\n if (opt->type == COMMANDLINE_STRING ||\n opt->type == COMMANDLINE_INTEGER)\n {\n printf(\"[value] \");\n }\n\n if (opt->long_name == nullptr)\n {\n printf(\" \");\n }\n\n if (opt->description != nullptr)\n {\n size_t pad_length = padding - strlen(opt->long_name);\n\n for (size_t i = 0; i < pad_length; i++)\n {\n printf(\" \");\n }\n\n printf(\"%s\", opt->description);\n }\n }\n\n printf(\"\\n\\t\");\n }\n\n printf(\"\\n\");\n\n if (cmdline->epiloge)\n {\n printf(cmdline->epiloge);\n printf(\"\\n\");\n }\n\n process_exit(0);\n}\n\n/* --- Public functions ----------------------------------------------------- */\n\nint cmdline_parse(CommandLine *cmdline, int argc, char **argv)\n{\n cmdline->name = argv[0];\n\n // Parsing arguments\n for (int i = 1; i < argc; i++)\n {\n char *current_argument = argv[i];\n\n if (current_argument == nullptr)\n {\n continue;\n }\n\n if (current_argument[0] != '-')\n {\n continue;\n }\n\n if (current_argument[1] == '-')\n {\n CommandLineOption *option = get_long_option(cmdline, current_argument + 2);\n\n if (option == nullptr)\n {\n stream_format(err_stream, \"Unknow option '%s'!\\n\", current_argument + 2);\n process_exit(-1);\n }\n\n do_option(cmdline, option, i, argc, argv);\n }\n else\n {\n for (int j = 0; current_argument[1 + j]; j++)\n {\n CommandLineOption *option = get_short_option(cmdline, current_argument[1 + j]);\n\n if (option == nullptr)\n {\n stream_format(err_stream, \"Unknow option '%c'!\\n\", current_argument[1 + j]);\n process_exit(-1);\n }\n\n do_option(cmdline, option, i, argc, argv);\n }\n }\n\n argv[i] = nullptr;\n }\n\n // Packing argv\n int index = 0;\n\n for (int i = 0; i < argc; i++)\n {\n if (argv[i] != nullptr)\n {\n argv[index] = argv[i];\n index++;\n }\n }\n\n return index;\n}\n" }, { "alpha_fraction": 0.7271364331245422, "alphanum_fraction": 0.8035982251167297, "avg_line_length": 36.05555725097656, "blob_id": "88783e09ca73b7db33d97d9e09ff15da61eafcfc", "content_id": "3fbdbe41d6969189892b7e07537e20f3ed8b0e5b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 667, "license_type": "permissive", "max_line_length": 89, "num_lines": 18, "path": "/libraries/libutils/Strings.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nnamespace Strings\n{\n\nstatic constexpr auto WHITESPACE = \" \\n\\r\\t\";\nstatic constexpr auto DIGITS = \"0123456789\";\nstatic constexpr auto XDIGITS = \"0123456789abcdef\";\nstatic constexpr auto ALL_XDIGITS = \"0123456789abcdefABCDEF\";\nstatic constexpr auto LOWERCASE_XDIGITS = \"0123456789abcdef\";\nstatic constexpr auto UPPERCASE_XDIGITS = \"0123456789ABCDEF\";\nstatic constexpr auto UTF8BOM = \"\\xEF\\xBB\\xBF\";\n\nstatic constexpr auto ALL_ALPHA = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nstatic constexpr auto LOWERCASE_ALPHA = \"abcdefghijklmnopqrstuvwxyz\";\nstatic constexpr auto UPPERCASE_ALPHA = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n} // namespace Strings\n" }, { "alpha_fraction": 0.5852090120315552, "alphanum_fraction": 0.5884244441986084, "avg_line_length": 18.06122398376465, "blob_id": "cbf43815bc91b844adb50163b55e1d22bafa0e30", "content_id": "3a16a2c02c50aadbbe07b0e296025c56fc4d5186", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 933, "license_type": "permissive", "max_line_length": 65, "num_lines": 49, "path": "/libraries/libsystem/io/BinaryWriter.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/Common.h>\n#include <libsystem/io/Writer.h>\n#include <libutils/String.h>\n\nclass BinaryWriter : public Writer\n{\nprivate:\n Writer &_writer;\n\npublic:\n BinaryWriter(Writer &writer) : _writer(writer)\n {\n }\n\n // Put functions\n template <typename T>\n inline void put(const T &data)\n {\n uint8_t *bytes = (uint8_t *)&data;\n write(bytes, sizeof(T));\n }\n\n inline void put_fixed_len_string(const String &str)\n {\n write((uint8_t *)str.cstring(), str.length());\n }\n\n // Inherited from Writer\n inline size_t position() override\n {\n return _writer.position();\n }\n\n inline size_t length() override\n {\n return _writer.length();\n }\n\n inline void flush() override\n {\n _writer.flush();\n }\n\n inline size_t write(const void *buffer, size_t size) override\n {\n return _writer.write(buffer, size);\n }\n};" }, { "alpha_fraction": 0.5545338988304138, "alphanum_fraction": 0.5558021664619446, "avg_line_length": 16.23497200012207, "blob_id": "cfdc04fa30a4a5bfbde7ef9236b44c9108a12aa1", "content_id": "41a1caaa2ffb55a99b2968715146c1f48f65148d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3154, "license_type": "permissive", "max_line_length": 105, "num_lines": 183, "path": "/libraries/libmarkup/Parser.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/Logger.h>\n#include <libutils/unicode/Codepoint.h>\n#include <libutils/NumberParser.h>\n#include <libutils/Scanner.h>\n#include <libutils/ScannerUtils.h>\n#include <libutils/StringBuilder.h>\n#include <libutils/Strings.h>\n#include <string.h>\n\n#include <libmarkup/Markup.h>\n\nnamespace markup\n{\n\nstatic void whitespace(Scanner &scan)\n{\n scan.eat(Strings::WHITESPACE);\n}\n\nstatic String identifier(Scanner &scan)\n{\n StringBuilder builder{};\n\n while (scan.current_is(Strings::ALL_ALPHA) &&\n scan.do_continue())\n {\n builder.append(scan.current());\n scan.foreward();\n }\n\n return builder.finalize();\n}\n\nstatic String string(Scanner &scan)\n{\n StringBuilder builder{};\n\n scan.skip('\"');\n\n while (scan.do_continue() &&\n scan.current() != '\"')\n {\n if (scan.current() == '\\\\')\n {\n builder.append(scan_json_escape_sequence(scan));\n }\n else\n {\n builder.append(scan.current());\n scan.foreward();\n }\n }\n\n scan.skip('\"');\n\n return builder.finalize();\n}\n\nstatic void attribute(Scanner &scan, Attributes &attr)\n{\n auto ident = identifier(scan);\n\n whitespace(scan);\n\n if (scan.skip('='))\n {\n whitespace(scan);\n attr[ident] = string(scan);\n }\n else\n {\n attr[ident] = \"\";\n }\n}\n\nstatic Node opening_tag(Scanner &scan)\n{\n if (!scan.skip('<'))\n {\n return {\"error\"};\n }\n\n whitespace(scan);\n\n auto type = identifier(scan);\n\n whitespace(scan);\n\n Attributes attr{};\n\n while (scan.current_is(Strings::ALL_ALPHA) &&\n scan.do_continue())\n {\n attribute(scan, attr);\n whitespace(scan);\n }\n\n auto flags = Node::NONE;\n\n if (scan.skip('/'))\n {\n scan.skip('>');\n\n flags = Node::SELF_CLOSING;\n }\n\n scan.skip('>');\n\n return {type, flags, move(attr)};\n}\n\nstatic void closing_tag(Scanner &scan, const Node &node)\n{\n scan.skip('<');\n scan.skip('/');\n\n whitespace(scan);\n\n auto type = identifier(scan);\n\n if (!node.is(type))\n {\n logger_warn(\n \"Opening tag <%s> doesn't match closing tag </%s>\",\n node.type().cstring(),\n type.cstring());\n }\n\n whitespace(scan);\n\n scan.skip('>');\n}\n\nstatic Node node(Scanner &scan)\n{\n whitespace(scan);\n\n auto n = opening_tag(scan);\n\n if (n.flags() & Node::SELF_CLOSING)\n {\n return n;\n }\n\n whitespace(scan);\n\n while (scan.peek(0) == '<' &&\n scan.peek(1) != '/' &&\n scan.do_continue())\n {\n n.add_child(node(scan));\n whitespace(scan);\n }\n\n whitespace(scan);\n\n closing_tag(scan, n);\n\n return n;\n}\n\nNode parse(Scanner &scan)\n{\n scan_skip_utf8bom(scan);\n return node(scan);\n}\n\nNode parse_file(String path)\n{\n __cleanup(stream_cleanup) Stream *json_file = stream_open(path.cstring(), OPEN_READ | OPEN_BUFFERED);\n\n if (handle_has_error(json_file))\n {\n return {\"error\"};\n }\n\n StreamScanner scan{json_file};\n scan_skip_utf8bom(scan);\n return node(scan);\n}\n\n} // namespace markup\n" }, { "alpha_fraction": 0.6964980363845825, "alphanum_fraction": 0.6964980363845825, "avg_line_length": 15.0625, "blob_id": "1b1de6574e1b7eee878f45edcf2c98ab339e324b", "content_id": "71cf16892d5c10ea2a3ef19d28b8c4ef8732a420", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 257, "license_type": "permissive", "max_line_length": 90, "num_lines": 16, "path": "/kernel/drivers/VirtioGraphic.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"kernel/devices/VirtioDevice.h\"\n\nclass VirtioGraphic : public VirtioDevice\n{\nprivate:\npublic:\n VirtioGraphic(DeviceAddress address) : VirtioDevice(address, DeviceClass::FRAMEBUFFER)\n {\n }\n\n ~VirtioGraphic()\n {\n }\n};\n" }, { "alpha_fraction": 0.5856992602348328, "alphanum_fraction": 0.5888538360595703, "avg_line_length": 15.701754570007324, "blob_id": "453d8a9598410911e624d1e15c9e406e569dd890", "content_id": "3c57f907fa9ae5406ff124848d5816fcc5a95ee9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 951, "license_type": "permissive", "max_line_length": 99, "num_lines": 57, "path": "/libraries/libsystem/io/FileWriter.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/FileWriter.h>\n\nFileWriter::FileWriter(const char *path) : _handle(path, OPEN_WRITE | OPEN_CREATE | OPEN_STREAM)\n{\n}\n\nFileWriter::FileWriter(Path &path) : _handle(path.string(), OPEN_WRITE | OPEN_CREATE | OPEN_STREAM)\n{\n}\n\nFileWriter::FileWriter(System::Handle &&handle) : _handle{move(handle)}\n{\n}\n\nvoid FileWriter::flush() {}\n\nsize_t FileWriter::write(const void *buffer, size_t size)\n{\n auto result_or_write = _handle.write(buffer, size);\n\n if (result_or_write)\n {\n return *result_or_write;\n }\n else\n {\n return 0;\n }\n}\n\nsize_t FileWriter::length()\n{\n auto result_or_stat = _handle.stat();\n\n if (result_or_stat)\n {\n return result_or_stat->size;\n }\n else\n {\n return 0;\n }\n}\n\nsize_t FileWriter::position()\n{\n auto result_or_tell = _handle.tell();\n\n if (result_or_tell)\n {\n return *result_or_tell;\n }\n else\n {\n return 0;\n }\n}" }, { "alpha_fraction": 0.7027027010917664, "alphanum_fraction": 0.7027027010917664, "avg_line_length": 11.333333015441895, "blob_id": "cd4cb754e79d5156942ddb084a2f09e565949336", "content_id": "659b2ec95db80827adc51e65e7ad2fdc05c86878", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 37, "license_type": "permissive", "max_line_length": 20, "num_lines": 3, "path": "/libraries/libwidget/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += WIDGET\n\nWIDGET_NAME = widget\n" }, { "alpha_fraction": 0.5450746417045593, "alphanum_fraction": 0.5495522618293762, "avg_line_length": 15.507389068603516, "blob_id": "267498e1acdba97d23596bc08fd2415735d1a7f8", "content_id": "5e125cd4fb644b5d83b226e8a38b86dee6feb681", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3350, "license_type": "permissive", "max_line_length": 105, "num_lines": 203, "path": "/libraries/libutils/json/Parser.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/NumberParser.h>\n#include <libutils/Scanner.h>\n#include <libutils/ScannerUtils.h>\n#include <libutils/StringBuilder.h>\n#include <libutils/Strings.h>\n#include <libutils/json/Value.h>\n\nnamespace json\n{\nValue value(Scanner &scan);\n\ninline void whitespace(Scanner &scan)\n{\n scan.eat(Strings::WHITESPACE);\n}\n\ninline Value number(Scanner &scan)\n{\n#ifdef __KERNEL__\n return Value{scan_int(scan, 10)};\n#else\n return {scan_float(scan)};\n#endif\n}\n\ninline String string(Scanner &scan)\n{\n StringBuilder builder{};\n\n scan.skip('\"');\n\n while (scan.current() != '\"' && scan.do_continue())\n {\n if (scan.current() == '\\\\')\n {\n builder.append(scan_json_escape_sequence(scan));\n }\n else\n {\n builder.append(scan.current());\n scan.foreward();\n }\n }\n\n scan.skip('\"');\n\n return builder.finalize();\n}\n\ninline Value array(Scanner &scan)\n{\n scan.skip('[');\n\n Value::Array array{};\n\n whitespace(scan);\n\n if (scan.skip(']'))\n {\n return move(array);\n }\n\n int index = 0;\n\n do\n {\n scan.skip(',');\n array.push_back(value(scan));\n index++;\n } while (scan.current() == ',');\n\n scan.skip(']');\n\n return move(array);\n}\n\ninline Value object(Scanner &scan)\n{\n scan.skip('{');\n\n Value::Object object{};\n\n whitespace(scan);\n\n if (scan.skip('}'))\n {\n return move(object);\n }\n\n while (scan.current() != '}')\n {\n auto k = string(scan);\n whitespace(scan);\n\n scan.skip(':');\n\n object[k] = value(scan);\n\n scan.skip(',');\n\n whitespace(scan);\n }\n\n scan.skip('}');\n\n return object;\n}\n\ninline Value keyword(Scanner &scan)\n{\n StringBuilder builder{};\n\n while (scan.current_is(Strings::LOWERCASE_ALPHA) &&\n scan.do_continue())\n {\n builder.append(scan.current());\n scan.foreward();\n }\n\n auto keyword = builder.finalize();\n\n if (keyword == \"true\")\n {\n return true;\n }\n else if (keyword == \"false\")\n {\n return false;\n }\n else\n {\n return nullptr;\n }\n}\n\ninline Value value(Scanner &scan)\n{\n whitespace(scan);\n\n Value value{};\n\n if (scan.current() == '\"')\n {\n value = string(scan);\n }\n else if (scan.current_is(\"-\") ||\n scan.current_is(\"0123456789\"))\n {\n value = number(scan);\n }\n else if (scan.current() == '{')\n {\n value = object(scan);\n }\n else if (scan.current() == '[')\n {\n value = array(scan);\n }\n else\n {\n value = keyword(scan);\n }\n\n whitespace(scan);\n\n return value;\n}\n\ninline Value parse(Scanner &scan)\n{\n scan_skip_utf8bom(scan);\n return value(scan);\n}\n\ninline Value parse(const char *str, size_t size)\n{\n StringScanner scan{str, size};\n return parse(scan);\n};\n\ninline Value parse(const String &str)\n{\n StringScanner scan{str.cstring(), str.length()};\n return parse(scan);\n};\n\ninline Value parse_file(String path)\n{\n __cleanup(stream_cleanup) Stream *json_file = stream_open(path.cstring(), OPEN_READ | OPEN_BUFFERED);\n\n if (handle_has_error(json_file))\n {\n return nullptr;\n }\n\n StreamScanner scan{json_file};\n scan_skip_utf8bom(scan);\n return value(scan);\n}\n\n} // namespace json" }, { "alpha_fraction": 0.5766961574554443, "alphanum_fraction": 0.5792772769927979, "avg_line_length": 18.941177368164062, "blob_id": "e109157f1c25aff69a42a34ee426ad83afc50bfd", "content_id": "ed0095f516e93897332d481451947c51cf400271", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2712, "license_type": "permissive", "max_line_length": 80, "num_lines": 136, "path": "/apps/shell/Parser.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Logger.h>\n#include <libsystem/utils/BufferBuilder.h>\n\n#include <libutils/Scanner.h>\n#include <libutils/ScannerUtils.h>\n\n#include \"shell/Nodes.h\"\n\n#define SHELL_WHITESPACE \" \\r\\n\\t\"\n\nstatic void whitespace(Scanner &scan)\n{\n scan.eat(SHELL_WHITESPACE);\n}\n\nstatic char *string(Scanner &scan)\n{\n BufferBuilder *builder = buffer_builder_create(16);\n\n scan.skip('\"');\n\n while (scan.current() != '\"' &&\n scan.do_continue())\n {\n if (scan.current() == '\\\\')\n {\n buffer_builder_append_str(builder, scan_json_escape_sequence(scan));\n }\n else\n {\n buffer_builder_append_chr(builder, scan.current());\n scan.foreward();\n }\n }\n\n scan.skip('\"');\n\n return buffer_builder_finalize(builder);\n}\n\nstatic char *argument(Scanner &scan)\n{\n if (scan.current() == '\"')\n {\n return string(scan);\n }\n\n BufferBuilder *builder = buffer_builder_create(16);\n\n while (!scan.current_is(SHELL_WHITESPACE) &&\n scan.do_continue())\n {\n if (scan.current() == '\\\\')\n {\n scan.foreward();\n }\n\n if (scan.do_continue())\n {\n buffer_builder_append_chr(builder, scan.current());\n scan.foreward();\n }\n }\n\n return buffer_builder_finalize(builder);\n}\n\nstatic ShellNode *command(Scanner &scan)\n{\n char *command_name = argument(scan);\n\n whitespace(scan);\n\n List *arguments = list_create();\n\n whitespace(scan);\n\n while (scan.do_continue() &&\n scan.current() != '|' &&\n scan.current() != '>')\n {\n list_pushback(arguments, argument(scan));\n whitespace(scan);\n }\n\n return shell_command_create(command_name, arguments);\n}\n\nstatic ShellNode *pipeline(Scanner &scan)\n{\n List *commands = list_create();\n\n do\n {\n whitespace(scan);\n list_pushback(commands, command(scan));\n whitespace(scan);\n } while (scan.skip('|'));\n\n if (commands->count() == 1)\n {\n ShellNode *node = (ShellNode *)list_peek(commands);\n list_destroy(commands);\n return node;\n }\n\n return shell_pipeline_create(commands);\n}\n\nstatic ShellNode *redirect(Scanner &scan)\n{\n ShellNode *node = pipeline(scan);\n\n whitespace(scan);\n\n if (!scan.skip('>'))\n {\n return node;\n }\n\n whitespace(scan);\n\n char *destination = argument(scan);\n\n return shell_redirect_create(node, destination);\n}\n\nShellNode *shell_parse(char *command_text)\n{\n StringScanner scan(command_text, strlen(command_text));\n\n // Skip the utf8 bom header if present.\n scan_skip_utf8bom(scan);\n whitespace(scan);\n return redirect(scan);\n}\n" }, { "alpha_fraction": 0.71659916639328, "alphanum_fraction": 0.7206477522850037, "avg_line_length": 18.076923370361328, "blob_id": "5601a6f357e67defeaebbab7cfa01b030e5a57d5", "content_id": "b34c06642cfd760d174d7d975878711ef66733f1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 247, "license_type": "permissive", "max_line_length": 55, "num_lines": 13, "path": "/libraries/libsystem/io/SeekableReader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Filesystem.h>\n#include <libsystem/io/Reader.h>\n\nclass Writer;\nclass SeekableReader : public Reader\n{\npublic:\n virtual size_t seek(size_t pos, Whence whence) = 0;\n\n virtual void copy_to(Writer &writer) override;\n};" }, { "alpha_fraction": 0.5934343338012695, "alphanum_fraction": 0.5959596037864685, "avg_line_length": 17, "blob_id": "47a62f1f8e8b4556cfec969c28033b64da670c1c", "content_id": "fc5324b8c49103ae5c996c4ad6209a3a327570af", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 792, "license_type": "permissive", "max_line_length": 80, "num_lines": 44, "path": "/libraries/libwidget/Application.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Window.h>\n\nnamespace Application\n{\n\n/* --- Server --------------------------------------------------------------- */\n\nvoid show_window(Window *window);\n\nvoid hide_window(Window *window);\n\nvoid flip_window(Window *window, Recti bound);\n\nvoid move_window(Window *window, Vec2i position);\n\nvoid window_change_cursor(Window *window, CursorState state);\n\nVec2i mouse_position();\n\n/* --- Client --------------------------------------------------------------- */\n\nvoid add_window(Window *window);\n\nvoid remove_window(Window *window);\n\nWindow *get_window(int id);\n\nResult initialize(int argc, char **argv);\n\nint run();\n\nint run_nested();\n\nint pump();\n\nvoid exit(int exit_value);\n\nvoid exit_nested(int exit_value);\n\nbool show_wireframe();\n\n} // namespace Application\n" }, { "alpha_fraction": 0.6400966048240662, "alphanum_fraction": 0.6425120830535889, "avg_line_length": 19.700000762939453, "blob_id": "b085f705b84a1638ea0eed5bf7f32bbef950124b", "content_id": "12ca05dae276641a2fa9e26828c6eba94f15fab1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 414, "license_type": "permissive", "max_line_length": 91, "num_lines": 20, "path": "/libraries/libwidget/Panel.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n#include <libsystem/Logger.h>\n#include <libwidget/Panel.h>\n\nPanel::Panel(Widget *parent)\n : Widget(parent)\n{\n}\n\nvoid Panel::paint(Painter &painter, const Recti &)\n{\n if (_border_radius > 0)\n {\n painter.fill_rectangle_rounded(bound(), _border_radius, color(THEME_MIDDLEGROUND));\n }\n else\n {\n painter.clear(bound(), color(THEME_MIDDLEGROUND));\n }\n}\n" }, { "alpha_fraction": 0.5710784196853638, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 20.473684310913086, "blob_id": "4b6f87b4438219bfdc2944baca13a2469282a0ae", "content_id": "0a3b25ddf3f8e0e9e266fa64a42fdeb687548b8e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 408, "license_type": "permissive", "max_line_length": 67, "num_lines": 19, "path": "/apps/utilities/unlink.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/Filesystem.h>\n#include <libsystem/io/Stream.h>\n\nint main(int argc, char **argv)\n{\n if (argc == 1)\n {\n stream_format(err_stream, \"%s: missing operand\", argv[0]);\n return PROCESS_FAILURE;\n }\n\n if (argc < 2)\n {\n stream_format(err_stream, \"%s: extra operand\\n,\", argv[2]);\n return PROCESS_FAILURE;\n }\n\n return filesystem_unlink(argv[1]);\n}\n" }, { "alpha_fraction": 0.7397260069847107, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 17.25, "blob_id": "720da4a8afc7e037f4d7bad27afc6e2a46d466ad", "content_id": "a390eec40e7c51dfb1eba29e6524780f99d45868", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 73, "license_type": "permissive", "max_line_length": 38, "num_lines": 4, "path": "/apps/panel/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += PANEL\n\nPANEL_NAME = panel\nPANEL_LIBS = widget settings graphic c\n" }, { "alpha_fraction": 0.5001689791679382, "alphanum_fraction": 0.5079419016838074, "avg_line_length": 26.91509437561035, "blob_id": "6ff473f3e05119128e2d516540159f7633972433", "content_id": "3fd65355b9354978ecefa7099a728fcd09963353", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5918, "license_type": "permissive", "max_line_length": 96, "num_lines": 212, "path": "/libraries/libsystem/cmdline/ReadLine.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Logger.h>\n#include <libsystem/cmdline/History.h>\n#include <libsystem/cmdline/ReadLine.h>\n#include <libsystem/io/Stream.h>\n#include <stdio.h>\n\n#define READLINE_ALLOCATED 128\n\nstatic UnicodeString *readline_string(ReadLine *readline)\n{\n if (readline->history_current == 0)\n {\n return readline->string;\n }\n else\n {\n return history_peek(readline->history_current - 1);\n }\n}\n\nstatic char *readline_cstring(ReadLine *readline)\n{\n return unicode_string_as_cstring(readline_string(readline));\n}\n\nstatic void readline_recale_history(ReadLine *readline)\n{\n if (readline->history_current != 0)\n {\n unicode_string_copy(history_peek(readline->history_current - 1), readline->string);\n readline->history_current = 0;\n }\n}\n\nstatic void readline_repaint(ReadLine *readline)\n{\n printf(\"\\e[%luD\\e[J\", readline->old_cursor);\n\n __cleanup_malloc char *cstring_buffer = readline_cstring(readline);\n\n stream_write(out_stream, cstring_buffer, strlen(cstring_buffer));\n\n printf(\"\\e[%luD\", unicode_string_length(readline_string(readline)));\n\n printf(\"\\e[%luC\", readline->cursor);\n\n readline->old_cursor = readline->cursor;\n}\n\nResult readline_readline(ReadLine *readline, char **line)\n{\n unicode_string_clear(readline->string);\n\n readline->cursor = 0;\n readline->old_cursor = 0;\n readline->should_continue = true;\n\n while (readline->should_continue &&\n !readline->scan->ended())\n {\n if (readline->scan->current() == U'\\n' ||\n readline->scan->current() == U'\\r')\n {\n readline_recale_history(readline);\n\n readline->should_continue = false;\n\n readline->scan->foreward();\n }\n else if (readline->scan->current() == U'\\b' ||\n readline->scan->current() == 127 /*DEL*/)\n {\n readline_recale_history(readline);\n\n if (readline->cursor > 0)\n {\n readline->cursor--;\n unicode_string_remove(readline->string, readline->cursor);\n }\n\n readline->scan->foreward();\n }\n else if (readline->scan->current() == U'\\t')\n {\n readline->scan->foreward();\n }\n else if (readline->scan->current() == U'\\e')\n {\n readline->scan->foreward();\n\n if (readline->scan->current() != '[')\n {\n continue;\n }\n\n readline->scan->foreward();\n\n if (readline->scan->current() == 'A')\n {\n if (readline->history_current < history_length())\n {\n readline->history_current++;\n readline->cursor = unicode_string_length(readline_string(readline));\n }\n }\n else if (readline->scan->current() == 'B')\n {\n if (readline->history_current > 0)\n {\n readline->history_current--;\n readline->cursor = unicode_string_length(readline_string(readline));\n }\n }\n else if (readline->scan->current() == 'C')\n {\n if (readline->cursor < unicode_string_length(readline_string(readline)))\n {\n readline->cursor++;\n }\n }\n else if (readline->scan->current() == 'D')\n {\n if (readline->cursor > 0)\n {\n readline->cursor--;\n }\n }\n else if (readline->scan->current_is(\"0123456789\"))\n {\n // https://en.wikipedia.org/wiki/ANSI_escape_code#Terminal_input_sequences\n int digits = 0;\n\n while (readline->scan->current_is(\"0123456789\"))\n {\n digits *= 10;\n digits += readline->scan->current() - '0';\n readline->scan->foreward();\n }\n\n if (readline->scan->current() == '~')\n {\n if (digits == 1) // Home\n {\n readline->cursor = 0;\n }\n else if (digits == 3) // Delete\n {\n if (readline->cursor < unicode_string_length(readline_string(readline)))\n {\n unicode_string_remove(readline->string, readline->cursor);\n }\n }\n else if (digits == 4) // End\n {\n readline->cursor = unicode_string_length(readline_string(readline));\n }\n }\n }\n\n readline->scan->foreward();\n }\n else\n {\n readline_recale_history(readline);\n\n readline->decoder->write(readline->scan->current());\n readline->scan->foreward();\n }\n\n readline_repaint(readline);\n }\n\n printf(\"\\n\\e[0m\");\n\n if (handle_has_error(readline->stream))\n {\n return handle_get_error(readline->stream);\n }\n\n *line = readline_cstring(readline);\n\n history_commit(readline->string);\n\n return SUCCESS;\n}\n\nReadLine *readline_create(Stream *stream)\n{\n ReadLine *readline = __create(ReadLine);\n\n readline->stream = stream;\n\n readline->string = unicode_string_create(READLINE_ALLOCATED);\n\n readline->decoder = new UTF8Decoder([readline](auto codepoint) {\n unicode_string_insert(readline->string, codepoint, readline->cursor);\n readline->cursor++;\n });\n\n readline->scan = new StreamScanner(readline->stream);\n\n return readline;\n}\n\nvoid readline_destroy(ReadLine *readline)\n{\n delete readline->scan;\n delete readline->decoder;\n unicode_string_destroy(readline->string);\n\n free(readline);\n}\n" }, { "alpha_fraction": 0.6883364915847778, "alphanum_fraction": 0.6921606063842773, "avg_line_length": 18.407407760620117, "blob_id": "2209be50a6129a657256ff361e9c78228ac39c81", "content_id": "b4bac0c623f10815a96b2c013fb92d4ce2975d05", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 523, "license_type": "permissive", "max_line_length": 66, "num_lines": 27, "path": "/libraries/libwidget/TextField.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n#include <libwidget/model/TextModel.h>\n\nclass TextField : public Widget\n{\nprivate:\n RefPtr<TextModel> _model;\n OwnPtr<Observer<TextModel>> _model_observer;\n\n TextCursor _cursor{};\n int _hscroll_offset = 0;\n\npublic:\n TextField(Widget *parent, RefPtr<TextModel> model);\n\n ~TextField() override;\n\n void scroll_to_cursor();\n\n void paint(Painter &painter, const Recti &rectangle) override;\n\n Vec2i size() override;\n\n void event(Event *event) override;\n};" }, { "alpha_fraction": 0.6523929238319397, "alphanum_fraction": 0.6549118161201477, "avg_line_length": 35.09090805053711, "blob_id": "c6033a704ec9843ca35ed6bafb3442805e00aa14", "content_id": "d0468ef8e9c1c2ed01c1790f2887f3c4767f280f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 397, "license_type": "permissive", "max_line_length": 69, "num_lines": 11, "path": "/distros/grub-x86_32/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "$(BOOTDISK): $(RAMDISK) $(KERNEL_BINARY) $(DISTRO_DIRECTORY)/grub.cfg\n\t$(DIRECTORY_GUARD)\n\t@echo [GRUB-MKRESCUE] $@\n\n\t@mkdir -p $(BOOTROOT)/boot/grub\n\t@cp $(DISTRO_DIRECTORY)/grub.cfg $(BOOTROOT)/boot/grub/\n\t@gzip -c $(RAMDISK) > $(BOOTROOT)/boot/ramdisk.tar.gz\n\t@gzip -c $(KERNEL_BINARY) > $(BOOTROOT)/boot/kernel.bin.gz\n\n\t@grub-mkrescue -o $@ $(BOOTROOT) || \\\n\t grub2-mkrescue -o $@ $(BOOTROOT)\n" }, { "alpha_fraction": 0.5774278044700623, "alphanum_fraction": 0.5826771855354309, "avg_line_length": 15.565217018127441, "blob_id": "1e036ca08b17757efc1115b1f9cb69694c29d327", "content_id": "943a2a21ba3616ce21c27b598d99a5a0e5950f3f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 381, "license_type": "permissive", "max_line_length": 57, "num_lines": 23, "path": "/tests/Makefile", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": ".DEFAULT_GOAL := all\n\nTESTS=$(wildcard test_*.cpp)\n\nCXXFLAGS:= \\\n\t-MD \\\n\t-std=c++20 \\\n\t-I../libraries \\\n\t-Idummies \\\n\t-fsanitize=address \\\n\t-fsanitize=undefined\n\n%.out: %.cpp Makefile\n\t$(CXX) $(CXXFLAGS) -o $@ $< common.cpp\n\t./$@\n\t@echo $@ SUCCESS\n\n-include $(wildcard *.d)\n\nall: $(patsubst %.cpp, %.out, $(TESTS))\n\nclean:\n\trm -f $(patsubst %.cpp, %.out, $(TESTS)) $(wildcard *.d)\n" }, { "alpha_fraction": 0.7785388231277466, "alphanum_fraction": 0.7785388231277466, "avg_line_length": 22.052631378173828, "blob_id": "a27d09c5f5991ffafb98e934b1913a24d485ed01", "content_id": "f130dbed24078cfdcf387df13626414dd0c2d36a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 438, "license_type": "permissive", "max_line_length": 80, "num_lines": 19, "path": "/libraries/libsystem/io/Socket.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Filesystem.h>\n\nstruct Connection;\n\nstruct Socket;\n\nSocket *socket_open(const char *path, OpenFlag flags);\n\nstruct Connection *socket_connect(const char *path);\n\nstruct Connection *socket_accept(Socket *socket);\n\nvoid socket_close(Socket *socket);\n\nvoid socket_did_connection_open(Socket *socket, struct Connection *connection);\n\nvoid socket_did_connection_close(Socket *socket, struct Connection *connection);\n" }, { "alpha_fraction": 0.6571879982948303, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 17.617647171020508, "blob_id": "bdd720157acbffd22f69e20eeb3ffbc910712e17", "content_id": "8a84dd9e147c96db2c666dc2e115df0979376f52", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 633, "license_type": "permissive", "max_line_length": 57, "num_lines": 34, "path": "/libraries/libwidget/Slider.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Painter.h>\n#include <libutils/Callback.h>\n#include <libwidget/Widget.h>\n#include <libwidget/Window.h>\n\nclass Slider : public Widget\n{\nprivate:\n static constexpr auto THUMP_SIZE = 12;\n static constexpr auto TRACK_HEIGHT = 4;\n\n double _value = 0.5;\n\n Recti track_bound();\n\n Recti value_bound();\n\n Recti thumb_bound();\n\n void slide_to(Vec2i position);\n\npublic:\n double value() { return _value; }\n\n void value(double value) { _value = value; }\n\n Slider(Widget *parent);\n\n void event(Event *event) override;\n\n void paint(Painter &painter, const Recti &) override;\n};\n" }, { "alpha_fraction": 0.703125, "alphanum_fraction": 0.703125, "avg_line_length": 11.800000190734863, "blob_id": "2590682b73ef6a2a4f3eb7c7e35351a429bca921", "content_id": "847cec07c92e9f7a4790afeb8093f8fce05d12ed", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 64, "license_type": "permissive", "max_line_length": 24, "num_lines": 5, "path": "/libraries/libsystem/system/System.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/System.h>\n\nTick system_get_ticks();\n" }, { "alpha_fraction": 0.4554294943809509, "alphanum_fraction": 0.4655591547489166, "avg_line_length": 14.769968032836914, "blob_id": "047cd20a33933ef6f78d06a66897bd68c4fc0827", "content_id": "12b86a6f8b967761c56333d1a7a7b71de2520bd0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4936, "license_type": "permissive", "max_line_length": 100, "num_lines": 313, "path": "/archs/x86/kernel/CPUID.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/Stream.h>\n#include <string.h>\n\n#include \"archs/x86/kernel/CPUID.h\"\n\nstatic inline int cpuid_string(int code, int where[4])\n{\n asm volatile(\"cpuid\"\n : \"=a\"(*where), \"=b\"(*(where + 0)),\n \"=d\"(*(where + 1)), \"=c\"(*(where + 2))\n : \"a\"(code));\n return (int)where[0];\n}\n\nCPUID cpuid()\n{\n CPUID cid;\n memset(&cid.vendorid, 0, 16);\n cpuid_string(0, (int *)&cid.vendorid[0]);\n cid.RAW_ECX = cpuid_get_feature_ECX();\n cid.RAW_EDX = cpuid_get_feature_EDX();\n\n return cid;\n}\n\nvoid cpuid_dump()\n{\n CPUID cid = cpuid();\n\n stream_format(out_stream, \"\\n\\n\\tCPUID dump:\\n\\t - Vendorid: %s\\n\\t - Features:\", cid.vendorid);\n\n if (cid.PCLMUL)\n {\n stream_format(out_stream, \" PCLMUL\");\n }\n\n if (cid.DTES64)\n {\n stream_format(out_stream, \" DTES64\");\n }\n\n if (cid.MONITOR)\n {\n stream_format(out_stream, \" MONITOR\");\n }\n\n if (cid.DS_CPL)\n {\n stream_format(out_stream, \" DS_CPL\");\n }\n\n if (cid.VMX)\n {\n stream_format(out_stream, \" VMX\");\n }\n\n if (cid.SMX)\n {\n stream_format(out_stream, \" SMX\");\n }\n\n if (cid.EST)\n {\n stream_format(out_stream, \" EST\");\n }\n\n if (cid.TM2)\n {\n stream_format(out_stream, \" TM2\");\n }\n\n if (cid.SSSE3)\n {\n stream_format(out_stream, \" SSSE3\");\n }\n\n if (cid.CID)\n {\n stream_format(out_stream, \" CID\");\n }\n\n if (cid.FMA)\n {\n stream_format(out_stream, \" FMA\");\n }\n\n if (cid.CX16)\n {\n stream_format(out_stream, \" CX16\");\n }\n\n if (cid.ETPRD)\n {\n stream_format(out_stream, \" ETPRD\");\n }\n\n if (cid.PDCM)\n {\n stream_format(out_stream, \" PDCM\");\n }\n\n if (cid.PCIDE)\n {\n stream_format(out_stream, \" PCIDE\");\n }\n\n if (cid.DCA)\n {\n stream_format(out_stream, \" DCA\");\n }\n\n if (cid.SSE4_1)\n {\n stream_format(out_stream, \" SSE4_1\");\n }\n\n if (cid.SSE4_2)\n {\n stream_format(out_stream, \" SSE4_2\");\n }\n\n if (cid.x2APIC)\n {\n stream_format(out_stream, \" x2APIC\");\n }\n\n if (cid.MOVBE)\n {\n stream_format(out_stream, \" MOVBE\");\n }\n\n if (cid.POPCNT)\n {\n stream_format(out_stream, \" POPCNT\");\n }\n\n if (cid.AES)\n {\n stream_format(out_stream, \" AES\");\n }\n\n if (cid.XSAVE)\n {\n stream_format(out_stream, \" XSAVE\");\n }\n\n if (cid.OSXSAVE)\n {\n stream_format(out_stream, \" OSXSAVE\");\n }\n\n if (cid.AVX)\n {\n stream_format(out_stream, \" AVX\");\n }\n\n if (cid.FPU)\n {\n stream_format(out_stream, \" FPU\");\n }\n\n if (cid.VME)\n {\n stream_format(out_stream, \" VME\");\n }\n\n if (cid.DE)\n {\n stream_format(out_stream, \" DE\");\n }\n\n if (cid.PSE)\n {\n stream_format(out_stream, \" PSE\");\n }\n\n if (cid.TSC)\n {\n stream_format(out_stream, \" TSC\");\n }\n\n if (cid.MSR)\n {\n stream_format(out_stream, \" MSR\");\n }\n\n if (cid.PAE)\n {\n stream_format(out_stream, \" PAE\");\n }\n\n if (cid.MCE)\n {\n stream_format(out_stream, \" MCE\");\n }\n\n if (cid.CX8)\n {\n stream_format(out_stream, \" CX8\");\n }\n\n if (cid.APIC)\n {\n stream_format(out_stream, \" APIC\");\n }\n\n if (cid.SEP)\n {\n stream_format(out_stream, \" SEP\");\n }\n\n if (cid.MTRR)\n {\n stream_format(out_stream, \" MTRR\");\n }\n\n if (cid.PGE)\n {\n stream_format(out_stream, \" PGE\");\n }\n\n if (cid.MCA)\n {\n stream_format(out_stream, \" MCA\");\n }\n\n if (cid.CMOV)\n {\n stream_format(out_stream, \" CMOV\");\n }\n\n if (cid.PAT)\n {\n stream_format(out_stream, \" PAT\");\n }\n\n if (cid.PSE36)\n {\n stream_format(out_stream, \" PSE36\");\n }\n\n if (cid.PSN)\n {\n stream_format(out_stream, \" PSN\");\n }\n\n if (cid.CLF)\n {\n stream_format(out_stream, \" CLF\");\n }\n\n if (cid.DTES)\n {\n stream_format(out_stream, \" DTES\");\n }\n\n if (cid.ACPI)\n {\n stream_format(out_stream, \" ACPI\");\n }\n\n if (cid.MMX)\n {\n stream_format(out_stream, \" MMX\");\n }\n\n if (cid.FXSR)\n {\n stream_format(out_stream, \" FXSR\");\n }\n\n if (cid.SSE)\n {\n stream_format(out_stream, \" SSE\");\n }\n\n if (cid.SSE2)\n {\n stream_format(out_stream, \" SSE2\");\n }\n\n if (cid.SSE3)\n {\n stream_format(out_stream, \" SSE3\");\n }\n\n if (cid.SS)\n {\n stream_format(out_stream, \" SS\");\n }\n\n if (cid.HTT)\n {\n stream_format(out_stream, \" HTT\");\n }\n\n if (cid.TM1)\n {\n stream_format(out_stream, \" TM1\");\n }\n\n if (cid.IA64)\n {\n stream_format(out_stream, \" IA64\");\n }\n\n if (cid.PBE)\n {\n stream_format(out_stream, \" PBE\");\n }\n\n stream_format(out_stream, \"\\n\");\n}\n" }, { "alpha_fraction": 0.8046875, "alphanum_fraction": 0.8046875, "avg_line_length": 30.75, "blob_id": "12310c1b3b7cc393469f203529afade3c9d369a3", "content_id": "007a566993b6c253926ef7dd1782ef1686fc703b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 128, "license_type": "permissive", "max_line_length": 62, "num_lines": 4, "path": "/apps/archive-manager/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += ARCHIVE_MANAGER\n\nARCHIVE_MANAGER_NAME = archive-manager\nARCHIVE_MANAGER_LIBS = file filepicker widget settings graphic\n\n" }, { "alpha_fraction": 0.5216284990310669, "alphanum_fraction": 0.5363867878913879, "avg_line_length": 23.271604537963867, "blob_id": "57f18dfbd57c0e9b7765461a4b41056df795d75d", "content_id": "cfe5f62475c97b5336969ec35f63eea5a5c5e39b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1965, "license_type": "permissive", "max_line_length": 98, "num_lines": 81, "path": "/libraries/libsystem/io/BitReader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/Common.h>\n#include <libsystem/io/Reader.h>\n#include <libutils/Vector.h>\n\nclass BitReader\n{\npublic:\n inline BitReader(const Vector<uint8_t> &data) : _data(data.raw_storage()), _size(data.count())\n {\n }\n\n inline BitReader(uint8_t *data, size_t size) : _data(data), _size(size)\n {\n }\n\n inline BitReader(Reader &reader) : _data(new uint8_t[reader.length()]), _size(reader.length())\n {\n reader.read((uint8_t *)_data, reader.length());\n }\n\n inline void skip_bits(size_t num_bits)\n {\n _index += num_bits;\n }\n\n inline uint16_t grab_uint16()\n {\n uint16_t result = _data[_index / 8] + (_data[(_index / 8) + 1] << 8);\n _index += 16;\n return result;\n }\n\n inline uint8_t peek_bit()\n {\n return (_data[_index / 8] & (1 << (_index % 8))) ? 1 : 0;\n }\n\n inline unsigned int grab_bits(unsigned int num_bits)\n {\n unsigned int ret_val = 0;\n for (unsigned int i = 0; i != num_bits; i++)\n {\n ret_val |= (unsigned int)peek_bit() << i;\n _index++;\n }\n return ret_val;\n }\n\n inline unsigned int peek_bits(size_t num_bits)\n {\n unsigned int cached_index = _index;\n unsigned int result = grab_bits(num_bits);\n _index = cached_index;\n return result;\n }\n\n inline unsigned int grab_bits_reverse(size_t num_bits)\n {\n unsigned int ret_val = 0;\n for (unsigned int i = 0; i != num_bits; i++)\n {\n ret_val |= (unsigned int)peek_bit() << ((num_bits - 1) - i);\n _index++;\n }\n return ret_val;\n }\n\n inline unsigned int peek_bits_reverse(size_t num_bits)\n {\n unsigned int cached_index = _index;\n unsigned int result = grab_bits_reverse(num_bits);\n _index = cached_index;\n return result;\n }\n\nprivate:\n const uint8_t *_data;\n const size_t _size;\n size_t _index = 0;\n};" }, { "alpha_fraction": 0.6791045069694519, "alphanum_fraction": 0.6840795874595642, "avg_line_length": 21.38888931274414, "blob_id": "652b6681313d8e08be971dacf84c3375ddee7359", "content_id": "6560e75864bcc11d541d76515321ca7f4c64552a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 402, "license_type": "permissive", "max_line_length": 60, "num_lines": 18, "path": "/libraries/libsystem/io/ScopedReader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/io/Reader.h>\n#include <libsystem/math/MinMax.h>\n\nclass ScopedReader final : public Reader\n{\npublic:\n ScopedReader(Reader &reader, size_t size);\n\n virtual size_t length() override;\n virtual size_t position() override;\n virtual size_t read(void *buffer, size_t size) override;\n\nprivate:\n size_t _start_pos = 0;\n size_t _size = 0;\n Reader &_reader;\n};" }, { "alpha_fraction": 0.568708598613739, "alphanum_fraction": 0.570364236831665, "avg_line_length": 22.705883026123047, "blob_id": "5f3daeda25fc66179f1822f6c5ab777b0c813819", "content_id": "353f4061fb1d679be4d81238cb1423b87e99146d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1208, "license_type": "permissive", "max_line_length": 75, "num_lines": 51, "path": "/libraries/libwidget/HScroll.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Container.h>\n#include <libwidget/ScrollBar.h>\n#include <libwidget/Widget.h>\n\nclass HScroll : public Widget\n{\nprivate:\n Container *_host = nullptr;\n ScrollBar *_scrollbar = nullptr;\n\npublic:\n Container *host() { return _host; }\n\n HScroll(Widget *parent) : Widget(parent)\n {\n _host = new Container(this);\n\n _scrollbar = new ScrollBar(this);\n _scrollbar->flags(Widget::NOT_AFFECTED_BY_SCROLL);\n\n _scrollbar->on(Event::VALUE_CHANGE, [this](auto) {\n scroll({_scrollbar->value(), scroll().y()});\n should_repaint();\n });\n }\n\n void do_layout() override\n {\n int content_width = _host->size().x();\n\n _host->container(content().take_left(content_width));\n _scrollbar->container(content().take_bottom(ScrollBar::SIZE));\n _scrollbar->update(content_width, content().width(), scroll().y());\n }\n\n void event(Event *event) override\n {\n if (event->type == Event::MOUSE_SCROLL)\n {\n event->accepted = true;\n _scrollbar->dispatch_event(event);\n }\n }\n\n Vec2i size() override\n {\n return {0, _host->size().y()};\n }\n};" }, { "alpha_fraction": 0.7654321193695068, "alphanum_fraction": 0.7654321193695068, "avg_line_length": 15.199999809265137, "blob_id": "e7503360cfa1bd26e0e9762ba129e8bf28d58b14", "content_id": "724f6e4a465ce5d25e56e20f70c63eebc9cb9e1f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 81, "license_type": "permissive", "max_line_length": 35, "num_lines": 5, "path": "/archs/x86/kernel/PIT.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nvoid pit_initialize(int frequency);\n" }, { "alpha_fraction": 0.6519315242767334, "alphanum_fraction": 0.658303439617157, "avg_line_length": 28.89285659790039, "blob_id": "64857687ee7d0e6b28fd290bbf0181a2b5a4fbe8", "content_id": "c73bfc2c6b4ecb6372a4be376c0df7a7ad2146eb", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2511, "license_type": "permissive", "max_line_length": 120, "num_lines": 84, "path": "/apps/logout/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Syscalls.h>\n\n#include <libwidget/Application.h>\n#include <libwidget/Button.h>\n#include <libwidget/Container.h>\n#include <libwidget/IconPanel.h>\n#include <libwidget/Label.h>\n#include <libwidget/Panel.h>\n#include <libwidget/Screen.h>\n#include <libwidget/Spacer.h>\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n Window *window = new Window(WINDOW_BORDERLESS | WINDOW_ALWAYS_FOCUSED | WINDOW_ACRYLIC | WINDOW_NO_ROUNDED_CORNERS);\n\n window->type(WINDOW_TYPE_POPOVER);\n window->bound(Screen::bound());\n window->opacity(0);\n window->root()->layout(STACK());\n\n auto background = new Panel(window->root());\n\n background->layout(STACK());\n background->color(THEME_MIDDLEGROUND, Colors::BLACK.with_alpha(0.5));\n background->flags(Widget::FILL);\n\n auto dialog = new Container(background);\n\n dialog->min_width(256);\n dialog->min_height(256);\n dialog->layout(VFLOW(8));\n\n auto icon_and_title_container = new Panel(dialog);\n icon_and_title_container->layout(HFLOW(4));\n icon_and_title_container->border_radius(6);\n icon_and_title_container->insets(Insetsi{8});\n\n auto title_icon = new IconPanel(icon_and_title_container, Icon::get(\"power-standby\"));\n title_icon->icon_size(ICON_36PX);\n\n auto warning_container = new Container(icon_and_title_container);\n warning_container->flags(Widget::FILL);\n warning_container->layout(VGRID(2));\n\n new Label(warning_container, \"Shutdown or restart your computer.\", Anchor::BOTTOM_LEFT);\n new Label(warning_container, \"Any unsaved work will be lost!\", Anchor::TOP_LEFT);\n\n new Spacer(dialog);\n\n auto shutdown_button = new Button(dialog, Button::TEXT, Icon::get(\"power-standby\"), \"Shutdown\");\n\n shutdown_button->on(EventType::ACTION, [&](auto) {\n hj_system_shutdown();\n });\n\n auto reboot_button = new Button(dialog, Button::TEXT, Icon::get(\"restart\"), \"Reboot\");\n\n reboot_button->on(EventType::ACTION, [&](auto) {\n hj_system_reboot();\n });\n\n new Button(dialog, Button::TEXT, Icon::get(\"logout\"), \"Logoff\");\n\n new Spacer(dialog);\n\n auto cancel_button = new Button(dialog, Button::FILLED, \"Cancel\");\n\n cancel_button->on(EventType::ACTION, [&](auto) {\n window->hide();\n });\n\n window->on(Event::KEYBOARD_KEY_PRESS, [&](Event *event) {\n if (event->keyboard.key == KEYBOARD_KEY_ESC)\n {\n Application::exit(PROCESS_SUCCESS);\n }\n });\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.7063210010528564, "alphanum_fraction": 0.7606534361839294, "avg_line_length": 34.64556884765625, "blob_id": "4ab7ea30311266cde4825f6816f2172569de6ad1", "content_id": "50bbc0e8adf97d2b9d731d8c3c3d886f9e12bc03", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2816, "license_type": "permissive", "max_line_length": 76, "num_lines": 79, "path": "/libraries/libwidget/Theme.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Color.h>\n\n#define THEME_DEFAULT_BORDER Color::from_byte(255, 255, 255, 31)\n#define THEME_DEFAULT_BACKGROUND Color::from_hex(0x333333)\n#define THEME_DEFAULT_MIDDLEGROUND Color::from_hex(0x444444)\n#define THEME_DEFAULT_FOREGROUND Color::from_hex(0xFFFFFF)\n#define THEME_DEFAULT_FOREGROUND_INACTIVE Color::from_hex(0x888888)\n#define THEME_DEFAULT_FOREGROUND_DISABLED Color::from_hex(0x888888)\n#define THEME_DEFAULT_SELECTION Color::from_byte(0, 102, 255, 127)\n#define THEME_DEFAULT_SELECTION_INACTIVE Color::from_byte(136, 136, 136, 63)\n#define THEME_DEFAULT_ACCENT Color::from_hex(0x0066FF)\n#define THEME_DEFAULT_ACCENT_INACTIVE Color::from_hex(0x444444)\n#define THEME_DEFAULT_ANSI_CURSOR Color::from_hex(0xFFB454)\n#define THEME_DEFAULT_ANSI_BACKGROUND Color::from_hex(0x0A0E14)\n#define THEME_DEFAULT_ANSI_FOREGROUND Color::from_hex(0xB3B1AD)\n#define THEME_DEFAULT_ANSI_BLACK Color::from_hex(0x01060E)\n#define THEME_DEFAULT_ANSI_RED Color::from_hex(0xEA6C73)\n#define THEME_DEFAULT_ANSI_GREEN Color::from_hex(0x91B362)\n#define THEME_DEFAULT_ANSI_YELLOW Color::from_hex(0xF9AF4F)\n#define THEME_DEFAULT_ANSI_BLUE Color::from_hex(0x53BDFA)\n#define THEME_DEFAULT_ANSI_MAGENTA Color::from_hex(0xFAE994)\n#define THEME_DEFAULT_ANSI_CYAN Color::from_hex(0x90E1C6)\n#define THEME_DEFAULT_ANSI_WHITE Color::from_hex(0xC7C7C7)\n#define THEME_DEFAULT_ANSI_BRIGHT_BLACK Color::from_hex(0x686868)\n#define THEME_DEFAULT_ANSI_BRIGHT_RED Color::from_hex(0xF07178)\n#define THEME_DEFAULT_ANSI_BRIGHT_GREEN Color::from_hex(0xC2D94C)\n#define THEME_DEFAULT_ANSI_BRIGHT_YELLOW Color::from_hex(0xFFB454)\n#define THEME_DEFAULT_ANSI_BRIGHT_BLUE Color::from_hex(0x59C2FF)\n#define THEME_DEFAULT_ANSI_BRIGHT_MAGENTA Color::from_hex(0xFFEE99)\n#define THEME_DEFAULT_ANSI_BRIGHT_CYAN Color::from_hex(0x95E6CB)\n#define THEME_DEFAULT_ANSI_BRIGHT_WHITE Color::from_hex(0xFFFFFF)\n\nenum ThemeColorRole\n{\n THEME_BORDER,\n THEME_BACKGROUND,\n THEME_MIDDLEGROUND,\n THEME_FOREGROUND,\n THEME_FOREGROUND_INACTIVE,\n THEME_FOREGROUND_DISABLED,\n THEME_SELECTION,\n THEME_SELECTION_INACTIVE,\n THEME_ACCENT,\n THEME_ACCENT_INACTIVE,\n\n THEME_ANSI_CURSOR,\n THEME_ANSI_BACKGROUND,\n THEME_ANSI_FOREGROUND,\n\n THEME_ANSI_BLACK,\n THEME_ANSI_RED,\n THEME_ANSI_GREEN,\n THEME_ANSI_YELLOW,\n THEME_ANSI_BLUE,\n THEME_ANSI_MAGENTA,\n THEME_ANSI_CYAN,\n THEME_ANSI_WHITE,\n\n THEME_ANSI_BRIGHT_BLACK,\n THEME_ANSI_BRIGHT_RED,\n THEME_ANSI_BRIGHT_GREEN,\n THEME_ANSI_BRIGHT_YELLOW,\n THEME_ANSI_BRIGHT_BLUE,\n THEME_ANSI_BRIGHT_MAGENTA,\n THEME_ANSI_BRIGHT_CYAN,\n THEME_ANSI_BRIGHT_WHITE,\n\n __THEME_COLOR_COUNT\n};\n\nbool theme_is_dark();\n\nvoid theme_load(const char *path);\n\nColor theme_get_color(ThemeColorRole role);\n\nvoid theme_set_color(ThemeColorRole role, Color color);\n" }, { "alpha_fraction": 0.6734693646430969, "alphanum_fraction": 0.681898832321167, "avg_line_length": 29.066667556762695, "blob_id": "38d74c8ff99f6367dafc9293192d17643a659331", "content_id": "38d6cbf83767630abe8d8ee9621e5b7bfc51f472", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2254, "license_type": "permissive", "max_line_length": 109, "num_lines": 75, "path": "/libraries/libsystem/compression/Deflate.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/compression/Common.h>\n#include <libsystem/compression/Deflate.h>\n#include <libsystem/compression/Huffman.h>\n#include <libsystem/io/Reader.h>\n#include <libsystem/io/Writer.h>\n\nDeflate::Deflate(unsigned int compression_level) : _compression_level(compression_level)\n{\n /*\n\t * The higher the compression level, the more we should bother trying to\n\t * compress very small inputs.\n\t */\n _min_size_to_compress = 56 - (_compression_level * 4);\n\n switch (compression_level)\n {\n // TODO: set the compression method according to the level\n default:\n _compression_method = compress_none;\n }\n}\n\nvoid Deflate::write_block_header(BitWriter &out_writer, BlockType block_type, bool final)\n{\n out_writer.put_bits(final ? 1 : 0, 1);\n out_writer.put_bits(block_type, 2);\n}\n\nvoid Deflate::write_uncompressed_block(Reader &in_data, uint16_t data_len, BitWriter &out_writer, bool final)\n{\n Vector<uint8_t> data(data_len);\n assert(in_data.read(data.raw_storage(), data_len) == data_len);\n\n // Write the data\n write_block_header(out_writer, BlockType::BT_UNCOMPRESSED, final);\n out_writer.align();\n out_writer.put_uint16(data_len);\n out_writer.put_uint16(~data_len);\n out_writer.put_data(data.raw_storage(), data_len);\n}\n\nvoid Deflate::write_uncompressed_blocks(Reader &in_data, BitWriter &out_writer, bool final)\n{\n auto data_length = in_data.length();\n\n do\n {\n uint16_t len = MIN(data_length, UINT16_MAX);\n\n write_uncompressed_block(in_data, len, out_writer, final && (len == data_length));\n data_length -= len;\n } while (data_length != 0);\n}\n\nResult Deflate::compress_none(Reader &uncompressed, Writer &compressed)\n{\n BitWriter bit_writer(compressed);\n write_uncompressed_blocks(uncompressed, bit_writer, true);\n\n return Result::SUCCESS;\n}\n\nResult Deflate::perform(Reader &uncompressed, Writer &compressed)\n{\n // If the data amount is too small it's not worth compressing it.\n // Depends on the compression level\n if (uncompressed.length() < _min_size_to_compress)\n [[unlikely]]\n {\n return compress_none(uncompressed, compressed);\n }\n\n return _compression_method(uncompressed, compressed);\n}" }, { "alpha_fraction": 0.6955645084381104, "alphanum_fraction": 0.6955645084381104, "avg_line_length": 16.13793182373047, "blob_id": "065975b55c4191f8dde81677a9eab68e13cf225e", "content_id": "966f856a769e6ad522187cf8db439fbd73489317", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 496, "license_type": "permissive", "max_line_length": 54, "num_lines": 29, "path": "/apps/task-manager/widgets/CPUGraph.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/eventloop/Timer.h>\n\n#include <libwidget/Graph.h>\n#include <libwidget/Label.h>\n\n#include \"task-manager/model/TaskModel.h\"\n\nnamespace task_manager\n{\n\nclass CPUGraph : public Graph\n{\nprivate:\n RefPtr<TaskModel> _model;\n\n Label *_label_average;\n Label *_label_greedy;\n Label *_label_uptime;\n\n OwnPtr<Timer> _graph_timer{};\n OwnPtr<Timer> _text_timer{};\n\npublic:\n CPUGraph(Widget *parent, RefPtr<TaskModel> model);\n};\n\n} // namespace task_manager" }, { "alpha_fraction": 0.5338189601898193, "alphanum_fraction": 0.569198727607727, "avg_line_length": 19.89130401611328, "blob_id": "a6d77930abee811e02acaaec1bc624c74da90a77", "content_id": "011895f6c8e6a7043e1e47838919e859f042e7bd", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 961, "license_type": "permissive", "max_line_length": 78, "num_lines": 46, "path": "/libraries/libc/time.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n#include <stddef.h>\n\n__BEGIN_HEADER\n\n#define CLOCKS_PER_SEC 1000\n\ntypedef long int time_t;\n\ntypedef long int clock_t;\n\nstruct tm\n{\n int tm_sec; /* Seconds. [0-60] */\n int tm_min; /* Minutes. [0-59] */\n int tm_hour; /* Hours. [0-23] */\n int tm_mday; /* Day. [1-31] */\n int tm_mon; /* Month. [0-11] */\n int tm_year; /* Year - 1900. */\n int tm_wday; /* Day of week. [0-6] */\n int tm_yday; /* Days in year.[0-365] */\n int tm_isdst; /* DST. [-1/0/1] */\n};\n\ntime_t time(time_t *timer);\n\nclock_t clock(void);\n\nstruct tm *gmtime(const time_t *timer);\n\nstruct tm *localtime(const time_t *timer);\n\nsize_t strftime(char *s, size_t n, const char *format, const struct tm *tptr);\n\ntime_t mktime(struct tm *ptm);\n\ndouble difftime(time_t timer2, time_t timer1);\n\nchar *asctime(const struct tm *pTime);\n\nchar *ctime(const time_t *pTime);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.6835442781448364, "alphanum_fraction": 0.6835442781448364, "avg_line_length": 19.481481552124023, "blob_id": "08d00845f2af12d2b58798005793b07793f8615e", "content_id": "04aea1e64aa324b2ba8a0036ad7558660d4d3df9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 553, "license_type": "permissive", "max_line_length": 64, "num_lines": 27, "path": "/apps/paint/PaintCanvas.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\n#include \"paint/PaintDocument.h\"\n#include \"paint/PaintTool.h\"\n\nclass PaintCanvas : public Widget\n{\nprivate:\n RefPtr<PaintDocument> _document;\n OwnPtr<PaintTool> _tool;\n\npublic:\n void tool(OwnPtr<PaintTool> tool) { _tool = tool; }\n\n Recti paint_area()\n {\n return _document->bound().centered_within(bound());\n }\n\n PaintCanvas(Widget *parent, RefPtr<PaintDocument> document);\n\n void paint(Painter &painter, const Recti &dirty) override;\n\n void event(Event *event) override;\n};\n" }, { "alpha_fraction": 0.5696821808815002, "alphanum_fraction": 0.5745721459388733, "avg_line_length": 18.5, "blob_id": "66400940639ac5ee970050002abd5cfb33fbe4b6", "content_id": "c8307c9800a791404c75f744ebc46af7ad74c349", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 818, "license_type": "permissive", "max_line_length": 80, "num_lines": 42, "path": "/libraries/libsystem/io_new/Seek.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Handle.h>\n#include <libutils/ResultOr.h>\n\nnamespace System\n{\n\nclass Seek\n{\npublic:\n virtual ResultOr<size_t> seek(size_t pos, Whence whence) = 0;\n virtual ResultOr<size_t> tell() = 0;\n\n virtual ResultOr<size_t> length()\n {\n auto original_position = seek(0, WHENCE_HERE);\n\n if (!original_position)\n {\n return original_position.result();\n }\n\n auto end_position = seek(0, WHENCE_END);\n\n if (!end_position)\n {\n return end_position.result();\n }\n\n auto back_to_original_position = seek(*original_position, WHENCE_START);\n\n if (!back_to_original_position)\n {\n return back_to_original_position.result();\n }\n\n return *end_position;\n }\n};\n\n} // namespace System" }, { "alpha_fraction": 0.6741706132888794, "alphanum_fraction": 0.6741706132888794, "avg_line_length": 20.100000381469727, "blob_id": "3393dd1e875233e80e18675a615566936d64fb7d", "content_id": "ac098e597c5f462cbe67e537370ec1ce1dc49e57", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 844, "license_type": "permissive", "max_line_length": 69, "num_lines": 40, "path": "/libraries/libsystem/io_new/File.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Path.h>\n\n#include <libsystem/Handle.h>\n#include <libsystem/io_new/Reader.h>\n#include <libsystem/io_new/Writer.h>\n\nnamespace System\n{\n\nclass File final :\n public Reader,\n public Writer,\n public Seek\n{\nprivate:\n System::Handle _handle;\n Optional<Path> _path;\n\npublic:\n const Optional<Path> &path() { return _path; }\n\n File(const char *path, OpenFlag flags);\n File(String path, OpenFlag flags);\n File(Path &path, OpenFlag flags);\n File(System::Handle &&handle);\n\n ResultOr<size_t> read(void *buffer, size_t size) override;\n ResultOr<size_t> write(const void *buffer, size_t size) override;\n\n ResultOr<size_t> seek(size_t pos, Whence whence) override;\n ResultOr<size_t> tell() override;\n\n ResultOr<size_t> length() override;\n\n bool exist();\n};\n\n} // namespace System\n" }, { "alpha_fraction": 0.5423076748847961, "alphanum_fraction": 0.5484615564346313, "avg_line_length": 19.619047164916992, "blob_id": "3f6db1360eb27397f84ccb18895f825d19531c07", "content_id": "c27346b8c5afe6e5d16d1af1c8e6a9a4b684fdd0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1300, "license_type": "permissive", "max_line_length": 102, "num_lines": 63, "path": "/apps/utilities/cat.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/Result.h>\n#include <libsystem/io/Stream.h>\n#include <libutils/Array.h>\n\nResult cat(const char *path)\n{\n __cleanup(stream_cleanup) Stream *stream = stream_open(path, OPEN_READ);\n\n if (handle_has_error(stream))\n {\n return handle_get_error(stream);\n }\n\n FileState stat = {};\n stream_stat(stream, &stat);\n\n size_t read;\n Array<char, 1024> buffer;\n\n while ((read = stream_read(stream, buffer.raw_storage(), buffer.count())) != 0)\n {\n if (handle_has_error(stream))\n {\n return handle_get_error(stream);\n }\n\n stream_write(out_stream, buffer.raw_storage(), read);\n\n if (handle_has_error(out_stream))\n {\n return ERR_WRITE_STDOUT;\n }\n }\n\n stream_flush(out_stream);\n\n return SUCCESS;\n}\n\nint main(int argc, char **argv)\n{\n if (argc == 1)\n {\n /* TODO: stdin option */\n return PROCESS_SUCCESS;\n }\n\n Result result;\n int exit_code = PROCESS_SUCCESS;\n\n for (int i = 1; i < argc; i++)\n {\n result = cat(argv[i]);\n\n if (result != SUCCESS)\n {\n stream_format(err_stream, \"%s: %s: %s\", argv[0], argv[i], get_result_description(result));\n exit_code = PROCESS_FAILURE;\n }\n }\n\n return exit_code;\n}\n" }, { "alpha_fraction": 0.7134503126144409, "alphanum_fraction": 0.7134503126144409, "avg_line_length": 14.545454978942871, "blob_id": "2153bf7906c73757c838ba30f77542304619ac24", "content_id": "4b83bb9ceff48dec7e25b7441ca86e47aa67f210", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 513, "license_type": "permissive", "max_line_length": 57, "num_lines": 33, "path": "/archs/Architectures.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <skift/Time.h>\n\nstruct Task;\n\nvoid arch_disable_interrupts();\n\nvoid arch_enable_interrupts();\n\nvoid arch_halt();\n\nvoid arch_yield();\n\nvoid arch_save_context(Task *task);\n\nvoid arch_load_context(Task *task);\n\nvoid arch_task_go(Task *task);\n\nsize_t arch_debug_write(const void *buffer, size_t size);\n\nTimeStamp arch_get_time();\n\n__no_return void arch_reboot();\n\n__no_return void arch_shutdown();\n\nvoid arch_panic_dump();\n\nvoid arch_dump_stack_frame(void *stackframe);\n\nvoid arch_backtrace();\n" }, { "alpha_fraction": 0.6052150130271912, "alphanum_fraction": 0.6061299443244934, "avg_line_length": 18.1842098236084, "blob_id": "9dd28fa552b75a24139ce9d0ade8b87e83e0a0ac", "content_id": "0e9b167856623c0830367bd5113e2dbbdef24aa7", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2186, "license_type": "permissive", "max_line_length": 79, "num_lines": 114, "path": "/libraries/libsettings/Settings.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libutils/Vector.h>\n\n#include <libsettings/ServerConnection.h>\n#include <libsettings/Settings.h>\n#include <libsettings/Watcher.h>\n\nnamespace Settings\n{\n\nstatic Vector<Watcher *> _watchers;\nstatic OwnPtr<ServerConnection> _server;\n\nstatic void notify_watchers(const Path &path, const json::Value &value)\n{\n for (size_t i = 0; i < _watchers.count(); i++)\n {\n if (path.match(_watchers[i]->path()))\n {\n _watchers[i]->invoke(value);\n }\n }\n}\n\nstatic ServerConnection &server()\n{\n if (!_server)\n {\n _server = ServerConnection::open();\n\n _server->on_notify = notify_watchers;\n }\n\n return *_server;\n}\n\nstatic bool is_watching_path(const Path &path)\n{\n for (size_t i = 0; i < _watchers.count(); i++)\n {\n if (path.match(_watchers[i]->path()))\n {\n return true;\n }\n }\n\n return false;\n}\n\nvoid register_watcher(Watcher &watcher)\n{\n if (!is_watching_path(watcher.path()))\n {\n Message message;\n\n message.type = Message::CLIENT_WATCH;\n message.path = watcher.path();\n\n server().request(message, Message::SERVER_ACK);\n }\n\n _watchers.push_back(&watcher);\n}\n\nvoid unregister_watcher(Watcher &watcher)\n{\n _watchers.remove_value(&watcher);\n\n if (!is_watching_path(watcher.path()))\n {\n Message message;\n\n message.type = Message::CLIENT_UNWATCH;\n message.path = watcher.path();\n\n server().request(message, Message::SERVER_ACK);\n }\n}\n\nOptional<json::Value> read(const Path path)\n{\n Message message;\n\n message.type = Message::CLIENT_READ;\n message.path = path;\n\n auto result_or_response = server().request(message, Message::SERVER_VALUE);\n\n if (!result_or_response)\n {\n return {};\n }\n\n return result_or_response->payload;\n}\n\nbool write(const Path path, json::Value value)\n{\n Message message;\n\n message.type = Message::CLIENT_WRITE;\n message.path = path;\n message.payload = value;\n\n auto result = server().request(message, Message::SERVER_ACK);\n\n if (result)\n {\n notify_watchers(path, value);\n }\n\n return result.success();\n}\n\n} // namespace Settings" }, { "alpha_fraction": 0.6039845943450928, "alphanum_fraction": 0.6071303486824036, "avg_line_length": 23.452991485595703, "blob_id": "7e1fd4a6690ffab71ba704de9ada2bf296a7314d", "content_id": "499d52a91ae3e49ca1bf3521164dc3a8f6bb1bab", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2861, "license_type": "permissive", "max_line_length": 98, "num_lines": 117, "path": "/libraries/libgraphic/Font.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libgraphic/Font.h>\n#include <libsystem/Logger.h>\n#include <libsystem/Result.h>\n#include <libsystem/io/File.h>\n#include <libutils/HashMap.h>\n#include <libutils/Path.h>\n#include <stdio.h>\n\nstatic HashMap<String, RefPtr<Font>> _fonts;\n\nstatic ResultOr<Vector<Glyph>> font_load_glyph(String name)\n{\n char glyph_path[PATH_LENGTH];\n snprintf(glyph_path, PATH_LENGTH, \"/Files/Fonts/%s.glyph\", name.cstring());\n\n Glyph *glyph_buffer = nullptr;\n size_t glyph_size = 0;\n File glyph_file{glyph_path};\n Result result = glyph_file.read_all((void **)&glyph_buffer, &glyph_size);\n\n if (result != SUCCESS)\n {\n logger_error(\"Failed to load glyph from %s: %s\", glyph_path, handle_error_string(result));\n return result;\n }\n\n return Vector(ADOPT, glyph_buffer, glyph_size / sizeof(Glyph));\n}\n\nstatic ResultOr<RefPtr<Bitmap>> font_load_bitmap(String name)\n{\n return Bitmap::load_from(String::format(\"/Files/Fonts/{}.png\", name));\n}\n\nResultOr<RefPtr<Font>> Font::get(String name)\n{\n if (!_fonts.has_key(name))\n {\n auto glyph_or_error = font_load_glyph(name);\n\n if (!glyph_or_error.success())\n {\n logger_error(\"Failed to load font %s: missing glyphs\", name.cstring());\n return glyph_or_error.result();\n }\n\n auto bitmap_or_error = font_load_bitmap(name);\n\n if (!bitmap_or_error.success())\n {\n logger_error(\"Failed to load font %s: missing bitmap\", name.cstring());\n return bitmap_or_error.result();\n }\n\n _fonts[name] = make<Font>(bitmap_or_error.take_value(), glyph_or_error.take_value());\n }\n\n return _fonts[name];\n}\n\nbool Font::has(Codepoint codepoint) const\n{\n for (int i = 0; _glyphs[i].codepoint != 0; i++)\n {\n if (_glyphs[i].codepoint == codepoint)\n {\n return true;\n }\n }\n\n return false;\n}\n\nconst Glyph &Font::glyph(Codepoint codepoint) const\n{\n for (int i = 0; _glyphs[i].codepoint != 0; i++)\n {\n if (_glyphs[i].codepoint == codepoint)\n {\n return _glyphs[i];\n }\n }\n\n return _default;\n}\n\nRecti Font::mesure(Codepoint codepoint) const\n{\n auto &g = glyph(codepoint);\n\n return {g.advance, metrics().lineheight()};\n}\n\nRecti Font::mesure(const char *string) const\n{\n int width = 0;\n\n codepoint_foreach(reinterpret_cast<const uint8_t *>(string), [&](auto codepoint) {\n auto &g = glyph(codepoint);\n width += g.advance;\n });\n\n return Recti(width, metrics().lineheight());\n}\n\nRecti Font::mesure_with_fulllineheight(const char *string)\n{\n int width = 0;\n\n codepoint_foreach(reinterpret_cast<const uint8_t *>(string), [&](auto codepoint) {\n auto &g = glyph(codepoint);\n width += g.advance;\n });\n\n return Recti(width, metrics().fulllineheight());\n}\n" }, { "alpha_fraction": 0.7002341747283936, "alphanum_fraction": 0.7002341747283936, "avg_line_length": 16.079999923706055, "blob_id": "83ab144c93ec566921bc28c82877b90be634d51c", "content_id": "4dba79fd821c89725fecf1212c988d30fa8f6077", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 427, "license_type": "permissive", "max_line_length": 42, "num_lines": 25, "path": "/apps/task-manager/windows/MainWindow.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Table.h>\n#include <libwidget/Window.h>\n\n#include \"task-manager/widgets/CPUGraph.h\"\n#include \"task-manager/widgets/RAMGraph.h\"\n\nnamespace task_manager\n{\n\nclass MainWinow : public Window\n{\nprivate:\n RAMGraph *_ram_graph;\n CPUGraph *_cpu_graph;\n Table *_table;\n RefPtr<TaskModel> _table_model;\n OwnPtr<Timer> _table_timer;\n\npublic:\n MainWinow();\n};\n\n} // namespace task_manager\n" }, { "alpha_fraction": 0.7588075995445251, "alphanum_fraction": 0.7669376730918884, "avg_line_length": 17.450000762939453, "blob_id": "b3904adb7c07f001f4b603379fd35ff1ea9578fd", "content_id": "704bf1f4ea90d6f153e03a991e2f2bc023b10c6d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 369, "license_type": "permissive", "max_line_length": 55, "num_lines": 20, "path": "/apps/compositor/Cursor.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Mouse.h>\n#include <libgraphic/Painter.h>\n\nvoid cursor_initialize();\n\nvoid cursor_handle_packet(MousePacket packet);\n\nvoid cursor_render(Painter &painter);\n\nRecti cursor_bound_from_position(Vec2i position);\n\nRecti cursor_dirty_bound_from_position(Vec2i position);\n\nRecti cursor_bound();\n\nRecti cursor_dirty_bound();\n\nVec2i cursor_position();\n" }, { "alpha_fraction": 0.5570496916770935, "alphanum_fraction": 0.5635696649551392, "avg_line_length": 27.20689582824707, "blob_id": "72971574ed8274c43357e7b404b3ba32bc6497ba", "content_id": "9c425549d3c5f18c5d7366429b1742862a841bf0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2454, "license_type": "permissive", "max_line_length": 117, "num_lines": 87, "path": "/apps/archive-manager/MainWindow.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libfile/Archive.h>\n#include <libwidget/Container.h>\n#include <libwidget/Panel.h>\n#include <libwidget/TitleBar.h>\n#include <libwidget/Window.h>\n\n#include <libfilepicker/FilePicker.h>\n#include <libfilepicker/model/Navigation.h>\n#include <libfilepicker/widgets/ArchiveBrowser.h>\n#include <libfilepicker/widgets/JumpList.h>\n#include <libfilepicker/widgets/ToolBar.h>\n\nclass MainWindow :\n public Window\n{\nprivate:\n RefPtr<filepicker::Navigation> _navigation;\n RefPtr<Archive> _archive;\n filepicker::Dialog _dialog;\n\npublic:\n void set_archive(RefPtr<Archive> archive)\n {\n _archive = archive;\n render();\n }\n\n MainWindow(RefPtr<filepicker::Navigation> navigation, RefPtr<Archive> archive)\n : Window(WINDOW_RESIZABLE), _navigation(navigation), _archive(archive)\n {\n icon(Icon::get(\"folder-zip\"));\n title(\"Archive Manager\");\n size(Vec2i(700, 500));\n\n render();\n }\n\n void render()\n {\n root()->clear_children();\n root()->layout(VFLOW(0));\n\n new TitleBar(root());\n\n auto browser = new Container(root());\n\n browser->flags(Widget::FILL);\n\n if (!_archive)\n {\n browser->layout(STACK());\n auto load_button = new Button(browser, Button::FILLED, Icon::get(\"folder-open\"), \"Load an archive file\");\n load_button->on(Event::ACTION, [&](auto) {\n if (_dialog.show() == DialogResult::OK)\n {\n set_archive(Archive::open(Path::parse(*_dialog.selected_file())));\n }\n });\n }\n else\n {\n browser->layout(VFLOW(0));\n\n auto toolbar = new Panel(browser);\n toolbar->layout(HFLOW(4));\n toolbar->insets(Insetsi(4, 4));\n toolbar->max_height(38);\n toolbar->min_height(38);\n\n new Button(toolbar, Button::TEXT, Icon::get(\"archive-arrow-up\"), \"Extract All\");\n\n new Separator(toolbar);\n\n auto load_button = new Button(toolbar, Button::TEXT, Icon::get(\"folder-open\"));\n load_button->on(Event::ACTION, [&](auto) {\n if (_dialog.show() == DialogResult::OK)\n {\n set_archive(Archive::open(Path::parse(*_dialog.selected_file())));\n }\n });\n\n new filepicker::ArchiveBrowser(browser, _navigation, _archive);\n }\n }\n};\n" }, { "alpha_fraction": 0.5560708045959473, "alphanum_fraction": 0.558178722858429, "avg_line_length": 20.563636779785156, "blob_id": "ee72f903f423ee8f15fc745b520bb38cb730cd06", "content_id": "561ed45f6dc6e613c99b112985212514ac52641f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2372, "license_type": "permissive", "max_line_length": 122, "num_lines": 110, "path": "/apps/utilities/mkdir.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/cmdline/CMDLine.h>\n#include <libsystem/io/Directory.h>\n#include <libsystem/io/Filesystem.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n\nstatic bool parent = false;\nstatic bool verbose = false;\n\nstatic CommandLineOption options[] = {\n COMMANDLINE_OPT_HELP,\n COMMANDLINE_OPT_BOOL(\"parents\", 'p', parent, \"Make parent directories as needed.\", COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"verbose\", 'v', verbose, \"Print a message for each created directory.\", COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_END};\n\nstatic const char *usages[] = {\n \"[OPTION]... DIRECTORY...\",\n nullptr,\n};\n\nstatic CommandLine cmdline = CMDLINE(\n usages,\n options,\n \"Create the DIRECTORY(ies), if they do not already exist.\",\n \"Options can be combined.\");\n\nvoid print_path(const char *path)\n{\n if (verbose)\n {\n printf(\"mkdir: created directory %s\\n\", path);\n }\n}\n\nvoid mkdir_parent_dirs(const char *path)\n{\n if (directory_exist(path))\n {\n return;\n }\n\n const char *iter = path;\n size_t path_len = strlen(path);\n char *construct_parent_dirs = (char *)calloc(path_len + 1, sizeof(char));\n char *iter_recursively = construct_parent_dirs;\n\n if (!path_len)\n {\n free(construct_parent_dirs);\n return;\n }\n\n while (*iter != '\\0')\n {\n *iter_recursively = *iter;\n\n if (*iter == '/')\n {\n if (!directory_exist(construct_parent_dirs))\n {\n filesystem_mkdir(construct_parent_dirs);\n print_path(construct_parent_dirs);\n }\n }\n\n ++iter_recursively;\n ++iter;\n }\n\n --iter;\n if (*iter != '/')\n {\n if (!directory_exist(construct_parent_dirs))\n {\n filesystem_mkdir(construct_parent_dirs);\n print_path(construct_parent_dirs);\n }\n }\n\n free(construct_parent_dirs);\n}\n\nint main(int argc, char **argv)\n{\n cmdline_parse(&cmdline, argc, argv);\n\n if (parent)\n {\n for (int i = 1; i < argc; ++i)\n {\n mkdir_parent_dirs(argv[i]);\n }\n\n return PROCESS_SUCCESS;\n }\n\n else\n {\n int result = 0;\n\n for (int i = 1; i < argc; i++)\n {\n result |= filesystem_mkdir(argv[i]);\n print_path(argv[i]);\n }\n\n return result;\n }\n}\n" }, { "alpha_fraction": 0.6059016585350037, "alphanum_fraction": 0.6068852543830872, "avg_line_length": 33.65909194946289, "blob_id": "d6c2aee8f701ce038d5b06baa943377160b403f0", "content_id": "cce06189092aa2fa23d7c059dc92a0efdeae82d3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3050, "license_type": "permissive", "max_line_length": 100, "num_lines": 88, "path": "/apps/calculator/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libutils/NumberFormat.h>\n#include <libutils/StringBuilder.h>\n\n#include <libwidget/Application.h>\n#include <libwidget/Button.h>\n#include <libwidget/Label.h>\n#include <libwidget/Markup.h>\n\n#include <stdio.h>\n\n#include \"calculator/Calculator.h\"\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n Window *window = window_create_from_file(\"/Applications/calculator/calculator.markup\");\n\n Calculator calculator{};\n\n auto calculator_observer = calculator.observe([&](Calculator &calculator) {\n window->with_widget<Label>(\"screen\", [&](Label *label) {\n label->text(String::format(\"{}\", calculator.screen()));\n });\n });\n\n for (int i = 0; i < 10; i++)\n {\n auto button_name = String::format(\"button_{}\", i);\n window->with_widget<Button>(button_name, [&](auto button) {\n button->on(Event::ACTION, [&, i](auto) { calculator.enter_number(i); });\n });\n }\n\n window->with_widget<Button>(\"button_plus\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::ADD); });\n });\n\n window->with_widget<Button>(\"button_minus\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::SUBSTRACT); });\n });\n\n window->with_widget<Button>(\"button_plus\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::ADD); });\n });\n\n window->with_widget<Button>(\"button_minus\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::SUBSTRACT); });\n });\n\n window->with_widget<Button>(\"button_multiply\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::MULTIPLY); });\n });\n\n window->with_widget<Button>(\"button_divide\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::DIVIDE); });\n });\n\n window->with_widget<Button>(\"button_reciprocal\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::RECIPROCAL); });\n });\n\n window->with_widget<Button>(\"button_sqrt\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::SQRT); });\n });\n\n window->with_widget<Button>(\"button_exp\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.enter_operation(Operation::POWER); });\n });\n\n window->with_widget<Button>(\"button_equal\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.equal(); });\n });\n\n window->with_widget<Button>(\"button_clear\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.clear(); });\n });\n\n window->with_widget<Button>(\"button_clear_all\", [&](auto button) {\n button->on(Event::ACTION, [&](auto) { calculator.clear_all(); });\n });\n\n calculator.did_update();\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.5178571343421936, "alphanum_fraction": 0.5252976417541504, "avg_line_length": 15.800000190734863, "blob_id": "1aa88466908f9d87e37dc85f91e43c0521db4332", "content_id": "f0d618402b5412c1b1820d3f7a1ab820bcdff0a8", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 672, "license_type": "permissive", "max_line_length": 62, "num_lines": 40, "path": "/libraries/libwidget/Graph.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nclass Graph : public Widget\n{\nprivate:\n Color _color;\n float *_data;\n size_t _data_size;\n size_t _current;\n\npublic:\n Graph(Widget *parent, size_t data_size, Color data_color);\n\n ~Graph();\n\n void record(float data);\n\n float average()\n {\n if (_data_size == 0)\n {\n return 0;\n }\n\n float total = 0;\n\n for (size_t i = 0; i < MIN(_current, _data_size); i++)\n {\n total += _data[i];\n }\n\n return total / MIN(_current, _data_size);\n }\n\n void paint(Painter &painter, const Recti &dirty) override;\n\n Vec2i size() override;\n};\n" }, { "alpha_fraction": 0.6449864506721497, "alphanum_fraction": 0.6639566421508789, "avg_line_length": 20.764705657958984, "blob_id": "b64d1325b9950bf31e6100b773107c089affa276", "content_id": "0eb3a292008396b0d42d8ae8ee6ce982cb5f8b69", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 369, "license_type": "permissive", "max_line_length": 60, "num_lines": 17, "path": "/libraries/libsystem/io/SeekableReader.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/SeekableReader.h>\n#include <libsystem/io/Writer.h>\n\n#define COPY_CHUNK_SIZE 4096\n\nvoid SeekableReader::copy_to(Writer &writer)\n{\n seek(0, WHENCE_START);\n\n uint8_t copy_chunk[COPY_CHUNK_SIZE];\n size_t chunk_size = 0;\n\n while ((chunk_size = read(copy_chunk, COPY_CHUNK_SIZE)))\n {\n writer.write(copy_chunk, chunk_size);\n }\n}" }, { "alpha_fraction": 0.46846505999565125, "alphanum_fraction": 0.5232712626457214, "avg_line_length": 31.100608825683594, "blob_id": "a78ef361f5e56c7b0775c19bcdc44c1cead7c158", "content_id": "4b23298ca19999f047110b51b5a613fca98cc89f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10528, "license_type": "permissive", "max_line_length": 168, "num_lines": 328, "path": "/libraries/libsystem/compression/Inflate.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/compression/Common.h>\n#include <libsystem/compression/Huffman.h>\n#include <libsystem/compression/Inflate.h>\n#include <libsystem/io/MemoryWriter.h>\n#include <libsystem/io/Reader.h>\n#include <libsystem/io/Writer.h>\n\nstatic constexpr uint8_t BASE_LENGTH_EXTRA_BITS[] = {\n 0, 0, 0, 0, 0, 0, 0, 0, //257 - 264\n 1, 1, 1, 1, //265 - 268\n 2, 2, 2, 2, //269 - 273\n 3, 3, 3, 3, //274 - 276\n 4, 4, 4, 4, //278 - 280\n 5, 5, 5, 5, //281 - 284\n 0 //285\n};\n\nstatic constexpr uint16_t BASE_LENGTHS[] = {\n 3, 4, 5, 6, 7, 8, 9, 10, //257 - 264\n 11, 13, 15, 17, //265 - 268\n 19, 23, 27, 31, //269 - 273\n 35, 43, 51, 59, //274 - 276\n 67, 83, 99, 115, //278 - 280\n 131, 163, 195, 227, //281 - 284\n 258 //285\n};\n\nstatic constexpr uint16_t BASE_DISTANCE[] = {\n 1, 2, 3, 4, //0-3\n 5, 7, //4-5\n 9, 13, //6-7\n 17, 25, //8-9\n 33, 49, //10-11\n 65, 97, //12-13\n 129, 193, //14-15\n 257, 385, //16-17\n 513, 769, //18-19\n 1025, 1537, //20-21\n 2049, 3073, //22-23\n 4097, 6145, //24-25\n 8193, 12289, //26-27\n 16385, 24577, //28-29\n 0, 0 //30-31, error, shouldn't occur\n};\n\nstatic constexpr uint8_t BASE_DISTANCE_EXTRA_BITS[] = {\n 0, 0, 0, 0, //0-3\n 1, 1, //4-5\n 2, 2, //6-7\n 3, 3, //8-9\n 4, 4, //10-11\n 5, 5, //12-13\n 6, 6, //14-15\n 7, 7, //16-17\n 8, 8, //18-19\n 9, 9, //20-21\n 10, 10, //22-23\n 11, 11, //24-25\n 12, 12, //26-27\n 13, 13, //28-29\n 0, 0 //30-31 error, they shouldn't occur\n};\n\nvoid Inflate::get_bit_length_count(HashMap<unsigned int, unsigned int> &bit_length_count, const Vector<unsigned int> &code_bit_lengths)\n{\n for (unsigned int i = 0; i != code_bit_lengths.count(); i++)\n {\n bit_length_count[code_bit_lengths[i]] = 0;\n }\n\n for (unsigned int i = 0; i != code_bit_lengths.count(); i++)\n {\n bit_length_count[code_bit_lengths[i]]++;\n }\n}\n\nvoid Inflate::get_first_code(HashMap<unsigned int, unsigned int> &first_codes, HashMap<unsigned int, unsigned int> &bit_length_count)\n{\n unsigned int code = 0;\n unsigned int prev_bl_count = 0;\n for (unsigned int i = 1; i <= (unsigned int)bit_length_count.count(); i++)\n {\n if (i >= 2)\n {\n prev_bl_count = bit_length_count[i - 1];\n }\n code = (code + prev_bl_count) << 1;\n first_codes[i] = code;\n }\n}\n\nvoid Inflate::assign_huffman_codes(Vector<unsigned int> &assigned_codes, const Vector<unsigned int> &code_bit_lengths, HashMap<unsigned int, unsigned int> &first_codes)\n{\n assigned_codes.resize(code_bit_lengths.count());\n\n for (unsigned int i = 0; i < (unsigned int)code_bit_lengths.count(); i++)\n {\n if (code_bit_lengths[i])\n {\n assigned_codes[i] = first_codes[code_bit_lengths[i]]++;\n }\n else\n {\n assigned_codes[i] = 0;\n }\n }\n}\n\nvoid Inflate::build_huffman_alphabet(Vector<unsigned int> &alphabet, const Vector<unsigned int> &code_bit_lengths)\n{\n HashMap<unsigned int, unsigned int> bit_length_count, first_codes;\n\n get_bit_length_count(bit_length_count, code_bit_lengths);\n get_first_code(first_codes, bit_length_count);\n assign_huffman_codes(alphabet, code_bit_lengths, first_codes);\n}\n\n// TODO: use a constexpr function to calculate these tables\nvoid Inflate::build_fixed_huffman_alphabet()\n{\n if (_fixed_code_bit_lengths.count())\n {\n return;\n }\n\n _fixed_code_bit_lengths.resize(288);\n _fixed_dist_code_bit_lengths.resize(32);\n\n for (int i = 0; i <= 287; i++)\n {\n if (i >= 0 && i <= 143)\n {\n _fixed_code_bit_lengths[i] = 8;\n }\n else if (i >= 144 && i <= 255)\n {\n _fixed_code_bit_lengths[i] = 9;\n }\n else if (i >= 256 && i <= 279)\n {\n _fixed_code_bit_lengths[i] = 7;\n }\n else if (i >= 280 && i <= 287)\n {\n _fixed_code_bit_lengths[i] = 8;\n }\n }\n\n for (int i = 0; i != 32; i++)\n {\n _fixed_dist_code_bit_lengths[i] = 5;\n }\n\n build_huffman_alphabet(_fixed_alphabet, _fixed_code_bit_lengths);\n build_huffman_alphabet(_fixed_dist_alphabet, _fixed_dist_code_bit_lengths);\n}\n\nResult Inflate::build_dynamic_huffman_alphabet(BitReader &input)\n{\n Vector<unsigned int> code_length_of_code_length_order = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n Vector<unsigned int> code_length_of_code_length = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n\n unsigned int hlit = input.grab_bits(5) + 257;\n unsigned int hdist = input.grab_bits(5) + 1;\n unsigned int hclen = input.grab_bits(4) + 4;\n\n // See: https://github.com/madler/zlib/issues/82\n if (hlit > 286 || hdist > 30)\n {\n return Result::ERR_INVALID_DATA;\n }\n\n for (unsigned int i = 0; i < hclen; i++)\n {\n code_length_of_code_length[code_length_of_code_length_order[i]] = input.grab_bits(3);\n }\n\n Vector<unsigned int> lit_len_and_dist_alphabets;\n build_huffman_alphabet(lit_len_and_dist_alphabets, code_length_of_code_length);\n\n Vector<unsigned int> lit_len_and_dist_trees_unpacked;\n HuffmanDecoder huffman(lit_len_and_dist_alphabets, code_length_of_code_length);\n while (lit_len_and_dist_trees_unpacked.count() < (hdist + hlit))\n {\n unsigned int decoded_value = huffman.decode(input);\n\n // Everything below 16 corresponds directly to a codelength. See https://tools.ietf.org/html/rfc1951#section-3.2.7\n if (decoded_value < 16)\n {\n lit_len_and_dist_trees_unpacked.push_back(decoded_value);\n continue;\n }\n\n unsigned int repeat_count = 0;\n unsigned int code_length_to_repeat = 0;\n\n switch (decoded_value)\n {\n // 3-6\n case 16:\n repeat_count = input.grab_bits(2) + 3;\n code_length_to_repeat = lit_len_and_dist_trees_unpacked.peek_back();\n break;\n // 3-10\n case 17:\n repeat_count = input.grab_bits(3) + 3;\n break;\n // 11 - 138\n case 18:\n repeat_count = input.grab_bits(7) + 11;\n break;\n }\n\n for (unsigned int i = 0; i != repeat_count; i++)\n {\n lit_len_and_dist_trees_unpacked.push_back(code_length_to_repeat);\n }\n }\n\n _lit_len_code_bit_length.resize(hlit);\n for (unsigned int i = 0; i < _lit_len_code_bit_length.count(); i++)\n {\n _lit_len_code_bit_length[i] = lit_len_and_dist_trees_unpacked[i];\n }\n\n _dist_code_bit_length.resize(lit_len_and_dist_trees_unpacked.count() - hlit);\n for (unsigned int i = 0; i < _dist_code_bit_length.count(); i++)\n {\n _dist_code_bit_length[i] = lit_len_and_dist_trees_unpacked[hlit + i];\n }\n\n build_huffman_alphabet(_lit_len_alphabet, _lit_len_code_bit_length);\n build_huffman_alphabet(_dist_alphabet, _dist_code_bit_length);\n return Result::SUCCESS;\n}\n\nResult Inflate::perform(Reader &compressed, Writer &uncompressed)\n{\n assert(compressed.length() > 0);\n BitReader input(compressed);\n Vector<uint8_t> block_buffer;\n\n uint8_t bfinal;\n do\n {\n bfinal = input.grab_bits(1);\n uint8_t btype = input.grab_bits(2);\n\n // Uncompressed block\n if (btype == BT_UNCOMPRESSED)\n {\n // Align to byte bounadries\n input.skip_bits(5);\n auto len = input.grab_uint16();\n\n // Skip complement of LEN\n input.skip_bits(16);\n\n for (int i = 0; i != len; i++)\n {\n uncompressed.write_byte(input.grab_bits(8));\n }\n }\n else if (btype == BT_FIXED_HUFFMAN ||\n btype == BT_DYNAMIC_HUFFMAN)\n {\n block_buffer.clear();\n\n // Use a fixed huffman alphabet\n if (btype == BT_FIXED_HUFFMAN)\n {\n build_fixed_huffman_alphabet();\n }\n // Use a dynamic huffman alphabet\n else\n {\n auto result = build_dynamic_huffman_alphabet(input);\n if (result != Result::SUCCESS)\n {\n return result;\n }\n }\n\n // Do the actual huffman decoding\n HuffmanDecoder symbol_decoder(btype == BT_FIXED_HUFFMAN ? _fixed_alphabet : _lit_len_alphabet,\n btype == BT_FIXED_HUFFMAN ? _fixed_code_bit_lengths : _lit_len_code_bit_length);\n\n HuffmanDecoder dist_decoder(btype == BT_FIXED_HUFFMAN ? _fixed_dist_alphabet : _dist_alphabet,\n btype == BT_FIXED_HUFFMAN ? _fixed_dist_code_bit_lengths : _dist_code_bit_length);\n while (true)\n {\n unsigned int decoded_symbol = symbol_decoder.decode(input);\n if (decoded_symbol <= 255)\n {\n block_buffer.push_back((unsigned char)decoded_symbol);\n }\n else if (decoded_symbol == 256)\n {\n break;\n }\n else\n {\n unsigned int length_index = decoded_symbol - 257;\n unsigned int total_length = BASE_LENGTHS[length_index] + input.grab_bits(BASE_LENGTH_EXTRA_BITS[length_index]);\n unsigned int dist_code = dist_decoder.decode(input);\n\n unsigned int total_dist = BASE_DISTANCE[dist_code] + input.grab_bits(BASE_DISTANCE_EXTRA_BITS[dist_code]);\n uint8_t *pos = (uint8_t *)&block_buffer[block_buffer.count() - total_dist];\n for (unsigned int i = 0; i != total_length; i++)\n {\n block_buffer.push_back(*pos);\n pos = (uint8_t *)&block_buffer[block_buffer.count() - total_dist];\n }\n }\n }\n\n // Copy our temporary block buffer to output\n uncompressed.write(block_buffer.raw_storage(), block_buffer.count());\n }\n else\n {\n return Result::ERR_INVALID_DATA;\n }\n } while (!bfinal);\n\n return Result::SUCCESS;\n}" }, { "alpha_fraction": 0.6850912570953369, "alphanum_fraction": 0.6859787106513977, "avg_line_length": 14.65079402923584, "blob_id": "b5027869341b76d06116a6f2cd8d8da57ba82155", "content_id": "3f7e5a3deaa163c83ff50935d8be31b2efcacdac", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7888, "license_type": "permissive", "max_line_length": 121, "num_lines": 504, "path": "/libraries/libutils/Traits.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\ntemplate <bool B, class T = void>\nstruct EnableIf\n{\n};\n\ntemplate <class T>\nstruct EnableIf<true, T>\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct AddConst\n{\n using Type = const T;\n};\n\ntemplate <class T>\nstruct RemoveConst\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemoveConst<const T>\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemoveVolatile\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemoveVolatile<volatile T>\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemoveConstVolatile\n{\n typedef typename RemoveVolatile<typename RemoveConst<T>::Type>::Type Type;\n};\n\ntemplate <class T, T v>\nstruct IntegralConstant\n{\n static constexpr T value = v;\n using ValueType = T;\n using Type = IntegralConstant;\n constexpr operator ValueType() const { return value; }\n constexpr ValueType operator()() const { return value; }\n};\n\nusing FalseType = IntegralConstant<bool, false>;\n\nusing TrueType = IntegralConstant<bool, true>;\n\ntemplate <class T>\nstruct IsLvalueReference : FalseType\n{\n};\n\ntemplate <class T>\nstruct IsLvalueReference<T &> : TrueType\n{\n};\n\ntemplate <class T>\nstruct __IsPointerHelper : FalseType\n{\n};\n\ntemplate <class T>\nstruct __IsPointerHelper<T *> : TrueType\n{\n};\n\ntemplate <class T>\nstruct IsPointer : __IsPointerHelper<typename RemoveConstVolatile<T>::Type>\n{\n};\n\ntemplate <class>\nstruct IsFunction : FalseType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...)> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...)> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) const> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) const> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) volatile> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) volatile> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) const volatile> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) const volatile> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) &> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) &> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) const &> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) const &> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) volatile &> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) volatile &> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) const volatile &> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) const volatile &> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) &&> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) &&> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) const &&> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) const &&> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) volatile &&> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) volatile &&> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args...) const volatile &&> : TrueType\n{\n};\n\ntemplate <class Ret, class... Args>\nstruct IsFunction<Ret(Args..., ...) const volatile &&> : TrueType\n{\n};\n\ntemplate <class T>\nstruct IsRvalueReference : FalseType\n{\n};\n\ntemplate <class T>\nstruct IsRvalueReference<T &&> : TrueType\n{\n};\n\ntemplate <class T>\nstruct RemovePointer\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemovePointer<T *>\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemovePointer<T *const>\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemovePointer<T *volatile>\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemovePointer<T *const volatile>\n{\n using Type = T;\n};\n\ntemplate <typename T, typename U>\nstruct IsSame : FalseType\n{\n};\n\ntemplate <typename T>\nstruct IsSame<T, T> : TrueType\n{\n};\n\ntemplate <bool condition, class TrueType, class FalseType>\nstruct Conditional\n{\n typedef TrueType Type;\n};\n\ntemplate <class TrueType, class FalseType>\nstruct Conditional<false, TrueType, FalseType>\n{\n typedef FalseType Type;\n};\n\ntemplate <typename T>\nstruct RemoveReference\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemoveReference<T &>\n{\n using Type = T;\n};\n\ntemplate <class T>\nstruct RemoveReference<T &&>\n{\n using Type = T;\n};\n\ntemplate <typename T>\nstruct MakeUnsigned\n{\n};\n\ntemplate <>\nstruct MakeUnsigned<signed char>\n{\n typedef unsigned char Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<short>\n{\n typedef unsigned short Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<int>\n{\n typedef unsigned Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<long>\n{\n typedef unsigned long Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<long long>\n{\n typedef unsigned long long Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<unsigned char>\n{\n typedef unsigned char Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<unsigned short>\n{\n typedef unsigned short Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<unsigned int>\n{\n typedef unsigned Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<unsigned long>\n{\n typedef unsigned long Type;\n};\n\ntemplate <>\nstruct MakeUnsigned<unsigned long long>\n{\n typedef unsigned long long Type;\n};\n\ntemplate <typename T>\nstruct MakeSigned\n{\n};\n\ntemplate <>\nstruct MakeSigned<signed char>\n{\n typedef signed char Type;\n};\n\ntemplate <>\nstruct MakeSigned<short>\n{\n typedef short Type;\n};\n\ntemplate <>\nstruct MakeSigned<int>\n{\n typedef int Type;\n};\n\ntemplate <>\nstruct MakeSigned<long>\n{\n typedef long Type;\n};\n\ntemplate <>\nstruct MakeSigned<long long>\n{\n typedef long long Type;\n};\n\ntemplate <>\nstruct MakeSigned<unsigned char>\n{\n typedef char Type;\n};\n\ntemplate <>\nstruct MakeSigned<unsigned short>\n{\n typedef short Type;\n};\n\ntemplate <>\nstruct MakeSigned<unsigned int>\n{\n typedef int Type;\n};\n\ntemplate <>\nstruct MakeSigned<unsigned long>\n{\n typedef long Type;\n};\n\ntemplate <>\nstruct MakeSigned<unsigned long long>\n{\n typedef long long Type;\n};\n\ntemplate <class T>\nstruct IsVoid : IsSame<void, typename RemoveConstVolatile<T>::Type>\n{\n};\n\ntemplate <class T>\nstruct IsConst : FalseType\n{\n};\n\ntemplate <class T>\nstruct IsConst<const T> : TrueType\n{\n};\n\ntemplate <typename T>\nstruct IsUnion : public IntegralConstant<bool, __is_union(T)>\n{\n};\n\ntemplate <typename T>\nstruct IsClass : public IntegralConstant<bool, __is_class(T)>\n{\n};\n\ntemplate <typename Base, typename Derived>\nstruct IsBaseOf : public IntegralConstant<bool, __is_base_of(Base, Derived)>\n{\n};\n\ntemplate <typename T>\nstruct __IsIntegral : FalseType\n{\n};\n\ntemplate <>\nstruct __IsIntegral<uint8_t> : TrueType\n{\n};\n\ntemplate <>\nstruct __IsIntegral<uint16_t> : TrueType\n{\n};\n\ntemplate <>\nstruct __IsIntegral<uint32_t> : TrueType\n{\n};\n\ntemplate <>\nstruct __IsIntegral<uint64_t> : TrueType\n{\n};\n\ntemplate <typename T>\nusing IsIntegral = __IsIntegral<typename MakeUnsigned<typename RemoveConstVolatile<T>::Type>::Type>;\n\ntemplate <typename T>\nstruct __IsFloatingPoint : FalseType\n{\n};\n\ntemplate <>\nstruct __IsFloatingPoint<float> : TrueType\n{\n};\n\ntemplate <>\nstruct __IsFloatingPoint<double> : TrueType\n{\n};\n\ntemplate <typename T>\nusing IsFloatingPoint = __IsFloatingPoint<typename RemoveConstVolatile<T>::Type>;\n\ntemplate <typename ReferenceType, typename T>\nusing CopyConst =\n typename Conditional<IsConst<ReferenceType>::value, typename AddConst<T>::Type, typename RemoveConst<T>::Type>::Type;\n" }, { "alpha_fraction": 0.6902238130569458, "alphanum_fraction": 0.6902238130569458, "avg_line_length": 19.190475463867188, "blob_id": "5f6681e64dfa409fc972171d463747cc27f86ab0", "content_id": "70e47156d4841b80c9f9d176cba6f9ddd5cac73e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 849, "license_type": "permissive", "max_line_length": 80, "num_lines": 42, "path": "/libraries/libsystem/io/Directory.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Directory.h>\n\nstruct Directory\n{\n Handle handle;\n};\n\nDirectory *directory_open(const char *path, OpenFlag flags)\n{\n Directory *directory = __create(Directory);\n\n __plug_handle_open(HANDLE(directory), path, flags | OPEN_DIRECTORY);\n\n return directory;\n}\n\nvoid directory_close(Directory *directory)\n{\n __plug_handle_close(HANDLE(directory));\n\n free(directory);\n}\n\nint directory_read(Directory *directory, DirectoryEntry *entry)\n{\n return __plug_handle_read(HANDLE(directory), entry, sizeof(DirectoryEntry));\n}\n\nbool directory_exist(const char *path)\n{\n Directory *directory = directory_open(path, OPEN_READ);\n\n if (handle_has_error(directory))\n {\n directory_close(directory);\n return false;\n }\n\n directory_close(directory);\n return true;\n}\n" }, { "alpha_fraction": 0.6954732537269592, "alphanum_fraction": 0.6954732537269592, "avg_line_length": 17.69230842590332, "blob_id": "87faf0b744caf7990d3a9a68682fddd667dea8f6", "content_id": "a127863d3e8b35862c04e51ab9341e550c626145", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 243, "license_type": "permissive", "max_line_length": 64, "num_lines": 13, "path": "/apps/panel/widgets/UserAccount.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <skift/Environment.h>\n\n#include \"panel/widgets/UserAccount.h\"\n\nnamespace panel\n{\n\nUserAccount::UserAccount(Widget *parent) : Label(parent, \"\")\n{\n text(environment().get(\"POSIX\").get(\"LOGNAME\").as_string());\n}\n\n} // namespace panel\n" }, { "alpha_fraction": 0.60297030210495, "alphanum_fraction": 0.60792076587677, "avg_line_length": 19.404041290283203, "blob_id": "53c589bd66c82c4a2235783f134ff5787021546c", "content_id": "929ef16c128e46459e976a642ad3ed0dd9ce109c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2020, "license_type": "permissive", "max_line_length": 88, "num_lines": 99, "path": "/libraries/libsystem/utils/BufferBuilder.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/math/MinMax.h>\n#include <libsystem/utils/BufferBuilder.h>\n\nstruct BufferBuilder\n{\n size_t used;\n size_t size;\n char *buffer;\n};\n\nBufferBuilder *buffer_builder_create(size_t preallocated)\n{\n preallocated = MAX(preallocated, 16);\n\n BufferBuilder *buffer = __create(BufferBuilder);\n\n buffer->buffer = (char *)calloc(preallocated, sizeof(char));\n buffer->size = preallocated;\n buffer->used = 0;\n\n return buffer;\n}\n\nvoid buffer_builder_destroy(BufferBuilder *buffer)\n{\n if (buffer->buffer)\n {\n free(buffer->buffer);\n }\n\n free(buffer);\n}\n\nchar *buffer_builder_finalize(BufferBuilder *buffer)\n{\n char *result = buffer->buffer;\n buffer->buffer = nullptr;\n\n buffer_builder_destroy(buffer);\n\n return result;\n}\n\nconst char *buffer_builder_intermediate(BufferBuilder *builder)\n{\n return builder->buffer;\n}\n\nvoid buffer_builder_append_str(BufferBuilder *buffer, const char *str)\n{\n if (str)\n {\n for (size_t i = 0; str[i]; i++)\n {\n buffer_builder_append_chr(buffer, str[i]);\n }\n }\n else\n {\n buffer_builder_append_str(buffer, \"<null>\");\n }\n}\n\nvoid buffer_builder_append_str_size(BufferBuilder *buffer, const char *str, size_t size)\n{\n if (str)\n {\n for (size_t i = 0; i < size; i++)\n {\n buffer_builder_append_chr(buffer, str[i]);\n }\n }\n else\n {\n buffer_builder_append_str(buffer, \"<null>\");\n }\n}\n\nvoid buffer_builder_append_chr(BufferBuilder *buffer, char chr)\n{\n if (buffer->used + 1 == buffer->size)\n {\n buffer->size += buffer->size / 4;\n buffer->buffer = (char *)realloc(buffer->buffer, buffer->size);\n }\n\n buffer->buffer[buffer->used] = chr;\n buffer->buffer[buffer->used + 1] = '\\0';\n buffer->used++;\n}\n\nvoid buffer_builder_rewind(BufferBuilder *buffer, size_t how_many)\n{\n assert(buffer->used >= how_many);\n\n buffer->used -= how_many;\n buffer->buffer[buffer->used] = '\\0';\n}\n" }, { "alpha_fraction": 0.7084282636642456, "alphanum_fraction": 0.7084282636642456, "avg_line_length": 19.904762268066406, "blob_id": "9fe7c32f317cb81f628fd656118680c1b0ef5c65", "content_id": "3be9a2be39df2354fd7746658afde88bbd9073ee", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 439, "license_type": "permissive", "max_line_length": 72, "num_lines": 21, "path": "/libraries/libwidget/Image.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nclass Image : public Widget\n{\nprivate:\n RefPtr<Bitmap> _bitmap;\n BitmapScaling _scaling = BitmapScaling::FIT;\n\npublic:\n Image(Widget *parent, RefPtr<Bitmap> bitmap);\n\n Image(Widget *parent, RefPtr<Bitmap> bitmap, BitmapScaling scaling);\n\n void change_bitmap(RefPtr<Bitmap> bitmap);\n\n void scaling(BitmapScaling scaling);\n\n void paint(Painter &, const Recti &) override;\n};\n" }, { "alpha_fraction": 0.47953489422798157, "alphanum_fraction": 0.49534884095191956, "avg_line_length": 18.369369506835938, "blob_id": "9bb6593842564105c7a18c2e878a9c3a6e762971", "content_id": "72af62829fb1524895ba510f1e4ce59dad34ddeb", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2150, "license_type": "permissive", "max_line_length": 78, "num_lines": 111, "path": "/libraries/libsystem/io_new/MemoryWriter.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <string.h>\n\n#include <libutils/RefPtr.h>\n#include <libutils/SliceStorage.h>\n#include <libutils/StringStorage.h>\n\n#include <libsystem/io_new/Writer.h>\n#include <libsystem/math/MinMax.h>\n\nnamespace System\n{\n\nclass MemoryWriter :\n public Writer\n{\nprivate:\n size_t _used = 0;\n size_t _size = 0;\n uint8_t *_buffer = nullptr;\n\npublic:\n MemoryWriter() : MemoryWriter(16)\n {\n }\n\n MemoryWriter(size_t preallocated)\n {\n preallocated = MAX(preallocated, 16);\n\n _buffer = new uint8_t[preallocated];\n _buffer[0] = '\\0';\n _size = preallocated;\n _used = 0;\n }\n\n ~MemoryWriter()\n {\n if (_buffer)\n {\n delete[] _buffer;\n }\n }\n\n // Create a string and flush the buffer!;\n RefPtr<StringStorage> string()\n {\n write('\\0'); // Null terminator\n\n uint8_t *result = _buffer;\n size_t size = _used;\n\n _buffer = nullptr;\n _used = 0;\n _size = 0;\n\n return make<StringStorage>(AdoptTag::ADOPT, (char *)result, size - 1);\n }\n\n RefPtr<SliceStorage> slice()\n {\n uint8_t *result = _buffer;\n size_t size = _used;\n\n _buffer = nullptr;\n _used = 0;\n _size = 0;\n\n return make<SliceStorage>(SliceStorage::ADOPT, (void *)result, size);\n }\n\n ResultOr<size_t> write(uint8_t v) override\n {\n if (_size == 0)\n {\n _buffer = new uint8_t[16];\n _buffer[0] = '\\0';\n _size = 16;\n _used = 0;\n }\n\n if (_used == _size)\n {\n auto new_size = _size + _size / 4;\n auto new_buffer = new uint8_t[new_size];\n memcpy(new_buffer, _buffer, _size);\n delete[] _buffer;\n\n _size = new_size;\n _buffer = new_buffer;\n }\n\n _buffer[_used] = v;\n _used++;\n\n return 1;\n }\n\n ResultOr<size_t> write(const void *buffer, size_t size) override\n {\n for (size_t i = 0; i < size; i++)\n {\n write(((uint8_t *)buffer)[i]);\n }\n\n return size;\n }\n};\n\n} // namespace System\n" }, { "alpha_fraction": 0.6692506670951843, "alphanum_fraction": 0.6692506670951843, "avg_line_length": 23.1875, "blob_id": "e5163155e13df9be7c399bac51989b7f711986c6", "content_id": "8dde5b3922c46af6b0aca0bbd2e871cbe5d21995", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 387, "license_type": "permissive", "max_line_length": 96, "num_lines": 16, "path": "/libraries/libsystem/io/Handle.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Handle.h>\n#include <skift/Time.h>\n\n#define handle_printf_error(__handle, __args...) __handle_printf_error(HANDLE(__handle), __args)\n\nint __handle_printf_error(Handle *handle, const char *fmt, ...);\n\nResult handle_poll(\n Handle **handles,\n PollEvent *events,\n size_t count,\n Handle **selected,\n PollEvent *selected_events,\n Timeout timeout);\n" }, { "alpha_fraction": 0.704023003578186, "alphanum_fraction": 0.704023003578186, "avg_line_length": 15.571428298950195, "blob_id": "615fd1e633f6ab60f933b14e308e08c47e32b101", "content_id": "d3ab2b71b14ba84404f5e695d84e7812c74bbb81", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 348, "license_type": "permissive", "max_line_length": 57, "num_lines": 21, "path": "/apps/media-player/widgets/Cover.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Bitmap.h>\n#include <libwidget/Widget.h>\n\nnamespace media_player\n{\n\nclass Cover : public Widget\n{\nprivate:\n RefPtr<Bitmap> _cover;\n RefPtr<Bitmap> _backdrop;\n\npublic:\n Cover(Widget *parent, RefPtr<Bitmap> bitmap);\n\n void paint(Painter &painter, const Recti &) override;\n};\n\n} // namespace media_player\n" }, { "alpha_fraction": 0.5749342441558838, "alphanum_fraction": 0.5784399509429932, "avg_line_length": 20.94230842590332, "blob_id": "3adcf4b113453e823e3d47fae74fe1bf7538e7a7", "content_id": "de8382e0d52c7113572bf0a035577482bc17b795", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1141, "license_type": "permissive", "max_line_length": 73, "num_lines": 52, "path": "/libraries/libutils/StringStorage.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/RefCounted.h>\n#include <string.h>\n\nclass StringStorage :\n public RefCounted<StringStorage>\n{\nprivate:\n size_t _length;\n char *_buffer;\n\npublic:\n const char *cstring() { return _buffer; }\n\n size_t length() { return _length; }\n\n StringStorage(const char *cstring)\n : StringStorage(cstring, strlen(cstring))\n {\n }\n\n StringStorage(const char *cstring, size_t length)\n {\n _length = strnlen(cstring, length);\n _buffer = new char[_length + 1];\n memcpy(_buffer, cstring, _length);\n _buffer[_length] = '\\0';\n }\n\n StringStorage(AdoptTag, char *buffer, size_t length)\n {\n _length = length;\n _buffer = buffer;\n }\n\n StringStorage(StringStorage &left, StringStorage &right)\n {\n _length = left.length() + right.length();\n _buffer = new char[_length + 1];\n\n memcpy(_buffer, left.cstring(), left.length());\n memcpy(_buffer + left.length(), right.cstring(), right.length());\n\n _buffer[left.length() + right.length()] = '\\0';\n }\n\n ~StringStorage()\n {\n delete[] _buffer;\n }\n};\n" }, { "alpha_fraction": 0.5902255773544312, "alphanum_fraction": 0.6060150265693665, "avg_line_length": 21.931034088134766, "blob_id": "3d7744fbba4cc091c074b9fb434afc123f71a6c3", "content_id": "4c7bf41a0edeb03d0378b35d89e064f615582246", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1330, "license_type": "permissive", "max_line_length": 65, "num_lines": 58, "path": "/apps/text-editor/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Application.h>\n#include <libwidget/Button.h>\n#include <libwidget/Panel.h>\n#include <libwidget/TextEditor.h>\n#include <libwidget/TitleBar.h>\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n Window *window = new Window(WINDOW_RESIZABLE);\n\n window->icon(Icon::get(\"text-box\"));\n\n if (argc == 2)\n {\n window->title(argv[1]);\n }\n else\n {\n window->title(\"Text Editor\");\n }\n\n window->size(Vec2i(700, 500));\n\n window->root()->layout(VFLOW(0));\n\n new TitleBar(window->root());\n\n auto toolbar = new Panel(window->root());\n\n toolbar->layout(HFLOW(4));\n toolbar->insets(Insetsi(4, 4));\n toolbar->max_height(38);\n toolbar->min_height(38);\n\n new Button(toolbar, Button::TEXT, Icon::get(\"folder-open\"));\n new Button(toolbar, Button::TEXT, Icon::get(\"content-save\"));\n new Button(toolbar, Button::TEXT, Icon::get(\"file-plus\"));\n\n auto model = TextModel::empty();\n\n if (argc == 2)\n {\n logger_info(\"Opening text document from '%s'\", argv[1]);\n model = TextModel::from_file(argv[1]);\n }\n\n auto field = new TextEditor(window->root(), model);\n field->flags(Widget::FILL);\n field->overscroll(true);\n field->insets({4});\n field->focus();\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 21, "blob_id": "3dd145b430d93958daf5d4beca82e52a5dc20932", "content_id": "ec66536b8be2e9f38088b18b04926961df6f56d5", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 153, "license_type": "permissive", "max_line_length": 61, "num_lines": 7, "path": "/libraries/libwidget/Markup.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Window.h>\n\nWindow *window_create_from_file(String path);\n\nWidget *widget_create_from_file(Widget *parent, String path);" }, { "alpha_fraction": 0.6018099784851074, "alphanum_fraction": 0.6018099784851074, "avg_line_length": 17.41666603088379, "blob_id": "bbe75d5f308f4d29b7ef27e153c404b0cac90dfa", "content_id": "16bb61afdc35009db937bd16492b8015650704e0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 663, "license_type": "permissive", "max_line_length": 73, "num_lines": 36, "path": "/libraries/libsystem/eventloop/Notifier.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Callback.h>\n\n#include <libsystem/eventloop/EventLoop.h>\n#include <libsystem/io/Handle.h>\n\nclass Notifier\n{\nprivate:\n Handle *_handle;\n PollEvent _events;\n Callback<void()> _callback;\n\npublic:\n Handle *handle() { return _handle; }\n PollEvent events() { return _events; }\n\n Notifier(Handle *handle, PollEvent events, Callback<void()> callback)\n : _handle(handle),\n _events(events),\n _callback(callback)\n {\n EventLoop::register_notifier(this);\n }\n\n ~Notifier()\n {\n EventLoop::unregister_notifier(this);\n }\n\n void invoke()\n {\n _callback();\n }\n};\n" }, { "alpha_fraction": 0.624722421169281, "alphanum_fraction": 0.6321243643760681, "avg_line_length": 12.577889442443848, "blob_id": "e24ff584332f8d3d186fcb84505861911fd8fcad", "content_id": "f3c3132dd5a2a91baf910b03c8b2514e39f8f25e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2702, "license_type": "permissive", "max_line_length": 112, "num_lines": 199, "path": "/apps/utilities/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "UTILITIES = \\\n\tBASENAME \\\n\tCAT \\\n\tCLEAR \\\n\tCP \\\n\tDIRNAME \\\n\tDISPLAYCTL \\\n\tDSTART \\\n\tECHO \\\n\tENV \\\n\tFALSE \\\n\tGREP \\\n\tHEAD \\\n\tHEXDUMP \\\n\tINIT \\\n\tJSON \\\n\tKEYBOARDCTL \\\n\tKILL \\\n\tLINK \\\n\tLS \\\n\tMARKUP \\\n\tMKDIR \\\n\tMV \\\n\tNETCTL\\\n\tNOW \\\n\tOPEN \\\n\tPANIC \\\n\tPIANO \\\n\tPLAY \\\n\tPOWERCTL \\\n\tPWD\t\\\n\tRMDIR \\\n\tSETTINGSCTL \\\n\tSYSFETCH \\\n\tTAC \\\n\tTOUCH \\\n\tTRUE \\\n\tUNAME \\\n\tUNLINK \\\n\tUNZIP \\\n\tUPTIME \\\n\tYES \\\n\tZIP\n\nBASENAME_LIBS =\nBASENAME_NAME = basename\n\nCAT_LIBS =\nCAT_NAME = cat\n\nCLEAR_LIBS =\nCLEAR_NAME = clear\n\nCP_LIBS =\nCP_NAME = cp\n\nPLAY_LIBS =\nPLAY_NAME = play\n\nDSTART_LIBS =\nDSTART_NAME = dstart\n\nDIRNAME_LIBS =\nDIRNAME_NAME = dirname\n\nECHO_LIBS =\nECHO_NAME = echo\n\nENV_LIBS =\nENV_NAME = env\n\nGREP_LIBS =\nGREP_NAME = grep\n\nHEAD_LIBS =\nHEAD_NAME = head\n\nHEXDUMP_LIBS =\nHEXDUMP_NAME = hexdump\n\nINIT_LIBS =\nINIT_NAME = init\n\nJSON_LIBS =\nJSON_NAME = json\n\nKILL_LIBS =\nKILL_NAME = kill\n\nLINK_LIBS =\nLINK_NAME = link\n\nLS_LIBS =\nLS_NAME = ls\n\nMARKUP_LIBS = markup\nMARKUP_NAME = markup\n\nMKDIR_LIBS =\nMKDIR_NAME = mkdir\n\nMV_LIBS =\nMV_NAME = mv\n\nNOW_LIBS =\nNOW_NAME = now\n\nOPEN_LIBS =\nOPEN_NAME = open\n\nPANIC_LIBS =\nPANIC_NAME = panic\n\nRMDIR_LIBS =\nRMDIR_NAME = rmdir\n\nSYSFETCH_LIBS =\nSYSFETCH_NAME = sysfetch\n\nTAC_LIBS =\nTAC_NAME = tac\n\nTOUCH_LIBS =\nTOUCH_NAME = touch\n\nUNLINK_LIBS =\nUNLINK_NAME = unlink\n\nUPTIME_LIBS =\nUPTIME_NAME = uptime\n\nUNAME_LIBS =\nUNAME_NAME = uname\n\nTRUE_LIBS =\nTRUE_NAME = true\n\nFALSE_LIBS =\nFALSE_NAME = false\n\nYES_LIBS =\nYES_NAME = yes\n\nPWD_LIBS =\nPWD_NAME = pwd\n\nPIANO_LIBS = \nPIANO_NAME = piano\n\nDISPLAYCTL_LIBS =\nDISPLAYCTL_NAME = displayctl\n\nKEYBOARDCTL_LIBS =\nKEYBOARDCTL_NAME = keyboardctl\n\nNETCTL_LIBS =\nNETCTL_NAME = netctl\n\nPOWERCTL_LIBS =\nPOWERCTL_NAME = powerctl\n\nSETTINGSCTL_LIBS = settings\nSETTINGSCTL_NAME = settingsctl\n\nWALLPAPERCTL_LIBS = graphic\nWALLPAPERCTL_NAME = wallpaperctl\n\nZIP_LIBS = file\nZIP_NAME = zip\n\nUNZIP_LIBS = file\nUNZIP_NAME = unzip\n\ndefine UTIL_TEMPLATE =\n\n$(1)_BINARY = $(BUILD_DIRECTORY_UTILITIES)/$($(1)_NAME)\n$(1)_SOURCE = apps/utilities/$($(1)_NAME).cpp\n$(1)_OBJECT = $$(patsubst apps/utilities/%.cpp, $$(CONFIG_BUILD_DIRECTORY)/apps/utilities/%.o, $$($(1)_SOURCE))\n\nTARGETS += $$($(1)_BINARY)\nOBJECTS += $$($(1)_OBJECT)\n\n$$($(1)_BINARY): $$($(1)_OBJECT) $$(patsubst %, $$(BUILD_DIRECTORY_LIBS)/lib%.a, $$($(1)_LIBS) system) $(CRTS)\n\t$$(DIRECTORY_GUARD)\n\t@echo [$(1)] [LD] $($(1)_NAME)\n\t@$(CXX) $(LDFLAGS) -o $$@ $$($(1)_OBJECT) $$(patsubst %, -l%, $$($(1)_LIBS)) -lsystem\n\t@if $(CONFIG_STRIP); then \\\n\t\techo [$(1)] [STRIP] $($(1)_NAME); \\\n\t\t$(STRIP) $$@; \\\n\tfi\n\n$$($(1)_OBJECT): $$($(1)_SOURCE)\n\t$$(DIRECTORY_GUARD)\n\t@echo [$(1)] [CXX] $$<\n\t@$(CXX) $(CXXFLAGS) -c -o $$@ $$<\n\nendef\n\n$(foreach util, $(UTILITIES), $(eval $(call UTIL_TEMPLATE,$(util))))\n" }, { "alpha_fraction": 0.7440000176429749, "alphanum_fraction": 0.7440000176429749, "avg_line_length": 15.666666984558105, "blob_id": "ae86300c061145c6b7af565b592dfaff3ebd432a", "content_id": "03937c02370c1cd37955b537d0df0555e8a16ad4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 250, "license_type": "permissive", "max_line_length": 37, "num_lines": 15, "path": "/libraries/libutils/json/Json.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Scanner.h>\n#include <libutils/String.h>\n\n#include <libutils/json/Parser.h>\n#include <libutils/json/Prettifier.h>\n#include <libutils/json/Value.h>\n\nnamespace json\n{\n\nValue parse_file(String path);\n\n} // namespace json\n" }, { "alpha_fraction": 0.704081654548645, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 23.5, "blob_id": "717b07f21225fecc066ff7b7ed44a0a904284561", "content_id": "41d934e3736d2b424b34dd999410a824ac18bf41", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 196, "license_type": "permissive", "max_line_length": 32, "num_lines": 8, "path": "/libraries/abi/Process.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define PROCESS_NAME_SIZE 128\n#define PROCESS_STACK_SIZE 65536\n#define PROCESS_ARG_COUNT 128\n#define PROCESS_HANDLE_COUNT 128\n#define PROCESS_SUCCESS (0)\n#define PROCESS_FAILURE (1)\n" }, { "alpha_fraction": 0.6336939930915833, "alphanum_fraction": 0.6336939930915833, "avg_line_length": 16.486486434936523, "blob_id": "d9f370045030014e214db0cacc26d7f0917818f2", "content_id": "e7c798f02a025ad8c1c37e5529907811306be448", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 647, "license_type": "permissive", "max_line_length": 55, "num_lines": 37, "path": "/libraries/libsystem/io/File.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Path.h>\n#include <libutils/ResultOr.h>\n#include <libutils/Slice.h>\n#include <libutils/String.h>\n\n#include <libsystem/Common.h>\n#include <libsystem/Result.h>\n\nclass File\n{\nprivate:\n Path _path;\n\npublic:\n const Path &path()\n {\n return _path;\n }\n\n File(const char *path) : File(Path::parse(path)) {}\n\n File(String path) : File(Path::parse(path)) {}\n\n File(Path path) : _path(path) {}\n\n Result read_all(void **buffer, size_t *size);\n\n ResultOr<Slice> read_all();\n\n Result write_all(const void *buffer, size_t size);\n\n bool exist();\n\n Result copy(const char *destination);\n};\n" }, { "alpha_fraction": 0.5861344337463379, "alphanum_fraction": 0.5861344337463379, "avg_line_length": 14.354838371276855, "blob_id": "f05a16ed4d1265f572dbaae8a8a7eb6d68125111", "content_id": "936aa47792606f5bc9c735c6543038b205c25c91", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 476, "license_type": "permissive", "max_line_length": 57, "num_lines": 31, "path": "/libraries/libsystem/eventloop/Timer.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/eventloop/EventLoop.h>\n#include <libsystem/eventloop/Timer.h>\n\nTimer::Timer(Timeout interval, Callback<void()> callback)\n : _interval(interval),\n _callback(callback)\n{\n}\n\nTimer::~Timer()\n{\n stop();\n}\n\nvoid Timer::start()\n{\n if (!_running)\n {\n _running = true;\n EventLoop::register_timer(this);\n }\n}\n\nvoid Timer::stop()\n{\n if (_running)\n {\n _running = false;\n EventLoop::unregister_timer(this);\n }\n}\n" }, { "alpha_fraction": 0.5657666325569153, "alphanum_fraction": 0.5853465795516968, "avg_line_length": 28.59345817565918, "blob_id": "b16b5cae8171157c126a4459b24bc56b594212a1", "content_id": "f1f7a83c57d5cf96a7039b4ffe52a13cb796b1cd", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6333, "license_type": "permissive", "max_line_length": 94, "num_lines": 214, "path": "/apps/paint/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n\n#include <libwidget/Application.h>\n#include <libwidget/Button.h>\n#include <libwidget/Container.h>\n#include <libwidget/Panel.h>\n#include <libwidget/Separator.h>\n#include <libwidget/TitleBar.h>\n\n#include \"paint/PaintCanvas.h\"\n#include \"paint/PaintDocument.h\"\n#include \"paint/PaintTool.h\"\n\nstatic Color _color_palette[] = {\n Color::from_hex(0x000000),\n Color::from_hex(0x1a1c2c),\n Color::from_hex(0x5d275d),\n Color::from_hex(0xb13e53),\n Color::from_hex(0xef7d57),\n Color::from_hex(0xffcd75),\n Color::from_hex(0xa7f070),\n Color::from_hex(0x38b764),\n Color::from_hex(0x257179),\n Color::from_hex(0x29366f),\n Color::from_hex(0x3b5dc9),\n Color::from_hex(0x41a6f6),\n Color::from_hex(0x73eff7),\n Color::from_hex(0xffffff),\n Color::from_hex(0xf4f4f4),\n Color::from_hex(0x94b0c2),\n Color::from_hex(0x566c86),\n Color::from_hex(0x333c57),\n};\n\nstruct PaintWindow : public Window\n{\nprivate:\n RefPtr<PaintDocument> _document;\n\n /// --- Toolbar --- ///\n Widget *_open_document;\n Widget *_save_document;\n Widget *_new_document;\n\n Widget *_pencil;\n Widget *_brush;\n Widget *_eraser;\n Widget *_fill;\n Widget *_picker;\n\n Widget *_insert_text;\n Widget *_insert_line;\n Widget *_insert_rectangle;\n Widget *_insert_circle;\n\n Panel *_primary_color;\n Panel *_secondary_color;\n\n /// --- Canvas --- ///\n PaintCanvas *_canvas;\n\npublic:\n PaintWindow(RefPtr<PaintDocument> document) : Window(WINDOW_RESIZABLE)\n {\n icon(Icon::get(\"brush\"));\n title(\"Paint\");\n size(Vec2i(600, 560));\n\n _document = document;\n\n root()->layout(VFLOW(0));\n\n new TitleBar(root());\n\n create_toolbar(root());\n\n _canvas = new PaintCanvas(root(), document);\n _canvas->flags(Widget::FILL);\n\n create_color_palette(root());\n\n document->on_color_change = [this]() {\n update_toolbar();\n };\n }\n\n void create_toolbar(Widget *parent)\n {\n auto toolbar = new Panel(parent);\n\n toolbar->layout(HFLOW(4));\n toolbar->insets(Insetsi(4, 4));\n toolbar->max_height(38);\n toolbar->min_height(38);\n\n _open_document = new Button(toolbar, Button::TEXT, Icon::get(\"folder-open\"));\n _save_document = new Button(toolbar, Button::TEXT, Icon::get(\"content-save\"));\n _new_document = new Button(toolbar, Button::TEXT, Icon::get(\"image-plus\"));\n\n new Separator(toolbar);\n\n _pencil = new Button(toolbar, Button::TEXT, Icon::get(\"pencil\"));\n _pencil->on(Event::ACTION, [this](auto) {\n _canvas->tool(own<PencilTool>());\n update_toolbar();\n });\n\n _brush = new Button(toolbar, Button::TEXT, Icon::get(\"brush\"));\n _brush->on(Event::ACTION, [this](auto) {\n _canvas->tool(own<BrushTool>());\n update_toolbar();\n });\n\n _eraser = new Button(toolbar, Button::TEXT, Icon::get(\"eraser\"));\n _eraser->on(Event::ACTION, [this](auto) {\n _canvas->tool(own<EraserTool>());\n update_toolbar();\n });\n\n _fill = new Button(toolbar, Button::TEXT, Icon::get(\"format-color-fill\"));\n _fill->on(Event::ACTION, [this](auto) {\n _canvas->tool(own<FillTool>());\n update_toolbar();\n });\n\n _picker = new Button(toolbar, Button::TEXT, Icon::get(\"eyedropper\"));\n _picker->on(Event::ACTION, [this](auto) {\n _canvas->tool(own<PickerTool>());\n update_toolbar();\n });\n\n new Separator(toolbar);\n\n // TODO:\n _insert_text = new Button(toolbar, Button::TEXT, Icon::get(\"format-text-variant\"));\n _insert_line = new Button(toolbar, Button::TEXT, Icon::get(\"vector-line\"));\n _insert_rectangle = new Button(toolbar, Button::TEXT, Icon::get(\"rectangle-outline\"));\n _insert_circle = new Button(toolbar, Button::TEXT, Icon::get(\"circle-outline\"));\n\n new Separator(toolbar);\n\n Widget *primary_color_container = new Container(toolbar);\n primary_color_container->insets(Insetsi(4));\n primary_color_container->flags(Widget::SQUARE);\n\n _primary_color = new Panel(primary_color_container);\n _primary_color->border_radius(4);\n _primary_color->color(THEME_MIDDLEGROUND, _document->primary_color());\n\n Widget *secondary_color_container = new Container(toolbar);\n secondary_color_container->insets(Insetsi(4));\n secondary_color_container->flags(Widget::SQUARE);\n\n _secondary_color = new Panel(secondary_color_container);\n _secondary_color->border_radius(4);\n _secondary_color->color(THEME_MIDDLEGROUND, _document->secondary_color());\n }\n\n void create_color_palette(Widget *parent)\n {\n auto palette = new Panel(parent);\n\n palette->layout(HFLOW(4));\n palette->insets(Insetsi(4, 4));\n palette->max_height(38);\n palette->min_height(38);\n\n palette->layout(HFLOW(4));\n\n for (size_t i = 0; i < __array_length(_color_palette); i++)\n {\n Color color = _color_palette[i];\n\n auto color_widget = new Panel(palette);\n color_widget->border_radius(4);\n color_widget->min_width(30);\n color_widget->color(THEME_MIDDLEGROUND, color);\n\n color_widget->on(Event::MOUSE_BUTTON_PRESS, [this, color](auto event) {\n if (event->mouse.button == MOUSE_BUTTON_LEFT)\n {\n _document->primary_color(color);\n }\n else if (event->mouse.button == MOUSE_BUTTON_RIGHT)\n {\n _document->secondary_color(color);\n }\n\n update_toolbar();\n });\n }\n }\n\n void update_toolbar()\n {\n _primary_color->color(THEME_MIDDLEGROUND, _document->primary_color());\n _secondary_color->color(THEME_MIDDLEGROUND, _document->secondary_color());\n }\n};\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n auto bitmap = Bitmap::create_shared(400, 400).take_value();\n bitmap->clear(Colors::BLACKTRANSPARENT);\n\n auto document = make<PaintDocument>(bitmap);\n\n auto window = new PaintWindow(document);\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.7085427045822144, "alphanum_fraction": 0.7085427045822144, "avg_line_length": 12.266666412353516, "blob_id": "60343b60428a760a30534496725d34379bdb0aa3", "content_id": "44a2d4c4a763491bbd75c3ece7902be141c0db1c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 199, "license_type": "permissive", "max_line_length": 57, "num_lines": 15, "path": "/apps/settings/widgets/Link.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Button.h>\n\nnamespace Settings\n{\n\nclass Link : public Button\n{\nprivate:\npublic:\n Link(Widget *parent, RefPtr<Icon> icon, String name);\n};\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.6327731013298035, "alphanum_fraction": 0.6453781723976135, "avg_line_length": 24.869565963745117, "blob_id": "8f6a48d8b2145d1cf88a175ba740b821c190bdc0", "content_id": "cfbded85b754546122edb3f8c2a3cc11479e2de9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1190, "license_type": "permissive", "max_line_length": 106, "num_lines": 46, "path": "/apps/image-viewer/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsettings/Settings.h>\n\n#include <libsystem/process/Process.h>\n\n#include <libwidget/Application.h>\n#include <libwidget/Button.h>\n#include <libwidget/Image.h>\n#include <libwidget/Panel.h>\n#include <libwidget/TitleBar.h>\n\nint main(int argc, char **argv)\n{\n if (argc == 1)\n return -1;\n\n if (Application::initialize(argc, argv) != SUCCESS)\n return -1;\n\n Window *window = new Window(WINDOW_RESIZABLE);\n\n window->icon(Icon::get(\"image\"));\n window->title(\"Image Viewer\");\n window->size(Vec2i(700, 500));\n window->root()->layout(VFLOW(0));\n\n new TitleBar(window->root());\n\n auto toolbar = new Panel(window->root());\n toolbar->layout(HFLOW(0));\n toolbar->insets(4);\n\n auto bitmap = Bitmap::load_from_or_placeholder(argv[1]);\n\n auto set_has_wallaper = new Button(toolbar, Button::TEXT, Icon::get(\"wallpaper\"), \"Set As Wallpaper\");\n\n set_has_wallaper->on(Event::ACTION, [&](auto) {\n Settings::write(Settings::Path::parse(\"appearance:wallpaper.image\"), process_resolve(argv[1]));\n });\n\n auto image = new Image(window->root(), bitmap);\n image->flags(Widget::FILL);\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.6764705777168274, "alphanum_fraction": 0.6764705777168274, "avg_line_length": 10.333333015441895, "blob_id": "6ee916e5b39c4df745284e632c80a5466968ce2c", "content_id": "0bacf2b92d10523e8c7981b73873df68ee428a8a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 34, "license_type": "permissive", "max_line_length": 18, "num_lines": 3, "path": "/libraries/libmedia/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += MEDIA\n\nMEDIA_NAME = media\n" }, { "alpha_fraction": 0.5712230205535889, "alphanum_fraction": 0.5769784450531006, "avg_line_length": 18.577465057373047, "blob_id": "ba1d59581a8710b14f5572af493bf7eb48f68f01", "content_id": "fde1b1a858130e74c8013c34cb590b28b9809d2d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1390, "license_type": "permissive", "max_line_length": 59, "num_lines": 71, "path": "/kernel/node/Node.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Logger.h>\n#include <string.h>\n\n#include \"kernel/node/Handle.h\"\n#include \"kernel/node/Node.h\"\n\nFsNode::FsNode(FileType type)\n{\n _type = type;\n}\n\nvoid FsNode::ref_handle(FsHandle &handle)\n{\n if (handle.flags() & OPEN_READ)\n {\n __atomic_add_fetch(&_readers, 1, __ATOMIC_SEQ_CST);\n }\n\n if (handle.flags() & OPEN_WRITE)\n {\n __atomic_add_fetch(&_writers, 1, __ATOMIC_SEQ_CST);\n }\n\n if (handle.flags() & OPEN_CLIENT)\n {\n __atomic_add_fetch(&_clients, 1, __ATOMIC_SEQ_CST);\n }\n\n if (handle.flags() & OPEN_SERVER)\n {\n __atomic_add_fetch(&_server, 1, __ATOMIC_SEQ_CST);\n }\n}\n\nvoid FsNode::deref_handle(FsHandle &handle)\n{\n if (handle.flags() & OPEN_READ)\n {\n __atomic_sub_fetch(&_readers, 1, __ATOMIC_SEQ_CST);\n }\n\n if (handle.flags() & OPEN_WRITE)\n {\n __atomic_sub_fetch(&_writers, 1, __ATOMIC_SEQ_CST);\n }\n\n if (handle.flags() & OPEN_CLIENT)\n {\n __atomic_sub_fetch(&_clients, 1, __ATOMIC_SEQ_CST);\n }\n\n if (handle.flags() & OPEN_SERVER)\n {\n __atomic_sub_fetch(&_server, 1, __ATOMIC_SEQ_CST);\n }\n}\n\nbool FsNode::is_acquire()\n{\n return _lock.locked();\n}\n\nvoid FsNode::acquire(int who_acquire)\n{\n _lock.acquire_for(who_acquire, SOURCE_LOCATION);\n}\n\nvoid FsNode::release(int who_release)\n{\n _lock.release_for(who_release, SOURCE_LOCATION);\n}\n" }, { "alpha_fraction": 0.6732673048973083, "alphanum_fraction": 0.6732673048973083, "avg_line_length": 10.222222328186035, "blob_id": "219f1018858563ed369bb54fa2a9098d7921a7d8", "content_id": "41175f9765c2149e9d108f8f18e402a0dc82bd7a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 101, "license_type": "permissive", "max_line_length": 21, "num_lines": 9, "path": "/kernel/graphics/PixelFormat.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nenum PixelFormat\n{\n PIXELFORMAT_NONE,\n\n PIXELFORMAT_CGA,\n PIXELFORMAT_RGB,\n};\n" }, { "alpha_fraction": 0.8571428656578064, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 28, "blob_id": "64e9e7db8f86654173201745482a30be1604f661", "content_id": "4592a5f502959d80f4fc5a1e044effda286dce2f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "permissive", "max_line_length": 28, "num_lines": 1, "path": "/manual/40-human-interface/guidelines.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# Human Interface Guidelines" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 27, "blob_id": "73ecae4f65dae0a0a126aaff104ecfc74e4b6143", "content_id": "4f36a6e66eaa77c596103be7be93a70589f33b63", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 28, "license_type": "permissive", "max_line_length": 27, "num_lines": 1, "path": "/libraries/libc/skift/Syscall.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Syscalls.cpp>\n" }, { "alpha_fraction": 0.6969696879386902, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 17.045454025268555, "blob_id": "655bf69950435649a1dbeb8853feedfa85d723fc", "content_id": "a38672b93682c211661e3b27a9c085e1dc62ba24", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 396, "license_type": "permissive", "max_line_length": 52, "num_lines": 22, "path": "/libraries/libsystem/io/BinaryReader.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/BinaryReader.h>\n\n// Inherited from SeekableReader\nsize_t BinaryReader::length()\n{\n return _reader.length();\n}\n\nsize_t BinaryReader::position()\n{\n return _reader.position();\n}\n\nsize_t BinaryReader::seek(size_t pos, Whence whence)\n{\n return _reader.seek(pos, whence);\n}\n\nsize_t BinaryReader::read(void *buffer, size_t size)\n{\n return _reader.read(buffer, size);\n}" }, { "alpha_fraction": 0.5257998108863831, "alphanum_fraction": 0.5443756580352783, "avg_line_length": 18.18811798095703, "blob_id": "2413aa9f5e3f96a5beb724b289855e4492f836df", "content_id": "f317217ade868342352f16579478265a1430f635", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1938, "license_type": "permissive", "max_line_length": 88, "num_lines": 101, "path": "/libraries/libc/skift/NumberFormatter.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#ifndef __KERNEL__\n# include <math.h>\n#endif\n#include <skift/NumberFormatter.h>\n#include <string.h>\n\nstatic const char *digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\nstatic const char *digits_capitalized = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nsize_t format_uint(NumberFormater formater, unsigned long value, char *str, size_t size)\n{\n if (size == 0)\n {\n return 0;\n }\n\n size_t written = 0;\n\n str[0] = '\\0';\n if (value == 0)\n {\n strnapd(str, '0', size);\n written++;\n }\n\n while (value != 0)\n {\n if (formater.capitalized)\n {\n strnapd(str, digits[value % formater.base], size);\n }\n else\n {\n strnapd(str, digits_capitalized[value % formater.base], size);\n }\n\n value /= formater.base;\n written++;\n }\n\n if (formater.padded_with_zero)\n {\n while (written < size)\n {\n strnapd(str, '0', size);\n written++;\n }\n }\n\n strrvs(str);\n\n return written;\n}\n\nsize_t format_int(NumberFormater formater, long value, char *str, size_t size)\n{\n if (size == 0)\n {\n return 0;\n }\n\n size_t written = 0;\n str[0] = '\\0';\n\n if (value < 0)\n {\n strnapd(str, '-', size);\n str++;\n size--;\n value = -value;\n written++;\n }\n\n written += format_uint(formater, value, str, size);\n return written;\n}\n\n#ifndef __KERNEL__\n\nsize_t format_double(NumberFormater formater, double value, char *str, size_t size)\n{\n int ipart = (int)value;\n\n float fpart = value - (float)ipart;\n\n size_t written = format_int(formater, ipart, str, size);\n\n if (formater.after_point != 0)\n {\n strnapd(str, '.', size);\n written++;\n\n fpart = fpart * pow(formater.base, formater.after_point);\n\n format_int(formater, (int)fpart, str + written, size - written);\n }\n\n return written;\n}\n\n#endif\n" }, { "alpha_fraction": 0.7075555324554443, "alphanum_fraction": 0.7155555486679077, "avg_line_length": 19.83333396911621, "blob_id": "885c38370ae22a50c1aa1414e6c30bf4c8fad23c", "content_id": "1cd47a2a761358141d2dccc5d1aa327cbc23b993", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1125, "license_type": "permissive", "max_line_length": 75, "num_lines": 54, "path": "/kernel/graphics/Graphics.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Logger.h>\n\n#include \"kernel/graphics/Graphics.h\"\n#include \"kernel/interrupts/Interupts.h\"\n\nstatic uintptr_t _framebuffer_address = 0;\nstatic int _framebuffer_width = 0;\nstatic int _framebuffer_height = 0;\n\nvoid graphic_early_initialize(Handover *handover)\n{\n _framebuffer_address = handover->framebuffer_addr;\n _framebuffer_width = handover->framebuffer_width;\n _framebuffer_height = handover->framebuffer_height;\n}\n\nvoid graphic_initialize(Handover *handover)\n{\n if (_framebuffer_address != 0)\n {\n return;\n }\n\n framebuffer_initialize(handover);\n}\n\nvoid graphic_did_find_framebuffer(uintptr_t address, int width, int height)\n{\n InterruptsRetainer retainer;\n\n _framebuffer_address = address;\n _framebuffer_width = width;\n _framebuffer_height = height;\n}\n\nbool graphic_has_framebuffer()\n{\n return _framebuffer_address != 0;\n}\n\nuint32_t *graphic_framebuffer()\n{\n return reinterpret_cast<uint32_t *>(_framebuffer_address);\n}\n\nint graphic_framebuffer_width()\n{\n return _framebuffer_width;\n}\n\nint graphic_framebuffer_height()\n{\n return _framebuffer_height;\n}\n" }, { "alpha_fraction": 0.7560975551605225, "alphanum_fraction": 0.7560975551605225, "avg_line_length": 12.666666984558105, "blob_id": "ab8a74b43bafae753fdd6040c1aa8e2f38cc7676", "content_id": "02e882dfd5f15eab053366d532e84f2cfbb1e7dc", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 41, "license_type": "permissive", "max_line_length": 26, "num_lines": 3, "path": "/kernel/tasking/Tasking.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nvoid tasking_initialize();\n" }, { "alpha_fraction": 0.6576576828956604, "alphanum_fraction": 0.6576576828956604, "avg_line_length": 22.16666603088379, "blob_id": "d5c9a2c977b25dedb511b48d007c885e0ed8a306", "content_id": "20892b174144d61e6160b3bd6ef7dc0a7e35d2fe", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 555, "license_type": "permissive", "max_line_length": 73, "num_lines": 24, "path": "/libraries/libsystem/io/ScopedReader.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/ScopedReader.h>\n\nScopedReader::ScopedReader(Reader &reader, size_t size) : _reader(reader)\n{\n assert((reader.length() - reader.position()) > size);\n _start_pos = reader.position();\n _size = MIN(reader.length() - _start_pos, size);\n}\n\nsize_t ScopedReader::length()\n{\n return _size;\n}\n\nsize_t ScopedReader::position()\n{\n return _reader.position() - _start_pos;\n}\n\nsize_t ScopedReader::read(void *buffer, size_t size)\n{\n size_t rem_size = MIN(length() - position(), size);\n return _reader.read(buffer, rem_size);\n}" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 13.772727012634277, "blob_id": "fac489d6a57b01fea663a1021000ff85a7ba408e", "content_id": "a89bf64abef746d252a211020473ce44b854b791", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 325, "license_type": "permissive", "max_line_length": 32, "num_lines": 22, "path": "/libraries/libsystem/io/Stream_internal.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Handle.h>\n\nstruct Stream\n{\n Handle handle;\n\n StreamBufferMode read_mode;\n void *write_buffer;\n size_t write_used;\n\n StreamBufferMode write_mode;\n void *read_buffer;\n size_t read_used;\n size_t read_head;\n\n bool has_unget;\n int unget_char;\n\n bool is_end_of_file;\n};\n" }, { "alpha_fraction": 0.6223588585853577, "alphanum_fraction": 0.631346583366394, "avg_line_length": 25.311203002929688, "blob_id": "59de8103ccdfeca9ec6b223fc0e5f1f43594570d", "content_id": "75d80a79d87bd714212e090f5697e2f609798691", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6342, "license_type": "permissive", "max_line_length": 118, "num_lines": 241, "path": "/kernel/memory/Memory.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <assert.h>\n#include <libsystem/Logger.h>\n#include <libsystem/io/Stream.h>\n#include <string.h>\n\n#include \"archs/VirtualMemory.h\"\n\n#include \"kernel/graphics/Graphics.h\"\n#include \"kernel/interrupts/Interupts.h\"\n#include \"kernel/memory/Memory.h\"\n#include \"kernel/memory/MemoryObject.h\"\n#include \"kernel/memory/Physical.h\"\n\nstatic bool _memory_initialized = false;\n\nextern int __start;\nextern int __end;\n\nstatic MemoryRange kernel_memory_range()\n{\n return MemoryRange::around_non_aligned_address((uintptr_t)&__start, (size_t)&__end - (size_t)&__start);\n}\n\nvoid memory_initialize(Handover *handover)\n{\n logger_info(\"Initializing memory management...\");\n\n for (size_t i = 0; i < 1024 * 1024 / 8; i++)\n {\n MEMORY[i] = 0xff;\n }\n\n for (size_t i = 0; i < handover->memory_map_size; i++)\n {\n MemoryMapEntry *entry = &handover->memory_map[i];\n\n if (entry->type == MEMORY_MAP_ENTRY_AVAILABLE)\n {\n physical_set_free(entry->range);\n }\n }\n\n arch_virtual_initialize();\n\n USED_MEMORY = 0;\n TOTAL_MEMORY = handover->memory_usable;\n\n logger_info(\"Mapping kernel...\");\n memory_map_identity(arch_kernel_address_space(), kernel_memory_range(), MEMORY_NONE);\n\n logger_info(\"Mapping modules...\");\n for (size_t i = 0; i < handover->modules_size; i++)\n {\n memory_map_identity(arch_kernel_address_space(), handover->modules[i].range, MEMORY_NONE);\n }\n\n // Unmap the 0 page\n MemoryRange page_zero{0, ARCH_PAGE_SIZE};\n arch_virtual_free(arch_kernel_address_space(), page_zero);\n physical_set_used(page_zero);\n\n arch_address_space_switch(arch_kernel_address_space());\n graphic_did_find_framebuffer(0, 0, 0);\n\n arch_virtual_memory_enable();\n\n logger_info(\"%uKio of memory detected\", TOTAL_MEMORY / 1024);\n logger_info(\"%uKio of memory is used by the kernel\", USED_MEMORY / 1024);\n\n logger_info(\"Paging enabled!\");\n\n _memory_initialized = true;\n\n memory_object_initialize();\n}\n\nvoid memory_dump()\n{\n stream_format(out_stream, \"\\n\\tMemory status:\");\n stream_format(out_stream, \"\\n\\t - Used physical Memory: %12dkib\", USED_MEMORY / 1024);\n stream_format(out_stream, \"\\n\\t - Total physical Memory: %12dkib\", TOTAL_MEMORY / 1024);\n}\n\nsize_t memory_get_used()\n{\n InterruptsRetainer retainer;\n\n return USED_MEMORY;\n}\n\nsize_t memory_get_total()\n{\n InterruptsRetainer retainer;\n\n return TOTAL_MEMORY;\n}\n\nResult memory_map(void *address_space, MemoryRange virtual_range, MemoryFlags flags)\n{\n assert(virtual_range.is_page_aligned());\n\n InterruptsRetainer retainer;\n\n for (size_t i = 0; i < virtual_range.size() / ARCH_PAGE_SIZE; i++)\n {\n uintptr_t virtual_address = virtual_range.base() + i * ARCH_PAGE_SIZE;\n\n if (!arch_virtual_present(address_space, virtual_address))\n {\n auto physical_range = physical_alloc(ARCH_PAGE_SIZE);\n Result virtual_map_result = arch_virtual_map(address_space, physical_range, virtual_address, flags);\n\n if (virtual_map_result != SUCCESS)\n {\n return virtual_map_result;\n }\n }\n }\n\n if (flags & MEMORY_CLEAR)\n {\n memset((void *)virtual_range.base(), 0, virtual_range.size());\n }\n\n return SUCCESS;\n}\n\nResult memory_map_identity(void *address_space, MemoryRange physical_range, MemoryFlags flags)\n{\n assert(physical_range.is_page_aligned());\n\n InterruptsRetainer retainer;\n\n physical_set_used(physical_range);\n assert(SUCCESS == arch_virtual_map(address_space, physical_range, physical_range.base(), flags));\n\n if (flags & MEMORY_CLEAR)\n {\n memset((void *)physical_range.base(), 0, physical_range.size());\n }\n\n return SUCCESS;\n}\n\nResult memory_alloc(void *address_space, size_t size, MemoryFlags flags, uintptr_t *out_address)\n\n{\n assert(IS_PAGE_ALIGN(size));\n\n InterruptsRetainer retainer;\n\n if (!size)\n {\n *out_address = 0;\n logger_warn(\"Allocation with size=0!\");\n return SUCCESS;\n }\n\n *out_address = 0;\n\n auto physical_range = physical_alloc(size);\n\n if (physical_range.empty())\n {\n logger_error(\"Failed to allocate memory: Not enough physical memory!\");\n return ERR_OUT_OF_MEMORY;\n }\n\n uintptr_t virtual_address = arch_virtual_alloc(address_space, physical_range, flags).base();\n\n if (!virtual_address)\n {\n physical_free(physical_range);\n\n logger_error(\"Failed to allocate memory: Not enough virtual memory!\");\n return ERR_OUT_OF_MEMORY;\n }\n\n if (flags & MEMORY_CLEAR)\n {\n memset((void *)virtual_address, 0, size);\n }\n\n *out_address = virtual_address;\n return SUCCESS;\n}\n\nResult memory_alloc_identity(void *address_space, MemoryFlags flags, uintptr_t *out_address)\n{\n InterruptsRetainer retainer;\n\n for (size_t i = 1; i < 256 * 1024; i++)\n {\n MemoryRange identity_range{i * ARCH_PAGE_SIZE, ARCH_PAGE_SIZE};\n\n if (!arch_virtual_present(address_space, identity_range.base()) &&\n !physical_is_used(identity_range))\n {\n physical_set_used(identity_range);\n assert(SUCCESS == arch_virtual_map(address_space, identity_range, identity_range.base(), flags));\n\n if (flags & MEMORY_CLEAR)\n {\n memset((void *)identity_range.base(), 0, ARCH_PAGE_SIZE);\n }\n\n *out_address = identity_range.base();\n\n return SUCCESS;\n }\n }\n\n logger_warn(\"Failed to allocate identity mapped page!\");\n\n *out_address = 0;\n\n return ERR_OUT_OF_MEMORY;\n}\n\nResult memory_free(void *address_space, MemoryRange virtual_range)\n{\n assert(virtual_range.is_page_aligned());\n\n InterruptsRetainer retainer;\n\n for (size_t i = 0; i < virtual_range.size() / ARCH_PAGE_SIZE; i++)\n {\n uintptr_t virtual_address = virtual_range.base() + i * ARCH_PAGE_SIZE;\n\n if (arch_virtual_present(address_space, virtual_address))\n {\n MemoryRange page_physical_range{arch_virtual_to_physical(address_space, virtual_address), ARCH_PAGE_SIZE};\n MemoryRange page_virtual_range{virtual_address, ARCH_PAGE_SIZE};\n\n physical_free(page_physical_range);\n arch_virtual_free(address_space, page_virtual_range);\n }\n }\n\n return SUCCESS;\n}\n" }, { "alpha_fraction": 0.3512990176677704, "alphanum_fraction": 0.35146039724349976, "avg_line_length": 42.950355529785156, "blob_id": "3cfeff594a7ef0d1836fc02afdd755e71b9e4f8b", "content_id": "37262c22cc034fcb0c9249ecbf5a42e0ce0703b7", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6197, "license_type": "permissive", "max_line_length": 95, "num_lines": 141, "path": "/libraries/libsystem/cmdline/CMDLine.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nstruct CommandLine;\nstruct CommandLineOption;\n\ntypedef void CommandLineCallback(struct CommandLine *cmdline, struct CommandLineOption *opt);\n\nenum CommandLineOptionType\n{\n COMMANDLINE_BOOLEAN,\n COMMANDLINE_STRING,\n COMMANDLINE_INTEGER,\n COMMANDLINE_ACTION,\n COMMANDLINE_SECTION,\n COMMANDLINE_SEPARATOR,\n COMMANDLINE_END\n};\n\nstruct CommandLineOption\n{\n CommandLineOptionType type;\n\n void *value;\n const char short_name;\n const char *long_name;\n const char *description;\n\n CommandLineCallback *callback;\n};\n\nstruct CommandLine\n{\n const char *name;\n const char *const *usages;\n const char *prologue;\n CommandLineOption *options;\n const char *epiloge;\n};\n\n#define COMMANDLINE_NEWLINE \"\\n\\t\"\n\n#define COMMANDLINE_NO_LONG_NAME nullptr\n#define COMMANDLINE_NO_SHORT_NAME '\\0'\n#define COMMANDLINE_NO_CALLBACK nullptr\n#define COMMANDLINE_NO_VALUE nullptr\n\n#define COMMANDLINE_OPT_SECTION(__name) \\\n { \\\n .type = COMMANDLINE_SECTION, \\\n .value = COMMANDLINE_NO_VALUE, \\\n .short_name = COMMANDLINE_NO_SHORT_NAME, \\\n .long_name = __name, \\\n .description = nullptr, \\\n .callback = COMMANDLINE_NO_CALLBACK, \\\n }\n\n#define COMMANDLINE_OPT_SEPARATOR \\\n { \\\n .type = COMMANDLINE_SEPARATOR, \\\n .value = COMMANDLINE_NO_VALUE, \\\n .short_name = COMMANDLINE_NO_SHORT_NAME, \\\n .long_name = nullptr, \\\n .description = nullptr, \\\n .callback = COMMANDLINE_NO_CALLBACK, \\\n }\n\n#define COMMANDLINE_OPT_BOOL(__long_name, __short_name, __value, __description, __callback) \\\n { \\\n .type = COMMANDLINE_BOOLEAN, \\\n .value = &(__value), \\\n .short_name = __short_name, \\\n .long_name = __long_name, \\\n .description = __description, \\\n .callback = __callback, \\\n }\n\n#define COMMANDLINE_OPT_STRING(__long_name, __short_name, __value, __description, __callback) \\\n { \\\n .type = COMMANDLINE_STRING, \\\n .value = &(__value), \\\n .short_name = __short_name, \\\n .long_name = __long_name, \\\n .description = __description, \\\n .callback = __callback, \\\n }\n\n#define COMMANDLINE_OPT_INT(__long_name, __short_name, __value, __description, __callback) \\\n { \\\n .type = COMMANDLINE_INTEGER, \\\n .value = &(__value), \\\n .short_name = __short_name, \\\n .long_name = __long_name, \\\n .description = __description, \\\n .callback = __callback, \\\n }\n\n#define COMMANDLINE_OPT_ACTION(__long_name, __short_name, __description, __callback) \\\n { \\\n .type = COMMANDLINE_ACTION, \\\n .value = COMMANDLINE_NO_VALUE, \\\n .short_name = __short_name, \\\n .long_name = __long_name, \\\n .description = __description, \\\n .callback = __callback, \\\n }\n\n#define COMMANDLINE_OPT_HELP \\\n { \\\n .type = COMMANDLINE_BOOLEAN, \\\n .value = nullptr, \\\n .short_name = 'h', \\\n .long_name = \"help\", \\\n .description = \"Show this help message and exit.\", \\\n .callback = cmdline_callback_help, \\\n }\n\n#define COMMANDLINE_OPT_END \\\n { \\\n .type = COMMANDLINE_END, \\\n \\\n .value = nullptr, \\\n .short_name = 'x', \\\n .long_name = \"\", \\\n .description = \"\", \\\n \\\n .callback = nullptr, \\\n }\n\n#define CMDLINE(__usages, __options, __prologue, __epiloge) \\\n { \\\n .name = \"<null>\", \\\n .usages = __usages, \\\n .prologue = __prologue, \\\n .options = __options, \\\n .epiloge = __epiloge \\\n }\n\nvoid cmdline_callback_help(CommandLine *cmdline, CommandLineOption *option);\nint cmdline_parse(CommandLine *cmdline, int argc, char **argv);\n" }, { "alpha_fraction": 0.715976357460022, "alphanum_fraction": 0.715976357460022, "avg_line_length": 13.083333015441895, "blob_id": "08e9775e0c62baab8060021b36b182961ad3edc9", "content_id": "ff9ddbb5802b25760d6cf332bd185cca1b79445c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 169, "license_type": "permissive", "max_line_length": 49, "num_lines": 12, "path": "/libraries/libutils/Iteration.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Callback.h>\n\nenum class Iteration\n{\n CONTINUE,\n STOP,\n};\n\ntemplate <typename T>\nusing IterationCallback = Callback<Iteration(T)>;\n" }, { "alpha_fraction": 0.6385542154312134, "alphanum_fraction": 0.6746987700462341, "avg_line_length": 15.600000381469727, "blob_id": "5a233a4db98d357a0cfe7a06b0ed5111c55c8fe3", "content_id": "060f40000b6e233ede0a0387b207338a0e37f59d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 83, "license_type": "permissive", "max_line_length": 54, "num_lines": 5, "path": "/contribs/zlib/build-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\ncd sources\nCROSS_PREFIX=i686-pc-skift- ./configure && make libz.a\ncd ..\n" }, { "alpha_fraction": 0.5460729598999023, "alphanum_fraction": 0.5615336894989014, "avg_line_length": 22.420289993286133, "blob_id": "f4d1919af55758fc65c0d587d89535121fde5456", "content_id": "b389b38c3a6d9298e684443bc98ec1ac20f89ef4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1617, "license_type": "permissive", "max_line_length": 104, "num_lines": 69, "path": "/libraries/libsystem/Logger.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/Logger.h>\n#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Stream.h>\n\nstatic bool logger_log_level = LOGGER_TRACE;\n\nstatic bool logger_is_quiet = false;\n\nstatic const char *logger_level_colors[] = {\"\\e[34m\", \"\\e[36m\", \"\\e[32m\", \"\\e[33m\", \"\\e[31m\", \"\\e[35m\"};\n\nvoid logger_level(LogLevel log_level)\n{\n logger_log_level = log_level;\n}\n\nvoid logger_quiet(bool quiet)\n{\n logger_is_quiet = quiet;\n}\n\nvoid logger_log(LogLevel level, const char *file, int line, const char *fmt, ...)\n{\n if (level >= logger_log_level)\n {\n __plug_logger_lock();\n\n#ifndef __KERNEL__\n stream_format(log_stream, \"\\e[1m\");\n#endif\n\n int process_id = __plug_process_this();\n\n if (process_id >= 0)\n {\n stream_format(log_stream, \"%3d: \", process_id);\n }\n else\n {\n stream_format(log_stream, \" \", process_id);\n }\n\n stream_format(log_stream, \"%s: \", __plug_process_name());\n\n#ifndef __KERNEL__\n stream_format(log_stream, \"\\e[m\");\n#endif\n\n DateTime datetime = datetime_now();\n stream_format(log_stream, \"%02d:%02d:%02d \", datetime.hour, datetime.minute, datetime.second);\n\n stream_format(log_stream, \"%s%s:%d:\\e[37;1m \", logger_level_colors[level], file, line);\n\n va_list va;\n va_start(va, fmt);\n\n stream_vprintf(log_stream, fmt, va);\n stream_format(log_stream, \"\\e[0m\\n\");\n stream_flush(log_stream);\n\n va_end(va);\n\n if (level == LOGGER_FATAL)\n {\n __plug_logger_fatal();\n }\n\n __plug_logger_unlock();\n }\n}\n" }, { "alpha_fraction": 0.708737850189209, "alphanum_fraction": 0.708737850189209, "avg_line_length": 10.44444465637207, "blob_id": "5d0e94087b23d09d92b5cf4833efddfac8736bc5", "content_id": "f802be5a3a7e8e06f57af4678b5c127f281a64b7", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 103, "license_type": "permissive", "max_line_length": 56, "num_lines": 9, "path": "/manual/10-utilities/sysfetch.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# sysfetch\n\n```\nsysfetch\n```\n\n## Description\n\nDisplay information of the system next to an ascii logo.\n" }, { "alpha_fraction": 0.698630154132843, "alphanum_fraction": 0.7191780805587769, "avg_line_length": 23.38888931274414, "blob_id": "f2562fc849baed7e564b592ddeac9adb27dcf9fb", "content_id": "20be6619bd41e11cfd478753e237dc409b3243a3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 438, "license_type": "permissive", "max_line_length": 87, "num_lines": 18, "path": "/apps/panel/windows/DateAndTimeWindow.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Screen.h>\n\n#include \"panel/windows/DateAndTimeWindow.h\"\n#include \"panel/windows/PanelWindow.h\"\n\nnamespace panel\n{\n\nDateAndTimeWindow::DateAndTimeWindow()\n : Window(WINDOW_ALWAYS_FOCUSED | WINDOW_AUTO_CLOSE | WINDOW_ACRYLIC)\n{\n title(\"Date And Time\");\n bound(Rect{320, 256}.centered_within(Screen::bound()).with_y(PanelWindow::HEIGHT));\n type(WINDOW_TYPE_POPOVER);\n opacity(0.85);\n}\n\n} // namespace panel" }, { "alpha_fraction": 0.5592820048332214, "alphanum_fraction": 0.5687293410301208, "avg_line_length": 19.355770111083984, "blob_id": "aab8b2b8f994ffd2a2b3244b64ef7d0a3a9cd95c", "content_id": "73e12efe0c8878f29b41def83b1c8c4188eae92c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4234, "license_type": "permissive", "max_line_length": 91, "num_lines": 208, "path": "/libraries/libgraphic/vector/Path.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Rect.h>\n#include <libutils/Scanner.h>\n#include <libutils/Vector.h>\n\n#include <libgraphic/vector/Arc.h>\n#include <libgraphic/vector/SubPath.h>\n\nnamespace graphic\n{\n\nclass Path\n{\nprivate:\n Vector<SubPath> _subpath;\n bool _subpath_ended = true;\n\n SubPath &current()\n {\n if (_subpath_ended)\n {\n begin_subpath();\n }\n\n return _subpath[_subpath.count() - 1];\n }\n\n SubPath &current_or_begin()\n {\n if (_subpath_ended)\n {\n begin_subpath(current().first_point());\n }\n\n return _subpath[_subpath.count() - 1];\n }\n\npublic:\n static Path parse(const char *str)\n {\n StringScanner scan{str, strlen(str)};\n return parse(scan);\n }\n\n static Path parse(Scanner &scan);\n\n const SubPath &subpath(size_t index) const\n {\n return _subpath[index];\n }\n\n size_t subpath_count() const\n {\n return _subpath.count();\n }\n\n Path()\n {\n }\n\n void begin_subpath()\n {\n begin_subpath({0, 0});\n }\n\n void begin_subpath(Vec2f point)\n {\n if (!_subpath_ended)\n {\n end_subpath();\n }\n\n SubPath subpath{point};\n _subpath.push_back(move(subpath));\n _subpath_ended = false;\n }\n\n void begin_subpath_relative()\n {\n begin_subpath_relative({0, 0});\n }\n\n void begin_subpath_relative(Vec2f point)\n {\n if (_subpath.count() > 0)\n {\n begin_subpath(current().last_point() + point);\n }\n else\n {\n begin_subpath(point);\n }\n }\n\n void reset_subpath()\n {\n current().reset();\n }\n\n void reset_subpath(Vec2f start)\n {\n current().reset(start);\n }\n\n void end_subpath()\n {\n _subpath_ended = true;\n }\n\n void close_subpath()\n {\n current().close();\n _subpath_ended = true;\n }\n\n void move_to(Vec2f point)\n {\n current().move_to(point);\n }\n\n void move_to_relative(Vec2f point)\n {\n current().move_to_relative(point);\n }\n\n void line_to(Vec2f point)\n {\n current_or_begin().line_to(point);\n }\n\n void line_to_relative(Vec2f point)\n {\n current_or_begin().line_to_relative(point);\n }\n\n void vline_to(float y)\n {\n current_or_begin().vline_to(y);\n }\n\n void vline_to_relative(float y)\n {\n current_or_begin().vline_to_relative(y);\n }\n\n void hline_to(float x)\n {\n current_or_begin().hline_to(x);\n }\n\n void hline_to_relative(float x)\n {\n current_or_begin().hline_to_relative(x);\n }\n\n void cubic_bezier_to(Vec2f control_point1, Vec2f control_point2, Vec2f point)\n {\n current_or_begin().cubic_bezier_to(control_point1, control_point2, point);\n }\n\n void cubic_bezier_to_relative(Vec2f control_point1, Vec2f control_point2, Vec2f point)\n {\n current_or_begin().cubic_bezier_to_relative(control_point1, control_point2, point);\n }\n\n void smooth_cubic_bezier_to(Vec2f control_point, Vec2f point)\n {\n current_or_begin().smooth_cubic_bezier_to(control_point, point);\n }\n\n void smooth_cubic_bezier_to_relative(Vec2f control_point, Vec2f point)\n {\n current_or_begin().smooth_cubic_bezier_to_relative(control_point, point);\n }\n\n void quad_bezier_to(Vec2f control_point, Vec2f point)\n {\n current_or_begin().quad_bezier_to(control_point, point);\n }\n\n void quad_bezier_to_relative(Vec2f control_point, Vec2f point)\n {\n current_or_begin().quad_bezier_to_relative(control_point, point);\n }\n\n void smooth_quad_bezier_to(Vec2f point)\n {\n current_or_begin().smooth_quad_bezier_to(point);\n }\n\n void smooth_quad_bezier_to_relative(Vec2f point)\n {\n current_or_begin().smooth_quad_bezier_to_relative(point);\n }\n\n void arc_to(float rx, float ry, float angle, int flags, Vec2f point)\n {\n current_or_begin().arc_to(rx, ry, angle, flags, point);\n }\n\n void arc_to_relative(float rx, float ry, float angle, int flags, Vec2f point)\n {\n current_or_begin().arc_to_relative(rx, ry, angle, flags, point);\n }\n};\n\n} // namespace graphic\n" }, { "alpha_fraction": 0.5510203838348389, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 15.333333015441895, "blob_id": "a8f4865e1a6a546be45ddd47bad6a8036d05da5e", "content_id": "ffd28dbb4b1243cd0698b5c06c12b0b11acc489f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 49, "license_type": "permissive", "max_line_length": 37, "num_lines": 3, "path": "/contribs/ffmpeg/clean-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nrm -fr sources &> /dev/null || exit 0\n" }, { "alpha_fraction": 0.4864864945411682, "alphanum_fraction": 0.5, "avg_line_length": 26.75, "blob_id": "e146c36e343507f17dfb9b958e0a9c75832ebd04", "content_id": "896e2068bd0aff9396613148e10b7e420fe2791a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 444, "license_type": "permissive", "max_line_length": 75, "num_lines": 16, "path": "/archs/Memory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#ifndef ARCH_PAGE_SIZE\n# define ARCH_PAGE_SIZE (4096)\n#endif\n\n#define PAGE_ALIGN(__x) ((__x) + ARCH_PAGE_SIZE - ((__x) % ARCH_PAGE_SIZE))\n\n#define PAGE_ALIGN_UP(__x) \\\n ((__x % ARCH_PAGE_SIZE == 0) \\\n ? (__x) \\\n : (__x) + ARCH_PAGE_SIZE - ((__x) % ARCH_PAGE_SIZE))\n\n#define PAGE_ALIGN_DOWN(__x) ((__x) - ((__x) % ARCH_PAGE_SIZE))\n\n#define IS_PAGE_ALIGN(__x) (__x % ARCH_PAGE_SIZE == 0)\n" }, { "alpha_fraction": 0.6803874373435974, "alphanum_fraction": 0.6828086972236633, "avg_line_length": 27.98245620727539, "blob_id": "2f669dc01f47880f9e7b22ae9ed6fa00ca177df6", "content_id": "30973d7b9dc84cd759c41e6490f415c4cd45e32c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1652, "license_type": "permissive", "max_line_length": 61, "num_lines": 57, "path": "/libraries/libc/string.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n#include <stddef.h>\n#include <stdint.h>\n\n__BEGIN_HEADER\n\nvoid *memset(void *dest, int c, size_t n);\nvoid *memcpy(void *dest, const void *src, size_t n);\nvoid *memmove(void *dest, const void *src, size_t n);\n\nvoid *memchr(const void *src, int c, size_t n);\nvoid *memrchr(const void *m, int c, size_t n);\nint memcmp(const void *vl, const void *vr, size_t n);\n\nchar *strdup(const char *s);\nchar *stpcpy(char *d, const char *s);\nchar *strcpy(char *dest, const char *src);\nchar *strchrnul(const char *s, int c);\nchar *strchr(const char *s, int c);\nchar *strrchr(const char *s, int c);\nchar *strpbrk(const char *s, const char *b);\nchar *strstr(const char *h, const char *n);\n\nchar *strncpy(char *dest, const char *src, size_t n);\n\nint strcmp(const char *l, const char *r);\nint strncmp(const char *s1, const char *s2, size_t n);\nint strcoll(const char *s1, const char *s2);\n\nsize_t strcspn(const char *s, const char *c);\nsize_t strspn(const char *s, const char *c);\nsize_t strlen(const char *s);\nsize_t strnlen(const char *s, size_t maxlen);\n\nint atoi(const char *s);\n\nchar *strcat(char *dest, const char *src);\nchar *strncat(char *dest, const char *src, size_t n);\n\nchar *strtok(char *str, const char *delim);\nchar *strtok_r(char *str, const char *delim, char **saveptr);\n\nchar *strncpy(char *dest, const char *src, size_t n);\n\nchar *strerror(int errnum);\nsize_t strxfrm(char *dest, const char *src, size_t n);\n\n// Skift extensions, will be removed\nvoid strrvs(char *str);\nvoid strnapd(char *str, char c, size_t n);\nvoid strapd(char *str, char c);\nsize_t strlcpy(char *dst, const char *src, size_t maxlen);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.5577867031097412, "alphanum_fraction": 0.574743390083313, "avg_line_length": 19.56880760192871, "blob_id": "144144712a962e1e2d8d53f20d3480238ccddcf6", "content_id": "86a447ec63259019d03c7093de799a8a87b6d006", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2241, "license_type": "permissive", "max_line_length": 103, "num_lines": 109, "path": "/libraries/libutils/NumberParser.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libutils/Scanner.h>\n#include <libutils/Strings.h>\n#include <string.h>\n\nstruct NumberParser\n{\n int base;\n};\n\n#define PARSER_BINARY ((NumberParser){2})\n#define PARSER_OCTAL ((NumberParser){8})\n#define PARSER_DECIMAL ((NumberParser){10})\n#define PARSER_HEXADECIMAL ((NumberParser){16})\n\nstatic constexpr const char *XDIGITS = \"0123456789abcdefghijklmnopqrstuvwxyz\";\nstatic constexpr const char *XDIGITS_CAPITALIZED = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\ninline bool parse_uint(NumberParser parser, const char *str, size_t size, unsigned int *result)\n{\n if (str == nullptr || size == 0)\n {\n *result = 0;\n return false;\n }\n\n unsigned int value = 0;\n\n for (size_t i = 0; (i < size && str[i]); i++)\n {\n value = value * parser.base;\n\n for (int j = 0; j < parser.base; j++)\n {\n if ((Strings::LOWERCASE_XDIGITS[j] == str[i]) ||\n (Strings::UPPERCASE_XDIGITS[j] == str[i]))\n {\n value += j;\n }\n }\n }\n\n *result = value;\n return true;\n}\n\ninline unsigned int parse_uint_inline(NumberParser parser, const char *str, unsigned int default_value)\n{\n unsigned int result = 0;\n\n if (parse_uint(parser, str, strlen(str), &result))\n {\n return result;\n }\n\n return default_value;\n}\n\ninline bool parse_int(NumberParser parser, const char *str, size_t size, int *result)\n{\n if (str == nullptr || size == 0)\n {\n *result = 0;\n return false;\n }\n\n bool is_negative = str[0] == '-';\n if (is_negative)\n {\n str++;\n size--;\n }\n\n unsigned int unsigned_value = 0;\n if (!parse_uint(parser, str, size, &unsigned_value))\n {\n *result = 0;\n return false;\n }\n\n if (is_negative)\n {\n *result = -unsigned_value;\n }\n else\n {\n *result = unsigned_value;\n }\n\n return true;\n}\n\ninline int parse_int_inline(NumberParser parser, const char *str, int default_value)\n{\n if (str == nullptr)\n {\n return default_value;\n }\n\n int result = 0;\n if (parse_int(parser, str, strlen(str), &result))\n {\n return result;\n }\n\n return default_value;\n}" }, { "alpha_fraction": 0.6136114001274109, "alphanum_fraction": 0.6212952733039856, "avg_line_length": 15.267857551574707, "blob_id": "6aefede40d46dc5f3b8a0387b5d30d16b27d1611", "content_id": "ffb90dc2d63d4690261b382dc880eef55af88d14", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 911, "license_type": "permissive", "max_line_length": 52, "num_lines": 56, "path": "/kernel/system/System.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/BuildInfo.h>\n#include <libsystem/Logger.h>\n\n#include \"archs/Architectures.h\"\n#include \"kernel/scheduling/Scheduler.h\"\n#include \"kernel/system/System.h\"\n\nvoid system_hang()\n{\n while (true)\n {\n arch_halt();\n }\n}\n\nvoid system_stop()\n{\n arch_disable_interrupts();\n logger_info(\"System stopped!\");\n\n while (1)\n {\n arch_disable_interrupts();\n arch_halt();\n }\n}\n\nstatic uint32_t _system_tick;\n\nvoid system_tick()\n{\n if (_system_tick + 1 < _system_tick)\n {\n system_panic(\"System tick overflow!\");\n }\n\n _system_tick++;\n}\n\nuint32_t system_get_tick()\n{\n return _system_tick;\n}\n\nstatic TimeStamp _system_boot_timestamp = 0;\n\nElapsedTime system_get_uptime()\n{\n return arch_get_time() - _system_boot_timestamp;\n}\n\nvoid system_initialize()\n{\n _system_boot_timestamp = arch_get_time();\n logger_info(\"hjert - \" __BUILD_GITREF__);\n}\n" }, { "alpha_fraction": 0.6208651661872864, "alphanum_fraction": 0.6230915784835815, "avg_line_length": 19.953332901000977, "blob_id": "9b26e80736444230a9ff0a9263aeffde2169f796", "content_id": "2cf257450c3d646104f6e11f44e321b47b4b3b37", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3144, "license_type": "permissive", "max_line_length": 90, "num_lines": 150, "path": "/kernel/scheduling/Scheduler.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include \"archs/Architectures.h\"\n#include \"archs/VirtualMemory.h\"\n\n#include \"kernel/interrupts/Interupts.h\"\n#include \"kernel/scheduling/Scheduler.h\"\n#include \"kernel/system/System.h\"\n\nstatic bool scheduler_context_switch = false;\nstatic int scheduler_record[SCHEDULER_RECORD_COUNT] = {};\n\nstatic Task *running = nullptr;\nstatic Task *idle = nullptr;\n\nstatic List *blocked_tasks;\nstatic List *running_tasks;\n\nvoid scheduler_initialize()\n{\n blocked_tasks = list_create();\n running_tasks = list_create();\n}\n\nvoid scheduler_did_create_idle_task(Task *task)\n{\n idle = task;\n}\n\nvoid scheduler_did_create_running_task(Task *task)\n{\n running = task;\n}\n\nvoid scheduler_did_change_task_state(Task *task, TaskState oldstate, TaskState newstate)\n{\n ASSERT_INTERRUPTS_RETAINED();\n\n if (oldstate != newstate)\n {\n if (oldstate == TASK_STATE_RUNNING)\n {\n list_remove(running_tasks, task);\n }\n\n if (oldstate == TASK_STATE_BLOCKED)\n {\n list_remove(blocked_tasks, task);\n }\n\n if (newstate == TASK_STATE_BLOCKED)\n {\n list_push(blocked_tasks, task);\n }\n\n if (newstate == TASK_STATE_RUNNING)\n {\n list_push(running_tasks, task);\n }\n }\n}\n\nbool scheduler_is_context_switch()\n{\n return scheduler_context_switch;\n}\n\nTask *scheduler_running()\n{\n return running;\n}\n\nint scheduler_running_id()\n{\n if (running == nullptr)\n {\n return -1;\n }\n\n return running->id;\n}\n\nvoid scheduler_yield()\n{\n arch_yield();\n}\n\nint scheduler_get_usage(int task_id)\n{\n InterruptsRetainer retainer;\n\n int count = 0;\n\n for (int i = 0; i < SCHEDULER_RECORD_COUNT; i++)\n {\n if (scheduler_record[i] == task_id)\n {\n count++;\n }\n }\n\n return (count * 100) / SCHEDULER_RECORD_COUNT;\n}\n\nstatic Iteration wakeup_task_if_unblocked(void *target, Task *task)\n{\n __unused(target);\n\n Blocker *blocker = task->blocker;\n\n if (blocker->can_unblock(task))\n {\n blocker->on_unblock(task);\n blocker->_result = BLOCKER_UNBLOCKED;\n task->state(TASK_STATE_RUNNING);\n }\n else if (blocker->_timeout != (Timeout)-1 &&\n blocker->_timeout <= system_get_tick())\n {\n blocker->on_timeout(task);\n blocker->_result = BLOCKER_TIMEOUT;\n task->state(TASK_STATE_RUNNING);\n }\n\n return Iteration::CONTINUE;\n}\n\nuintptr_t schedule(uintptr_t current_stack_pointer)\n{\n scheduler_context_switch = true;\n\n running->kernel_stack_pointer = current_stack_pointer;\n arch_save_context(running);\n\n scheduler_record[system_get_tick() % SCHEDULER_RECORD_COUNT] = running->id;\n\n list_iterate(blocked_tasks, nullptr, (ListIterationCallback)wakeup_task_if_unblocked);\n\n // Get the next task\n if (!list_peek_and_pushback(running_tasks, (void **)&running))\n {\n // Or the idle task if there are no running tasks.\n running = idle;\n }\n\n arch_address_space_switch(running->address_space);\n arch_load_context(running);\n\n scheduler_context_switch = false;\n\n return running->kernel_stack_pointer;\n}\n" }, { "alpha_fraction": 0.5689354538917542, "alphanum_fraction": 0.5689354538917542, "avg_line_length": 13.717948913574219, "blob_id": "0170cb0c47a9513c01236f497b54890ef007fe1b", "content_id": "9890878981eea0aa1606df619cb04ec7e4880566", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 573, "license_type": "permissive", "max_line_length": 48, "num_lines": 39, "path": "/libraries/libutils/StringView.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <string.h>\n\n#include <libutils/RefPtr.h>\n#include <libutils/StringStorage.h>\n\nclass StringView\n{\nprivate:\n RefPtr<StringStorage> _storage;\n const char *_buffer;\n size_t _size;\n\npublic:\n const char *buffer() const\n {\n return _buffer;\n }\n\n size_t size() const\n {\n return _size;\n }\n\n StringView(const char *buffer)\n : _buffer(buffer), _size(strlen(buffer))\n {\n }\n\n StringView(const char *buffer, size_t size)\n : _buffer(buffer), _size(size)\n {\n }\n\n ~StringView()\n {\n }\n};" }, { "alpha_fraction": 0.7027027010917664, "alphanum_fraction": 0.7027027010917664, "avg_line_length": 11.333333015441895, "blob_id": "8afaf8d0f7da5125d5f362a3312f4f312c5d5bc6", "content_id": "76763bbebe5079c9bdca7042bcedf67ef3532ef6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 37, "license_type": "permissive", "max_line_length": 20, "num_lines": 3, "path": "/libraries/libmarkup/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += MARKUP\n\nMARKUP_NAME = markup\n" }, { "alpha_fraction": 0.7804877758026123, "alphanum_fraction": 0.7804877758026123, "avg_line_length": 40, "blob_id": "f140eb393a7233905081bd4f7f58d1745f23561e", "content_id": "1d269d214dcb5e0bbc16fd27cb2d7b1e682d070e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 41, "license_type": "permissive", "max_line_length": 40, "num_lines": 1, "path": "/configs/user.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# Override configs from configs.mk here.\n" }, { "alpha_fraction": 0.6158536672592163, "alphanum_fraction": 0.6280487775802612, "avg_line_length": 28.81818199157715, "blob_id": "b7fa8a109eff37d40602c07a43267985ea2451f2", "content_id": "2d12de26b793905b2e935a0c3d1a11f3137aa6d6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 328, "license_type": "permissive", "max_line_length": 72, "num_lines": 11, "path": "/libraries/libgraphic/StackBlur.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nvoid stackblur(\n unsigned char *src, ///< input image data\n unsigned int w, ///< image width\n unsigned int h, ///< image height\n unsigned int radius, ///< blur intensity (should be in 2..254 range)\n unsigned int minX,\n unsigned int maxX,\n unsigned int minY,\n unsigned int maxY);\n" }, { "alpha_fraction": 0.779411792755127, "alphanum_fraction": 0.779411792755127, "avg_line_length": 27.10344886779785, "blob_id": "c453f674fcd97633eb456e91940ed2c231c6817a", "content_id": "7e5d55a80624d53f1135adf7c1948cb2f9edd938", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 816, "license_type": "permissive", "max_line_length": 119, "num_lines": 29, "path": "/archs/VirtualMemory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Memory.h>\n\n#include <libsystem/Result.h>\n\n#include \"kernel/memory/MemoryRange.h\"\n\nvoid *arch_kernel_address_space();\n\nvoid arch_virtual_initialize();\n\nvoid arch_virtual_memory_enable();\n\nbool arch_virtual_present(void *address_space, uintptr_t virtual_address);\n\nuintptr_t arch_virtual_to_physical(void *address_space, uintptr_t virtual_address);\n\nResult arch_virtual_map(void *address_space, MemoryRange physical_range, uintptr_t virtual_address, MemoryFlags flags);\n\nMemoryRange arch_virtual_alloc(void *address_space, MemoryRange physical_range, MemoryFlags flags);\n\nvoid arch_virtual_free(void *address_space, MemoryRange virtual_range);\n\nvoid *arch_address_space_create();\n\nvoid arch_address_space_destroy(void *address_space);\n\nvoid arch_address_space_switch(void *address_space);\n\n" }, { "alpha_fraction": 0.626204252243042, "alphanum_fraction": 0.6300578117370605, "avg_line_length": 19, "blob_id": "824790bfbe21a16688c359729eaf1d8a943d90ea", "content_id": "5cec9c0d30f3756af0becd1d719e68a167b034eb", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 519, "license_type": "permissive", "max_line_length": 58, "num_lines": 26, "path": "/libraries/libc/stdio/printf.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <skift/Printf.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid file_append(printf_info_t *info, char c)\n{\n fputc(c, (FILE *)info->output);\n}\n\nint vfprintf(FILE *file, const char *fmt, va_list va)\n{\n printf_info_t info = {};\n\n info.format = fmt;\n info.append = file_append;\n info.output = file;\n info.allocated = -1;\n\n // We need it to start with a 0 because we use strapd.\n return __printf(&info, va);\n}\n\nint vprintf(const char *fmt, va_list va)\n{\n return vfprintf(stdout, fmt, va);\n}" }, { "alpha_fraction": 0.5785456299781799, "alphanum_fraction": 0.5797508955001831, "avg_line_length": 18.91200065612793, "blob_id": "025a057c8ccc22156c17c11725df034f326185d0", "content_id": "edfd40c252c5f25a0375aa96e7718dbd526315dd", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2489, "license_type": "permissive", "max_line_length": 70, "num_lines": 125, "path": "/libraries/libmarkup/Markup.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Enum.h>\n#include <libutils/HashMap.h>\n#include <libutils/Prettifier.h>\n#include <libutils/Scanner.h>\n#include <libutils/String.h>\n#include <libutils/Vector.h>\n\nnamespace markup\n{\n\nusing Attributes = HashMap<String, String>;\n\nclass Node\n{\nprivate:\n String _type;\n int _flags;\n Vector<Node> _childs;\n HashMap<String, String> _attributes;\n\npublic:\n static constexpr auto NONE = 0;\n static constexpr auto SELF_CLOSING = 1 << 0;\n\n auto type() const { return _type; }\n\n auto is(String type) const { return _type == type; }\n\n auto flags() { return _flags; }\n\n auto count_child() { return _childs.count(); }\n\n Node(String type, int flags = NONE)\n : _type(type),\n _flags(flags)\n {\n }\n\n Node(String type, int flags, Attributes &&attributes)\n : _type(type),\n _flags(flags),\n _attributes(attributes)\n {\n }\n\n bool has_attribute(String attribute)\n {\n return _attributes.has_key(attribute);\n }\n\n void set_attribute(String attribute, String value)\n {\n _attributes[attribute] = value;\n }\n\n String get_attribute(String attribute)\n {\n if (_attributes.has_key(attribute))\n {\n return _attributes[attribute];\n }\n else\n {\n return \"\";\n }\n }\n\n template <typename TCallback>\n bool with_attribute(String attribute, TCallback callback)\n {\n if (_attributes.has_key(attribute))\n {\n callback(_attributes[attribute]);\n return true;\n }\n else\n {\n return false;\n }\n }\n\n String get_attribute_or_default(String attribute, String fallback)\n {\n if (_attributes.has_key(attribute))\n {\n return _attributes[attribute];\n }\n else\n {\n return fallback;\n }\n }\n\n template <typename TCallback>\n Iteration foreach_attributes(TCallback callback)\n {\n return _attributes.foreach (callback);\n }\n\n void add_child(const Node &child)\n {\n _childs.push_back(child);\n }\n\n void add_child(Node &&child)\n {\n _childs.push_back(move(child));\n }\n\n template <typename TCallback>\n Iteration foreach_child(TCallback callback)\n {\n return _childs.foreach (callback);\n }\n};\n\nNode parse(Scanner &scan);\n\nNode parse_file(String path);\n\nvoid prettify(Prettifier &pretty, Node &node);\n\n} // namespace markup\n" }, { "alpha_fraction": 0.5485436916351318, "alphanum_fraction": 0.6104369163513184, "avg_line_length": 33.3125, "blob_id": "7eeafd9d1f0e98d394e05fa5a06d1ed0c9c2ef38", "content_id": "d0905f668854130b68386ea00873a22ccdd6b308", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1648, "license_type": "permissive", "max_line_length": 97, "num_lines": 48, "path": "/apps/demo/Graphics.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <assert.h>\n\n#include \"demo/Demos.h\"\n\nstatic RefPtr<Bitmap> _test_image = nullptr;\nstatic int _frame = 0;\n\nvoid graphics_draw(Painter &painter, Recti screen, float time)\n{\n __unused(time);\n\n if (_test_image == nullptr)\n {\n _test_image = Bitmap::load_from_or_placeholder(\"/Applications/demo/test.png\");\n }\n\n for (int x = 0; x < screen.width(); x++)\n {\n for (int y = 0; y < screen.height(); y++)\n {\n uint8_t pixel = x ^ y;\n\n painter.plot(screen.position() + Vec2i(x, y), Color::from_byte(pixel, pixel, pixel));\n }\n }\n\n Recti test_image_bound(\n screen.x() + screen.width() / 2 - (_frame % screen.width()) / 2,\n screen.y() + screen.height() / 2 - (_frame % screen.height()) / 2,\n _frame % screen.width(),\n _frame % screen.height());\n\n painter.blit(*_test_image, _test_image->bound(), test_image_bound);\n\n painter.draw_rectangle(Recti(75, 75, 100, 100), Colors::WHITE);\n painter.fill_rectangle(Recti(100, 100, 100, 100), Colors::RED.with_alpha(0.5));\n painter.fill_rectangle(Recti(125, 125, 100, 100), Colors::GREEN.with_alpha(0.5));\n painter.fill_rectangle_rounded(Recti(150, 150, 100, 100), 32, Colors::BLUE.with_alpha(0.5));\n\n painter.draw_rectangle_rounded(screen, 64, 16, Colors::RED.with_alpha(0.75));\n painter.draw_rectangle_rounded(screen, 64, 12, Colors::YELLOW.with_alpha(0.75));\n painter.draw_rectangle_rounded(screen, 64, 8, Colors::GREEN.with_alpha(0.75));\n painter.draw_rectangle_rounded(screen, 64, 4, Colors::BLUE.with_alpha(0.75));\n\n painter.blur(Recti(100, 100, 200, 200), 8);\n\n _frame++;\n}\n" }, { "alpha_fraction": 0.6115362048149109, "alphanum_fraction": 0.62860506772995, "avg_line_length": 25.984127044677734, "blob_id": "5a79a86cdeb139b284ea35f67f1e7e1218be57ea", "content_id": "d143e9066af9a826cb80f33a3e62891972158c5c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1699, "license_type": "permissive", "max_line_length": 79, "num_lines": 63, "path": "/apps/task-manager/widgets/RAMGraph.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Syscalls.h>\n\n#include <libutils/StringBuilder.h>\n\n#include <libsystem/system/System.h>\n\n#include <libwidget/Container.h>\n#include <libwidget/IconPanel.h>\n\n#include <stdio.h>\n\n#include \"task-manager/widgets/RAMGraph.h\"\n\nnamespace task_manager\n{\n\nRAMGraph::RAMGraph(Widget *parent, RefPtr<TaskModel> model)\n : Graph(parent, 256, Colors::ROYALBLUE),\n _model(model)\n{\n layout(VFLOW(0));\n insets(Insetsi(8));\n flags(Widget::FILL);\n\n auto icon_and_text = new Container(this);\n icon_and_text->layout(HFLOW(4));\n new IconPanel(icon_and_text, Icon::get(\"chip\"));\n new Label(icon_and_text, \"Memory\");\n\n auto cpu_filler = new Container(this);\n cpu_filler->flags(Widget::FILL);\n\n _label_usage = new Label(this, \"Usage: nil Mio\", Anchor::RIGHT);\n _label_available = new Label(this, \"Available: nil Mio\", Anchor::RIGHT);\n _label_greedy = new Label(this, \"Most greedy: nil\", Anchor::RIGHT);\n\n _graph_timer = own<Timer>(500, [&]() {\n SystemStatus status{};\n hj_system_status(&status);\n\n record(status.used_ram / (float)status.total_ram);\n });\n\n _graph_timer->start();\n\n _text_timer = own<Timer>(1000, [&]() {\n SystemStatus status{};\n hj_system_status(&status);\n\n unsigned usage = status.used_ram / 1024 / 1024;\n _label_usage->text(String::format(\"Usage: {} Mio\", usage));\n\n unsigned available = status.total_ram / 1024 / 1024;\n _label_available->text(String::format(\"Available: {} Mio\", available));\n\n auto greedy = _model->ram_greedy();\n _label_greedy->text(String::format(\"Most greedy: {}\", greedy));\n });\n\n _text_timer->start();\n}\n\n} // namespace task_manager" }, { "alpha_fraction": 0.521276593208313, "alphanum_fraction": 0.5457446575164795, "avg_line_length": 16.090909957885742, "blob_id": "261368d806811afec3e3e364e0af7d0697ccebbc", "content_id": "a26891b6f19db3c53486f44759da5f96755996e7", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 940, "license_type": "permissive", "max_line_length": 49, "num_lines": 55, "path": "/archs/x86/kernel/x86.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"archs/Architectures.h\"\n\n#ifdef __x86_64__\nusing CRRegister = uint64_t;\n#else\nusing CRRegister = uint32_t;\n#endif\n\nstatic inline CRRegister CR0()\n{\n CRRegister r;\n asm volatile(\"mov %%cr0, %0\"\n : \"=r\"(r));\n return r;\n}\n\nstatic inline CRRegister CR1()\n{\n CRRegister r;\n asm volatile(\"mov %%cr1, %0\"\n : \"=r\"(r));\n return r;\n}\n\nstatic inline CRRegister CR2()\n{\n CRRegister r;\n asm volatile(\"mov %%cr2, %0\"\n : \"=r\"(r));\n return r;\n}\n\nstatic inline CRRegister CR3()\n{\n CRRegister r;\n asm volatile(\"mov %%cr3, %0\"\n : \"=r\"(r));\n return r;\n}\n\nstatic inline CRRegister CR4()\n{\n CRRegister r;\n asm volatile(\"mov %%cr4, %0\"\n : \"=r\"(r));\n return r;\n}\n\nstatic inline void cli() { asm volatile(\"cli\"); }\n\nstatic inline void sti() { asm volatile(\"sti\"); }\n\nstatic inline void hlt() { asm volatile(\"hlt\"); }\n" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 8.777777671813965, "blob_id": "0435318cd5e8121c0ef79e75b9dcbe511a9b7e84", "content_id": "61b15b364051d9d6b5deb886e69c7049311c0922", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 88, "license_type": "permissive", "max_line_length": 45, "num_lines": 9, "path": "/manual/10-utilities/uptime.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# uptime\n\n```\nuptime\n```\n\n## Description\n\nReturns how long the system has been running.\n" }, { "alpha_fraction": 0.7356828451156616, "alphanum_fraction": 0.7356828451156616, "avg_line_length": 28.65217399597168, "blob_id": "6a3cf2c319e341386367be05107997d20223e525", "content_id": "9618b2fd3d9c55af37a3010af3a891663d16905f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 681, "license_type": "permissive", "max_line_length": 88, "num_lines": 23, "path": "/libraries/libfile/ZipArchive.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libfile/Archive.h>\n#include <libsystem/io/BinaryReader.h>\n#include <libsystem/io/BinaryWriter.h>\n\nclass ZipArchive : public Archive\n{\npublic:\n ZipArchive(Path path, bool read = true);\n\n Result extract(unsigned int entry_index, const char *dest_path) override;\n Result insert(const char *entry_name, const char *src_path) override;\n\nprivate:\n void read_archive();\n void read_local_headers(BinaryReader &reader);\n Result read_central_directory(BinaryReader &reader);\n\n void write_archive();\n void write_entry(const Entry &entry, BinaryWriter &writer, Reader &compressed_data);\n void write_central_directory(BinaryWriter &writer);\n};" }, { "alpha_fraction": 0.5588585138320923, "alphanum_fraction": 0.5624256730079651, "avg_line_length": 23.735294342041016, "blob_id": "a55d1d44c46b1100c392b8c1a6dd2bbff11b1caa", "content_id": "7946ec8642ce1eea03bdda6336a9345f1895ba4f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 841, "license_type": "permissive", "max_line_length": 40, "num_lines": 34, "path": "/libraries/libc/locale.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <limits.h>\n#include <locale.h>\n\nstatic struct lconv _locale_defaults = {\n .decimal_point = \".\",\n .thousands_sep = \"\",\n .grouping = \"\",\n .mon_decimal_point = \"\",\n .mon_thousands_sep = \"\",\n .mon_grouping = \"\",\n .positive_sign = \"\",\n .negative_sign = \"\",\n .currency_symbol = \"\",\n .frac_digits = CHAR_MAX,\n .p_cs_precedes = CHAR_MAX,\n .n_cs_precedes = CHAR_MAX,\n .p_sep_by_space = 0,\n .n_sep_by_space = 0,\n .p_sign_posn = CHAR_MAX,\n .n_sign_posn = CHAR_MAX,\n .int_curr_symbol = \"\",\n .int_frac_digits = 0,\n .int_p_cs_precedes = CHAR_MAX,\n .int_n_cs_precedes = CHAR_MAX,\n .int_p_sep_by_space = CHAR_MAX,\n .int_n_sep_by_space = CHAR_MAX,\n .int_p_sign_posn = CHAR_MAX,\n .int_n_sign_posn = CHAR_MAX,\n};\n\nstruct lconv *localeconv(void)\n{\n return &_locale_defaults;\n}\n" }, { "alpha_fraction": 0.720588207244873, "alphanum_fraction": 0.720588207244873, "avg_line_length": 15.75, "blob_id": "2503551152c352b7e71d4a5d9ba653b96f11cac5", "content_id": "28369066dab21e709568696ecf7d9068ea52930b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 68, "license_type": "permissive", "max_line_length": 35, "num_lines": 4, "path": "/apps/neko/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += NEKO\n\nNEKO_NAME = neko\nNEKO_LIBS = widget settings graphic\n\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 14.9375, "blob_id": "1744a83c66390bb61531013891387c9ddc3dc209", "content_id": "a3a431c11ba1bda97d795f4926d679a6dce14d63", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 255, "license_type": "permissive", "max_line_length": 55, "num_lines": 16, "path": "/apps/panel/widgets/SearchBar.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Callback.h>\n#include <libwidget/Panel.h>\n#include <libwidget/model/TextModel.h>\n\nnamespace panel\n{\n\nclass SearchBar : public Panel\n{\npublic:\n SearchBar(Widget *parent, RefPtr<TextModel> model);\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.7313432693481445, "alphanum_fraction": 0.7313432693481445, "avg_line_length": 20.645160675048828, "blob_id": "037eda5e9d9be21683cae58904812f80ec602b58", "content_id": "278902d3410e039e762a30df75931ffd11d6adfd", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 670, "license_type": "permissive", "max_line_length": 91, "num_lines": 31, "path": "/libraries/libfilepicker/widgets/Breadcrumb.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\n#include <libfilepicker/model/Bookmarks.h>\n#include <libfilepicker/model/Navigation.h>\n\nnamespace filepicker\n{\n\nstruct Breadcrumb : public Widget\n{\nprivate:\n RefPtr<Navigation> _navigation;\n RefPtr<Bookmarks> _bookmarks;\n\n OwnPtr<Observer<Navigation>> _navigation_observer;\n OwnPtr<Observer<Bookmarks>> _bookmarks_observer;\n\n RefPtr<Icon> _icon_computer;\n RefPtr<Icon> _icon_expand;\n RefPtr<Icon> _icon_bookmark;\n RefPtr<Icon> _icon_bookmark_outline;\n\npublic:\n Breadcrumb(Widget *parent, RefPtr<Navigation> navigation, RefPtr<Bookmarks> bookmarks);\n\n void render();\n};\n\n} // namespace filepicker" }, { "alpha_fraction": 0.539393961429596, "alphanum_fraction": 0.5412121415138245, "avg_line_length": 19.134145736694336, "blob_id": "4fcb5fc72010ba7ff3e6a41d971836a9f05fd69f", "content_id": "28ce57c6c07679be6e784145d13442f0a20e6507", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1650, "license_type": "permissive", "max_line_length": 83, "num_lines": 82, "path": "/libraries/libutils/Array.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <initializer_list>\n#include <type_traits>\n\n#include <assert.h>\n#include <libsystem/Common.h>\n\ntemplate <typename T, size_t N>\nclass Array\n{\n static_assert(N > 0, \"Array must have size greater than 0\");\n\nprivate:\n T _storage[N];\n\npublic:\n constexpr size_t count() const { return N; }\n\n constexpr T* raw_storage() { return _storage; } \n constexpr const T *raw_storage() const { return _storage; }\n\n T &at(size_t index)\n {\n assert(index < N);\n return _storage[index];\n }\n\n const T &at(size_t index) const\n {\n assert(index < N);\n return _storage[index];\n }\n\n constexpr Array()\n {\n }\n\n constexpr Array(std::initializer_list<T> data)\n {\n static_assert(data.size() == N, \"Must initialize all values of array\");\n\n for (size_t i = 0; i < N; i++)\n {\n _storage[i] = data[i];\n }\n }\n\n T &operator[](size_t index)\n {\n assert(index < N);\n\n return _storage[index];\n }\n\n constexpr T &operator[](size_t index) const\n {\n assert(index < N);\n\n return _storage[index];\n }\n\n // Array iteration\n class iterator\n {\n public:\n iterator(T *ptr) : _ptr(ptr) {}\n iterator operator++()\n {\n ++_ptr;\n return *this;\n }\n bool operator!=(const iterator &other) const { return _ptr != other._ptr; }\n const T &operator*() const { return *_ptr; }\n\n private:\n T *_ptr;\n };\n\n constexpr iterator begin() const { return iterator(_storage); }\n constexpr iterator end() const { return iterator(_storage + N); }\n};" }, { "alpha_fraction": 0.6073423624038696, "alphanum_fraction": 0.6073423624038696, "avg_line_length": 21.799999237060547, "blob_id": "5c87d455eaf7a8e2e784c332b7645de400c206eb", "content_id": "2d2c9949f4ffc106af23e8108842ec68e474b378", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1253, "license_type": "permissive", "max_line_length": 62, "num_lines": 55, "path": "/libraries/libsystem/io/BinaryReader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/io/SeekableReader.h>\n#include <libutils/Slice.h>\n#include <libutils/String.h>\n\nclass BinaryReader : public SeekableReader\n{\npublic:\n BinaryReader(SeekableReader &reader) : _reader(reader)\n {\n }\n\n // Peek & Get functons\n template <typename T>\n inline T peek()\n {\n T result = get<T>();\n _reader.seek(-sizeof(T), WHENCE_HERE);\n return result;\n }\n\n template <typename T>\n inline T get()\n {\n T result;\n assert(_reader.read(&result, sizeof(T)) == sizeof(T));\n return result;\n }\n\n inline String get_fixed_len_string(size_t len)\n {\n char *cstr = new char[len];\n assert(_reader.read(cstr, len) == len);\n return String(make<StringStorage>(cstr, len));\n }\n\n inline void skip(size_t num_bytes)\n {\n _reader.seek(num_bytes, WHENCE_HERE);\n }\n\n inline bool good()\n {\n return _reader.position() < _reader.length();\n }\n\n // Inherited from SeekableReader\n virtual size_t length() override;\n virtual size_t position() override;\n virtual size_t seek(size_t pos, Whence whence) override;\n virtual size_t read(void *buffer, size_t size) override;\n\nprivate:\n SeekableReader &_reader;\n};" }, { "alpha_fraction": 0.776203989982605, "alphanum_fraction": 0.776203989982605, "avg_line_length": 22.53333282470703, "blob_id": "cb45e16ef18e9c4971bcb45d7414d746bb774bb3", "content_id": "14bf0e57480ebe8547d3a8e675dad209a46b3639", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 353, "license_type": "permissive", "max_line_length": 80, "num_lines": 15, "path": "/libraries/libsystem/io/Connection.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Handle.h>\n\nstruct Socket;\n\nstruct Connection;\n\nConnection *connection_create(struct Socket *socket, Handle handle);\n\nvoid connection_close(Connection *connection);\n\nsize_t connection_send(Connection *connection, const void *buffer, size_t size);\n\nsize_t connection_receive(Connection *connection, void *buffer, size_t size);\n" }, { "alpha_fraction": 0.48948705196380615, "alphanum_fraction": 0.4922597110271454, "avg_line_length": 17.493589401245117, "blob_id": "b02e82f9bd9af96ae74e091ca54f7c69394802ea", "content_id": "cc65eceae75cc9910296611e0198c2759a0b8e66", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8656, "license_type": "permissive", "max_line_length": 101, "num_lines": 468, "path": "/libraries/libsystem/utils/List.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/utils/List.h>\n#include <string.h>\n\nList *list_create()\n{\n List *list = __create(List);\n\n list->_count = 0;\n list->_head = nullptr;\n list->_tail = nullptr;\n\n return list;\n}\n\nvoid list_destroy(List *list) { list_destroy_with_callback(list, nullptr); }\nvoid list_destroy_with_callback(List *list, ListDestroyElementCallback callback)\n{\n list_clear_with_callback(list, callback);\n free(list);\n}\n\nvoid list_clear(List *list) { list_clear_with_callback(list, nullptr); }\nvoid list_clear_with_callback(List *list, ListDestroyElementCallback callback)\n{\n ListItem *current = list->_head;\n\n while (current)\n {\n ListItem *next = current->next;\n\n if (callback)\n {\n callback(current->value);\n }\n\n free(current);\n\n current = next;\n }\n\n list->_count = 0;\n list->_head = nullptr;\n list->_tail = nullptr;\n}\n\nList *list_clone(List *list)\n{\n List *copy = list_create();\n\n list_foreach(void, value, list)\n {\n list_pushback(copy, value);\n }\n\n return copy;\n}\n\nvoid list_insert_sorted(List *list, void *value, ListCompareElementCallback callback)\n{\n if (list->_head == nullptr || callback(value, list->_head->value))\n {\n list_push(list, value);\n }\n else\n {\n ListItem *current = list->_head;\n\n while (current->next != nullptr && callback(current->next->value, value))\n {\n current = current->next;\n }\n\n ListItem *item = __create(ListItem);\n\n item->prev = current;\n item->next = current->next;\n item->value = value;\n\n if (current->next == nullptr)\n {\n list->_tail = item;\n }\n else\n {\n current->next->prev = item;\n }\n\n current->next = item;\n\n list->_count++;\n }\n}\n\nvoid *list_peek(List *list)\n{\n if (list->_head != nullptr)\n {\n return list->_head->value;\n }\n else\n {\n return nullptr;\n }\n}\n\nbool list_peek_and_pushback(List *list, void **value)\n{\n *value = list_peek(list);\n\n if (*value)\n {\n ListItem *item = list->_head;\n\n // Pop\n if (list->_count == 1)\n {\n list->_count = 0;\n list->_head = nullptr;\n list->_tail = nullptr;\n }\n else if (list->_count > 1)\n {\n item->next->prev = nullptr;\n list->_head = item->next;\n\n list->_count--;\n }\n\n // Push back\n item->prev = nullptr;\n item->next = nullptr;\n\n list->_count++;\n\n if (list->_tail == nullptr)\n {\n list->_tail = item;\n list->_head = item;\n }\n else\n {\n list->_tail->next = item;\n item->prev = list->_tail;\n list->_tail = item;\n }\n\n return true;\n }\n else\n {\n return false;\n }\n}\n\nvoid *list_peekback(List *list)\n{\n if (list->_tail != nullptr)\n {\n return list->_tail->value;\n }\n else\n {\n return nullptr;\n }\n}\n\nstatic void list_peekat_from_head(List *list, int index, void **value)\n{\n ListItem *current = list->_head;\n\n for (int i = 0; i < index; i++)\n {\n if (current->next)\n {\n current = current->next;\n }\n }\n\n *value = current->value;\n}\n\nstatic void list_peekat_from_back(List *list, int index, void **value)\n{\n ListItem *current = list->_tail;\n\n for (int i = 0; i < (list->_count - index - 1); i++)\n {\n if (current->prev)\n {\n current = current->prev;\n }\n }\n\n *value = current->value;\n}\n\nbool list_peekat(List *list, int index, void **value)\n{\n *value = nullptr;\n\n if (list->_count >= 1 && index >= 0 && index < list->_count)\n {\n if (index < list->_count / 2)\n {\n list_peekat_from_head(list, index, value);\n }\n else\n {\n list_peekat_from_back(list, index, value);\n }\n\n return true;\n }\n else\n {\n return false;\n }\n}\n\nint list_indexof(List *list, void *value)\n{\n int index = 0;\n\n list_foreach(void, item, list)\n {\n if (item == value)\n {\n return index;\n }\n\n index++;\n }\n\n return -1;\n}\n\nvoid list_insert(List *list, int index, void *value)\n{\n if (list->empty())\n {\n list_pushback(list, value);\n return;\n }\n\n if (index == 0)\n {\n list_push(list, value);\n }\n\n ListItem *current = list->_head;\n\n for (int i = 0; i < index - 1; i++)\n {\n if (current->next)\n {\n current = current->next;\n }\n }\n\n ListItem *item = __create(ListItem);\n\n item->prev = current;\n item->next = current->next;\n item->value = value;\n\n current->next = item;\n\n if (list->_tail == current)\n {\n list->_tail = item;\n }\n\n list->_count++;\n}\n\nvoid list_push(List *list, void *value)\n{\n ListItem *item = __create(ListItem);\n\n item->value = value;\n\n list->_count++;\n\n if (list->_head == nullptr)\n {\n list->_head = item;\n list->_tail = item;\n }\n else\n {\n list->_head->prev = item;\n item->next = list->_head;\n list->_head = item;\n }\n}\n\nbool list_pop(List *list, void **value)\n{\n ListItem *item = list->_head;\n\n if (list->_count == 0)\n {\n return false;\n }\n else if (list->_count == 1)\n {\n list->_count = 0;\n list->_head = nullptr;\n list->_tail = nullptr;\n }\n else if (list->_count > 1)\n {\n item->next->prev = nullptr;\n list->_head = item->next;\n\n list->_count--;\n }\n\n if (value != nullptr)\n {\n *value = item->value;\n }\n\n return true;\n}\n\nvoid list_pushback(List *list, void *value)\n{\n ListItem *item = __create(ListItem);\n\n item->prev = nullptr;\n item->next = nullptr;\n item->value = value;\n\n list->_count++;\n\n if (list->_tail == nullptr)\n {\n list->_tail = item;\n list->_head = item;\n }\n else\n {\n list->_tail->next = item;\n item->prev = list->_tail;\n list->_tail = item;\n }\n}\n\nvoid list_pushback_copy(List *list, void *value, size_t size)\n{\n void *copy = malloc(size);\n memcpy(copy, value, size);\n list_pushback(list, copy);\n}\n\nbool list_popback(List *list, void **value)\n{\n ListItem *item = list->_tail;\n\n if (list->_count == 0)\n {\n return false;\n }\n else if (list->_count == 1)\n {\n list->_count = 0;\n list->_head = nullptr;\n list->_tail = nullptr;\n }\n else if (list->_count > 1)\n {\n item->prev->next = nullptr;\n list->_tail = item->prev;\n\n list->_count--;\n }\n\n if (value != nullptr)\n {\n *value = item->value;\n }\n\n return true;\n}\n\nbool list_remove(List *list, void *value) { return list_remove_with_callback(list, value, nullptr); }\nbool list_remove_with_callback(List *list, void *value, ListDestroyElementCallback callback)\n{\n for (ListItem *item = list->_head; item != nullptr; item = item->next)\n {\n if (item->value == value)\n {\n if (item->prev != nullptr)\n {\n item->prev->next = item->next;\n }\n else\n {\n list->_head = item->next;\n }\n\n if (item->next != nullptr)\n {\n item->next->prev = item->prev;\n }\n else\n {\n list->_tail = item->prev;\n }\n\n list->_count--;\n\n if (callback)\n {\n callback(item->value);\n }\n\n free(item);\n\n return true;\n }\n }\n\n return false;\n}\n\nbool list_remove_at(List *list, int index)\n{\n return list_remove_at_with_callback(list, index, nullptr);\n}\n\nbool list_remove_at_with_callback(List *list, int index, ListDestroyElementCallback callback)\n{\n void *value = nullptr;\n list_peekat(list, index, &value);\n return list_remove_with_callback(list, value, callback);\n}\n\nbool list_contains(List *list, void *value)\n{\n list_foreach(void, item, list)\n {\n if (item == value)\n {\n return true;\n }\n }\n\n return false;\n}\n\nbool list_iterate(List *list, void *target, ListIterationCallback callback)\n{\n ListItem *current = list->_head;\n\n while (current)\n {\n ListItem *next = current->next;\n if (callback(target, current->value) == Iteration::STOP)\n {\n return false;\n }\n current = next;\n }\n\n return true;\n}\n" }, { "alpha_fraction": 0.6892123222351074, "alphanum_fraction": 0.6977739930152893, "avg_line_length": 23.87234115600586, "blob_id": "37ebe968dd389205f4fff7a7c7ee748eaa32adc7", "content_id": "5cb10358d08805082aa2737a7648d455fbde6e58", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1168, "license_type": "permissive", "max_line_length": 102, "num_lines": 47, "path": "/libraries/libwidget/dialog/MessageBox.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Container.h>\n#include <libwidget/Label.h>\n#include <libwidget/Spacer.h>\n\n#include <libwidget/dialog/MessageBox.h>\n\nDialogResult MessageBox::create_and_show(String title, String message)\n{\n return create_and_show(title, message, Icon::get(\"info\"), DialogButton::OK);\n}\n\nDialogResult MessageBox::create_and_show(String title, String message, RefPtr<Icon> icon)\n{\n return create_and_show(title, message, icon, DialogButton::OK);\n}\n\nDialogResult MessageBox::create_and_show(String title, String message, RefPtr<Icon> icon, int buttons)\n{\n MessageBox dialog;\n\n dialog.icon(icon);\n dialog.title(title);\n dialog.message(message);\n dialog.buttons(buttons);\n\n return dialog.show();\n}\n\nvoid MessageBox::render(Window *window)\n{\n window->icon(_icon);\n\n window->size(Vec2i(300, 200));\n\n window->root()->layout(VFLOW(0));\n window->root()->insets(Insetsi(8));\n\n auto message_label = new Label(window->root(), _message, Anchor::CENTER);\n message_label->flags(Widget::FILL);\n\n auto container = new Container(window->root());\n container->layout(HFLOW(4));\n\n new Spacer(container);\n\n create_buttons(container);\n}" }, { "alpha_fraction": 0.5240700244903564, "alphanum_fraction": 0.5317286849021912, "avg_line_length": 23.675676345825195, "blob_id": "2008aae12649c6055a7293514e774931c95fba4d", "content_id": "9c0cb77ffc84840b4adc0de83ba0fb96c46b911c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 914, "license_type": "permissive", "max_line_length": 80, "num_lines": 37, "path": "/kernel/modules/Modules.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n/* modules.c : kernel modules/ramdisk loader */\n\n#include <libsystem/Logger.h>\n#include <string.h>\n\n#include \"kernel/modules/Modules.h\"\n\nvoid module_load(Module *module)\n{\n if (strcmp(\"ramdisk\", module->command_line) == 0)\n {\n ramdisk_load(module);\n }\n else\n {\n logger_warn(\"Unknow module '%s'!\", module->command_line);\n }\n}\n\nvoid modules_initialize(Handover *handover)\n{\n logger_info(\"Loading modules:\");\n for (size_t i = 0; i < handover->modules_size; i++)\n {\n Module *module = &handover->modules[i];\n\n logger_info(\"\\tModule %d: %08x-%08x: %s\",\n i,\n module->range.base(),\n module->range.base() + module->range.size() - 1,\n module->command_line);\n\n module_load(module);\n }\n\n logger_info(\"%d module loaded!\", handover->modules_size);\n}\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 9, "blob_id": "2c3d6b9987c15d0fcae7acd7158a8372c50522f2", "content_id": "52a5b3ffa3c1f018a5802945239e69218814e88b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 120, "license_type": "permissive", "max_line_length": 26, "num_lines": 12, "path": "/libraries/libwidget/Screen.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Rect.h>\n\nnamespace Screen\n{\n\nRecti bound();\n\nvoid bound(Recti);\n\n} // namespace Screen\n" }, { "alpha_fraction": 0.6801801919937134, "alphanum_fraction": 0.6801801919937134, "avg_line_length": 29.272727966308594, "blob_id": "b07a028c34402df519648289b699c3237ea076a1", "content_id": "ff860f083862b071a342923fd4b749e4ef87b9eb", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 666, "license_type": "permissive", "max_line_length": 96, "num_lines": 22, "path": "/kernel/filesystem/DevicesFileSystem.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Paths.h>\n#include <libsystem/Logger.h>\n\n#include \"kernel/devices/Device.h\"\n#include \"kernel/devices/Devices.h\"\n#include \"kernel/filesystem/DevicesFileSystem.h\"\n#include \"kernel/node/Device.h\"\n#include \"kernel/scheduling/Scheduler.h\"\n\nvoid devices_filesystem_initialize()\n{\n auto &domain = scheduler_running()->domain();\n domain.mkdir(Path::parse(DEVICE_PATH));\n\n device_iterate([&](auto device) {\n String path = device->path();\n logger_info(\"Mounting %s to %s\", device->address().as_static_cstring(), path.cstring());\n domain.link(Path::parse(path), make<FsDevice>(device));\n\n return Iteration::CONTINUE;\n });\n}\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7283950448036194, "avg_line_length": 15.199999809265137, "blob_id": "be1d753ef487e71b198b19cee1b76b3159895ce2", "content_id": "a9338d8e6f1b96bc880e13a9311d4552357231e3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 81, "license_type": "permissive", "max_line_length": 39, "num_lines": 5, "path": "/libraries/libgraphic/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += GRAPHIC\n\nGRAPHIC_NAME = graphic\n\nGRAPHIC_CXXFLAGS=-O3 -mmmx -msse -msse2\n" }, { "alpha_fraction": 0.517760157585144, "alphanum_fraction": 0.5185959339141846, "avg_line_length": 20.08370018005371, "blob_id": "b767adf51e37dacf7c2492f1c3073a24420c9733", "content_id": "fa73e3302e6132dc59f29041d04ec34d8c7385ef", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4786, "license_type": "permissive", "max_line_length": 115, "num_lines": 227, "path": "/libraries/libsystem/io_new/Format.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Scanner.h>\n\n#include <libsystem/io_new/Writer.h>\n\nclass String;\n\nnamespace System\n{\n\nstruct Formating\n{\n enum Align\n {\n LEFT,\n CENTER,\n RIGHT,\n };\n\n enum Type\n {\n DEFAULT,\n STRING,\n CHARACTER,\n BINARY,\n DECIMAL,\n OCTAL,\n HEXADECIMAL,\n };\n\n bool prefix;\n Type type = DEFAULT;\n\n static Formating parse(Scanner &scanner)\n {\n Formating format{};\n\n scanner.skip('{');\n\n auto parse_type = [&]() {\n switch (scanner.current())\n {\n case 's':\n format.type = STRING;\n break;\n\n case 'c':\n format.type = CHARACTER;\n break;\n\n case 'b':\n format.type = BINARY;\n break;\n\n case 'd':\n format.type = DECIMAL;\n break;\n\n case 'o':\n format.type = OCTAL;\n break;\n\n case 'x':\n format.type = HEXADECIMAL;\n break;\n\n default:\n break;\n }\n };\n\n if (scanner.current_is(\"scbdox\"))\n {\n parse_type();\n scanner.foreward();\n }\n\n while (!scanner.ended() && scanner.current() != '}')\n {\n\n scanner.foreward();\n }\n\n scanner.skip('}');\n\n return format;\n }\n};\n\nclass Format\n{\npublic:\n virtual ResultOr<size_t> format(Writer &writer);\n};\n\ntemplate <typename T>\nconcept Formatable = IsBaseOf<Format, T>::value || requires(Writer &writer, const Formating &formating, const T &t)\n{\n format(writer, formating, t);\n};\n\nResultOr<size_t> format(Writer &, const Formating &, char);\n\nResultOr<size_t> format(Writer &, const Formating &, unsigned char);\n\nResultOr<size_t> format(Writer &, const Formating &, short int);\n\nResultOr<size_t> format(Writer &, const Formating &, unsigned short int);\n\nResultOr<size_t> format(Writer &, const Formating &, int);\n\nResultOr<size_t> format(Writer &, const Formating &, unsigned int);\n\nResultOr<size_t> format(Writer &, const Formating &, long int);\n\nResultOr<size_t> format(Writer &, const Formating &, unsigned long int);\n\nResultOr<size_t> format(Writer &, const Formating &, float);\n\nResultOr<size_t> format(Writer &, const Formating &, double);\n\nResultOr<size_t> format(Writer &, const Formating &, const char *);\n\nResultOr<size_t> format(Writer &, const Formating &, const String);\n\nstatic inline ResultOr<size_t> format(Writer &writer, Scanner &scanner)\n{\n size_t written = 0;\n\n while (!scanner.ended())\n {\n auto result = writer.write(scanner.current());\n\n if (result != SUCCESS)\n {\n return result;\n }\n\n written += 1;\n scanner.foreward();\n }\n\n return written;\n}\n\ntemplate <Formatable First, Formatable... Args>\nstatic inline ResultOr<size_t> format(Writer &writer, Scanner &scanner, First first, Args... args)\n{\n size_t written = 0;\n\n while (!(scanner.ended() || scanner.current() == '{'))\n {\n auto result = writer.write(scanner.current());\n\n if (result != SUCCESS)\n {\n return result;\n }\n\n written += 1;\n scanner.foreward();\n }\n\n if (scanner.current() == '{')\n {\n auto formating = Formating::parse(scanner);\n\n auto format_proxy = [&]() {\n if constexpr (IsBaseOf<Format, First>::value)\n {\n return first.format(writer);\n }\n else if constexpr (requires(const First &t) {\n format(writer, formating, t);\n })\n {\n return format(writer, formating, first);\n }\n else\n {\n ASSERT_NOT_REACHED();\n }\n };\n\n auto format_result = format_proxy();\n\n if (format_result)\n {\n written += *format_result;\n }\n else\n {\n return format_result.result();\n }\n }\n\n if (!scanner.ended())\n {\n auto format_result = format(writer, scanner, forward<Args>(args)...);\n\n if (format_result)\n {\n return written + *format_result;\n }\n else\n {\n return format_result.result();\n }\n }\n\n return written;\n}\n\ntemplate <Formatable... Args>\nstatic inline ResultOr<size_t> format(Writer &writer, const char *fmt, Args... args)\n{\n StringScanner scan{fmt, strlen(fmt)};\n return format(writer, scan, forward<Args>(args)...);\n}\n\nstatic inline ResultOr<size_t> format(Writer &writer, const char *fmt)\n{\n return writer.write(fmt);\n}\n\n} // namespace System\n" }, { "alpha_fraction": 0.5153152942657471, "alphanum_fraction": 0.570270299911499, "avg_line_length": 18.821428298950195, "blob_id": "6194bb92dc9a45633400541421aa7014e25a8031", "content_id": "070be0a47cceb434e47d1267c6009bef7378cf69", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 94, "num_lines": 56, "path": "/kernel/drivers/PCSpeaker.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"kernel/drivers/PCSpeaker.h\"\n#include \"kernel/scheduling/Scheduler.h\"\n#include \"kernel/tasking/Task.h\"\n\nPCSpeaker::PCSpeaker(DeviceAddress address) : LegacyDevice(address, DeviceClass::PCSPEAKER) {}\n\nPCSpeaker::~PCSpeaker() {}\n\nvoid PCSpeaker::note(int length, int freq)\n{\n\n uint8_t t;\n\n if (length == 0)\n {\n t = in8(0x61) & 0xFC;\n out8(0x61, t);\n return;\n }\n\n uint32_t div = 11931800 / freq;\n\n out8(0x43, 0xb6);\n out8(0x42, (uint8_t)(div));\n out8(0x42, (uint8_t)(div >> 8));\n\n t = in8(0x61);\n out8(0x61, t | 0x3);\n\n if (length > 0)\n {\n\n task_sleep(scheduler_running(), length);\n\n t = in8(0x61) & 0xFC;\n out8(0x61, t);\n }\n}\n\nResultOr<size_t> PCSpeaker::write(size64_t offset, const void *buffer, size_t size)\n{\n __unused(offset);\n if (!size % (sizeof(struct Speaker)))\n {\n return 0;\n }\n\n struct Speaker *s = (struct Speaker *)buffer;\n while ((uintptr_t)s < (uintptr_t)buffer + size)\n {\n note(s->length, s->frequency);\n s++;\n }\n\n return (uintptr_t)s - (uintptr_t)buffer;\n}\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 34, "blob_id": "416567c6e9ae19dc6837b1120d8c9c9d26f6ec87", "content_id": "9dc538652681e1acba71d5abc3cdfdc4d75734b4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 35, "license_type": "permissive", "max_line_length": 34, "num_lines": 1, "path": "/libraries/libsystem/utils/NumberParser.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libutils/NumberParser.h>\n" }, { "alpha_fraction": 0.6317991614341736, "alphanum_fraction": 0.6485355496406555, "avg_line_length": 13.9375, "blob_id": "71d260cebcbfde784389a0718b040f72da4e9cf8", "content_id": "946979c57c173ffe59090e640a71efe4f9ca0241", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 239, "license_type": "permissive", "max_line_length": 57, "num_lines": 16, "path": "/libraries/libc/setjmp.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n__BEGIN_HEADER\n\n/* i386 */\n#define _JBLEN 6\n\ntypedef int jmp_buf[_JBLEN];\n\n__attribute__((noreturn)) void longjmp(jmp_buf j, int r);\n\n__attribute__((returns_twice)) int setjmp(jmp_buf j);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.3787234127521515, "alphanum_fraction": 0.394946813583374, "avg_line_length": 15.860986709594727, "blob_id": "f072573e7be53fbc274390d42863a35f7eb81d84", "content_id": "1d47e18ca3be344689a9d281c9920f2275bc514a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3760, "license_type": "permissive", "max_line_length": 66, "num_lines": 223, "path": "/libraries/libsystem/io_new/Scanner.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/InlineRingBuffer.h>\n\n#include <libsystem/io_new/Reader.h>\n\nnamespace System\n{\n\ntemplate <typename TReader>\nclass Scanner final\n{\nprivate:\n static constexpr int PEEK_SIZE = 16;\n\n TReader _reader;\n utils::InlineRingBuffer<uint8_t, 16> _peek{};\n bool _is_end_of_file = false;\n\n void refill()\n {\n auto read_result = _reader.read_byte();\n\n if (!read_result)\n {\n _is_end_of_file = true;\n return;\n }\n\n _peek.put(*read_result);\n }\n\npublic:\n Scanner(TReader reader) : _reader(reader)\n {\n }\n\n bool ended()\n {\n if (_peek.empty())\n {\n refill();\n }\n\n return _is_end_of_file;\n }\n\n void foreward()\n {\n if (_peek.empty())\n {\n refill();\n }\n\n if (!ended())\n {\n _peek.get();\n }\n }\n\n char peek(size_t peek)\n {\n while (!ended() && peek >= _peek.used())\n {\n refill();\n }\n\n if (ended())\n {\n return '\\0';\n }\n\n return _peek.peek(peek);\n }\n\n bool do_continue()\n {\n return !ended();\n }\n\n void foreward(size_t n)\n {\n for (size_t i = 0; i < n; i++)\n {\n foreward();\n }\n }\n\n void foreward_codepoint()\n {\n if ((current() & 0xf8) == 0xf0)\n {\n foreward(4);\n }\n else if ((current() & 0xf0) == 0xe0)\n {\n foreward(3);\n }\n else if ((current() & 0xe0) == 0xc0)\n {\n foreward(2);\n }\n else\n {\n foreward(1);\n }\n }\n\n char current()\n {\n return peek(0);\n }\n\n Codepoint current_codepoint()\n {\n size_t size = 0;\n Codepoint codepoint = peek(0);\n\n if ((current() & 0xf8) == 0xf0)\n {\n size = 4;\n codepoint = (0x07 & codepoint) << 18;\n }\n else if ((current() & 0xf0) == 0xe0)\n {\n size = 3;\n codepoint = (0x0f & codepoint) << 12;\n }\n else if ((current() & 0xe0) == 0xc0)\n {\n codepoint = (0x1f & codepoint) << 6;\n size = 2;\n }\n\n for (size_t i = 1; i < size; i++)\n {\n codepoint |= (0x3f & peek(i)) << (6 * (size - i - 1));\n }\n\n return codepoint;\n }\n\n bool current_is(const char *what)\n {\n return current_is(what, strlen(what));\n }\n\n bool current_is(const char *what, size_t size)\n {\n for (size_t i = 0; i < size; i++)\n {\n if (current() == what[i])\n {\n return true;\n }\n }\n\n return false;\n }\n\n bool current_is_word(const char *word)\n {\n for (size_t i = 0; word[i]; i++)\n {\n if (peek(i) != word[i])\n {\n return false;\n }\n }\n\n return true;\n }\n\n void eat(const char *what)\n {\n while (current_is(what) &&\n do_continue())\n {\n foreward();\n }\n }\n\n bool skip(char chr)\n {\n if (current() == chr)\n {\n foreward();\n\n return true;\n }\n\n return false;\n }\n\n bool skip(const char *chr)\n {\n if (current_is(chr))\n {\n foreward();\n\n return true;\n }\n\n return false;\n }\n\n bool skip_word(const char *word)\n {\n if (current_is_word(word))\n {\n for (size_t i = 0; i < strlen(word); i++)\n {\n foreward();\n }\n\n return true;\n }\n\n return false;\n }\n};\n\n} // namespace System\n" }, { "alpha_fraction": 0.5048754215240479, "alphanum_fraction": 0.5232936143875122, "avg_line_length": 19.977272033691406, "blob_id": "7e08c9e56f790985752be8d4fc79d9f105914348", "content_id": "2604b8666f35aa6ebb0327b2f2b8b5be738d2a8c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 923, "license_type": "permissive", "max_line_length": 74, "num_lines": 44, "path": "/apps/utilities/hexdump.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/Stream.h>\n\n#include <stdio.h>\n\nint main(int argc, char **argv)\n{\n if (argc == 1)\n {\n printf(\"Usage: %s FILENAME\", argv[0]);\n return PROCESS_FAILURE;\n }\n\n Stream *stream = stream_open(argv[1], OPEN_READ);\n\n if (handle_has_error(stream))\n {\n handle_printf_error(stream, \"Couldn't read %s\", argv[1]);\n return PROCESS_FAILURE;\n }\n\n size_t read;\n size_t offset = 0;\n uint8_t buffer[16];\n\n while ((read = stream_read(stream, buffer, 16)) != 0)\n {\n printf(\"%08x \", (unsigned int)offset * 16);\n for (unsigned char i : buffer)\n {\n printf(\"%02x \", i);\n }\n\n printf(\"\\n\");\n offset++;\n\n if (handle_has_error(out_stream))\n {\n handle_printf_error(out_stream, \"Couldn't write to stdout\\n\");\n return PROCESS_FAILURE;\n }\n }\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.4632352888584137, "alphanum_fraction": 0.47163864970207214, "avg_line_length": 20.613636016845703, "blob_id": "1bba56efdf6c5d2063760c145d3ade6ea658240f", "content_id": "46a220047d9273adb24437c3262a93c51517c477", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 952, "license_type": "permissive", "max_line_length": 72, "num_lines": 44, "path": "/libraries/libsystem/system/Memory.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/math/MinMax.h>\n#include <libsystem/system/Memory.h>\n\nvoid memory_zero(void *where, size_t how_many)\n{\n for (size_t i = 0; i < how_many; i++)\n {\n ((char *)where)[i] = 0;\n }\n}\n\nvoid memory_set(void *where, char what, size_t how_many)\n{\n for (size_t i = 0; i < how_many; i++)\n {\n ((char *)where)[i] = what;\n }\n}\n\nvoid memory_copy(void *from, size_t from_size, void *to, size_t to_size)\n{\n for (size_t i = 0; i < MIN(from_size, to_size); i++)\n {\n ((char *)to)[i] = ((char *)from)[i];\n }\n}\n\nvoid memory_move(void *from, size_t from_size, void *to, size_t to_size)\n{\n if (to < from)\n {\n for (size_t i = 0; i < MIN(from_size, to_size); i++)\n {\n ((char *)to)[i] = ((char *)from)[i];\n }\n }\n else\n {\n for (size_t i = MIN(from_size, to_size); i > 0; i++)\n {\n ((char *)to)[i - 1] = ((char *)from)[i - 1];\n }\n }\n}\n" }, { "alpha_fraction": 0.6946386694908142, "alphanum_fraction": 0.6946386694908142, "avg_line_length": 15.538461685180664, "blob_id": "585cb3ecd15f1eac71e169771630ee5bf402ea72", "content_id": "098356a5f47af2c9c93c3ed529d04b41d3d59ac1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 429, "license_type": "permissive", "max_line_length": 69, "num_lines": 26, "path": "/libraries/libfilepicker/dialogs/FilePicker.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/dialog/Dialog.h>\n\n#include <libfilepicker/model/Navigation.h>\n\nnamespace filepicker\n{\n\nclass Dialog : public ::Dialog\n{\nprivate:\n RefPtr<Navigation> _navigation = nullptr;\n Optional<String> _selected_file{};\n\npublic:\n Dialog();\n\n ~Dialog();\n\n Optional<String> selected_file() const { return _selected_file; }\n\n virtual void render(Window *window);\n};\n\n} // namespace filepicker" }, { "alpha_fraction": 0.44337016344070435, "alphanum_fraction": 0.45303866267204285, "avg_line_length": 17.445859909057617, "blob_id": "b88806d17f419c3503cb768dd9af3db4804c56ea", "content_id": "530229ea1b7f4e5950facd6936208b17e4990388", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2896, "license_type": "permissive", "max_line_length": 74, "num_lines": 157, "path": "/libraries/libutils/StringBuilder.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <assert.h>\n#include <libsystem/Common.h>\n#include <libsystem/math/MinMax.h>\n#include <libutils/unicode/Codepoint.h>\n#include <libutils/String.h>\n#include <libutils/Vector.h>\n\nclass StringBuilder\n{\nprivate:\n size_t _used = 0;\n size_t _size = 0;\n char *_buffer = nullptr;\n\n __noncopyable(StringBuilder);\n __nonmovable(StringBuilder);\n\npublic:\n size_t length() const\n {\n return _used;\n }\n\n StringBuilder() : StringBuilder(16)\n {\n }\n\n StringBuilder(size_t preallocated)\n {\n preallocated = MAX(preallocated, 16);\n\n _buffer = new char[preallocated];\n _buffer[0] = '\\0';\n _size = preallocated;\n _used = 0;\n }\n\n ~StringBuilder()\n {\n if (_buffer)\n delete[] _buffer;\n }\n\n String finalize()\n {\n if (!_buffer)\n {\n return \"\";\n }\n\n char *result = _buffer;\n size_t size = _used;\n\n _buffer = nullptr;\n _used = 0;\n _size = 0;\n\n return String(make<StringStorage>(AdoptTag::ADOPT, result, size));\n }\n\n String intermediate()\n {\n return String(make<StringStorage>(_buffer, _used));\n }\n\n StringBuilder &append(String string)\n {\n for (size_t i = 0; i < string.length(); i++)\n {\n append(string[i]);\n }\n\n return *this;\n }\n\n StringBuilder &append(const char *str)\n {\n if (!str)\n {\n append(\"<null>\");\n }\n else\n {\n for (size_t i = 0; str[i]; i++)\n {\n append(str[i]);\n }\n }\n\n return *this;\n }\n\n StringBuilder &append(const char *str, size_t size)\n {\n if (!str)\n {\n append(\"<null>\");\n }\n else\n {\n for (size_t i = 0; i < size; i++)\n {\n append(str[i]);\n }\n }\n\n return *this;\n }\n\n StringBuilder &append_codepoint(Codepoint cp)\n {\n char buffer[5];\n codepoint_to_utf8(cp, (uint8_t *)buffer);\n append(buffer);\n\n return *this;\n }\n\n StringBuilder &append(char chr)\n {\n if (_size == 0)\n {\n _buffer = new char[16];\n _size = 16;\n _used = 0;\n }\n\n if (_used + 1 == _size)\n {\n auto new_size = _size + _size / 4;\n auto new_buffer = new char[new_size];\n memcpy(new_buffer, _buffer, _size);\n delete[] _buffer;\n\n _size = new_size;\n _buffer = new_buffer;\n }\n\n _buffer[_used] = chr;\n _buffer[_used + 1] = '\\0';\n _used++;\n\n return *this;\n }\n\n StringBuilder &rewind(size_t how_many)\n {\n assert(_used >= how_many);\n\n _used -= how_many;\n _buffer[_used] = '\\0';\n\n return *this;\n }\n};\n" }, { "alpha_fraction": 0.667870044708252, "alphanum_fraction": 0.6750902533531189, "avg_line_length": 22.08333396911621, "blob_id": "ff8091e79dab06a57dcd633d59c655d571137157", "content_id": "3e961ef225a0143b2066f414cd4f9c3c2811501a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1108, "license_type": "permissive", "max_line_length": 101, "num_lines": 48, "path": "/kernel/memory/MMIO.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Logger.h>\n\n#include \"archs/VirtualMemory.h\"\n\n#include \"kernel/interrupts/Interupts.h\"\n#include \"kernel/memory/MMIO.h\"\n#include \"kernel/memory/Physical.h\"\n\nMMIORange::MMIORange()\n{\n}\n\nMMIORange::MMIORange(size_t size)\n{\n size = PAGE_ALIGN_UP(size);\n\n InterruptsRetainer retainer;\n\n _own_physical_range = true;\n _physical_range = {physical_alloc(size)};\n _virtual_range = {arch_virtual_alloc(arch_kernel_address_space(), _physical_range, MEMORY_NONE)};\n}\n\nMMIORange::MMIORange(MemoryRange range)\n{\n InterruptsRetainer retainer;\n\n _physical_range = {range};\n _virtual_range = {arch_virtual_alloc(arch_kernel_address_space(), _physical_range, MEMORY_NONE)};\n\n logger_info(\"Created MMIO region %08x-%08x mapped to %08x-%08x\",\n range.base(), range.end(), _virtual_range.base(), _virtual_range.end());\n}\n\nMMIORange::~MMIORange()\n{\n if (empty())\n return;\n\n InterruptsRetainer retainer;\n\n arch_virtual_free(arch_kernel_address_space(), _virtual_range);\n\n if (!_own_physical_range)\n return;\n\n physical_free(_physical_range);\n}\n" }, { "alpha_fraction": 0.7433537840843201, "alphanum_fraction": 0.7433537840843201, "avg_line_length": 27.764705657958984, "blob_id": "b51dcd4d81d48545339b7766e040ce4e3ea5eac6", "content_id": "7be1294d92c549d50eac4fc0b5ddc5aa5673cd09", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 978, "license_type": "permissive", "max_line_length": 93, "num_lines": 34, "path": "/kernel/tasking/Task-Memory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"kernel/memory/MemoryObject.h\"\n#include \"kernel/tasking/Task.h\"\n\nstruct MemoryMapping\n{\n MemoryObject *object;\n\n uintptr_t address;\n size_t size;\n\n MemoryRange range() { return {address, size}; }\n};\n\nMemoryMapping *task_memory_mapping_create(Task *task, MemoryObject *memory_object);\n\nvoid task_memory_mapping_destroy(Task *task, MemoryMapping *memory_mapping);\n\nMemoryMapping *task_memory_mapping_by_address(Task *task, uintptr_t address);\n\nResult task_memory_alloc(Task *task, size_t size, uintptr_t *out_address);\n\nResult task_memory_map(Task *task, uintptr_t address, size_t size, MemoryFlags flags);\n\nResult task_memory_free(Task *task, uintptr_t address);\n\nResult task_memory_include(Task *task, int handle, uintptr_t *out_address, size_t *out_size);\n\nResult task_memory_get_handle(Task *task, uintptr_t address, int *out_handle);\n\nvoid *task_switch_address_space(Task *task, void *address_space);\n\nsize_t task_memory_usage(Task *task);\n" }, { "alpha_fraction": 0.6520231366157532, "alphanum_fraction": 0.6520231366157532, "avg_line_length": 22.37837791442871, "blob_id": "8494f6fc11b79427689b8a90a0beef041f5f4997", "content_id": "66d4842572d2612c57955b02f106d5ae950f7edf", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 865, "license_type": "permissive", "max_line_length": 110, "num_lines": 37, "path": "/libraries/libsettings/ServerConnection.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libipc/Peer.h>\n#include <libsettings/Protocol.h>\n\nnamespace Settings\n{\n\nclass ServerConnection : public ipc::Peer<Protocol>\n{\npublic:\n Callback<void(const Path &path, const json::Value &value)> on_notify;\n\n static OwnPtr<ServerConnection> open()\n {\n return own<ServerConnection>(socket_connect(\"/Session/settings.ipc\"));\n }\n\n ServerConnection(Connection *connection) : Peer(connection)\n {\n }\n\n ResultOr<Message> request(Message message, Message::Type expected)\n {\n return send_and_wait_for(message, [&](const Message &incoming) { return incoming.type == expected; });\n }\n\n void handle_message(const Message &message) override\n {\n if (message.type == Message::SERVER_NOTIFY)\n {\n on_notify(*message.path, *message.payload);\n }\n }\n};\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.6742950677871704, "alphanum_fraction": 0.6742950677871704, "avg_line_length": 32.52054977416992, "blob_id": "009728cada5d0bd7935f8222cae81830e333aa93", "content_id": "f04d95f8de0303d83303f82ab8140510d4eea4bc", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2447, "license_type": "permissive", "max_line_length": 109, "num_lines": 73, "path": "/kernel/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "KERNEL_SOURCES += \\\n\t$(wildcard kernel/*.cpp) \\\n\t$(wildcard kernel/*/*.cpp) \\\n\t$(wildcard kernel/*/*/*.cpp)\n\nKERNEL_ASSEMBLY_SOURCES += \\\n\t$(wildcard kernel/*.s) \\\n\t$(wildcard kernel/*/*.s)\n\nKERNEL_LIBRARIES_SOURCES = \\\n\t$(wildcard libraries/libc/string.cpp) \\\n\t$(wildcard libraries/libc/assert.cpp) \\\n\t$(wildcard libraries/libc/ctype.cpp) \\\n\t$(wildcard libraries/libc/skift/NumberFormatter.cpp) \\\n\t$(wildcard libraries/libc/skift/Printf.cpp) \\\n\t$(wildcard libraries/libc/skift/Time.cpp) \\\n\t$(wildcard libraries/libc/stdlib/allocator.cpp) \\\n\t$(wildcard libraries/libc/stdio/sprintf.cpp) \\\n\t$(wildcard libraries/libc/cxx/new-delete.cpp) \\\n\t$(wildcard libraries/libfile/TARArchive.cpp) \\\n\t$(wildcard libraries/libsystem/json/*.cpp) \\\n\t$(wildcard libraries/libsystem/*.cpp) \\\n\t$(wildcard libraries/libsystem/compression/*.cpp) \\\n\t$(wildcard libraries/libsystem/io/*.cpp) \\\n\t$(wildcard libraries/libsystem/unicode/*.cpp) \\\n\t$(wildcard libraries/libsystem/process/*.cpp) \\\n\t$(wildcard libraries/libsystem/utils/*.cpp) \\\n\t$(wildcard libraries/libsystem/core/*.cpp) \\\n\t$(wildcard libraries/libsystem/thread/*.cpp) \\\n\t$(wildcard libraries/libsystem/system/*.cpp) \\\n\nKERNEL_BINARY = $(CONFIG_BUILD_DIRECTORY)/kernel.bin\n\nKERNEL_OBJECTS = \\\n\t$(patsubst %.cpp, $(CONFIG_BUILD_DIRECTORY)/%.o, $(KERNEL_SOURCES)) \\\n\t$(patsubst %.s, $(CONFIG_BUILD_DIRECTORY)/%.s.o, $(KERNEL_ASSEMBLY_SOURCES)) \\\n\t$(patsubst libraries/%.cpp, $(CONFIG_BUILD_DIRECTORY)/kernel/%.o, $(KERNEL_LIBRARIES_SOURCES))\n\nKERNEL_CXXFLAGS += \\\n\t$(CXXFLAGS) \t\\\n\t-fno-rtti \\\n\t-fno-exceptions \\\n\t-ffreestanding \\\n\t-nostdlib \\\n\t-D__KERNEL__ \\\n\t-DCONFIG_KEYBOARD_LAYOUT=\\\"\"${CONFIG_KEYBOARD_LAYOUT}\"\\\"\n\nOBJECTS += $(KERNEL_OBJECTS)\n\n$(CONFIG_BUILD_DIRECTORY)/kernel/%.o: libraries/%.cpp\n\t$(DIRECTORY_GUARD)\n\t@echo [KERNEL] [CXX] $<\n\t@$(CXX) $(KERNEL_CXXFLAGS) -c -o $@ $<\n\n$(CONFIG_BUILD_DIRECTORY)/kernel/%.o: kernel/%.cpp\n\t$(DIRECTORY_GUARD)\n\t@echo [KERNEL] [CXX] $<\n\t@$(CXX) $(KERNEL_CXXFLAGS) -ffreestanding -nostdlib -c -o $@ $<\n\n$(CONFIG_BUILD_DIRECTORY)/archs/%.o: archs/%.cpp\n\t$(DIRECTORY_GUARD)\n\t@echo [KERNEL] [CXX] $<\n\t@$(CXX) $(KERNEL_CXXFLAGS) -c -o $@ $<\n\n$(CONFIG_BUILD_DIRECTORY)/archs/%.s.o: archs/%.s\n\t$(DIRECTORY_GUARD)\n\t@echo [KERNEL] [AS] $<\n\t@$(AS) $(ASFLAGS) $^ -o $@\n\n$(KERNEL_BINARY): $(KERNEL_OBJECTS)\n\t$(DIRECTORY_GUARD)\n\t@echo [KERNEL] [LD] $(KERNEL_BINARY)\n\t@$(CXX) $(LDFLAGS) $(KERNEL_LDFLAGS) -T archs/$(CONFIG_ARCH)/link.ld -o $@ -ffreestanding $^ -nostdlib -lgcc\n" }, { "alpha_fraction": 0.5567010045051575, "alphanum_fraction": 0.5573883056640625, "avg_line_length": 17.653846740722656, "blob_id": "d981c112649264a9d257f2e548418d5ed1dcfdbe", "content_id": "55b3e37adb10e3450d1844ceba3eed587ee72dc1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1455, "license_type": "permissive", "max_line_length": 61, "num_lines": 78, "path": "/libraries/libsettings/Path.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libutils/ScannerUtils.h>\n\n#include <libsettings/Path.h>\n\nnamespace Settings\n{\n\nPath Path::parse(Scanner &scan)\n{\n Path path;\n\n auto parse_string = [&](char sep) {\n StringBuilder build;\n\n while (scan.current() != sep && scan.do_continue())\n {\n build.append(scan.current());\n scan.foreward();\n }\n\n return build.finalize();\n };\n\n path.domain = parse_string(':');\n\n if (!scan.skip(':'))\n {\n return path;\n }\n\n path.bundle = parse_string('.');\n\n if (!scan.skip('.'))\n {\n return path;\n }\n\n path.key = parse_string('\\0');\n\n return path;\n}\n\nPath Path::parse(const String &str)\n{\n StringScanner scan{str.cstring(), str.length()};\n return parse(scan);\n};\n\nPath Path::parse(const char *str, size_t size)\n{\n StringScanner scan{str, size};\n return parse(scan);\n};\n\nvoid Path::prettify(Prettifier &pretty) const\n{\n pretty.append(domain);\n pretty.append(':');\n pretty.append(bundle);\n pretty.append('.');\n pretty.append(key);\n}\n\nbool Path::match(const Path &other) const\n{\n return (other.domain == \"*\" || other.domain == domain) &&\n (other.bundle == \"*\" || other.bundle == bundle) &&\n (other.key == \"*\" || other.key == key);\n}\n\nbool Path::operator==(const Path &other)\n{\n return domain == other.domain &&\n bundle == other.domain &&\n key == other.key;\n}\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.6269429922103882, "alphanum_fraction": 0.6580311059951782, "avg_line_length": 18.299999237060547, "blob_id": "5d59603eddb1f2a703492b822526687e3e3aa4fa", "content_id": "e9084d8d007fcaee81515b863f3fc5dbb70ccd97", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 193, "license_type": "permissive", "max_line_length": 32, "num_lines": 10, "path": "/kernel/bus/VirtioAddress.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nenum VirtioAddress\n{\n VIRTIO_DEVICE_NETWORK = 1,\n VIRTIO_DEVICE_BLOCK = 2,\n VIRTIO_DEVICE_CONSOLE = 3,\n VIRTIO_DEVICE_ENTROPY = 4,\n VIRTIO_DEVICE_GRAPHICS = 16,\n};\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 27.600000381469727, "blob_id": "c3801aaf364c458af574558b7779e180e67056fd", "content_id": "54fccf514d8f57c680076dc179f695aef9238f2c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 572, "license_type": "permissive", "max_line_length": 76, "num_lines": 20, "path": "/libraries/libsystem/system/Memory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libsystem/Result.h>\n\nvoid memory_zero(void *where, size_t how_many);\n\nvoid memory_set(void *where, char what, size_t how_many);\n\nvoid memory_copy(void *from, size_t from_size, void *to, size_t to_size);\n\nvoid memory_move(void *from, size_t from_size, void *to, size_t to_size);\n\nResult memory_alloc(size_t size, uintptr_t *out_address);\n\nResult memory_free(uintptr_t address);\n\nResult memory_include(int handle, uintptr_t *out_address, size_t *out_size);\n\nResult memory_get_handle(uintptr_t address, int *out_handle);\n" }, { "alpha_fraction": 0.7732558250427246, "alphanum_fraction": 0.7732558250427246, "avg_line_length": 18.11111068725586, "blob_id": "51b5aeda6a8cdec066dd844cd4e967d0968fd623", "content_id": "70814532bece92cd7cc72649ca02a06e37089e93", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 172, "license_type": "permissive", "max_line_length": 44, "num_lines": 9, "path": "/libraries/libsystem/cmdline/History.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/unicode/UnicodeString.h>\n\nvoid history_commit(UnicodeString *text);\n\nUnicodeString *history_peek(size_t index);\n\nsize_t history_length();\n" }, { "alpha_fraction": 0.7023809552192688, "alphanum_fraction": 0.7023809552192688, "avg_line_length": 11, "blob_id": "1aeb43ea59b4d48e532276b186e916332250f0b3", "content_id": "d123e54fe1a0af11e7039356ac43f6593d92c40b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 84, "license_type": "permissive", "max_line_length": 24, "num_lines": 7, "path": "/archs/x86/kernel/PIC.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nvoid pic_initialize();\n\nvoid pic_ack(int intno);\n\nvoid pic_disable();\n" }, { "alpha_fraction": 0.7120000123977661, "alphanum_fraction": 0.7120000123977661, "avg_line_length": 16.85714340209961, "blob_id": "1fbad1d28db0c20b982018642e6f294c38096dd7", "content_id": "acf3c92146d346e8eee15723186444a790481150", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 125, "license_type": "permissive", "max_line_length": 37, "num_lines": 7, "path": "/libraries/libsystem/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += SYSTEM\n\nSYSTEM_NAME = system\nSYSTEM_CXXFLAGS = \\\n\t-fno-tree-loop-distribute-patterns \\\n\t-fno-rtti \\\n\t-fno-exceptions\n" }, { "alpha_fraction": 0.6150907278060913, "alphanum_fraction": 0.6609359979629517, "avg_line_length": 36.39285659790039, "blob_id": "04321bb88f01baedd6021fa9984d28a72951bd16", "content_id": "26da80aad9a2ba7163bcf4079f1a83234e0fd765", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1047, "license_type": "permissive", "max_line_length": 84, "num_lines": 28, "path": "/icons/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "ICONS=$(wildcard icons/*.svg)\n\nICONS_AT_18PX = $(patsubst icons/%.svg, $(SYSROOT)/Files/Icons/%@18px.png, $(ICONS))\nICONS_AT_24PX = $(patsubst icons/%.svg, $(SYSROOT)/Files/Icons/%@24px.png, $(ICONS))\nICONS_AT_36PX = $(patsubst icons/%.svg, $(SYSROOT)/Files/Icons/%@36px.png, $(ICONS))\nICONS_AT_48PX = $(patsubst icons/%.svg, $(SYSROOT)/Files/Icons/%@48px.png, $(ICONS))\n\nTARGETS += $(ICONS_AT_18PX) $(ICONS_AT_24PX) $(ICONS_AT_36PX) $(ICONS_AT_48PX)\n\n$(SYSROOT)/Files/Icons/%@18px.png: icons/%.svg\n\t$(DIRECTORY_GUARD)\n\t@echo [ImageMagick] $(notdir $@)\n\t@convert -background none -resize 18x18 $< $@\n\n$(SYSROOT)/Files/Icons/%@24px.png: icons/%.svg\n\t$(DIRECTORY_GUARD)\n\t@echo [ImageMagick] $(notdir $@)\n\t@convert -background none -resize 24x24 $< $@\n\n$(SYSROOT)/Files/Icons/%@36px.png: icons/%.svg\n\t$(DIRECTORY_GUARD)\n\t@echo [ImageMagick] $(notdir $@)\n\t@convert -background none -resize 36x36 $< $@\n\n$(SYSROOT)/Files/Icons/%@48px.png: icons/%.svg\n\t$(DIRECTORY_GUARD)\n\t@echo [ImageMagick] $(notdir $@)\n\t@convert -background none -resize 48x48 $< $@\n" }, { "alpha_fraction": 0.6246498823165894, "alphanum_fraction": 0.6330532431602478, "avg_line_length": 26.461538314819336, "blob_id": "e07b981315f61d4f35615b77a03005a1fe1a035d", "content_id": "d9a49a5a4eedc133c53138154b6d3eadfbc6f87b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1071, "license_type": "permissive", "max_line_length": 123, "num_lines": 39, "path": "/apps/utilities/cp.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/File.h>\n#include <libsystem/io/Filesystem.h>\n#include <libsystem/io/Stream.h>\n#include <libutils/Path.h>\n\n// implementation of cp open a input stream from file to copied and create a new file and open it as output stream and\n// paste all the content into it.\n// Add more options\n// - Create new file\n// - append to already existing file\n// - only copy if file already exists\n// - only logs if used with option -v\n\nint main(int argc, char **argv)\n{\n if (argc == 1)\n {\n stream_format(err_stream, \"%s: Missing file operand\\n\", argv[0]);\n return PROCESS_FAILURE;\n }\n\n if (argc == 2)\n {\n stream_format(err_stream, \"%s: Missing destination file operand after '%s'\\n\", argv[0], argv[1]);\n return PROCESS_FAILURE;\n }\n\n File file{argv[1]};\n\n Result result = file.copy(argv[2]);\n\n if (result != SUCCESS)\n {\n stream_format(err_stream, \"%s: Failed to copy '%s' to '%s': %s\", argv[1], argv[2], get_result_description(result));\n return PROCESS_FAILURE;\n }\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6234263777732849, "alphanum_fraction": 0.6305418610572815, "avg_line_length": 20, "blob_id": "114dd7a6c66bf1a81197ed087a1fb1f903e2a526", "content_id": "5ba7d1c96d622fb898a0d434d8c4e04b3ef8a80f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1827, "license_type": "permissive", "max_line_length": 61, "num_lines": 87, "path": "/tests/test_path.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n#include <libsystem/Assert.h>\n#include <libutils/Path.h>\n\n#define TEST(__func) void __func()\n\nTEST(absolute_path_are_absolute)\n{\n auto p = Path::parse(\"/home/user/local\");\n\n assert(p.absolute());\n}\n\nTEST(absolute_path_are_no_relative)\n{\n auto p = Path::parse(\"/home/user/local\");\n\n assert(!p.relative());\n}\n\nTEST(relative_path_are_not_absolute)\n{\n auto p = Path::parse(\"user/local\");\n\n assert(!p.absolute());\n}\n\nTEST(relative_path_are_relative)\n{\n auto p = Path::parse(\"user/local\");\n\n assert(p.relative());\n}\n\nTEST(same_path_are_equals)\n{\n auto p1 = Path::parse(\"/home/user/local\");\n auto p2 = Path::parse(\"/home/user/local\");\n\n assert(p1 == p2);\n}\n\nTEST(different_path_are_not_equals)\n{\n auto p1 = Path::parse(\"/home/user/local/documents\");\n auto p2 = Path::parse(\"/home/user/local\");\n\n assert(p1 != p2);\n}\n\nTEST(a_path_and_its_string_representation_are_equals)\n{\n auto p = Path::parse(\"/home/user/local\");\n assert(p.string() == \"/home/user/local\");\n}\n\nTEST(path_is_equal_to_its_normalized_counter_part)\n{\n auto p = Path::parse(\"/home/../home/././././user/local\");\n p = p.normalized();\n\n assert(p.string() == \"/home/user/local\");\n}\n\nTEST(joined_path_is_equal_to_its_normalized_counter_part)\n{\n auto p1 = Path::parse(\"/home/\");\n auto p2 = Path::join(p1, \"user/local\");\n\n assert(p2.string() == \"/home/user/local\");\n}\n\nint main(int, char const *[])\n{\n absolute_path_are_absolute();\n absolute_path_are_no_relative();\n relative_path_are_not_absolute();\n relative_path_are_relative();\n same_path_are_equals();\n different_path_are_not_equals();\n a_path_and_its_string_representation_are_equals();\n path_is_equal_to_its_normalized_counter_part();\n joined_path_is_equal_to_its_normalized_counter_part();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6545240879058838, "alphanum_fraction": 0.6650998592376709, "avg_line_length": 20.274999618530273, "blob_id": "1514ebb0418afd489599fcd3d99ab4ce6bea4b44", "content_id": "1a6203cf8a4a5751d89b9e4b1628e601820ebf93", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 851, "license_type": "permissive", "max_line_length": 96, "num_lines": 40, "path": "/libraries/abi/Handle.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Filesystem.h>\n\n#include <libsystem/Result.h>\n\n#define POLL_READ (1 << 0)\n#define POLL_WRITE (1 << 1)\n#define POLL_CONNECT (1 << 2)\n#define POLL_ACCEPT (1 << 3)\n\ntypedef unsigned int PollEvent;\n\nstruct Handle\n{\n int id;\n OpenFlag flags;\n Result result;\n};\n\nstruct HandleSet\n{\n int *handles;\n PollEvent *events;\n size_t count;\n};\n\n#define HANDLE_INVALID_ID (-1)\n\n#define HANDLE(__subclass) ((Handle *)(__subclass))\n\n#define handle_has_error(__handle) (HANDLE(__handle)->result != SUCCESS)\n\n#define handle_error_string(__handle) result_to_string(HANDLE(__handle)->result)\n\n#define handle_get_error(__handle) (HANDLE(__handle)->result)\n\n#define handle_clear_error(__handle) (HANDLE(__handle)->result = SUCCESS)\n\n#define handle_has_flags(__handle, __flags) ((HANDLE(__handle)->flags & (__flags)) == (__flags))\n" }, { "alpha_fraction": 0.7046632170677185, "alphanum_fraction": 0.7046632170677185, "avg_line_length": 20.44444465637207, "blob_id": "87b0d169239b953a32c88e02c03b6190f2e5de7a", "content_id": "fc0f49f15bd11ff10661a8ac0fb35342cd29f7aa", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 193, "license_type": "permissive", "max_line_length": 136, "num_lines": 9, "path": "/manual/10-utilities/man.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# man\n\n```sh\nman [SECTION] [TOPIC]\n```\n\n## Description\n\nman is short for manual. It provides documentation on commands. Add the -l parameter to show a list of the available manuals. **Try it**\n" }, { "alpha_fraction": 0.5295788049697876, "alphanum_fraction": 0.533838152885437, "avg_line_length": 24.16666603088379, "blob_id": "7b180157613c5840a7c1b66f460b97d54bd2b4e0", "content_id": "07b159737923af92b683444172910646a8e8f696", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2113, "license_type": "permissive", "max_line_length": 97, "num_lines": 84, "path": "/libraries/libwidget/TitleBar.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n\n#include <libwidget/Button.h>\n#include <libwidget/Spacer.h>\n#include <libwidget/TitleBar.h>\n#include <libwidget/Window.h>\n\nTitleBar::TitleBar(Widget *parent) : Widget(parent)\n{\n max_height(36);\n\n layout(HFLOW(4));\n insets({6, 6});\n\n new Button(\n this,\n Button::TEXT,\n window()->icon(),\n window()->title());\n\n new Spacer(this);\n\n if (window()->flags() & WINDOW_RESIZABLE)\n {\n Widget *button_minimize = new Button(this, Button::TEXT, Icon::get(\"window-minimize\"));\n button_minimize->insets(3);\n\n Widget *button_maximize = new Button(this, Button::TEXT, Icon::get(\"window-maximize\"));\n button_maximize->insets(3);\n button_maximize->on(Event::ACTION, [this](auto) {\n window()->toggle_maximise();\n });\n }\n\n Widget *close_button = new Button(this, Button::TEXT, Icon::get(\"window-close\"));\n close_button->insets(3);\n\n close_button->on(Event::ACTION, [this](auto) {\n window()->hide();\n });\n}\n\nTitleBar::~TitleBar()\n{\n}\n\nvoid TitleBar::event(Event *event)\n{\n __unused(event);\n\n if (is_mouse_event(event))\n {\n if (window()->maximised())\n {\n return;\n }\n\n if (!_is_dragging &&\n event->type == Event::MOUSE_BUTTON_PRESS &&\n event->mouse.button == MOUSE_BUTTON_LEFT)\n {\n _is_dragging = true;\n cursor(CURSOR_MOVE);\n event->accepted = true;\n }\n else if (\n _is_dragging &&\n event->type == Event::MOUSE_BUTTON_RELEASE &&\n event->mouse.button == MOUSE_BUTTON_LEFT)\n {\n _is_dragging = false;\n cursor(CURSOR_DEFAULT);\n event->accepted = true;\n }\n else if (\n _is_dragging &&\n event->type == Event::MOUSE_MOVE)\n {\n Vec2i offset = event->mouse.position_on_screen - event->mouse.old_position_on_screen;\n window()->bound(window()->bound_on_screen().offset(offset));\n event->accepted = true;\n }\n }\n}" }, { "alpha_fraction": 0.7105262875556946, "alphanum_fraction": 0.7105262875556946, "avg_line_length": 18.25, "blob_id": "a034d9d2f05141246aa4ec2abf4209acc8465642", "content_id": "687c16296a6edd7c4a452450be2b96e585d1ddad", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 76, "license_type": "permissive", "max_line_length": 42, "num_lines": 4, "path": "/libraries/libc/memory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n// Historical alternative to `<string.h>`.\n#include <string.h>" }, { "alpha_fraction": 0.6564986705780029, "alphanum_fraction": 0.6684350371360779, "avg_line_length": 16.136363983154297, "blob_id": "3aa82dbe33634076d834fe26e2002f552e833dc3", "content_id": "8be9411f1a4037683a987008589cfeada0c87bc9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 754, "license_type": "permissive", "max_line_length": 42, "num_lines": 44, "path": "/apps/neko/model/Neko.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Bitmap.h>\n#include <libgraphic/Painter.h>\n#include <libutils/Observable.h>\n\n#include \"neko/graphics/Sprites.h\"\n#include \"neko/model/Behavior.h\"\n\nnamespace neko\n{\n\nclass Neko : public Observable<Neko>\n{\nprivate:\n int _tick = 0;\n Vec2f _position;\n RefPtr<Bitmap> _sprites;\n\n OwnPtr<Behavior> _behavior;\n OwnPtr<Behavior> _next_behavior;\n\n Recti sprite();\n\npublic:\n static constexpr int SIZE = 32;\n static constexpr int SPEED = 16;\n\n int tick() { return _tick; }\n\n Vec2f position() { return _position; }\n\n Neko(Vec2f starting_position);\n\n void update();\n\n void paint(Painter &painter);\n\n void move_to(Vec2f position);\n\n void behavior(OwnPtr<Behavior>);\n};\n\n} // namespace neko\n" }, { "alpha_fraction": 0.49390244483947754, "alphanum_fraction": 0.5853658318519592, "avg_line_length": 19.5, "blob_id": "4e326b00da6493ef1f0a211af6300f188eb58071", "content_id": "34d240c5179fa7ed49eae13ba7f2db9771affdef", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 164, "license_type": "permissive", "max_line_length": 58, "num_lines": 8, "path": "/toolbox/convert-audio.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nif [[ -z $1 && -z $2 ]]; then\n echo \"Please specify input and output file.\"\n exit 1\nfi\n\nffmpeg -i $1 -f s16le -acodec pcm_s16le -ar 96000 -ac 1 $2\n" }, { "alpha_fraction": 0.5747572779655457, "alphanum_fraction": 0.5747572779655457, "avg_line_length": 20.45833396911621, "blob_id": "5cd06a9118ac8ae9803ac1cdb2473ddb911c3e77", "content_id": "5844e0c78b82ca28879e6398bc8e9c1fafeeb5cf", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 515, "license_type": "permissive", "max_line_length": 80, "num_lines": 24, "path": "/libraries/libsettings/Settings.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsettings/Path.h>\n#include <libutils/json/Json.h>\n#include <libutils/Optional.h>\n\nnamespace Settings\n{\n\n/* --- Private Functions ---------------------------------------------------- */\n\nclass Watcher;\n\nvoid register_watcher(Watcher &watcher);\n\nvoid unregister_watcher(Watcher &watcher);\n\n/* --- Public functions ----------------------------------------------------- */\n\nOptional<json::Value> read(const Path path);\n\nbool write(const Path path, json::Value value);\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.6538461446762085, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 9.11111068725586, "blob_id": "fc3ab6ffaa06d4b8e0d074dc115385f7eae4ba64", "content_id": "aa5957291668a45bb743d02992ab9ee359f4a5cd", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 182, "license_type": "permissive", "max_line_length": 29, "num_lines": 18, "path": "/libraries/libwidget/Screen.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Screen.h>\n\nnamespace Screen\n{\n\nstatic Recti _bound;\n\nRecti bound()\n{\n return _bound;\n}\n\nvoid bound(Recti bound)\n{\n _bound = bound;\n}\n\n} // namespace Screen\n" }, { "alpha_fraction": 0.7909091114997864, "alphanum_fraction": 0.7909091114997864, "avg_line_length": 26.5, "blob_id": "719b56ef97d0de4cbbb2037f4ff797eb62e3c038", "content_id": "ba9d29812e81781a260822a22a948d160cf503d0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 110, "license_type": "permissive", "max_line_length": 51, "num_lines": 4, "path": "/apps/layout-viewer/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += LAYOUT_VIEWER\n\nLAYOUT_VIEWER_NAME = layout-viewer\nLAYOUT_VIEWER_LIBS = widget settings markup graphic\n" }, { "alpha_fraction": 0.7830188870429993, "alphanum_fraction": 0.7830188870429993, "avg_line_length": 25.5, "blob_id": "7617fb182dfcb2fd007d9ec18bbec3dde3204f83", "content_id": "d9ac8c3929b42b87e79e4b1b91acf1f5159b80d9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 106, "license_type": "permissive", "max_line_length": 50, "num_lines": 4, "path": "/apps/media-player/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += MEDIA_PLAYER\n\nMEDIA_PLAYER_NAME = media-player\nMEDIA_PLAYER_LIBS = widget settings markup graphic\n" }, { "alpha_fraction": 0.6829971075057983, "alphanum_fraction": 0.698847234249115, "avg_line_length": 17.756755828857422, "blob_id": "2d50ce08c2c6084d898518e68a5f0bb676562b59", "content_id": "cd7b81db5155b5cbdd1cd8586e150be478e404c9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 694, "license_type": "permissive", "max_line_length": 94, "num_lines": 37, "path": "/libraries/libgraphic/vector/Rasterizer.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Trans2.h>\n\n#include <libgraphic/Bitmap.h>\n#include <libgraphic/vector/Path.h>\n\nclass Painter;\n\nnamespace graphic\n{\n\nclass Rasterizer\n{\nprivate:\n Vector<Vec2f> _points;\n\npublic:\n static constexpr auto TOLERANCE = 0.25f;\n static constexpr auto MAX_DEPTH = 8;\n\n Rasterizer()\n {\n }\n\n void tessellate_cubic_bezier(BezierCurve &curve, int depth);\n\n void flatten(BezierCurve &curve) { tessellate_cubic_bezier(curve, 0); }\n\n void rasterize();\n\n void fill(Path &path, Vec2f position, Trans2f transform, Color color);\n\n void stroke(Painter &painter, Path &path, Vec2f position, Trans2f transform, Color color);\n};\n\n} // namespace graphic\n" }, { "alpha_fraction": 0.6161100268363953, "alphanum_fraction": 0.6161100268363953, "avg_line_length": 26.365591049194336, "blob_id": "38e755d502d4e3d60e972e29444f434b799ef50d", "content_id": "5e002bc5b46b0569cb2c83ca81a13e0c879a52b4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2545, "license_type": "permissive", "max_line_length": 101, "num_lines": 93, "path": "/libraries/libsystem/core/Plugs.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Filesystem.h>\n#include <abi/Handle.h>\n#include <abi/IOCall.h>\n#include <abi/Launchpad.h>\n#include <abi/System.h>\n#include <skift/Time.h>\n\n#include <libutils/String.h>\n\nextern \"C\" void __plug_initialize();\n\nextern \"C\" void __plug_uninitialize(int exit_code);\n\nclass Lock;\n__no_return void __plug_lock_ensure_failed(Lock &, const char *raison, __SOURCE_LOCATION__ location);\n\n/* --- Logger --------------------------------------------------------------- */\n\nvoid __plug_logger_lock();\n\nvoid __plug_logger_unlock();\n\nvoid __no_return __plug_logger_fatal();\n\n/* --- File system ---------------------------------------------------------- */\n\nResult __plug_filesystem_link(const char *oldpath, const char *newpath);\n\nResult __plug_filesystem_unlink(const char *path);\n\nResult __plug_filesystem_mkdir(const char *path);\n\n/* --- System --------------------------------------------------------------- */\n\nTimeStamp __plug_system_get_time();\n\nTick __plug_system_get_ticks();\n\n/* --- Processes ------------------------------------------------------------ */\n\nint __plug_process_this();\n\nconst char *__plug_process_name();\n\nResult __plug_process_launch(Launchpad *launchpad, int *pid);\n\nvoid __no_return __plug_process_exit(int code);\n\nResult __plug_process_cancel(int pid);\n\nString __plug_process_resolve(String raw_path);\n\nResult __plug_process_get_directory(char *buffer, size_t size);\n\nResult __plug_process_set_directory(const char *directory);\n\nResult __plug_process_sleep(int time);\n\nResult __plug_process_wait(int pid, int *exit_value);\n\n/* --- I/O ------------------------------------------------------------------ */\n\nvoid __plug_handle_open(Handle *handle, const char *path, OpenFlag flags);\n\nvoid __plug_handle_close(Handle *handle);\n\nResult __plug_handle_poll(\n HandleSet *handles,\n int *selected,\n PollEvent *selected_events,\n Timeout timeout);\n\nsize_t __plug_handle_read(Handle *handle, void *buffer, size_t size);\n\nsize_t __plug_handle_write(Handle *handle, const void *buffer, size_t size);\n\nResult __plug_handle_call(Handle *handle, IOCall request, void *args);\n\nint __plug_handle_seek(Handle *handle, int offset, Whence whence);\n\nint __plug_handle_tell(Handle *handle);\n\nint __plug_handle_stat(Handle *handle, FileState *stat);\n\nvoid __plug_handle_connect(Handle *handle, const char *path);\n\nvoid __plug_handle_accept(Handle *handle, Handle *connection_handle);\n\nResult __plug_create_pipe(int *reader_handle, int *writer_handle);\n\nResult __plug_create_term(int *server_handle, int *client_handle);\n" }, { "alpha_fraction": 0.7390572428703308, "alphanum_fraction": 0.7390572428703308, "avg_line_length": 18.161291122436523, "blob_id": "f92d9d9849b301081a9fcc7308a99df738b4d351", "content_id": "74cde53fffcf46b558e668cdec2394e096a39810", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 594, "license_type": "permissive", "max_line_length": 56, "num_lines": 31, "path": "/libraries/libsystem/process/Process.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Process.h>\n\n#include <libsystem/Common.h>\n#include <libsystem/Result.h>\n#include <libutils/String.h>\n\nint process_this();\n\nconst char *process_name();\n\nResult process_run(const char *command, int *pid);\n\nint process_clone();\n\nvoid __no_return process_abort();\n\nvoid __no_return process_exit(int code);\n\nResult process_cancel(int pid);\n\nResult process_get_directory(char *buffer, size_t size);\n\nResult process_set_directory(const char *directory);\n\nString process_resolve(String path);\n\nResult process_sleep(int time);\n\nResult process_wait(int pid, int *exit_value);\n" }, { "alpha_fraction": 0.6613923907279968, "alphanum_fraction": 0.6693037748336792, "avg_line_length": 22.44444465637207, "blob_id": "1015741af3426dafd57d0b317fb5177f630ae293", "content_id": "bf18791e30565b41053f774a2ac35aeea3e3e9e0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 632, "license_type": "permissive", "max_line_length": 77, "num_lines": 27, "path": "/apps/panel/widgets/SearchBar.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/IconPanel.h>\n#include <libwidget/TextField.h>\n\n#include \"panel/widgets/SearchBar.h\"\n\nnamespace panel\n{\n\nSearchBar::SearchBar(Widget *parent, RefPtr<TextModel> model) : Panel(parent)\n{\n layout(HFLOW(4));\n insets({6});\n outsets({8});\n border_radius(6);\n color(THEME_MIDDLEGROUND, Colors::WHITE);\n layout(HFLOW(4));\n\n auto icon = new IconPanel(this, Icon::get(\"search\"));\n icon->color(THEME_FOREGROUND, Colors::BLACK);\n\n auto field = new TextField(this, model);\n field->flags(Widget::FILL);\n field->color(THEME_FOREGROUND, Colors::BLACK);\n field->focus();\n}\n\n} // namespace panel" }, { "alpha_fraction": 0.5594452023506165, "alphanum_fraction": 0.5620871782302856, "avg_line_length": 21.611940383911133, "blob_id": "7d4eb1adb4e76a546be2c82bb57b7ed1f24b6cac", "content_id": "a96b5d7dbf548a3b93d63143c2f69f4b1940767d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 88, "num_lines": 67, "path": "/libraries/libfilepicker/widgets/JumpList.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Button.h>\n#include <libwidget/Label.h>\n#include <libwidget/Panel.h>\n#include <libwidget/VScroll.h>\n\n#include <libfilepicker/model/Bookmarks.h>\n#include <libfilepicker/model/Navigation.h>\n\nnamespace filepicker\n{\n\nclass JumpList : public Panel\n{\nprivate:\n RefPtr<Navigation> _navigation;\n RefPtr<Bookmarks> _bookmarks;\n\n OwnPtr<Observer<Bookmarks>> _bookmark_observer;\n\n VScroll *_listing;\n\npublic:\n JumpList(Widget *parent, RefPtr<Navigation> navigation, RefPtr<Bookmarks> bookmarks)\n : Panel(parent),\n _navigation(navigation),\n _bookmarks(bookmarks)\n {\n layout(VFLOW(6));\n insets(Insetsi{4});\n\n _bookmark_observer = bookmarks->observe([this](auto &) {\n render();\n });\n\n new Label(this, \"Bookmarks\");\n\n _listing = new VScroll(this);\n _listing->flags(Widget::FILL);\n\n render();\n }\n\n void render()\n {\n _listing->host()->clear_children();\n _listing->host()->layout(VFLOW(4));\n\n for (size_t i = 0; i < _bookmarks->all().count(); i++)\n {\n auto bookmark = _bookmarks->all()[i];\n\n auto button = new Button(\n _listing->host(),\n Button::TEXT,\n bookmark.icon(),\n bookmark.name());\n\n button->on(Event::ACTION, [this, bookmark](auto) {\n _navigation->navigate(bookmark.path());\n });\n }\n }\n};\n\n} // namespace filepicker" }, { "alpha_fraction": 0.6989011168479919, "alphanum_fraction": 0.6989011168479919, "avg_line_length": 22.947368621826172, "blob_id": "42bbe59f383e6f5ee22c12a2f08ced112831cd87", "content_id": "d5bce24e4a6d58d9322aaf5ca1aceb317999f75b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 455, "license_type": "permissive", "max_line_length": 56, "num_lines": 19, "path": "/apps/file-manager/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/process/Process.h>\n#include <libwidget/Application.h>\n\n#include \"file-manager/MainWindow.h\"\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n auto navigation = make<filepicker::Navigation>();\n auto bookmarks = filepicker::Bookmarks::load();\n\n auto window = new MainWindow(navigation, bookmarks);\n\n navigation->go_home_dont_record_history();\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.7080745100975037, "alphanum_fraction": 0.7101449370384216, "avg_line_length": 22.047618865966797, "blob_id": "5056e63289a3b6887718453e7761dfb0d24c7b8c", "content_id": "f47c42c58ea086a3e3c51bd59ca1d083d463998c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 483, "license_type": "permissive", "max_line_length": 60, "num_lines": 21, "path": "/libraries/libsystem/compression/DeflateReader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/compression/Inflate.h>\n#include <libsystem/io/MemoryWriter.h>\n#include <libsystem/io/Reader.h>\n#include <libutils/Vector.h>\n\nclass DeflateReader : public Reader\n{\n DeflateReader(Reader &reader);\n\n virtual size_t length() override;\n virtual size_t position() override;\n\n virtual size_t read(void *buffer, size_t size) override;\n\nprivate:\n MemoryWriter _mem_buffer;\n Reader &_reader;\n Inflate _inflate;\n size_t _position = 0;\n};" }, { "alpha_fraction": 0.5291420817375183, "alphanum_fraction": 0.5448592305183411, "avg_line_length": 24.04918098449707, "blob_id": "002c224afd8a738770d7d58a231145eaaba6fc5f", "content_id": "831afc0bfb2154ac38711d4b1799625ad436d3a0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1527, "license_type": "permissive", "max_line_length": 120, "num_lines": 61, "path": "/kernel/storage/Partitions.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"kernel/storage/Partitions.h\"\n#include \"kernel/devices/Devices.h\"\n#include \"kernel/storage/MBR.h\"\n#include \"kernel/storage/Partition.h\"\n\nbool partition_load_mbr(RefPtr<Device> disk, const MBR &mbr)\n{\n if (mbr.magic != 0xAA55)\n {\n return false;\n }\n\n logger_info(\"MBR on '%s': \", disk->path().cstring());\n logger_info(\" - magic = 0x%04x\", mbr.magic);\n logger_info(\" - signature = 0x%08x\", mbr.signature);\n\n for (size_t i = 0; i < 4; i++)\n {\n const MBREntry &entry = mbr.entries[i];\n\n logger_info(\" - Partition[%d] = {start=%8d, size=%8d, type=0x%01x}\", i, entry.start, entry.size, entry.type);\n\n if (entry.type != 0)\n {\n disk->add(make<Partition>(disk, i, entry.start * 512, entry.size * 512));\n }\n }\n\n return true;\n}\n\nbool partition_load_gpt(RefPtr<Device> disk, const MBR &mbr)\n{\n __unused(disk);\n __unused(mbr);\n\n // TODO: GPT partition support\n\n return false;\n}\n\nvoid partitions_initialize()\n{\n device_iterate([](RefPtr<Device> device) {\n if (device->klass() == DeviceClass::DISK)\n {\n MBR mbr;\n device->read(0, &mbr, sizeof(MBR));\n\n bool success = partition_load_gpt(device, mbr) ||\n partition_load_mbr(device, mbr);\n\n if (!success)\n {\n logger_warn(\"Device '%s' don't have a valid partion table!\", device->path().cstring());\n }\n }\n\n return Iteration::CONTINUE;\n });\n}" }, { "alpha_fraction": 0.5633281469345093, "alphanum_fraction": 0.6024941802024841, "avg_line_length": 22.759260177612305, "blob_id": "a6dabee5357ba4ae8654cb236b33531f1ee7d07d", "content_id": "58afd1401d3463c928c2e24251e3827c183b086e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5132, "license_type": "permissive", "max_line_length": 107, "num_lines": 216, "path": "/archs/x86_64/kernel/x86_64.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/Logger.h>\n#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Stream.h>\n\n#include \"kernel/graphics/Graphics.h\"\n#include \"kernel/handover/Handover.h\"\n#include \"kernel/interrupts/Interupts.h\"\n#include \"kernel/system/System.h\"\n#include \"kernel/tasking/Task.h\"\n\n#include \"archs/x86/kernel/COM.h\"\n#include \"archs/x86/kernel/CPUID.h\"\n#include \"archs/x86/kernel/FPU.h\"\n#include \"archs/x86/kernel/IOPort.h\"\n#include \"archs/x86/kernel/PIC.h\"\n#include \"archs/x86/kernel/PIT.h\"\n#include \"archs/x86/kernel/RTC.h\"\n\n#include \"archs/x86_64/kernel/GDT.h\"\n#include \"archs/x86_64/kernel/IDT.h\"\n#include \"archs/x86_64/kernel/Interrupts.h\"\n#include \"archs/x86_64/kernel/x86_64.h\"\n\nextern \"C\" void arch_main(void *info, uint32_t magic)\n{\n __plug_initialize();\n\n com_initialize(COM1);\n com_initialize(COM2);\n com_initialize(COM3);\n com_initialize(COM4);\n\n auto handover = handover_initialize(info, magic);\n\n graphic_early_initialize(handover);\n\n if (handover->memory_usable < 127 * 1024)\n {\n system_panic(\"No enoughs memory (%uKio)!\", handover->memory_usable / 1024);\n }\n\n gdt_initialize();\n idt_initialize();\n pic_initialize();\n fpu_initialize();\n pit_initialize(1000);\n\n system_main(handover);\n\n ASSERT_NOT_REACHED();\n}\n\nvoid arch_disable_interrupts() { cli(); }\n\nvoid arch_enable_interrupts() { sti(); }\n\nvoid arch_halt()\n{\n hlt();\n}\n\nvoid arch_yield()\n{\n asm(\"int $127\");\n}\n\nvoid arch_save_context(Task *task)\n{\n fpu_save_context(task);\n}\n\nvoid arch_load_context(Task *task)\n{\n fpu_load_context(task);\n set_kernel_stack((uint64_t)task->kernel_stack + PROCESS_STACK_SIZE);\n}\n\nvoid arch_task_go(Task *task)\n{\n if (task->user)\n {\n InterruptStackFrame stackframe = {};\n\n stackframe.rsp = (uintptr_t)task->user_stack_pointer;\n\n stackframe.rflags = 0x202;\n stackframe.rip = (uintptr_t)task->entry_point;\n stackframe.rbp = (uintptr_t)stackframe.rsp;\n\n stackframe.cs = 0x1b;\n stackframe.ss = 0x23;\n\n task_kernel_stack_push(task, &stackframe, sizeof(InterruptStackFrame));\n }\n else\n {\n InterruptStackFrame stackframe = {};\n\n stackframe.rsp = (uintptr_t)task->kernel_stack_pointer - sizeof(InterruptStackFrame);\n\n stackframe.rflags = 0x202;\n stackframe.rip = (uintptr_t)task->entry_point;\n stackframe.rbp = (uintptr_t)stackframe.rsp;\n\n stackframe.cs = 0x08;\n stackframe.ss = 0x10;\n\n task_kernel_stack_push(task, &stackframe, sizeof(InterruptStackFrame));\n }\n}\n\nsize_t arch_debug_write(const void *buffer, size_t size)\n{\n return com_write(COM1, buffer, size);\n}\n\nTimeStamp arch_get_time()\n{\n return rtc_now();\n}\n\n__no_return void arch_reboot()\n{\n logger_warn(\"STUB %s\", __func__);\n ASSERT_NOT_REACHED();\n}\n\n__no_return void arch_shutdown()\n{\n logger_warn(\"STUB %s\", __func__);\n ASSERT_NOT_REACHED();\n}\n\nvoid arch_panic_dump()\n{\n cpuid_dump();\n}\n\nstruct Stackframe\n{\n Stackframe *rbp;\n uint64_t rip;\n};\n\nvoid backtrace_internal(uint64_t rbp)\n{\n bool empty = true;\n Stackframe *stackframe = reinterpret_cast<Stackframe *>(rbp);\n\n while (stackframe)\n {\n empty = false;\n stream_format(log_stream, \"\\t%016x\\n\", stackframe->rip);\n stackframe = stackframe->rbp;\n }\n\n if (empty)\n {\n stream_format(log_stream, \"\\t[EMPTY]\\n\");\n }\n}\n\nvoid arch_dump_stack_frame(void *sfptr)\n{\n auto stackframe = reinterpret_cast<InterruptStackFrame *>(sfptr);\n\n stream_format(out_stream, \"\\tRAX=%016x RBX=%016x RCX=%016x \\n\",\n stackframe->rax,\n stackframe->rbx,\n stackframe->rcx);\n\n stream_format(out_stream, \"\\tRDX=%016x RSI=%016x RDI=%016x\\n\",\n stackframe->rdx,\n stackframe->rsi,\n stackframe->rdi);\n\n stream_format(out_stream, \"\\tR08=%016x R09=%016x R10=%016x\\n\",\n stackframe->r8,\n stackframe->r9,\n stackframe->r10);\n\n stream_format(out_stream, \"\\tR11=%016x R12=%016x R13=%016x\\n\",\n stackframe->r11,\n stackframe->r12,\n stackframe->r13);\n\n stream_format(out_stream, \"\\tR14=%016x R15=%016x RBP=%016x\\n\",\n stackframe->r14,\n stackframe->r15,\n stackframe->rbp);\n\n stream_format(out_stream, \"\\n\");\n\n stream_format(out_stream, \"\\tINT=%08x ERR=%08x\\n\", stackframe->intno, stackframe->err);\n\n stream_format(out_stream, \"\\n\");\n\n stream_format(out_stream, \"\\tRIP=%016x CS=%016x FLG=%016x\\n\"\n \"\\tRSP=%016x SS=%016x\",\n stackframe->rip,\n stackframe->cs,\n stackframe->rflags,\n stackframe->rsp,\n stackframe->ss);\n\n stream_format(out_stream, \" CR0=%016x\\n\\tCR2=%016x CR3=%016x CR4=%016x\\n\", CR0(), CR2(), CR3(), CR4());\n\n stream_format(out_stream, \"\\n\\tBacktrace:\\n\");\n backtrace_internal(stackframe->rbp);\n}\n\nvoid arch_backtrace()\n{\n backtrace_internal(RBP());\n}\n" }, { "alpha_fraction": 0.36948853731155396, "alphanum_fraction": 0.3871252238750458, "avg_line_length": 15.676470756530762, "blob_id": "ae46989151e03b0f75e78c97703d4df70ae20c76", "content_id": "d72ec38ced12c8a1849cc9a209e42dcf47a70f61", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1134, "license_type": "permissive", "max_line_length": 48, "num_lines": 68, "path": "/libraries/libutils/Prettifier.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/StringBuilder.h>\n\nstruct Prettifier : public StringBuilder\n{\nprivate:\n int _depth = 0;\n int _flags;\n\npublic:\n static constexpr auto NONE = 0;\n static constexpr auto COLORS = 1 << 0;\n static constexpr auto INDENTS = 1 << 1;\n\n Prettifier(int flags = NONE) : _flags(flags)\n {\n }\n\n void ident()\n {\n if (_flags & INDENTS)\n {\n append('\\n');\n\n for (int i = 0; i < _depth; i++)\n {\n append(\" \");\n }\n }\n }\n\n void push_ident()\n {\n _depth++;\n }\n\n void pop_ident()\n {\n assert(_depth);\n _depth--;\n }\n\n void color_depth()\n {\n if (_flags & COLORS)\n {\n const char *depth_color[] = {\n \"\\e[91m\",\n \"\\e[92m\",\n \"\\e[93m\",\n \"\\e[94m\",\n \"\\e[95m\",\n \"\\e[96m\",\n };\n\n append(depth_color[_depth % 6]);\n }\n }\n\n void color_clear()\n {\n if (_flags & COLORS)\n {\n append(\"\\e[m\");\n }\n }\n};\n" }, { "alpha_fraction": 0.6274206042289734, "alphanum_fraction": 0.6328427791595459, "avg_line_length": 25.346939086914062, "blob_id": "341335aeca6b3c56e35bcdce0e98cde2aaba254e", "content_id": "bda7044bc38e4b75453050ff980b7ce81555bf49", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1292, "license_type": "permissive", "max_line_length": 87, "num_lines": 49, "path": "/apps/utilities/init.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Paths.h>\n\n#include <libsystem/Logger.h>\n#include <libsystem/io/Filesystem.h>\n#include <libsystem/io/Stream.h>\n#include <libsystem/process/Launchpad.h>\n#include <libsystem/process/Process.h>\n#include <skift/Environment.h>\n\n#include <stdio.h>\n\nint main(int argc, char **argv)\n{\n __unused(argc);\n __unused(argv);\n\n logger_level(LOGGER_TRACE);\n\n logger_info(\"Loading environement variables...\");\n\n environment() = json::parse_file(\"/Configs/environment.json\");\n\n if (filesystem_exist(FRAMEBUFFER_DEVICE_PATH, FILE_TYPE_DEVICE))\n {\n logger_info(\"Starting settings-service...\");\n process_run(\"settings-service\", nullptr);\n\n int splash_pid = -1;\n process_run(\"splash-screen\", &splash_pid);\n process_wait(splash_pid, nullptr);\n\n logger_info(\"Starting desktop environement...\");\n int compositor_pid = -1;\n process_run(\"compositor\", &compositor_pid);\n process_wait(compositor_pid, nullptr);\n }\n else\n {\n stream_format(err_stream, \"No framebuffer! Starting a shell, good luck :^)\\n\");\n\n int shell_pid = -1;\n process_run(\"shell\", &shell_pid);\n process_wait(shell_pid, nullptr);\n }\n\n printf(\"\\n\\n\\t\\e[1;34mGoodbye!\\e[m - n°1\\n\\n\");\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.7290167808532715, "alphanum_fraction": 0.7290167808532715, "avg_line_length": 17.130434036254883, "blob_id": "f9285f9cfa2d7eb68fb6d1c582ab551690eb4efe", "content_id": "d5e33340a373966d2ff984a5f96081bea980ce51", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 834, "license_type": "permissive", "max_line_length": 72, "num_lines": 46, "path": "/apps/shell/Nodes.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/utils/List.h>\n\nenum ShellNodeType\n{\n SHELL_NODE_NONE,\n SHELL_NODE_COMMAND,\n SHELL_NODE_PIPELINE,\n SHELL_NODE_REDIRECT,\n};\n\nstruct ShellNode;\n\ntypedef void (*ShellNodeDestroyCallback)(struct ShellNode *node);\n\nstruct ShellNode\n{\n ShellNodeType type;\n ShellNodeDestroyCallback destroy;\n};\n\nstruct ShellCommand : public ShellNode\n{\n char *command;\n List /* of cstring */ *arguments;\n};\n\nstruct ShellPipeline : public ShellNode\n{\n List *commands;\n};\n\nstruct ShellRedirect : public ShellNode\n{\n ShellNode *command;\n char *destination;\n};\n\nvoid shell_node_destroy(ShellNode *node);\n\nShellNode *shell_command_create(char *command, List *arguments);\n\nShellNode *shell_pipeline_create(List *commands);\n\nShellNode *shell_redirect_create(ShellNode *command, char *destination);\n" }, { "alpha_fraction": 0.5654008388519287, "alphanum_fraction": 0.5696202516555786, "avg_line_length": 18.66666603088379, "blob_id": "0ff1cba4298dd5ab2c21bc1cb38c613edd551398", "content_id": "0b79cdeda7d3ebda0bf0af588df13f99065e76ef", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 237, "license_type": "permissive", "max_line_length": 59, "num_lines": 12, "path": "/apps/utilities/touch.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/io/Stream.h>\n\nint main(int argc, char **argv)\n{\n for (int i = 1; i < argc; i++)\n {\n Stream *stream = stream_open(argv[i], OPEN_CREATE);\n stream_close(stream);\n }\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.703157901763916, "alphanum_fraction": 0.703157901763916, "avg_line_length": 24, "blob_id": "9b9caa951d7bc464fae6b717318f49365cb8ee59", "content_id": "a2f7320babbf9bb11fa1e3525853fb6bab9b736e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 475, "license_type": "permissive", "max_line_length": 68, "num_lines": 19, "path": "/apps/shell/Nodes/Command.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"shell/Nodes.h\"\n\nvoid shell_command_destroy(ShellCommand *node)\n{\n free(node->command);\n list_destroy_with_callback(node->arguments, free);\n}\n\nShellNode *shell_command_create(char *command, List *arguments)\n{\n ShellCommand *node = __create(ShellCommand);\n\n node->type = SHELL_NODE_COMMAND;\n node->command = command;\n node->arguments = arguments;\n node->destroy = (ShellNodeDestroyCallback)shell_command_destroy;\n\n return (ShellNode *)node;\n}\n" }, { "alpha_fraction": 0.580066978931427, "alphanum_fraction": 0.5844002366065979, "avg_line_length": 21.869369506835938, "blob_id": "2f6603a6ad3132b47d6a5b677c247ebb84b52185", "content_id": "fcefa7cfb0834967b7c709d43ac50c1e28a9100a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5077, "license_type": "permissive", "max_line_length": 80, "num_lines": 222, "path": "/libraries/libwidget/Window.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Bitmap.h>\n#include <libgraphic/Painter.h>\n#include <libsystem/eventloop/Invoker.h>\n#include <libutils/HashMap.h>\n#include <libutils/Vector.h>\n#include <libwidget/Cursor.h>\n#include <libwidget/Event.h>\n#include <libwidget/Widget.h>\n\n#include \"compositor/Protocol.h\"\n\n#define WINDOW_RESIZE_AREA 16\n\nclass Window\n{\nprivate:\n int _handle = -1;\n\n String _title = \"Window\";\n RefPtr<Icon> _icon;\n Recti _bound{250, 250};\n WindowFlag _flags;\n WindowType _type = WINDOW_TYPE_REGULAR;\n\n float _opacity;\n\n bool _focused = false;\n bool _visible = false;\n\n bool _is_maximised = false;\n bool _is_resizing = false;\n\n bool _resize_vertical = false;\n bool _resize_horizontal = false;\n\n Vec2i _resize_begin;\n Recti _previous_bound;\n\n CursorState cursor_state = CURSOR_DEFAULT;\n\n RefPtr<Bitmap> frontbuffer;\n OwnPtr<Painter> frontbuffer_painter;\n\n RefPtr<Bitmap> backbuffer;\n OwnPtr<Painter> backbuffer_painter;\n\n Vector<Recti> _dirty_rects{};\n bool _dirty_layout;\n\n EventHandler _handlers[EventType::__COUNT];\n\n Widget *_root;\n\n Widget *_keyboard_focus = nullptr;\n Widget *_mouse_focus = nullptr;\n Widget *_mouse_over = nullptr;\n\n HashMap<String, Widget *> _widget_by_id{};\n\n OwnPtr<Invoker> _repaint_invoker;\n OwnPtr<Invoker> _relayout_invoker;\n\npublic:\n int handle() { return this->_handle; }\n\n int frontbuffer_handle() const { return frontbuffer->handle(); }\n\n Vec2i frontbuffer_size() const { return frontbuffer->size(); }\n\n int backbuffer_handle() const { return backbuffer->handle(); }\n\n Vec2i backbuffer_size() const { return backbuffer->size(); }\n\n void title(String title) { _title = title; }\n\n String title() { return _title; }\n\n WindowFlag flags() { return _flags; }\n\n void icon(RefPtr<Icon> icon)\n {\n if (icon)\n {\n _icon = icon;\n }\n }\n\n RefPtr<Icon> icon() { return _icon; }\n\n void opacity(float value) { _opacity = value; }\n\n float opacity() { return _opacity; }\n\n bool visible() { return _visible; }\n\n bool focused()\n {\n return (_flags & WINDOW_ALWAYS_FOCUSED) || _focused;\n }\n\n bool maximised() { return _is_maximised; }\n\n void toggle_maximise();\n\n WindowType type() { return _type; }\n\n void type(WindowType type) { _type = type; }\n\n Color color(ThemeColorRole role);\n\n Window(WindowFlag flags);\n\n virtual ~Window();\n\n void show();\n\n void hide();\n\n void cursor(CursorState state);\n\n /* --- Geometry --------------------------------------------------------- */\n\n Vec2i position() { return bound_on_screen().position(); }\n\n void position(Vec2i position) { bound(bound_on_screen().moved(position)); }\n\n Vec2i size() { return bound().size(); }\n\n void size(Vec2i size) { bound(bound_on_screen().resized(size)); }\n\n Recti bound() { return _bound.moved({0, 0}); }\n\n void bound(Recti bound);\n\n Recti bound_on_screen() { return _bound; }\n\n void change_framebuffer_if_needed();\n\n Border resize_bound_containe(Vec2i position);\n\n void begin_resize(Vec2i mouse_position);\n\n void do_resize(Vec2i mouse_position);\n\n void end_resize();\n\n /* --- Childs ----------------------------------------------------------- */\n\n Widget *root() { return _root; }\n\n void focus_widget(Widget *widget);\n\n void widget_removed(Widget *widget);\n\n void register_widget_by_id(String id, Widget *widget);\n\n Widget *child_at(Vec2i position);\n\n template <typename WidgetType, typename CallbackType>\n void with_widget(String name, CallbackType callback)\n {\n if (_widget_by_id.has_key(name))\n {\n auto widget = dynamic_cast<WidgetType *>(_widget_by_id[name]);\n\n if (widget)\n {\n callback(widget);\n }\n }\n }\n\n /* --- Focus ------------------------------------------------------------ */\n\n bool has_keyboard_focus(Widget *widget);\n\n /* --- Layout ----------------------------------------------------------- */\n\n void relayout();\n\n void should_relayout();\n\n /* --- Render ----------------------------------------------------------- */\n\n virtual void repaint(Painter &painter, Recti rectangle);\n\n void repaint_dirty();\n\n void should_repaint(Recti rectangle);\n\n /* --- Events ----------------------------------------------------------- */\n\n void on(EventType event, EventHandler handler);\n\n void dispatch_event(Event *event);\n\n void handle_event(Event *Event);\n\n void handle_got_focus(Event *event);\n\n void handle_lost_focus(Event *event);\n\n void handle_window_closing(Event *event);\n\n void handle_mouse_move(Event *event);\n\n void handle_mouse_scroll(Event *event);\n\n void handle_mouse_button_press(Event *event);\n\n void handle_mouse_button_release(Event *event);\n\n void handle_mouse_double_click(Event *event);\n\n void handle_keyboard_key_typed(Event *event);\n\n void handle_keyboard_key_press(Event *event);\n\n void handle_keyboard_key_release(Event *event);\n};\n" }, { "alpha_fraction": 0.5739644765853882, "alphanum_fraction": 0.5739644765853882, "avg_line_length": 11.071428298950195, "blob_id": "a78d8c14b1bd858f49b5b8b688a46202ba3cac49", "content_id": "4d22c3972b35bbe5c308f777c723833ab87405f5", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 169, "license_type": "permissive", "max_line_length": 18, "num_lines": 14, "path": "/libraries/libutils/Anchor.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nenum class Anchor\n{\n LEFT,\n CENTER,\n RIGHT,\n TOP_LEFT,\n TOP_CENTER,\n TOP_RIGHT,\n BOTTOM_LEFT,\n BOTTOM_CENTER,\n BOTTOM_RIGHT,\n};\n" }, { "alpha_fraction": 0.6484490633010864, "alphanum_fraction": 0.6573116779327393, "avg_line_length": 27.808509826660156, "blob_id": "c30cfffccd4b713efc3931bdd6f6b0701af9c543", "content_id": "f3b82733552675e417a73e25e5852391a5b73736", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1354, "license_type": "permissive", "max_line_length": 98, "num_lines": 47, "path": "/apps/file-manager/MainWindow.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Container.h>\n#include <libwidget/TitleBar.h>\n#include <libwidget/Window.h>\n\n#include <libfilepicker/model/Navigation.h>\n#include <libfilepicker/widgets/DirectoryBrowser.h>\n#include <libfilepicker/widgets/JumpList.h>\n#include <libfilepicker/widgets/ToolBar.h>\n\nclass MainWindow :\n public Window\n{\nprivate:\npublic:\n MainWindow(RefPtr<filepicker::Navigation> navigation, RefPtr<filepicker::Bookmarks> bookmarks)\n : Window(WINDOW_RESIZABLE)\n {\n icon(Icon::get(\"folder\"));\n title(\"File Manager\");\n size(Vec2i(700, 500));\n\n root()->layout(VFLOW(0));\n\n new TitleBar(root());\n\n new filepicker::ToolBar(root(), navigation, bookmarks);\n\n auto bookmarks_and_browser = new Container(root());\n\n bookmarks_and_browser->flags(Widget::FILL);\n bookmarks_and_browser->layout(HFLOW(1));\n\n auto jump_list = new filepicker::JumpList(bookmarks_and_browser, navigation, bookmarks);\n\n jump_list->min_width(160);\n\n auto browser = new filepicker::DirectoryBrowser(bookmarks_and_browser, navigation);\n\n browser->on_element_selected = [&](String &path) {\n auto l = launchpad_create(\"open\", \"/System/Utilities/open\");\n launchpad_argument(l, path.cstring());\n launchpad_launch(l, nullptr);\n };\n }\n};\n" }, { "alpha_fraction": 0.634361207485199, "alphanum_fraction": 0.7136563658714294, "avg_line_length": 21.700000762939453, "blob_id": "6b78add3fdc3ae63a6c8c2dbc749fa4c9944fe95", "content_id": "f7209a692b3aac54c5b1cc20d31c92ab7d47dba0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 227, "license_type": "permissive", "max_line_length": 59, "num_lines": 10, "path": "/archs/x86_32/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "CC:=i686-pc-skift-gcc\nCXX:=i686-pc-skift-g++\nLD:=i686-pc-skift-ld\nAR:=i686-pc-skift-ar\nAS=nasm\nASFLAGS=-f elf32\n\nKERNEL_SOURCES += $(wildcard archs/x86/kernel/*.cpp)\n\nKERNEL_ASSEMBLY_SOURCES += $(wildcard archs/x86/kernel/*.s)\n" }, { "alpha_fraction": 0.7001763582229614, "alphanum_fraction": 0.7001763582229614, "avg_line_length": 16.44615364074707, "blob_id": "e5aae41b610527bacac85256b2c48144df624cd6", "content_id": "852e82c9428fdd75fa591c7507c8ccde10c2f73b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1134, "license_type": "permissive", "max_line_length": 75, "num_lines": 65, "path": "/apps/paint/PaintTool.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Color.h>\n#include <libwidget/Event.h>\n\nstruct PaintDocument;\n\nclass PaintTool\n{\nprivate:\npublic:\n virtual ~PaintTool() {}\n\n virtual void event(PaintDocument &document, Event &event, Color &color)\n {\n __unused(document);\n __unused(event);\n __unused(color);\n }\n};\n\nclass PencilTool : public PaintTool\n{\nprivate:\npublic:\n void event(PaintDocument &document, Event &event, Color &color);\n};\n\nclass BrushTool : public PaintTool\n{\nprivate:\npublic:\n void event(PaintDocument &document, Event &event, Color &color);\n};\n\nclass EraserTool : public PaintTool\n{\nprivate:\npublic:\n void event(PaintDocument &document, Event &event, Color &color);\n};\n\nclass FillTool : public PaintTool\n{\nprivate:\npublic:\n void event(PaintDocument &document, Event &event, Color &color);\n};\n\nclass PickerTool : public PaintTool\n{\nprivate:\npublic:\n void event(PaintDocument &document, Event &event, Color &color);\n};\n\nPaintTool *pencil_tool_create();\n\nPaintTool *brush_tool_create();\n\nPaintTool *eraser_tool_create();\n\nPaintTool *fill_tool_create();\n\nPaintTool *picker_tool_create();\n" }, { "alpha_fraction": 0.4619799256324768, "alphanum_fraction": 0.5021520853042603, "avg_line_length": 18.36111068725586, "blob_id": "e71accfbfc742a0ebf1f7a396ff0091f3466639e", "content_id": "56d5d61fe0097896379bab9f0869e8f82d717458", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 697, "license_type": "permissive", "max_line_length": 66, "num_lines": 36, "path": "/archs/x86_32/kernel/x86_32.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"archs/x86/kernel/IOPort.h\"\n#include \"archs/x86/kernel/x86.h\"\n\n#include <libsystem/Common.h>\n\nstatic inline uint32_t EBP()\n{\n uint32_t r;\n asm volatile(\"mov %%ebp, %0\"\n : \"=r\"(r));\n return r;\n}\n\nstatic inline uint32_t ESP()\n{\n uint32_t r;\n asm volatile(\"mov %%esp, %0\"\n : \"=r\"(r));\n return r;\n}\n\nstatic inline void rdmsr(uint32_t msr, uint32_t *lo, uint32_t *hi)\n{\n asm volatile(\"rdmsr\"\n : \"=a\"(*lo), \"=d\"(*hi)\n : \"c\"(msr));\n}\n\nstatic inline void wrmsr(uint32_t msr, uint32_t lo, uint32_t hi)\n{\n asm volatile(\"wrmsr\"\n :\n : \"a\"(lo), \"d\"(hi), \"c\"(msr));\n}\n" }, { "alpha_fraction": 0.6132956147193909, "alphanum_fraction": 0.6226308345794678, "avg_line_length": 26.6171875, "blob_id": "771b8ad3e36ec7000b1b890410bbaea89ce89e8a", "content_id": "5159eb03286709d2df8750703a6639732ef7acc6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3535, "license_type": "permissive", "max_line_length": 120, "num_lines": 128, "path": "/apps/onboarding/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Application.h>\n#include <libwidget/Button.h>\n#include <libwidget/Container.h>\n#include <libwidget/Image.h>\n#include <libwidget/Markup.h>\n#include <libwidget/PaginationDots.h>\n#include <libwidget/Panel.h>\n#include <libwidget/Screen.h>\n#include <libwidget/Spacer.h>\n#include <stdio.h>\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n Window *window = new Window(WINDOW_BORDERLESS | WINDOW_ALWAYS_FOCUSED | WINDOW_ACRYLIC | WINDOW_NO_ROUNDED_CORNERS);\n\n window->title(\"Onboarding\");\n window->type(WINDOW_TYPE_POPOVER);\n window->bound(Screen::bound());\n window->opacity(0);\n window->show();\n window->root()->layout(STACK());\n\n auto background = new Panel(window->root());\n\n background->layout(STACK());\n background->color(THEME_MIDDLEGROUND, Colors::BLACK.with_alpha(0.5));\n background->flags(Widget::FILL);\n\n auto dialog = new Panel(background);\n\n dialog->min_width(420);\n dialog->min_height(420);\n\n dialog->layout(VFLOW(0));\n dialog->border_radius(6);\n\n auto illustration = new Panel(dialog);\n\n illustration->min_height(160);\n illustration->border_radius(6);\n illustration->color(THEME_MIDDLEGROUND, Colors::WHITE);\n\n auto image = new Image(illustration, Bitmap::placeholder());\n image->flags(Widget::FILL);\n image->scaling(BitmapScaling::CENTER);\n\n auto content = new Container(dialog);\n content->flags(Widget::FILL);\n content->insets(16);\n\n auto dots_container = new Container(dialog);\n dots_container->insets(16);\n\n auto dots = new PaginationDots(dots_container, 5);\n\n auto navigation = new Container(dialog);\n\n navigation->layout(HFLOW(4));\n navigation->insets(8);\n\n auto skipall_button = new Button(navigation, Button::TEXT, \"Skip All\");\n\n new Spacer(navigation);\n\n auto back_button = new Button(navigation, Button::OUTLINE, \"Previous\");\n\n auto next_button = new Button(navigation, Button::FILLED, \"Next\");\n\n int current_page = 0;\n\n auto set_current_page = [&](int index) {\n if (index == 5)\n {\n Application::exit(PROCESS_SUCCESS);\n }\n\n if (index < 0 || index > 4)\n {\n return;\n }\n\n current_page = index;\n\n skipall_button->enable_if(current_page < 4);\n back_button->enable_if(current_page > 0);\n dots->index(index);\n\n auto image_path = String::format(\"/Applications/onboarding/illustration{}.png\", index);\n auto content_path = String::format(\"/Applications/onboarding/content{}.markup\", index);\n\n content->clear_children();\n image->change_bitmap(*Bitmap::load_from(image_path));\n widget_create_from_file(content, content_path);\n };\n\n set_current_page(0);\n\n skipall_button->on(Event::ACTION, [](auto) {\n Application::exit(PROCESS_SUCCESS);\n });\n\n back_button->on(Event::ACTION, [&](auto) {\n set_current_page(current_page - 1);\n });\n\n next_button->on(Event::ACTION, [&](auto) {\n set_current_page(current_page + 1);\n });\n\n window->on(Event::KEYBOARD_KEY_PRESS, [&](Event *event) {\n if (event->keyboard.key == KEYBOARD_KEY_ESC)\n {\n Application::exit(PROCESS_SUCCESS);\n }\n else if (event->keyboard.key == KEYBOARD_KEY_RIGHT)\n {\n set_current_page(current_page + 1);\n }\n else if (event->keyboard.key == KEYBOARD_KEY_LEFT)\n {\n set_current_page(current_page - 1);\n }\n });\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.6237006187438965, "alphanum_fraction": 0.6257796287536621, "avg_line_length": 18.260000228881836, "blob_id": "2570e19c901fd7fe80eb18fbc71a2ad22520b719", "content_id": "13ef7b5da2a6434b886ac265ce6074fd0c082e29", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 962, "license_type": "permissive", "max_line_length": 110, "num_lines": 50, "path": "/libraries/libsystem/io/MemoryReader.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/MemoryReader.h>\n\nMemoryReader::MemoryReader(const uint8_t *data, size_t size) : _data(data), _size(size)\n{\n}\n\nMemoryReader::MemoryReader(const Vector<uint8_t> &buffer) : MemoryReader(buffer.raw_storage(), buffer.count())\n{\n}\n\nsize_t MemoryReader::length()\n{\n return _size;\n}\n\nsize_t MemoryReader::position()\n{\n return _position;\n}\n\nsize_t MemoryReader::seek(size_t position, Whence whence)\n{\n switch (whence)\n {\n case WHENCE_START:\n _position = position;\n break;\n case WHENCE_HERE:\n _position += position;\n break;\n case WHENCE_END:\n _position = _size + position;\n break;\n default:\n ASSERT_NOT_REACHED();\n break;\n }\n\n return _position;\n}\n\nsize_t MemoryReader::read(void *buffer, size_t size)\n{\n size_t remaining = MIN(length() - position(), size);\n\n memcpy(buffer, _data + _position, remaining);\n _position += remaining;\n\n return remaining;\n}" }, { "alpha_fraction": 0.5905368328094482, "alphanum_fraction": 0.5905368328094482, "avg_line_length": 18.625, "blob_id": "1cca1955121d78109b12b0ab202c7d339966b9b3", "content_id": "41af34fba109a34432892180039e82a3d709c03f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1099, "license_type": "permissive", "max_line_length": 54, "num_lines": 56, "path": "/apps/paint/PaintDocument.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Painter.h>\n#include <libutils/Callback.h>\n\nclass PaintDocument : public RefCounted<PaintDocument>\n{\nprivate:\n RefPtr<Bitmap> _bitmap;\n Painter _painter;\n\n Color _primary_color = Colors::BLACK;\n Color _secondary_color = Colors::WHITE;\n\n bool _dirty = true;\n\npublic:\n Callback<void()> on_color_change;\n\n Recti bound() { return _bitmap->bound(); }\n Bitmap &bitmap() { return *_bitmap; }\n Painter &painter() { return _painter; }\n\n bool dirty() { return _dirty; }\n void dirty(bool value) { _dirty = value; }\n\n Color primary_color() { return _primary_color; }\n\n void primary_color(Color value)\n {\n _primary_color = value;\n\n if (on_color_change)\n on_color_change();\n }\n\n Color secondary_color()\n {\n\n return _secondary_color;\n }\n\n void secondary_color(Color value)\n {\n _secondary_color = value;\n\n if (on_color_change)\n on_color_change();\n }\n\n PaintDocument(RefPtr<Bitmap> bitmap)\n : _bitmap(bitmap),\n _painter(bitmap)\n {\n }\n};\n" }, { "alpha_fraction": 0.6639801859855652, "alphanum_fraction": 0.684438943862915, "avg_line_length": 19.417720794677734, "blob_id": "011d2d32a1febf481099d5227b4aa57daca0706b", "content_id": "e47ef4a0fde9eadd92e4d9c405caf3aa3c6287a4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1613, "license_type": "permissive", "max_line_length": 91, "num_lines": 79, "path": "/libraries/libgraphic/vector/SubPath.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Vector.h>\n\n#include <libgraphic/vector/Arc.h>\n#include <libgraphic/vector/BezierCurve.h>\n\nnamespace graphic\n{\n\nclass SubPath\n{\nprivate:\n Vector<Vec2f> _points;\n bool _closed = false;\n\npublic:\n size_t length() const;\n\n BezierCurve curves(size_t index) const;\n\n bool closed() const { return _closed; }\n\n Vec2f first_point() const;\n\n Vec2f last_point() const;\n\n Vec2f last_cubic_control_point() const;\n\n SubPath();\n\n SubPath(Vec2f start);\n\n void add(Vec2f point);\n\n void reset();\n\n void reset(Vec2f start);\n\n void close();\n\n void move_to(Vec2f point);\n\n void move_to_relative(Vec2f point);\n\n void line_to(Vec2f point);\n\n void line_to_relative(Vec2f point);\n\n void vline_to(float y);\n\n void vline_to_relative(float y);\n\n void hline_to(float x);\n\n void hline_to_relative(float x);\n\n void cubic_bezier_to(Vec2f control_point1, Vec2f control_point2, Vec2f point);\n\n void cubic_bezier_to_relative(Vec2f control_point1, Vec2f control_point2, Vec2f point);\n\n void smooth_cubic_bezier_to(Vec2f control_point, Vec2f point);\n\n void smooth_cubic_bezier_to_relative(Vec2f control_point, Vec2f point);\n\n void quad_bezier_to(Vec2f control_point, Vec2f point);\n\n void quad_bezier_to_relative(Vec2f control_point, Vec2f point);\n\n void smooth_quad_bezier_to(Vec2f point);\n\n void smooth_quad_bezier_to_relative(Vec2f point);\n\n void arc_to(float rx, float ry, float angle, int flags, Vec2f point);\n\n void arc_to_relative(float rx, float ry, float angle, int flags, Vec2f point);\n};\n\n} // namespace graphic\n" }, { "alpha_fraction": 0.6406619548797607, "alphanum_fraction": 0.6453900933265686, "avg_line_length": 18.227272033691406, "blob_id": "d96de009e09465e3f2f41a7bb958873717689f3d", "content_id": "18ca9966cd839e92bd83c10358e9edadb8a39d59", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 423, "license_type": "permissive", "max_line_length": 59, "num_lines": 22, "path": "/libraries/libsystem/Common.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <stdarg.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#include <abi/Process.h>\n#include <libsystem/Macros.h>\n\nstruct __SOURCE_LOCATION__\n{\n const char *file;\n const char *function;\n int line;\n};\n\n#define SOURCE_LOCATION \\\n (__SOURCE_LOCATION__{__FILE__, __FUNCTION__, __LINE__})\n\n#define INVALID_SOURCE_LOCATION \\\n (__SOURCE_LOCATION__{\"no-file\", \"no-function\", 69})\n" }, { "alpha_fraction": 0.5221238732337952, "alphanum_fraction": 0.5575221180915833, "avg_line_length": 8.416666984558105, "blob_id": "f7494abc9d43d68b594b8537f5d3bf651260fe0a", "content_id": "2ad16c3dbc435dda09bbb0409e71b3a1906d13bb", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 113, "license_type": "permissive", "max_line_length": 22, "num_lines": 12, "path": "/libraries/libgraphic/vector/Arc.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nnamespace graphic\n{\n\nenum Arc\n{\n LARGE = 1 << 0,\n SWEEP = 1 << 1,\n};\n\n} // namespace graphic\n" }, { "alpha_fraction": 0.5436018705368042, "alphanum_fraction": 0.5592417120933533, "avg_line_length": 23.534883499145508, "blob_id": "520bf5f5e560ae8df808d0475c2c64270b9f521c", "content_id": "3bdfc514e42fabf1e7ee37443c056ce9e0954bc2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2110, "license_type": "permissive", "max_line_length": 116, "num_lines": 86, "path": "/kernel/handover/Handover.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/Logger.h>\n\n#include \"kernel/handover/Handover.h\"\n#include \"kernel/system/System.h\"\n\nstatic Handover _handover;\n\nconst char *entry_type_to_string[] = {\n \"AVAILABLE\",\n \"RESERVED\",\n \"ACPI\",\n \"NVS\",\n \"BADRAM\",\n \"KERNEL\",\n};\n\nHandover *handover()\n{\n return &_handover;\n}\n\nvoid handover_assert(uint32_t magic)\n{\n if (!(is_multiboot2(magic) ||\n is_stivale2(magic)))\n {\n system_panic(\"Wrong bootloader please use any multiboot/stival bootloader\\n\\tMagic number: 0x%08x!\", magic);\n }\n}\n\nvoid handover_dump()\n{\n logger_info(\"Bootloader: '%s'\", _handover.bootloader);\n logger_info(\"Command lines: '%s'\", _handover.command_line);\n\n logger_info(\"Memory map:\");\n for (size_t i = 0; i < _handover.memory_map_size; i++)\n {\n MemoryMapEntry *entry = &_handover.memory_map[i];\n\n logger_info(\"\\t%d: %08p-%08p: %s\",\n i,\n entry->range.base(),\n entry->range.base() + entry->range.size() - 1,\n entry_type_to_string[entry->type]);\n }\n logger_info(\"\\t -> Usable memory: %dKio\", _handover.memory_usable / 1024);\n\n logger_info(\"Modules:\");\n for (size_t i = 0; i < _handover.modules_size; i++)\n {\n Module *module = &_handover.modules[i];\n logger_info(\"\\t%d: %08p-%08p: %s\",\n i,\n module->range.base(),\n module->range.base() + module->range.size() - 1,\n module->command_line);\n }\n logger_info(\"\\t-> %d module found\", _handover.modules_size);\n}\n\nHandover *handover_initialize(void *header, uint32_t magic)\n{\n handover_assert(magic);\n\n logger_info(\"Parsing handover informations...\");\n logger_info(\"Header=%08x, Magic=%08x\", header, magic);\n\n if (is_multiboot2(magic))\n {\n multiboot2_parse_header(&_handover, header);\n }\n else if (is_stivale2(magic))\n {\n stivale2_parse_header(&_handover, header);\n }\n else\n {\n ASSERT_NOT_REACHED();\n }\n\n handover_dump();\n\n return &_handover;\n}\n" }, { "alpha_fraction": 0.6083943247795105, "alphanum_fraction": 0.6091644167900085, "avg_line_length": 21.582609176635742, "blob_id": "db5b714ab3ab9d7b32f8f2bcd1dae42dd052dd07", "content_id": "31e5d28da3ce5718fb4ea691d3de08ae3c164724", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2597, "license_type": "permissive", "max_line_length": 87, "num_lines": 115, "path": "/libraries/libsettings/Protocol.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsettings/Protocol.h>\n\nnamespace Settings\n{\n\nstruct MessageHeader\n{\n Message::Type type;\n size_t path_length;\n size_t payload_length;\n};\n\nResult Protocol::encode_message(Connection *connection, const Message &message)\n{\n String path_buffer = \"\";\n\n if (message.path)\n {\n Prettifier pretty;\n message.path->prettify(pretty);\n path_buffer = pretty.finalize();\n }\n\n String payload_buffer = \"\";\n\n if (message.payload)\n {\n Prettifier pretty;\n json::prettify(pretty, *message.payload);\n payload_buffer = pretty.finalize();\n }\n\n MessageHeader header;\n header.type = message.type;\n header.path_length = path_buffer.length();\n header.payload_length = payload_buffer.length();\n\n connection_send(connection, &header, sizeof(MessageHeader));\n\n if (handle_has_error(connection))\n {\n return handle_get_error(connection);\n }\n\n if (path_buffer.length())\n {\n connection_send(connection, path_buffer.cstring(), path_buffer.length());\n\n if (handle_has_error(connection))\n {\n return handle_get_error(connection);\n }\n }\n\n if (payload_buffer.length())\n {\n connection_send(connection, payload_buffer.cstring(), payload_buffer.length());\n\n if (handle_has_error(connection))\n {\n return handle_get_error(connection);\n }\n }\n\n return SUCCESS;\n}\n\nResultOr<Message> Protocol::decode_message(Connection *connection)\n{\n MessageHeader header;\n connection_receive(connection, &header, sizeof(header));\n\n if (handle_has_error(connection))\n {\n return handle_get_error(connection);\n }\n\n Message message;\n\n message.type = header.type;\n\n if (header.path_length > 0)\n {\n auto *buffer = new char[header.path_length];\n connection_receive(connection, buffer, header.path_length);\n\n if (handle_has_error(connection))\n {\n delete[] buffer;\n return handle_get_error(connection);\n }\n\n message.path = Path::parse(buffer, header.path_length);\n delete[] buffer;\n }\n\n if (header.payload_length > 0)\n {\n auto *buffer = new char[header.payload_length];\n connection_receive(connection, buffer, header.payload_length);\n\n if (handle_has_error(connection))\n {\n delete[] buffer;\n return handle_get_error(connection);\n }\n\n message.payload = json::parse(buffer, header.payload_length);\n delete[] buffer;\n }\n\n return message;\n}\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.6020066738128662, "alphanum_fraction": 0.6036789417266846, "avg_line_length": 19.620689392089844, "blob_id": "dbc422a8b228622cad73d281aafb167a34af6eee", "content_id": "8ba6c29c6125a6496608a3ad2c391c5ccb2e38e3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 598, "license_type": "permissive", "max_line_length": 55, "num_lines": 29, "path": "/tests/test_string.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n#include <libsystem/Assert.h>\n#include <libutils/String.h>\n\nint main(int, char const *[])\n{\n String hello_world = \"Hello, world!\";\n\n assert(hello_world == \"Hello, world!\");\n assert(hello_world != \"Something else blablabla!\");\n assert(!hello_world.null_or_empty());\n\n String empty = \"\";\n\n assert(empty == \"\");\n assert(empty != \"Something else blablabla!\");\n assert(empty.null_or_empty());\n\n String first = \"first\";\n String second = \"second\";\n\n first = move(second);\n\n assert(first == \"second\");\n assert(second == \"first\");\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5336313247680664, "alphanum_fraction": 0.5403902530670166, "avg_line_length": 19.75565528869629, "blob_id": "524ec60aa3b95841806d32d6f23dddaaed9ea19a", "content_id": "5009526b53ffd6d36fc2b3c8368ee0545f273e1b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9173, "license_type": "permissive", "max_line_length": 110, "num_lines": 442, "path": "/libraries/libwidget/Markup.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libmarkup/Markup.h>\n#include <libsystem/Logger.h>\n#include <libutils/NumberParser.h>\n#include <libutils/Scanner.h>\n#include <string.h>\n\n#include <libwidget/Button.h>\n#include <libwidget/Container.h>\n#include <libwidget/Image.h>\n#include <libwidget/Label.h>\n#include <libwidget/Markup.h>\n#include <libwidget/Panel.h>\n#include <libwidget/Placeholder.h>\n#include <libwidget/Slider.h>\n#include <libwidget/TitleBar.h>\n\nstatic void whitespace(Scanner &scan)\n{\n scan.eat(\" \");\n}\n\nstatic int number(Scanner &scan)\n{\n int number = 0;\n\n while (scan.current_is(\"0123456789\"))\n {\n number *= 10;\n number += scan.current() - '0';\n scan.foreward();\n }\n\n return number;\n}\n\nstatic Layout layout_parse(const char *string)\n{\n if (!string)\n {\n return STACK();\n }\n\n Layout result = STACK();\n\n StringScanner scan(string, strlen(string));\n\n if (scan.skip_word(\"stack\"))\n {\n result = STACK();\n }\n\n if (scan.skip_word(\"grid\"))\n {\n scan.skip('(');\n\n whitespace(scan);\n\n int hcell = number(scan);\n\n whitespace(scan);\n\n scan.skip(',');\n\n whitespace(scan);\n\n int vcell = number(scan);\n\n whitespace(scan);\n\n scan.skip(',');\n\n whitespace(scan);\n\n int hspacing = number(scan);\n\n whitespace(scan);\n\n scan.skip(',');\n\n whitespace(scan);\n\n int vspacing = number(scan);\n\n result = GRID(hcell, vcell, hspacing, vspacing);\n }\n\n if (scan.skip_word(\"vgrid\"))\n {\n scan.skip('(');\n whitespace(scan);\n int spacing = number(scan);\n result = VGRID(spacing);\n }\n\n if (scan.skip_word(\"hgrid\"))\n {\n scan.skip('(');\n whitespace(scan);\n int spacing = number(scan);\n result = HGRID(spacing);\n }\n\n if (scan.skip_word(\"vflow\"))\n {\n scan.skip('(');\n whitespace(scan);\n\n int spacing = number(scan);\n result = VFLOW(spacing);\n }\n\n if (scan.skip_word(\"hflow\"))\n {\n scan.skip('(');\n whitespace(scan);\n\n int spacing = number(scan);\n result = HFLOW(spacing);\n }\n\n return result;\n}\n\nInsetsi insets_parse(const char *string)\n{\n if (!string)\n {\n return Insetsi(0);\n }\n\n StringScanner scan{string, strlen(string)};\n\n if (!scan.skip_word(\"insets\"))\n {\n return Insetsi(0);\n }\n\n scan.skip('(');\n whitespace(scan);\n\n int count;\n int args[4];\n\n for (count = 0; count < 4 && scan.current_is(\"0123456789\"); count++)\n {\n args[count] = number(scan);\n whitespace(scan);\n scan.skip(',');\n whitespace(scan);\n }\n\n Insetsi result = Insetsi(0);\n\n if (count == 1)\n {\n result = Insetsi(args[0]);\n }\n else if (count == 2)\n {\n result = Insetsi(args[0], args[1]);\n }\n else if (count == 3)\n {\n result = Insetsi(args[0], args[1], args[2]);\n }\n else if (count == 4)\n {\n result = Insetsi(args[0], args[1], args[2], args[3]);\n }\n\n return result;\n}\n\nAnchor anchor_parse(const char *string)\n{\n if (strcmp(string, \"left\") == 0)\n {\n return Anchor::LEFT;\n }\n if (strcmp(string, \"center\") == 0)\n {\n return Anchor::CENTER;\n }\n if (strcmp(string, \"right\") == 0)\n {\n return Anchor::RIGHT;\n }\n if (strcmp(string, \"top_left\") == 0)\n {\n return Anchor::TOP_LEFT;\n }\n if (strcmp(string, \"top_center\") == 0)\n {\n return Anchor::TOP_CENTER;\n }\n if (strcmp(string, \"top_right\") == 0)\n {\n return Anchor::TOP_RIGHT;\n }\n if (strcmp(string, \"bottom_left\") == 0)\n {\n return Anchor::BOTTOM_LEFT;\n }\n if (strcmp(string, \"bottom_center\") == 0)\n {\n return Anchor::BOTTOM_CENTER;\n }\n if (strcmp(string, \"bottom_right\") == 0)\n {\n return Anchor::BOTTOM_RIGHT;\n }\n\n return Anchor::LEFT;\n}\n\nstatic BitmapScaling scaling_parse(String string)\n{\n if (string == \"center\")\n {\n return BitmapScaling::CENTER;\n }\n\n if (string == \"cover\")\n {\n return BitmapScaling::COVER;\n }\n\n if (string == \"fit\")\n {\n return BitmapScaling::FIT;\n }\n\n if (string == \"stretch\")\n {\n return BitmapScaling::STRETCH;\n }\n\n return BitmapScaling::CENTER;\n}\n\nvoid widget_apply_attribute_from_markup(Widget *widget, markup::Node &node)\n{\n node.with_attribute(\"id\", [&](auto &id) {\n widget->id(id);\n });\n\n node.with_attribute(\"layout\", [&](auto &layout) {\n widget->layout(layout_parse(layout.cstring()));\n });\n\n node.with_attribute(\"padding\", [&](auto &insets) {\n widget->insets(insets_parse(insets.cstring()));\n });\n\n if (node.has_attribute(\"fill\"))\n {\n widget->flags(Widget::FILL);\n }\n}\n\nWidget *widget_create_from_markup(Widget *parent, markup::Node &node)\n{\n Widget *widget = nullptr;\n\n if (node.is(\"Container\"))\n {\n widget = new Container(parent);\n }\n\n if (node.is(\"Panel\"))\n {\n if (node.has_attribute(\"rounded\"))\n {\n auto panel = new Panel(parent);\n panel->border_radius(6);\n widget = panel;\n }\n else\n {\n widget = new Panel(parent);\n }\n }\n\n if (node.is(\"Button\"))\n {\n Button::Style button_style = Button::TEXT;\n\n if (node.has_attribute(\"filled\"))\n {\n button_style = Button::FILLED;\n }\n\n if (node.has_attribute(\"outlined\"))\n {\n button_style = Button::OUTLINE;\n }\n\n if (node.has_attribute(\"text\") && node.has_attribute(\"icon\"))\n {\n widget = new Button(\n parent,\n button_style,\n Icon::get(node.get_attribute_or_default(\"icon\", \"duck\")),\n node.get_attribute_or_default(\"text\", \"Button\"));\n }\n else if (node.has_attribute(\"text\"))\n {\n widget = new Button(\n parent,\n button_style,\n node.get_attribute_or_default(\"text\", \"Button\"));\n }\n else if (node.has_attribute(\"icon\"))\n {\n widget = new Button(\n parent,\n button_style,\n Icon::get(node.get_attribute_or_default(\"icon\", \"duck\")));\n }\n else\n {\n widget = new Button(\n parent,\n button_style);\n }\n }\n\n if (node.is(\"Label\"))\n {\n widget = new Label(\n parent,\n node.get_attribute_or_default(\"text\", \"Label\"),\n anchor_parse(node.get_attribute_or_default(\"anchor\", \"left\")\n .cstring()));\n }\n\n if (node.is(\"Image\"))\n {\n auto bitmap = Bitmap::load_from_or_placeholder(node.get_attribute_or_default(\"path\", \"null\"));\n\n widget = new Image(parent, bitmap, scaling_parse(node.get_attribute_or_default(\"scaling\", \"center\")));\n }\n\n if (node.is(\"Slider\"))\n {\n widget = new Slider(parent);\n }\n\n if (node.is(\"TitleBar\"))\n {\n widget = new TitleBar(parent);\n }\n\n if (widget == nullptr)\n {\n widget = new Placeholder(parent, node.type());\n }\n\n widget_apply_attribute_from_markup(widget, node);\n\n return widget;\n}\n\nvoid widget_create_childs_from_markup(Widget *parent, markup::Node &node)\n{\n node.foreach_child([&](auto &child) {\n auto widget = widget_create_from_markup(parent, child);\n widget_create_childs_from_markup(widget, child);\n\n return Iteration::CONTINUE;\n });\n}\n\nWindowFlag window_flags_from_markup(markup::Node &node)\n{\n WindowFlag flags = 0;\n\n if (node.has_attribute(\"borderless\"))\n {\n flags |= WINDOW_BORDERLESS;\n }\n\n if (node.has_attribute(\"resizable\"))\n {\n flags |= WINDOW_RESIZABLE;\n }\n\n if (node.has_attribute(\"always-focused\"))\n {\n flags |= WINDOW_ALWAYS_FOCUSED;\n }\n\n if (node.has_attribute(\"transparent\"))\n {\n flags |= WINDOW_TRANSPARENT;\n }\n\n return flags;\n}\n\nWindow *window_create_from_markup(markup::Node &node)\n{\n auto window = new Window(window_flags_from_markup(node));\n\n int width = parse_int_inline(PARSER_DECIMAL, node.get_attribute(\"width\").cstring(), 250);\n\n int height = parse_int_inline(PARSER_DECIMAL, node.get_attribute(\"height\").cstring(), 250);\n\n window->size(Vec2i(width, height));\n\n node.with_attribute(\"icon\", [&](auto &icon) {\n window->icon(Icon::get(icon));\n });\n\n node.with_attribute(\"title\", [&](auto &title) {\n window->title(title);\n });\n\n return window;\n}\n\nWindow *window_create_from_file(String path)\n{\n auto root = markup::parse_file(path);\n\n auto window = window_create_from_markup(root);\n\n widget_apply_attribute_from_markup(window->root(), root);\n widget_create_childs_from_markup(window->root(), root);\n\n return window;\n}\n\nWidget *widget_create_from_file(Widget *parent, String path)\n{\n auto root = markup::parse_file(path);\n\n auto widget = widget_create_from_markup(parent, root);\n widget_create_childs_from_markup(widget, root);\n\n return widget;\n}" }, { "alpha_fraction": 0.41523680090904236, "alphanum_fraction": 0.5010294914245605, "avg_line_length": 46.92763137817383, "blob_id": "07caf0f4982d6d27a6f94474bea8b9e25117c393", "content_id": "8b792e56fcd79505c3f099de9a133dd894a6c282", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7285, "license_type": "permissive", "max_line_length": 47, "num_lines": 152, "path": "/libraries/libgraphic/ColorsNames.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#define COLOR_LIST(__ENTRY) \\\n __ENTRY(TRANSPARENT, 0xFFFFFF00) \\\n __ENTRY(BLACKTRANSPARENT, 0x00000000) \\\n __ENTRY(WHITETRANSPARENT, 0xFFFFFF00) \\\n __ENTRY(ALICEBLUE, 0xF0F8FFFF) \\\n __ENTRY(ANTIQUEWHITE, 0xFAEBD7FF) \\\n __ENTRY(AQUA, 0x00FFFFFF) \\\n __ENTRY(AQUAMARINE, 0x7FFFD4FF) \\\n __ENTRY(AZURE, 0xF0FFFFFF) \\\n __ENTRY(BEIGE, 0xF5F5DCFF) \\\n __ENTRY(BISQUE, 0xFFE4C4FF) \\\n __ENTRY(BLACK, 0x000000FF) \\\n __ENTRY(BLANCHEDALMOND, 0xFFEBCDFF) \\\n __ENTRY(BLUE, 0x0000FFFF) \\\n __ENTRY(BLUEVIOLET, 0x8A2BE2FF) \\\n __ENTRY(BROWN, 0xA52A2AFF) \\\n __ENTRY(BURLYWOOD, 0xDEB887FF) \\\n __ENTRY(CADETBLUE, 0x5F9EA0FF) \\\n __ENTRY(CHARTREUSE, 0x7FFF00FF) \\\n __ENTRY(CHOCOLATE, 0xD2691EFF) \\\n __ENTRY(CORAL, 0xFF7F50FF) \\\n __ENTRY(CORNFLOWERBLUE, 0x6495EDFF) \\\n __ENTRY(CORNSILK, 0xFFF8DCFF) \\\n __ENTRY(CRIMSON, 0xDC143CFF) \\\n __ENTRY(CYAN, 0x00FFFFFF) \\\n __ENTRY(DARKBLUE, 0x00008BFF) \\\n __ENTRY(DARKCYAN, 0x008B8BFF) \\\n __ENTRY(DARKGOLDENROD, 0xB8860BFF) \\\n __ENTRY(DARKGRAY, 0xA9A9A9FF) \\\n __ENTRY(DARKGREY, 0xA9A9A9FF) \\\n __ENTRY(DARKGREEN, 0x006400FF) \\\n __ENTRY(DARKKHAKI, 0xBDB76BFF) \\\n __ENTRY(DARKMAGENTA, 0x8B008BFF) \\\n __ENTRY(DARKOLIVEGREEN, 0x556B2FFF) \\\n __ENTRY(DARKORANGE, 0xFF8C00FF) \\\n __ENTRY(DARKORCHID, 0x9932CCFF) \\\n __ENTRY(DARKRED, 0x8B0000FF) \\\n __ENTRY(DARKSALMON, 0xE9967AFF) \\\n __ENTRY(DARKSEAGREEN, 0x8FBC8FFF) \\\n __ENTRY(DARKSLATEBLUE, 0x483D8BFF) \\\n __ENTRY(DARKSLATEGRAY, 0x2F4F4FFF) \\\n __ENTRY(DARKSLATEGREY, 0x2F4F4FFF) \\\n __ENTRY(DARKTURQUOISE, 0x00CED1FF) \\\n __ENTRY(DARKVIOLET, 0x9400D3FF) \\\n __ENTRY(DEEPPINK, 0xFF1493FF) \\\n __ENTRY(DEEPSKYBLUE, 0x00BFFFFF) \\\n __ENTRY(DIMGRAY, 0x696969FF) \\\n __ENTRY(DIMGREY, 0x696969FF) \\\n __ENTRY(DODGERBLUE, 0x1E90FFFF) \\\n __ENTRY(FIREBRICK, 0xB22222FF) \\\n __ENTRY(FLORALWHITE, 0xFFFAF0FF) \\\n __ENTRY(FORESTGREEN, 0x228B22FF) \\\n __ENTRY(FUCHSIA, 0xFF00FFFF) \\\n __ENTRY(GAINSBORO, 0xDCDCDCFF) \\\n __ENTRY(GHOSTWHITE, 0xF8F8FFFF) \\\n __ENTRY(GOLD, 0xFFD700FF) \\\n __ENTRY(GOLDENROD, 0xDAA520FF) \\\n __ENTRY(GRAY, 0x808080FF) \\\n __ENTRY(GREY, 0x808080FF) \\\n __ENTRY(GREEN, 0x008000FF) \\\n __ENTRY(GREENYELLOW, 0xADFF2FFF) \\\n __ENTRY(HONEYDEW, 0xF0FFF0FF) \\\n __ENTRY(HOTPINK, 0xFF69B4FF) \\\n __ENTRY(INDIANRED, 0xCD5C5CFF) \\\n __ENTRY(INDIGO, 0x4B0082FF) \\\n __ENTRY(IVORY, 0xFFFFF0FF) \\\n __ENTRY(KHAKI, 0xF0E68CFF) \\\n __ENTRY(LAVENDER, 0xE6E6FAFF) \\\n __ENTRY(LAVENDERBLUSH, 0xFFF0F5FF) \\\n __ENTRY(LAWNGREEN, 0x7CFC00FF) \\\n __ENTRY(LEMONCHIFFON, 0xFFFACDFF) \\\n __ENTRY(LIGHTBLUE, 0xADD8E6FF) \\\n __ENTRY(LIGHTCORAL, 0xF08080FF) \\\n __ENTRY(LIGHTCYAN, 0xE0FFFFFF) \\\n __ENTRY(LIGHTGOLDENRODYELLOW, 0xFAFAD2FF) \\\n __ENTRY(LIGHTGRAY, 0xD3D3D3FF) \\\n __ENTRY(LIGHTGREY, 0xD3D3D3FF) \\\n __ENTRY(LIGHTGREEN, 0x90EE90FF) \\\n __ENTRY(LIGHTPINK, 0xFFB6C1FF) \\\n __ENTRY(LIGHTSALMON, 0xFFA07AFF) \\\n __ENTRY(LIGHTSEAGREEN, 0x20B2AAFF) \\\n __ENTRY(LIGHTSKYBLUE, 0x87CEFAFF) \\\n __ENTRY(LIGHTSLATEGRAY, 0x778899FF) \\\n __ENTRY(LIGHTSLATEGREY, 0x778899FF) \\\n __ENTRY(LIGHTSTEELBLUE, 0xB0C4DEFF) \\\n __ENTRY(LIGHTYELLOW, 0xFFFFE0FF) \\\n __ENTRY(LIME, 0x00FF00FF) \\\n __ENTRY(LIMEGREEN, 0x32CD32FF) \\\n __ENTRY(LINEN, 0xFAF0E6FF) \\\n __ENTRY(MAGENTA, 0xFF00FFFF) \\\n __ENTRY(MAROON, 0x800000FF) \\\n __ENTRY(MEDIUMAQUAMARINE, 0x66CDAAFF) \\\n __ENTRY(MEDIUMBLUE, 0x0000CDFF) \\\n __ENTRY(MEDIUMORCHID, 0xBA55D3FF) \\\n __ENTRY(MEDIUMPURPLE, 0x9370DBFF) \\\n __ENTRY(MEDIUMSEAGREEN, 0x3CB371FF) \\\n __ENTRY(MEDIUMSLATEBLUE, 0x7B68EEFF) \\\n __ENTRY(MEDIUMSPRINGGREEN, 0x00FA9AFF) \\\n __ENTRY(MEDIUMTURQUOISE, 0x48D1CCFF) \\\n __ENTRY(MEDIUMVIOLETRED, 0xC71585FF) \\\n __ENTRY(MIDNIGHTBLUE, 0x191970FF) \\\n __ENTRY(MINTCREAM, 0xF5FFFAFF) \\\n __ENTRY(MISTYROSE, 0xFFE4E1FF) \\\n __ENTRY(MOCCASIN, 0xFFE4B5FF) \\\n __ENTRY(NAVAJOWHITE, 0xFFDEADFF) \\\n __ENTRY(NAVY, 0x000080FF) \\\n __ENTRY(OLDLACE, 0xFDF5E6FF) \\\n __ENTRY(OLIVE, 0x808000FF) \\\n __ENTRY(OLIVEDRAB, 0x6B8E23FF) \\\n __ENTRY(ORANGE, 0xFFA500FF) \\\n __ENTRY(ORANGERED, 0xFF4500FF) \\\n __ENTRY(ORCHID, 0xDA70D6FF) \\\n __ENTRY(PALEGOLDENROD, 0xEEE8AAFF) \\\n __ENTRY(PALEGREEN, 0x98FB98FF) \\\n __ENTRY(PALETURQUOISE, 0xAFEEEEFF) \\\n __ENTRY(PALEVIOLETRED, 0xDB7093FF) \\\n __ENTRY(PAPAYAWHIP, 0xFFEFD5FF) \\\n __ENTRY(PEACHPUFF, 0xFFDAB9FF) \\\n __ENTRY(PERU, 0xCD853FFF) \\\n __ENTRY(PINK, 0xFFC0CBFF) \\\n __ENTRY(PLUM, 0xDDA0DDFF) \\\n __ENTRY(POWDERBLUE, 0xB0E0E6FF) \\\n __ENTRY(PURPLE, 0x800080FF) \\\n __ENTRY(REBECCAPURPLE, 0x663399FF) \\\n __ENTRY(RED, 0xFF0000FF) \\\n __ENTRY(ROSYBROWN, 0xBC8F8FFF) \\\n __ENTRY(ROYALBLUE, 0x4169E1FF) \\\n __ENTRY(SADDLEBROWN, 0x8B4513FF) \\\n __ENTRY(SALMON, 0xFA8072FF) \\\n __ENTRY(SANDYBROWN, 0xF4A460FF) \\\n __ENTRY(SEAGREEN, 0x2E8B57FF) \\\n __ENTRY(SEASHELL, 0xFFF5EEFF) \\\n __ENTRY(SIENNA, 0xA0522DFF) \\\n __ENTRY(SILVER, 0xC0C0C0FF) \\\n __ENTRY(SKYBLUE, 0x87CEEBFF) \\\n __ENTRY(SLATEBLUE, 0x6A5ACDFF) \\\n __ENTRY(SLATEGRAY, 0x708090FF) \\\n __ENTRY(SLATEGREY, 0x708090FF) \\\n __ENTRY(SNOW, 0xFFFAFAFF) \\\n __ENTRY(SPRINGGREEN, 0x00FF7FFF) \\\n __ENTRY(STEELBLUE, 0x4682B4FF) \\\n __ENTRY(TAN, 0xD2B48CFF) \\\n __ENTRY(TEAL, 0x008080FF) \\\n __ENTRY(THISTLE, 0xD8BFD8FF) \\\n __ENTRY(TOMATO, 0xFF6347FF) \\\n __ENTRY(TURQUOISE, 0x40E0D0FF) \\\n __ENTRY(VIOLET, 0xEE82EEFF) \\\n __ENTRY(WHEAT, 0xF5DEB3FF) \\\n __ENTRY(WHITE, 0xFFFFFFFF) \\\n __ENTRY(WHITESMOKE, 0xF5F5F5FF) \\\n __ENTRY(YELLOW, 0xFFFF00FF) \\\n __ENTRY(YELLOWGREEN, 0x9ACD32FF)\n" }, { "alpha_fraction": 0.6634078025817871, "alphanum_fraction": 0.6634078025817871, "avg_line_length": 16.487804412841797, "blob_id": "b9cf80b882ab35ba7efd521b77e57fedf41b90a1", "content_id": "6bfef29c7ebc0571b5ce30115d336fc25ebf84ae", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 716, "license_type": "permissive", "max_line_length": 63, "num_lines": 41, "path": "/kernel/tasking/Domain.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Path.h>\n\n#include \"kernel/node/Handle.h\"\n#include \"kernel/node/Node.h\"\n\nclass Domain\n{\nprivate:\n RefPtr<FsNode> _root;\n\npublic:\n RefPtr<FsNode> root() { return _root; }\n\n Domain();\n\n Domain(const Domain &other);\n\n ~Domain();\n\n Domain &operator=(const Domain &other);\n\n RefPtr<FsNode> find(Path path);\n\n ResultOr<RefPtr<FsHandle>> open(Path path, OpenFlag flags);\n\n ResultOr<RefPtr<FsHandle>> connect(Path path);\n\n Result link(Path path, RefPtr<FsNode> node);\n\n Result unlink(Path path);\n\n Result rename(Path old_path, Path new_path);\n\n Result mkdir(Path path);\n\n Result mkpipe(Path path);\n\n Result mklink(Path old_path, Path new_path);\n};" }, { "alpha_fraction": 0.6535764336585999, "alphanum_fraction": 0.6535764336585999, "avg_line_length": 18.80555534362793, "blob_id": "976582364bfd4b086b7236a327705b39cb7a0ebb", "content_id": "9def7c966719e427f34f6d3cd7a28bf836a2373d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 713, "license_type": "permissive", "max_line_length": 75, "num_lines": 36, "path": "/libraries/libwidget/Button.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Icon.h>\n#include <libwidget/Widget.h>\n\nclass Button : public Widget\n{\npublic:\n enum Style\n {\n TEXT,\n OUTLINE,\n FILLED,\n };\n\nprivate:\n bool _mouse_over = false;\n bool _mouse_press = false;\n\n Style _style = TEXT;\n\npublic:\n Button(Widget *parent, Style style);\n\n Button(Widget *parent, Style style, RefPtr<Icon> icon);\n\n Button(Widget *parent, Style style, String text);\n\n Button(Widget *parent, Style style, RefPtr<Icon> icon, String text);\n\n Button(Widget *parent, Style style, RefPtr<Bitmap> image, String text);\n\n void paint(Painter &painter, const Recti &rectangle) override;\n\n void event(Event *event) override;\n};\n" }, { "alpha_fraction": 0.6978480219841003, "alphanum_fraction": 0.7031181454658508, "avg_line_length": 21.544553756713867, "blob_id": "a551c99d6a6acb156e9b3a92f5cdb32bdc366f01", "content_id": "5f42535a90cb55b6770d5f00dd637048fa67b5d4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2277, "license_type": "permissive", "max_line_length": 70, "num_lines": 101, "path": "/libraries/libc/unistd.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n#include <stddef.h>\n#include <stdint.h>\n#include <sys/types.h>\n\n__BEGIN_HEADER\n\nextern char **environ;\n\npid_t getpid(void);\npid_t getppid(void);\n\nint close(int fd);\n\npid_t fork(void);\n\nint execl(const char *path, const char *arg, ...);\nint execlp(const char *file, const char *arg, ...);\nint execle(const char *path, const char *arg, ...);\nint execv(const char *path, char *const argv[]);\nint execvp(const char *file, char *const argv[]);\nint execvpe(const char *file, char *const argv[], char *const envp[]);\nint execve(const char *name, char *const argv[], char *const envp[]);\nvoid _exit(int status);\n\nint setuid(uid_t uid);\n\nuid_t getuid(void);\nuid_t geteuid(void);\ngid_t getgid(void);\ngid_t getegid(void);\nchar *getcwd(char *buf, size_t size);\nint pipe(int pipefd[2]);\nint dup(int oldfd);\nint dup2(int oldfd, int newfd);\n\npid_t tcgetpgrp(int fd);\nint tcsetpgrp(int fd, pid_t pgrp);\n\nssize_t write(int fd, const void *buf, size_t count);\nssize_t read(int fd, void *buf, size_t count);\n\nint symlink(const char *target, const char *linkpath);\nssize_t readlink(const char *pathname, char *buf, size_t bufsiz);\n\nint chdir(const char *path);\n// int fchdir(int fd);\nint isatty(int fd);\n\nunsigned int sleep(unsigned int seconds);\nint usleep(useconds_t usec);\noff_t lseek(int fd, off_t offset, int whence);\n\nint access(const char *pathname, int mode);\n\nint getopt(int argc, char *const argv[], const char *optstring);\n\nextern char *optarg;\nextern int optind, opterr, optopt;\n\nint unlink(const char *pathname);\n\nstruct utimbuf\n{\n time_t actime;\n time_t modtime;\n};\nchar *ttyname(int fd);\nint utime(const char *filename, const struct utimbuf *times);\nint rmdir(const char *pathname); /* TODO rm probably just works */\nint chown(const char *pathname, uid_t owner, gid_t group);\nchar *getlogin(void);\n\n#define STDIN_FILENO 0\n#define STDOUT_FILENO 1\n#define STDERR_FILENO 2\n\n#define SEEK_SET 0\n#define SEEK_CUR 1\n#define SEEK_END 2\n\n#define F_OK 0\n#define R_OK 4\n#define W_OK 2\n#define X_OK 1\n\nint gethostname(char *name, size_t len);\nint sethostname(const char *name, size_t len);\n\npid_t setsid(void);\nint setpgid(pid_t, pid_t);\npid_t getpgid(pid_t);\n\nunsigned int alarm(unsigned int seconds);\n\nvoid *sbrk(intptr_t increment);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.7533718943595886, "alphanum_fraction": 0.7533718943595886, "avg_line_length": 23.714284896850586, "blob_id": "ad40f4658baabafa1c45b36b66f832c3e0db9854", "content_id": "a98773fc3d0cbb912ce6bec0fe33689d032b436e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 519, "license_type": "permissive", "max_line_length": 77, "num_lines": 21, "path": "/apps/demo/Demos.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/eventloop/Timer.h>\n#include <libwidget/Application.h>\n#include <libwidget/Widget.h>\n\nvoid colors_draw(Painter &painter, Recti screen, float time);\n\nvoid graphics_draw(Painter &painter, Recti screen, float time);\n\nvoid lines_draw(Painter &painter, Recti screen, float time);\n\nvoid path_draw(Painter &Painter, Recti screen, float time);\n\ntypedef void (*DrawDemoCallback)(Painter &painter, Recti screen, float time);\n\nstruct Demo\n{\n const char *name;\n DrawDemoCallback callback;\n};\n" }, { "alpha_fraction": 0.5123513340950012, "alphanum_fraction": 0.5144861340522766, "avg_line_length": 18.75301170349121, "blob_id": "9d3dd14ca73435900466c2f9254e00b3673276d8", "content_id": "f25489e148ced3b17eafeb68dade75721712655f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3279, "license_type": "permissive", "max_line_length": 105, "num_lines": 166, "path": "/libraries/libsystem/Handle.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Syscalls.h>\n\n#include <libsystem/process/Process.h>\n\n#include <libutils/Optional.h>\n#include <libutils/ResultOr.h>\n#include <libutils/String.h>\n\nnamespace System\n{\n\nclass Handle\n{\nprivate:\n int _handle = HANDLE_INVALID_ID;\n Result _result = ERR_BAD_HANDLE;\n\n __noncopyable(Handle);\n\npublic:\n Handle(int handle) : _handle(handle), _result(handle != HANDLE_INVALID_ID ? SUCCESS : ERR_BAD_HANDLE)\n {\n }\n\n Handle(const String path, OpenFlag flags)\n {\n auto resolved_path = process_resolve(path);\n _result = hj_handle_open(&_handle, resolved_path.cstring(), resolved_path.length(), flags);\n }\n\n Handle(Handle &&other)\n {\n _handle = exchange_and_return_initial_value(other._handle, HANDLE_INVALID_ID);\n _result = exchange_and_return_initial_value(other._result, ERR_BAD_HANDLE);\n }\n\n Handle &operator=(Handle &&other)\n {\n swap(_handle, other._handle);\n swap(_result, other._result);\n\n return *this;\n }\n\n ~Handle()\n {\n if (_handle != HANDLE_INVALID_ID)\n {\n hj_handle_close(_handle);\n _handle = -1;\n }\n }\n\n ResultOr<size_t> read(void *buffer, size_t size)\n {\n size_t data_read = 0;\n _result = hj_handle_read(_handle, buffer, size, &data_read);\n\n if (_result != SUCCESS)\n {\n return _result;\n }\n else\n {\n return data_read;\n }\n }\n\n ResultOr<size_t> write(const void *buffer, size_t size)\n {\n size_t data_written = 0;\n _result = hj_handle_write(_handle, buffer, size, &data_written);\n\n if (_result != SUCCESS)\n {\n return _result;\n }\n else\n {\n return data_written;\n }\n }\n\n Result call(IOCall request, void *args)\n {\n _result = hj_handle_call(_handle, request, args);\n return _result;\n }\n\n ResultOr<int> seek(int offset, Whence whence)\n {\n int result_offset = 0;\n\n _result = hj_handle_seek(_handle, offset, whence, &result_offset);\n\n if (_result != SUCCESS)\n {\n return _result;\n }\n else\n {\n return result_offset;\n }\n }\n\n ResultOr<int> tell()\n {\n int result_offset = 0;\n\n _result = hj_handle_seek(_handle, 0, WHENCE_HERE, &result_offset);\n\n if (_result != SUCCESS)\n {\n return _result;\n }\n else\n {\n return result_offset;\n }\n }\n\n ResultOr<FileState> stat()\n {\n FileState stat{};\n _result = hj_handle_stat(_handle, &stat);\n\n if (_result != SUCCESS)\n {\n return _result;\n }\n else\n {\n return stat;\n }\n }\n\n ResultOr<Handle> accept()\n {\n int connection_handle;\n _result = hj_handle_accept(_handle, &connection_handle);\n\n if (_result != SUCCESS)\n {\n return _result;\n }\n else\n {\n return Handle{connection_handle};\n }\n }\n\n bool valid()\n {\n return _handle != HANDLE_INVALID_ID;\n }\n};\n\nclass RawHandle\n{\npublic:\n virtual Handle &handle() = 0;\n};\n\n} // namespace System\n" }, { "alpha_fraction": 0.7081813216209412, "alphanum_fraction": 0.7097446322441101, "avg_line_length": 23.9350643157959, "blob_id": "57559cd86a950d078641cdd7131e8557bab8e695", "content_id": "c552a3ca8bdbe48d4243326d3f2ef52777390e47", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1919, "license_type": "permissive", "max_line_length": 78, "num_lines": 77, "path": "/libraries/libsystem/io/Stream.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n/* stream.h: generic io interface */\n\n#include <abi/Filesystem.h>\n#include <abi/IOCall.h>\n#include <abi/Paths.h>\n\n#include <libsystem/io/Handle.h>\n\nenum StreamBufferMode\n{\n STREAM_BUFFERED_NONE,\n STREAM_BUFFERED_LINE,\n STREAM_BUFFERED_BLOCK,\n};\n\n#define STREAM_BUFFER_SIZE 512\n\nstruct Stream;\n\n#ifndef __KERNEL__\nStream *__stream_get_in_stream();\nStream *__stream_get_out_stream();\nStream *__stream_get_err_stream();\nStream *__stream_get_log_stream();\n\n# define in_stream (__stream_get_in_stream())\n# define out_stream (__stream_get_out_stream())\n# define err_stream (__stream_get_err_stream())\n# define log_stream (__stream_get_log_stream())\n#else\nextern Stream *in_stream;\nextern Stream *out_stream;\nextern Stream *err_stream;\nextern Stream *log_stream;\n#endif\n\nStream *stream_open(const char *path, OpenFlag flags);\n\nStream *stream_open_handle(int handle_id, OpenFlag flags);\n\nResult stream_create_term(Stream **server, Stream **client);\n\nvoid stream_close(Stream *stream);\n\nvoid stream_cleanup(Stream **stream);\n\nvoid stream_set_read_buffer_mode(Stream *stream, StreamBufferMode mode);\n\nvoid stream_set_write_buffer_mode(Stream *stream, StreamBufferMode mode);\n\nsize_t stream_read(Stream *stream, void *buffer, size_t size);\n\nsize_t stream_write(Stream *stream, const void *buffer, size_t size);\n\nvoid stream_flush(Stream *stream);\n\nResult stream_call(Stream *stream, IOCall request, void *arg);\n\nint stream_seek(Stream *stream, int offset, Whence whence);\n\nint stream_tell(Stream *stream);\n\nvoid stream_stat(Stream *stream, FileState *stat);\n\nint stream_putchar(Stream *stream, char c);\n\nchar stream_getchar(Stream *stream);\n\nint stream_ungetchar(Stream *stream, char c);\n\nbool stream_is_end_file(Stream *stream);\n\nint stream_format(Stream *stream, const char *fmt, ...);\n\nint stream_vprintf(Stream *stream, const char *fmt, va_list va);" }, { "alpha_fraction": 0.6924939751625061, "alphanum_fraction": 0.694915235042572, "avg_line_length": 18.66666603088379, "blob_id": "c380eb7b326082760e3684d394b345c48334aeab", "content_id": "2a17cdb8d8b086a250e5e4610dda190ece385891", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 413, "license_type": "permissive", "max_line_length": 70, "num_lines": 21, "path": "/apps/terminal/Common.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Painter.h>\n#include <libterminal/Cell.h>\n\nRefPtr<Font> font();\n\nRecti cell_bound(int x, int y);\n\nVec2i cell_size();\n\nvoid render_cell(\n Painter &painter,\n int x,\n int y,\n Codepoint codepoint,\n terminal::Color foreground,\n terminal::Color background,\n terminal::Attributes attributes);\n\nvoid render_cell(Painter &painter, int x, int y, terminal::Cell cell);\n" }, { "alpha_fraction": 0.5951492786407471, "alphanum_fraction": 0.625, "avg_line_length": 10.911110877990723, "blob_id": "7bdf672e93d8162d0c1b3c27d6c279926641d7e6", "content_id": "b5f6c8b3768baeb0232f38857dd1b4c3446f8cb9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 536, "license_type": "permissive", "max_line_length": 32, "num_lines": 45, "path": "/libraries/libmedia/WAVE.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Endian.h>\n\nnamespace media::wave\n{\n\nstruct RIFFChunk\n{\n char id[4];\n le_uint32_t size;\n};\n\nstruct RIFF\n{\n RIFFChunk chunk;\n\n char format[4];\n};\n\nstruct FMT\n{\n RIFFChunk chunk;\n\n le_uint16_t audio_format;\n le_uint16_t num_channel;\n le_uint32_t sample_rate;\n le_uint32_t byte_rate;\n le_uint16_t byte_per_block;\n le_uint16_t bits_per_sample;\n};\n\nstruct DATA\n{\n RIFFChunk chunk;\n};\n\nstruct WAVE\n{\n RIFF riff;\n FMT fmt;\n DATA data;\n};\n\n} // namespace media::wave\n" }, { "alpha_fraction": 0.583928108215332, "alphanum_fraction": 0.604017972946167, "avg_line_length": 22.49689483642578, "blob_id": "ba33dbf2900f283d12a1e6a4e28c7b7b67a1a765", "content_id": "c5de05899c100eee391eb79b059274f780f6d6ec", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3783, "license_type": "permissive", "max_line_length": 116, "num_lines": 161, "path": "/apps/utilities/displayctl.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Paths.h>\n\n#include <libutils/ArgParse.h>\n\n#include <libsystem/Result.h>\n#include <libsystem/io/Connection.h>\n#include <libsystem/io/File.h>\n#include <libsystem/io/Socket.h>\n#include <libsystem/io_new/Streams.h>\n\n#include \"compositor/Protocol.h\"\n\nstatic const IOCallDisplayModeArgs GFX_MODES[] = {\n {640, 360},\n {800, 600},\n {1024, 768},\n {1280, 720},\n {1280, 800},\n {1280, 1024},\n {1360, 768},\n {1366, 768},\n {1920, 1080},\n {3840, 2160},\n};\n\nOptional<IOCallDisplayModeArgs> gfxmode_by_name(String &name)\n{\n for (size_t i = 0; i < __array_length(GFX_MODES); i++)\n {\n auto &gfx_mode = GFX_MODES[i];\n\n if (String::format(\"{}x{}\", gfx_mode.width, gfx_mode.height) == name)\n {\n return gfx_mode;\n }\n }\n\n return {};\n}\n\nint gfxmode_list()\n{\n for (size_t i = 0; i < __array_length(GFX_MODES); i++)\n {\n auto &gfx_mode = GFX_MODES[i];\n\n System::outln(\"- {}x{}\", gfx_mode.width, gfx_mode.height);\n }\n\n return PROCESS_SUCCESS;\n}\n\nint gfxmode_get(Stream *framebuffer_device)\n{\n IOCallDisplayModeArgs framebuffer_info;\n\n if (stream_call(framebuffer_device, IOCALL_DISPLAY_GET_MODE, &framebuffer_info) < 0)\n {\n handle_printf_error(framebuffer_device, \"Ioctl to \" FRAMEBUFFER_DEVICE_PATH \" failed\");\n return PROCESS_FAILURE;\n }\n\n System::outln(\"Height: {}\\nWidth: {}\\n\",\n framebuffer_info.width,\n framebuffer_info.height);\n\n return PROCESS_SUCCESS;\n}\n\nint gfxmode_set_compositor(IOCallDisplayModeArgs mode)\n{\n Connection *compositor_connection = socket_connect(\"/Session/compositor.ipc\");\n\n if (handle_has_error(compositor_connection))\n {\n handle_printf_error(compositor_connection, \"Failed to connect to the compositor (Failling back on iocall)\");\n return PROCESS_FAILURE;\n }\n\n CompositorMessage message = (CompositorMessage){\n .type = COMPOSITOR_MESSAGE_SET_RESOLUTION,\n .set_resolution = {\n mode.width,\n mode.height,\n },\n };\n\n connection_send(compositor_connection, &message, sizeof(message));\n\n return PROCESS_SUCCESS;\n}\n\nint gfxmode_set_iocall(Stream *device, IOCallDisplayModeArgs mode)\n{\n if (stream_call(device, IOCALL_DISPLAY_SET_MODE, &mode) != SUCCESS)\n {\n handle_printf_error(device, \"Ioctl to \" FRAMEBUFFER_DEVICE_PATH \" failed\");\n return PROCESS_FAILURE;\n }\n\n return PROCESS_SUCCESS;\n}\n\nint gfxmode_set(String &mode_name)\n{\n auto mode = gfxmode_by_name(mode_name);\n\n if (!mode)\n {\n System::errln(\"Error: unknow graphic mode: {}\", mode_name);\n return PROCESS_FAILURE;\n }\n\n int result = gfxmode_set_compositor(*mode);\n\n if (result != 0)\n {\n __cleanup(stream_cleanup) Stream *device = stream_open(FRAMEBUFFER_DEVICE_PATH, OPEN_READ);\n result = gfxmode_set_iocall(device, *mode);\n }\n\n if (result == 0)\n {\n System::outln(\"Graphic mode set to: {}\", mode_name);\n return PROCESS_SUCCESS;\n }\n else\n {\n return PROCESS_FAILURE;\n }\n}\n\nint main(int argc, const char *argv[])\n{\n\n ArgParse args{};\n\n args.show_help_if_no_option_given();\n args.should_abort_on_failure();\n\n args.usage(\"\");\n args.usage(\"OPTION...\");\n\n args.prologue(\"Get or set graphics modes.\");\n\n args.option('l', \"list\", \"List all available graphics modes.\", [](auto &) {\n return gfxmode_list();\n });\n\n args.option('g', \"get\", \"Get the current graphic mode.\", [](auto &) {\n return gfxmode_list();\n });\n\n args.option_string('s', \"set\", \"Set graphic mode.\", [&](String &mode) {\n return gfxmode_set(mode);\n });\n\n args.epiloge(\"Options can be combined.\");\n\n return args.eval(argc, argv);\n}\n" }, { "alpha_fraction": 0.5890699028968811, "alphanum_fraction": 0.6158697009086609, "avg_line_length": 25.81690216064453, "blob_id": "b5d990b196654c377a67508c2d1948a52a604c40", "content_id": "671767e173672f0bc246e490ea147526366f3688", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1903, "license_type": "permissive", "max_line_length": 106, "num_lines": 71, "path": "/apps/task-manager/widgets/CPUGraph.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Syscalls.h>\n\n#include <libutils/StringBuilder.h>\n\n#include <libsystem/eventloop/Timer.h>\n#include <libsystem/system/System.h>\n\n#include <libwidget/Container.h>\n#include <libwidget/IconPanel.h>\n#include <libwidget/Label.h>\n\n#include <stdio.h>\n\n#include \"task-manager/widgets/CPUGraph.h\"\n\nnamespace task_manager\n{\n\nCPUGraph::CPUGraph(Widget *parent, RefPtr<TaskModel> model)\n : Graph(parent, 256, Colors::SEAGREEN),\n _model(model)\n{\n layout(VFLOW(0));\n insets(Insetsi(8));\n flags(Widget::FILL);\n\n auto icon_and_text = new Container(this);\n icon_and_text->layout(HFLOW(4));\n new IconPanel(icon_and_text, Icon::get(\"memory\"));\n new Label(icon_and_text, \"Processor\");\n\n auto cpu_filler = new Container(this);\n cpu_filler->flags(Widget::FILL);\n\n _label_average = new Label(this, \"Average: nil%\", Anchor::RIGHT);\n _label_greedy = new Label(this, \"Most greedy: nil\", Anchor::RIGHT);\n _label_uptime = new Label(this, \"Uptime: nil\", Anchor::RIGHT);\n\n _graph_timer = own<Timer>(100, [&]() {\n SystemStatus status{};\n hj_system_status(&status);\n\n record(status.cpu_usage / 100.0);\n });\n\n _graph_timer->start();\n\n _text_timer = own<Timer>(1000, [&]() {\n SystemStatus status{};\n hj_system_status(&status);\n\n auto greedy = _model->cpu_greedy();\n\n _label_average->text(String::format(\"Average: {}%\", (int)(average() * 100.0)));\n _label_greedy->text(String::format(\"Most greedy: {}\", greedy));\n\n ElapsedTime seconds = status.uptime;\n int days = seconds / 86400;\n seconds %= 86400;\n int hours = seconds / 3600;\n seconds %= 3600;\n int minutes = seconds / 60;\n seconds %= 60;\n\n _label_uptime->text(String::format(\"Uptime: {03}:{02}:{02}:{02}\", days, hours, minutes, seconds));\n });\n\n _text_timer->start();\n}\n\n} // namespace task_manager" }, { "alpha_fraction": 0.6651785969734192, "alphanum_fraction": 0.6678571701049805, "avg_line_length": 23.34782600402832, "blob_id": "60715102c77423cf56bbbfb4cb5c3fdba23cb987", "content_id": "63c965ac09d3d9dff6217e4d11c69207a7b38859", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1120, "license_type": "permissive", "max_line_length": 101, "num_lines": 46, "path": "/kernel/tasking/Tasking.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"kernel/tasking/Tasking.h\"\n#include \"kernel/scheduling/Scheduler.h\"\n#include \"kernel/system/System.h\"\n#include \"kernel/tasking/Task.h\"\n\nstatic Iteration destroy_task_if_canceled(void *target, Task *task)\n{\n __unused(target);\n\n if (task->state() == TASK_STATE_CANCELED)\n {\n task_destroy(task);\n }\n\n return Iteration::CONTINUE;\n}\n\nvoid garbage_collector()\n{\n while (true)\n {\n task_sleep(scheduler_running(), 100);\n task_iterate(nullptr, destroy_task_if_canceled);\n }\n}\n\nvoid tasking_initialize()\n{\n logger_info(\"Initializing tasking...\");\n\n Task *idle_task = task_spawn(nullptr, \"idle\", system_hang, nullptr, false);\n task_go(idle_task);\n idle_task->state(TASK_STATE_HANG);\n\n scheduler_did_create_idle_task(idle_task);\n\n Task *kernel_task = task_spawn(nullptr, \"system\", nullptr, nullptr, false);\n task_go(kernel_task);\n\n scheduler_did_create_running_task(kernel_task);\n\n Task *garbage_task = task_spawn(nullptr, \"garbage-collector\", garbage_collector, nullptr, false);\n task_go(garbage_task);\n\n logger_info(\"Tasking initialized!\");\n}\n" }, { "alpha_fraction": 0.477011501789093, "alphanum_fraction": 0.5287356376647949, "avg_line_length": 14.818181991577148, "blob_id": "903d78392d3105b08a5d09d02402d86c76536b82", "content_id": "ee004adeb297115366b6c2a823d9076794e98468", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 174, "license_type": "permissive", "max_line_length": 33, "num_lines": 11, "path": "/archs/x86_64/kernel/x86_64.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"archs/x86/kernel/x86.h\"\n\nstatic inline uint64_t RBP()\n{\n uint64_t r;\n asm volatile(\"mov %%rbp, %0\"\n : \"=r\"(r));\n return r;\n}\n" }, { "alpha_fraction": 0.6474394798278809, "alphanum_fraction": 0.6488463878631592, "avg_line_length": 22.529800415039062, "blob_id": "b7142830bc0d3972c070f8d29932b71c3feba535", "content_id": "4da97de46549ca1e3d40b993bb085771dc816445", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3554, "license_type": "permissive", "max_line_length": 116, "num_lines": 151, "path": "/libraries/libsystem/io_new/Streams.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/String.h>\n\n#include <libsystem/Handle.h>\n#include <libsystem/io_new/Format.h>\n#include <libsystem/io_new/MemoryWriter.h>\n#include <libsystem/io_new/Reader.h>\n#include <libsystem/io_new/Scanner.h>\n#include <libsystem/io_new/Writer.h>\n\nnamespace System\n{\n\nclass InStream :\n public Reader,\n public RawHandle\n{\nprivate:\n Handle _handle{0};\n\npublic:\n using Reader::read;\n\n ResultOr<size_t> read(void *buffer, size_t size) override { return _handle.read(buffer, size); }\n Handle &handle() override { return _handle; }\n};\n\nclass OutStream :\n public Writer,\n public RawHandle\n{\nprivate:\n Handle _handle{1};\n\npublic:\n using Writer::write;\n\n ResultOr<size_t> write(const void *buffer, size_t size) override { return _handle.write(buffer, size); }\n Handle &handle() override { return _handle; }\n};\n\nclass ErrStream :\n public Writer,\n public RawHandle\n\n{\nprivate:\n Handle _handle{2};\n\npublic:\n using Writer::write;\n\n ResultOr<size_t> write(const void *buffer, size_t size) override { return _handle.write(buffer, size); }\n Handle &handle() override { return _handle; }\n};\n\nclass LogStream :\n public Writer,\n public RawHandle\n{\nprivate:\n Handle _handle{3};\n\npublic:\n using Writer::write;\n\n ResultOr<size_t> write(const void *buffer, size_t size) override { return _handle.write(buffer, size); }\n Handle &handle() override { return _handle; }\n};\n\nInStream &in();\n\nOutStream &out();\n\nErrStream &err();\n\nLogStream &log();\n\nstatic inline ResultOr<String> inln()\n{\n Scanner<Reader &> scan{in()};\n MemoryWriter writer{};\n\n while (!(scan.ended() || scan.current() == '\\n'))\n {\n writer.write(scan.current());\n out().write(scan.current());\n scan.foreward();\n }\n\n out().write('\\n');\n scan.skip('\\n');\n\n return String{writer.string()};\n}\n\ntemplate <Formatable... Args>\nstatic ResultOr<size_t> print(Writer &writer, const char *fmt, Args... args)\n{\n StringScanner scan{fmt, strlen(fmt)};\n auto format_result = format(writer, scan, forward<Args>(args)...);\n\n if (!format_result)\n {\n return format_result.result();\n }\n\n return *format_result;\n}\n\ntemplate <Formatable... Args>\nstatic ResultOr<size_t> println(Writer &writer, const char *fmt, Args... args)\n{\n StringScanner scan{fmt, strlen(fmt)};\n auto format_result = format(writer, scan, forward<Args>(args)...);\n\n if (!format_result)\n {\n return format_result.result();\n }\n\n auto endline_result = writer.write('\\n');\n\n if (endline_result != SUCCESS)\n {\n return endline_result;\n }\n\n return *format_result + 1;\n}\n\ntemplate <Formatable... Args>\nstatic ResultOr<size_t> out(const char *fmt, Args... args) { return print(out(), fmt, forward<Args>(args)...); }\n\ntemplate <Formatable... Args>\nstatic ResultOr<size_t> outln(const char *fmt, Args... args) { return println(out(), fmt, forward<Args>(args)...); }\n\ntemplate <Formatable... Args>\nstatic ResultOr<size_t> err(const char *fmt, Args... args) { return print(err(), fmt, forward<Args>(args)...); }\n\ntemplate <Formatable... Args>\nstatic ResultOr<size_t> errln(const char *fmt, Args... args) { return println(err(), fmt, forward<Args>(args)...); }\n\ntemplate <Formatable... Args>\nstatic ResultOr<size_t> log(const char *fmt, Args... args) { return print(log(), fmt, forward<Args>(args)...); }\n\ntemplate <Formatable... Args>\nstatic ResultOr<size_t> logln(const char *fmt, Args... args) { return println(log(), fmt, forward<Args>(args)...); }\n\n} // namespace System\n\n" }, { "alpha_fraction": 0.71074378490448, "alphanum_fraction": 0.71074378490448, "avg_line_length": 11.736842155456543, "blob_id": "97eb1cfeb76deb79bc0023a68e999d4f83502588", "content_id": "8b86e420df119bde7bfade27f3b7df47ca0a279a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 242, "license_type": "permissive", "max_line_length": 38, "num_lines": 19, "path": "/apps/panel/widgets/DateAndTime.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/eventloop/Timer.h>\n\n#include <libwidget/Button.h>\n\nnamespace panel\n{\n\nclass DateAndTime : public Button\n{\nprivate:\n OwnPtr<Timer> _timer;\n\npublic:\n DateAndTime(Widget *parent);\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.7966101765632629, "alphanum_fraction": 0.7966101765632629, "avg_line_length": 22.600000381469727, "blob_id": "4f250d928993df2670abbff9414b149d0a29c4a0", "content_id": "f41780804982182ef8f90988125879ae5995850a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 118, "license_type": "permissive", "max_line_length": 49, "num_lines": 5, "path": "/apps/onboarding/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += ONBOARDING\n\nONBOARDING_NAME = onboarding\nONBOARDING_LIBS = widget settings markup graphic\nONBOARDING_ICONS =\n" }, { "alpha_fraction": 0.7266666889190674, "alphanum_fraction": 0.746666669845581, "avg_line_length": 29.200000762939453, "blob_id": "2ed787abc6ce0c291a81c1a65bd6f84590fc9df5", "content_id": "d8668e6b7af1bb94379fa5170fd3781c44c274f0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 150, "license_type": "permissive", "max_line_length": 87, "num_lines": 5, "path": "/contribs/ffmpeg/get-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\nVERSION=4.3\n\necho \"Getting FFMPEG version: $VERSION\"\ngit clone --depth 1 --branch release/$VERSION https://git.ffmpeg.org/ffmpeg.git sources" }, { "alpha_fraction": 0.791304349899292, "alphanum_fraction": 0.791304349899292, "avg_line_length": 22.200000762939453, "blob_id": "978722da9aa90e8aadd3fc579f8ccda71709fc83", "content_id": "b7566cd1ff34081bacc2a719131d84aa346de533", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 115, "license_type": "permissive", "max_line_length": 46, "num_lines": 5, "path": "/apps/settings/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += SETTINGS\n\nSETTINGS_NAME = settings\nSETTINGS_LIBS = widget settings graphic markup\nSETTINGS_ICONS = cog home" }, { "alpha_fraction": 0.7785714268684387, "alphanum_fraction": 0.7785714268684387, "avg_line_length": 20.538461685180664, "blob_id": "a1a556386b14cf9958dd4f4e0acade9bdfc37753", "content_id": "8cd170f7bedcbca570f6cdd6172aa51965a1e38c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 280, "license_type": "permissive", "max_line_length": 64, "num_lines": 13, "path": "/libraries/libsystem/io/Directory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/io/Handle.h>\n\nstruct Directory;\n\nDirectory *directory_open(const char *path, OpenFlag flags);\n\nvoid directory_close(Directory *directory);\n\nint directory_read(Directory *directory, DirectoryEntry *entry);\n\nbool directory_exist(const char *path);\n" }, { "alpha_fraction": 0.7138554453849792, "alphanum_fraction": 0.7138554453849792, "avg_line_length": 26.58333396911621, "blob_id": "3bce5ab4867e36855c700e4390a60045199ec23a", "content_id": "0538f2b869cea97227ddcf730451665dc7ff6d28", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": true, "language": "Makefile", "length_bytes": 332, "license_type": "permissive", "max_line_length": 70, "num_lines": 12, "path": "/thirdparty/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "ECHFS:=thirdparty/echfs/echfs-utils\nLIMINE:=thirdparty/limine/limine-install\nLIMINE_LOADER:=thirdparty/limine/limine.bin\n\n$(ECHFS):\n\tcd thirdparty/echfs/ && $(MAKE) all\n\n$(LIMINE):\n\tcd thirdparty/limine/ && $(MAKE) bootloader && $(MAKE) limine-install\n\n$(LIMINE_LOADER):\n\tcd thirdparty/limine/ && $(MAKE) bootloader && $(MAKE) all\n\n" }, { "alpha_fraction": 0.38805970549583435, "alphanum_fraction": 0.4029850661754608, "avg_line_length": 21.33333396911621, "blob_id": "fe8347f04252a6496856aa10ffff5d7d33501470", "content_id": "e2799d9cc356e9faca1494d1060c92430ee3833e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 871, "license_type": "permissive", "max_line_length": 64, "num_lines": 39, "path": "/libraries/libsystem/utils/Hexdump.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <ctype.h>\n#include <libsystem/io/Stream.h>\n\nstatic inline void hexdump(const void *ptr, int buflen)\n{\n unsigned char *buf = (unsigned char *)ptr;\n for (int i = 0; i < buflen; i += 16)\n {\n stream_format(out_stream, \"%06x: \", i);\n\n for (int j = 0; j < 16; j++)\n {\n if (i + j < buflen)\n {\n stream_format(out_stream, \"%02x \", buf[i + j]);\n }\n else\n {\n stream_format(out_stream, \" \");\n }\n }\n\n stream_format(out_stream, \" \");\n\n for (int j = 0; j < 16; j++)\n {\n if (i + j < buflen)\n {\n char c = isprint(buf[i + j]) ? buf[i + j] : '.';\n\n stream_format(out_stream, \"%c\", c);\n }\n }\n\n stream_format(out_stream, \"\\n\");\n }\n}\n" }, { "alpha_fraction": 0.7560975551605225, "alphanum_fraction": 0.7560975551605225, "avg_line_length": 26.33333396911621, "blob_id": "78afbd625eb9a04ca6f7be1786ec42fae460a5be", "content_id": "09f5528125655df65a7cffff69dc89206e84dd94", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 82, "license_type": "permissive", "max_line_length": 41, "num_lines": 3, "path": "/distros/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "DISTRO_DIRECTORY:=distros/$(BUILD_DISTRO)\n\n-include $(DISTRO_DIRECTORY)/.build.mk\n" }, { "alpha_fraction": 0.6892130970954895, "alphanum_fraction": 0.6962864995002747, "avg_line_length": 24.704545974731445, "blob_id": "ce9c17a824245d0eda2b0ca4f9a8b1789e7cbea3", "content_id": "16a65fac0e4a2be2fefe3f274588c97779f53477", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2262, "license_type": "permissive", "max_line_length": 88, "num_lines": 88, "path": "/libraries/libsystem/io_new/Format.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libutils/NumberFormat.h>\n#include <libutils/String.h>\n\n#include <libsystem/io_new/Format.h>\n\nnamespace System\n{\n\nResultOr<size_t> Format::format(Writer &writer)\n{\n return System::format(writer, \"Object({#x})\", reinterpret_cast<uintptr_t>(this));\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &formating, char value)\n{\n if (formating.type == Formating::CHARACTER)\n {\n return writer.write(value);\n }\n else\n {\n return NumberFormat::decimal().format(writer, (int64_t)value);\n }\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &formating, unsigned char value)\n{\n if (formating.type == Formating::CHARACTER)\n {\n return writer.write(value);\n }\n else\n {\n return NumberFormat::decimal().format(writer, (uint64_t)value);\n }\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, short int value)\n{\n return NumberFormat::decimal().format(writer, (int64_t)value);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, unsigned short int value)\n{\n return NumberFormat::decimal().format(writer, (uint64_t)value);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, int value)\n{\n return NumberFormat::decimal().format(writer, (int64_t)value);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, unsigned int value)\n{\n return NumberFormat::decimal().format(writer, (uint64_t)value);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, long int value)\n{\n return NumberFormat::decimal().format(writer, (int64_t)value);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, unsigned long int value)\n{\n return NumberFormat::decimal().format(writer, (uint64_t)value);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, float value)\n{\n return NumberFormat::decimal().format(writer, value);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, double value)\n{\n return NumberFormat::decimal().format(writer, value);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, const char *cstring)\n{\n return writer.write(cstring);\n}\n\nResultOr<size_t> format(Writer &writer, const Formating &, const String string)\n{\n return writer.write(string.cstring());\n}\n\n} // namespace System\n" }, { "alpha_fraction": 0.6612411141395569, "alphanum_fraction": 0.6683621406555176, "avg_line_length": 19.914894104003906, "blob_id": "be7789692942fa62367d1fc544ee1f4d4cfa2d31", "content_id": "6da0e006f5e96365f1b3a086386d5bffe89045df", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 983, "license_type": "permissive", "max_line_length": 50, "num_lines": 47, "path": "/libraries/libc/locale.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n__BEGIN_HEADER\n\n#define LC_ALL 1\n#define LC_COLLATE 2\n#define LC_CTYPE 3\n#define LC_MONETARY 4\n#define LC_NUMERIC 5\n#define LC_TIME 6\n#define LC_MESSAGES 7\n\nstruct lconv\n{\n const char *decimal_point;\n const char *thousands_sep;\n const char *grouping;\n const char *mon_decimal_point;\n const char *mon_thousands_sep;\n const char *mon_grouping;\n const char *positive_sign;\n const char *negative_sign;\n const char *currency_symbol;\n char frac_digits;\n char p_cs_precedes;\n char n_cs_precedes;\n char p_sep_by_space;\n char n_sep_by_space;\n char p_sign_posn;\n char n_sign_posn;\n const char *int_curr_symbol;\n char int_frac_digits;\n char int_p_cs_precedes;\n char int_n_cs_precedes;\n char int_p_sep_by_space;\n char int_n_sep_by_space;\n char int_p_sign_posn;\n char int_n_sign_posn;\n};\n\nstruct lconv *localeconv(void);\n\nchar *setlocale(int category, const char *locale);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.5778588652610779, "alphanum_fraction": 0.5815085172653198, "avg_line_length": 21.008928298950195, "blob_id": "d172ee83fa1b52a10e776f949546936a4fd2dead", "content_id": "f096443f0584f6856ac4ad63d4ef2d2b00273659", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2466, "license_type": "permissive", "max_line_length": 133, "num_lines": 112, "path": "/apps/utilities/ls.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/Logger.h>\n#include <libsystem/Result.h>\n#include <libsystem/cmdline/CMDLine.h>\n#include <libsystem/io/Stream.h>\n#include <libsystem/io_new/Directory.h>\n#include <libsystem/io_new/Streams.h>\n\nstatic bool option_all = false;\nstatic bool option_list = false;\nstatic bool option_color = false;\n\nstatic const char *usages[] = {\n \"\",\n \"FILES...\",\n \"OPTION... FILES...\",\n nullptr,\n};\n\nstatic CommandLineOption options[] = {\n COMMANDLINE_OPT_HELP,\n\n COMMANDLINE_OPT_BOOL(\"all\", 'a', option_all, \"Do not ignore entries starting with '.'.\", COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"list\", 'l', option_list, \"Long listing mode.\", COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"color\", 'c', option_color, \"Enable colored output.\", COMMANDLINE_NO_CALLBACK),\n\n COMMANDLINE_OPT_END};\n\nstatic CommandLine cmdline = CMDLINE(\n usages,\n options,\n \"List files and directories in the current working directory by default.\",\n \"Options can be combined.\");\n\nconst char *file_type_name[] = {\n \"-\", // None\n \"-\", // File\n \"c\", // Char device\n \"d\", // Directory\n \"p\", // Pipe\n};\n\nvoid ls_print_entry(System::Directory::Entry &entry)\n{\n FileState stat = entry.stat;\n\n if (option_list)\n {\n System::format(System::out(), \"{}rwxrwxrwx {5} \", file_type_name[stat.type], stat.size);\n }\n\n if (option_all || entry.name[0] != '.')\n {\n System::format(System::out(), (stat.type == FILE_TYPE_DIRECTORY && option_color) ? \"\\e[1;34m{}\\e[0m/ \" : \"{} \", entry.name);\n }\n\n if (option_list)\n {\n System::out().write(\"\\n\");\n }\n}\n\nResult ls(const char *target_path, bool with_prefix)\n{\n System::Directory directory{target_path};\n\n if (!directory.exist())\n {\n return ERR_NO_SUCH_FILE_OR_DIRECTORY;\n }\n\n if (with_prefix)\n {\n System::outln(\"{}:\", target_path);\n }\n\n for (auto entry : directory.entries())\n {\n ls_print_entry(entry);\n }\n\n if (!option_list)\n {\n System::out(\"\\n\");\n }\n\n return SUCCESS;\n}\n\nint main(int argc, char **argv)\n{\n argc = cmdline_parse(&cmdline, argc, argv);\n\n if (argc == 1)\n {\n return ls(\".\", false);\n }\n\n Result result;\n int exit_code = PROCESS_SUCCESS;\n\n for (int i = 1; i < argc; i++)\n {\n result = ls(argv[i], argc > 2);\n\n if (result != SUCCESS)\n {\n exit_code = PROCESS_FAILURE;\n }\n }\n\n return exit_code;\n}\n" }, { "alpha_fraction": 0.7086007595062256, "alphanum_fraction": 0.7086007595062256, "avg_line_length": 24.161291122436523, "blob_id": "f162af0ddba6e9ad0b7ff6627ba794e935bf8355", "content_id": "fcf2cb5553cf6bbc4e43c0635df9fa08dc823741", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 779, "license_type": "permissive", "max_line_length": 76, "num_lines": 31, "path": "/libraries/libsystem/compression/DeflateReader.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/compression/DeflateReader.h>\n#include <libsystem/io/MemoryReader.h>\n#include <libsystem/io/MemoryWriter.h>\n#include <libsystem/io/ScopedReader.h>\n\nDeflateReader::DeflateReader(Reader &reader) : _reader(reader)\n{\n // TODO: we shouldn't decompress everything at once\n _inflate.perform(reader, _mem_buffer);\n}\n\nsize_t DeflateReader::length()\n{\n return _mem_buffer.length();\n}\n\nsize_t DeflateReader::position()\n{\n return _position;\n}\n\nsize_t DeflateReader::read(void *buffer, size_t size)\n{\n // Do inflate until we have enough data or no more uncompressed data\n size_t remaining = MIN(length() - position(), size);\n\n memcpy(buffer, _mem_buffer.data().raw_storage() + _position, remaining);\n _position += remaining;\n\n return remaining;\n}" }, { "alpha_fraction": 0.6550976037979126, "alphanum_fraction": 0.6550976037979126, "avg_line_length": 16.074073791503906, "blob_id": "bacfda4d5a665cf1c93f2ce299bddc2182f4d89d", "content_id": "1f7e15b6d23e49799656bb86fc7729ec9693673f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 468, "license_type": "permissive", "max_line_length": 90, "num_lines": 27, "path": "/manual/10-utilities/shell.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# Shell\n\n## Usage\n\n### Changing the current working directory\n\nThe shell supports the `cd` command:\n\n```sh\n/a/b/c µ cd d # Change the current directory to d/\n\n/a/b/c/d µ cd .. # Go back to the parent directory\n\n/a/b/c µ\n```\n\nBut also shorthand navigation:\n\n```sh\n/a/b/c µ d # Change the current directory to d/\n\n/a/b/c/d µ .. # Go back to the parent directory\n\n/a/b/c µ .... # Go back to the parent directory but each additional . got one level upper.\n\n/ µ\n```\n" }, { "alpha_fraction": 0.7962616682052612, "alphanum_fraction": 0.7962616682052612, "avg_line_length": 23.31818199157715, "blob_id": "147fd29be33b77b7b8ed4a176a0783086d04fecd", "content_id": "98e30793c749a2226c2adce99bebabd9c4c9337d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 535, "license_type": "permissive", "max_line_length": 64, "num_lines": 22, "path": "/kernel/devices/Devices.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libutils/Callback.h>\n\n#include \"kernel/devices/DeviceAddress.h\"\n#include \"kernel/devices/DeviceClass.h\"\n#include \"kernel/devices/Driver.h\"\n\nvoid device_scan(IterationCallback<DeviceAddress> address);\n\nvoid device_iterate(IterationCallback<RefPtr<Device>> callback);\n\nString device_claim_name(DeviceClass klass);\n\nvoid device_initialize();\n\nvoid devices_acknowledge_interrupt(int interrupt);\n\nvoid devices_handle_interrupt(int interrupt);\n\nvoid device_mount(RefPtr<Device> device);\n" }, { "alpha_fraction": 0.5116772651672363, "alphanum_fraction": 0.5116772651672363, "avg_line_length": 17.115385055541992, "blob_id": "633600da91543bc8e1658b5e396d47876828c7b4", "content_id": "8901f462b9a8a6836cccfe68f58ad9135b55dbb0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 942, "license_type": "permissive", "max_line_length": 80, "num_lines": 52, "path": "/libraries/libsystem/eventloop/EventLoop.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nclass Notifier;\n\nclass Timer;\n\nclass Invoker;\n\nnamespace EventLoop\n{\n\n/* --- Notifiers ------------------------------------------------------------ */\n\nvoid register_notifier(Notifier *notifier);\n\nvoid unregister_notifier(Notifier *notifier);\n\n/* --- Timers --------------------------------------------------------------- */\n\nvoid register_timer(Timer *timer);\n\nvoid unregister_timer(Timer *timer);\n\n/* --- Invokers ------------------------------------------------------------- */\n\nvoid register_invoker(Invoker *timer);\n\nvoid unregister_invoker(Invoker *timer);\n\n/* --- Loop ----------------------------------------------------------------- */\n\nusing AtExitHook = void (*)(void);\n\nvoid initialize();\n\nvoid uninitialize();\n\nvoid atexit(AtExitHook hook);\n\nvoid pump(bool pool);\n\nint run();\n\nvoid exit(int exit_value);\n\nint run_nested();\n\nvoid exit_nested(int exit_value);\n\n} // namespace EventLoop\n" }, { "alpha_fraction": 0.7976190447807312, "alphanum_fraction": 0.7976190447807312, "avg_line_length": 20, "blob_id": "303efd3650af4ca5ced5b08bf8f9403a4b116836", "content_id": "a8f1833130cdee740aa73df5c50f1e3926a0a977", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 84, "license_type": "permissive", "max_line_length": 34, "num_lines": 4, "path": "/apps/compositor/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += COMPOSITOR\n\nCOMPOSITOR_NAME = compositor\nCOMPOSITOR_LIBS = settings graphic\n" }, { "alpha_fraction": 0.6659242510795593, "alphanum_fraction": 0.6681514382362366, "avg_line_length": 14, "blob_id": "5903fbb53555b1decc39c9dfe1a61c4f03b89123", "content_id": "31e62dd1936b14a55fc3f529aacf8bf7dc6828d2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 449, "license_type": "permissive", "max_line_length": 59, "num_lines": 30, "path": "/libraries/libsystem/io/MemoryWriter.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/MemoryWriter.h>\n\nMemoryWriter::MemoryWriter(size_t reserve) : _data(reserve)\n{\n}\n\nsize_t MemoryWriter::length()\n{\n return _data.count();\n}\n\nsize_t MemoryWriter::position()\n{\n return _data.count();\n}\n\nvoid MemoryWriter::flush()\n{\n}\n\nvoid MemoryWriter::clear()\n{\n _data.clear();\n}\n\nsize_t MemoryWriter::write(const void *buffer, size_t size)\n{\n _data.push_back_many((const uint8_t *)buffer, size);\n return size;\n}" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 39, "blob_id": "0aa9a86bf83d630915d8a4e6d11d5dd01183e42b", "content_id": "731510733411f0aeb1153f6145684f624b05838c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 40, "license_type": "permissive", "max_line_length": 39, "num_lines": 1, "path": "/kernel/drivers/VirtioBlock.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"kernel/drivers/VirtioBlock.h\"\n" }, { "alpha_fraction": 0.6958959698677063, "alphanum_fraction": 0.7815447449684143, "avg_line_length": 18.522388458251953, "blob_id": "51aa58f41f51fd5cabbd6e36b7c4017ed276a34f", "content_id": "ea493ad87b1f15164bc4e56b8fb57cfd6f472e05", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3923, "license_type": "permissive", "max_line_length": 31, "num_lines": 201, "path": "/libraries/libc/inttypes.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n#include <stddef.h>\n#include <stdint.h>\n\n__BEGIN_HEADER\n\n#define PRId8 \"hhd\"\n#define PRId16 \"hd\"\n#define PRId32 \"d\"\n#define PRId64 \"ld\"\n\n#define PRIdLEAST8 \"hhd\"\n#define PRIdLEAST16 \"hd\"\n#define PRIdLEAST32 \"d\"\n#define PRIdLEAST64 \"ld\"\n\n#define PRIdFAST8 \"hhd\"\n#define PRIdFAST16 \"hd\"\n#define PRIdFAST32 \"d\"\n#define PRIdFAST64 \"ld\"\n\n#define PRIi8 \"hhi\"\n#define PRIi16 \"hi\"\n#define PRIi32 \"i\"\n#define PRIi64 \"li\"\n\n#define PRIiLEAST8 \"hhi\"\n#define PRIiLEAST16 \"hi\"\n#define PRIiLEAST32 \"i\"\n#define PRIiLEAST64 \"li\"\n\n#define PRIiFAST8 \"hhi\"\n#define PRIiFAST16 \"hi\"\n#define PRIiFAST32 \"i\"\n#define PRIiFAST64 \"li\"\n\n#define PRIo8 \"hho\"\n#define PRIo16 \"ho\"\n#define PRIo32 \"o\"\n#define PRIo64 \"lo\"\n\n#define PRIoLEAST8 \"hho\"\n#define PRIoLEAST16 \"ho\"\n#define PRIoLEAST32 \"o\"\n#define PRIoLEAST64 \"lo\"\n\n#define PRIoFAST8 \"hho\"\n#define PRIoFAST16 \"ho\"\n#define PRIoFAST32 \"o\"\n#define PRIoFAST64 \"lo\"\n\n#define PRIu8 \"hhu\"\n#define PRIu16 \"hu\"\n#define PRIu32 \"u\"\n#define PRIu64 \"lu\"\n\n#define PRIuLEAST8 \"hhu\"\n#define PRIuLEAST16 \"hu\"\n#define PRIuLEAST32 \"u\"\n#define PRIuLEAST64 \"lu\"\n\n#define PRIuFAST8 \"hhu\"\n#define PRIuFAST16 \"hu\"\n#define PRIuFAST32 \"u\"\n#define PRIuFAST64 \"lu\"\n\n#define PRIx8 \"hhx\"\n#define PRIx16 \"hx\"\n#define PRIx32 \"x\"\n#define PRIx64 \"lx\"\n\n#define PRIxLEAST8 \"hhx\"\n#define PRIxLEAST16 \"hx\"\n#define PRIxLEAST32 \"x\"\n#define PRIxLEAST64 \"lx\"\n\n#define PRIxFAST8 \"hhx\"\n#define PRIxFAST16 \"hx\"\n#define PRIxFAST32 \"x\"\n#define PRIxFAST64 \"lx\"\n\n#define PRIX8 \"hhX\"\n#define PRIX16 \"hX\"\n#define PRIX32 \"X\"\n#define PRIX64 \"lX\"\n\n#define PRIXLEAST8 \"hhX\"\n#define PRIXLEAST16 \"hX\"\n#define PRIXLEAST32 \"X\"\n#define PRIXLEAST64 \"lX\"\n\n#define PRIXFAST8 \"hhX\"\n#define PRIXFAST16 \"hX\"\n#define PRIXFAST32 \"X\"\n#define PRIXFAST64 \"lX\"\n\n#define PRIdMAX \"jd\"\n#define PRIiMAX \"ji\"\n#define PRIoMAX \"jo\"\n#define PRIuMAX \"ju\"\n#define PRIxMAX \"jx\"\n#define PRIXMAX \"jX\"\n\n#define PRIdPTR \"td\"\n#define PRIiPTR \"ti\"\n#define PRIoPTR \"to\"\n#define PRIuPTR \"tu\"\n#define PRIxPTR \"tx\"\n#define PRIXPTR \"tX\"\n\n#define SCNd8 PRId8\n#define SCNd16 PRId16\n#define SCNd32 PRId32\n#define SCNd64 PRId64\n\n#define SCNdLEAST8 PRIdLEAST8\n#define SCNdLEAST16 PRIdLEAST16\n#define SCNdLEAST32 PRIdLEAST32\n#define SCNdLEAST64 PRIdLEAST64\n\n#define SCNdFAST8 PRIdFAST8\n#define SCNdFAST16 PRIdFAST16\n#define SCNdFAST32 PRIdFAST32\n#define SCNdFAST64 PRIdFAST64\n\n#define SCNi8 PRIi8\n#define SCNi16 PRIi16\n#define SCNi32 PRIi32\n#define SCNi64 PRIi64\n\n#define SCNiLEAST8 PRIiLEAST8\n#define SCNiLEAST16 PRIiLEAST16\n#define SCNiLEAST32 PRIiLEAST32\n#define SCNiLEAST64 PRIiLEAST64\n\n#define SCNiFAST8 PRIiFAST8\n#define SCNiFAST16 PRIiFAST16\n#define SCNiFAST32 PRIiFAST32\n#define SCNiFAST64 PRIiFAST64\n\n#define SCNo8 PRIo8\n#define SCNo16 PRIo16\n#define SCNo32 PRIo32\n#define SCNo64 PRIo64\n\n#define SCNoLEAST8 PRIoLEAST8\n#define SCNoLEAST16 PRIoLEAST16\n#define SCNoLEAST32 PRIoLEAST32\n#define SCNoLEAST64 PRIoLEAST64\n\n#define SCNoFAST8 PRIoFAST8\n#define SCNoFAST16 PRIoFAST16\n#define SCNoFAST32 PRIoFAST32\n#define SCNoFAST64 PRIoFAST64\n\n#define SCNu8 PRIu8\n#define SCNu16 PRIu16\n#define SCNu32 PRIu32\n#define SCNu64 PRIu64\n\n#define SCNuLEAST8 PRIuLEAST8\n#define SCNuLEAST16 PRIuLEAST16\n#define SCNuLEAST32 PRIuLEAST32\n#define SCNuLEAST64 PRIuLEAST64\n\n#define SCNuFAST8 PRIuFAST8\n#define SCNuFAST16 PRIuFAST16\n#define SCNuFAST32 PRIuFAST32\n#define SCNuFAST64 PRIuFAST64\n\n#define SCNx8 PRIx8\n#define SCNx16 PRIx16\n#define SCNx32 PRIx32\n#define SCNx64 PRIx64\n\n#define SCNxLEAST8 PRIxLEAST8\n#define SCNxLEAST16 PRIxLEAST16\n#define SCNxLEAST32 PRIxLEAST32\n#define SCNxLEAST64 PRIxLEAST64\n\n#define SCNxFAST8 PRIxFAST8\n#define SCNxFAST16 PRIxFAST16\n#define SCNxFAST32 PRIxFAST32\n#define SCNxFAST64 PRIxFAST64\n\n#define SCNdMAX PRIdMAX\n#define SCNiMAX PRIiMAX\n#define SCNoMAX PRIoMAX\n#define SCNuMAX PRIuMAX\n#define SCNxMAX PRIxMAX\n\n#define SCNdPTR PRIdPTR\n#define SCNiPTR PRIiPTR\n#define SCNoPTR PRIoPTR\n#define SCNuPTR PRIuPTR\n#define SCNxPTR PRIxPTR\n\n__END_HEADER" }, { "alpha_fraction": 0.7234782576560974, "alphanum_fraction": 0.7234782576560974, "avg_line_length": 21.959999084472656, "blob_id": "e5e7d4c2ddd28c6f34828845b659ceafe2194efe", "content_id": "8cd286d9a065d8fd44d28d52761d89faea1de5be", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 575, "license_type": "permissive", "max_line_length": 75, "num_lines": 25, "path": "/libraries/libsystem/plugs/__plug_memory.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <abi/Syscalls.h>\n\n#include <libsystem/Logger.h>\n#include <libsystem/Result.h>\n#include <libsystem/system/Memory.h>\n\nResult memory_alloc(size_t size, uintptr_t *out_address)\n{\n return hj_memory_alloc(size, out_address);\n}\n\nResult memory_free(uintptr_t address)\n{\n return hj_memory_free(address);\n}\n\nResult memory_include(int handle, uintptr_t *out_address, size_t *out_size)\n{\n return hj_memory_include(handle, out_address, out_size);\n}\n\nResult memory_get_handle(uintptr_t address, int *out_handle)\n{\n return hj_memory_get_handle(address, out_handle);\n}\n" }, { "alpha_fraction": 0.6328552961349487, "alphanum_fraction": 0.6365058422088623, "avg_line_length": 22.96875, "blob_id": "fc1099ef304a5fc899372c7b1c24cb539f6bed31", "content_id": "832ae84864003c34d40e8351b9b941875c44349b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3835, "license_type": "permissive", "max_line_length": 105, "num_lines": 160, "path": "/libraries/libgraphic/Bitmap.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#define LODEPNG_NO_COMPILE_DISK\n#define LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS\n#define LODEPNG_NO_COMPILE_CPP\n#include <thirdparty/lodepng/lodepng.cpp>\n#undef LODEPNG_NO_COMPILE_CPP\n#undef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS\n#undef LODEPNG_NO_COMPILE_DISK\n\n#include <assert.h>\n#include <libsystem/Logger.h>\n#include <libsystem/Result.h>\n#include <libsystem/io/File.h>\n#include <libsystem/system/Memory.h>\n\n#include <libgraphic/Bitmap.h>\n\nstatic Color _placeholder_buffer[] = {\n Colors::MAGENTA,\n Colors::BLACK,\n Colors::BLACK,\n Colors::MAGENTA,\n};\n\nResultOr<RefPtr<Bitmap>> Bitmap::create_shared(int width, int height)\n{\n Color *pixels = nullptr;\n Result result = memory_alloc(width * height * sizeof(Color), reinterpret_cast<uintptr_t *>(&pixels));\n\n if (result != SUCCESS)\n {\n return result;\n }\n\n int handle = -1;\n memory_get_handle(reinterpret_cast<uintptr_t>(pixels), &handle);\n\n auto bitmap = make<Bitmap>(handle, BITMAP_SHARED, width, height, pixels);\n bitmap->clear(Colors::BLACK);\n\n return bitmap;\n}\n\nResultOr<RefPtr<Bitmap>> Bitmap::create_shared_from_handle(int handle, Vec2i width_and_height)\n{\n Color *pixels = nullptr;\n size_t size = 0;\n Result result = memory_include(handle, reinterpret_cast<uintptr_t *>(&pixels), &size);\n\n if (result != SUCCESS)\n {\n return result;\n }\n\n if (size < width_and_height.x() * width_and_height.y() * sizeof(Color))\n {\n memory_free(reinterpret_cast<uintptr_t>(pixels));\n return ERR_BAD_IMAGE_FILE_FORMAT;\n }\n\n memory_get_handle(reinterpret_cast<uintptr_t>(pixels), &handle);\n\n return make<Bitmap>(handle, BITMAP_SHARED, width_and_height.x(), width_and_height.y(), pixels);\n}\n\nRefPtr<Bitmap> Bitmap::create_static(int width, int height, Color *pixels)\n{\n return make<Bitmap>(-1, BITMAP_STATIC, width, height, pixels);\n}\n\nRefPtr<Bitmap> Bitmap::placeholder()\n{\n return create_static(2, 2, _placeholder_buffer);\n}\n\nResultOr<RefPtr<Bitmap>> Bitmap::load_from(String path)\n{\n File file{path};\n auto result_or_read = file.read_all();\n\n if (!result_or_read.success())\n {\n return result_or_read.result();\n }\n\n auto raw_data = result_or_read.take_value();\n\n unsigned int decoded_width = 0;\n unsigned int decoded_height = 0;\n void *decoded_data = nullptr;\n\n int decode_result = lodepng_decode32(\n (unsigned char **)&decoded_data,\n &decoded_width,\n &decoded_height,\n (const unsigned char *)raw_data.start(),\n raw_data.size());\n\n if (decode_result != 0)\n {\n return ERR_BAD_IMAGE_FILE_FORMAT;\n }\n\n auto bitmap_or_result = Bitmap::create_shared(decoded_width, decoded_height);\n\n if (bitmap_or_result.success())\n {\n auto bitmap = bitmap_or_result.take_value();\n memcpy(bitmap->pixels(), decoded_data, sizeof(Color) * decoded_width * decoded_height);\n free(decoded_data);\n return bitmap;\n }\n else\n {\n free(decoded_data);\n return bitmap_or_result;\n }\n}\n\nRefPtr<Bitmap> Bitmap::load_from_or_placeholder(String path)\n{\n auto result = load_from(path);\n\n if (!result.success())\n {\n return placeholder();\n }\n\n return result.take_value();\n}\n\nResult Bitmap::save_to(String path)\n{\n void *outbuffer __cleanup_malloc = nullptr;\n\n size_t outbuffer_size = 0;\n\n int err = lodepng_encode_memory(\n (unsigned char **)&outbuffer,\n &outbuffer_size,\n (const unsigned char *)_pixels,\n _width,\n _height,\n LCT_RGBA, 8);\n\n if (err != 0)\n {\n return ERR_BAD_IMAGE_FILE_FORMAT;\n }\n\n File file{path};\n return file.write_all(outbuffer, outbuffer_size);\n}\n\nBitmap::~Bitmap()\n{\n if (_storage == BITMAP_SHARED)\n {\n memory_free(reinterpret_cast<uintptr_t>(_pixels));\n }\n}\n" }, { "alpha_fraction": 0.43370166420936584, "alphanum_fraction": 0.43370166420936584, "avg_line_length": 16.0134220123291, "blob_id": "e50cc5e1b9a2805f1eba92d92231730005c57c70", "content_id": "83625986d3b054bb8e4750a54f0263497749f75f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2534, "license_type": "permissive", "max_line_length": 54, "num_lines": 149, "path": "/libraries/libutils/Optional.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <assert.h>\n#include <libutils/Move.h>\n#include <libutils/New.h>\n\ntemplate <typename T>\nclass Optional\n{\nprivate:\n bool _present = false;\n char _storage[sizeof(T)];\n\npublic:\n bool present() const\n {\n return _present;\n }\n\n T &value()\n {\n assert(present());\n return *reinterpret_cast<T *>(_storage);\n }\n\n const T &value() const\n {\n assert(present());\n return *reinterpret_cast<const T *>(_storage);\n }\n\n T take_value()\n {\n assert(present());\n\n T v = move(value());\n clear();\n\n return v;\n }\n\n T value_or(const T &defaut_value) const\n {\n if (present())\n {\n return value();\n }\n else\n {\n return defaut_value;\n }\n }\n\n Optional() {}\n\n Optional(const T &value)\n {\n _present = true;\n new (&_storage) T(value);\n }\n\n Optional(T &&value)\n {\n _present = true;\n new (&_storage) T(move(value));\n }\n\n Optional(const Optional &other)\n {\n if (other.present())\n {\n _present = true;\n new (&_storage) T(*other);\n }\n }\n\n Optional(Optional &&other)\n {\n if (other.present())\n {\n new (&_storage) T(other.take_value());\n _present = true;\n }\n }\n\n Optional &operator=(const Optional &other)\n {\n if (this != &other)\n {\n clear();\n _present = other._present;\n if (other._present)\n {\n new (_storage) T(*other);\n }\n }\n\n return *this;\n }\n\n Optional &operator=(Optional &&other)\n {\n if (this != &other)\n {\n clear();\n _present = other._present;\n if (other._present)\n {\n new (_storage) T(other.take_value());\n }\n }\n\n return *this;\n }\n\n bool operator==(const T &other) const\n {\n if (!present())\n {\n return false;\n }\n\n return value() == other;\n }\n\n ~Optional()\n {\n clear();\n }\n\n void clear()\n {\n if (_present)\n {\n value().~T();\n _present = false;\n }\n }\n\n operator bool() const { return _present; }\n\n T &operator*() { return value(); }\n\n const T &operator*() const { return value(); }\n\n T *operator->() { return &value(); }\n\n const T *operator->() const { return &value(); }\n};" }, { "alpha_fraction": 0.6027713418006897, "alphanum_fraction": 0.6043109893798828, "avg_line_length": 18.68181800842285, "blob_id": "7933fd661f2873f925e511af469cb2384da94362", "content_id": "6698cc54beda8712504ecc8560a0c9af6bf2e961", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1299, "license_type": "permissive", "max_line_length": 78, "num_lines": 66, "path": "/apps/panel/widgets/ApplicationListing.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/process/Process.h>\n#include <libutils/FuzzyMatcher.h>\n#include <libwidget/Button.h>\n#include <libwidget/Label.h>\n#include <libwidget/Window.h>\n\n#include \"panel/model/MenuEntry.h\"\n#include \"panel/widgets/ApplicationListing.h\"\n\nnamespace panel\n{\n\nApplicationListing::ApplicationListing(Widget *parent) : VScroll(parent)\n{\n layout(VFLOW(4));\n flags(Widget::FILL);\n\n render();\n}\n\nvoid ApplicationListing::filter(const String &filter)\n{\n if (_filter == filter)\n {\n return;\n }\n\n _filter = filter;\n\n render();\n}\n\nvoid ApplicationListing::render()\n{\n FuzzyMatcher matcher;\n\n host()->clear_children();\n host()->layout(VFLOW(4));\n\n bool find_any = false;\n\n MenuEntry::load().foreach ([&](auto &entry) {\n if (!matcher.match(_filter, entry.name))\n {\n return Iteration::CONTINUE;\n }\n\n find_any = true;\n\n auto item = new Button(host(), Button::TEXT, entry.image, entry.name);\n\n item->on(Event::ACTION, [this, entry](auto) {\n process_run(entry.command.cstring(), nullptr);\n window()->hide();\n });\n\n return Iteration::CONTINUE;\n });\n\n if (!find_any)\n {\n new Label(host(), \"No application found!\", Anchor::CENTER);\n }\n}\n\n} // namespace panel\n" }, { "alpha_fraction": 0.732758641242981, "alphanum_fraction": 0.732758641242981, "avg_line_length": 20.8125, "blob_id": "b62fb496df8179829805c209234f5b4cc73067a3", "content_id": "2036d89247504d32a407f1a7d82205094336ee40", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 348, "license_type": "permissive", "max_line_length": 73, "num_lines": 16, "path": "/libraries/libsystem/io_new/Duplex.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/io_new/Reader.h>\n#include <libsystem/io_new/Seek.h>\n#include <libsystem/io_new/Writer.h>\n\nnamespace System\n{\n\ntemplate <typename T>\nconcept Duplex = IsBaseOf<Reader, T>::value &&IsBaseOf<Writer, T>::value;\n\ntemplate <typename T>\nconcept SeekableDuplex = Duplex<T> &&IsBaseOf<Seek, T>::value;\n\n} // namespace System" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 41, "blob_id": "ed96ad4c476cfec5938c286bc42d0b9e0164d735", "content_id": "dcd87d1eae2956eba64edbc0715b56ff231fd0bc", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 42, "license_type": "permissive", "max_line_length": 41, "num_lines": 1, "path": "/kernel/drivers/VirtioEntropy.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"kernel/drivers/VirtioEntropy.h\"\n" }, { "alpha_fraction": 0.7420924305915833, "alphanum_fraction": 0.7420924305915833, "avg_line_length": 20.63157844543457, "blob_id": "147851ebd8f455543a6301bb556f4f9736afdc37", "content_id": "aba09dd57d11d7aab24b8d5b13560e4c84987f0b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 411, "license_type": "permissive", "max_line_length": 65, "num_lines": 19, "path": "/apps/shell/Shell.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"shell/Nodes.h\"\n\nbool find_command_path(char *buffer, const char *command);\n\ntypedef int (*ShellBuiltinCallback)(int argc, const char **argv);\n\nstruct ShellBuiltin\n{\n const char *name;\n ShellBuiltinCallback handler;\n};\n\nShellBuiltinCallback shell_get_builtin(const char *name);\n\nShellNode *shell_parse(char *command_text);\n\nint shell_eval(ShellNode *node, Stream *in, Stream *out);\n" }, { "alpha_fraction": 0.7262969613075256, "alphanum_fraction": 0.7298747897148132, "avg_line_length": 18.964284896850586, "blob_id": "45f70011a9cd5c136c6ceb4f6b93c81047a700c1", "content_id": "67af200f7200c39f6ca78ab56d0e8168c5ee5bc7", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 559, "license_type": "permissive", "max_line_length": 58, "num_lines": 28, "path": "/libraries/libsystem/cmdline/ReadLine.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n#include <libsystem/Result.h>\n#include <libsystem/unicode/UTF8Decoder.h>\n#include <libsystem/unicode/UnicodeString.h>\n#include <libutils/Scanner.h>\n\nstruct ReadLine\n{\n bool should_continue;\n\n size_t cursor;\n size_t old_cursor;\n\n size_t history_current;\n\n Stream *stream;\n UTF8Decoder *decoder;\n UnicodeString *string;\n StreamScanner *scan;\n};\n\nReadLine *readline_create(Stream *stream);\n\nvoid readline_destroy(ReadLine *readline);\n\nResult readline_readline(ReadLine *readline, char **line);\n" }, { "alpha_fraction": 0.641791045665741, "alphanum_fraction": 0.6567164063453674, "avg_line_length": 21.375, "blob_id": "36ead94b6de29dcfa187d3a518a7f226614c2913", "content_id": "193a917f9733e610ff65498551fc88303ba7ad5b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 536, "license_type": "permissive", "max_line_length": 94, "num_lines": 24, "path": "/libraries/libc/skift/Plugs.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n\n#include <abi/Syscalls.h>\n#include <skift/Plugs.h>\n\n#ifndef __KERNEL__\n\nvoid __plug_assert_failed(const char *expr, const char *file, const char *function, int line)\n{\n char buffer[256];\n snprintf(buffer, 256, \"Assert failed: %s in %s:%s() ln%d!\\n\", expr, file, function, line);\n fwrite(buffer, strlen(buffer), 1, stdlog);\n abort();\n}\n\n#endif\n\nTimeStamp __plug_system_get_time()\n{\n TimeStamp timestamp = 0;\n assert(hj_system_time(&timestamp) == SUCCESS);\n return timestamp;\n}" }, { "alpha_fraction": 0.7880184054374695, "alphanum_fraction": 0.7880184054374695, "avg_line_length": 18.727272033691406, "blob_id": "bc6c006f55dbcf836e733710a121ed6f819f7947", "content_id": "4431a0a033dcdfb815fb60c9e732bc0eb040f4dd", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 217, "license_type": "permissive", "max_line_length": 59, "num_lines": 11, "path": "/kernel/bus/PCI.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Callback.h>\n\n#include \"kernel/devices/DeviceAddress.h\"\n\nvoid pci_initialize();\n\nint pci_get_interrupt(PCIAddress address);\n\nIteration pci_scan(IterationCallback<PCIAddress> callback);\n" }, { "alpha_fraction": 0.49760764837265015, "alphanum_fraction": 0.49760764837265015, "avg_line_length": 10.61111068725586, "blob_id": "0e85bf9ac145a7113494e2f9452b219c07f6a9d8", "content_id": "98d494823ae7c9d8271ad52a734e2d3746c3fba8", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 209, "license_type": "permissive", "max_line_length": 28, "num_lines": 18, "path": "/libraries/libc/__libc__.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#ifdef __cplusplus\n\n# define __BEGIN_HEADER \\\n extern \"C\" \\\n {\n\n# define __END_HEADER \\\n }\n\n#else\n\n# define __BEGIN_HEADER\n\n# define __END_HEADER\n\n#endif\n" }, { "alpha_fraction": 0.6740087866783142, "alphanum_fraction": 0.6740087866783142, "avg_line_length": 13.1875, "blob_id": "c1999ce1038750930a795f7a53c7caebb88901f8", "content_id": "d22f66e97284428350eba530e18933d7e4da0c9c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 227, "license_type": "permissive", "max_line_length": 38, "num_lines": 16, "path": "/libraries/libwidget/TitleBar.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nclass TitleBar : public Widget\n{\nprivate:\n bool _is_dragging = false;\n\npublic:\n TitleBar(Widget *parent);\n\n ~TitleBar() override;\n\n void event(Event *event) override;\n};\n" }, { "alpha_fraction": 0.774193525314331, "alphanum_fraction": 0.774193525314331, "avg_line_length": 30, "blob_id": "8f22bf3f6d020f2a077fbedf2089db1dae7f59f5", "content_id": "58c025cc23a39b9ec3c5c4acb90d615812ba98f4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 62, "license_type": "permissive", "max_line_length": 32, "num_lines": 2, "path": "/apps/paint/PaintDocument.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"paint/PaintDocument.h\"\n#include \"paint/PaintTool.h\"\n" }, { "alpha_fraction": 0.40890154242515564, "alphanum_fraction": 0.42293357849121094, "avg_line_length": 16.01865577697754, "blob_id": "c2fab164d2215225a48fb6d1e0b909befaac81a9", "content_id": "0e62313bc2eed57c6938d1d1a7c8158a247bbb9d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4561, "license_type": "permissive", "max_line_length": 66, "num_lines": 268, "path": "/libraries/libutils/Scanner.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <assert.h>\n#include <libsystem/Logger.h>\n#include <libsystem/io/Stream.h>\n#include <libutils/unicode/Codepoint.h>\n#include <libutils/NumberParser.h>\n#include <libutils/RingBuffer.h>\n#include <string.h>\n\nclass Scanner\n{\npublic:\n virtual ~Scanner(){};\n\n virtual bool ended() = 0;\n\n virtual void foreward() = 0;\n\n virtual char peek(size_t peek) = 0;\n\n bool do_continue()\n {\n return !ended();\n }\n\n void foreward(size_t n)\n {\n for (size_t i = 0; i < n; i++)\n {\n foreward();\n }\n }\n\n void foreward_codepoint()\n {\n if ((current() & 0xf8) == 0xf0)\n {\n foreward(4);\n }\n else if ((current() & 0xf0) == 0xe0)\n {\n foreward(3);\n }\n else if ((current() & 0xe0) == 0xc0)\n {\n foreward(2);\n }\n else\n {\n foreward(1);\n }\n }\n\n char current()\n {\n return peek(0);\n }\n\n Codepoint current_codepoint()\n {\n size_t size = 0;\n Codepoint codepoint = peek(0);\n\n if ((current() & 0xf8) == 0xf0)\n {\n size = 4;\n codepoint = (0x07 & codepoint) << 18;\n }\n else if ((current() & 0xf0) == 0xe0)\n {\n size = 3;\n codepoint = (0x0f & codepoint) << 12;\n }\n else if ((current() & 0xe0) == 0xc0)\n {\n codepoint = (0x1f & codepoint) << 6;\n size = 2;\n }\n\n for (size_t i = 1; i < size; i++)\n {\n codepoint |= (0x3f & peek(i)) << (6 * (size - i - 1));\n }\n\n return codepoint;\n }\n\n bool current_is(const char *what)\n {\n return current_is(what, strlen(what));\n }\n\n bool current_is(const char *what, size_t size)\n {\n for (size_t i = 0; i < size; i++)\n {\n if (current() == what[i])\n {\n return true;\n }\n }\n\n return false;\n }\n\n bool current_is_word(const char *word)\n {\n for (size_t i = 0; word[i]; i++)\n {\n if (peek(i) != word[i])\n {\n return false;\n }\n }\n\n return true;\n }\n\n void eat(const char *what)\n {\n while (current_is(what) &&\n do_continue())\n {\n foreward();\n }\n }\n\n bool skip(char chr)\n {\n if (current() == chr)\n {\n foreward();\n\n return true;\n }\n\n return false;\n }\n\n bool skip(const char *chr)\n {\n if (current_is(chr))\n {\n foreward();\n\n return true;\n }\n\n return false;\n }\n\n bool skip_word(const char *word)\n {\n if (current_is_word(word))\n {\n for (size_t i = 0; i < strlen(word); i++)\n {\n foreward();\n }\n\n return true;\n }\n\n return false;\n }\n};\n\nclass StreamScanner : public Scanner\n{\nprivate:\n static constexpr int PEEK_SIZE = 16;\n\n RingBuffer _peek{PEEK_SIZE};\n Stream *_stream = nullptr;\n\n void refill()\n {\n char c = stream_getchar(_stream);\n\n if (!handle_has_error(_stream))\n {\n _peek.put(c);\n }\n }\n\npublic:\n StreamScanner(Stream *stream)\n {\n _stream = stream;\n }\n\n bool ended() override\n {\n return stream_is_end_file(_stream) ||\n handle_has_error(_stream);\n }\n\n void foreward() override\n {\n if (_peek.empty())\n {\n refill();\n }\n\n if (!ended())\n {\n _peek.get();\n }\n }\n\n char peek(size_t peek) override\n {\n\n while (peek >= _peek.used() && !ended())\n {\n refill();\n }\n\n if (ended())\n {\n return '\\0';\n }\n\n return _peek.peek(peek);\n }\n};\n\nclass StringScanner : public Scanner\n{\nprivate:\n const char *_string = nullptr;\n\n size_t _size = 0;\n size_t _offset = 0;\n\npublic:\n StringScanner(const char *string, size_t size)\n {\n _string = string;\n _size = size;\n }\n\n bool ended() override\n {\n return _offset >= _size;\n }\n\n void foreward() override\n {\n if (!ended())\n {\n _offset++;\n }\n }\n\n char peek(size_t peek) override\n {\n size_t offset = _offset + peek;\n\n if (offset >= _size)\n {\n return '\\0';\n }\n\n return _string[offset];\n }\n};\n" }, { "alpha_fraction": 0.6780821681022644, "alphanum_fraction": 0.6849315166473389, "avg_line_length": 18.46666717529297, "blob_id": "e1685fd46f1ee64219eca8a12bde05f337249545", "content_id": "33f47ef748d46560df7a9d4f13b081261336e71e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 292, "license_type": "permissive", "max_line_length": 44, "num_lines": 15, "path": "/apps/panel/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Application.h>\n\n#include \"panel/windows/PanelWindow.h\"\n\nstatic constexpr int PANEL_HEIGHT = 38;\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n auto window = own<panel::PanelWindow>();\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.6883925199508667, "alphanum_fraction": 0.693518877029419, "avg_line_length": 23.827272415161133, "blob_id": "c7d54694e4335a29835f1a43988532d1ca492536", "content_id": "a970ac0e8502dc73fd667b281a586c081d42fc3c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2731, "license_type": "permissive", "max_line_length": 72, "num_lines": 110, "path": "/libraries/libc/stdio.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n#include <stdarg.h>\n#include <stddef.h>\n\n__BEGIN_HEADER\n\ntypedef struct\n{\n int handle;\n int is_eof;\n int error;\n} FILE;\n#define __DEFINED_FILE\n\n#define BUFSIZ 8192\n\nFILE *__stdio_get_stdin(void);\nFILE *__stdio_get_stdout(void);\nFILE *__stdio_get_stderr(void);\nFILE *__stdio_get_stdlog(void);\n\n#define stdin (__stdio_get_stdin())\n#define stdout (__stdio_get_stdout())\n#define stderr (__stdio_get_stderr())\n#define stdlog (__stdio_get_stdlog())\n\n#define EOF (-1)\n\n#define SEEK_SET 0\n#define SEEK_CUR 1\n#define SEEK_END 2\n\nFILE *fopen(const char *path, const char *mode);\nint fclose(FILE *stream);\nint fseek(FILE *stream, long offset, int whence);\nlong ftell(FILE *stream);\nFILE *fdopen(int fd, const char *mode);\nFILE *freopen(const char *path, const char *mode, FILE *stream);\n\nsize_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);\nsize_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);\n\nint fileno(FILE *stream);\nint fflush(FILE *stream);\n\nint vasprintf(char **buf, const char *fmt, va_list args);\nint sprintf(char *buf, const char *fmt, ...);\nint fprintf(FILE *stream, const char *fmt, ...);\nint printf(const char *fmt, ...);\nint snprintf(char *buf, size_t size, const char *fmt, ...);\nint vsprintf(char *buf, const char *fmt, va_list args);\nint vsnprintf(char *buf, size_t size, const char *fmt, va_list args);\nint vfprintf(FILE *stream, const char *format, va_list ap);\nint vprintf(const char *format, va_list ap);\n\nint puts(const char *s);\nint fputs(const char *s, FILE *stream);\nint fputc(int c, FILE *stream);\nint putc(int c, FILE *stream);\nint putchar(int c);\nint fgetc(FILE *stream);\nint getc(FILE *stream);\nchar *fgets(char *s, int size, FILE *stream);\nint getchar(void);\n\nvoid rewind(FILE *stream);\nvoid setbuf(FILE *stream, char *buf);\n\nvoid perror(const char *s);\n\nint ungetc(int c, FILE *stream);\n\nint feof(FILE *stream);\nvoid clearerr(FILE *stream);\nint ferror(FILE *stream);\n\nchar *strerror(int errnum);\n\nint _fwouldblock(FILE *stream);\n\nFILE *tmpfile(void);\n\nint setvbuf(FILE *stream, char *buf, int mode, size_t size);\n\nint remove(const char *pathname);\nint rename(const char *oldpath, const char *newpath);\n\n#define _IONBF 0\n#define _IOLBF 1\n#define _IOFBF 2\n\nchar *tmpnam(char *s);\nchar *tempnam(const char *dir, const char *s);\n#define L_tmpnam 256\n\nint vsscanf(const char *str, const char *format, va_list ap);\nint sscanf(const char *str, const char *format, ...);\nint vfscanf(FILE *stream, const char *format, va_list ap);\nint fscanf(FILE *stream, const char *format, ...);\nint scanf(const char *format, ...);\n\ntypedef long fpos_t;\n\nint fgetpos(FILE *stream, fpos_t *pos);\nint fsetpos(FILE *stream, const fpos_t *pos);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.7003012299537659, "alphanum_fraction": 0.7003012299537659, "avg_line_length": 16.473684310913086, "blob_id": "3a78861e2456878b46092ae4efec6a433516a723", "content_id": "41092282c980ca9c0d6ca03cadd9d296ae022c25", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 664, "license_type": "permissive", "max_line_length": 80, "num_lines": 38, "path": "/kernel/node/Directory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Vector.h>\n\n#include \"kernel/node/Node.h\"\n\nstruct DirectoryListing\n{\n size_t count;\n DirectoryEntry entries[];\n};\n\nstruct FsDirectoryEntry\n{\n String name;\n RefPtr<FsNode> node;\n};\n\nclass FsDirectory : public FsNode\n{\nprivate:\n Vector<FsDirectoryEntry> _childs{};\n\npublic:\n FsDirectory();\n\n Result open(FsHandle &handle) override;\n\n void close(FsHandle &handle) override;\n\n ResultOr<size_t> read(FsHandle &handle, void *buffer, size_t size) override;\n\n RefPtr<FsNode> find(String name) override;\n\n Result link(String name, RefPtr<FsNode> child) override;\n\n Result unlink(String name) override;\n};\n" }, { "alpha_fraction": 0.7116182446479797, "alphanum_fraction": 0.7116182446479797, "avg_line_length": 23.100000381469727, "blob_id": "3a06f540f94b7ee1ef11bd4dca4b61579a90271d", "content_id": "7e16a328a75003183b49b875dc34679b71947d59", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 482, "license_type": "permissive", "max_line_length": 71, "num_lines": 20, "path": "/apps/shell/Nodes/Redirect.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"shell/Nodes.h\"\n\nvoid shell_redirect_destroy(ShellRedirect *node)\n{\n shell_node_destroy(node->command);\n free(node->destination);\n}\n\nShellNode *shell_redirect_create(ShellNode *command, char *destination)\n{\n ShellRedirect *node = __create(ShellRedirect);\n\n node->type = SHELL_NODE_REDIRECT;\n node->destroy = (ShellNodeDestroyCallback)shell_redirect_destroy;\n\n node->command = command;\n node->destination = destination;\n\n return (ShellNode *)node;\n}\n" }, { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 27.571428298950195, "blob_id": "9d133e74dc66ea9da611f9942bee1254e3681194", "content_id": "a6dd078d8c2e26c9c13c59ce33fba33d82377141", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 600, "license_type": "permissive", "max_line_length": 89, "num_lines": 21, "path": "/libraries/libsystem/utils/BufferBuilder.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nstruct BufferBuilder;\n\nBufferBuilder *buffer_builder_create(size_t preallocated);\n\nvoid buffer_builder_destroy(BufferBuilder *buffer);\n\nchar *buffer_builder_finalize(BufferBuilder *buffer);\n\nconst char *buffer_builder_intermediate(BufferBuilder *builder);\n\nvoid buffer_builder_append_str(BufferBuilder *buffer, const char *str);\n\nvoid buffer_builder_append_str_size(BufferBuilder *buffer, const char *str, size_t size);\n\nvoid buffer_builder_append_chr(BufferBuilder *buffer, char chr);\n\nvoid buffer_builder_rewind(BufferBuilder *buffer, size_t how_many);\n" }, { "alpha_fraction": 0.39303481578826904, "alphanum_fraction": 0.39303481578826904, "avg_line_length": 27.714284896850586, "blob_id": "aa9fa76e94a3500e14354e6b8224bf56235e9010", "content_id": "f5f8ea5dccaaab0124d19e6c92044e5b357da371", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 201, "license_type": "permissive", "max_line_length": 76, "num_lines": 7, "path": "/libraries/libsystem/math/MinMax.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define clamp(__v, __lower, __upper) (MAX(MIN((__v), (__upper)), (__lower)))\n\n#define MIN(__x, __y) ((__x) < (__y) ? (__x) : (__y))\n\n#define MAX(__x, __y) ((__x) > (__y) ? (__x) : (__y))\n" }, { "alpha_fraction": 0.6752577424049377, "alphanum_fraction": 0.6804123520851135, "avg_line_length": 15.166666984558105, "blob_id": "4de22d3683ee10813cde614e3a33780455c1bae8", "content_id": "85a8921f0fafc423ee387e97e71606f6aeea37a0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 194, "license_type": "permissive", "max_line_length": 50, "num_lines": 12, "path": "/libraries/libwidget/Separator.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nstruct Separator : public Widget\n{\n Separator(Widget *parent);\n\n void paint(Painter &, const Recti &) override;\n\n Vec2i size() override;\n};\n" }, { "alpha_fraction": 0.6603773832321167, "alphanum_fraction": 0.6603773832321167, "avg_line_length": 23.090909957885742, "blob_id": "6ad5b3c227d7e3dd54c70858f4adfce1eba511c8", "content_id": "19e75ebd406aec07050bb8156a56df06b66d83b7", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 265, "license_type": "permissive", "max_line_length": 88, "num_lines": 11, "path": "/tests/common.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\n#include <libsystem/Assert.h>\n\nvoid assert_failed(const char *expr, const char *file, const char *function, int line)\n{\n fprintf(stderr, \"Assert failed: %s in %s:%s() ln%d!\\n\", expr, file, function, line);\n\n abort();\n}\n" }, { "alpha_fraction": 0.6179540753364563, "alphanum_fraction": 0.6200417280197144, "avg_line_length": 16.740739822387695, "blob_id": "9b33780fb5d2a87fd5b7b34fcde03a1d2c3be44b", "content_id": "8903a474a01fcd836b6b845a822b946be94a167c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 479, "license_type": "permissive", "max_line_length": 54, "num_lines": 27, "path": "/libraries/libwidget/Label.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/String.h>\n#include <libwidget/Widget.h>\n\nclass Label : public Widget\n{\nprivate:\n String _text = \"Label\";\n Anchor _anchor = Anchor::LEFT;\n\npublic:\n void text(String text)\n {\n _text = text;\n should_relayout();\n should_repaint();\n }\n\n Label(Widget *parent, String text);\n\n Label(Widget *parent, String text, Anchor anchor);\n\n void paint(Painter &, const Recti &) override;\n\n Vec2i size() override;\n};\n" }, { "alpha_fraction": 0.7029703259468079, "alphanum_fraction": 0.7029703259468079, "avg_line_length": 10.882352828979492, "blob_id": "703e6274845688cdd62d979c0a626916310fa191", "content_id": "6e26d6ba1983453db8cdd57e6077d0ed0e09a258", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 202, "license_type": "permissive", "max_line_length": 39, "num_lines": 17, "path": "/apps/media-player/windows/Main.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Window.h>\n\n#include \"media-player/widgets/Cover.h\"\n\nnamespace media_player\n{\n\nclass Main : public Window\n{\nprivate:\npublic:\n Main();\n};\n\n} // namespace media_player\n" }, { "alpha_fraction": 0.8135592937469482, "alphanum_fraction": 0.8135592937469482, "avg_line_length": 19, "blob_id": "9ae9a4f19e5fceab1b6f01978894dd5a50f6bb52", "content_id": "7fcc92df83781420f16768a14d299bba3408b30b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 59, "license_type": "permissive", "max_line_length": 45, "num_lines": 3, "path": "/libraries/libfilepicker/FilePicker.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libfilepicker/dialogs/FilePicker.h>" }, { "alpha_fraction": 0.7701149582862854, "alphanum_fraction": 0.7701149582862854, "avg_line_length": 20.75, "blob_id": "623ddadd1813d505d562ae5833842044de129e62", "content_id": "17ea6f8a6dda514e882a7413b8f0db0dd2f460be", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 87, "license_type": "permissive", "max_line_length": 34, "num_lines": 4, "path": "/apps/splash-screen/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += SPLASH_SCREEN\n\nSPLASH_SCREEN_NAME = splash-screen\nSPLASH_SCREEN_LIBS = graphic\n" }, { "alpha_fraction": 0.6266924738883972, "alphanum_fraction": 0.676982581615448, "avg_line_length": 13.36111068725586, "blob_id": "ea9e2c3ee640e383196ab88bb384e05b6817f8ed", "content_id": "19e3f874c79b0b49080892628432c047e9ae2155", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 517, "license_type": "permissive", "max_line_length": 25, "num_lines": 36, "path": "/libraries/libc/ctype.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n__BEGIN_HEADER\n\nint isalnum(int c);\nint isalpha(int c);\nint isdigit(int c);\nint islower(int c);\nint isprint(int c);\nint isgraph(int c);\nint iscntrl(int c);\nint isgraph(int c);\nint ispunct(int c);\nint isspace(int c);\nint isupper(int c);\nint isxdigit(int c);\n\nint isascii(int c);\n\nint tolower(int c);\nint toupper(int c);\n\n#define _U 01\n#define _L 02\n#define _N 04\n#define _S 010\n#define _P 020\n#define _C 040\n#define _X 0100\n#define _B 0200\n\nextern char _ctype_[256];\n\n__END_HEADER\n" }, { "alpha_fraction": 0.6680942177772522, "alphanum_fraction": 0.680942177772522, "avg_line_length": 21.238094329833984, "blob_id": "3b2595814bcbc0e5592a562f4ac0c765361e49bc", "content_id": "6798b96074423419e0763d967fb4d017fd1bbd76", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 467, "license_type": "permissive", "max_line_length": 58, "num_lines": 21, "path": "/apps/settings/widgets/Link.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/IconPanel.h>\n#include <libwidget/Label.h>\n\n#include \"settings/widgets/Link.h\"\n\nnamespace Settings\n{\n\nLink::Link(Widget *parent, RefPtr<Icon> icon, String name)\n : Button(parent, Button::TEXT)\n{\n layout(VFLOW(4));\n insets({8, 24});\n\n auto icon_container = new IconPanel(this, icon);\n icon_container->icon_size(ICON_36PX);\n icon_container->flags(Widget::FILL);\n new Label(this, name, Anchor::CENTER);\n}\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.6260945796966553, "alphanum_fraction": 0.6272621154785156, "avg_line_length": 26.190475463867188, "blob_id": "821e9bb3cef4b1eab097d8c94867acf90bbda239", "content_id": "93b9607e6d8c5f2bc305e47d24d2d750ae96cee7", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3426, "license_type": "permissive", "max_line_length": 110, "num_lines": 126, "path": "/apps/utilities/keyboardctl.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Keyboard.h>\n#include <abi/Paths.h>\n\n#include <libutils/ArgParse.h>\n\n#include <libsystem/io_new/Copy.h>\n#include <libsystem/io_new/Directory.h>\n#include <libsystem/io_new/File.h>\n#include <libsystem/io_new/Streams.h>\n\nint loadkey_list_keymap()\n{\n System::Directory keymap_directory{\"/Files/Keyboards\"};\n\n if (!keymap_directory.exist())\n {\n System::errln(\"keyboardctl: Failed to query keymaps from /Files/Keyboards\");\n return PROCESS_FAILURE;\n }\n\n for (auto entry : keymap_directory.entries())\n {\n Path keymap_path = Path::parse(entry.name);\n System::outln(\"- {}\", keymap_path.basename_without_extension());\n }\n\n return PROCESS_SUCCESS;\n}\n\nint loadkey_set_keymap(System::Handle &keyboard_device, String keymap_path)\n{\n System::File file{keymap_path, OPEN_READ};\n auto read_all_result = System::read_all(file);\n\n if (!read_all_result.success())\n {\n System::errln(\"keyboardctl: Failed to open the keymap file: {}\", read_all_result.description());\n\n return PROCESS_FAILURE;\n }\n\n KeyMap *keymap = (KeyMap *)read_all_result->start();\n size_t keymap_size = read_all_result->size();\n\n if (keymap_size < sizeof(KeyMap) ||\n keymap->magic[0] != 'k' ||\n keymap->magic[1] != 'm' ||\n keymap->magic[2] != 'a' ||\n keymap->magic[3] != 'p')\n {\n System::errln(\"keyboardctl: Invalid keymap file format!\");\n\n return PROCESS_FAILURE;\n }\n\n IOCallKeyboardSetKeymapArgs args = {\n .keymap = keymap,\n .size = keymap_size,\n };\n\n auto call_result = keyboard_device.call(IOCALL_KEYBOARD_SET_KEYMAP, &args);\n\n if (call_result != SUCCESS)\n {\n System::errln(\"keyboardctl: Failed to open the keymap file: {}\", get_result_description(call_result));\n\n return PROCESS_FAILURE;\n }\n\n System::outln(\"Keymap set to {}({})\", keymap->language, keymap->region);\n\n return PROCESS_SUCCESS;\n}\n\nint loadkey_get_keymap(System::Handle &keyboard_device)\n{\n KeyMap keymap;\n\n if (keyboard_device.call(IOCALL_KEYBOARD_GET_KEYMAP, &keymap) != SUCCESS)\n {\n System::errln(\"keyboardctl: Failed to retrived the current keymap\");\n return PROCESS_FAILURE;\n }\n\n System::outln(\"Current keymap is {}({})\", keymap.language, keymap.region);\n\n return PROCESS_SUCCESS;\n}\n\nint main(int argc, const char *argv[])\n{\n ArgParse args{};\n args.should_abort_on_failure();\n args.show_help_if_no_option_given();\n\n args.prologue(\"Get or set the current keyboard keymap\");\n\n args.usage(\"\");\n args.usage(\"OPTION...\");\n\n args.epiloge(\"Options can be combined.\");\n\n System::Handle keyboard_handle{KEYBOARD_DEVICE_PATH, OPEN_READ};\n\n if (!keyboard_handle.valid())\n {\n System::errln(\"keyboardctl: Failed to open the keyboard device\");\n\n return PROCESS_FAILURE;\n }\n\n args.option('l', \"list\", \"List all installed keymap on this system.\", [&](auto &) {\n return loadkey_list_keymap();\n });\n\n args.option('g', \"get\", \"Get the current keyboard keymap.\", [&](auto &) {\n return loadkey_get_keymap(keyboard_handle);\n });\n\n args.option_string('s', \"set\", \"Set the current keyboard keymap.\", [&](auto &keymap_name) {\n auto kaymap_path = String::format(\"/Files/Keyboards/{}.kmap\", keymap_name);\n return loadkey_set_keymap(keyboard_handle, kaymap_path);\n });\n\n return args.eval(argc, argv);\n}\n" }, { "alpha_fraction": 0.7829457521438599, "alphanum_fraction": 0.7829457521438599, "avg_line_length": 24.799999237060547, "blob_id": "43d8f42221eb4de51f0a54d947f5c3b63762c886", "content_id": "abde969a7e9ed2d59bf1246bd79f67ad5b9237ba", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 774, "license_type": "permissive", "max_line_length": 85, "num_lines": 30, "path": "/libraries/libsystem/unicode/UnicodeString.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/unicode/Codepoint.h>\n\nstruct UnicodeString\n{\n Codepoint *buffer;\n size_t used;\n size_t allocated;\n};\n\nUnicodeString *unicode_string_create(size_t size);\n\nvoid unicode_string_destroy(UnicodeString *string);\n\nUnicodeString *unicode_string_clone(UnicodeString *string);\n\nvoid unicode_string_copy(UnicodeString *source, UnicodeString *destination);\n\nbool unicode_string_equals(UnicodeString *left, UnicodeString *right);\n\nvoid unicode_string_insert(UnicodeString *string, Codepoint codepoint, size_t where);\n\nvoid unicode_string_remove(UnicodeString *string, size_t where);\n\nsize_t unicode_string_length(UnicodeString *string);\n\nchar *unicode_string_as_cstring(UnicodeString *string);\n\nvoid unicode_string_clear(UnicodeString *string);\n" }, { "alpha_fraction": 0.7604166865348816, "alphanum_fraction": 0.7604166865348816, "avg_line_length": 22.75, "blob_id": "7c10d3a96ae154a20b78aec78a390533191a724e", "content_id": "ed787adb7dd9946dffbf335023bda8615ab00360", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 96, "license_type": "permissive", "max_line_length": 42, "num_lines": 4, "path": "/apps/text-editor/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += TEXT_EDITOR\n\nTEXT_EDITOR_NAME = text-editor\nTEXT_EDITOR_LIBS = widget settings graphic\n\n" }, { "alpha_fraction": 0.6601178646087646, "alphanum_fraction": 0.6719056963920593, "avg_line_length": 23.829267501831055, "blob_id": "789b2d53ea034ff29f649638627edaf1e95b4a8c", "content_id": "aae1404098c808564df2748a4f605ddffad1ee16", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1018, "license_type": "permissive", "max_line_length": 109, "num_lines": 41, "path": "/apps/media-player/windows/Main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Icon.h>\n#include <libwidget/Button.h>\n#include <libwidget/Container.h>\n#include <libwidget/Slider.h>\n#include <libwidget/Spacer.h>\n#include <libwidget/TitleBar.h>\n\n#include \"media-player/windows/Main.h\"\n\nnamespace media_player\n{\n\nMain::Main() : Window(WINDOW_NONE | WINDOW_RESIZABLE)\n{\n icon(Icon::get(\"movie\"));\n title(\"Media Player\");\n size(Vec2i(700, 500));\n\n root()->layout(VFLOW(0));\n\n auto cover = new Cover(root(), Bitmap::load_from_or_placeholder(\"/Applications/media-player/cover.png\"));\n\n cover->layout(VFLOW(0));\n cover->flags(Widget::FILL);\n\n new TitleBar(cover);\n new Spacer(cover);\n\n auto control_bar = new Container(cover);\n\n control_bar->insets(12);\n control_bar->layout(HFLOW(4));\n\n new Button(control_bar, Button::FILLED, Icon::get(\"play\"));\n new Button(control_bar, Button::OUTLINE, Icon::get(\"stop\"));\n new Button(control_bar, Button::OUTLINE, Icon::get(\"volume-high\"));\n\n new Slider(control_bar);\n}\n\n} // namespace media_player\n" }, { "alpha_fraction": 0.6615384817123413, "alphanum_fraction": 0.6820513010025024, "avg_line_length": 15.25, "blob_id": "2119ff476c0d3c66994feb64182a176ac55f8f49", "content_id": "16d335df23360a1a59071df97e886c296f7a7fa3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 195, "license_type": "permissive", "max_line_length": 58, "num_lines": 12, "path": "/libraries/libc/strings.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n#include <stdlib.h>\n\n__BEGIN_HEADER\n\nint strcasecmp(const char *s1, const char *s2);\nint strncasecmp(const char *s1, const char *s2, size_t n);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.4429530203342438, "alphanum_fraction": 0.5771812200546265, "avg_line_length": 17.625, "blob_id": "5ceb7a41f24f6970d63c4d18012b174c178bf946", "content_id": "0c6b62578333f54113cd18a2880061a0cf770b22", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 149, "license_type": "permissive", "max_line_length": 28, "num_lines": 8, "path": "/libraries/libsystem/bits/float.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define NAN (0.0 / 0.0)\n#define INFINITY (1.0 / 0.0)\n\n#define INF (1.0 / 0.0)\n#define POS_INF (1.0 / 0.0)\n#define NEG_INF (-1.0 / 0.0)\n" }, { "alpha_fraction": 0.6114910840988159, "alphanum_fraction": 0.6114910840988159, "avg_line_length": 17.274999618530273, "blob_id": "43b460b079eedfb25bac56dba502bfadb16501bf", "content_id": "16d095e42ac2fe063fe9ca2478e64e24237e9c44", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 731, "license_type": "permissive", "max_line_length": 74, "num_lines": 40, "path": "/libraries/libwidget/Image.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n#include <libwidget/Image.h>\n\nImage::Image(Widget *parent, RefPtr<Bitmap> bitmap)\n : Widget(parent), _bitmap(bitmap)\n{\n}\n\nImage::Image(Widget *parent, RefPtr<Bitmap> bitmap, BitmapScaling scaling)\n : Widget(parent), _bitmap(bitmap), _scaling(scaling)\n{\n}\n\nvoid Image::change_bitmap(RefPtr<Bitmap> bitmap)\n{\n if (_bitmap != bitmap)\n {\n _bitmap = bitmap;\n should_repaint();\n }\n}\n\nvoid Image::scaling(BitmapScaling scaling)\n{\n if (_scaling != scaling)\n {\n _scaling = scaling;\n should_repaint();\n }\n}\n\nvoid Image::paint(Painter &painter, const Recti &)\n{\n if (!_bitmap)\n {\n return;\n }\n\n painter.blit(*_bitmap, _scaling, bound());\n}\n" }, { "alpha_fraction": 0.5752097964286804, "alphanum_fraction": 0.5765009522438049, "avg_line_length": 24.83333396911621, "blob_id": "8d7ba377c664cb8bf16adeaa0d692870073e498c", "content_id": "09f001e3ceee638c1c5f4015ec3d212054f9d324", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1549, "license_type": "permissive", "max_line_length": 90, "num_lines": 60, "path": "/libraries/libfilepicker/widgets/DirectoryBrowser.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/process/Launchpad.h>\n#include <libwidget/Table.h>\n\n#include <libfilepicker/model/DirectoryListing.h>\n#include <libfilepicker/model/Navigation.h>\n\nnamespace filepicker\n{\n\nclass DirectoryBrowser : public Table\n{\nprivate:\n RefPtr<Navigation> _navigation;\n RefPtr<DirectoryListing> _listing;\n OwnPtr<Observer<Navigation>> _navigation_observer;\n\npublic:\n Optional<String> selected_path()\n {\n\n return process_resolve(_listing->info(selected()).name);\n }\n\n Callback<void(String &path)> on_element_selected;\n\n DirectoryBrowser(Widget *parent, RefPtr<Navigation> navigation)\n : Table(parent), _navigation(navigation)\n {\n _listing = make<DirectoryListing>(navigation);\n model(_listing);\n\n flags(Widget::FILL);\n\n empty_message(\"This directory is empty.\");\n\n _navigation_observer = navigation->observe([this](auto &) {\n select(-1);\n scroll_to_top();\n });\n\n on(Event::ACTION, [this](auto) {\n if (selected() >= 0)\n {\n if (_listing->info(selected()).type == FILE_TYPE_DIRECTORY)\n {\n _navigation->navigate(_listing->info(selected()).name);\n }\n else if (on_element_selected)\n {\n auto resolved_path = process_resolve(_listing->info(selected()).name);\n on_element_selected(resolved_path);\n }\n }\n });\n }\n};\n\n} // namespace filepicker" }, { "alpha_fraction": 0.6583011746406555, "alphanum_fraction": 0.6583011746406555, "avg_line_length": 20.58333396911621, "blob_id": "83dd4effdf8c986019dcd3841a16fdfede14e208", "content_id": "f86b3640a314bd30f098b85c3959441538ef7c88", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 518, "license_type": "permissive", "max_line_length": 61, "num_lines": 24, "path": "/libraries/libsystem/io/Pipe.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Pipe.h>\n\nPipe *pipe_create()\n{\n Pipe *pipe = __create(Pipe);\n\n int reader_handle = HANDLE_INVALID_ID;\n int writer_handle = HANDLE_INVALID_ID;\n\n __plug_create_pipe(&reader_handle, &writer_handle);\n\n pipe->in = stream_open_handle(writer_handle, OPEN_WRITE);\n pipe->out = stream_open_handle(reader_handle, OPEN_READ);\n\n return pipe;\n}\n\nvoid pipe_destroy(Pipe *pipe)\n{\n stream_close(pipe->in);\n stream_close(pipe->out);\n free(pipe);\n}\n" }, { "alpha_fraction": 0.5792880058288574, "alphanum_fraction": 0.590614914894104, "avg_line_length": 21.88888931274414, "blob_id": "fff1ec5db9ae90480c2e104cf1f1186120d7d227", "content_id": "655c245c5da974aa1f2d4f5573be004e1c11eb3c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1236, "license_type": "permissive", "max_line_length": 79, "num_lines": 54, "path": "/apps/demo/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Button.h>\n#include <libwidget/Container.h>\n#include <libwidget/TitleBar.h>\n\n#include \"demo/DemoWidget.h\"\n\nstatic Demo _demos[] = {\n {\"Path\", path_draw},\n {\"Colors\", colors_draw},\n {\"Graphics\", graphics_draw},\n {\"Lines\", lines_draw},\n {nullptr, nullptr},\n};\n\nint main(int argc, char **argv)\n{\n Result result = Application::initialize(argc, argv);\n\n if (result != SUCCESS)\n {\n return -1;\n }\n\n Window *window = new Window(WINDOW_RESIZABLE);\n window->icon(Icon::get(\"duck\"));\n window->title(\"Demos\");\n window->size(Vec2i(500, 400));\n\n window->root()->layout(VFLOW(0));\n\n new TitleBar(window->root());\n\n Widget *navbar = new Container(window->root());\n\n navbar->insets(Insetsi(4, 4));\n navbar->layout(HGRID(4));\n\n DemoWidget *demo_widget = new DemoWidget(window->root());\n demo_widget->flags(Widget::FILL);\n demo_widget->demo(&_demos[0]);\n\n for (size_t i = 0; _demos[i].name; i++)\n {\n Widget *demo_button = new Button(navbar, Button::TEXT, _demos[i].name);\n\n demo_button->on(Event::ACTION, [i, demo_widget](auto) {\n demo_widget->demo(&_demos[i]);\n });\n }\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.7265625, "alphanum_fraction": 0.7265625, "avg_line_length": 15, "blob_id": "0c40ecbb05dfd5064b4fbc08ca30e2bf016ded88", "content_id": "0b4a9c3825fafbada5419f63f539702af09b3d00", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 128, "license_type": "permissive", "max_line_length": 37, "num_lines": 8, "path": "/apps/logout/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += LOGOUT\n\nLOGOUT_NAME = logout\nLOGOUT_LIBS = widget settings graphic\nLOGOUT_ICONS = \\\n\tpower-standby \\\n\trestart \\\n\tlogout\n" }, { "alpha_fraction": 0.70652174949646, "alphanum_fraction": 0.70652174949646, "avg_line_length": 9.222222328186035, "blob_id": "99f7ceef3b4d78329da09b9033cda204e31a8ae5", "content_id": "8bce603c4848fdea5b82f2ac4fa5a2dea18c153a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 92, "license_type": "permissive", "max_line_length": 27, "num_lines": 9, "path": "/manual/10-utilities/wallpaperctl.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# wallpaperctl\n\n```sh\nwallpaperctl [IMAGE]\n```\n\n## Description\n\nSets the desktop wallpaper.\n" }, { "alpha_fraction": 0.6262425184249878, "alphanum_fraction": 0.6262425184249878, "avg_line_length": 22.578125, "blob_id": "0ae93aa080e54778d76dc33e1522ac35ca022b4e", "content_id": "73ebb6ebaa690a7ae858b44e313deef662517851", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1509, "license_type": "permissive", "max_line_length": 108, "num_lines": 64, "path": "/apps/utilities/now.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/cmdline/CMDLine.h>\n#include <libsystem/io/Stream.h>\n#include <skift/Time.h>\n\n#include <stdio.h>\n\nstatic bool option_time = false;\nstatic bool option_date = false;\nstatic bool option_epoch = false;\n\nstatic const char *usages[] = {\n \"\",\n \"OPTION...\",\n nullptr};\n\nstatic CommandLineOption options[] = {\n COMMANDLINE_OPT_HELP,\n\n COMMANDLINE_OPT_BOOL(\"time\", 't', option_time, \"Display the time of the day.\", COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"date\", 'd', option_date, \"Display today date.\", COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"epoch\", 'e', option_epoch, \"Display the current epoch.\", COMMANDLINE_NO_CALLBACK),\n\n COMMANDLINE_OPT_END,\n};\n\nstatic CommandLine cmdline = CMDLINE(\n usages,\n options,\n \"Get the time of the day.\",\n \"Options can be combined.\");\n\nint main(int argc, char **argv)\n{\n argc = cmdline_parse(&cmdline, argc, argv);\n\n if (!(option_time || option_date || option_epoch))\n {\n option_time = true;\n option_date = true;\n option_epoch = false;\n }\n\n TimeStamp timestamp = timestamp_now();\n DateTime datetime = timestamp_to_datetime(timestamp);\n\n if (option_time)\n {\n printf(\"%d:%d:%d \", datetime.hour, datetime.minute, datetime.second);\n }\n\n if (option_date)\n {\n printf(\"%d/%d/%d \", datetime.day, datetime.month, datetime.year);\n }\n\n if (option_epoch)\n {\n printf(\"%d\", timestamp);\n }\n\n printf(\"\\n\");\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.770682156085968, "alphanum_fraction": 0.770682156085968, "avg_line_length": 26.559999465942383, "blob_id": "d7bfbd0135d7f26f59e62343587a6964fc7ee7f5", "content_id": "4401aa563699acc689768ee7b54667a62a759226", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 689, "license_type": "permissive", "max_line_length": 97, "num_lines": 25, "path": "/kernel/memory/Memory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Memory.h>\n#include <libsystem/Result.h>\n\n#include \"kernel/handover/Handover.h\"\n#include \"kernel/memory/MemoryRange.h\"\n\nvoid memory_initialize(Handover *handover);\n\nvoid memory_dump();\n\nsize_t memory_get_used();\n\nsize_t memory_get_total();\n\nResult memory_map(void *address_space, MemoryRange range, MemoryFlags flags);\n\nResult memory_map_identity(void *address_space, MemoryRange range, MemoryFlags flags);\n\nResult memory_alloc(void *address_space, size_t size, MemoryFlags flags, uintptr_t *out_address);\n\nResult memory_alloc_identity(void *address_space, MemoryFlags flags, uintptr_t *out_address);\n\nResult memory_free(void *address_space, MemoryRange range);\n" }, { "alpha_fraction": 0.6149425506591797, "alphanum_fraction": 0.6919540166854858, "avg_line_length": 15.730769157409668, "blob_id": "ab7f4ce82d83b4c1e6ec9a53dfe4e595ab31632c", "content_id": "748efb0e6e9b53a4cd50130754e8188d47c3af3f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 870, "license_type": "permissive", "max_line_length": 46, "num_lines": 52, "path": "/libraries/libc/fcntl.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <__libc__.h>\n\n#include <sys/types.h>\n\n__BEGIN_HEADER\n\n#define O_RDONLY 0x0000\n#define O_WRONLY 0x0001\n#define O_RDWR 0x0002\n#define O_APPEND 0x0008\n#define O_CREAT 0x0200\n#define O_TRUNC 0x0400\n#define O_EXCL 0x0800\n#define O_NOFOLLOW 0x1000\n#define O_PATH 0x2000\n#define O_NONBLOCK 0x4000\n#define O_DIRECTORY 0x8000\n\n#define F_GETFD 1\n#define F_SETFD 2\n\n#define F_GETFL 3\n#define F_SETFL 4\n\n/* Advisory locks are not currently supported;\n * these definitions are stubs. */\n#define F_GETLK 5\n#define F_SETLK 6\n#define F_SETLKW 7\n\n#define F_RDLCK 0\n#define F_WRLCK 1\n#define F_UNLCK 2\n\nstruct flock\n{\n short l_type;\n short l_whence;\n off_t l_start;\n off_t l_len;\n pid_t l_pid;\n};\n\n#define FD_CLOEXEC (1 << 0)\n\nint open(const char *, int, ...);\nint chmod(const char *path, mode_t mode);\nint fcntl(int fd, int cmd, ...);\n\n__END_HEADER\n" }, { "alpha_fraction": 0.5840757489204407, "alphanum_fraction": 0.596325159072876, "avg_line_length": 24.657142639160156, "blob_id": "a11554fba749e5282dc68689ffa4dfaca2be38d8", "content_id": "2a2e18f36a2e9b118671d65ed948fcad82ad2a9c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1796, "license_type": "permissive", "max_line_length": 99, "num_lines": 70, "path": "/apps/task-manager/windows/MainWindow.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Button.h>\n#include <libwidget/Panel.h>\n#include <libwidget/Separator.h>\n#include <libwidget/TitleBar.h>\n#include <libwidget/dialog/MessageBox.h>\n\n#include \"task-manager/windows/MainWindow.h\"\n\nnamespace task_manager\n{\n\nMainWinow::MainWinow() : Window(WINDOW_RESIZABLE)\n{\n icon(Icon::get(\"memory\"));\n title(\"Task Manager\");\n size(Vec2i(700, 500));\n\n root()->layout(VFLOW(0));\n\n new TitleBar(root());\n\n /// --- Toolbar --- ///\n auto toolbar = new Panel(root());\n\n toolbar->layout(HFLOW(4));\n toolbar->insets(Insetsi(4, 4));\n toolbar->max_height(38);\n toolbar->min_height(38);\n\n new Button(toolbar, Button::FILLED, Icon::get(\"plus\"), \"New task\");\n\n auto cancel_task_button = new Button(toolbar, Button::TEXT, Icon::get(\"close\"), \"Cancel task\");\n cancel_task_button->on(Event::ACTION, [&](auto) {\n auto result = MessageBox::create_and_show(\n \"Cancel task\",\n \"Are you sure about that ?\",\n Icon::get(\"close\"),\n DialogButton::YES | DialogButton::NO);\n\n if (result == DialogResult::YES)\n {\n _table_model->kill_task(_table->selected());\n };\n });\n\n /// --- Table view --- //\n _table_model = make<TaskModel>();\n\n _table = new Table(root(), _table_model);\n _table->flags(Widget::FILL);\n\n _table_timer = own<Timer>(1000, [&]() {\n _table_model->update();\n });\n\n _table_timer->start();\n\n /// --- Graphs --- ///\n auto graphs_container = new Panel(root());\n graphs_container->layout(HFLOW(0));\n graphs_container->max_height(96);\n\n _cpu_graph = new CPUGraph(graphs_container, _table_model);\n\n new Separator(graphs_container);\n\n _ram_graph = new RAMGraph(graphs_container, _table_model);\n}\n\n} // namespace task_manager\n" }, { "alpha_fraction": 0.5688118934631348, "alphanum_fraction": 0.5995049476623535, "avg_line_length": 29.606060028076172, "blob_id": "40eaa706ea0a7e8fe9bc5559f96a64e4d30e5788", "content_id": "1477e28060fae792a7bec093e9922da1a334c4d1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2020, "license_type": "permissive", "max_line_length": 107, "num_lines": 66, "path": "/apps/splash-screen/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Framebuffer.h>\n#include <libsystem/process/Process.h>\n\nstatic const auto BACKGROUND = Color::from_hex(0x18181B);\nstatic const auto PROGRESS = Color::from_hex(0x0066ff);\nstatic const auto REMAINING = Color::from_hex(0x444444);\n\nint main(int argc, char **argv)\n{\n __unused(argc);\n __unused(argv);\n\n auto framebuffer_or_result = Framebuffer::open();\n\n if (!framebuffer_or_result.success())\n {\n return -1;\n }\n\n auto framebuffer = framebuffer_or_result.take_value();\n\n auto logo = Bitmap::load_from_or_placeholder(\"/Applications/splash-screen/logo.png\");\n auto cat = Bitmap::load_from_or_placeholder(\"/Applications/splash-screen/cat.png\");\n\n auto logo_container = logo->bound().centered_within(framebuffer->resolution());\n\n auto loading_container = Recti(0, 0, logo_container.width() * 1.4, 4)\n .centered_within(framebuffer->resolution())\n .offset(Vec2i(0, logo_container.height() + 26));\n\n auto &painter = framebuffer->painter();\n\n painter.clear(BACKGROUND);\n\n painter.blit(*logo, logo->bound(), logo_container);\n\n framebuffer->mark_dirty_all();\n framebuffer->blit();\n\n for (size_t i = 0; i <= 100; i++)\n {\n painter.clear(loading_container, REMAINING);\n\n Recti progress = loading_container.take_left(loading_container.width() * (i / 100.0));\n\n if (argc == 2 && strcmp(argv[1], \"--nyan\") == 0)\n {\n auto color = Color::from_hsv((int)(360 * (i / 100.0) * 2) % 360, 0.5, 1);\n\n painter.clear(progress, color);\n painter.blit(*cat, cat->bound(), cat->bound().moved(progress.top_right() + Vec2i(-4, -2 - 8)));\n }\n else\n {\n painter.clear(progress, PROGRESS);\n painter.fill_rectangle(progress.take_right(1), REMAINING);\n }\n\n framebuffer->mark_dirty(loading_container.expended(Insetsi(16)));\n framebuffer->blit();\n\n process_sleep(5);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6589403748512268, "alphanum_fraction": 0.6589403748512268, "avg_line_length": 19.133333206176758, "blob_id": "aa3a85402f0128122977167388f273acb290f5d9", "content_id": "84aa6aa620bf97d6795270d52f5da5d1b996d2a6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 302, "license_type": "permissive", "max_line_length": 47, "num_lines": 15, "path": "/apps/utilities/pwd.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/Stream.h>\n#include <libsystem/process/Process.h>\n#include <stdio.h>\n\nint main(int argc, char **argv)\n{\n __unused(argc);\n __unused(argv);\n\n char buffer[PATH_LENGTH];\n process_get_directory(buffer, PATH_LENGTH);\n printf(\"%s\", buffer);\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.5665137767791748, "alphanum_fraction": 0.5756880640983582, "avg_line_length": 14.571428298950195, "blob_id": "cadc09983ccfb45cfcbbc2c807d6ffa3a040bad0", "content_id": "efac3c5822ab32add96493dfb53928f2b24f32b8", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 436, "license_type": "permissive", "max_line_length": 50, "num_lines": 28, "path": "/apps/demo/DemoWidget.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\n#include \"demo/Demos.h\"\n\nclass DemoWidget : public Widget\n{\nprivate:\n double _time{};\n Demo *_demo;\n OwnPtr<Timer> _timer;\n\npublic:\n Demo *demo() { return _demo; }\n\n void demo(Demo *demo)\n {\n _demo = demo;\n should_repaint();\n }\n\n DemoWidget(Widget *parent);\n\n void tick() { _time += 1.0 / 60; }\n\n void paint(Painter &, const Recti &) override;\n};\n" }, { "alpha_fraction": 0.6788412928581238, "alphanum_fraction": 0.6788412928581238, "avg_line_length": 22.701492309570312, "blob_id": "80075c036adb8dddac8563fd8a3fcc1acb2248d8", "content_id": "235042a9cda1d21f20a259cc73cff134d908fb47", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1588, "license_type": "permissive", "max_line_length": 106, "num_lines": 67, "path": "/kernel/tasking/Handles.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Path.h>\n\n#include \"kernel/node/Handle.h\"\n\nclass Handles\n{\nprivate:\n Lock _lock{\"handles-lock\"};\n\n RefPtr<FsHandle> _handles[PROCESS_HANDLE_COUNT];\n\n ResultOr<int> add(RefPtr<FsHandle> handle);\n\n Result add_at(RefPtr<FsHandle> handle, int index);\n\n bool is_valid_handle(int handle);\n\n Result remove(int handle_index);\n\n RefPtr<FsHandle> acquire(int handle_index);\n\n Result release(int handle_index);\n\npublic:\n Handles() {}\n\n ~Handles() { close_all(); }\n\n ResultOr<int> open(Domain &domain, Path &path, OpenFlag flags);\n\n ResultOr<int> connect(Domain &domain, Path &socket_path);\n\n Result close(int handle_index);\n\n void close_all();\n\n Result reopen(int handle, int *reopened);\n\n Result copy(int source, int destination);\n\n Result poll(HandleSet *handles_set, int *selected_index, PollEvent *selected_events, Timeout timeout);\n\n ResultOr<size_t> read(int handle_index, void *buffer, size_t size);\n\n ResultOr<size_t> write(int handle_index, const void *buffer, size_t size);\n\n ResultOr<int> seek(int handle_index, int offset, Whence whence);\n\n Result call(int handle_index, IOCall request, void *args);\n\n Result stat(int handle_index, FileState *stat);\n\n ResultOr<int> accept(int handle_index);\n\n Result duplex(\n RefPtr<FsNode> node,\n int *server, OpenFlag server_flags,\n int *client, OpenFlag client_flags);\n\n Result term(int *server, int *client);\n\n Result pipe(int *reader, int *writer);\n\n Result pass(Handles &handles, int source, int destination);\n};\n" }, { "alpha_fraction": 0.7943925261497498, "alphanum_fraction": 0.7943925261497498, "avg_line_length": 25.75, "blob_id": "c4700b6069e29ba016f5e75537d31bce8c18bb08", "content_id": "10f19cbd0923e2ef4bcc4261694b9095f94ce249", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 107, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/apps/device-manager/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += DEVICE_MANAGER\n\nDEVICE_MANAGER_NAME = device-manager\nDEVICE_MANAGER_LIBS = widget settings graphic\n" }, { "alpha_fraction": 0.7313432693481445, "alphanum_fraction": 0.7313432693481445, "avg_line_length": 15.75, "blob_id": "f9f020d1b65c708a4ae401564e8a36af694c7254", "content_id": "baf948bce4bb2048c64a95690617da1a31e0d4b4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 67, "license_type": "permissive", "max_line_length": 35, "num_lines": 4, "path": "/apps/demo/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += DEMO\n\nDEMO_NAME = demo\nDEMO_LIBS = widget settings graphic\n" }, { "alpha_fraction": 0.6446378827095032, "alphanum_fraction": 0.6497823596000671, "avg_line_length": 28.057470321655273, "blob_id": "91e881f919a7ae2750fc473e91dc35c36ef24438", "content_id": "8c457ab7a24b3aa6aa65292e64cb323ba443cf0a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2527, "license_type": "permissive", "max_line_length": 125, "num_lines": 87, "path": "/apps/panel/windows/MenuWindow.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/process/Process.h>\n#include <libwidget/Button.h>\n#include <libwidget/Container.h>\n#include <libwidget/Panel.h>\n#include <libwidget/Screen.h>\n#include <libwidget/Separator.h>\n#include <libwidget/Spacer.h>\n#include <skift/Environment.h>\n\n#include \"panel/model/MenuEntry.h\"\n#include \"panel/widgets/ApplicationListing.h\"\n#include \"panel/widgets/SearchBar.h\"\n#include \"panel/windows/MenuWindow.h\"\n#include \"panel/windows/PanelWindow.h\"\n\nnamespace panel\n{\n\nMenuWindow::MenuWindow()\n : Window(WINDOW_BORDERLESS | WINDOW_ALWAYS_FOCUSED | WINDOW_AUTO_CLOSE | WINDOW_ACRYLIC | WINDOW_NO_ROUNDED_CORNERS)\n{\n title(\"Panel\");\n bound(Screen::bound().with_width(WIDTH).shrinked({PanelWindow::HEIGHT, 0, 0, 0}));\n type(WINDOW_TYPE_POPOVER);\n opacity(0.85);\n\n on(Event::DISPLAY_SIZE_CHANGED, [this](auto) {\n bound(Screen::bound().with_width(WIDTH).shrinked({PanelWindow::HEIGHT, 0, 0, 0}));\n });\n\n root()->layout(HFLOW(0));\n\n auto container = new Container(root());\n container->layout(VFLOW(0));\n container->flags(Widget::FILL);\n\n new Separator(root());\n\n auto model = TextModel::empty();\n\n new SearchBar(container, model);\n\n auto listing = new ApplicationListing(container);\n\n _search_query_observer = model->observe([listing](auto &text) {\n listing->filter(text.string());\n });\n\n auto account_container = new Panel(container);\n account_container->layout(HFLOW(4));\n account_container->insets({6});\n\n new Button(account_container, Button::TEXT, Icon::get(\"account\"), environment().get(\"POSIX\").get(\"LOGNAME\").as_string());\n\n new Spacer(account_container);\n\n auto folder_button = new Button(account_container, Button::TEXT, Icon::get(\"folder\"));\n\n folder_button->on(EventType::ACTION, [&](auto) {\n process_run(\"file-manager\", nullptr);\n });\n\n auto setting_button = new Button(account_container, Button::TEXT, Icon::get(\"cog\"));\n\n setting_button->on(EventType::ACTION, [&](auto) {\n process_run(\"settings\", nullptr);\n });\n\n auto logout_button = new Button(account_container, Button::TEXT, Icon::get(\"power-standby\"));\n logout_button->on(EventType::ACTION, [&](auto) {\n process_run(\"logout\", nullptr);\n });\n\n on(Event::KEYBOARD_KEY_PRESS, [this](Event *event) {\n if (event->keyboard.key == KEYBOARD_KEY_ESC)\n {\n hide();\n event->accepted = true;\n }\n });\n\n on(Event::GOT_FOCUS, [model](auto) {\n model->clear();\n });\n}\n\n} // namespace panel" }, { "alpha_fraction": 0.7157894968986511, "alphanum_fraction": 0.7157894968986511, "avg_line_length": 13.300000190734863, "blob_id": "8ee407bd9d239a95ae9885b42541e7e842edce0b", "content_id": "b847f70c664c0195c4126ef14515915a61e3f0b0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 285, "license_type": "permissive", "max_line_length": 38, "num_lines": 20, "path": "/apps/panel/widgets/RessourceMonitor.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/eventloop/Timer.h>\n\n#include <libwidget/Button.h>\n\nnamespace panel\n{\n\nclass RessourceMonitor : public Button\n{\nprivate:\n OwnPtr<Timer> _ram_timer;\n OwnPtr<Timer> _cpu_timer;\n\npublic:\n RessourceMonitor(Widget *parent);\n};\n\n} // namespace panel" }, { "alpha_fraction": 0.5924491882324219, "alphanum_fraction": 0.6011616587638855, "avg_line_length": 25.487178802490234, "blob_id": "32f79262d84b0d0dddbec2c08ec3901cbd2fda11", "content_id": "7eeecf45c764183baaa65c098c1b17678b8f5d13", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1033, "license_type": "permissive", "max_line_length": 52, "num_lines": 39, "path": "/toolbox/include-contrib.py", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/env python3\nimport sys\nimport os\n\nif not \"SKIFT_SYSROOT\" in os.environ:\n print(\"Please run use-it.sh first\")\n exit(1)\n\ndef usage():\n print(f\"Usage: {sys.argv[0]} <name> <name> ...\")\n\nif len(sys.argv) < 2:\n usage()\n\nsysroot = os.environ[\"SKIFT_SYSROOT\"]\ncontrib = os.environ[\"SKIFT_CONTRIBROOT\"]\nskift = os.path.join(contrib, \"..\")\n\nfor module in sys.argv[1:]:\n path = os.path.join(contrib, module)\n if not os.path.isdir(path):\n print(f\"{path} not found\")\n continue\n os.chdir(path)\n if not os.system(\"./clean-it.sh\") == 0:\n print(f\"Error while cleaning {module}\")\n continue\n if not os.system(\"./get-it.sh\") == 0:\n print(f\"Error while downloading {module}\")\n continue\n if not os.system(\"./build-it.sh\") == 0:\n print(f\"Error while building {module}\")\n continue\n if not os.system(\"./install-it.sh\") == 0:\n print(f\"Error while installing {module}\")\n continue\n os.chdir(skift)\nos.chdir(contrib)\nos.system(\"git checkout -- *\")\n" }, { "alpha_fraction": 0.5563470125198364, "alphanum_fraction": 0.566013753414154, "avg_line_length": 28.5563907623291, "blob_id": "156cc829712d84b2636794fcc2cb62e793e74fce", "content_id": "75dd474923fab968773fe0f5fa499ff36d0ffe5e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3932, "license_type": "permissive", "max_line_length": 153, "num_lines": 133, "path": "/kernel/system/Panic.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"archs/Architectures.h\"\n\n#include \"kernel/graphics/EarlyConsole.h\"\n#include \"kernel/graphics/Font.h\"\n#include \"kernel/interrupts/Interupts.h\"\n#include \"kernel/scheduling/Scheduler.h\"\n#include \"kernel/system/System.h\"\n#include \"kernel/tasking/Task.h\"\n\nstatic const char *YO_DAWG =\n \"Yo DAWG, I heard you like errors, \\n\\t\"\n \"// so I put an error in your error handler\\n\\t\"\n \"// so you can get error while you get error\";\n\nstatic const char *const witty_comments[] = {\n \"Witty comment unavailable :(\",\n\n \"Excuse me Sir, \\n\\t\"\n \"// Do you have a moment to talk about TempleOS?\",\n\n \"Surprise! Haha. Well, this is awkward.\",\n \"Oh - I know what I did wrong!\",\n \"Uh... Did I do that?\",\n \"Oops.\",\n \"On the bright side, I bought you a teddy bear!\",\n \"DON'T PANIC!\",\n \"...\",\n \"Greenpeace free'd the mallocs \\\\o/\",\n \"Typo in the code.\",\n \"System consumed all the paper for paging!\",\n \"Suspicious pointer corrupted the machine.\",\n \"I'm tired of this ;_;\",\n \"PC LOAD LETTER\",\n \"Abort, Retry, Fail?\",\n \"Bad command or file name\",\n \"OOF!\",\n \"OoooOOoOoOF!\",\n \"Et là c'est le drame...\",\n \"Everything's going to plan. No, really, that was supposed to happen.\",\n \"My bad.\",\n \"Minecraft crashed!\",\n \"Quite honestly, I wouldn't worry myself about that.\",\n \"This doesn't make any sense!\",\n \"It's not a good surprise...\",\n \"Don't do that.\",\n \"Get the f*** outa my room, I'm playing minecraft\",\n};\n\nstatic bool has_panic = false;\nstatic bool nested_panic = false;\n\nvoid system_panic_internal(__SOURCE_LOCATION__ location, void *stackframe, const char *message, ...)\n{\n interrupts_retain();\n interrupts_disable_holding();\n\n font_set_bg(0xff333333);\n\n early_console_enable();\n\n va_list va;\n va_start(va, message);\n\n if (nested_panic)\n {\n system_stop();\n }\n\n if (!has_panic)\n {\n has_panic = true;\n stream_format(out_stream, \"\\n\\e[0;33m--- \\e[0;31m!!!\\e[0;33m ------------------------------------------------------------------------\\e[0m\\n\");\n stream_format(out_stream, \"\\n\\tKERNEL\");\n stream_format(out_stream, \" PANIC\\n\\t// %s\\n\\n\\t\\e[0;31m\", witty_comments[system_get_tick() % __array_length(witty_comments)]);\n }\n else\n {\n nested_panic = true;\n stream_format(out_stream, \"\\n\\n\\e[0;33m- - \\e[0;31mNESTED\\e[0;33m - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\\e[0m\\n\");\n stream_format(out_stream, \"\\n\\tNESTED\");\n stream_format(out_stream, \" PANIC\\n\\t// %s\\n\\n\\t\\e[0;31m\", YO_DAWG);\n }\n\n stream_vprintf(out_stream, message, va);\n stream_format(out_stream, \"\\e[0m\\n\\tthrow by %s %s() ln%d\", location.file, location.function, location.line);\n\n stream_format(out_stream, \"\\n\");\n stream_format(out_stream, \"\\n\\tDiagnostic:\");\n stream_format(out_stream, \"\\n\\tThe system was running for %d tick.\", system_get_tick());\n\n if (scheduler_running_id() != -1)\n {\n stream_format(out_stream, \"\\n\\tThe running process is %d: %s\", scheduler_running_id(), scheduler_running()->name);\n }\n\n if (scheduler_is_context_switch())\n {\n stream_format(out_stream, \"\\n\\tWe are context switching\\n\", system_get_tick());\n }\n else\n {\n stream_format(out_stream, \"\\n\");\n }\n\n stream_format(out_stream, \"\\n\\tStackframe:\\n\");\n if (stackframe)\n {\n arch_dump_stack_frame(stackframe);\n }\n else\n {\n arch_backtrace();\n }\n stream_format(out_stream, \"\\n\");\n\n memory_dump();\n\n stream_format(out_stream, \"\\n\");\n\n if (!nested_panic)\n {\n task_dump(scheduler_running());\n arch_panic_dump();\n }\n\n stream_format(out_stream, \"\\n\");\n\n stream_format(out_stream, \"\\n\\tSystem halted!\\n\");\n\n stream_format(out_stream, \"\\n\\e[0;33m--------------------------------------------------------------------------------\\n\\n\");\n\n system_stop();\n}\n" }, { "alpha_fraction": 0.7558139562606812, "alphanum_fraction": 0.7558139562606812, "avg_line_length": 20.5, "blob_id": "fe4a0a51c30a8d89af7d641a56b336bebff27fcf", "content_id": "19a50810c47908bb136d942fa152f994eda4c698", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 86, "license_type": "permissive", "max_line_length": 51, "num_lines": 4, "path": "/libraries/libutils/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += UTILS\n\nUTILS_NAME = utils\nUTILS_CXXFLAGS = -fno-tree-loop-distribute-patterns\n" }, { "alpha_fraction": 0.6504854559898376, "alphanum_fraction": 0.6504854559898376, "avg_line_length": 10.44444465637207, "blob_id": "49359eb032eb5231d5577f12e343b42be2744b57", "content_id": "083751507a3abbd932de0d718a6db7b6914e357e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 103, "license_type": "permissive", "max_line_length": 59, "num_lines": 9, "path": "/manual/10-utilities/ls.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# ls\n\n```sh\nls [PATH]\n```\n\n## Description\n\nls is short for list. ls lists the contents of a directory.\n" }, { "alpha_fraction": 0.41310933232307434, "alphanum_fraction": 0.5337372422218323, "avg_line_length": 23.36912727355957, "blob_id": "3f4e5df7e27590b49825a5fab38d871bb69059f3", "content_id": "d1ecbb5363e5fdbf539c91f95e50acb91f2379d8", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3631, "license_type": "permissive", "max_line_length": 104, "num_lines": 149, "path": "/toolbox/kmap-compiler.py", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport json\nimport sys\nimport struct\n\nKEYS = {\n \"KEY_ESC\": 0x01,\n \"KEY_NUM1\": 0x02,\n \"KEY_NUM2\": 0x03,\n \"KEY_NUM3\": 0x04,\n \"KEY_NUM4\": 0x05,\n \"KEY_NUM5\": 0x06,\n \"KEY_NUM6\": 0x07,\n \"KEY_NUM7\": 0x08,\n \"KEY_NUM8\": 0x09,\n \"KEY_NUM9\": 0x0A,\n \"KEY_NUM0\": 0x0B,\n \"KEY_SYM1\": 0x0C,\n \"KEY_SYM2\": 0x0D,\n \"KEY_BKSPC\": 0x0E,\n \"KEY_TAB\": 0x0F,\n \"KEY_Q\": 0x10,\n \"KEY_W\": 0x11,\n \"KEY_E\": 0x12,\n \"KEY_R\": 0x13,\n \"KEY_T\": 0x14,\n \"KEY_Y\": 0x15,\n \"KEY_U\": 0x16,\n \"KEY_I\": 0x17,\n \"KEY_O\": 0x18,\n \"KEY_P\": 0x19,\n \"KEY_SYM3\": 0x1A,\n \"KEY_SYM4\": 0x1B,\n \"KEY_ENTER\": 0x1C,\n \"KEY_LCTRL\": 0x1D,\n \"KEY_A\": 0x1E,\n \"KEY_S\": 0x1F,\n \"KEY_D\": 0x20,\n \"KEY_F\": 0x21,\n \"KEY_G\": 0x22,\n \"KEY_H\": 0x23,\n \"KEY_J\": 0x24,\n \"KEY_K\": 0x25,\n \"KEY_L\": 0x26,\n \"KEY_SYM5\": 0x27,\n \"KEY_SYM6\": 0x28,\n \"KEY_SYM7\": 0x29,\n \"KEY_LSHIFT\": 0x2A,\n \"KEY_SYM8\": 0x2B,\n \"KEY_Z\": 0x2C,\n \"KEY_X\": 0x2D,\n \"KEY_C\": 0x2E,\n \"KEY_V\": 0x2F,\n \"KEY_B\": 0x30,\n \"KEY_N\": 0x31,\n \"KEY_M\": 0x32,\n \"KEY_SYM9\": 0x33,\n \"KEY_SYM10\": 0x34,\n \"KEY_SYM11\": 0x35,\n \"KEY_RSHIFT\": 0x36,\n \"KEY_SYM12\": 0x37,\n \"KEY_LALT\": 0x38,\n \"KEY_SPACE\": 0x39,\n \"KEY_CAPSLOCK\": 0x3A,\n \"KEY_F1\": 0x3B,\n \"KEY_F2\": 0x3C,\n \"KEY_F3\": 0x3D,\n \"KEY_F4\": 0x3E,\n \"KEY_F5\": 0x3F,\n \"KEY_F6\": 0x40,\n \"KEY_F7\": 0x41,\n \"KEY_F8\": 0x42,\n \"KEY_F9\": 0x43,\n \"KEY_F10\": 0x44,\n \"KEY_NUMLOCK\": 0x45,\n \"KEY_SCROLLLOCK\": 0x46,\n \"KEY_KPAD7\": 0x47,\n \"KEY_KPAD8\": 0x48,\n \"KEY_KPAD9\": 0x49,\n \"KEY_SYM13\": 0x4A,\n \"KEY_KPAD4\": 0x4B,\n \"KEY_KPAD5\": 0x4C,\n \"KEY_KPAD6\": 0x4D,\n \"KEY_SYM14\": 0x4E,\n \"KEY_KPAD1\": 0x4F,\n \"KEY_KPAD2\": 0x50,\n \"KEY_KPAD3\": 0x51,\n \"KEY_KPAD0\": 0x52,\n \"KEY_SYM15\": 0x53,\n \"KEY_ALTSYSRQ\": 0x54,\n \"KEY_NO_STANDARD_MEANING_1\": 0x55,\n \"KEY_NO_STANDARD_MEANING_2\": 0x56,\n \"KEY_F11\": 0x57,\n \"KEY_F12\": 0x58,\n \"KEY_KPADENTER\": (0x80 + 0x1C),\n \"KEY_RCTRL\": (0x80 + 0x1D),\n \"KEY_FAKELSHIFT\": (0x80 + 0x2A),\n \"KEY_SYM16\": (0x80 + 0x35),\n \"KEY_FAKERSHIFT\": (0x80 + 0x36),\n \"KEY_CTRLPRINTSCRN\": (0x80 + 0x37),\n \"KEY_RALT\": (0x80 + 0x38),\n \"KEY_CTRLBREAK\": (0x80 + 0x46),\n \"KEY_HOME\": (0x80 + 0x47),\n \"KEY_UP\": (0x80 + 0x48),\n \"KEY_PGUP\": (0x80 + 0x49),\n \"KEY_LEFT\": (0x80 + 0x4B),\n \"KEY_RIGHT\": (0x80 + 0x4D),\n \"KEY_END\": (0x80 + 0x4F),\n \"KEY_DOWN\": (0x80 + 0x50),\n \"KEY_PGDOWN\": (0x80 + 0x51),\n \"KEY_INSERT\": (0x80 + 0x52),\n \"KEY_DELETE\": (0x80 + 0x53),\n \"KEY_LSUPER\": (0x80 + 0x5B),\n \"KEY_RSUPER\": (0x80 + 0x5C),\n \"KEY_MENU\": (0x80 + 0x5D),\n}\n\nin_filename = sys.argv[1]\nout_filename = sys.argv[2]\n\ninfp = open(in_filename, 'r')\ndata = json.load(infp)\ninfp.close()\n\noutfp = open(out_filename, 'wb')\n\noutfp.write(struct.pack(\"4s\", b\"kmap\"))\noutfp.write(struct.pack(\"16s\", data[\"language\"].encode(\"utf-8\")))\noutfp.write(struct.pack(\"16s\", data[\"region\"].encode(\"utf-8\")))\n\noutfp.write(struct.pack(\"I\", len(data[\"mappings\"])))\n\nfor key in data[\"mappings\"]:\n bind = data[\"mappings\"][key]\n\n if len(bind) == 4:\n codepoint_regular = 0 if len(bind[0]) == 0 else ord(bind[0])\n codepoint_shift = 0 if len(bind[1]) == 0 else ord(bind[1])\n codepoint_alt = 0 if len(bind[2]) == 0 else ord(bind[2])\n codepoint_shift_alt = 0 if len(bind[3]) == 0 else ord(bind[3])\n\n outfp.write(struct.pack(\n \"IIIII\", KEYS[key], codepoint_regular, codepoint_shift, codepoint_alt, codepoint_shift_alt))\n else:\n print(\"Warning invalid mapping for key \" + key)\n\n\noutfp.close()\n" }, { "alpha_fraction": 0.5537757277488708, "alphanum_fraction": 0.5598779320716858, "avg_line_length": 18.27941131591797, "blob_id": "925b78801f84d6c9fa09da5ba1704d92dc298c27", "content_id": "9dc343f6567cb7c203b844f7d664c53c5803a541", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1311, "license_type": "permissive", "max_line_length": 86, "num_lines": 68, "path": "/libraries/libsystem/io_new/Copy.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Array.h>\n#include <libutils/Slice.h>\n\n#include <libsystem/io_new/MemoryWriter.h>\n#include <libsystem/io_new/Reader.h>\n#include <libsystem/io_new/Writer.h>\n\nnamespace System\n{\n\nResult copy(Reader &from, Writer &to)\n{\n constexpr int COPY_CHUNK_SIZE = 4096;\n\n do\n {\n Array<uint8_t, COPY_CHUNK_SIZE> copy_chunk;\n\n auto result_or_read = from.read(copy_chunk.raw_storage(), copy_chunk.count());\n\n if (!result_or_read)\n {\n return result_or_read.result();\n }\n\n if (*result_or_read == 0)\n {\n to.flush();\n return SUCCESS;\n }\n\n size_t chunk_size = *result_or_read;\n auto result_or_written = to.write(copy_chunk.raw_storage(), chunk_size);\n\n if (!result_or_written)\n {\n return result_or_written.result();\n }\n\n if (*result_or_written == 0)\n {\n to.flush();\n return SUCCESS;\n }\n } while (1);\n}\n\nResultOr<Slice> read_all(Reader &reader)\n{\n MemoryWriter memory;\n\n auto copy_result = copy(reader, memory);\n\n if (copy_result != SUCCESS)\n {\n return copy_result;\n }\n\n return Slice{memory.slice()};\n}\n//\n// Result write_all(Writer &writer, Slice data)\n// {\n// }\n\n} // namespace System\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.6410256624221802, "avg_line_length": 7.666666507720947, "blob_id": "6020352f79d1a12733c0c1c1ce79a4f275007b4a", "content_id": "2288ae1a2be3dae24d4ceddce17a63c030643d78", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 78, "license_type": "permissive", "max_line_length": 28, "num_lines": 9, "path": "/manual/10-utilities/echo.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# echo\n\n```sh\necho [STRING]\n```\n\n## Description\n\nPrints text to the terminal.\n" }, { "alpha_fraction": 0.7414805889129639, "alphanum_fraction": 0.7438308000564575, "avg_line_length": 30.55555534362793, "blob_id": "e8459df05b7e6fa1c0bf11aaf29b055937a7e2d5", "content_id": "2250c42254c21059613e2950f389a06819ee8fa9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 851, "license_type": "permissive", "max_line_length": 113, "num_lines": 27, "path": "/libraries/libsystem/compression/Deflate.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/Common.h>\n#include <libsystem/Result.h>\n#include <libsystem/compression/Common.h>\n#include <libsystem/io/BitWriter.h>\n#include <libutils/Callback.h>\n\nclass Reader;\nclass Writer;\nclass Deflate\n{\npublic:\n Deflate(unsigned int compression_level);\n\n Result perform(Reader &uncompressed, Writer &compressed);\n\nprivate:\n static void write_block_header(BitWriter &out_stream, BlockType block_type, bool final);\n static void write_uncompressed_block(Reader &in_data, uint16_t block_len, BitWriter &out_stream, bool final);\n static void write_uncompressed_blocks(Reader &in_data, BitWriter &out_stream, bool final);\n\n static Result compress_none(Reader &, Writer &);\n\n Callback<Result(Reader &, Writer &)> _compression_method;\n unsigned int _compression_level;\n unsigned int _min_size_to_compress;\n};" }, { "alpha_fraction": 0.5608380436897278, "alphanum_fraction": 0.5608380436897278, "avg_line_length": 16.72857093811035, "blob_id": "83d5bcf04f6773b45c06f88598dd144ee04dcc01", "content_id": "c5bafcc5509299003c8430a5b86c5a3f27b92966", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1241, "license_type": "permissive", "max_line_length": 64, "num_lines": 70, "path": "/libraries/libutils/ResultOr.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <assert.h>\n#include <libsystem/Result.h>\n\n#include <libutils/Move.h>\n#include <libutils/Optional.h>\n\ntemplate <typename T>\nclass ResultOr\n{\nprivate:\n Result _result = SUCCESS;\n Optional<T> _value;\n\npublic:\n bool success() { return _result == SUCCESS; }\n\n T &value()\n {\n assert(success());\n\n return *_value;\n }\n\n const T &value() const\n {\n assert(success());\n\n return *_value;\n }\n\n T take_value()\n {\n assert(success());\n\n return _value.take_value();\n }\n\n Result result() const { return _result; }\n\n const char *description()\n {\n return get_result_description(_result);\n }\n\n ResultOr(Result result) : _result{result}, _value{} {}\n\n ResultOr(T value) : _result{SUCCESS}, _value{move(value)} {}\n\n bool operator==(Result result) const\n {\n return _result == result;\n }\n\n bool operator==(const T &other) const\n {\n return _value == other;\n }\n\n operator bool() const { return _result == SUCCESS; }\n\n T &operator*() { return value(); }\n\n const T &operator*() const { return value(); }\n\n T *operator->() { return &value(); }\n\n const T *operator->() const { return &value(); }\n};\n" }, { "alpha_fraction": 0.4722370505332947, "alphanum_fraction": 0.4954618215560913, "avg_line_length": 19.032085418701172, "blob_id": "d5181fa69c8046a17c62648fe793c742089ff1cf", "content_id": "060545c42856f844259fd8ef60d05fe51e5fbd98", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3752, "license_type": "permissive", "max_line_length": 105, "num_lines": 187, "path": "/libraries/libutils/ScannerUtils.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#ifndef __KERNEL__\n# include <math.h>\n#endif\n\n#include <libutils/Scanner.h>\n#include <libutils/Strings.h>\n\nstatic inline const char *scan_json_escape_sequence(Scanner &scan)\n{\n scan.skip('\\\\');\n\n if (scan.ended())\n {\n return \"\\\\\";\n }\n\n char chr = scan.current();\n scan.foreward();\n\n switch (chr)\n {\n case '\"':\n return \"\\\"\";\n\n case '\\\\':\n return \"\\\\\";\n\n case '/':\n return \"/\";\n\n case 'b':\n return \"\\b\";\n\n case 'f':\n return \"\\f\";\n\n case 'n':\n return \"\\n\";\n\n case 'r':\n return \"\\r\";\n\n case 't':\n return \"\\t\";\n\n case 'u':\n {\n auto read_4hex = [&]() {\n char buffer[5];\n for (size_t i = 0; i < 4 && scan.current_is(Strings::LOWERCASE_XDIGITS); i++)\n {\n buffer[i] = scan.current();\n scan.foreward();\n }\n\n uint32_t value = 0;\n parse_uint(PARSER_HEXADECIMAL, buffer, 5, (unsigned int *)&value);\n return value;\n };\n\n uint32_t first_surrogate = read_4hex();\n\n if (first_surrogate >= 0xDC00 && first_surrogate <= 0xDFFF)\n {\n // FIXME: We should use char8_t\n return reinterpret_cast<const char *>(u8\"�\");\n }\n\n if (!(first_surrogate >= 0xD800 && first_surrogate <= 0xDBFF))\n {\n // Not an UTF16 surrogate pair.\n static uint8_t utf8[5] = {};\n codepoint_to_utf8((Codepoint)first_surrogate, utf8);\n return (char *)utf8;\n }\n\n if (!scan.skip_word(\"\\\\u\"))\n {\n // FIXME: We should use char8_t\n return reinterpret_cast<const char *>(u8\"�\");\n }\n\n uint32_t second_surrogate = read_4hex();\n\n if ((second_surrogate < 0xDC00) || (second_surrogate > 0xDFFF))\n {\n // Invalid second half of the surrogate pair\n // FIXME: We should use char8_t\n return reinterpret_cast<const char *>(u8\"�\");\n }\n\n Codepoint codepoint = 0x10000 + (((first_surrogate & 0x3FF) << 10) | (second_surrogate & 0x3FF));\n\n static uint8_t utf8[5] = {};\n codepoint_to_utf8((Codepoint)codepoint, utf8);\n return (char *)utf8;\n }\n\n default:\n break;\n }\n\n static char buffer[3] = \"\\\\x\";\n buffer[1] = chr;\n\n return buffer;\n}\n\nstatic inline unsigned int scan_uint(Scanner &scan, int base)\n{\n assert(base >= 2 && base <= 16);\n\n unsigned int v = 0;\n while (scan.current_is(Strings::LOWERCASE_XDIGITS, base))\n {\n v *= base;\n v += scan.current() - '0';\n scan.foreward();\n }\n\n return v;\n}\n\nstatic inline int scan_int(Scanner &scan, int base)\n{\n assert(base >= 2 && base <= 16);\n\n int sign = 1;\n\n if (scan.current_is(\"-\"))\n {\n sign = -1;\n }\n\n scan.skip(\"+-\");\n\n int digits = 0;\n\n while (scan.current_is(Strings::LOWERCASE_XDIGITS, base))\n {\n digits *= base;\n digits += scan.current() - '0';\n scan.foreward();\n }\n\n return digits * sign;\n}\n\n#ifndef __KERNEL__\n\nstatic inline double scan_float(Scanner &scan)\n{\n int ipart = scan_int(scan, 10);\n\n double fpart = 0;\n\n if (scan.skip('.'))\n {\n double multiplier = 0.1;\n\n while (scan.current_is(Strings::DIGITS))\n {\n fpart += multiplier * (scan.current() - '0');\n multiplier *= 0.1;\n scan.foreward();\n }\n }\n\n int exp = 0;\n\n if (scan.current_is(\"eE\"))\n {\n scan.foreward();\n exp = scan_int(scan, 10);\n }\n\n return (ipart + fpart) * pow(10, exp);\n}\n\n#endif\n\nstatic inline void scan_skip_utf8bom(Scanner &scan)\n{\n scan.skip_word(\"\\xEF\\xBB\\xBF\");\n}\n" }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 13.333333015441895, "blob_id": "4bb6f68ba69d22445d7308cc2ce688a9f8d8f75e", "content_id": "89e219334cab509629a5960811d4478ac50e82db", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 43, "license_type": "permissive", "max_line_length": 24, "num_lines": 3, "path": "/libraries/libterminal/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += TERMINAL\n\nTERMINAL_NAME = terminal\n" }, { "alpha_fraction": 0.7071428298950195, "alphanum_fraction": 0.7071428298950195, "avg_line_length": 22.3125, "blob_id": "54d3fb17e10a3c4848de3232a98728af0940125f", "content_id": "0ad13340ed762dda0323ebbdcb383743ebee4031", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1120, "license_type": "permissive", "max_line_length": 79, "num_lines": 48, "path": "/libraries/libsystem/io/Connection.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <assert.h>\n#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Connection.h>\n#include <libsystem/io/Socket.h>\n\nstruct Connection\n{\n Handle handle;\n struct Socket *socket;\n};\n\nConnection *connection_create(Socket *socket, Handle handle)\n{\n Connection *connection = __create(Connection);\n\n connection->handle = handle;\n connection->socket = socket;\n\n socket_did_connection_open(socket, connection);\n\n return connection;\n}\n\nvoid connection_close(Connection *connection)\n{\n assert(connection != nullptr);\n\n socket_did_connection_close(connection->socket, connection);\n\n connection->socket = nullptr;\n __plug_handle_close(HANDLE(connection));\n}\n\nsize_t connection_send(Connection *connection, const void *buffer, size_t size)\n{\n assert(connection != nullptr);\n assert(buffer != nullptr);\n\n return __plug_handle_write(HANDLE(connection), buffer, size);\n}\n\nsize_t connection_receive(Connection *connection, void *buffer, size_t size)\n{\n assert(connection != nullptr);\n assert(buffer != nullptr);\n\n return __plug_handle_read(HANDLE(connection), buffer, size);\n}\n" }, { "alpha_fraction": 0.7297297120094299, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 13.800000190734863, "blob_id": "437cc89cfd9c7fbb1d3e2ec3b2fbae1da3aab131", "content_id": "fd2464f6290a32228a8083ab66224857e9f6dbba", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 222, "license_type": "permissive", "max_line_length": 39, "num_lines": 15, "path": "/libraries/libterminal/Cell.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/unicode/Codepoint.h>\n#include <libterminal/Attributes.h>\n\nnamespace terminal\n{\nstruct Cell\n{\n Codepoint codepoint;\n Attributes attributes;\n bool dirty;\n};\n\n} // namespace terminal\n" }, { "alpha_fraction": 0.4816247522830963, "alphanum_fraction": 0.5938104391098022, "avg_line_length": 15.15625, "blob_id": "be9fb6348fcf1bb1f6f8dfe75c932431d4dbb018", "content_id": "572f33ec20c35085a1beb6ba37365a526ad8f429", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 517, "license_type": "permissive", "max_line_length": 35, "num_lines": 32, "path": "/archs/x86_64/kernel/Interrupts.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nstruct __packed InterruptStackFrame\n{\n uint64_t r15;\n uint64_t r14;\n uint64_t r13;\n uint64_t r12;\n uint64_t r11;\n uint64_t r10;\n uint64_t r9;\n uint64_t r8;\n uint64_t rbp;\n uint64_t rdi;\n uint64_t rsi;\n uint64_t rdx;\n uint64_t rcx;\n uint64_t rbx;\n uint64_t rax;\n\n uint64_t intno;\n uint64_t err;\n\n // the interrupt stackframe\n uint64_t rip;\n uint64_t cs;\n uint64_t rflags;\n uint64_t rsp;\n uint64_t ss;\n};\n" }, { "alpha_fraction": 0.6455122232437134, "alphanum_fraction": 0.648232102394104, "avg_line_length": 18.35087776184082, "blob_id": "0968d1c867fc916d93bf9334b28af216c43b341c", "content_id": "e39d2d25ba7090cfc2dd5d9ee0e2c69168f0101f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1103, "license_type": "permissive", "max_line_length": 50, "num_lines": 57, "path": "/apps/compositor/model/Wallpaper.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Bitmap.h>\n#include <libgraphic/Painter.h>\n\n#include <libsettings/Setting.h>\n#include <libsystem/eventloop/Invoker.h>\n\nnamespace compositor\n{\nclass Wallpaper\n{\nprivate:\n BitmapScaling _scaling = BitmapScaling::COVER;\n\n Vec2i _resolution = {};\n Color _background = Colors::BLACK;\n RefPtr<Bitmap> _orginal = nullptr;\n RefPtr<Bitmap> _scaled = nullptr;\n RefPtr<Bitmap> _acrylic = nullptr;\n\n OwnPtr<Settings::Setting> _setting_image;\n OwnPtr<Settings::Setting> _setting_color;\n OwnPtr<Settings::Setting> _setting_scaling;\n\n OwnPtr<Invoker> _render_invoker;\n\npublic:\n Callback<void()> on_change;\n\n Recti bound() { return {{}, _resolution}; }\n\n int width() { return _resolution.x(); }\n int height() { return _resolution.y(); }\n\n Bitmap &scaled()\n {\n return *_scaled;\n }\n\n Bitmap &acrylic()\n {\n return *_acrylic;\n }\n\n Wallpaper(Vec2i resolution);\n\n void render_scaled();\n\n void render_acrylic();\n\n void render();\n\n void change_resolution(Vec2i resolution);\n};\n\n} // namespace compositor\n" }, { "alpha_fraction": 0.4457831382751465, "alphanum_fraction": 0.5030120611190796, "avg_line_length": 25.559999465942383, "blob_id": "ad32ad53a6eed56036ed36750ecb6e1340557427", "content_id": "8912df485146468ee6c9bb11c807db6f56c1de46", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 664, "license_type": "permissive", "max_line_length": 59, "num_lines": 25, "path": "/archs/x86_64/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "CC:=x86_64-pc-skift-gcc\nCXX:=x86_64-pc-skift-g++\nLD:=x86_64-pc-skift-ld\nAR:=x86_64-pc-skift-ar\nAS:=nasm\nASFLAGS:=-f elf64\n\nKERNEL_CXXFLAGS += \\\n\t-z max-page-size=0x1000 \t \\\n\t-fno-pic \\\n\t-mno-sse \\\n\t-mno-sse2 \\\n\t-mno-mmx \\\n\t-mno-80387 \\\n\t-mno-red-zone \\\n\t-mcmodel=kernel \\\n\t-ffreestanding \\\n\t-fno-stack-protector \\\n\t-fno-omit-frame-pointer\n\nKERNEL_LDFLAGS += -z max-page-size=0x1000\n\nKERNEL_SOURCES += $(wildcard archs/x86/kernel/*.cpp)\n\nKERNEL_ASSEMBLY_SOURCES += $(wildcard archs/x86/kernel/*.s)\n" }, { "alpha_fraction": 0.5604575276374817, "alphanum_fraction": 0.5686274766921997, "avg_line_length": 16.02777862548828, "blob_id": "ac5df4e3df3ccec7a97051affee841c22cff32ae", "content_id": "58a0b35765b9453ef46e5bf0e0ed4773417a795c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 612, "license_type": "permissive", "max_line_length": 79, "num_lines": 36, "path": "/libraries/libsystem/io_new/Reader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/ResultOr.h>\n\n#include <libsystem/io_new/Seek.h>\n\nnamespace System\n{\n\nclass Reader\n{\npublic:\n virtual ResultOr<size_t> read(void *buffer, size_t size) = 0;\n\n virtual ResultOr<uint8_t> read_byte()\n {\n uint8_t byte = 0xfe;\n auto result = read(&byte, 1).result();\n\n if (result != SUCCESS)\n {\n return result;\n }\n else\n {\n return byte;\n }\n\n return result;\n };\n};\n\ntemplate <typename T>\nconcept SeekableReader = IsBaseOf<Reader, T>::value &&IsBaseOf<Seek, T>::value;\n\n} // namespace System" }, { "alpha_fraction": 0.5900900959968567, "alphanum_fraction": 0.6006006002426147, "avg_line_length": 23.629629135131836, "blob_id": "697cdbd9de3ba1ce7b5cd569baea81e78b5fb37e", "content_id": "f6ef0218d87d3b888b1aad33e6657ede87f7768f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 666, "license_type": "permissive", "max_line_length": 103, "num_lines": 27, "path": "/apps/utilities/mv.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/io/Filesystem.h>\n#include <libsystem/io/Stream.h>\n\nint main(int argc, char **argv)\n{\n if (argc == 1)\n {\n stream_format(err_stream, \"%s: missing file operand\\n\", argv[0]);\n return PROCESS_FAILURE;\n }\n\n if (argc == 2)\n {\n stream_format(err_stream, \"%s: missing destination file operand after '%s'\", argv[0], argv[1]);\n return PROCESS_FAILURE;\n }\n\n Result result = filesystem_rename(argv[1], argv[2]);\n\n if (result != SUCCESS)\n {\n stream_format(err_stream, \"Failed to move file: %s\", get_result_description(result));\n return PROCESS_FAILURE;\n }\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.5543199181556702, "alphanum_fraction": 0.556030809879303, "avg_line_length": 19.491228103637695, "blob_id": "13fb8443fb1e3df8c883fedb5515be0bcd87114a", "content_id": "b5ee231711c59a9d25c3e8399524e01a25815ea6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1169, "license_type": "permissive", "max_line_length": 69, "num_lines": 57, "path": "/libraries/libsystem/io/Handle.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Stream.h>\n\nint __handle_printf_error(Handle *handle, const char *fmt, ...)\n{\n va_list va;\n va_start(va, fmt);\n\n int result = stream_vprintf(err_stream, fmt, va);\n\n va_end(va);\n\n stream_format(err_stream, \": %s\\n\", handle_error_string(handle));\n\n return result;\n}\n\nResult handle_poll(\n Handle **handles,\n PollEvent *events,\n size_t count,\n Handle **selected,\n PollEvent *selected_events,\n Timeout timeout)\n{\n int *handles_index = (int *)calloc(count, sizeof(int));\n\n for (size_t i = 0; i < count; i++)\n {\n handles_index[i] = handles[i]->id;\n }\n\n int selected_index = HANDLE_INVALID_ID;\n\n HandleSet handleset = (HandleSet){handles_index, events, count};\n\n Result result = __plug_handle_poll(\n &handleset,\n &selected_index,\n selected_events,\n timeout);\n\n free(handles_index);\n\n if (result == SUCCESS)\n {\n for (size_t i = 0; i < count; i++)\n {\n if (handles[i]->id == selected_index)\n {\n *selected = handles[i];\n }\n }\n }\n\n return result;\n}\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5681818127632141, "avg_line_length": 16.600000381469727, "blob_id": "4e5c50d9efa6e58b416ded16f7924529bb2a5f9a", "content_id": "34eee615d5f85524cb5405bbaca9058911eca186", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 352, "license_type": "permissive", "max_line_length": 58, "num_lines": 20, "path": "/apps/layout-viewer/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Application.h>\n#include <libwidget/Markup.h>\n\nint main(int argc, char **argv)\n{\n if (argc >= 2)\n {\n Application::initialize(argc, argv);\n\n Window *window = window_create_from_file(argv[1]);\n\n window->show();\n\n return Application::run();\n }\n else\n {\n return PROCESS_FAILURE;\n }\n}\n" }, { "alpha_fraction": 0.5944815874099731, "alphanum_fraction": 0.6045150756835938, "avg_line_length": 23.91666603088379, "blob_id": "a0486b954d4c77416f4e29c995f250bed47d9607", "content_id": "461c93e1178887c89df558d809f0617ae83aef43", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1196, "license_type": "permissive", "max_line_length": 106, "num_lines": 48, "path": "/apps/utilities/play.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"kernel/drivers/AC97.h\"\n#include <libsystem/io/File.h>\n#include <libsystem/io/Filesystem.h>\n#include <libsystem/io/Stream.h>\n#include <libutils/Path.h>\nint main(int argc, char **argv)\n{\n if (argc == 1)\n {\n stream_format(err_stream, \"%s: Missing Audio file operand\\n\", argv[0]);\n return PROCESS_FAILURE;\n }\n __cleanup(stream_cleanup) Stream *streamin = stream_open(argv[1], OPEN_READ);\n\n if (handle_has_error(streamin))\n {\n return handle_get_error(streamin);\n }\n\n __cleanup(stream_cleanup) Stream *streamout = stream_open(\"/Devices/sound\", OPEN_WRITE | OPEN_CREATE);\n\n if (handle_has_error(streamout))\n {\n return handle_get_error(streamout);\n }\n\n size_t read;\n char buffer[2 * AC97_BDL_BUFFER_LEN];\n\n while ((read = stream_read(streamin, &buffer, 2 * AC97_BDL_BUFFER_LEN)) != 0)\n {\n if (handle_has_error(streamin))\n {\n return handle_get_error(streamin);\n }\n\n stream_write(streamout, buffer, read);\n\n if (handle_has_error(streamout))\n {\n return handle_get_error(streamout);\n }\n }\n\n printf(\"Finish Playing\");\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6102620363235474, "alphanum_fraction": 0.6179039478302002, "avg_line_length": 21.604938507080078, "blob_id": "93cd05da982ebe4e39ba6a0c63bcec9e0e2e6f81", "content_id": "cd2dc34fd1e7f9604bbdd08967bfdcebc020c68d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1832, "license_type": "permissive", "max_line_length": 90, "num_lines": 81, "path": "/libraries/libc/skift/Time.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/core/Plugs.h>\n#include <skift/Time.h>\n\nTimeStamp timestamp_now()\n{\n return __plug_system_get_time();\n}\n\nTime timestamp_to_time(TimeStamp timestamp)\n{\n return (Time){\n .second = (int)(timestamp % 60),\n .minute = (int)((timestamp / SECONDS_PER_MINUTE) % 60),\n .hour = (int)((timestamp / SECONDS_PER_HOURS) % 24),\n };\n}\n\nDate timestamp_to_date(TimeStamp timestamp)\n{\n Date date = {};\n\n int days = timestamp / SECONDS_PER_DAY;\n\n date.year = EPOCH_YEAR;\n while (days - DAYS_PER_YEAR[IS_LEAP_YEAR(date.year)] > 0)\n {\n days -= DAYS_PER_YEAR[IS_LEAP_YEAR(date.year)];\n date.year++;\n }\n\n date.month = 0;\n while (days - DAYS_PER_MONTH[IS_LEAP_YEAR(date.year)][date.month] > 0)\n {\n days -= DAYS_PER_MONTH[IS_LEAP_YEAR(date.year)][date.month];\n date.month++;\n }\n\n date.month++;\n\n date.day = days + 1;\n\n return date;\n}\n\nDateTime timestamp_to_datetime(TimeStamp timestamp)\n{\n DateTime datetime = {};\n\n datetime.time = timestamp_to_time(timestamp);\n datetime.date = timestamp_to_date(timestamp);\n\n return datetime;\n}\n\nTimeStamp datetime_to_timestamp(DateTime datetime)\n{\n TimeStamp timestamp = 0;\n\n for (int year = EPOCH_YEAR; year < datetime.year; year++)\n {\n timestamp += DAYS_PER_YEAR[IS_LEAP_YEAR(year)] * SECONDS_PER_DAY;\n }\n\n for (int month = 0; month < datetime.month - 1; month++)\n {\n timestamp += DAYS_PER_MONTH[IS_LEAP_YEAR(datetime.year)][month] * SECONDS_PER_DAY;\n }\n\n timestamp += (datetime.day - 1) * SECONDS_PER_DAY;\n\n timestamp += datetime.hour * SECONDS_PER_HOURS;\n timestamp += datetime.minute * SECONDS_PER_MINUTE;\n timestamp += datetime.second;\n\n return timestamp;\n}\n\nDateTime datetime_now()\n{\n return timestamp_to_datetime(timestamp_now());\n}\n" }, { "alpha_fraction": 0.7789473533630371, "alphanum_fraction": 0.7789473533630371, "avg_line_length": 18, "blob_id": "92ee92cf727b68b1768049783e7423c00c6e0199", "content_id": "566a936792fc08d37a22a02f06a3caf155d3c6c2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 95, "license_type": "permissive", "max_line_length": 41, "num_lines": 5, "path": "/archs/x86_32/kernel/ACPI.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"kernel/handover/Handover.h\"\n\nvoid acpi_initialize(Handover *handover);\n" }, { "alpha_fraction": 0.5863125920295715, "alphanum_fraction": 0.5898876190185547, "avg_line_length": 29.123077392578125, "blob_id": "0dbc11b0bc8083d2ddab1d18352fdc522f742300", "content_id": "d7248fbd26af2fee0d32fdde0f86b30a33f8ee7f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1958, "license_type": "permissive", "max_line_length": 107, "num_lines": 65, "path": "/apps/about/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/BuildInfo.h>\n\n#include <libwidget/Application.h>\n#include <libwidget/Button.h>\n#include <libwidget/Image.h>\n#include <libwidget/Label.h>\n#include <libwidget/Markup.h>\n#include <libwidget/TextEditor.h>\n#include <libwidget/TitleBar.h>\n\nstatic auto logo_based_on_color_scheme()\n{\n auto path = theme_is_dark() ? \"/Applications/about/logo-white.png\"\n : \"/Applications/about/logo-black.png\";\n\n return Bitmap::load_from_or_placeholder(path);\n}\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n Window *window = window_create_from_file(\"/Applications/about/about.markup\");\n\n window->with_widget<Image>(\"system-image\", [&](auto image) {\n image->change_bitmap(logo_based_on_color_scheme());\n });\n\n window->with_widget<Label>(\"version-label\", [&](auto label) {\n label->text(__BUILD_VERSION__);\n });\n\n window->with_widget<Label>(\"commit-label\", [&](auto label) {\n label->text(__BUILD_GITREF__ \"/\" __BUILD_CONFIG__);\n });\n\n window->with_widget<Button>(\"license-button\", [&](auto button) {\n button->on(Event::ACTION, [window](auto) {\n auto license_window = new Window(WINDOW_NONE);\n license_window->title(\"License\");\n license_window->size({570, 416});\n license_window->root()->layout(VFLOW(0));\n\n new TitleBar(license_window->root());\n\n auto field = new TextEditor(license_window->root(), TextModel::from_file(\"/Files/license.md\"));\n field->flags(Widget::FILL);\n field->readonly(true);\n field->font(Font::get(\"mono\").take_value());\n field->focus();\n\n license_window->show();\n });\n });\n\n window->with_widget<Button>(\"ok-button\", [&](auto button) {\n button->on(Event::ACTION, [window](auto) {\n window->hide();\n });\n });\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 41, "blob_id": "dc589cdc591f8d677655869ef74ea6ff6f746f8d", "content_id": "24dc3a11ac6c7ca0908be64ca52afe2d824eaeaf", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 42, "license_type": "permissive", "max_line_length": 41, "num_lines": 1, "path": "/kernel/drivers/VirtioNetwork.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"kernel/drivers/VirtioGraphic.h\"\n" }, { "alpha_fraction": 0.6205533742904663, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 23.119047164916992, "blob_id": "3a43d51595da8dfb80dd9bcc41119d404295d858", "content_id": "9bd2da032bfe91a3295cdc1ce1fa603fc5193408", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1012, "license_type": "permissive", "max_line_length": 69, "num_lines": 42, "path": "/apps/panel/widgets/RessourceMonitor.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <abi/Syscalls.h>\n#include <skift/Environment.h>\n\n#include <libsystem/eventloop/Timer.h>\n#include <libwidget/Graph.h>\n#include <libwidget/Label.h>\n\n#include \"panel/widgets/RessourceMonitor.h\"\n\nnamespace panel\n{\n\nRessourceMonitor::RessourceMonitor(Widget *parent)\n : Button(parent, Button::TEXT)\n{\n layout(VGRID(1));\n insets(0);\n\n auto ram_graph = new Graph(this, 50, Colors::ROYALBLUE);\n new Label(ram_graph, \"RAM\", Anchor::CENTER);\n\n auto cpu_graph = new Graph(this, 50, Colors::SEAGREEN);\n new Label(cpu_graph, \"CPU\", Anchor::CENTER);\n\n _ram_timer = own<Timer>(500, [ram_graph]() {\n SystemStatus status{};\n hj_system_status(&status);\n\n ram_graph->record(status.used_ram / (float)status.total_ram);\n });\n\n _cpu_timer = own<Timer>(100, [cpu_graph]() {\n SystemStatus status{};\n hj_system_status(&status);\n cpu_graph->record(status.cpu_usage / 100.0);\n });\n\n _ram_timer->start();\n _cpu_timer->start();\n}\n\n} // namespace panel" }, { "alpha_fraction": 0.6580796241760254, "alphanum_fraction": 0.6674473285675049, "avg_line_length": 21.526315689086914, "blob_id": "05adb46384b8b03dbf01fd1ed1303d11d2c28ba8", "content_id": "e33c93b2b56d032f7da64a71794f4a75e23a2caa", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 427, "license_type": "permissive", "max_line_length": 49, "num_lines": 19, "path": "/libraries/libc/endian.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#ifndef _ENDIAN_H\n#define _ENDIAN_H\n\n#ifdef __GNUC__\n# define BYTE_ORDER __BYTE_ORDER__\n# define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__\n# define BIG_ENDIAN __ORDER_BIG_ENDIAN__\n# define PDP_ENDIAN __ORDER_PDP_ENDIAN__\n#else\n# error \"Unsupported compiler\"\n#endif\n\n#if BYTE_ORDER == LITTLE_ENDIAN\n# define le16toh(x) (uint16_t)(x)\n#else\n# error \"Big endian support is missing here\"\n#endif\n\n#endif // _ENDIAN_H" }, { "alpha_fraction": 0.5468277931213379, "alphanum_fraction": 0.5498489141464233, "avg_line_length": 19.369230270385742, "blob_id": "65ed7f80039a0391bda254ab2bc695a1cf83756c", "content_id": "efcb7019e0de4e181585d1138d91c8548b67e027", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1324, "license_type": "permissive", "max_line_length": 86, "num_lines": 65, "path": "/apps/panel/widgets/SettingToggle.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsettings/Setting.h>\n#include <libwidget/Button.h>\n#include <libwidget/IconPanel.h>\n#include <libwidget/Label.h>\n\nnamespace panel\n{\n\nclass SettingToggle : public Button\n{\nprivate:\n String _name;\n RefPtr<Icon> _icon;\n OwnPtr<Settings::Setting> _setting;\n bool _enabled;\n\npublic:\n SettingToggle(Widget *parent, String name, RefPtr<Icon> icon, const char *setting)\n : Button(parent, Button::TEXT),\n _name(name),\n _icon(icon)\n {\n _setting = own<Settings::Setting>(setting, [this](auto &value) {\n _enabled = value.as_bool();\n render();\n });\n\n render();\n }\n\n ~SettingToggle()\n {\n }\n\n void render()\n {\n clear_children();\n\n auto icon = new IconPanel(this, _icon);\n icon->insets(Insetsi(0, 0, 0, 4));\n\n auto label = new Label(this, _name);\n\n if (_enabled)\n {\n icon->color(THEME_FOREGROUND, icon->color(THEME_ACCENT));\n label->color(THEME_FOREGROUND, icon->color(THEME_ACCENT));\n }\n }\n\n void event(Event *event) override\n {\n if (event->type == Event::ACTION)\n {\n _setting->write(!_enabled);\n event->accepted = true;\n }\n\n Button::event(event);\n }\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 23.75, "blob_id": "51102605ac619e0fa9e71333c85c9644db008702", "content_id": "b9a11f37734f4d36dee199fa9c463c5a3e45e1d0", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 99, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/apps/task-manager/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += TASK_MANAGER\n\nTASK_MANAGER_NAME = task-manager\nTASK_MANAGER_LIBS = widget settings graphic\n" }, { "alpha_fraction": 0.6658823490142822, "alphanum_fraction": 0.6705882549285889, "avg_line_length": 13.655172348022461, "blob_id": "c33f7da04e6c57bc997786fcf448cb09bc355bae", "content_id": "583a5b7c2d5ee53120888d9f9c475fc679b346e1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 425, "license_type": "permissive", "max_line_length": 55, "num_lines": 29, "path": "/apps/neko/states/Wandering.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Random.h>\n\n#include \"neko/model/Behavior.h\"\n\nnamespace neko\n{\n\nclass Wandering : public Behavior\n{\nprivate:\n Random _random;\n Vec2f _destination;\n int _timer;\n\n Vec2f pick_destination();\n\npublic:\n const char *name() override { return \"Wandering\"; }\n\n Wandering();\n\n void update(Neko &neko) override;\n\n Animation animation(Neko &neko) override;\n};\n\n} // namespace neko\n" }, { "alpha_fraction": 0.7157894968986511, "alphanum_fraction": 0.7157894968986511, "avg_line_length": 18, "blob_id": "56bb2431954e04e5fa05bf1de9048d9ae9a5d1d6", "content_id": "b29b113e02d84f12e1b9d10fb40f1ef04c0b2796", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 95, "license_type": "permissive", "max_line_length": 49, "num_lines": 5, "path": "/libraries/libc/cxx/cxx.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nextern \"C\" void __cxa_finalize(void *dso_handle);\n" }, { "alpha_fraction": 0.6268174648284912, "alphanum_fraction": 0.6284329295158386, "avg_line_length": 18.967741012573242, "blob_id": "7e12f1cc50fdff0ad58793204914314c1b13786a", "content_id": "cbd60f71938e2a718670637445b3d083c130d5d1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 619, "license_type": "permissive", "max_line_length": 72, "num_lines": 31, "path": "/libraries/libwidget/Label.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n#include <libwidget/Label.h>\n#include <libwidget/Window.h>\n#include <string.h>\n\nLabel::Label(Widget *parent, String text)\n : Label(parent, text, Anchor::LEFT)\n{\n}\n\nLabel::Label(Widget *parent, String text, Anchor anchor)\n : Widget(parent)\n{\n _text = text;\n _anchor = anchor;\n}\n\nvoid Label::paint(Painter &painter, const Recti &)\n{\n painter.draw_string_within(\n *font(),\n _text.cstring(),\n content(),\n _anchor,\n color(THEME_FOREGROUND));\n}\n\nVec2i Label::size()\n{\n return {font()->mesure_with_fulllineheight(_text.cstring()).size()};\n}\n" }, { "alpha_fraction": 0.6582278609275818, "alphanum_fraction": 0.7088607549667358, "avg_line_length": 10.285714149475098, "blob_id": "9a29541c06ed7a9c5f9a71da6d929ff192eb350f", "content_id": "2f972cab45d1aace792fde376f0f1dcff6c116f5", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 158, "license_type": "permissive", "max_line_length": 33, "num_lines": 14, "path": "/archs/x86_32/kernel/Power.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nnamespace x86\n{\n\nvoid reboot_8042();\n\nvoid reboot_triple_fault();\n\nvoid shutdown_virtual_machines();\n\nvoid shutdown_acpi();\n\n} // namespace x86\n" }, { "alpha_fraction": 0.7524271607398987, "alphanum_fraction": 0.7524271607398987, "avg_line_length": 22, "blob_id": "cc10a7b6792d1c235162cfab43c4b3a7d987353d", "content_id": "2dfe613b6b07db45b8a0687be35ebb9460bb00e2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 206, "license_type": "permissive", "max_line_length": 70, "num_lines": 9, "path": "/kernel/tasking/Task-Launchpad.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Launchpad.h>\n\n#include \"kernel/tasking/Task.h\"\n\nResult task_launch(Task *parent_task, Launchpad *launchpad, int *pid);\n\nResult task_exec(Task *parent_task, Launchpad *launchpad);" }, { "alpha_fraction": 0.6679292917251587, "alphanum_fraction": 0.6679292917251587, "avg_line_length": 19.30769157409668, "blob_id": "9edfb9c3d531cc283dd9b40ae4cd26b8b2fbf502", "content_id": "a9e6f4f5a8f2cb1fa8204c47806c19faa69ddaa4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 792, "license_type": "permissive", "max_line_length": 66, "num_lines": 39, "path": "/libraries/libutils/Move.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Traits.h>\n\nusing nullptr_t = decltype(nullptr);\n\ntemplate <typename T>\nconstexpr typename RemoveReference<T>::Type &&move(T &&arg)\n{\n return static_cast<typename RemoveReference<T>::Type &&>(arg);\n}\n\ntemplate <class T>\nconstexpr T &&forward(typename RemoveReference<T>::Type &param)\n{\n return static_cast<T &&>(param);\n}\n\ntemplate <class T>\nconstexpr T &&forward(typename RemoveReference<T>::Type &&param)\n{\n return static_cast<T &&>(param);\n}\n\ntemplate <typename T>\nvoid swap(T &left, T &right)\n{\n T tmp = move(left);\n left = move(right);\n right = move(tmp);\n}\n\ntemplate <typename T, typename U = T>\nconstexpr T exchange_and_return_initial_value(T &slot, U &&value)\n{\n T old = move(slot);\n slot = forward<U>(value);\n return old;\n}\n" }, { "alpha_fraction": 0.5765765905380249, "alphanum_fraction": 0.6096096038818359, "avg_line_length": 25.639999389648438, "blob_id": "32ea877316bca926fef81704f9866546b344adae", "content_id": "445ee94d502b260a51755332a1498bf696efd592", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 666, "license_type": "permissive", "max_line_length": 147, "num_lines": 25, "path": "/apps/utilities/netctl.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/Stream.h>\n#include <stdio.h>\n#include <string.h>\n\nint main(int argc, char **argv)\n{\n __unused(argc);\n __unused(argv);\n\n Stream *network_device = stream_open(NETWORK_DEVICE_PATH, OPEN_READ | OPEN_WRITE);\n\n if (argc == 2 && strcmp(argv[1], \"-i\") == 0)\n {\n IOCallNetworkSateAgs state = {};\n\n stream_call(network_device, IOCALL_NETWORK_GET_STATE, &state);\n\n printf(\"MAC: %02x:%02x:%02x:%02x:%02x:%02x\\n\",\n state.mac_address[0], state.mac_address[1], state.mac_address[2], state.mac_address[3], state.mac_address[4], state.mac_address[5]);\n }\n\n stream_close(network_device);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 15.833333015441895, "blob_id": "2fe1da8a9796a896363d0f2b2a48f1c441a58ed3", "content_id": "9b205e5d54d1ab692476d75851484ca20bdafec6", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 102, "license_type": "permissive", "max_line_length": 37, "num_lines": 6, "path": "/libraries/libsystem/system/System.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <libsystem/core/Plugs.h>\n\nTick system_get_ticks()\n{\n return __plug_system_get_ticks();\n}\n" }, { "alpha_fraction": 0.79347825050354, "alphanum_fraction": 0.79347825050354, "avg_line_length": 22, "blob_id": "36c2fd4b0dde5d42b3c580ef615fc34dae8935e7", "content_id": "f6ffc6dc94b03213de419556bf0ebe3c56b85c24", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 92, "license_type": "permissive", "max_line_length": 48, "num_lines": 4, "path": "/apps/terminal/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += TERMINAL\n\nTERMINAL_NAME = terminal\nTERMINAL_LIBS = terminal widget settings graphic\n" }, { "alpha_fraction": 0.40414905548095703, "alphanum_fraction": 0.4099116325378418, "avg_line_length": 43.11864471435547, "blob_id": "3c3f37eae74a36cbc8738030e92bf7bc5582e3b1", "content_id": "2cbf1ed32402cc29120eefcd45d0c3c78206f16b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2603, "license_type": "permissive", "max_line_length": 133, "num_lines": 59, "path": "/kernel/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "/* _ _ _ _____ ____ _____ */\n/* | | | | | | ____| _ \\_ _| */\n/* | |_| |_ | | _| | |_) || | */\n/* | _ | |_| | |___| _ < | | */\n/* |_| |_|\\___/|_____|_| \\_\\|_| */\n/* */\n\n#include <assert.h>\n#include <libsystem/Logger.h>\n\n#include \"kernel/devices/Devices.h\"\n#include \"kernel/devices/Driver.h\"\n#include \"kernel/filesystem/DevicesFileSystem.h\"\n#include \"kernel/graphics/Graphics.h\"\n#include \"kernel/interrupts/Interupts.h\"\n#include \"kernel/modules/Modules.h\"\n#include \"kernel/node/DevicesInfo.h\"\n#include \"kernel/node/ProcessInfo.h\"\n#include \"kernel/scheduling/Scheduler.h\"\n#include \"kernel/storage/Partitions.h\"\n#include \"kernel/system/System.h\"\n#include \"kernel/tasking/Tasking.h\"\n#include \"kernel/tasking/Userspace.h\"\n\nstatic void splash_screen()\n{\n stream_format(log_stream, \"\\n\");\n stream_format(log_stream, \" _ _ _ _____ ____ _____ \\n\");\n stream_format(log_stream, \" | | | | | | ____| _ \\\\_ _| \\n\");\n stream_format(log_stream, \" | |_| |_ | | _| | |_) || | \\n\");\n stream_format(log_stream, \" | _ | |_| | |___| _ < | | \\n\");\n stream_format(log_stream, \" |_| |_|\\\\___/|_____|_| \\\\_\\\\|_| \\n\");\n stream_format(log_stream, \" \\n\");\n stream_format(log_stream, \"\\u001b[34;1m--------------------------------------------------------------------------------\\e[0m\\n\");\n stream_format(log_stream, \" Copyright (c) 2018-2021 The skiftOS contributors \\n\");\n stream_format(log_stream, \"\\n\");\n}\n\nvoid system_main(Handover *handover)\n{\n splash_screen();\n system_initialize();\n memory_initialize(handover);\n\n scheduler_initialize();\n tasking_initialize();\n interrupts_initialize();\n modules_initialize(handover);\n driver_initialize();\n device_initialize();\n partitions_initialize();\n process_info_initialize();\n device_info_initialize();\n devices_filesystem_initialize();\n graphic_initialize(handover);\n userspace_initialize();\n\n ASSERT_NOT_REACHED();\n}\n" }, { "alpha_fraction": 0.6257668733596802, "alphanum_fraction": 0.6319018602371216, "avg_line_length": 24.46875, "blob_id": "b9cd922ffb4769dee5d60bc8b303ec593b67ea46", "content_id": "2c840e9138a5ec243ef67fc6d31fce33e1c4915c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 815, "license_type": "permissive", "max_line_length": 64, "num_lines": 32, "path": "/archs/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "CRTS= \\\n\t$(BUILD_DIRECTORY_LIBS)/crt0.o \\\n\t$(BUILD_DIRECTORY_LIBS)/crti.o \\\n\t$(BUILD_DIRECTORY_LIBS)/crtn.o\n\n-include archs/$(CONFIG_ARCH)/.build.mk\n\n$(BUILD_DIRECTORY_LIBS)/crt0.o: archs/$(CONFIG_ARCH)/crts/crt0.s\n\t$(DIRECTORY_GUARD)\n\t@echo [AS] $^\n\t@$(AS) $(ASFLAGS) -o $@ $^\n\n$(BUILD_DIRECTORY_LIBS)/crti.o: archs/$(CONFIG_ARCH)/crts/crt0.s\n\t$(DIRECTORY_GUARD)\n\t@echo [AS] $^\n\t@$(AS) $(ASFLAGS) -o $@ $^\n\n$(BUILD_DIRECTORY_LIBS)/crtn.o: archs/$(CONFIG_ARCH)/crts/crt0.s\n\t$(DIRECTORY_GUARD)\n\t@echo [AS] $^\n\t@$(AS) $(ASFLAGS) -o $@ $^\n\nKERNEL_SOURCES += \\\n\t$(wildcard archs/$(CONFIG_ARCH)/kernel/*.cpp) \\\n\t$(wildcard archs/$(CONFIG_ARCH)/kernel/*/*.cpp)\n\nKERNEL_ASSEMBLY_SOURCES += \\\n\t$(wildcard archs/$(CONFIG_ARCH)/kernel/*.s) \\\n\t$(wildcard archs/$(CONFIG_ARCH)/kernel/*/*.s)\n\nlist-src:\n\t@echo $(KERNEL_SOURCES)\n" }, { "alpha_fraction": 0.622535228729248, "alphanum_fraction": 0.6422535181045532, "avg_line_length": 19.941177368164062, "blob_id": "0b56c5f1c99c46eb80019555b50a7aa371ee35b3", "content_id": "b08bf97b8bffc41ac55e841f8d9d96a6947655fe", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 355, "license_type": "permissive", "max_line_length": 60, "num_lines": 17, "path": "/libraries/libsystem/io/Reader.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/Reader.h>\n#include <libsystem/io/Writer.h>\n\n#define COPY_CHUNK_SIZE 4096\n\nvoid Reader::copy_to(Writer &writer)\n{\n assert(position() == 0);\n\n uint8_t copy_chunk[COPY_CHUNK_SIZE];\n size_t chunk_size = 0;\n\n while ((chunk_size = read(copy_chunk, COPY_CHUNK_SIZE)))\n {\n writer.write(copy_chunk, chunk_size);\n }\n}" }, { "alpha_fraction": 0.7195122241973877, "alphanum_fraction": 0.7195122241973877, "avg_line_length": 10.714285850524902, "blob_id": "bb0c45b566a585659ee52deb0f983f52a3702c93", "content_id": "3421ee002f6462c65bce1742c353cca852f21825", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 164, "license_type": "permissive", "max_line_length": 39, "num_lines": 14, "path": "/apps/panel/windows/DateAndTimeWindow.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Window.h>\n\nnamespace panel\n{\n\nclass DateAndTimeWindow : public Window\n{\npublic:\n DateAndTimeWindow();\n};\n\n} // namespace panel\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6703296899795532, "avg_line_length": 16.0625, "blob_id": "9d241f7e49d669c6ce8d2e7c235a0450733338da", "content_id": "4489d3b4d4133208c0bc701ea7464b8210cc0ad5", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 273, "license_type": "permissive", "max_line_length": 61, "num_lines": 16, "path": "/libraries/libwidget/Panel.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nclass Panel : public Widget\n{\nprivate:\n int _border_radius = 0;\n\npublic:\n void border_radius(int value) { _border_radius = value; }\n\n Panel(Widget *parent);\n\n void paint(Painter &painter, const Recti &) override;\n};\n" }, { "alpha_fraction": 0.598918080329895, "alphanum_fraction": 0.599690854549408, "avg_line_length": 15.602563858032227, "blob_id": "e61ae1d6d323a309c17c502097da1d4c899108df", "content_id": "6d51c28512302bf3294ff4cbffb70e528074fc6a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1294, "license_type": "permissive", "max_line_length": 61, "num_lines": 78, "path": "/libraries/libsystem/io_new/File.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io_new/File.h>\n\nnamespace System\n{\n\nFile::File(const char *path, OpenFlag flags)\n : _handle(path, flags | OPEN_STREAM),\n _path{Path::parse(path)}\n{\n}\n\nFile::File(String path, OpenFlag flags)\n : _handle(path, flags | OPEN_STREAM),\n _path{Path::parse(path)}\n{\n}\n\nFile::File(Path &path, OpenFlag flags)\n : _handle{path.string(), flags | OPEN_STREAM},\n _path{path}\n{\n}\n\nFile::File(System::Handle &&handle)\n : _handle{move(handle)}\n{\n}\n\nResultOr<size_t> File::read(void *buffer, size_t size)\n{\n return _handle.read(buffer, size);\n}\n\nResultOr<size_t> File::write(const void *buffer, size_t size)\n{\n return _handle.write(buffer, size);\n}\n\nResultOr<size_t> File::seek(size_t pos, Whence whence)\n{\n auto seek_result = _handle.seek(pos, whence);\n\n if (seek_result)\n {\n return (size_t)*seek_result;\n }\n else\n {\n return seek_result.result();\n }\n}\n\nResultOr<size_t> File::tell()\n{\n // FIXME: sketchy cast\n return (size_t)_handle.tell().value();\n}\n\nResultOr<size_t> File::length()\n{\n auto result_or_stat = _handle.stat();\n\n if (result_or_stat)\n {\n return result_or_stat->size;\n }\n else\n {\n return 0;\n }\n}\n\nbool File::exist()\n{\n return _handle.valid();\n}\n\n} // namespace System" }, { "alpha_fraction": 0.6492718458175659, "alphanum_fraction": 0.6650485396385193, "avg_line_length": 23.235294342041016, "blob_id": "b7a28705e35443bb50ab56c8d58d23c08d737982", "content_id": "316c05975c1cc9ba241289c1cbc9835fa9d594dd", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 824, "license_type": "permissive", "max_line_length": 71, "num_lines": 34, "path": "/apps/settings/windows/MainWindow.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Button.h>\n#include <libwidget/Panel.h>\n#include <libwidget/TitleBar.h>\n\n#include \"settings/pages/Home.h\"\n#include \"settings/windows/MainWindow.h\"\n\nnamespace Settings\n{\n\nMainWindow::MainWindow() : Window(WINDOW_RESIZABLE)\n{\n title(\"Settings\");\n icon(Icon::get(\"cog\"));\n size({700, 500});\n\n root()->layout(VFLOW(0));\n\n new TitleBar(root());\n\n auto navigation_bar = new Panel(root());\n navigation_bar->layout(HFLOW(4));\n navigation_bar->insets(4);\n navigation_bar->max_height(38);\n navigation_bar->min_height(38);\n\n new Button(navigation_bar, Button::TEXT, Icon::get(\"arrow-left\"));\n new Button(navigation_bar, Button::TEXT, Icon::get(\"arrow-right\"));\n new Button(navigation_bar, Button::TEXT, Icon::get(\"home\"));\n\n new HomePage(root());\n}\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.39194387197494507, "alphanum_fraction": 0.44817832112312317, "avg_line_length": 18.17136573791504, "blob_id": "16ef2aa2a63f41ef21735899ee7c6dd8f917d115", "content_id": "29917903b188cb06520fe9bc0b64c8374fd3f0d9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9089, "license_type": "permissive", "max_line_length": 73, "num_lines": 461, "path": "/libraries/libutils/unicode/Codepoint.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\ntypedef uint32_t Codepoint;\n\ninline bool codepoint_is_digit(Codepoint codepoint)\n{\n return (codepoint >= U'0' && codepoint <= U'9');\n}\n\ninline bool codepoint_is_alpha(Codepoint codepoint)\n{\n return (codepoint >= U'a' && codepoint <= U'z') ||\n (codepoint >= U'A' && codepoint <= U'Z');\n}\n\ninline int codepoint_numeric_value(Codepoint codepoint)\n{\n if (codepoint_is_digit(codepoint))\n {\n return codepoint - U'0';\n }\n else\n {\n return 0;\n }\n}\n\ninline int utf8_to_codepoint(const uint8_t *buffer, Codepoint *codepoint)\n{\n if ((buffer[0] & 0xf8) == 0xf0)\n {\n *codepoint = ((0x07 & buffer[0]) << 18) |\n ((0x3f & buffer[1]) << 12) |\n ((0x3f & buffer[2]) << 6) |\n ((0x3f & buffer[3]));\n\n return 4;\n }\n else if ((buffer[0] & 0xf0) == 0xe0)\n {\n *codepoint = ((0x0f & buffer[0]) << 12) |\n ((0x3f & buffer[1]) << 6) |\n ((0x3f & buffer[2]));\n\n return 3;\n }\n else if ((buffer[0] & 0xe0) == 0xc0)\n {\n *codepoint = ((0x1f & buffer[0]) << 6) |\n ((0x3f & buffer[1]));\n\n return 2;\n }\n else\n {\n *codepoint = buffer[0];\n\n return 1;\n }\n\n return 0;\n}\n\ninline int codepoint_to_utf8(Codepoint codepoint, uint8_t *buffer)\n{\n if (codepoint <= 0x7F)\n {\n buffer[0] = (uint8_t)codepoint;\n buffer[1] = 0;\n\n return 1;\n }\n else if (codepoint <= 0x07FF)\n {\n buffer[0] = (uint8_t)(((codepoint >> 6) & 0x1F) | 0xC0);\n buffer[1] = (uint8_t)(((codepoint >> 0) & 0x3F) | 0x80);\n buffer[2] = 0;\n\n return 2;\n }\n else if (codepoint <= 0xFFFF)\n {\n buffer[0] = (uint8_t)(((codepoint >> 12) & 0x0F) | 0xE0);\n buffer[1] = (uint8_t)(((codepoint >> 6) & 0x3F) | 0x80);\n buffer[2] = (uint8_t)(((codepoint >> 0) & 0x3F) | 0x80);\n buffer[3] = 0;\n\n return 3;\n }\n else if (codepoint <= 0x10FFFF)\n {\n buffer[0] = (uint8_t)(((codepoint >> 18) & 0x07) | 0xF0);\n buffer[1] = (uint8_t)(((codepoint >> 12) & 0x3F) | 0x80);\n buffer[2] = (uint8_t)(((codepoint >> 6) & 0x3F) | 0x80);\n buffer[3] = (uint8_t)(((codepoint >> 0) & 0x3F) | 0x80);\n buffer[4] = 0;\n\n return 4;\n }\n else\n {\n buffer[0] = (uint8_t)0xEF;\n buffer[1] = (uint8_t)0xBF;\n buffer[2] = (uint8_t)0xBD;\n buffer[3] = 0;\n\n return 0;\n }\n}\n\ninline char codepoint_to_cp437(Codepoint codepoint)\n{\n if (codepoint >= U'\\x20' && codepoint < U'\\x7f')\n {\n return (char)codepoint;\n }\n\n switch (codepoint)\n {\n case U'☺':\n return 0x1;\n case U'☻':\n return 0x2;\n case U'♥':\n return 0x3;\n case U'♦':\n return 0x4;\n case U'♣':\n return 0x5;\n case U'♠':\n return 0x6;\n case U'•':\n return 0x7;\n case U'◘':\n return 0x8;\n case U'○':\n return 0x9;\n case U'◙':\n return 0xa;\n case U'♂':\n return 0xb;\n case U'♀':\n return 0xc;\n case U'♪':\n return 0xd;\n case U'♫':\n return 0xe;\n case U'☼':\n return 0xf;\n case U'►':\n return 0x10;\n case U'◄':\n return 0x11;\n case U'↕':\n return 0x12;\n case U'‼':\n return 0x13;\n case U'¶':\n return 0x14;\n case U'§':\n return 0x15;\n case U'▬':\n return 0x16;\n case U'↨':\n return 0x17;\n case U'↑':\n return 0x18;\n case U'↓':\n return 0x19;\n case U'→':\n return 0x1a;\n case U'←':\n return 0x1b;\n case U'∟':\n return 0x1c;\n case U'↔':\n return 0x1d;\n case U'▲':\n return 0x1e;\n case U'▼':\n return 0x1f;\n case U'⌂':\n return 0x7f;\n case U'Ç':\n return 0x80;\n case U'ü':\n return 0x81;\n case U'é':\n return 0x82;\n case U'â':\n return 0x83;\n case U'ä':\n return 0x84;\n case U'à':\n return 0x85;\n case U'å':\n return 0x86;\n case U'ç':\n return 0x87;\n case U'ê':\n return 0x88;\n case U'ë':\n return 0x89;\n case U'è':\n return 0x8a;\n case U'ï':\n return 0x8b;\n case U'î':\n return 0x8c;\n case U'ì':\n return 0x8d;\n case U'Ä':\n return 0x8e;\n case U'Å':\n return 0x8f;\n case U'É':\n return 0x90;\n case U'æ':\n return 0x91;\n case U'Æ':\n return 0x92;\n case U'ô':\n return 0x93;\n case U'ö':\n return 0x94;\n case U'ò':\n return 0x95;\n case U'û':\n return 0x96;\n case U'ù':\n return 0x97;\n case U'ÿ':\n return 0x98;\n case U'Ö':\n return 0x99;\n case U'Ü':\n return 0x9a;\n case U'¢':\n return 0x9b;\n case U'£':\n return 0x9c;\n case U'¥':\n return 0x9d;\n case U'₧':\n return 0x9e;\n case U'ƒ':\n return 0x9f;\n case U'á':\n return 0xa0;\n case U'í':\n return 0xa1;\n case U'ó':\n return 0xa2;\n case U'ú':\n return 0xa3;\n case U'ñ':\n return 0xa4;\n case U'Ñ':\n return 0xa5;\n case U'ª':\n return 0xa6;\n case U'º':\n return 0xa7;\n case U'¿':\n return 0xa8;\n case U'⌐':\n return 0xa9;\n case U'¬':\n return 0xaa;\n case U'½':\n return 0xab;\n case U'¼':\n return 0xac;\n case U'¡':\n return 0xad;\n case U'«':\n return 0xae;\n case U'»':\n return 0xaf;\n case U'░':\n return 0xb0;\n case U'▒':\n return 0xb1;\n case U'▓':\n return 0xb2;\n case U'│':\n return 0xb3;\n case U'┤':\n return 0xb4;\n case U'╡':\n return 0xb5;\n case U'╢':\n return 0xb6;\n case U'╖':\n return 0xb7;\n case U'╕':\n return 0xb8;\n case U'╣':\n return 0xb9;\n case U'║':\n return 0xba;\n case U'╗':\n return 0xbb;\n case U'╝':\n return 0xbc;\n case U'╜':\n return 0xbd;\n case U'╛':\n return 0xbe;\n case U'┐':\n return 0xbf;\n case U'└':\n return 0xc0;\n case U'┴':\n return 0xc1;\n case U'┬':\n return 0xc2;\n case U'├':\n return 0xc3;\n case U'─':\n return 0xc4;\n case U'┼':\n return 0xc5;\n case U'╞':\n return 0xc6;\n case U'╟':\n return 0xc7;\n case U'╚':\n return 0xc8;\n case U'╔':\n return 0xc9;\n case U'╩':\n return 0xca;\n case U'╦':\n return 0xcb;\n case U'╠':\n return 0xcc;\n case U'═':\n return 0xcd;\n case U'╬':\n return 0xce;\n case U'╧':\n return 0xcf;\n case U'╨':\n return 0xd0;\n case U'╤':\n return 0xd1;\n case U'╥':\n return 0xd2;\n case U'╙':\n return 0xd3;\n case U'╘':\n return 0xd4;\n case U'╒':\n return 0xd5;\n case U'╓':\n return 0xd6;\n case U'╫':\n return 0xd7;\n case U'╪':\n return 0xd8;\n case U'┘':\n return 0xd9;\n case U'┌':\n return 0xda;\n case U'█':\n return 0xdb;\n case U'▄':\n return 0xdc;\n case U'▌':\n return 0xdd;\n case U'▐':\n return 0xde;\n case U'▀':\n return 0xdf;\n case U'α':\n return 0xe0;\n case U'ß':\n return 0xe1;\n case U'Γ':\n return 0xe2;\n case U'π':\n return 0xe3;\n case U'Σ':\n return 0xe4;\n case U'σ':\n return 0xe5;\n case U'µ':\n return 0xe6;\n case U'τ':\n return 0xe7;\n case U'Φ':\n return 0xe8;\n case U'Θ':\n return 0xe9;\n case U'Ω':\n return 0xea;\n case U'δ':\n return 0xeb;\n case U'∞':\n return 0xec;\n case U'φ':\n return 0xed;\n case U'ε':\n return 0xee;\n case U'∩':\n return 0xef;\n case U'≡':\n return 0xf0;\n case U'±':\n return 0xf1;\n case U'≥':\n return 0xf2;\n case U'≤':\n return 0xf3;\n case U'⌠':\n return 0xf4;\n case U'⌡':\n return 0xf5;\n case U'÷':\n return 0xf6;\n case U'≈':\n return 0xf7;\n case U'°':\n return 0xf8;\n case U'∙':\n return 0xf9;\n case U'·':\n return 0xfa;\n case U'√':\n return 0xfb;\n case U'ⁿ':\n return 0xfc;\n case U'²':\n return 0xfd;\n case U'■':\n return 0xfe;\n\n default:\n return '?';\n }\n}\n\ntemplate <typename T>\ninline void codepoint_foreach(const uint8_t *buffer, T callback)\n{\n Codepoint codepoint = 0;\n\n size_t size = utf8_to_codepoint(buffer, &codepoint);\n buffer += size;\n\n while (size && codepoint != 0)\n {\n callback(codepoint);\n\n size = utf8_to_codepoint(buffer, &codepoint);\n buffer += size;\n }\n}\n" }, { "alpha_fraction": 0.6894409656524658, "alphanum_fraction": 0.6894409656524658, "avg_line_length": 17.399999618530273, "blob_id": "474eeba0b60d20794ba19a85eca24bb96216a008", "content_id": "7c8d8ea4f1e97f48eea387aa36d8bee47297845c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 644, "license_type": "permissive", "max_line_length": 68, "num_lines": 35, "path": "/libraries/libsystem/plugs/__plugs.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "\n#include <assert.h>\n#include <skift/Lock.h>\n\n#include <libsystem/Logger.h>\n#include <libsystem/core/Plugs.h>\n#include <libsystem/io/Stream.h>\n#include <libsystem/process/Process.h>\n#include <libsystem/system/Memory.h>\n\nstatic Lock _logger_lock{\"logger_lock\"};\n\nvoid __plug_initialize()\n{\n}\n\nvoid __plug_uninitialize(int exit_code)\n{\n __unused(exit_code);\n}\n\nvoid __plug_logger_lock()\n{\n _logger_lock.acquire(SOURCE_LOCATION);\n}\n\nvoid __plug_logger_unlock()\n{\n _logger_lock.release(SOURCE_LOCATION);\n}\n\nvoid __no_return __plug_logger_fatal()\n{\n stream_format(err_stream, \"Fatal error occurred (see logs)!\\n\");\n process_abort();\n}" }, { "alpha_fraction": 0.7909091114997864, "alphanum_fraction": 0.7909091114997864, "avg_line_length": 26.5, "blob_id": "7e338be2f84ba4512b8fc80c0fa4b6b4eff112cd", "content_id": "5f86da4b3379683c4d6be8952134cbecab743ce3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 110, "license_type": "permissive", "max_line_length": 54, "num_lines": 4, "path": "/apps/file-manager/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += FILE_MANAGER\n\nFILE_MANAGER_NAME = file-manager\nFILE_MANAGER_LIBS = filepicker widget settings graphic\n" }, { "alpha_fraction": 0.5397121906280518, "alphanum_fraction": 0.5438235998153687, "avg_line_length": 25.35960578918457, "blob_id": "d15bd659c458df777bfc6bdea6a42ba41728a0a0", "content_id": "579c2962c407d4281096b8b0e5dee11a91c9e7ae", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5351, "license_type": "permissive", "max_line_length": 112, "num_lines": 203, "path": "/apps/shell/Eval.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <skift/Environment.h>\n#include <stdio.h>\n\n#include <libsystem/Result.h>\n#include <libsystem/io/File.h>\n#include <libsystem/io/Filesystem.h>\n#include <libsystem/io/Pipe.h>\n#include <libsystem/io/Stream.h>\n#include <libsystem/process/Launchpad.h>\n#include <libsystem/process/Process.h>\n#include <libutils/Path.h>\n\n#include \"shell/Shell.h\"\n\nbool find_command_path(char *buffer, const char *command)\n{\n if (command[0] == '/' ||\n command[0] == '.')\n {\n snprintf(buffer, PATH_LENGTH, \"%s\", command);\n\n File file{buffer};\n return file.exist();\n }\n else\n {\n snprintf(buffer, PATH_LENGTH, \"/Applications/%s/%s\", command, command);\n\n File file{buffer};\n if (file.exist())\n {\n return true;\n }\n\n auto &path = environment().get(\"POSIX\").get(\"PATH\");\n\n for (size_t i = 0; i < path.length(); i++)\n {\n snprintf(buffer, PATH_LENGTH, \"%s/%s\", path.get(i).as_string().cstring(), command);\n\n File file{buffer};\n if (file.exist())\n {\n return true;\n }\n }\n }\n\n return false;\n}\n\nResult shell_exec(ShellCommand *command, Stream *instream, Stream *outstream, int *pid)\n{\n char executable[PATH_LENGTH];\n if (!find_command_path(executable, command->command))\n {\n *pid = -1;\n return ERR_NO_SUCH_FILE_OR_DIRECTORY;\n }\n\n Launchpad *launchpad = launchpad_create(command->command, executable);\n\n list_foreach(char, arg, command->arguments)\n {\n launchpad_argument(launchpad, arg);\n }\n\n launchpad_handle(launchpad, HANDLE(instream), 0);\n launchpad_handle(launchpad, HANDLE(outstream), 1);\n\n return launchpad_launch(launchpad, pid);\n}\n\nint shell_eval(ShellNode *node, Stream *instream, Stream *outstream)\n{\n switch (node->type)\n {\n case SHELL_NODE_COMMAND:\n {\n ShellCommand *command = (ShellCommand *)node;\n\n ShellBuiltinCallback builtin = shell_get_builtin(command->command);\n\n if (builtin)\n {\n // list_count(command->arguments) + 1 for argv[0] which is the command name.\n char **argv = (char **)calloc(command->arguments->count() + 1, sizeof(argv));\n argv[0] = command->command;\n int argc = 1;\n\n list_foreach(char, arg, command->arguments)\n {\n argv[argc] = arg;\n argc++;\n }\n\n int result = builtin(argc, (const char **)argv);\n free(argv);\n\n return result;\n }\n\n int pid;\n Result result = shell_exec(command, instream, outstream, &pid);\n auto path = Path::parse(command->command, Path::PARENT_SHORTHAND);\n\n if (result == SUCCESS)\n {\n int command_result = -1;\n process_wait(pid, &command_result);\n return command_result;\n }\n else if (filesystem_exist(path.string().cstring(), FILE_TYPE_DIRECTORY))\n {\n process_set_directory(path.string().cstring());\n\n return PROCESS_SUCCESS;\n }\n else\n {\n printf(\"%s: Command not found! \\e[90m%s\\e[m\\n\", command->command, result_to_string(result));\n return PROCESS_FAILURE;\n }\n }\n break;\n\n case SHELL_NODE_PIPELINE:\n {\n ShellPipeline *pipeline = (ShellPipeline *)node;\n\n List *pipes = list_create();\n\n for (int i = 0; i < pipeline->commands->count() - 1; i++)\n {\n list_pushback(pipes, pipe_create());\n }\n\n int *processes = (int *)calloc(pipeline->commands->count(), sizeof(int));\n\n for (int i = 0; i < pipeline->commands->count(); i++)\n {\n ShellCommand *command = nullptr;\n list_peekat(pipeline->commands, i, (void **)&command);\n assert(command);\n\n Stream *command_stdin = instream;\n Stream *command_stdout = outstream;\n\n if (i > 0)\n {\n Pipe *input_pipe;\n assert(list_peekat(pipes, i - 1, (void **)&input_pipe));\n command_stdin = input_pipe->out;\n }\n\n if (i < pipeline->commands->count() - 1)\n {\n Pipe *output_pipe;\n assert(list_peekat(pipes, i, (void **)&output_pipe));\n command_stdout = output_pipe->in;\n }\n\n shell_exec(command, command_stdin, command_stdout, &processes[i]);\n }\n\n list_destroy_with_callback(pipes, (ListDestroyElementCallback)pipe_destroy);\n\n int exit_value;\n\n for (int i = 0; i < pipeline->commands->count(); i++)\n {\n process_wait(processes[i], &exit_value);\n }\n\n free(processes);\n\n return exit_value;\n }\n break;\n\n case SHELL_NODE_REDIRECT:\n {\n ShellRedirect *redirect = (ShellRedirect *)node;\n\n __cleanup(stream_cleanup) Stream *stream = stream_open(redirect->destination, OPEN_WRITE | OPEN_CREATE);\n\n if (handle_has_error(stream))\n {\n handle_printf_error(stream, \"Failed to open '%s'\", redirect->destination);\n return PROCESS_FAILURE;\n }\n\n return shell_eval(redirect->command, instream, stream);\n }\n break;\n\n default:\n break;\n }\n\n return -1;\n}\n" }, { "alpha_fraction": 0.6971830725669861, "alphanum_fraction": 0.7253521084785461, "avg_line_length": 27.600000381469727, "blob_id": "9ce866ae59c605f7d32f1f034b78c691420ed05b", "content_id": "99cb1f02dd1e0d267d413be48da156fc821fb968", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 142, "license_type": "permissive", "max_line_length": 77, "num_lines": 5, "path": "/contribs/zlib/get-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\nVERSION = 1.2.9\n\necho \"Getting ZLIB version: $VERSION\"\ngit clone --depth 1 --branch v$VERSION https://github.com/madler/zlib sources" }, { "alpha_fraction": 0.4190213680267334, "alphanum_fraction": 0.41971054673194885, "avg_line_length": 15.122221946716309, "blob_id": "7be4fa4e2393aa5063f25e7051807fd41c63b5ce", "content_id": "47132547c69bc3027f5e3aebe98e84766c7c9293", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1451, "license_type": "permissive", "max_line_length": 61, "num_lines": 90, "path": "/libraries/libutils/SliceStorage.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/RefCounted.h>\n#include <string.h>\n\nclass SliceStorage : public RefCounted<SliceStorage>\n{\nprivate:\n void *_data = nullptr;\n size_t _size = 0;\n bool _owned = false;\n\npublic:\n void *start()\n {\n return _data;\n }\n\n void *end()\n {\n return reinterpret_cast<char *>(_data) + _size;\n }\n\n const void *start() const\n {\n return _data;\n }\n\n const void *end() const\n {\n return reinterpret_cast<const char *>(_data) + _size;\n }\n\n size_t size()\n {\n return _size;\n }\n\n enum Mode\n {\n ADOPT,\n WRAP,\n COPY,\n };\n\n SliceStorage(size_t size)\n {\n _owned = true;\n _data = malloc(size);\n _size = size;\n }\n\n SliceStorage(Mode mode, void *data, size_t size)\n {\n if (mode == ADOPT)\n {\n _data = data;\n _size = size;\n _owned = true;\n }\n else if (mode == WRAP)\n {\n _data = data;\n _size = size;\n _owned = false;\n }\n else if (mode == COPY)\n {\n _data = malloc(size);\n memcpy(_data, data, size);\n _size = size;\n _owned = false;\n }\n }\n\n ~SliceStorage()\n {\n if (!_data)\n {\n return;\n }\n\n if (_owned)\n {\n free(_data);\n }\n\n _data = nullptr;\n }\n};\n" }, { "alpha_fraction": 0.6449771523475647, "alphanum_fraction": 0.6449771523475647, "avg_line_length": 25.545454025268555, "blob_id": "a54a53c4128fccb41b6c7f20c422093cc0067340", "content_id": "7f6a6cb9f1a3ff9a93454713b9ee38793882ca7c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 876, "license_type": "permissive", "max_line_length": 84, "num_lines": 33, "path": "/libraries/libsystem/Logger.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\nenum LogLevel\n{\n LOGGER_TRACE,\n LOGGER_DEBUG,\n LOGGER_INFO,\n LOGGER_WARN,\n LOGGER_ERROR,\n LOGGER_FATAL,\n};\n\nvoid logger_level(LogLevel log_level);\n\nvoid logger_colors(bool use_colors);\n\nvoid logger_quiet(bool quiet);\n\nvoid logger_log(LogLevel level, const char *file, int line, const char *fmt, ...);\n\n#define logger_trace(__args...) logger_log(LOGGER_TRACE, __FILE__, __LINE__, __args)\n\n#define logger_debug(__args...) logger_log(LOGGER_DEBUG, __FILE__, __LINE__, __args)\n\n#define logger_info(__args...) logger_log(LOGGER_INFO, __FILE__, __LINE__, __args)\n\n#define logger_warn(__args...) logger_log(LOGGER_WARN, __FILE__, __LINE__, __args)\n\n#define logger_error(__args...) logger_log(LOGGER_ERROR, __FILE__, __LINE__, __args)\n\n#define logger_fatal(__args...) logger_log(LOGGER_FATAL, __FILE__, __LINE__, __args)\n" }, { "alpha_fraction": 0.5838697552680969, "alphanum_fraction": 0.5876561999320984, "avg_line_length": 20.128000259399414, "blob_id": "00981ecc5dec311305b24f74800787c743e50ca7", "content_id": "a1d6912f28d64bb72f4b3a82f08ca4318ea6ec8a", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2641, "license_type": "permissive", "max_line_length": 111, "num_lines": 125, "path": "/libraries/libsystem/io/File.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/File.h>\n#include <libsystem/io/Stream.h>\n\nResult File::read_all(void **buffer, size_t *size)\n{\n __cleanup(stream_cleanup) Stream *stream = stream_open(_path.string().cstring(), OPEN_READ);\n\n if (handle_has_error(stream))\n {\n return handle_get_error(stream);\n }\n\n FileState state = {};\n stream_stat(stream, &state);\n\n if (handle_has_error(stream))\n {\n return handle_get_error(stream);\n }\n\n *buffer = malloc(state.size);\n *size = state.size;\n\n stream_read(stream, *buffer, state.size);\n\n if (handle_has_error(stream))\n {\n free(*buffer);\n return handle_get_error(stream);\n }\n\n return SUCCESS;\n}\n\nResultOr<Slice> File::read_all()\n{\n void *buff = nullptr;\n size_t size = 0;\n\n auto res = read_all(&buff, &size);\n\n if (res == SUCCESS)\n {\n return Slice{make<SliceStorage>(SliceStorage::ADOPT, buff, size)};\n }\n else\n {\n return res;\n }\n}\n\nResult File::write_all(const void *buffer, size_t size)\n{\n __cleanup(stream_cleanup) Stream *stream = stream_open(_path.string().cstring(), OPEN_WRITE | OPEN_CREATE);\n\n if (handle_has_error(stream))\n {\n return handle_get_error(stream);\n }\n\n size_t remaining = size;\n\n while (remaining)\n {\n remaining -= stream_write(stream, ((char *)buffer + (size - remaining)), size);\n\n if (handle_has_error(stream))\n {\n return handle_get_error(stream);\n }\n }\n\n return SUCCESS;\n}\n\nbool File::exist()\n{\n __cleanup(stream_cleanup) Stream *stream = stream_open(_path.string().cstring(), OPEN_READ);\n\n if (handle_has_error(stream))\n {\n return false;\n }\n\n FileState state = {};\n stream_stat(stream, &state);\n\n return state.type == FILE_TYPE_REGULAR;\n}\n\nResult File::copy(const char *destination)\n{\n __cleanup(stream_cleanup) Stream *streamin = stream_open(_path.string().cstring(), OPEN_READ);\n\n if (handle_has_error(streamin))\n {\n return handle_get_error(streamin);\n }\n\n __cleanup(stream_cleanup) Stream *streamout = stream_open(destination, OPEN_WRITE | OPEN_CREATE);\n\n if (handle_has_error(streamout))\n {\n return handle_get_error(streamout);\n }\n\n size_t read;\n char buffer[4096];\n while ((read = stream_read(streamin, &buffer, 4096)) != 0)\n {\n if (handle_has_error(streamin))\n {\n return handle_get_error(streamin);\n }\n\n stream_write(streamout, buffer, read);\n\n if (handle_has_error(streamout))\n {\n return handle_get_error(streamout);\n }\n }\n\n return SUCCESS;\n}\n" }, { "alpha_fraction": 0.5061770081520081, "alphanum_fraction": 0.5175156593322754, "avg_line_length": 24.256410598754883, "blob_id": "cc462fe66d74970cf6d10e9a6a97c85051cca3a5", "content_id": "e2dc01e64f9b5def234551444d996d48504e6353", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5909, "license_type": "permissive", "max_line_length": 88, "num_lines": 234, "path": "/apps/terminal/TerminalWidget.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n#include <libsystem/Logger.h>\n#include <libsystem/process/Launchpad.h>\n#include <libwidget/Event.h>\n#include <libwidget/Window.h>\n\n#include \"terminal/Common.h\"\n#include \"terminal/TerminalWidget.h\"\n\n#define TERMINAL_IO_BUFFER_SIZE 4096\n\nTerminalWidget::TerminalWidget(Widget *parent) : Widget(parent)\n{\n _terminal = own<terminal::Terminal>(80, 24);\n\n assert(stream_create_term(&_server_stream, &_client_stream) == SUCCESS);\n\n _server_notifier = own<Notifier>(HANDLE(_server_stream), POLL_READ, [this]() {\n handle_read();\n });\n\n _cursor_blink_timer = own<Timer>(250, [this]() {\n blink();\n\n int cx = _terminal->cursor().x;\n int cy = _terminal->cursor().y;\n\n should_repaint(cell_bound(cx, cy).offset(bound().position()));\n });\n\n _cursor_blink_timer->start();\n\n Launchpad *shell_launchpad = launchpad_create(\"shell\", \"/Applications/shell/shell\");\n launchpad_handle(shell_launchpad, HANDLE(_client_stream), 0);\n launchpad_handle(shell_launchpad, HANDLE(_client_stream), 1);\n launchpad_handle(shell_launchpad, HANDLE(_client_stream), 2);\n launchpad_launch(shell_launchpad, nullptr);\n}\n\nTerminalWidget::~TerminalWidget()\n{\n stream_close(_server_stream);\n stream_close(_client_stream);\n}\n\nvoid TerminalWidget::paint(Painter &painter, const Recti &dirty)\n{\n for (int y = 0; y < _terminal->height(); y++)\n {\n for (int x = 0; x < _terminal->width(); x++)\n {\n terminal::Cell cell = _terminal->cell_at(x, y);\n render_cell(painter, x, y, cell);\n _terminal->cell_undirty(x, y);\n }\n }\n\n int cx = _terminal->cursor().x;\n int cy = _terminal->cursor().y;\n\n if (cell_bound(cx, cy).colide_with(dirty))\n {\n terminal::Cell cell = _terminal->cell_at(cx, cy);\n\n if (window()->focused())\n {\n if (_cursor_blink)\n {\n render_cell(\n painter,\n cx,\n cy,\n cell.codepoint,\n terminal::BACKGROUND,\n terminal::FOREGROUND,\n terminal::Attributes::defaults());\n }\n else\n {\n render_cell(painter, cx, cy, cell);\n }\n }\n else\n {\n render_cell(painter, cx, cy, cell);\n painter.draw_rectangle(cell_bound(cx, cy), color(THEME_ANSI_CURSOR));\n }\n }\n}\n\nvoid TerminalWidget::event(Event *event)\n{\n auto send_sequence = [&](auto sequence) {\n stream_write(_server_stream, sequence, strlen(sequence));\n event->accepted = true;\n };\n\n if (event->type == Event::KEYBOARD_KEY_TYPED)\n {\n switch (event->keyboard.key)\n {\n case KEYBOARD_KEY_DELETE:\n send_sequence(\"\\e[3~\");\n break;\n\n case KEYBOARD_KEY_END:\n send_sequence(\"\\e[4~\");\n break;\n\n case KEYBOARD_KEY_F1:\n send_sequence(\"\\e[11~\");\n break;\n\n case KEYBOARD_KEY_F2:\n send_sequence(\"\\e[12~\");\n break;\n\n case KEYBOARD_KEY_F3:\n send_sequence(\"\\e[13~\");\n break;\n\n case KEYBOARD_KEY_F4:\n send_sequence(\"\\e[14~\");\n break;\n\n case KEYBOARD_KEY_F5:\n send_sequence(\"\\e[15~\");\n break;\n\n case KEYBOARD_KEY_F6:\n send_sequence(\"\\e[17~\");\n break;\n\n case KEYBOARD_KEY_F7:\n send_sequence(\"\\e[18~\");\n break;\n\n case KEYBOARD_KEY_F8:\n send_sequence(\"\\e[19~\");\n break;\n\n case KEYBOARD_KEY_F9:\n send_sequence(\"\\e[20~\");\n break;\n\n case KEYBOARD_KEY_F10:\n send_sequence(\"\\e[21~\");\n break;\n\n case KEYBOARD_KEY_F11:\n send_sequence(\"\\e[23~\");\n break;\n\n case KEYBOARD_KEY_F12:\n send_sequence(\"\\e[24~\");\n break;\n\n case KEYBOARD_KEY_HOME:\n send_sequence(\"\\e[1~\");\n break;\n\n case KEYBOARD_KEY_INSERT:\n send_sequence(\"\\e[2~\");\n break;\n\n case KEYBOARD_KEY_PGUP:\n send_sequence(\"\\e[5~\");\n break;\n\n case KEYBOARD_KEY_PGDOWN:\n send_sequence(\"\\e[6~\");\n break;\n\n case KEYBOARD_KEY_UP:\n send_sequence(\"\\e[A\");\n break;\n\n case KEYBOARD_KEY_DOWN:\n send_sequence(\"\\e[B\");\n break;\n\n case KEYBOARD_KEY_RIGHT:\n send_sequence(\"\\e[C\");\n break;\n\n case KEYBOARD_KEY_LEFT:\n send_sequence(\"\\e[D\");\n break;\n\n default:\n if (event->keyboard.codepoint != 0)\n {\n uint8_t buffer[5];\n int size = codepoint_to_utf8(event->keyboard.codepoint, buffer);\n stream_write(_server_stream, buffer, size);\n event->accepted = true;\n }\n break;\n }\n }\n}\n\nvoid TerminalWidget::do_layout()\n{\n int width = bound().width() / cell_size().x();\n int height = bound().height() / cell_size().y();\n\n width = MAX(width, 8);\n height = MAX(height, 8);\n\n if (_terminal->width() != width ||\n _terminal->height() != height)\n {\n _terminal->resize(width, height);\n\n IOCallTerminalSizeArgs args = {width, height};\n assert(stream_call(_server_stream, IOCALL_TERMINAL_SET_SIZE, &args) == SUCCESS);\n }\n}\n\nvoid TerminalWidget::handle_read()\n{\n char buffer[TERMINAL_IO_BUFFER_SIZE];\n size_t size = stream_read(_server_stream, buffer, TERMINAL_IO_BUFFER_SIZE);\n\n if (handle_has_error(_server_stream))\n {\n handle_printf_error(_server_stream, \"Terminal: read from server failed\");\n return;\n }\n\n _terminal->write(buffer, size);\n should_repaint();\n}" }, { "alpha_fraction": 0.6738241314888, "alphanum_fraction": 0.685071587562561, "avg_line_length": 30.580644607543945, "blob_id": "a13ea3f4798d8e9a6369e1e37ffb8685c62e831a", "content_id": "ed18ae2f44ae06ad12d9dcb8687b11eb02685fb2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 978, "license_type": "permissive", "max_line_length": 113, "num_lines": 31, "path": "/apps/panel/windows/QuickSettingsWindow.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libwidget/Screen.h>\n\n#include \"panel/widgets/SettingToggle.h\"\n#include \"panel/windows/PanelWindow.h\"\n#include \"panel/windows/QuickSettingsWindow.h\"\n\nnamespace panel\n{\n\nQuickSettingsWindow::QuickSettingsWindow()\n : Window(WINDOW_AUTO_CLOSE | WINDOW_ALWAYS_FOCUSED | WINDOW_ACRYLIC)\n{\n title(\"Panel\");\n bound(Screen::bound().take_right(WIDTH).shrinked({PanelWindow::HEIGHT, 0, 0, 0}).with_height(HEIGHT));\n type(WINDOW_TYPE_POPOVER);\n opacity(0.85);\n\n on(Event::DISPLAY_SIZE_CHANGED, [this](auto) {\n bound(Screen::bound().take_right(WIDTH).shrinked({PanelWindow::HEIGHT, 0, 0, 0}).with_height(HEIGHT));\n });\n\n root()->layout(VFLOW(4));\n root()->insets(6);\n\n new Label(root(), \"Quick settings\");\n\n new SettingToggle(root(), \"Show Wireframe\", Icon::get(\"duck\"), \"appearance:widgets.wireframe\");\n new SettingToggle(root(), \"Night Light\", Icon::get(\"moon-waning-crescent\"), \"appearance:night-light.enable\");\n}\n\n} // namespace panel" }, { "alpha_fraction": 0.6634146571159363, "alphanum_fraction": 0.6878048777580261, "avg_line_length": 11.8125, "blob_id": "5565a8c80369eee6910a3820d54c99aca81a9520", "content_id": "384d9bf6837bed31c1ea142818e1cdfbf45c23f3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 205, "license_type": "permissive", "max_line_length": 30, "num_lines": 16, "path": "/libraries/libgraphic/vector/BezierCurve.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libutils/Vec2.h>\n\nnamespace graphic\n{\n\nstruct BezierCurve\n{\n Vec2f start;\n Vec2f first_control_point;\n Vec2f second_contol_point;\n Vec2f end;\n};\n\n} // namespace graphic\n" }, { "alpha_fraction": 0.43112701177597046, "alphanum_fraction": 0.4669051766395569, "avg_line_length": 17.633333206176758, "blob_id": "18af977696b68b5e4c0c8568e25dcb215ef3cf6e", "content_id": "160647520758a5c625abefde85a75cfb469e6f0b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 559, "license_type": "permissive", "max_line_length": 67, "num_lines": 30, "path": "/libraries/libc/strings.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <ctype.h>\n#include <strings.h>\n\nint strcasecmp(const char *s1, const char *s2)\n{\n for (; tolower(*s1) == tolower(*s2) && *s1; s1++, s2++)\n {\n ;\n }\n return *(unsigned char *)s1 - *(unsigned char *)s2;\n}\n\nint strncasecmp(const char *s1, const char *s2, size_t n)\n{\n if (n == 0)\n {\n return 0;\n }\n\n while (n-- && tolower(*s1) == tolower(*s2))\n {\n if (!n || !*s1)\n {\n break;\n }\n s1++;\n s2++;\n }\n return (unsigned int)tolower(*s1) - (unsigned int)tolower(*s2);\n}\n" }, { "alpha_fraction": 0.6281800270080566, "alphanum_fraction": 0.6360078454017639, "avg_line_length": 16.620689392089844, "blob_id": "636012b744cd223441e31640ed6003d225ef37c3", "content_id": "b9e2888c91646197a436f613ff938201896612ad", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 511, "license_type": "permissive", "max_line_length": 38, "num_lines": 29, "path": "/libraries/libsystem/BuildInfo.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#ifndef __BUILD_ARCH__\n# define __BUILD_ARCH__ \"unknown\"\n#endif\n\n#ifndef __BUILD_CONFIG__\n# define __BUILD_CONFIG__ \"unknown\"\n#endif\n\n#ifndef __BUILD_SYSTEM__\n# define __BUILD_SYSTEM__ \"unknown\"\n#endif\n\n#ifndef __BUILD_TARGET__\n# define __BUILD_TARGET__ \"unknown\"\n#endif\n\n#ifndef __BUILD_GITREF__\n# define __BUILD_GITREF__ \"unknown\"\n#endif\n\n#ifndef __BUILD_UNAME__\n# define __BUILD_UNAME__ \"unknown\"\n#endif\n\n#ifndef __BUILD_VERSION__\n# define __BUILD_VERSION__ \"00.00\"\n#endif\n" }, { "alpha_fraction": 0.7209302186965942, "alphanum_fraction": 0.7209302186965942, "avg_line_length": 11.285714149475098, "blob_id": "00a1293ec9ddae2c7d5d059ccbfab5836b66e467", "content_id": "ad01484b80680abdb91a08c5d10c27396004aee9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 172, "license_type": "permissive", "max_line_length": 33, "num_lines": 14, "path": "/apps/settings/pages/Home.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Container.h>\n\nnamespace Settings\n{\n\nclass HomePage : public Container\n{\npublic:\n HomePage(Widget *parent);\n};\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.6372581124305725, "alphanum_fraction": 0.6756313443183899, "avg_line_length": 39.66666793823242, "blob_id": "734644b8a55dab0159451b9522c270503ed75806", "content_id": "c30b7a02b3259fddef914437c3b2eb5b72df8876", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3049, "license_type": "permissive", "max_line_length": 66, "num_lines": 75, "path": "/manual/readme.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "![Banner](header.png)\n\n<h2 align=\"center\">\n The skiftOS manual\n</h2>\n\n## 0. Meta\n\n - [Building](00-meta/building.md)\n - [Code Of Conduct](00-meta/code_of_conduct.md)\n - [Coding Style](00-meta/coding_style.md)\n - [Contributing](00-meta/contributing.md)\n - [Running In Virtual Box](00-meta/running_in_vbox.md)\n\n## 1. Utilities\n\n - [cat](10-utilities/cat.md)\n - [cd](10-utilities/cd.md)\n - [displayctl](10-utilities/displayctl.md)\n - [echo](10-utilities/echo.md)\n - [ls](10-utilities/ls.md)\n - [man](10-utilities/man.md)\n - [shell](10-utilities/shell.md)\n - [sysfetch](10-utilities/sysfetch.md)\n - [uptime](10-utilities/uptime.md)\n - [wallpaperctl](10-utilities/wallpaperctl.md)\n\n## 2. Syscalls\n\n - [`hj_create_pipe()`](20-syscalls/hj_create_pipe.md)\n - [`hj_create_term()`](20-syscalls/hj_create_term.md)\n - [`hj_filesystem_link()`](20-syscalls/hj_filesystem_link.md)\n - [`hj_filesystem_mkdir()`](20-syscalls/hj_filesystem_mkdir.md)\n - [`hj_filesystem_mkpipe()`](20-syscalls/hj_filesystem_mkpipe.md)\n - [`hj_filesystem_rename()`](20-syscalls/hj_filesystem_rename.md)\n - [`hj_filesystem_unlink()`](20-syscalls/hj_filesystem_unlink.md)\n - [`hj_handle_accept()`](20-syscalls/hj_handle_accept.md)\n - [`hj_handle_call()`](20-syscalls/hj_handle_call.md)\n - [`hj_handle_close()`](20-syscalls/hj_handle_close.md)\n - [`hj_handle_connect()`](20-syscalls/hj_handle_connect.md)\n - [`hj_handle_copy()`](20-syscalls/hj_handle_copy.md)\n - [`hj_handle_open()`](20-syscalls/hj_handle_open.md)\n - [`hj_handle_poll()`](20-syscalls/hj_handle_poll.md)\n - [`hj_handle_read()`](20-syscalls/hj_handle_read.md)\n - [`hj_handle_reopen()`](20-syscalls/hj_handle_reopen.md)\n - [`hj_handle_seek()`](20-syscalls/hj_handle_seek.md)\n - [`hj_handle_stat()`](20-syscalls/hj_handle_stat.md)\n - [`hj_handle_write()`](20-syscalls/hj_handle_write.md)\n - [`hj_memory_alloc()`](20-syscalls/hj_memory_alloc.md)\n - [`hj_memory_free()`](20-syscalls/hj_memory_free.md)\n - [`hj_memory_get_handle()`](20-syscalls/hj_memory_get_handle.md)\n - [`hj_memory_include()`](20-syscalls/hj_memory_include.md)\n - [`hj_memory_map()`](20-syscalls/hj_memory_map.md)\n - [`hj_process_cancel()`](20-syscalls/hj_process_cancel.md)\n - [`hj_process_clone()`](20-syscalls/hj_process_clone.md)\n - [`hj_process_exit()`](20-syscalls/hj_process_exit.md)\n - [`hj_process_launch()`](20-syscalls/hj_process_launch.md)\n - [`hj_process_name()`](20-syscalls/hj_process_name.md)\n - [`hj_process_sleep()`](20-syscalls/hj_process_sleep.md)\n - [`hj_process_this()`](20-syscalls/hj_process_this.md)\n - [`hj_process_wait()`](20-syscalls/hj_process_wait.md)\n - [`hj_system_info()`](20-syscalls/hj_system_info.md)\n - [`hj_system_reboot()`](20-syscalls/hj_system_reboot.md)\n - [`hj_system_shutdown()`](20-syscalls/hj_system_shutdown.md)\n - [`hj_system_status()`](20-syscalls/hj_system_status.md)\n - [`hj_system_ticks()`](20-syscalls/hj_system_ticks.md)\n - [`hj_system_time()`](20-syscalls/hj_system_time.md)\n\n## 3. Files\n\n - [manifest.json](30-files/manifest.md)\n\n## 4. Human Interface\n\n- [Guidelines](40-human-interface/guidelines.md)" }, { "alpha_fraction": 0.646170437335968, "alphanum_fraction": 0.6510248184204102, "avg_line_length": 25.126760482788086, "blob_id": "c1c6151832d44c63324c0743b11b4608e97939b0", "content_id": "6ad0811714a7d35caed3157a8cf9c1bcaa5f3341", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1854, "license_type": "permissive", "max_line_length": 100, "num_lines": 71, "path": "/apps/panel/windows/PanelWindow.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/process/Process.h>\n\n#include <libwidget/Container.h>\n#include <libwidget/Screen.h>\n#include <libwidget/Separator.h>\n#include <libwidget/Spacer.h>\n\n#include \"panel/widgets/DateAndTime.h\"\n#include \"panel/widgets/RessourceMonitor.h\"\n#include \"panel/widgets/UserAccount.h\"\n#include \"panel/windows/PanelWindow.h\"\n\nnamespace panel\n{\n\nPanelWindow::PanelWindow()\n : Window(WINDOW_BORDERLESS | WINDOW_ALWAYS_FOCUSED | WINDOW_ACRYLIC | WINDOW_NO_ROUNDED_CORNERS)\n{\n title(\"Panel\");\n type(WINDOW_TYPE_PANEL);\n bound(Screen::bound().take_top(HEIGHT));\n opacity(0.85);\n on(Event::DISPLAY_SIZE_CHANGED, [this](auto) {\n bound(Screen::bound().take_top(HEIGHT));\n });\n\n _menu = own<MenuWindow>();\n _datetime = own<DateAndTimeWindow>();\n _quicksetting = own<QuickSettingsWindow>();\n\n root()->layout(VFLOW(0));\n\n auto container = new Container(root());\n container->flags(Widget::FILL);\n container->layout(HFLOW(8));\n container->insets(Insetsi(4));\n\n new Separator(root());\n (new Separator(root()))->color(THEME_BORDER, Colors::BLACK.with_alpha(0.25));\n\n auto menu = new Button(container, Button::TEXT, Icon::get(\"menu\"), \"Applications\");\n menu->on(Event::ACTION, [this](auto) {\n _menu->show();\n });\n\n new Spacer(container);\n\n auto date_and_time = new DateAndTime(container);\n\n date_and_time->on(Event::ACTION, [this](auto) {\n _datetime->show();\n });\n\n new Spacer(container);\n\n new UserAccount(container);\n\n auto ressource_monitor = new RessourceMonitor(container);\n\n ressource_monitor->on(Event::ACTION, [](auto) {\n process_run(\"task-manager\", nullptr);\n });\n\n auto dots = new Button(container, Button::TEXT, Icon::get(\"dots\"));\n\n dots->on(Event::ACTION, [this](auto) {\n _quicksetting->show();\n });\n}\n\n} // namespace panel" }, { "alpha_fraction": 0.717131495475769, "alphanum_fraction": 0.7211155295372009, "avg_line_length": 18.30769157409668, "blob_id": "d6214ef9b5a7f51a3cc639faed6c772bce764ce1", "content_id": "709be4d6cdf735a3853084e15785afa92d05dd45", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 502, "license_type": "permissive", "max_line_length": 86, "num_lines": 26, "path": "/kernel/drivers/PCSpeaker.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"kernel/devices/Device.h\"\n#include \"kernel/devices/LegacyDevice.h\"\n#include \"kernel/drivers/PCSpeaker.h\"\n#include \"kernel/scheduling/Scheduler.h\"\n#include \"kernel/tasking/Task.h\"\n\nstruct Speaker\n{\n int length;\n int frequency;\n};\n\nclass PCSpeaker : public LegacyDevice\n{\nprivate:\n void note(int length, int freq);\n\npublic:\n PCSpeaker(DeviceAddress address);\n\n ~PCSpeaker();\n\n ResultOr<size_t> write(size64_t offset, const void *buffer, size_t size) override;\n};\n" }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.6448243260383606, "avg_line_length": 17.821428298950195, "blob_id": "e8117c1f84e66e79860816e17cb9a64306a80dce", "content_id": "217888f756e1ef098b2ee7ada537068781ef3f9c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1053, "license_type": "permissive", "max_line_length": 85, "num_lines": 56, "path": "/archs/x86_32/kernel/Power.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Logger.h>\n\n#include \"archs/Architectures.h\"\n#include \"archs/VirtualMemory.h\"\n\n#include \"archs/x86/kernel/IOPort.h\"\n#include \"archs/x86/kernel/x86.h\"\n#include \"archs/x86_32/kernel/ACPI.h\"\n#include \"archs/x86_32/kernel/Power.h\"\n\nnamespace x86\n{\n\nvoid reboot_8042()\n{\n logger_info(\"Trying to reboot using the 8042...\");\n\n uint8_t good = 0x02;\n\n while (good & 0x02)\n {\n good = in8(0x64);\n }\n\n out8(0x64, 0xFE);\n arch_halt();\n}\n\nvoid reboot_triple_fault()\n{\n logger_info(\"Trying to reboot by doing a triple fault...\");\n cli();\n arch_address_space_switch(0x0);\n *(uint32_t *)0x0 = 0xDEADDEAD;\n}\n\nvoid shutdown_virtual_machines()\n{\n logger_info(\"Maybe your are running a VM, trying to shutdown using io ports...\");\n\n // Bochs, and older versions of QEMU(than 2.0)\n out16(0xB004, 0x2000);\n\n // Newer versions of QEMU\n out16(0x604, 0x2000);\n\n // Virtualbox\n out16(0x4004, 0x3400);\n}\n\nvoid shutdown_acpi()\n{\n logger_info(\"Trying to shutdown using acpi...\");\n}\n\n} // namespace x86" }, { "alpha_fraction": 0.5825589895248413, "alphanum_fraction": 0.6190136075019836, "avg_line_length": 20.196969985961914, "blob_id": "d2f5e6cd2d9b615aa518de8f167b52111ee29407", "content_id": "0356772280c812c5c292e64f2e438c3e328072c4", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1399, "license_type": "permissive", "max_line_length": 59, "num_lines": 66, "path": "/archs/x86_32/kernel/Paging.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\n#include \"archs/Memory.h\"\n\n#define PAGE_DIRECTORY_INDEX(vaddr) ((vaddr) >> 22)\n#define PAGE_TABLE_INDEX(vaddr) (((vaddr) >> 12) & 0x03ff)\n\n#define PAGE_TABLE_ENTRY_COUNT 1024\n#define PAGE_DIRECTORY_ENTRY_COUNT 1024\n\nunion __packed PageTableEntry\n{\n struct __packed\n {\n bool Present : 1;\n bool Write : 1;\n bool User : 1;\n bool PageLevelWriteThrough : 1;\n bool PageLevelCacheDisable : 1;\n bool Accessed : 1;\n bool Dirty : 1;\n bool Pat : 1;\n uint32_t Ignored : 4;\n uint32_t PageFrameNumber : 20;\n };\n\n uint32_t as_uint;\n};\n\nstruct __packed PageTable\n{\n PageTableEntry entries[PAGE_TABLE_ENTRY_COUNT];\n};\n\nunion __packed PageDirectoryEntry\n{\n struct __packed\n {\n bool Present : 1;\n bool Write : 1;\n bool User : 1;\n bool PageLevelWriteThrough : 1;\n bool PageLevelCacheDisable : 1;\n bool Accessed : 1;\n bool Ignored1 : 1;\n bool LargePage : 1;\n uint32_t Ignored2 : 4;\n uint32_t PageFrameNumber : 20;\n };\n uint32_t as_uint;\n};\n\nstruct __packed PageDirectory\n{\n PageDirectoryEntry entries[PAGE_DIRECTORY_ENTRY_COUNT];\n};\n\nextern \"C\" void paging_enable();\n\nextern \"C\" void paging_disable();\n\nextern \"C\" void paging_load_directory(uintptr_t directory);\n\nextern \"C\" void paging_invalidate_tlb();\n" }, { "alpha_fraction": 0.5923970341682434, "alphanum_fraction": 0.6008448004722595, "avg_line_length": 29.223403930664062, "blob_id": "d226e93466ece9397cd3cb35fbc6afef8b5ee239", "content_id": "781f7ffbc4748f6a4aea6c5417d26d6575655cab", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2841, "license_type": "permissive", "max_line_length": 94, "num_lines": 94, "path": "/apps/widget-factory/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libfilepicker/FilePicker.h>\n#include <libwidget/Application.h>\n#include <libwidget/Container.h>\n#include <libwidget/Label.h>\n#include <libwidget/Panel.h>\n#include <libwidget/TextField.h>\n#include <libwidget/TitleBar.h>\n\nint main(int argc, char **argv)\n{\n Application::initialize(argc, argv);\n\n auto acrylic_window = own<Window>(WINDOW_ACRYLIC);\n acrylic_window->title(\"Acrylic!\");\n new TitleBar(acrylic_window->root());\n\n auto window = own<Window>(WINDOW_RESIZABLE);\n\n window->icon(Icon::get(\"widgets\"));\n window->title(\"Widget Factory\");\n window->size(Vec2i(500, 400));\n\n window->root()->layout(VFLOW(8));\n\n new TitleBar(window->root());\n\n Widget *panel_hflow = new Container(window->root());\n {\n panel_hflow->layout(HFLOW(8));\n\n auto p0 = new Panel(panel_hflow);\n p0->flags(Widget::FILL);\n\n auto p1 = new Panel(panel_hflow);\n p1->flags(Widget::FILL);\n\n auto button = new Button(panel_hflow, Button::TEXT, \"Hello, world!\");\n button->flags(Widget::FILL);\n\n auto p2 = new Panel(panel_hflow);\n p2->flags(Widget::FILL);\n\n auto p3 = new Panel(panel_hflow);\n p3->flags(Widget::FILL);\n }\n\n new Label(window->root(), \"Buttons\", Anchor::CENTER);\n Widget *buttons = new Container(window->root());\n {\n buttons->layout(HFLOW(8));\n buttons->insets(Insetsi(0, 8));\n\n new Button(buttons, Button::TEXT, \"BUTTON\");\n new Button(buttons, Button::OUTLINE, \"BUTTON\");\n new Button(buttons, Button::FILLED, \"BUTTON\");\n new Button(buttons, Button::TEXT, Icon::get(\"widgets\"), \"BUTTON\");\n new Button(buttons, Button::OUTLINE, Icon::get(\"widgets\"), \"BUTTON\");\n new Button(buttons, Button::FILLED, Icon::get(\"widgets\"), \"BUTTON\");\n }\n\n new Label(window->root(), \"Grid layout\", Anchor::CENTER);\n\n Widget *panel_grid = new Container(window->root());\n {\n panel_grid->layout(GRID(3, 3, 4, 4));\n panel_grid->flags(Widget::FILL);\n\n new Panel(panel_grid);\n new TextField(panel_grid, TextModel::empty());\n auto text_field = new TextField(panel_grid, TextModel::empty());\n text_field->focus();\n\n auto acrylic_button = new Button(panel_grid, Button::FILLED, \"Open acrylic window !\");\n acrylic_button->on(Event::ACTION, [&](auto) {\n acrylic_window->show();\n });\n\n new Button(panel_grid, Button::FILLED, \"Grid layout!\");\n\n auto dialog_button = new Button(panel_grid, Button::FILLED, \"Open dialog!\");\n dialog_button->on(Event::ACTION, [&](auto) {\n filepicker::Dialog picker{};\n picker.show();\n });\n\n new Panel(panel_grid);\n new Panel(panel_grid);\n new Panel(panel_grid);\n }\n\n window->show();\n\n return Application::run();\n}\n" }, { "alpha_fraction": 0.7661691308021545, "alphanum_fraction": 0.7661691308021545, "avg_line_length": 22.647058486938477, "blob_id": "861d621ee6f56e389fbebee84b7716c41415a38d", "content_id": "339a3dbdfc28d7e3ca9d7ab70f925f93bf2ae875", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 402, "license_type": "permissive", "max_line_length": 69, "num_lines": 17, "path": "/libraries/libsystem/io/Filesystem.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <abi/Filesystem.h>\n\n#include <libsystem/Result.h>\n\nResult filesystem_link(const char *oldpath, const char *newpath);\n\nResult filesystem_unlink(const char *path);\n\nResult filesystem_mkdir(const char *path);\n\nResult filesystem_mkpipe(const char *path);\n\nResult filesystem_rename(const char *old_path, const char *new_path);\n\nbool filesystem_exist(const char *path, FileType type);\n" }, { "alpha_fraction": 0.6314199566841125, "alphanum_fraction": 0.6480362415313721, "avg_line_length": 26.58333396911621, "blob_id": "a0b692d2c62eea4c5837d2bd3f7afc9e3274ab78", "content_id": "a1a8c8553bcc1593ce657de630c9393b56e82da8", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 662, "license_type": "permissive", "max_line_length": 85, "num_lines": 24, "path": "/libraries/libwidget/Placeholder.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n#include <libwidget/Placeholder.h>\n#include <libwidget/Window.h>\n#include <stdio.h>\n#include <string.h>\n\nPlaceholder::Placeholder(Widget *parent, String text)\n : Widget(parent), _alert_icon(Icon::get(\"alert\"))\n{\n _text = String::format(\"Cannot create an instance of \\\"{}\\\".\", text);\n}\n\nvoid Placeholder::paint(Painter &painter, const Recti &)\n{\n painter.draw_rectangle(bound(), Colors::RED);\n\n painter.blit(\n *_alert_icon,\n ICON_18PX,\n _alert_icon->bound(ICON_18PX).moved(Vec2i(8, 8)),\n Colors::RED);\n\n painter.draw_string(*font(), _text.cstring(), {32, 20}, color(THEME_FOREGROUND));\n}\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.692307710647583, "avg_line_length": 25.33333396911621, "blob_id": "99d994711d7e493678ea0472d92630cf3704d2de", "content_id": "88f5423f1280a08097b34c3f256b2ad6d194572c", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 78, "license_type": "permissive", "max_line_length": 43, "num_lines": 3, "path": "/vms/bochs.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": ".PHONY: run-bochs\nrun: $(BOOTDISK)\n\tbochs -q -f vms/.bochsrc -rc vms/.bochsini" }, { "alpha_fraction": 0.7464788556098938, "alphanum_fraction": 0.7464788556098938, "avg_line_length": 16.75, "blob_id": "c60718766db77a50f80c278b4fe93dba480afd9a", "content_id": "437bd02f97cf912f869ca05b434a4d1f5e0010ca", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 71, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/apps/paint/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += PAINT\n\nPAINT_NAME = paint\nPAINT_LIBS = widget settings graphic\n" }, { "alpha_fraction": 0.5323424935340881, "alphanum_fraction": 0.5362269878387451, "avg_line_length": 27.19523811340332, "blob_id": "31ea7e609725cbdd842b0b6d24ee6823d16b3cf2", "content_id": "a9e988bf67636c8e5fef6bd4b5f72fafe3836f48", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5921, "license_type": "permissive", "max_line_length": 134, "num_lines": 210, "path": "/apps/utilities/head.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/cmdline/CMDLine.h>\n#include <libsystem/io/Stream.h>\n#include <stdio.h>\n\n#define BUFFER_SIZE 1024\n\nstatic bool count_lines = true;\nstatic int count = 10;\nstatic bool quiet = false;\nstatic bool verbose = false;\nstatic bool zero_delimiter = false;\nstatic char delimiter = '\\n';\n\nvoid set_delimiter_zero(CommandLine *, CommandLineOption *);\nvoid set_character_mode(CommandLine *, CommandLineOption *);\nResult head(Stream *const, char *const);\n\nstatic const char *usages[] = {\n \"[OPTION]... NAME...\",\n nullptr,\n};\n\nstatic CommandLineOption options[] = {\n COMMANDLINE_OPT_HELP,\n COMMANDLINE_OPT_INT(\"bytes\", 'c', count,\n \"Print the first NUM bytes of each file; with the leading '-', print all but the last NUM bytes of each file\",\n set_character_mode),\n COMMANDLINE_OPT_INT(\"lines\", 'n', count,\n \"Print the first NUM bytes of each file; with the leading '-', print all but the last NUM bytes of each file\",\n COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"quiet\", 'q', quiet,\n \"Never print headers giving file names\",\n COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"verbose\", 'v', verbose,\n \"Always print headers giving file names\",\n COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"zero-terminated\", 'z', zero_delimiter,\n \"Line delimiter is NUL, not newline\",\n set_delimiter_zero),\n COMMANDLINE_OPT_END};\n\nstatic CommandLine cmdline = CMDLINE(\n usages,\n options,\n \"Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with\\\n a header giving the file name\\n\",\n \"If no filename provided read from input stream\\n\");\n\nint main(int argc, char **argv)\n{\n argc = cmdline_parse(&cmdline, argc, argv);\n\n if (count < 0)\n {\n /* TODO: print everthing but last COUNT lines when count is negative */\n stream_format(err_stream, \"%s\", get_result_description(ERR_FUNCTION_NOT_IMPLEMENTED));\n return PROCESS_FAILURE;\n }\n\n Result result;\n int process_status = PROCESS_SUCCESS;\n\n if (argc == 1)\n {\n count = 1;\n char input_stream_name[] = \"Standard Input\";\n\n stream_set_read_buffer_mode(in_stream, STREAM_BUFFERED_LINE);\n stream_set_write_buffer_mode(out_stream, STREAM_BUFFERED_NONE);\n result = head(in_stream, input_stream_name);\n if (result != SUCCESS)\n {\n stream_format(err_stream, \"%s: %s: %s\", argv[0], \"STDIN\", get_result_description(result));\n process_status = PROCESS_FAILURE;\n }\n\n return process_status;\n }\n\n if (argc > 2 && quiet == false)\n {\n verbose = true;\n }\n\n for (int i = 1; i < argc; i++)\n {\n __cleanup(stream_cleanup) Stream *file_stream = stream_open(argv[i], OPEN_READ);\n\n if (handle_has_error(file_stream))\n {\n stream_format(err_stream, \"%s: %s: %s\", argv[0], argv[i], get_result_description(handle_get_error(file_stream)));\n process_status = PROCESS_FAILURE;\n continue;\n }\n\n result = head(file_stream, argv[i]);\n if (argc > 2 && i != argc - 1)\n {\n printf(\"\\n\");\n }\n\n if (result != SUCCESS)\n {\n stream_format(err_stream, \"%s: %s: %s\", argv[0], argv[i], get_result_description(result));\n process_status = PROCESS_FAILURE;\n }\n }\n\n return process_status;\n}\n\nvoid set_delimiter_zero(CommandLine *cmdline, CommandLineOption *opt)\n{\n __unused(cmdline);\n __unused(opt);\n\n delimiter = '\\0';\n}\n\nvoid set_character_mode(CommandLine *cmdline, CommandLineOption *opt)\n{\n __unused(cmdline);\n __unused(opt);\n\n count_lines = false;\n}\n\nResult head(Stream *const input_stream, char *const stream_name)\n{\n char buffer[BUFFER_SIZE];\n\n size_t bytes_read;\n int counter = 0;\n\n if (verbose)\n {\n stream_format(out_stream, \"==> %s <==\\n\", stream_name);\n if (handle_has_error(out_stream))\n {\n return ERR_WRITE_STDOUT;\n }\n }\n\n // Character mode\n if (count_lines == false)\n {\n int full_reads = count / BUFFER_SIZE;\n size_t remainder = count % BUFFER_SIZE;\n\n while (counter < full_reads)\n {\n bytes_read = stream_read(input_stream, buffer, BUFFER_SIZE);\n if (bytes_read == 0)\n {\n break;\n }\n\n stream_write(out_stream, buffer, bytes_read);\n if (handle_has_error(out_stream))\n {\n return ERR_WRITE_STDOUT;\n }\n\n counter++;\n }\n\n bytes_read = stream_read(input_stream, buffer, remainder);\n if (bytes_read)\n {\n stream_write(out_stream, buffer, bytes_read);\n if (handle_has_error(out_stream))\n {\n return ERR_WRITE_STDOUT;\n }\n }\n }\n else // Line count mode\n {\n while (counter < count)\n {\n bytes_read = stream_read(input_stream, buffer, BUFFER_SIZE);\n if (bytes_read == 0)\n {\n break;\n }\n\n size_t buffer_iterator = 0;\n while (buffer_iterator < bytes_read)\n {\n if (buffer[buffer_iterator] == delimiter)\n {\n counter++;\n if (counter == count)\n {\n break;\n }\n }\n buffer_iterator++;\n }\n\n stream_write(out_stream, buffer, buffer_iterator);\n if (handle_has_error(out_stream))\n {\n return ERR_WRITE_STDOUT;\n }\n }\n }\n\n return SUCCESS;\n}\n" }, { "alpha_fraction": 0.578125, "alphanum_fraction": 0.5852272510528564, "avg_line_length": 16.625, "blob_id": "1c2c21a9ac8e8b4f96ea6d85a0e4ca497711038e", "content_id": "46b0c3e4ddc756d839bbc4c1d72bcfdd4f4c0baa", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 704, "license_type": "permissive", "max_line_length": 50, "num_lines": 40, "path": "/libraries/libwidget/PaginationDots.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Widget.h>\n\nclass PaginationDots : public Widget\n{\nprivate:\n int _count = 3;\n int _index = 0;\n\npublic:\n static constexpr int DOTSIZE = 4;\n static constexpr int DOTSPACING = 8;\n\n int count() const { return _count; }\n\n void count(int count)\n {\n _count = count;\n max_width(size().x());\n should_relayout();\n should_repaint();\n }\n\n int index() const { return _index; }\n\n void index(int index)\n {\n should_repaint();\n _index = index;\n }\n\n PaginationDots(Widget *parent, int count);\n\n ~PaginationDots() override;\n\n void paint(Painter &, const Recti &) override;\n\n Vec2i size() override;\n};" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6875, "avg_line_length": 11.44444465637207, "blob_id": "459912b2ab2845f1262cb1ea0b57996b1e0e1b34", "content_id": "00f2667cd2dc193ae33ac7c17f52b033ac28373f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 112, "license_type": "permissive", "max_line_length": 35, "num_lines": 9, "path": "/manual/10-utilities/displayctl.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# displayctl\n\n```sh\ndisplayctl [OPTION...] [RESOLUTION]\n```\n\n## Description\n\nGet or set the screen resolutions.\n" }, { "alpha_fraction": 0.6964705586433411, "alphanum_fraction": 0.6964705586433411, "avg_line_length": 19.238094329833984, "blob_id": "dd4d654a3302894e47102a6b7493a65812fef176", "content_id": "4c19b42ed50cd10f890707a84afbb83dbce40256", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 425, "license_type": "permissive", "max_line_length": 51, "num_lines": 21, "path": "/apps/settings-service/main.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/Logger.h>\n#include <libsystem/io/Socket.h>\n\n#include <libsystem/eventloop/EventLoop.h>\n#include <libsystem/eventloop/Notifier.h>\n\n#include \"settings-service/Server.h\"\n\nint main(int argc, const char **argv)\n{\n __unused(argc);\n __unused(argv);\n\n EventLoop::initialize();\n\n auto repository = Settings::Repository::load();\n\n Settings::Server server{repository};\n\n return EventLoop::run();\n}\n" }, { "alpha_fraction": 0.5314053297042847, "alphanum_fraction": 0.5467690825462341, "avg_line_length": 26.320987701416016, "blob_id": "b3a5534d62c80b029136887c51079c5c1b68b720", "content_id": "819e6db6114b9034a8dc584cef7acf1bfd277b76", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2213, "license_type": "permissive", "max_line_length": 101, "num_lines": 81, "path": "/libraries/libgraphic/vector/Rasterizer.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libgraphic/Painter.h>\n#include <libgraphic/vector/Rasterizer.h>\n\nnamespace graphic\n{\n\nvoid Rasterizer::tessellate_cubic_bezier(BezierCurve &curve, int depth)\n{\n if (depth > MAX_DEPTH)\n {\n return;\n }\n\n auto a = curve.start;\n auto b = curve.first_control_point;\n auto c = curve.second_contol_point;\n auto d = curve.end;\n\n auto delta1 = d - a;\n float delta2 = fabsf((b.x() - d.x()) * delta1.y() - (b.y() - d.y()) * delta1.x());\n float delta3 = fabsf((c.x() - d.x()) * delta1.y() - (c.y() - d.y()) * delta1.x());\n\n if ((delta2 + delta3) * (delta2 + delta3) <\n TOLERANCE * (delta1.x() * delta1.x() + delta1.y() * delta1.y()))\n {\n _points.push_back(d);\n return;\n }\n\n auto ab = (a + b) / 2;\n auto bc = (b + c) / 2;\n auto cd = (c + d) / 2;\n auto abc = (ab + bc) / 2;\n auto bcd = (bc + cd) / 2;\n auto abcd = (abc + bcd) / 2;\n\n BezierCurve curve_a{a, ab, abc, abcd};\n\n tessellate_cubic_bezier(curve_a, depth + 1);\n\n BezierCurve curve_b{abcd, bcd, cd, d};\n\n tessellate_cubic_bezier(curve_b, depth + 1);\n}\n\n// void Rasterizer::fill(Path &path, Vec2f position, Trans2f transform, Color color)\n// {\n// }\n\nvoid Rasterizer::stroke(Painter &painter, Path &path, Vec2f position, Trans2f transform, Color color)\n{\n for (size_t i = 0; i < path.subpath_count(); i++)\n {\n _points.clear();\n\n auto &subpath = path.subpath(i);\n\n _points.push_back(transform.apply(subpath.first_point()));\n\n for (size_t j = 0; j < subpath.length(); j++)\n {\n auto curve = subpath.curves(j);\n\n curve.start = transform.apply(curve.start) + position;\n curve.first_control_point = transform.apply(curve.first_control_point) + position;\n curve.second_contol_point = transform.apply(curve.second_contol_point) + position;\n curve.end = transform.apply(curve.end) + position;\n\n flatten(curve);\n }\n\n if (_points.count() > 0)\n {\n for (size_t i = 0; i < _points.count() - 1; i += 1)\n {\n painter.draw_line(_points[i], _points[i + 1], color);\n }\n }\n }\n}\n} // namespace graphic\n" }, { "alpha_fraction": 0.5724637508392334, "alphanum_fraction": 0.5748792290687561, "avg_line_length": 16.25, "blob_id": "8ae1173749c84b0cb3790f45e87fb1541b47a205", "content_id": "606dc6fb3ba7480c4d0e2d3d32f237c683bc213d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 414, "license_type": "permissive", "max_line_length": 86, "num_lines": 24, "path": "/libraries/libc/assert.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <stdlib.h>\n\n#include <skift/Plugs.h>\n\nstatic bool _nested = false;\n\nvoid assert_failed(const char *expr, const char *file, const char *function, int line)\n{\n __plug_assert_failed(expr, file, function, line);\n\n if (_nested)\n {\n // nested assert faillur...\n exit(-1);\n }\n else\n {\n _nested = true;\n }\n\n abort();\n __builtin_unreachable();\n}\n" }, { "alpha_fraction": 0.36003050208091736, "alphanum_fraction": 0.40757691860198975, "avg_line_length": 23.128833770751953, "blob_id": "1d3a4e04efa953203972cdc010f94397372a7bcc", "content_id": "27ec7dbaa892eefc19860b3dfcf8b5bee1225905", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3933, "license_type": "permissive", "max_line_length": 169, "num_lines": 163, "path": "/apps/utilities/piano.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/File.h>\n#include <libsystem/io/Filesystem.h>\n#include <libsystem/io/Stream.h>\n#include <libutils/Path.h>\n\n// piano utility takes a file that has notes data for eg:\n// echo \"c5d5e5g5a5b5c6\" > new.txt\n// piano new.txt\n\nstruct spkr\n{\n int length;\n int frequency;\n};\n\nvoid note(int length, int frequency, Stream *spkrstream)\n{\n struct spkr s = {\n .length = length,\n .frequency = frequency,\n };\n\n stream_write(spkrstream, &s, sizeof(s));\n}\n\nint main(int argc, char *argv[])\n{\n\n if (argc == 1)\n {\n stream_format(err_stream, \"%s: Missing notes file operand\\n Info : Write notes eg \\\"c5e5g5\\\" to a file and supply that files' path to this utility \\n\", argv[0]);\n return PROCESS_FAILURE;\n }\n\n __cleanup(stream_cleanup) Stream *streamin = stream_open(argv[1], OPEN_READ);\n\n if (handle_has_error(streamin))\n {\n return handle_get_error(streamin);\n }\n\n __cleanup(stream_cleanup) Stream *streamout = stream_open(\"/Devices/speaker\", OPEN_WRITE | OPEN_CREATE);\n\n if (handle_has_error(streamout))\n {\n return handle_get_error(streamout);\n }\n\n char c;\n char num;\n int read = 0;\n while ((read = stream_read(streamin, &c, 1)) != 0)\n {\n\n read = stream_read(streamin, &num, 1);\n switch (c)\n {\n case 'c':\n switch (num)\n {\n case '5':\n note(500, 523, streamout);\n break;\n case '6':\n note(500, 1046, streamout);\n break;\n case '7':\n note(500, 2093, streamout);\n break;\n case '8':\n note(500, 4186, streamout);\n break;\n }\n break;\n case 'd':\n switch (num)\n {\n case '5':\n note(500, 587, streamout);\n break;\n case '6':\n note(500, 1175, streamout);\n break;\n case '7':\n note(500, 2349, streamout);\n break;\n }\n break;\n case 'e':\n switch (num)\n {\n case '5':\n note(500, 659, streamout);\n break;\n case '6':\n note(500, 1319, streamout);\n break;\n case '7':\n note(500, 2637, streamout);\n break;\n }\n break;\n case 'f':\n switch (num)\n {\n case '5':\n note(500, 698, streamout);\n break;\n case '6':\n note(500, 1397, streamout);\n break;\n case '7':\n note(500, 2793, streamout);\n break;\n }\n break;\n case 'g':\n switch (num)\n {\n case '5':\n note(500, 784, streamout);\n break;\n case '6':\n note(500, 1568, streamout);\n break;\n case '7':\n note(500, 3136, streamout);\n break;\n }\n break;\n case 'a':\n switch (num)\n {\n case '5':\n note(500, 880, streamout);\n break;\n case '6':\n note(500, 1760, streamout);\n break;\n case '7':\n note(500, 3520, streamout);\n break;\n }\n break;\n case 'b':\n switch (num)\n {\n case '5':\n note(500, 988, streamout);\n break;\n case '6':\n note(500, 1976, streamout);\n break;\n case '7':\n note(500, 3951, streamout);\n break;\n }\n break;\n }\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6854838728904724, "alphanum_fraction": 0.6854838728904724, "avg_line_length": 12.777777671813965, "blob_id": "c411de8b8d01398fecbbffb86a5d40024c2f4cc7", "content_id": "ba386549abb84b80d0f3b842e2477d3c037d8ed1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 248, "license_type": "permissive", "max_line_length": 28, "num_lines": 18, "path": "/libraries/abi/Mouse.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nenum MouseButtonState\n{\n MOUSE_BUTTON_RELEASED,\n MOUSE_BUTTON_PRESSED,\n};\n\nstruct MousePacket\n{\n int offx;\n int offy;\n int scroll;\n\n MouseButtonState left;\n MouseButtonState right;\n MouseButtonState middle;\n};\n" }, { "alpha_fraction": 0.5147236585617065, "alphanum_fraction": 0.5155304670333862, "avg_line_length": 19.319671630859375, "blob_id": "a8497c84404308adc0ed12e11d60cda0e0069eb6", "content_id": "40ec2e51dc1af25164ba8126187ce68b34dbb5e5", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2479, "license_type": "permissive", "max_line_length": 95, "num_lines": 122, "path": "/libraries/libutils/Slice.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Common.h>\n\n#include <libutils/Move.h>\n#include <libutils/RefPtr.h>\n#include <libutils/SliceStorage.h>\n\nclass Slice\n{\nprivate:\n SliceStorage *_storage = nullptr;\n const void *_start = nullptr;\n size_t _size = 0;\n\npublic:\n bool any() const { return _size > 0; }\n\n size_t size() const { return _size; }\n\n const void *start() const\n {\n return _start;\n }\n\n const void *end() const\n {\n return reinterpret_cast<const char *>(start()) + _size;\n }\n\n Slice()\n {\n }\n\n Slice(SliceStorage &storage, size_t offset, size_t size) : _storage(&storage)\n {\n ref_if_not_null(_storage);\n\n _start = _storage->start();\n _start = static_cast<const void *>(static_cast<const char *>(_start) + offset);\n _size = size;\n }\n\n Slice(RefPtr<SliceStorage> &&storage) : _storage(storage.give_ref())\n {\n _start = _storage->start();\n _size = _storage->size();\n }\n\n Slice(const void *start, size_t size)\n {\n _start = start;\n _size = size;\n }\n\n Slice(const Slice &other) : _storage(other._storage)\n {\n ref_if_not_null(_storage);\n\n _start = other.start();\n _size = other.size();\n }\n\n Slice(Slice &&other) : _storage(other.give_storage())\n {\n _start = other.start();\n _size = other.size();\n }\n\n ~Slice()\n {\n deref_if_not_null(_storage);\n }\n\n Slice &operator=(const Slice &other)\n {\n if (_storage != other.naked_storage())\n {\n deref_if_not_null(_storage);\n _storage = other.naked_storage();\n ref_if_not_null(_storage);\n }\n\n return *this;\n }\n\n Slice &operator=(Slice &&other)\n {\n if (this != &other)\n {\n deref_if_not_null(_storage);\n _storage = other.give_storage();\n }\n\n return *this;\n }\n\n Slice slice(size_t offset, size_t size) const\n {\n if (_storage != nullptr)\n {\n return {*_storage, offset, size};\n }\n else\n {\n auto start = static_cast<const void *>(static_cast<const char *>(_start) + offset);\n return {start, size};\n }\n }\n\n [[nodiscard]] SliceStorage *give_storage()\n {\n SliceStorage *storage = _storage;\n _storage = nullptr;\n return storage;\n }\n\n SliceStorage *naked_storage() const\n {\n return _storage;\n }\n};\n" }, { "alpha_fraction": 0.6087515950202942, "alphanum_fraction": 0.6126126050949097, "avg_line_length": 14.235294342041016, "blob_id": "566a8ad079cbf9114e42aa44fe98b31ddbcd4e8f", "content_id": "8279c36a57c937ac8b7c3bf20554758573f067fc", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 777, "license_type": "permissive", "max_line_length": 41, "num_lines": 51, "path": "/kernel/interrupts/Interupts.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"archs/Architectures.h\"\n\n#include \"kernel/interrupts/Dispatcher.h\"\n#include \"kernel/interrupts/Interupts.h\"\n\nstatic bool _holded = false;\nstatic int _depth = 0;\n\nvoid interrupts_initialize()\n{\n dispatcher_initialize();\n interrupts_enable_holding();\n\n logger_info(\"Enabling interrupts!\");\n arch_enable_interrupts();\n}\n\nbool interrupts_retained()\n{\n return !_holded || _depth > 0;\n}\n\nvoid interrupts_enable_holding()\n{\n _holded = true;\n}\n\nvoid interrupts_disable_holding()\n{\n _holded = false;\n}\n\nvoid interrupts_retain()\n{\n if (_holded)\n {\n arch_disable_interrupts();\n _depth++;\n }\n}\n\nvoid interrupts_release()\n{\n if (_holded)\n {\n _depth--;\n\n if (_depth == 0)\n arch_enable_interrupts();\n }\n}\n" }, { "alpha_fraction": 0.6640211343765259, "alphanum_fraction": 0.6719576716423035, "avg_line_length": 17.899999618530273, "blob_id": "8032e7c0f4728cf77747ca4d2d971c0b718aec5a", "content_id": "d6d239529e88ffdbd8368137c165528f385bb6bd", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 378, "license_type": "permissive", "max_line_length": 56, "num_lines": 20, "path": "/libraries/libwidget/IconPanel.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libgraphic/Icon.h>\n#include <libwidget/Widget.h>\n\nclass IconPanel : public Widget\n{\nprivate:\n RefPtr<Icon> _icon;\n IconSize _icon_size = ICON_18PX;\n\npublic:\n void icon_size(IconSize size) { _icon_size = size; }\n\n IconPanel(Widget *parent, RefPtr<Icon> icon);\n\n void paint(Painter &, const Recti &) override;\n\n Vec2i size() override;\n};\n" }, { "alpha_fraction": 0.7020833492279053, "alphanum_fraction": 0.7020833492279053, "avg_line_length": 20.863636016845703, "blob_id": "68a38962d090b8c3564d190b92c317a59c9cc363", "content_id": "27836843afe0acdcac8e3e8aa1b9fb125911f759", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 480, "license_type": "permissive", "max_line_length": 67, "num_lines": 22, "path": "/libraries/libsystem/io/FileWriter.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Handle.h>\n#include <libsystem/io/Writer.h>\n#include <libutils/Path.h>\n\nclass FileWriter final : public Writer\n{\nprivate:\n System::Handle _handle;\n\npublic:\n FileWriter(const char *path);\n FileWriter(Path &path);\n FileWriter(System::Handle &&handle);\n\n virtual size_t length() override;\n virtual size_t position() override;\n\n virtual void flush() override;\n virtual size_t write(const void *buffer, size_t size) override;\n};" }, { "alpha_fraction": 0.5742574334144592, "alphanum_fraction": 0.5841584205627441, "avg_line_length": 19.200000762939453, "blob_id": "5bb6c6ea4e13b604e0b4030118cb3512d3b91bab", "content_id": "789659cbdfe1cabfc33cff6d533b0ea53469333d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 303, "license_type": "permissive", "max_line_length": 57, "num_lines": 15, "path": "/apps/utilities/basename.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io_new/Streams.h>\n#include <libutils/Path.h>\n\nint main(int argc, char **argv)\n{\n if (argc == 1)\n {\n System::errln(\"usage: %s path\", argv[0]);\n return PROCESS_FAILURE;\n }\n\n System::outln(\"{}\", Path::parse(argv[1]).basename());\n\n return PROCESS_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6391304135322571, "alphanum_fraction": 0.6391304135322571, "avg_line_length": 13.375, "blob_id": "92e8aaaa22d51c52ea7c69a51ffa37a6318b93a8", "content_id": "0ddba6f0eb6ad1a2670158010d4975b5d1112a63", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 230, "license_type": "permissive", "max_line_length": 20, "num_lines": 16, "path": "/libraries/libwidget/Cursor.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\nenum CursorState\n{\n CURSOR_DEFAULT,\n CURSOR_TEXT,\n CURSOR_DISABLED,\n CURSOR_BUSY,\n CURSOR_MOVE,\n CURSOR_RESIZEH,\n CURSOR_RESIZEHV,\n CURSOR_RESIZEV,\n CURSOR_RESIZEVH,\n\n __CURSOR_COUNT\n};\n" }, { "alpha_fraction": 0.7979797720909119, "alphanum_fraction": 0.7979797720909119, "avg_line_length": 23.5, "blob_id": "35803fb6669d899c70cb0a9751bdf3b265b0173f", "content_id": "742ff2faff5c140dfe471debd58ae56452d6312b", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 99, "license_type": "permissive", "max_line_length": 48, "num_lines": 4, "path": "/apps/calculator/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += CALCULATOR\n\nCALCULATOR_NAME = calculator\nCALCULATOR_LIBS = widget settings markup graphic\n\n" }, { "alpha_fraction": 0.582317054271698, "alphanum_fraction": 0.5853658318519592, "avg_line_length": 15.147541046142578, "blob_id": "a5a8d5e5e8b54be2503e900613bbc06f5b425ad6", "content_id": "4746fabc17138590685be5527d49c39b1560b234", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 984, "license_type": "permissive", "max_line_length": 84, "num_lines": 61, "path": "/libraries/libsystem/io/FileReader.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/io/FileReader.h>\n\nFileReader::FileReader(const char *path) : _handle{path, OPEN_READ | OPEN_STREAM}\n{\n}\n\nFileReader::FileReader(Path &path) : _handle{path.string(), OPEN_READ | OPEN_STREAM}\n{\n}\n\nFileReader::FileReader(System::Handle &&handle) : _handle{move(handle)}\n{\n}\n\nsize_t FileReader::seek(size_t pos, Whence whence)\n{\n _handle.seek(pos, whence);\n return pos;\n}\n\nsize_t FileReader::read(void *buffer, size_t size)\n{\n auto result_or_read = _handle.read(buffer, size);\n\n if (result_or_read)\n {\n return *result_or_read;\n }\n else\n {\n return 0;\n }\n}\n\nsize_t FileReader::length()\n{\n auto result_or_stat = _handle.stat();\n\n if (result_or_stat)\n {\n return result_or_stat->size;\n }\n else\n {\n return 0;\n }\n}\n\nsize_t FileReader::position()\n{\n auto result_or_tell = _handle.tell();\n\n if (result_or_tell)\n {\n return *result_or_tell;\n }\n else\n {\n return 0;\n }\n}" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 23.75, "blob_id": "f5e675e2148d6e92dbd4af6fcdeb44ff638ef856", "content_id": "12925c70fe80a66c8eb5db8476d3abfff56fd191", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 99, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/apps/image-viewer/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "APPS += IMAGE_VIEWER\n\nIMAGE_VIEWER_NAME = image-viewer\nIMAGE_VIEWER_LIBS = widget settings graphic\n" }, { "alpha_fraction": 0.5316764116287231, "alphanum_fraction": 0.5377680063247681, "avg_line_length": 23.28402328491211, "blob_id": "8b8bab7771478f8290ff5de8395b483c91d8723d", "content_id": "b84bdb48b3d129e72ccc6d729dd4e78e05b3ca25", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4104, "license_type": "permissive", "max_line_length": 122, "num_lines": 169, "path": "/apps/utilities/tac.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <libsystem/cmdline/CMDLine.h>\n#include <libsystem/io/Stream.h>\n#include <libutils/Path.h>\n#include <libutils/String.h>\n#include <libutils/StringBuilder.h>\n#include <libutils/Vector.h>\n\n#include <cstring>\n\nstatic bool before = false;\nstatic char *separator = nullptr;\n\nstatic const char *usages[] = {\n \"NAME...\",\n \"[OPTION]... NAME...\",\n nullptr,\n};\n\nstatic CommandLineOption options[] = {\n COMMANDLINE_OPT_HELP,\n COMMANDLINE_OPT_STRING(\"separator\", 's', separator,\n \"Choose the separator[STRING] to be used instead of \\\\n\",\n COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_BOOL(\"before\", 'b', before,\n \"Attach the separator before instead of after the string\",\n COMMANDLINE_NO_CALLBACK),\n COMMANDLINE_OPT_END};\n\nstatic CommandLine cmdline = CMDLINE(\n usages,\n options,\n \"Concatenate and print lines of file(s) in reverse.\",\n \"If no filename provided read from input stream\\nNote that command may not work as expected when \\\\0 is encountered\");\n\nchar *str_split(char *str, char *const sub_str)\n{\n /*\n Function to split string into parts with sub_str as delimiter\n Similar to strtok in string.h\n May not work as expected when the str contains '\\0' in between\n */\n static char *start = nullptr;\n\n if (start == nullptr)\n {\n start = str;\n }\n\n if (!*start)\n {\n return nullptr;\n }\n\n char *split = strstr(start, sub_str);\n\n if (split)\n {\n if (*(split + strlen(sub_str)))\n {\n (*split) = 0;\n }\n char *tmp = start;\n start = split + strlen(sub_str);\n return tmp;\n }\n\n int len = strlen(start);\n if (len)\n {\n char *tmp = start;\n start += len;\n return tmp;\n }\n\n return nullptr;\n}\n\nResult tac(Stream *const input_stream)\n{\n size_t read;\n char buffer[1024];\n char *split = nullptr;\n\n StringBuilder temp;\n Vector<String> lines(20);\n if (!separator)\n {\n separator = new char[2];\n strcpy(separator, \"\\n\");\n }\n\n while ((read = stream_read(input_stream, buffer, 1024 - 1)) != 0)\n {\n\n buffer[read] = 0;\n split = str_split(buffer, separator);\n while (split != nullptr)\n {\n temp.append(split);\n split = str_split(NULL, separator);\n if (!before && split)\n {\n temp.append(separator);\n }\n\n lines.push_back(temp.finalize());\n if (before && split)\n {\n temp.append(separator);\n }\n }\n if (temp.finalize().length())\n {\n lines.push_back(temp.finalize());\n }\n }\n\n for (size_t i = lines.count(); i > 0; i--)\n {\n stream_write(out_stream, lines[i - 1].cstring(), lines[i - 1].length());\n if (handle_has_error(out_stream))\n {\n return ERR_WRITE_STDOUT;\n }\n }\n\n return SUCCESS;\n}\n\nint main(int argc, char **argv)\n{\n argc = cmdline_parse(&cmdline, argc, argv);\n Result result;\n int process_status = PROCESS_SUCCESS;\n\n if (argc == 1)\n {\n result = tac(in_stream);\n if (result != SUCCESS)\n {\n stream_format(err_stream, \"%s: %s: %s\", argv[0], \"STDIN\", get_result_description(result));\n process_status = PROCESS_FAILURE;\n }\n\n return process_status;\n }\n\n for (int i = 1; i < argc; i++)\n {\n __cleanup(stream_cleanup) Stream *stream = stream_open(argv[i], OPEN_READ);\n\n if (handle_has_error(stream))\n {\n stream_format(err_stream, \"%s: %s: %s\", argv[0], argv[i], get_result_description(handle_get_error(stream)));\n process_status = PROCESS_FAILURE;\n continue;\n }\n\n result = tac(stream);\n\n if (result != SUCCESS)\n {\n stream_format(err_stream, \"%s: %s: %s\", argv[0], argv[i], get_result_description(result));\n process_status = PROCESS_FAILURE;\n }\n }\n\n return process_status;\n}\n" }, { "alpha_fraction": 0.6246089935302734, "alphanum_fraction": 0.6266945004463196, "avg_line_length": 17.09433937072754, "blob_id": "356d40b641f71e37aafd8f1895c02ab941641e44", "content_id": "f96044de5259f96cbf34c4c1feb59a8166cf571f", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 959, "license_type": "permissive", "max_line_length": 57, "num_lines": 53, "path": "/libraries/libsystem/cmdline/History.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <libsystem/cmdline/History.h>\n#include <libsystem/utils/List.h>\n\nstatic List *history = nullptr;\n\nstatic void initialize_history_if_not_already()\n{\n if (history)\n {\n return;\n }\n\n history = list_create();\n}\n\nvoid history_commit(UnicodeString *text)\n{\n if (unicode_string_length(text) == 0)\n {\n return;\n }\n\n initialize_history_if_not_already();\n\n if (history->any() &&\n unicode_string_equals(history_peek(0), text))\n {\n // We don't want duplicated entry in our history!\n return;\n }\n\n list_push(history, unicode_string_clone(text));\n}\n\nUnicodeString *history_peek(size_t index)\n{\n initialize_history_if_not_already();\n\n assert(index < history_length());\n\n UnicodeString *str = nullptr;\n list_peekat(history, index, (void **)&str);\n\n return str;\n}\n\nsize_t history_length()\n{\n initialize_history_if_not_already();\n\n return history->count();\n}\n" }, { "alpha_fraction": 0.6958855390548706, "alphanum_fraction": 0.703041136264801, "avg_line_length": 24.454545974731445, "blob_id": "7582b539dca833f78518e323ee17a01893c68bae", "content_id": "b9358eb605d05f22aa48050a6f1fa9ccc900a7cf", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 559, "license_type": "permissive", "max_line_length": 60, "num_lines": 22, "path": "/libraries/libsystem/io/MemoryReader.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/io/SeekableReader.h>\n#include <libsystem/io/Stream.h>\n#include <libutils/Path.h>\n\nclass MemoryReader final : public SeekableReader\n{\npublic:\n MemoryReader(const uint8_t *data, size_t size);\n MemoryReader(const Vector<uint8_t> &buffer);\n\n virtual size_t length() override;\n virtual size_t position() override;\n\n virtual size_t read(void *buffer, size_t size) override;\n virtual size_t seek(size_t pos, Whence whence) override;\n\nprivate:\n const uint8_t *_data;\n size_t _size;\n size_t _position = 0;\n};" }, { "alpha_fraction": 0.5723684430122375, "alphanum_fraction": 0.5723684430122375, "avg_line_length": 12.818181991577148, "blob_id": "28446d96f8a13cc6f8ffead9131b384606c583e3", "content_id": "78a54afa2778348f4b841330760b0065b43bd696", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 152, "license_type": "permissive", "max_line_length": 40, "num_lines": 11, "path": "/apps/shell/Nodes.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"shell/Nodes.h\"\n\nvoid shell_node_destroy(ShellNode *node)\n{\n if (node->destroy)\n {\n node->destroy(node);\n }\n\n free(node);\n}\n" }, { "alpha_fraction": 0.8133333325386047, "alphanum_fraction": 0.8133333325386047, "avg_line_length": 24, "blob_id": "9de13718c957dbd0d69a98f2bde761592223009e", "content_id": "7357ab5489572a5722fcb3330b3629548c1a7c15", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 75, "license_type": "permissive", "max_line_length": 57, "num_lines": 3, "path": "/contribs/README.md", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "# Contributions\n\nThis folder contain third-party software ported to skift.\n" }, { "alpha_fraction": 0.5931307673454285, "alphanum_fraction": 0.6010568141937256, "avg_line_length": 26.035715103149414, "blob_id": "6751db8935641be8601afdf20afd588d47c1f6c6", "content_id": "e51e53a075bd09f20ba21fa00a2df0ad5f712de3", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 757, "license_type": "permissive", "max_line_length": 47, "num_lines": 28, "path": "/apps/settings/pages/Home.cpp", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#include \"settings/pages/Home.h\"\n#include \"settings/widgets/Link.h\"\n\nnamespace Settings\n{\n\nHomePage::HomePage(Widget *parent)\n : Container(parent)\n{\n layout(STACK());\n flags(Widget::FILL);\n\n auto links = new Container(this);\n links->layout(GRID(6, 4, 8, 8));\n links->insets(16);\n\n new Link(links, Icon::get(\"home\"), \"test\");\n new Link(links, Icon::get(\"home\"), \"test\");\n new Link(links, Icon::get(\"home\"), \"test\");\n new Link(links, Icon::get(\"home\"), \"test\");\n new Link(links, Icon::get(\"home\"), \"test\");\n new Link(links, Icon::get(\"home\"), \"test\");\n new Link(links, Icon::get(\"home\"), \"test\");\n new Link(links, Icon::get(\"home\"), \"test\");\n new Link(links, Icon::get(\"home\"), \"test\");\n}\n\n} // namespace Settings\n" }, { "alpha_fraction": 0.6309719681739807, "alphanum_fraction": 0.6309719681739807, "avg_line_length": 15.405405044555664, "blob_id": "7f7cd00ecf18c8c5b5190310fcd6337b7ab930c4", "content_id": "570ea4a3c361cd1b1a5be02e7547fa4d644eb6cb", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 607, "license_type": "permissive", "max_line_length": 55, "num_lines": 37, "path": "/libraries/libsystem/io_new/Directory.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libsystem/Handle.h>\n#include <libutils/Path.h>\n\nnamespace System\n{\n\nclass Directory\n{\npublic:\n struct Entry\n {\n String name;\n FileState stat;\n };\n\nprivate:\n System::Handle _handle;\n Optional<Path> _path;\n Vector<Entry> _entries;\n\n void read_entries();\n\npublic:\n const Optional<Path> &path() { return _path; }\n const Vector<Entry> &entries() { return _entries; }\n\n Directory(const char *path);\n Directory(String path);\n Directory(const Path &path);\n Directory(System::Handle &&handle);\n\n bool exist();\n};\n\n} // namespace System\n" }, { "alpha_fraction": 0.7067961096763611, "alphanum_fraction": 0.708737850189209, "avg_line_length": 22.454545974731445, "blob_id": "3881a08950cc294332011de3dac6ffa0af397138", "content_id": "dbbb9040cfeb51500e69b65ab435c396ce7bb9a2", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 515, "license_type": "permissive", "max_line_length": 67, "num_lines": 22, "path": "/libraries/libsystem/compression/DeflateWriter.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n#include <libsystem/compression/Deflate.h>\n#include <libsystem/io/MemoryWriter.h>\n#include <libsystem/io/Writer.h>\n\nclass DeflateWriter : public Writer\n{\npublic:\n DeflateWriter(Writer &writer, int level = 5);\n ~DeflateWriter();\n\n virtual size_t length() override;\n virtual size_t position() override;\n\n virtual void flush() override;\n virtual size_t write(const void *buffer, size_t size) override;\n\nprivate:\n Deflate _deflate;\n MemoryWriter _mem_buffer;\n Writer &_writer;\n};" }, { "alpha_fraction": 0.5632495284080505, "alphanum_fraction": 0.5671179890632629, "avg_line_length": 24.860000610351562, "blob_id": "6a38a9263e419cbc8378457e7c2e012a7774bffa", "content_id": "bb352f32725f4a2a3f4137e017682553b51f922e", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2585, "license_type": "permissive", "max_line_length": 102, "num_lines": 100, "path": "/libraries/libfilepicker/widgets/ToolBar.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <libwidget/Button.h>\n#include <libwidget/Panel.h>\n#include <libwidget/Separator.h>\n\n#include <libfilepicker/model/Navigation.h>\n#include <libfilepicker/widgets/Breadcrumb.h>\n\nnamespace filepicker\n{\n\nclass ToolBar : public Panel\n{\nprivate:\n RefPtr<Navigation> _navigation;\n RefPtr<Bookmarks> _bookmarks;\n\n Widget *_go_backward;\n Widget *_go_foreward;\n Widget *_go_up;\n Widget *_go_home;\n\n Widget *_breadcrumb;\n\n Widget *_refresh;\n Widget *_open_terminal;\n\n OwnPtr<Observer<Navigation>> _observer;\n\npublic:\n static constexpr int NO_OPEN_TERMINAL = 1 << 0;\n\n ToolBar(Widget *parent, RefPtr<Navigation> navigation, RefPtr<Bookmarks> bookmarks, int flags = 0)\n : Panel(parent),\n _navigation(navigation),\n _bookmarks(bookmarks)\n {\n layout(HFLOW(4));\n insets(Insetsi(4, 4));\n max_height(38);\n min_height(38);\n\n _go_backward = new Button(this, Button::TEXT, Icon::get(\"arrow-left\"));\n\n _go_backward->on(Event::ACTION, [this](auto) {\n _navigation->go_backward();\n });\n\n _go_foreward = new Button(this, Button::TEXT, Icon::get(\"arrow-right\"));\n\n _go_foreward->on(Event::ACTION, [this](auto) {\n _navigation->go_forward();\n });\n\n _go_up = new Button(this, Button::TEXT, Icon::get(\"arrow-up\"));\n\n _go_up->on(Event::ACTION, [this](auto) {\n _navigation->go_up();\n });\n\n _go_home = new Button(this, Button::TEXT, Icon::get(\"home\"));\n\n _go_home->on(Event::ACTION, [this](auto) {\n _navigation->go_home();\n });\n\n new Separator(this);\n\n _breadcrumb = new Breadcrumb(this, _navigation, _bookmarks);\n _breadcrumb->flags(Widget::FILL);\n\n new Separator(this);\n\n _refresh = new Button(this, Button::TEXT, Icon::get(\"refresh\"));\n\n _refresh->on(Event::ACTION, [this](auto) {\n _navigation->refresh();\n });\n\n if (!(flags & NO_OPEN_TERMINAL))\n {\n Widget *terminal_button = new Button(this, Button::TEXT, Icon::get(\"console\"));\n\n terminal_button->on(Event::ACTION, [](auto) {\n process_run(\"terminal\", NULL);\n });\n }\n\n _observer = _navigation->observe([this](auto &) {\n _go_backward->enable_if(_navigation->can_go_backward());\n _go_foreward->enable_if(_navigation->can_go_forward());\n _go_up->enable_if(_navigation->can_go_up());\n });\n }\n\n ~ToolBar() override {}\n};\n\n} // namespace filepicker" }, { "alpha_fraction": 0.7678571343421936, "alphanum_fraction": 0.7678571343421936, "avg_line_length": 27, "blob_id": "b426961d25e79c2ea1bb76fec5dd5904c7699fda", "content_id": "264b8e10ed9c4bdfd570ed9ca2293aa9952b6dc1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 112, "license_type": "permissive", "max_line_length": 50, "num_lines": 4, "path": "/contribs/zlib/install-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\ncp sources/libz.a $SKIFT_SYSROOT/System/Libraries/\ncp sources/zlib.h $SKIFT_SYSROOT/System/Includes/\n" }, { "alpha_fraction": 0.6352201104164124, "alphanum_fraction": 0.649056613445282, "avg_line_length": 24.645160675048828, "blob_id": "ce909ba39c34bc594a1c9c692072cc120b44a18e", "content_id": "6a555137b8aed4675fcef6cf55df3926f6824bb1", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 795, "license_type": "permissive", "max_line_length": 60, "num_lines": 31, "path": "/toolbox/font-compiler.py", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport json\nimport sys\nimport struct\n\nin_filename = sys.argv[1]\nout_filename = sys.argv[2]\n\ninfp = open(in_filename, 'r')\ndata = json.load(infp)\ninfp.close()\n\noutfp = open(out_filename, 'wb')\n\nfor character in data[\"characters\"]:\n glyph = data[\"characters\"][character]\n codepoint = ord(character)\n\n outfp.write(struct.pack(\"I\", codepoint))\n outfp.write(struct.pack(\"I\", glyph[\"x\"]))\n outfp.write(struct.pack(\"I\", glyph[\"y\"]))\n outfp.write(struct.pack(\"I\", glyph[\"width\"]))\n outfp.write(struct.pack(\"I\", glyph[\"height\"]))\n outfp.write(struct.pack(\"i\", glyph[\"originX\"]))\n outfp.write(struct.pack(\"i\", glyph[\"originY\"]))\n outfp.write(struct.pack(\"I\", glyph[\"advance\"]))\n\noutfp.write(struct.pack(\"IIIIIiiI\", 0, 0, 0, 0, 0, 0, 0, 0))\n\noutfp.close()\n" }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 13.333333015441895, "blob_id": "595693ee2f5bf00316051256d087dd86c0b05c0f", "content_id": "d9480d79fdc18cb0b5aac930bd589359eb44e6f9", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 43, "license_type": "permissive", "max_line_length": 24, "num_lines": 3, "path": "/libraries/libsettings/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += SETTINGS\n\nSETTINGS_NAME = settings\n" }, { "alpha_fraction": 0.7076923251152039, "alphanum_fraction": 0.7107692360877991, "avg_line_length": 26.08333396911621, "blob_id": "482ae0a49143f545c04c8283457b71c06defbb99", "content_id": "8b8aab3bc179f330a90e71e876899dc7d73db995", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 325, "license_type": "permissive", "max_line_length": 55, "num_lines": 12, "path": "/toolchain/use-it.sh", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nexport PATH=\"$DIR/local/bin:$PATH\"\n\nexport SKIFT_SOURCEROOT=\"$DIR/..\"\nexport SKIFT_TOOLCHAIN=\"$SKIFT_SOURCEROOT/toolchain\"\nexport SKIFT_SYSROOT=\"$SKIFT_SOURCEROOT/build/sysroot\"\nexport SKIFT_CONTRIBROOT=\"$SKIFT_SOURCEROOT/contribs\"\n\necho \"$DIR/local/bin\"\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 9.333333015441895, "blob_id": "c8d2a6f3016c20262489398ec5d298f98c3df028", "content_id": "6f08a71b4f54e4f24324f890b90e9aa3bd948a8d", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 31, "license_type": "permissive", "max_line_length": 16, "num_lines": 3, "path": "/libraries/libfile/.build.mk", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "LIBS += FILE\n\nFILE_NAME = file\n" }, { "alpha_fraction": 0.8151260614395142, "alphanum_fraction": 0.8151260614395142, "avg_line_length": 22.799999237060547, "blob_id": "7031a1afd3909dfa1f3b604a601e0fc613df17f0", "content_id": "da1e4851bb2c8855d1a872e513d095f85f2d3197", "detected_licenses": [ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 119, "license_type": "permissive", "max_line_length": 61, "num_lines": 5, "path": "/kernel/bus/UNIX.h", "repo_name": "cristian-programmer/skift", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"kernel/devices/DeviceAddress.h\"\n\nIteration unix_scan(IterationCallback<UNIXAddress> callback);\n" } ]
469
yulstewartgurrea/CSC-124
https://github.com/yulstewartgurrea/CSC-124
1cb8a46d366d3647d1c7c6033b6c1a9f8a9d90b8
99f859e88a9cac821d0e2bfda8443f1bb081b8de
86419fc22f46cb8ad4198140a84d2e4c256978c1
refs/heads/master
2016-09-23T02:56:34.719730
2016-07-22T02:39:57
2016-07-22T02:39:57
63,917,645
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4224226772785187, "alphanum_fraction": 0.4376288652420044, "avg_line_length": 27.172931671142578, "blob_id": "2bdaf626bd641bf789a3af89a585a59c594af002", "content_id": "d59fc4d2770d48d67307947f614148bcb89ea91d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3880, "license_type": "no_license", "max_line_length": 111, "num_lines": 133, "path": "/Final Project/knapsack.cpp", "repo_name": "yulstewartgurrea/CSC-124", "src_encoding": "UTF-8", "text": "/* A Naive recursive implementation of 0-1 Knapsack problem */\r\n#include<stdio.h>\r\n#include<iostream>\r\n#include<windows.h>\r\n\r\nusing namespace std;\r\n\r\n// A utility function that returns maximum of two integers\r\nint max(int a, int b) { return (a > b)? a : b; }\r\n\r\n// Returns the maximum value that can be put in a knapsack of capacity W\r\nint knapSackRecursive(int W, int wt[], int val[], int n)\r\n{\r\n // Base Case\r\n if (n == 0 || W == 0)\r\n return 0;\r\n\r\n // If weight of the nth item is more than Knapsack capacity W, then\r\n // this item cannot be included in the optimal solution\r\n if (wt[n-1] > W)\r\n return knapSackRecursive(W, wt, val, n-1);\r\n\r\n // Return the maximum of two cases:\r\n // (1) nth item included\r\n // (2) not included\r\n else return max( val[n-1] + knapSackRecursive(W-wt[n-1], wt, val, n-1),\r\n knapSackRecursive(W, wt, val, n-1)\r\n );\r\n}\r\n\r\n// Returns the maximum value that can be put in a knapsack of capacity W\r\nint knapSackDynamic(int W, int wt[], int val[], int n)\r\n{\r\n int i, w;\r\n int K[n+1][W+1];\r\n\r\n // Build table K[][] in bottom up manner\r\n for (i = 0; i <= n; i++)\r\n {\r\n for (w = 0; w <= W; w++)\r\n {\r\n if (i==0 || w==0)\r\n K[i][w] = 0;\r\n else if (wt[i-1] <= w)\r\n K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);\r\n else\r\n K[i][w] = K[i-1][w];\r\n }\r\n }\r\n\r\n return K[n][W];\r\n}\r\n\r\n// Driver program to test above function\r\nint main()\r\n{\r\n int numberOfItems;\r\n int W; //max Weight\r\n int choice;\r\n bool flag = true;\r\n\r\n cout << \"\\t\\t\\t*****************************\\n\"\r\n << \"\\t\\t\\t** CSc 124 Final Project **\\n\"\r\n << \"\\t\\t\\t** Knapsack Algorithm **\\n\"\r\n << \"\\t\\t\\t*****************************\\n\\n\"\r\n << \"Please enter the total weight of the knapsack: \";\r\n cin >> W;\r\n cout << endl;\r\n cout << \"Please enter the number of items: \";\r\n cin >> numberOfItems;\r\n int val[numberOfItems]; //{60, 100, 120}\r\n int wt[numberOfItems]; // {10, 20, 30}\r\n\r\n cout << \"\\nPlease Enter the items' values and corresponding weights\\n\\n\";\r\n for(int i = 0; i < numberOfItems; i++)\r\n {\r\n cout << \"Value \" << i + 1 <<\": \";\r\n cin >> val[i];\r\n }\r\n\r\n cout << endl;\r\n\r\n for(int i = 0; i < numberOfItems; i++)\r\n {\r\n cout << \"Weight \" << i + 1 << \": \";\r\n cin >> wt[i];\r\n }\r\n int n = sizeof(val)/sizeof(val[0]);\r\n cout << endl;\r\n system(\"pause\");\r\n system (\"cls\");\r\n\r\n do\r\n {\r\n\r\n cout << \"\\t\\t\\t*****************************\\n\"\r\n << \"\\t\\t\\t** CSc 124 Final Project **\\n\"\r\n << \"\\t\\t\\t** Knapsack Algorithm **\\n\"\r\n << \"\\t\\t\\t*****************************\\n\\n\"\r\n << \"Please select an option:\\n\"\r\n << \"1 - Solve a Knapsack Problem using recursive approach\\n\"\r\n << \"2 - Solve a Knapsack Problem using dynamic approach\\n\"\r\n << \"3 - Exit Program \\n\\n\\n\"\r\n << \"> \";\r\n\r\n cin >> choice;\r\n\r\n switch(choice)\r\n {\r\n case 1:\r\n printf(\"\\n\\n%d\\n\\n\", knapSackRecursive(W, wt, val, n));\r\n break;\r\n case 2:\r\n printf(\"\\n\\n%d\\n\\n\", knapSackDynamic(W, wt, val, n));\r\n break;\r\n case 3:\r\n flag = false;\r\n system(\"cls\");\r\n cout << endl << endl << endl << endl << endl << endl\r\n << \"\\n\\n\\n\\n\\n\\n\"\r\n << \" ==============Thank you for using our program :)==============\" << endl << endl;\r\n return 0;\r\n break;\r\n default:\r\n break;\r\n }\r\n system(\"pause\");\r\n system(\"cls\");\r\n }while(flag);\r\n\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4684210419654846, "alphanum_fraction": 0.49473685026168823, "avg_line_length": 20.22222137451172, "blob_id": "a45739f9da86b8a4154420d3ac94b05aa9aaff4e", "content_id": "e3c85fb66f52d9da615d7829fef7350de040fb65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 46, "num_lines": 9, "path": "/Programs/LCS/lcs.py", "repo_name": "yulstewartgurrea/CSC-124", "src_encoding": "UTF-8", "text": "def lcs(x,y,m,n):\n\tm = len(x)\n\tn = len(y)\n\tif x[m] == y[n]:\n\t\tc[m,n] = lcs(x,y,m-1,n-1)+1\n\telse:\n\t\tc[m,n] = max(lcs(x,y,m-1,n), lcs(x,y,m,n-1))\n\nprint lcs(\"AGGTAB\", \"GXTXAYB\" ,len(x),len(y))" }, { "alpha_fraction": 0.49964413046836853, "alphanum_fraction": 0.5131672620773315, "avg_line_length": 23.509090423583984, "blob_id": "c0e19e30f934e598e6917292ea35633de0fb28cb", "content_id": "9781103c54c4779af9b7335d130333f158023c79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1405, "license_type": "no_license", "max_line_length": 68, "num_lines": 55, "path": "/Programs/BubbleSort/BubbleSort.java", "repo_name": "yulstewartgurrea/CSC-124", "src_encoding": "UTF-8", "text": "import java.util.Arrays;\r\nimport java.io.File;\r\nimport java.io.FileNotFoundException;\r\nimport java.util.Scanner;\r\n\r\npublic class BubbleSort {\r\n\tpublic static void main(String args[]) {\r\n\t\tFile file = new File(\"C:/Users/hp/Desktop/Lab124/array/list.txt\");\r\n\t\ttry {\r\n\t Scanner sc = new Scanner(file);\r\n\t int[] array = new int[9];\r\n\t int i = 0;\r\n\t while(sc.hasNextInt() && i < array.length) {\r\n\t array[i] = sc.nextInt();\r\n\t i++;\r\n\t }\r\n\t sc.close(); \r\n\t System.out.println(\"Unsorted List:\"); \t \r\n\t printArray(array);\r\n\t float startTime = (int) System.nanoTime();\r\n\t System.out.println(\"Sorted List:\"); \r\n\t bubbleSort(array);\r\n\t float endTime = (int) System.nanoTime();\r\n\t\tfloat totalTime = (endTime - startTime)/1000000;\r\n\t printArray(array);\r\n\t System.out.println(\"Running Time: \" +totalTime);\r\n\t\t}\r\n\t catch (FileNotFoundException e) {\r\n\t e.printStackTrace();\r\n\t }\r\n\t}\r\n\t\r\n\t\r\n\tpublic static void bubbleSort(int A[]){\r\n\t\tint swap;\r\n\t\tint n = A.length;\r\n\t\t for (int i=0; i < (n-1); i++) {\r\n\t\t for (int j=0; j < n-i-1; j++) {\r\n\t\t if (A[j] > A[j+1]) \r\n\t\t {\r\n\t\t swap = A[j];\r\n\t\t A[j] = A[j+1];\r\n\t\t A[j+1] = swap;\r\n\t\t }\r\n\t\t }\r\n\t\t }\r\n\t\t \r\n\t}\r\n\r\n\tpublic static void printArray(int[] a){ \r\n\t\tSystem.out.println(Arrays.toString(a)); \r\n\t\t} \r\n\r\n\t\r\n}\r\n\r\n" }, { "alpha_fraction": 0.4047481119632721, "alphanum_fraction": 0.415170818567276, "avg_line_length": 20.860759735107422, "blob_id": "50770a5cc2e2f448e0f56bb56b5515fdd7b6c280", "content_id": "fa902a5d92d4ea9e5ce71633258e45d88663d1a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1727, "license_type": "no_license", "max_line_length": 56, "num_lines": 79, "path": "/Programs/QuickSort/QuickSort/src/quicksort/QuickSort.java", "repo_name": "yulstewartgurrea/CSC-124", "src_encoding": "UTF-8", "text": "package quicksort;\nimport java.util.Random;\nimport java.util.Arrays;\n\n\npublic class QuickSort {\n\n \n @SuppressWarnings(\"static-access\")\n public static void main(String[] args) {\n QuickSort qs = new QuickSort();\n Random random = new Random(); \n \n int arraysize = 10;\n int A[] = new int[arraysize];\n System.out.println(\"Random Array: \");\n \n for(int i=0; i<arraysize; i++){\n A[i] = random.nextInt(arraysize); \n }\n \n System.out.println(\"Random: \");\n print(A);\n \n \n long start1 = System.nanoTime();\n qs.quickSort(A,0, arraysize-1);\n long end1 = System.nanoTime();\n long total1 = end1 - start1;\n \n System.out.println(\"Sorted Ascending\");\n print(A); \n \n System.out.println(\"time: \" +total1+ \"ns\" );\n }\n \n public static int partition(int A[], int p, int r){\n \n int x = A[r];\n int i = p-1; \n \n for(int j=p; j<=r; j++){ \n if(A[j] <= x){\n i++; \n int temp = A[i];\n A[i] = A[j];\n A[j] = temp;\n \n }\n \n }\n \n int temp2 = A[i+1];\n A[i+1] = A[r];\n A[r] = temp2;\n \n return i++;\n }\n \n public static void quickSort(int A[], int p, int r){\n int q;\n if(p<r){\n q = partition(A,p,r);\n quickSort(A, p, q-1);\n quickSort(A, q+1, r);\n }\n \n \n }\n \n public static void print(int A[]){\n System.out.println(Arrays.toString(A)); \n }\n \n \n \n \n \n}\n" }, { "alpha_fraction": 0.5213235020637512, "alphanum_fraction": 0.5345588326454163, "avg_line_length": 23.22222137451172, "blob_id": "88e681838680e9aee2a5c17dca55724df94ca520", "content_id": "2bfa47851bd41e3f9bb6e123238dbc1bfdd6aa54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1360, "license_type": "no_license", "max_line_length": 68, "num_lines": 54, "path": "/Programs/InsertionSort/InsertionSort.java", "repo_name": "yulstewartgurrea/CSC-124", "src_encoding": "UTF-8", "text": "import java.util.Arrays;\r\nimport java.io.File;\r\nimport java.io.FileNotFoundException;\r\nimport java.util.Scanner;\r\n\r\npublic class InsertionSort {\r\n\tpublic static void main(String args[]) {\r\n\t\tFile file = new File(\"C:/Users/hp/Desktop/Lab124/array/list.txt\");\r\n\t\ttry {\r\n\t Scanner sc = new Scanner(file);\r\n\t int[] array = new int[9];\r\n\t int i = 0;\r\n\t while(sc.hasNextInt() && i < array.length) {\r\n\t array[i] = sc.nextInt();\r\n\t i++;\r\n\t }\r\n\t sc.close(); \r\n\t System.out.println(\"Unsorted List:\");\r\n\t printArray(array);\r\n\t float startTime = (int) System.nanoTime();\r\n\t insertionSort(array);\r\n\t float endTime = (int) System.nanoTime();\r\n\t\tfloat totalTime = (endTime - startTime)/1000000;\r\n\t\tSystem.out.println(\"Sorted List:\");\r\n\t\tprintArray(array);\r\n\t System.out.println(\"Running Time: \" +totalTime);\t \r\n\t\t} \r\n\t catch (FileNotFoundException e) {\r\n\t e.printStackTrace();\r\n\t }\r\n\t}\r\n\t\r\n\tpublic static void insertionSort(int A[]) {\r\n \t\tint j, i; \t\t\r\n \t\tfor(j=1; j<A.length; j++){\r\n \t\t\tint key = A[j];\r\n \t\t\ti = j-1; \t\t\t\r\n \t\twhile(i>=0 && A[i]>key){\r\n \t\t\t A[i+1] = A[i];\r\n \t\t\t\ti = i-1;\r\n \t\t\t\tA[i+1] = key;\r\n \t\t}\r\n \t\t\t\r\n \t\t}\r\n \t\r\n }\r\n\t\r\n\tprivate static void printArray(int[] array){ \r\n\t\tSystem.out.println(Arrays.toString(array)); \r\n\t} \r\n\t\r\n\r\n\t\r\n}" } ]
5
yadavbha/RNAseqPipeline
https://github.com/yadavbha/RNAseqPipeline
f4ce5c16f43900dd6eb04369caf3c238dcb05e34
12513ce76ba045c9c453b28a5836e3b6ceb31381
a94802c72c190c3645337131325749f874174b98
refs/heads/master
2020-12-29T14:46:39.460992
2020-02-06T09:07:31
2020-02-06T09:07:31
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6019005179405212, "alphanum_fraction": 0.6322280764579773, "avg_line_length": 27.402297973632812, "blob_id": "9564f1749259c707f61dd743a1d212afead97907", "content_id": "668124e76cc1fa93f632447c35528642bebe5653", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4946, "license_type": "permissive", "max_line_length": 123, "num_lines": 174, "path": "/RNAseqPipeline.sh", "repo_name": "yadavbha/RNAseqPipeline", "src_encoding": "UTF-8", "text": "#!/bin/bash -l\n\n##Set parameters below\n\n#set project name\nprojectName='project_2001209'\n\n##set directories\ndataDir='/scratch/project_2001209/RawNGSdata/RNAseqFastqData/'\ngenomeDir='/scratch/project_2001209/GenomeDir'\nrefGeneDir='/scratch/project_2001209/RefHuGenome'\noutDir='/scratch/project_2001209/RNAseqResults'\nworkDir='/scratch/project_2001209/.work'\n\n## Path to different files\nfastaFile=\"$refGeneDir/GRCh38_13/*.fa\"\ngtfFile=\"$refGeneDir/GRCh38_13/*.gtf\"\nfastaERCC92=\"$refGeneDir/ERCC/*.fa\"\ngtfERCC=\"$refGeneDir/ERCC/*.gtf\"\n\n##set other parameters\ntrimReads=true #Trim Adaptors and filter phred 20\nsjdbOverhang=49 #default value is 149. Because our nucleotide length is 50i\nstrandedness='unstranded' ## unstranded, forward_stranded, reverse_stranded\naddERCC92=true\n\n##set if\ndownloadFasta=false\ndownloadGTF=false\n\nemail='[email protected]' #Don't work because of server blocking\n##End Parameters\nsaveTrimmed=false\nif [ $trimReads ]\nthen\n saveTrimmed=$trimReads\nfi\n\n################################## Don't Change anything down unless it is required #######################\n\nulimit -c unlimited\nulimit -s unlimited\n\nexport HOME='/projappl/project_2001209'\nexport NXF_HOME='/projappl/project_2001209/Softwares/RNAseqPipeline'\nexport PICARD_HOME='/projappl/project_2001209/Softwares/conda/condawockstrom/share/picard-2.21.4-0/'\nexport NXF_OPTS='-Xms512M -Xmx10G'\nexport LANGUAGE='en_US.UTF-8'\nexport LC_ALL='en_US.UTF-8'\nexport LANG='en_US.UTF-8'\nexport LC_CTYPE='en_US.UTF-8'\nexport R_LIBS_USER='/projappl/project_2001209/Softwares/Rlib'\nmodule load gcc/9.1.0\nmodule load r-env\n\nscript_path='/projappl/project_2001209/Softwares/RNAseqPipeline/main.nf'\n\nif [ $addERCC92 ]\nthen\n fastaFile=\"$refGeneDir/GRCh38_13_with_ERCC92_spikes/*.fa\"\n gtfFile=\"$refGeneDir/GRCh38_13_with_ERCC92_spikes/*.gtf\"\nfi\n\n\nif [[ $1 == 'help' || $1 == '--help' || $1 == '-h' ]]\nthen\n\tcmd=\"nextflow run $script_path -name $name --help\"\n\teval $cmd\n\nelif [ $1 == 'resume' ]\nthen\n if [ -f \"$genomeDir/SAindex\" ]\n then\n cmd=\"nextflow run $script_path -profile standard \\\n --project $projectName \\\n --genomedir $genomeDir \\\n --reads '${dataDir}*_R{1,2}_*.fastq.gz' \\\n\t--strandedness $strandedness \\\n\t--trim $trimReads \\\n --outdir $outDir \\\n --workdir $workDir \\\n --ercc $addERCC92 \\\n\t--download_fasta $downloadFasta \\\n\t--download_gtf $downloadGTF \\\n\t--saveTrimmed $saveTrimmed \\\n --email $email \\\n -resume\"\n echo \"Starting nextflow... Command:\"\n echo $cmd\n echo \"-----\"\n eval $cmd\n else\n\tcmd=\"nextflow run $script_path -profile standard \\\n\t--project $projectName \\\n\t--fasta $fastaFile \\\n --gtf $gtfFile \\\n --sjdbOverhang $sjdbOverhang \\\n\t--reads '${dataDir}*_R{1,2}_*.fastq.gz' \\\n --strandedness $strandedness \\\n --trim $trimReads \\\n\t--outdir $outDir \\\n\t--workdir $workDir \\\n --ercc $addERCC92 \\\n --download_fasta $downloadFasta \\\n --download_gtf $downloadGTF \\\n --saveTrimmed $saveTrimmed \\\n\t--email $email \\\n\t-resume\"\n\techo \"Starting nextflow... Command:\"\n\techo $cmd\n\techo \"-----\"\n\teval $cmd\n fi\n\nelif [ $1 == 'run' ]\n\n#rm -r $workDir/* #clean workdir\n\nthen\n if [ -f \"$genomeDir/SAindex\" ]\n then\n cmd=\"nextflow run $script_path -profile standard \\\n --project $projectName \\\n --genomedir $genomeDir \\\n --reads '${dataDir}*_R{1,2}_*.fastq.gz' \\\n --strandedness $strandedness \\\n --trim $trimReads \\\n --outdir $outDir \\\n\t--workdir $workDir \\\n --ercc $addERCC92 \\\n --download_fasta $downloadFasta \\\n --download_gtf $downloadGTF \\\n --saveTrimmed $saveTrimmed \\\n --email $email\"\n echo \"Starting nextflow... Command:\"\n echo $cmd\n echo \"-----\"\n eval $cmd\n else\n cmd=\"nextflow run $script_path -profile standard \\\n --project $projectName \\\n --fasta $fastaFile \\\n --gtf $gtfFile \\\n --sjdbOverhang $sjdbOverhang \\\n --reads '${dataDir}*_R{1,2}_*.fastq.gz' \\\n --strandedness $strandedness \\\n --trim $trimReads \\\n --outdir $outDir \\\n --workdir $workDir \\\n --ercc $addERCC92 \\\n --download_fasta $downloadFasta \\\n --download_gtf $downloadGTF \\\n --saveTrimmed $saveTrimmed \\\n --email $email\"\n echo \"Starting nextflow... Command:\"\n echo $cmd\n echo \"-----\"\n eval $cmd\n fi \nelse\n\tech \"Please enter correct parameter [help/run/resume]\"\n\nfi\n\nrm -r $outDir/RNAseq_timeline.html.*\nrm -r $outDir/RNAseq_trace.txt.*\n\n#if [ -d \"$outDir/multiQC\" ]; then\n#\trm -r $outDir/multiQC\n#\tmkdir $outDir/multiQC\n#fi\n#cd $outDir\n#multiqc $outDir -f --filename \"multiqc_report\" -o \"$outDir/multiQC\" -c \"$NXF_HOME/conf/\" --cl_config \"multiqc_config.yaml\"\n#$NXF_HOME/bin/markdown_to_html.r \"$NXF_HOME/docs/output.md\" \"$outDir/Documentation/results_description.html\" $R_LIBS_USER\n\n\n\n\n" }, { "alpha_fraction": 0.5971094369888306, "alphanum_fraction": 0.6131861209869385, "avg_line_length": 45.127342224121094, "blob_id": "d2bc4739375b5b871fb88b9cbcd2a76184e18a8a", "content_id": "404a981ecc4f51df158d87b3249935746266eefb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12316, "license_type": "permissive", "max_line_length": 180, "num_lines": 267, "path": "/bin/plot_complexity_curves.py", "repo_name": "yadavbha/RNAseqPipeline", "src_encoding": "UTF-8", "text": "#!/projappl/project_2001209/Softwares/conda/condawockstrom/bin/python\n\"\"\"\npreseq_complexity_curves.py\n\nTakes results preseq and plots complexity curves.\n\"\"\"\n\n\nimport sys\nimport os\nimport yaml\nimport glob\nimport subprocess\nimport argparse\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\ndef plot_complexity_curves(ccurves, coverage=5, read_length=5, real_counts_path=False, use_unique=True, output_name='complexity_curves', x_min=0, x_max=500000000):\n \"\"\"\n This script plots the complexity curves generated for one or several libraries. The script is designed to work using\n the output produced by preseq (http://smithlabresearch.org/software/preseq/). preseq version 1.0.0 is currently\n supported by this script (the script is compatible also with version 0.1.0). Preseq is a tool used to estimate the\n library complexity and/or to predict the library complexity. In the first case \"preseq c_curve\" should be use. In\n the second case \"preseq lc_extrap\" should be usued. Please, refer to preseq manual available at\n http://smithlabresearch.org/wp-content/uploads/manual.pdf for examples (pages 12 to 14 are the most informatives ones)\n \"\"\"\n\n if x_min < 0 or x_max <= x_min:\n sys.exit(\"problem with x-min or x-max ({}, {}). x-min must be equal or higher to 0 and less than x-max\".format(x_min, x_max))\n\n # Covert limit counts to coverage\n if coverage > 0:\n if read_length == 0:\n raise RuntimeError (\"Error: --coverage specified but not --read-length\")\n else:\n coverage = float(coverage) / float(read_length)\n x_max = float(x_max) / coverage\n x_min = float(x_min) / coverage\n\n # Get the real counts if we have them\n real_counts_total = {}\n real_counts_unique = {}\n if real_counts_path is not False:\n real_counts_path = os.path.realpath(real_counts_path)\n try:\n with open(real_counts_path) as fh:\n for line in fh:\n line = line.strip()\n cols = line.split() # Split on any whitespace\n for fn in [cols[0], '{}.preseq'.format(cols[0]), \"{}.bam\".format(cols[0])]:\n if fn in ccurves:\n try:\n if cols[1].isdigit():\n real_counts_total[fn] = int(cols[1])\n if cols[2].isdigit() and use_unique:\n real_counts_unique[fn] = int(cols[2])\n except IndexError:\n pass\n except IOError as e:\n # print('Error loading real counts file: {}'.format(real_counts_path))\n raise IOError(e)\n else:\n # print('Found {} matching sets of counts from {}'.format(len(real_counts_total), real_counts_path))\n\n # Covert real counts to coverage\n if coverage > 0:\n for f, c in real_counts_total.iteritems():\n real_counts_total[f] = float(c) / coverage\n for f, c in real_counts_unique.iteritems():\n real_counts_unique[f] = float(c) / coverage\n\n\n # Set up plot params\n legend = [[],[]]\n global_x_max_ccurve_limit = 0\n global_y_max_ccurve_limit = 0\n fig = plt.figure()\n ax = fig.add_subplot(111)\n max_label_length = 0\n\n # Each ccurve will get a different color\n colormap = plt.cm.gist_ncar\n plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, len(ccurves))])\n\n # Go through inputs and plot line\n for ccurve in ccurves:\n #print 'Processing {}'.format(ccurve)\n ccurve_table = pd.io.parsers.read_csv(ccurve, sep='\\t', header=0)\n ccurve_TOTAL_READS = []\n ccurve_EXPECTED_DISTINCT = []\n if \"TOTAL_READS\" in ccurve_table:\n ccurve_TOTAL_READS = ccurve_table[\"TOTAL_READS\"].tolist()\n ccurve_EXPECTED_DISTINCT = ccurve_table[\"EXPECTED_DISTINCT\"].tolist()\n elif \"total_reads\" in ccurve_table:\n ccurve_TOTAL_READS = ccurve_table[\"total_reads\"].tolist()\n ccurve_EXPECTED_DISTINCT = ccurve_table[\"distinct_reads\"].tolist()\n else:\n sys.exit('Error, table {} is not in the expected format... has been generated with preseq?'.format(ccurve))\n\n # Covert real counts to coverage\n if coverage > 0:\n ccurve_TOTAL_READS = [float(c) / coverage for c in ccurve_TOTAL_READS]\n ccurve_EXPECTED_DISTINCT = [float(c) / coverage for c in ccurve_EXPECTED_DISTINCT]\n\n # I need to find the interpolation point to print the plots\n x_min_ccurve_limit = computeLimit(x_min, ccurve_TOTAL_READS)\n x_max_ccurve_limit = computeLimit(x_max, ccurve_TOTAL_READS)\n try:\n if x_max_ccurve_limit > global_x_max_ccurve_limit:\n global_x_max_ccurve_limit = x_max_ccurve_limit\n if ccurve_EXPECTED_DISTINCT[x_max_ccurve_limit] > global_y_max_ccurve_limit:\n global_y_max_ccurve_limit = ccurve_EXPECTED_DISTINCT[x_max_ccurve_limit]\n x_max_ccurve_limit += 3 # Add a few points to be sure\n except IndexError:\n x_max_ccurve_limit = len(ccurve_EXPECTED_DISTINCT)\n\n # Plot the curve\n p, = ax.plot(ccurve_TOTAL_READS[x_min_ccurve_limit:x_max_ccurve_limit], ccurve_EXPECTED_DISTINCT[x_min_ccurve_limit:x_max_ccurve_limit])\n\n # Get the information for the legend\n sample_name = os.path.splitext(ccurve)[0]\n sample_name_raw = sample_name\n if(sample_name[:32] == 'accepted_hits_sorted_dupRemoved_'):\n sample_name = sample_name[32:]\n if(sample_name[:14] == 'accepted_hits_'):\n sample_name = sample_name[14:]\n if(len(sample_name) > max_label_length):\n max_label_length = len(sample_name)\n legend[0].append(p)\n legend[1].append(sample_name)\n\n # Plot the real data if we have it\n real_key = False\n if sample_name in real_counts_total:\n real_key = sample_name\n if ccurve in real_counts_total:\n real_key = ccurve\n if sample_name_raw + \".bam\" in real_counts_total:\n real_key = sample_name_raw + \".bam\"\n if real_key:\n\n t_reads = float(real_counts_total[real_key])\n\n if real_key in real_counts_unique:\n u_reads = int(real_counts_unique[real_key])\n ax.plot(t_reads, u_reads, 'o', color=p.get_color())\n #print 'INFO: Found real counts for {} - Total: {}, Unique: {}'.format(sample_name, t_reads, u_reads)\n else:\n xvalues = p.get_xdata()\n yvalues = p.get_ydata()\n if t_reads > max(xvalues):\n # print 'WARNING: Total reads for {} ({}) > max preseq value ({}) - skipping this point..'.format(sample_name, t_reads, max(xvalues))\n else:\n interp = np.interp(t_reads, xvalues, yvalues)\n ax.plot(t_reads, interp, 'o', color=p.get_color())\n # print 'INFO: Found real count for {} - Total: {:.2f} (preseq unique reads: {:.2f})'.format(sample_name, t_reads, interp)\n\n # plot perfect library as dashed line\n ax.plot([0, x_max], [0, x_max], color='black', linestyle='--', linewidth=1)\n\n # Set the axis limits\n max_total = 0\n if len(real_counts_total) > 0:\n max_total = int(max(d for d in real_counts_total.values()))\n if x_max < max_total:\n # print 'WARNING: x-max value {} is less than max real data {}'.format(x_max, max_total)\n plt.xlim(x_min, x_max)\n\n max_unique = 0\n if len(real_counts_unique) > 0:\n max_unique = int(max(d for d in real_counts_unique.values()))\n max_unique += max_unique * 0.1\n preseq_ymax = global_y_max_ccurve_limit\n preseq_ymax += global_y_max_ccurve_limit * 0.1\n\n default_ylim = 100000\n if coverage > 0:\n default_ylim = float(default_ylim) / coverage\n\n plt.ylim(default_ylim, max(preseq_ymax, max_unique))\n if preseq_ymax < max_unique:\n #print 'WARNING: y-max value changed from default {} to the max real data {}'.format(int(preseq_ymax), max_unique )\n\n # label the axis\n plt.ylabel('Unique Molecules')\n plt.xlabel('Total Molecules (including duplicates)')\n plt.title(\"Complexity Curve: preseq\")\n\n # Change labels if we're using coverage\n if coverage > 0:\n plt.ylabel('Unique Coverage')\n plt.xlabel('Total Coverage (including duplicates)')\n\n if len(real_counts_unique) > 0:\n plt.text(0.5, -0.15, 'Points show read count versus deduplicated read counts (externally calculated)',\n horizontalalignment='center', fontsize=8, transform = ax.transAxes)\n elif len(real_counts_total) > 0:\n plt.text(0.5, -0.15, 'Points show externally calculated read counts on the curves',\n horizontalalignment='center', fontsize=8, transform = ax.transAxes)\n\n # Sort out some of the nastier plotting defaults\n ax.tick_params(top=False, right=False, direction='out')\n\n # Move the subplot around to fit in the legend\n box = ax.get_position()\n ax.set_position([0.08, box.y0+0.05, (box.width * 0.78)-0.02, box.height-0.05])\n # Set the font size according to how big the legend text is\n font = {'size': 5}\n if len(legend[1]) <= 20 and max_label_length <= 45:\n font = {'size': 6}\n if len(legend[1]) <= 20 and max_label_length <= 30:\n font = {'size': 8}\n if len(legend[1]) <= 20 and max_label_length <= 10:\n font = {'size': 12}\n ax.legend(legend[0], legend[1],loc='center left', bbox_to_anchor=(1.01, 0.5), prop=font)\n\n # now save the plot\n png_fn = \"{}.png\".format(output_name)\n pdf_fn = \"{}.pdf\".format(output_name)\n plt.savefig(png_fn)\n plt.savefig(pdf_fn)\n plt.close(fig)\n return 0\n\n\ndef computeLimit(value, ccurve_TOTAL_READS):\n \"\"\"This function returns the index of ccurve_TOTAL_READS containing the closest value to x_max\"\"\"\n if ccurve_TOTAL_READS[-1] < value:\n # print('WARNING: value is set to a value higher than the highest extrapolated point by preseq (value={}, ccurve_TOTAL_READS[-1]={}).'.format(value, ccurve_TOTAL_READS[-1]))\n first_point = 0\n last_point = len(ccurve_TOTAL_READS)\n iterations = 0\n while first_point != last_point:\n middle_point = (first_point + last_point)/2\n middle_value = ccurve_TOTAL_READS[middle_point]\n if middle_value == value or iterations >= 10000:\n return middle_point\n elif middle_value >= value:\n last_point = middle_point -1\n else:\n first_point = middle_point +1\n iterations += 1\n\n return first_point\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\"plot_complexity_curves.py\", description=plot_complexity_curves.__doc__)\n parser.add_argument('ccurves', metavar='<preseq file>', nargs='+',\n help=\"List of input files generated by preseq\")\n parser.add_argument('-c', '--coverage', dest='coverage', type=int, default=0,\n help=\"Use coverage on axes instead of read counts. Enter number of base pairs of refernce. Human GRCh38.p2 = 3221487035, GRCh37 = 3137144693\")\n parser.add_argument('-l', '--read-length', dest='read_length', type=int, default=0,\n help=\"Sequence read length, for use in coverage calculations\")\n parser.add_argument('-r', '--real-counts', dest='real_counts_path', type=str, default=False,\n help=\"File name for file with three columns - preseq filename, total number reads, number of unique reads (unique optional, whitespace delimited)\")\n parser.add_argument('-u', '--ignore_unique', dest='use_unique', action='store_false',\n help=\"Ignore any information about unique read counts found in --real-counts file.\")\n parser.add_argument('-o', '--output-name', dest='output_name', type=str, default='complexity_curves',\n help=\"Output name (.png will be automatically added)\")\n parser.add_argument('-m', '--x-min', dest='x_min', type=int, default=0,\n help=\"Lower x-limit (default 0)\")\n parser.add_argument('-x', '--x-max', dest='x_max', type=int, default=500000000,\n help=\"Upper x-limit (default 500 million)\")\n kwargs = vars(parser.parse_args())\n plot_complexity_curves(**kwargs)\n" }, { "alpha_fraction": 0.7035842537879944, "alphanum_fraction": 0.716487467288971, "avg_line_length": 31.068965911865234, "blob_id": "609c2cdcbf7a05cb7d9ba1ecb036c4b28d6092dd", "content_id": "1d65c80307f7bcb334db1929ef64c37a72bcc49e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2790, "license_type": "permissive", "max_line_length": 186, "num_lines": 87, "path": "/bin/dupRadar.r", "repo_name": "yadavbha/RNAseqPipeline", "src_encoding": "UTF-8", "text": "#!/usr/bin/env Rscript\n\n# Command line argument processing\nargs = commandArgs(trailingOnly=TRUE)\nif (length(args) < 4) {\n stop(\"Usage: dupRadar.r <input.bam> <annotation.gtf> <strandedness (0 for unstranded, 1 for stranded and 2 for reverse)>, <paired/single> <R-package-location (optional)>\", call.=FALSE)\n}\ninput_bam <- args[1]\nannotation_gtf <- args[2]\nreads_strandedness <- args[3]\nif(isTRUE(args[4])){\npaired_end <- args[4]\n}else{\npaired_end <- if(args[4]=='paired') TRUE else FALSE\n}\n\ninput_bam_basename <- strsplit(input_bam, \"\\\\.\")[[1]][1]\n\n# Load / install packages\nif (length(args) > 3) { .libPaths( c( args[4], .libPaths() ) ) }\nif (!require(\"dupRadar\")){\n source(\"http://bioconductor.org/biocLite.R\")\n biocLite(\"dupRadar\", suppressUpdates=TRUE)\n library(\"dupRadar\")\n}\nif (!require(\"parallel\")) {\n install.packages(\"parallel\", dependencies=TRUE, repos='http://cloud.r-project.org/')\n library(\"parallel\")\n}\n\n# Duplicate stats\nstranded <- as.numeric(reads_strandedness)\nthreads <- detectCores()\ndm <- analyzeDuprates(input_bam, annotation_gtf, stranded, paired_end, threads)\nwrite.table(dm, file=paste(input_bam_basename, \"_dupMatrix.txt\", sep=\"\"), quote=F, row.name=F, sep=\"\\t\")\n\n# 2D density scatter plot\npdf(paste0(input_bam, \"_duprateExpDens.pdf\"))\nduprateExpDensPlot(DupMat=dm)\ntitle(\"Density scatter plot\")\nmtext(input_bam_basename, side=3)\ndev.off()\nfit <- duprateExpFit(DupMat=dm)\ncat(\n paste(\"- dupRadar Int (duprate at low read counts):\", fit$intercept),\n paste(\"- dupRadar Sl (progression of the duplication rate):\", fit$slope),\n fill=TRUE, labels=input_bam_basename,\n file=paste0(input_bam_basename, \"_intercept_slope.txt\"), append=FALSE\n)\n\n# Get numbers from dupRadar GLM\ncurve_x <- sort(log10(dm$RPK))\ncurve_y = 100*predict(fit$glm, data.frame(x=curve_x), type=\"response\")\n# Remove all of the infinite values\ninfs = which(curve_x %in% c(-Inf,Inf))\ncurve_x = curve_x[-infs]\ncurve_y = curve_y[-infs]\n# Reduce number of data points\ncurve_x <- curve_x[seq(1, length(curve_x), 10)]\ncurve_y <- curve_y[seq(1, length(curve_y), 10)]\n# Convert x values back to real counts\ncurve_x = 10^curve_x\n# Write to file\nwrite.table(\n cbind(curve_x, curve_y),\n file=paste0(input_bam_basename, \"_duprateExpDensCurve.txt\"),\n quote=FALSE, row.names=FALSE\n)\n\n# Distribution of expression box plot\npdf(paste0(input_bam_basename, \"_duprateExpBoxplot.pdf\"))\nduprateExpBoxplot(DupMat=dm)\ntitle(\"Percent Duplication by Expression\")\nmtext(input_bam_basename, side=3)\ndev.off()\n\n# Distribution of RPK values per gene\npdf(paste0(input_bam_basename, \"_expressionHist.pdf\"))\nexpressionHist(DupMat=dm)\ntitle(\"Distribution of RPK values per gene\")\nmtext(input_bam_basename, side=3)\ndev.off()\n\n# Print sessioninfo to standard out\nprint(input_bam_basename)\ncitation(\"dupRadar\")\nsessionInfo()\n" }, { "alpha_fraction": 0.7223765254020691, "alphanum_fraction": 0.7303114533424377, "avg_line_length": 39.98373794555664, "blob_id": "3683aa83e2cc4ae47dccf80f3bb279e1937b8f3f", "content_id": "21fff46f338ae40c132cfce05b89ad16c73d4d40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10083, "license_type": "permissive", "max_line_length": 374, "num_lines": 246, "path": "/docs/usage.md", "repo_name": "yadavbha/RNAseqPipeline", "src_encoding": "UTF-8", "text": "# RNAseq Pipeline Usage\n\n## Running the pipeline\nThe typical command for running the pipeline is as follows:\n\n```bash\nnextflow run rnaseqpipeline --reads '*_R{1,2}.fastq.gz' --genome GRCh37\n```\n\nNote that the pipeline will create files in your working directory:\n\n```bash\nwork # Directory containing the nextflow working files\nresults # Finished results (configurable, see below)\n.nextflow_log # Log file from Nextflow\n# Other nextflow hidden files, eg. history of pipeline runs and old logs.\n```\n\n### `--reads`\nLocation of the input FastQ files:\n\n```bash\n --reads 'path/to/data/sample_*_{1,2}.fastq'\n```\n\nPlease note the following requirements:\n\n1. The path must be enclosed in quotes\n2. The path must have at least one `*` wildcard character\n3. When using the pipeline with paired end data, the path must use `{1,2}` notation to specify read pairs.\n\nIf left unspecified, the pipeline will assume that the data is in a directory called `data` in the\nworking directory (`data/*{1,2}.fastq.gz`).\n\n### `--singleEnd`\nBy default, the pipeline expects paired-end data. If you have single-end data, specify `--singleEnd`\non the command line when you launch the pipeline. A normal glob pattern, enclosed in quotation marks,\ncan then be used for `--reads`. For example: `--singleEnd --reads '*.fastq'`\n\nIt is not possible to run a mixture of single-end and paired-end files in one run.\n\n### Library strandedness\nThree command line flags / config parameters set the library strandedness for a run:\n\n* `--forward_stranded`\n* `--reverse_stranded`\n* `--unstranded`\n\nIf not set, the pipeline will be run as unstranded. The UPPMAX configuration file sets `reverse_stranded` to true by default. Use `--unstranded` or `--forward_stranded` to overwrite this. Specifying `--pico` makes the pipeline run in `forward_stranded` mode.\n\nThese flags affect the commands used for several steps in the pipeline - namely HISAT2, featureCounts, RSeQC (`RPKM_saturation.py`)\nand StringTie:\n* `--forward_stranded`\n * HISAT2: `--rna-strandness F` / `--rna-strandness FR`\n * featureCounts: `-s 1`\n * RSeQC: `-d ++,--` / `-d 1++,1--,2+-,2-+`\n * StringTie: `--fr`\n* `--reverse_stranded`\n * HISAT2: `--rna-strandness R` / `--rna-strandness RF`\n * featureCounts: `-s 2`\n * RSeQC: `-d +-,-+` / `-d 1+-,1-+,2++,2--`\n * StringTie: `--rf`\n\n## Alignment tool\nThe pipeline uses [STAR](https://github.com/alexdobin/STAR) to align the raw FastQ reads\nto the reference genome. STAR is fast and common, but requires a great deal of RAM to run, typically\naround 38GB for the Human GRCh37 reference genome.\n\n## Reference Genomes\n\n### `--genome`\nThe reference genome to use for the analysis, needs to be one of the genome specified in the config file. This is `False` by default and needs to be specified (unless index files are supplied, see below).\n\nSee [`conf/uppmax.config`](conf/uppmax.config) for a list of the supported reference genomes\nand their keys. Common genomes that are supported are:\n\n* Human\n * `--genome GRCh37`\n* Mouse\n * `--genome GRCm38`\n* _Drosophila_\n * `--genome BDGP6`\n* _S. cerevisiae_\n * `--genome 'R64-1-1'`\n\n> There are numerous others - check the config file for more.\n\nIf you're not running on UPPMAX (the default profile), you can create your own config\nfile with paths to your reference genomes.\nSee the [Nextflow documentation](https://www.nextflow.io/docs/latest/config.html)\nfor instructions on where to add this.\n\nThe syntax for this reference configuration is as follows:\n\n```groovy\nparams {\n genomes {\n 'GRCh37' {\n star = '<path to the star index folder>'\n fasta = '<path to the genome fasta file>' // Used if no star index given\n gtf = '<path to the genome gtf file>'\n bed12 = '<path to the genome bed file>' // Generated from GTF if not given\n }\n // Any number of additional genomes, key is used with --genome\n }\n}\n```\n\n### `--star_index`, `--fasta`, `--gtf`, `--bed12`\nIf you prefer, you can specify the full path to your reference genome when you run the pipeline:\n\n```bash\n--star_index '[path to STAR index]' \\\n--fasta '[path to Fasta reference]' \\\n--gtf '[path to GTF file]' \\\n--bed12 '[path to bed12 file]'\n```\n\n### `--downloadFasta`, `--downloadGTF`\nIf no STAR / Fasta reference is supplied, a URL can be supplied to download a Fasta file\nat the start of the pipeline. The same with a GTF reference file. A required STAR index\nand BED12 files will then be generated from these downloaded files.\n\n### `--saveReference`\nSupply this parameter to save any generated reference genome files to your results folder.\nThese can then be used for future pipeline runs, reducing processing times.\n\n### `--saveTrimmed`\nBy default, trimmed FastQ files will not be saved to the results directory. Specify this\nflag (or set to true in your config file) to copy these files when complete.\n\n### `--saveAlignedIntermediates`\nAs above, by default intermediate BAM files will not be saved. The final BAM files created\nafter the Picard MarkDuplicates step are always saved. Set to true to also copy out BAM\nfiles from STAR / HISAT2 and sorting steps.\n\n## Adapter Trimming\nIf specific additional trimming is required (for example, from additional tags),\nyou can use any of the following command line parameters. These affect the command\nused to launch TrimGalore!\n\n### `--clip_r1 [int]`\nInstructs Trim Galore to remove bp from the 5' end of read 1 (or single-end reads).\n\n### `--clip_r2 [int]`\nInstructs Trim Galore to remove bp from the 5' end of read 2 (paired-end reads only).\n\n### `--three_prime_clip_r1 [int]`\nInstructs Trim Galore to remove bp from the 3' end of read 1 _AFTER_ adapter/quality trimming has been performed.\n\n### `--three_prime_clip_r2 [int]`\nInstructs Trim Galore to re move bp from the 3' end of read 2 _AFTER_ adapter/quality trimming has been performed.\n\n\n## Library Prep Presets\nSome command line options are available to automatically set parameters for common RNA-seq library preparation kits.\n\n> Note that these presets override other command line arguments. So if you specify `--pico --clip_r1 0`, the `--clip_r1` bit will be ignored.\n\nIf you have a kit that you'd like a preset added for, please let us know!\n\n### `--pico`\nSets trimming and standedness settings for the _SMARTer Stranded Total RNA-Seq Kit - Pico Input_ kit.\n\nEquivalent to: `--forward_stranded` `--clip_r1 3` `--three_prime_clip_r2 3`\n\n\n## Job Resources\n### Automatic resubmission\nEach step in the pipeline has a default set of requirements for number of CPUs, memory and time. For most of the steps in the pipeline, if the job exits on UPPMAX with an error code of `143` (exceeded requested resources) it will automatically resubmit with higher requests (2 x original, then 3 x original). If it still fails after three times then the pipeline is stopped.\n\n### Custom resource requests\nWherever process-specific requirements are set in the pipeline, the default value can be changed by creating a custom config file. See the files in [`conf`](../conf) for examples.\n\n## Other command line parameters\n### `--outdir`\nThe output directory where the results will be saved.\n\n### `--email`\nSet this parameter to your e-mail address to get a summary e-mail with details of the run sent to you when the workflow exits. If set in your user config file (`~/.nextflow/config`) then you don't need to speicfy this on the command line for every run.\n\n### `--plaintext_email`\nSet to receive plain-text e-mails instead of HTML formatted.\n\n### `--sampleLevel`\nUsed to turn of the edgeR MDS and heatmap. Set automatically when running on fewer than 3 samples.\n\n### `-name`\nName for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic.\n\nThis is used in the MultiQC report (if not default) and in the summary HTML / e-mail (always).\n\n**NB:** Single hyphen (core Nextflow option)\n\n### `-resume`\nSpecify this when restarting a pipeline. Nextflow will used cached results from any pipeline steps where the inputs are the same, continuing from where it got to previously.\n\nYou can also supply a run name to resume a specific run: `-resume [run-name]`. Use the `nextflow log` command to show previous run names.\n\n**NB:** Single hyphen (core Nextflow option)\n\n### `-c`\nSpecify the path to a specific config file (this is a core NextFlow command). Useful if using different UPPMAX\nprojects or different sets of reference genomes.\n\n**NB:** Single hyphen (core Nextflow option)\n\nNote - you can use this to override defaults. For example, we run on UPPMAX but don't want to use the MultiQC\nenvironment module as is the default. So we specify a config file using `-c` that contains the following:\n\n```groovy\nprocess.$multiqc.module = []\n```\n\n### `--rlocation`\nSome steps in the pipeline run R with required modules. By default, the pipeline will install\nthese modules to `~/R/nxtflow_libs/` if not present. You can specify what path to use with this\ncommand line flag.\n\n### `--multiqc_config`\nIf you would like to supply a custom config file to MultiQC, you can specify a path with `--multiqc_config`. This is used instead of the config file specific to the pipeline.\n\n### `--clusterOptions`\nSubmit arbitrary SLURM options (UPPMAX profile only). For instance, you could use `--clusterOptions '-p devcore'`\nto run on the development node (though won't work with default process time requests).\n\n## Stand-alone scripts\nThe `bin` directory contains some scripts used by the pipeline which may also be run manually:\n\n* `gtf2bed`\n * Script used to generate the BED12 reference files used by RSeQC. Takes a `.gtf` file as input\n* `dupRadar.r`\n * dupRadar script used in the _dupRadar_ pipeline process.\n* `edgeR_heatmap_MDS.r`\n * edgeR script used in the _Sample Correlation_ process\n* `RNA-pipeline-from-BAM.sh`\n * SLURM script used to mimic pipeline QC steps, taking an aligned BAM file as input.\n * Potentially unmaintained, use at your own risk!\n\n\n---\n\n[![SciLifeLab](images/SciLifeLab_logo.png)](http://www.scilifelab.se/)\n[![National Genomics Infrastructure](images/NGI_logo.png)](https://ngisweden.scilifelab.se/)\n\n---\n" } ]
4
zgongaware/PortlandRestaurantHeatmap
https://github.com/zgongaware/PortlandRestaurantHeatmap
60d2d1e3f61a11f481d007ce8963415563c43831
3745dcc793b9383197e0c9b6d7894f4f57c732a0
b49033c281fee39df34916e543594c570233caec
refs/heads/master
2022-01-07T18:29:07.103401
2019-06-06T02:23:26
2019-06-06T02:23:26
114,580,777
1
0
null
2017-12-18T01:01:03
2018-05-18T19:44:52
2019-01-18T04:57:04
Python
[ { "alpha_fraction": 0.8023256063461304, "alphanum_fraction": 0.8023256063461304, "avg_line_length": 85, "blob_id": "f7337999c89cd38b434381f5690baf1364691be8", "content_id": "80899d2db6a542fc8cce9e8d0180a366994ee595", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 172, "license_type": "no_license", "max_line_length": 141, "num_lines": 2, "path": "/README.md", "repo_name": "zgongaware/PortlandRestaurantHeatmap", "src_encoding": "UTF-8", "text": "# Portland Restaurant Heatmap\nTableau dashboard using Yelp Fusion API and public GIS data. Check out the dashboard at https://public.tableau.com/profile/zach.gongaware#!/\n" }, { "alpha_fraction": 0.6310938596725464, "alphanum_fraction": 0.6347320079803467, "avg_line_length": 28.6618709564209, "blob_id": "bdbbdb49077c1a08efccac7b8984772d6ca952d2", "content_id": "92175d8d9dea3fdec4c785edc471805ea946680d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4123, "license_type": "no_license", "max_line_length": 85, "num_lines": 139, "path": "/PortlandRestaurants.py", "repo_name": "zgongaware/PortlandRestaurantHeatmap", "src_encoding": "UTF-8", "text": "import requests\nimport pandas as pd\n\n\ndef retrieve_neighborhood_reviews(limit=50, search_term=\"\"):\n \"\"\"\n Import list of neighborhoods and iterate over, calling reviews for each.\n :param limit: Maximum number of reviews to retrieve for each neighborhood\n :param search_term: (Optional) Additional search term to add.\n :return:\n \"\"\"\n\n # Define desired results\n columns = [\n \"neighborhood\",\n \"name\",\n \"distance\",\n \"category\",\n \"address\",\n \"display_phone\",\n \"price\",\n \"rating\",\n \"review_count\",\n \"url\",\n \"latitude\",\n \"longitude\",\n ]\n final = pd.DataFrame(columns=columns)\n\n # Bring in neighborhoods\n print(\"Importing neighborhoods...\")\n nhoods = import_neighborhoods(\"Neighborhoods.csv\")\n print(\"...Complete\")\n\n # Find best restaurants in each neighborhood\n print(\"Retrieving reviews...\")\n for i, r in nhoods.iterrows():\n print(\"......%s\" % nhoods.iloc[i][\"Names\"])\n result = parse_reviews(columns, limit, nhoods.iloc[i][\"Names\"], search_term)\n final = pd.concat([final, result], ignore_index=True)\n\n print(\"...Complete\")\n\n # Clean out duplicate restaurants\n clean = final.sort_values(\"distance\", ascending=True).groupby([\"name\"]).head(1)\n\n # Write to restaurants.csv\n print(\"Saving to file...\")\n clean.to_csv(\"restaurants.csv\", encoding=\"utf-8\")\n\n\ndef get_credentials():\n \"\"\"\n Import in Yelp API credentials. Head to https://www.yelp.com/developers to\n generate your own API credentials.\n\n Credentials file is formatted as -\n app_id\n app_secret\n :return:\n \"\"\"\n with open(\"credentials.txt\") as f:\n credentials = [x.strip().split(\":\") for x in f.readlines()]\n\n return credentials[0][0], credentials[1][0]\n\n\ndef call_yelp_api(limit=50, neighborhood=\"\", search_term=\"\"):\n \"\"\"\n Collect credentials and retrieve data from Yelp's API\n :param limit: Maximum number of rows to retrieve.\n :param neighborhood: (Optional) Neighborhood to add to location search parameter.\n :param search_term: (Optional) Additional search term to add.\n :return:\n \"\"\"\n app_id, app_secret = get_credentials()\n\n url = \"https://api.yelp.com/v3/businesses/search\"\n headers = {\"Authorization\": \"bearer %s\" % app_secret}\n params = {\n \"location\": neighborhood + \", Portland, OR\",\n \"term\": \"Restaurant \" + search_term,\n \"sort_by\": \"distance\",\n \"limit\": limit,\n }\n\n resp = requests.get(url=url, params=params, headers=headers)\n\n if \"businesses\" in resp.json():\n return resp.json()[\"businesses\"]\n\n\ndef parse_reviews(columns, limit=50, neighborhood=\"\", search_term=\"\"):\n \"\"\"\n Retrieve reviews from Yelp API and parse results into a pandas dataframe\n :param columns: List of columns to pull from API results\n :param limit: Maximum number of rows to retrieve.\n :param neighborhood: (Optional) Neighborhood to add to location search parameter.\n :param search_term: (Optional) Additional search term to add.\n :return:\n \"\"\"\n\n # Call API and parse to dataframe\n rd = pd.DataFrame.from_dict(call_yelp_api(limit, neighborhood, search_term))\n\n # Parse columns with embedded dictionaries to appropriate information\n if \"categories\" in rd.columns:\n # Category\n rd[\"category\"] = rd.categories.apply(lambda x: x[0][\"title\"])\n\n if \"coordinates\" in rd.columns:\n # Latitude\n rd[\"latitude\"] = rd.coordinates.apply(lambda x: x[\"latitude\"])\n # Longitude\n rd[\"longitude\"] = rd.coordinates.apply(lambda x: x[\"longitude\"])\n\n if \"location\" in rd.columns:\n # Street Address\n rd[\"address\"] = rd.location.apply(lambda x: x[\"display_address\"][0])\n\n # Neighborhood\n rd[\"neighborhood\"] = neighborhood\n\n return rd[columns]\n\n\ndef import_neighborhoods(file_name=\"neighborhoods.csv\"):\n \"\"\"\n Import list of neighborhoods into pandas dataframe\n :param file_name:\n :return:\n \"\"\"\n df = pd.read_csv(file_name)\n\n return df\n\n\nif __name__ == \"__main__\":\n retrieve_neighborhood_reviews()\n" } ]
2
priyarvyas/datalicious_test_2
https://github.com/priyarvyas/datalicious_test_2
c18708d7a3f76c71f21e81163318724b433cda4c
a6c51fca2d2d35171da4e0400f8a25ce634c61f6
aa90d5c43485352d614aecfea7c1ef5f4d44f4a2
refs/heads/master
2016-06-04T20:55:14.306069
2015-11-20T21:41:36
2015-11-20T21:41:36
46,339,379
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.740784764289856, "alphanum_fraction": 0.7467300891876221, "avg_line_length": 43.26315689086914, "blob_id": "4c6334bc71ffa6c4004713939de16d462c44ca58", "content_id": "9b06fdbede6150026d4a2a21e6127e0a11f56b0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 841, "license_type": "no_license", "max_line_length": 129, "num_lines": 19, "path": "/README.md", "repo_name": "priyarvyas/datalicious_test_2", "src_encoding": "UTF-8", "text": "# datalicious_test_2\n\n## Algorithm used:\n\nTo find the least cost path of hex-grid, Dijkstra's algorithm is used here. Dijkstra's algorith is uninformed algorithm.<br>\nIt is specially used when you have no knowledge of the graph, and cannot estimate the distance from each node to the target.\n\n## Time and Space Complexity:\n\nThe algorithm implementation (inclusive of data conversion) has a total complexity of approximately O(n^2) or big-O of n-squared.\nThe steps performed are broken down as follows:\n\nRead hexgrid from file (with row/column iteration of data entries): O(n^2) <br>\nCreate directed graph (row/column iteration for nodes and edges): O(n^2) <br>\nShortest path via Dijkstra's (with sorted list): O(|V| + |E|) approx. O(n^2) <br>\nReverse tracing of path from destination to origin: O(n) <br>\n\n## Path found:\nr,r,d,d,r,d,d,r,r,d\n" }, { "alpha_fraction": 0.5070140361785889, "alphanum_fraction": 0.5325651168823242, "avg_line_length": 30.682538986206055, "blob_id": "4fb09cef9134d57243302d46bf25b6b204275926", "content_id": "ba9efd54dcef8a5a19f1e91c6d01968e43ad54a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1996, "license_type": "no_license", "max_line_length": 95, "num_lines": 63, "path": "/datalicious_assignment_2.py", "repo_name": "priyarvyas/datalicious_test_2", "src_encoding": "UTF-8", "text": "import time as t\n\ndef readmatrix(filename):\n f=open(filename, 'r')\n m=[map(lambda x: int(str(x),16),r.strip().split(\",\")) for r in f.readlines()]\n return m\n\ndef nextcell(dctresults):\n minw = 10000000\n mink = None\n for k in dctresults:\n if not dctresults[k][2]:\n if dctresults[k][1] < minw:\n minw = dctresults[k][1]\n mink = k\n return mink\n\ndef analyzecell(lstmat, tupcell, lstdirec, dctresults):\n i,j = tupcell\n for dr in lstdirec:\n di,dj = dr\n if (i+di) in range(len(lstmat)) and (j+dj) in range(len(lstmat)):\n if not dctresults.has_key((i+di,j+dj)):\n dctresults[(i+di,j+dj)] = [(i,j),dctresults[(i,j)][1]+lstmat[i+di][j+dj],False]\n else:\n oldw = dctresults[(i+di,j+dj)][1]\n neww = dctresults[(i,j)][1]+lstmat[i+di][j+dj]\n if neww < oldw:\n dctresults[(i+di,j+dj)][0] = (i,j)\n dctresults[(i+di,j+dj)][1] = neww\n dctresults[(i,j)][2] = True\n\ndef shortestpath(filename, directions):\n mat = readmatrix(filename)\n \n results = {}\n results[(0,0)] = [None,mat[0][0],False]\n cell = nextcell(results)\n while cell:\n analyzecell(mat,cell,directions,results)\n cell = nextcell(results)\n return results, results[(len(mat)-1,len(mat)-1)][1], mat\n\ndef showpath(res, inpmat):\n print ' '+'-'*len(inpmat)+' '\n pathcells = []\n curc = (len(inpmat)-1,len(inpmat)-1)\n while curc:\n pathcells += [curc]\n curc = res[curc][0]\n \n for i in range(len(inpmat)):\n s='|'\n for j in range(len(inpmat)):\n s+= '#' if (i,j) in pathcells else '.'\n print s+'|'\n print ' '+'-'*len(inpmat)+' '\n\nt1 = t.time()*1000\nresd, pathsum, mat = shortestpath('matrix_2.txt',[(-1,0),(+1,0),(0,-1),(0,+1)])\nt2 = t.time()*1000\nprint 'Shortest path sum', hex(pathsum)[2:], '; Calculation time is ', int(t2-t1), 'ms'\nshowpath(resd, mat)\n" } ]
2
kpisawesome/python
https://github.com/kpisawesome/python
89ca2771668350da3c99c0eaad8213edefb17d18
0dc4a2fa182de0771aa57ff55d2a248522c1d0b4
d17c28958e9a715764770fb5b6bba58e5c14c777
refs/heads/master
2020-06-26T11:15:34.300438
2019-07-24T07:15:10
2019-07-24T07:15:10
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7064117193222046, "alphanum_fraction": 0.7266591787338257, "avg_line_length": 25.117647171020508, "blob_id": "1dc717c070dade6571635536323741ba76edb323", "content_id": "2e1d29c5cead8f5b4dd1b8897af0a745b48736ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 889, "license_type": "no_license", "max_line_length": 68, "num_lines": 34, "path": "/testvenv/readme.md", "repo_name": "kpisawesome/python", "src_encoding": "UTF-8", "text": "1. Make virtual environment\n `virtualenv env_name`\n\n1a. For machine learning, use venv\n `python3 -m venv .venv`\n\n2. Activate virtual env\n `source .venv/bin/activate`\n\n3. See what packages is installed in this environment\n `pip list`\n\n4. Install packages into this environment (eg. django, numpy, etc.)\n `pip install package_name`\n\n5. Export these packages and their version numbers\n `pip freeze --local > requirements.txt`\n\n6. Remove virtual environment folder\n `rm -rf env_name`\n\n7. To restore virtual environment, run step 1 first, then\n `pip install -r requirements.txt`\n\n8. Similiar to node_modules in nodejs, dun commit env folder to git.\n\n9. To lint python file, install autopep8 and run\n `autopep8 --in-place --aggressive --aggressive src/newfile.py`\n\n10. To run unit tests, install nose and run\n `nosetests`\n\n11. To exit virtual environment,\n `deactivate`\n\n" }, { "alpha_fraction": 0.591176450252533, "alphanum_fraction": 0.6029411554336548, "avg_line_length": 15.190476417541504, "blob_id": "a1675cb1b1a8a8aa695ba50a2b956a8e31602a29", "content_id": "6e713fd93983f66a955c688aef58c23c2cb2bcec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 54, "num_lines": 21, "path": "/ML-titanic/src/scrap.py", "repo_name": "kpisawesome/python", "src_encoding": "UTF-8", "text": "import urllib.request\nimport re\n\n# fp = urllib.request.urlopen(\"http://www.python.org\")\n# mybytes = fp.read()\n\n# mystr = mybytes.decode(\"utf8\")\n# fp.close()\n\n\n# temp = mystr.split(\"slide-copy\", 1)\n# temp[0] = temp[0].replace(\"<>\", \"\")\n# mystr = \"I\".join(temp)\n\n\n# print(mystr)\n\nintro = \"<>I'm Tom.\"\nre.sub(r'.*I', 'I', intro)\n\nprint(intro)\n" }, { "alpha_fraction": 0.7099347114562988, "alphanum_fraction": 0.7505438923835754, "avg_line_length": 31.069766998291016, "blob_id": "1409f8e67b9c69bfe60d3d9a02359bfde0a6a1cd", "content_id": "01f571ac9c4c77af5c3c2e578a449a1daa615bdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "no_license", "max_line_length": 111, "num_lines": 43, "path": "/ML-titanic/src/predict_decision_tree.py", "repo_name": "kpisawesome/python", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport lib.utils as utils\nfrom sklearn import tree, model_selection\n\ntrain = pd.read_csv(\"docs/train.csv\")\nutils.clean_data(train)\n\n# What is the desired output? In this case, it is Survived.\ntarget = train[\"Survived\"].values\n\nfeature_names = [\"Pclass\", \"Age\", \"Fare\", \"Embarked\", \"Sex\", \"SibSp\", \"Parch\"]\nfeatures = train[feature_names].values\n\n# Build a decision tree\ngeneralized_tree = tree.DecisionTreeClassifier(\n random_state=1,\n max_depth=7,\n min_samples_split=2\n)\ngeneralized_tree_ = generalized_tree.fit(features, target)\n\nprint(generalized_tree_.score(features, target))\n\n# Result 0.9797979797979798\n# This is not too good. The algorithm is trying to fit as much data as possible using higher order polynomials.\n# We want the algorithm to keep as much generalisation as possible.\n\n# Use cross validation score\n# cv = no of runs\nscores = model_selection.cross_val_score(\n generalized_tree, features, target, scoring=\"accuracy\", cv=50)\nprint(scores)\nprint(scores.mean())\n\n# Result of mean without max_depth and min_samples_split is 0.7848856209150326\n# This is as good as the linear model, which is not good enough\n\n# Result of mean with max_depth and min_samples_split is 0.8243709150326798\n# Better performance\n\n# Visualise the decision tree\ntree.export_graphviz(\n generalized_tree_, feature_names=feature_names, out_file=\"tree.dot\")\n" }, { "alpha_fraction": 0.5579302310943604, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 21.820512771606445, "blob_id": "ba3b4034f1f32884c1875d978f04ddfb99632715", "content_id": "60c4625f0b84251a776d11c822318ef6159722f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 889, "license_type": "no_license", "max_line_length": 66, "num_lines": 39, "path": "/testvenv/src/tests/test_workshop.py", "repo_name": "kpisawesome/python", "src_encoding": "UTF-8", "text": "import unittest\nfrom src.workshop import add, impute_nans\n\nimport pandas as pd\nimport numpy as np\nfrom pandas.testing import assert_frame_equal\n\nclass TestWorkshop(unittest.TestCase):\n\n def test_impute_nans_should_fill_nans_with_median_value(self):\n #arrange\n df = pd.DataFrame({\n 'some_column': [1, np.nan]\n })\n\n expected = pd.DataFrame({\n 'some_column': [1., 1]\n })\n #act\n actual = impute_nans(df, columns=['some_column'])\n\n #assert\n assert_frame_equal(expected, actual)\n\n def test_df_should_equal_itself(self):\n df = pd.DataFrame({\n 'column_1': [1,2,3]\n })\n assert_frame_equal(df,df)\n\n def test_1_should_equals_one(self):\n #arrange\n actual = add(1,1)\n\n #act\n expected = 21\n\n #assert\n self.assertEqual(actual, expected)" }, { "alpha_fraction": 0.7189306616783142, "alphanum_fraction": 0.7608381509780884, "avg_line_length": 37.44444274902344, "blob_id": "efbcd4b1729b4f55421ed27c47312c9473d6e8a7", "content_id": "2e684654700abe5a43e904c91ddc1c36a3ca6a47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1384, "license_type": "no_license", "max_line_length": 106, "num_lines": 36, "path": "/ML-titanic/src/predict_logistic_regression.py", "repo_name": "kpisawesome/python", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport lib.utils as utils\nfrom sklearn import linear_model, preprocessing\n\ntrain = pd.read_csv(\"docs/train.csv\")\n# Use utils to clean the data\nutils.clean_data(train)\n\n# What is the desired output? In this case, it is Survived.\ntarget = train[\"Survived\"].values\n# What we tell the machine algorithm, these are the hints\n# Test 1:\n# features = train[[\"Pclass\", \"Age\", \"Sex\", \"SibSp\", \"Parch\"]].values\n# Test 2: add in more info\nfeature_names = [\"Pclass\", \"Age\", \"Fare\", \"Embarked\", \"Sex\", \"SibSp\", \"Parch\"]\nfeatures = train[feature_names].values\n\n# Create classifier object. Take 1 of these pasengers and decide which bucket its going to be assigned to\nclassifier = linear_model.LogisticRegression()\n# Classifier goes thru every row of the data and try to find some hidden relationship\nclassifier_ = classifier.fit(features, target)\n\n# Score is to double check if the classifier is doing anything\nprint(classifier_.score(features, target))\n\n# Result of features1 is 0.7934904601571269\n# Result of features2 is 0.7991021324354658\n\n# Take linear data and map to 2nd deg polynomial curve, maybe our data can be better described using curve\npoly = preprocessing.PolynomialFeatures(degree=2)\npoly_features = poly.fit_transform(features)\nclassifier_ = classifier.fit(poly_features, target)\n\nprint(classifier_.score(poly_features, target))\n\n# Result is 0.8327721661054994\n" }, { "alpha_fraction": 0.6449275612831116, "alphanum_fraction": 0.6884058117866516, "avg_line_length": 24.090909957885742, "blob_id": "5544cc7e757bed378aacfbaaad806a5897bb508e", "content_id": "418c3488c2f0656888044ba0a244b503fad532b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 552, "license_type": "no_license", "max_line_length": 62, "num_lines": 22, "path": "/ML-titanic/src/predict_gender.py", "repo_name": "kpisawesome/python", "src_encoding": "UTF-8", "text": "import pandas as pd\n\ntrain = pd.read_csv(\"docs/train.csv\")\n\n# Our hypothesis is female will survive more than male\n\n# Add Hyp column, fill every row to 0\ntrain[\"Hyp\"] = 0\n# Change value according to condition in [...]\ntrain.loc[train.Sex == \"female\", \"Hyp\"] = 1\n\n# Add Rsult column\ntrain[\"Result\"] = 0\n# If Survived column is same as hypothesis, update Result to 1\ntrain.loc[train.Survived == train[\"Hyp\"], \"Result\"] = 1\n\nprint(train[\"Result\"].value_counts(normalize=True))\n\n# Result is\n# 1 0.786756\n# 0 0.213244\n# Our hypothesis is 78% correct.\n" }, { "alpha_fraction": 0.5744680762290955, "alphanum_fraction": 0.5957446694374084, "avg_line_length": 17.153846740722656, "blob_id": "aea13a169fb922acfc69c1b3db89abf6e1f6b395", "content_id": "179ca1f11265f3dcac3a153784d9bdb8de75b784", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "no_license", "max_line_length": 42, "num_lines": 13, "path": "/ML-titanic/src/tests/test_workshop.py", "repo_name": "kpisawesome/python", "src_encoding": "UTF-8", "text": "import unittest\n\nclass TestWorkshop(unittest.TestCase):\n\n def test_1_should_equals_one(self):\n #arrange\n actual = add(1,1)\n\n #act\n expected = 21\n\n #assert\n self.assertEqual(actual, expected)" } ]
7
CireWire/is-this-a-number
https://github.com/CireWire/is-this-a-number
cb03c6a1d99bac29f521df2a29fb14b5b9261934
fd8d0037132f455c8ec9c986745d4aeacaa1ab0b
f3bd42c0eaf045ce44bbb9969a91ac632c7ba881
refs/heads/main
2023-03-13T04:37:19.903865
2021-02-26T16:44:53
2021-02-26T16:44:53
342,636,596
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.738095223903656, "alphanum_fraction": 0.738095223903656, "avg_line_length": 41, "blob_id": "1eddac24e0928cf65d328d9402fe5a1dc617450d", "content_id": "2ed72191ebfa1757cc1de255e31ce0dc42e9d308", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 84, "license_type": "permissive", "max_line_length": 64, "num_lines": 2, "path": "/README.md", "repo_name": "CireWire/is-this-a-number", "src_encoding": "UTF-8", "text": "# is-this-a-number\nAutomated a way to see if a number is actually a phone number...\n" }, { "alpha_fraction": 0.6290322542190552, "alphanum_fraction": 0.6674938201904297, "avg_line_length": 25.866666793823242, "blob_id": "389c1cbbd39ebb900698fce6196aecd4b73813fc", "content_id": "d252ed94d930054d0efd5bb1346d7082a0df4b82", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 806, "license_type": "permissive", "max_line_length": 82, "num_lines": 30, "path": "/number.py", "repo_name": "CireWire/is-this-a-number", "src_encoding": "UTF-8", "text": "#A function to see if the given number is a phone number.\n\ndef isPhoneNumber(text):\n#First, we see if our string is the proper length of a phone number (with hyphens)\n if len(text) != 12:\n return False\n#Then, we check if the first group actually has numbers.\n for i in range(0,3):\n if not text[i].isdecimal():\n return False\n#Does this index contain a hyphen? \n if text[3] != \"-\":\n return False\n#Does the next group contain numbers?\n for i in range (4,7):\n if not text[i].isdecimal():\n return False\n#Is there another sexy hyphen?\n if text[7] != \"-\":\n return False\n#Does the final group have numbers?\n for i in range(8,12):\n if not text[i].isdecimal():\n return False\n return True\n\n#Now we finally print\nprint (\"956-555-2021\")\n\nprint (isPhoneNumber(\"956-555-2021\"))\n" } ]
2
paca94/capstone_kvs_server
https://github.com/paca94/capstone_kvs_server
1865ad7bbcb9a52dbd461e123cc7cf962488c157
fc7b1ae6ca10dc7a431c22c62eb351b48c4b5a30
543c22f7f156caa82bb8f219d62028cc97459527
refs/heads/master
2022-08-16T20:40:18.311816
2018-11-24T11:14:06
2018-11-24T11:14:06
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7954545617103577, "alphanum_fraction": 0.7954545617103577, "avg_line_length": 21, "blob_id": "2749feb88ee19f363df9f9fb14f3526198f83ea5", "content_id": "6f26af816c4b137ca2d987b63ccbde76bbd807fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 44, "license_type": "no_license", "max_line_length": 21, "num_lines": 2, "path": "/README.md", "repo_name": "paca94/capstone_kvs_server", "src_encoding": "UTF-8", "text": "# capstone_kvs_server\nkvs server for python\n" }, { "alpha_fraction": 0.6424159407615662, "alphanum_fraction": 0.6479066610336304, "avg_line_length": 28.583755493164062, "blob_id": "2310cca34977de4bb0d9ce55b71e24c67f737c6f", "content_id": "d97890f5243c58095bbdda43b76beae44b3a3fba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5848, "license_type": "no_license", "max_line_length": 96, "num_lines": 197, "path": "/src/main.py", "repo_name": "paca94/capstone_kvs_server", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport os.path\nimport random\nimport string\nimport time\nimport setuptools\nimport tokenize\nimport os \nimport mysql.connector as mariadb\nimport boto3\n#https://mariadb.com/resources/blog/how-to-connect-python-programs-to-mariadb/\nmariadb_connection = mariadb.connect(pool_size=3)\ncursor = mariadb_connection.cursor()\n\n\ndef query(sql, params):\n try:\n cursor.execute(sql, params)\n except mariadb.Error as error:\n print(\"Error: {}\".format(error))\n mariadb_connection.commit()\n print(\"insert\")\n\n#retrieving information\n# some_name = 'Georgi'\n# cursor.execute(\"SELECT first_name,last_name FROM employees WHERE\n# first_name=%s\", (some_name,))\n\n# for first_name, last_name in cursor:\n# print(\"First name: {}, Last name: {}\").format(first_name,last_name)\n\n# #insert information\n# try:\n# cursor.execute(\"INSERT INTO employees (first_name,last_name) VALUES\n# (%s,%s)\", ('Maria','DB'))\n# except mariadb.Error as error:\n# print(\"Error: {}\".format(error))\n\n# mariadb_connection.commit()\n# print (\"The last inserted id was: \", cursor.lastrowid)\n\n# mariadb_connection.close()\n\n# import pymysql\n# # Connect to the database\n# connection = pymysql.connect(\n# charset='utf8mb4',\n# cursorclass=pymysql.cursors.DictCursor)\n\n# try:\n# with connection.cursor() as cursor:\n# # Create a new record\n# sql = \"INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)\"\n# cursor.execute(sql, ('[email protected]', 'very-secret'))\n\n# # connection is not autocommit by default. So you must commit to save\n# # your changes.\n# connection.commit()\n\n# with connection.cursor() as cursor:\n# # Read a single record\n# sql = \"SELECT * FROM `users` WHERE `email`=%s\"\n# cursor.execute(sql, ('[email protected]',))\n# result = cursor.fetchone()\n# print(result)\n# finally:\n# connection.close()\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\nprint(dir_path)\ndef set_header(self):\n self.set_header(\"Content-Type\", \"application/json\")\n\ndef publish_fcm(Message,Target):\n 1\n\n\nclass AuthHandler(tornado.web.RequestHandler):\n def post(self):\n body_data = tornado.escape.json_decode(self.request.body)\n print(body_data)\n id = body_data.get(\"id\")\n password = body_data.get(\"password\")\n self.write(tornado.escape.json_encode({\"result\":0}))\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n set_header(self)\n self.write(tornado.escape.json_encode({\"result\":0}))\n\n def post(self):\n set_header(self)\n self.write(tornado.escape.json_encode({\"result\":0}))\n\n# 사진 전송\nclass PictureHandler(tornado.web.RequestHandler):\n def get(self):\n set_header(self)\n file_name = self.get_argument(\"file_name\")\n fileName='test/' + file_name\n bucket='kvs-for-pcu-capstone'\n client=boto3.client('rekognition')\n response = client.detect_faces(\n Image={'S3Object':{'Bucket':bucket,'Name':fileName}},\n Attributes=['ALL', ]\n )\n print('Detected labels for ' + fileName) \n dic = dict()\n for emotion in response['FaceDetails'][0]['Emotions']:\n dic.update({emotion['Type']:str(emotion['Confidence'])})\n self.write(tornado.escape.json_encode({\"result\":0, \"picture_result\":dic}))\n\n\n def post(self):\n set_header(self)\n #print(self.request.files['file'])\n #self.write(\"Hello, world\")\n fileinfo = self.request.files['file'][0]\n original_fname = fileinfo['filename']\n current_time = int(time.time() * 1000)\n new_file_name = str(current_time) + \"_\" + original_fname\n output_file = open(dir_path + \"/uploads/\" + new_file_name, 'wb')\n output_file.write(fileinfo['body'])\n \n #query(\"INSERT INTO files (file_name) VALUES (%s)\", (original_fname,))\n # Create an S3 client\n s3 = boto3.client('s3')\n \n bucket_name = 'kvs-for-pcu-capstone'\n\n # Uploads the given file using a managed uploader, which will split up large\n # files automatically and upload parts in parallel.\n s3.upload_file(dir_path + \"/uploads/\" + new_file_name, bucket_name,\"test/\" + new_file_name)\n #mariadb_connection.commit()\n self.write(tornado.escape.json_encode({\"result\":0}))\n\n# 통계 가져오기\nclass StatsHandler(tornado.web.RequestHandler):\n def get(self):\n set_header(self)\n print(self.get_current_user())\n user_idx = self.get_argument(\"user_idx\")\n start_at = self.get_argument(\"start_at\")\n self.write(tornado.escape.json_encode({\"result\":0}))\n\n \nclass SettingHandler(tornado.web.RequestHandler):\n def get(self):\n set_header(self)\n self.write(\"get setting\")\n def put(self):\n set_header(self)\n self.write(\"put setting\")\n\nclass TestHandler(tornado.web.RequestHandler):\n def get(self):\n set_header(self)\n cursor = mariadb_connection.cursor()\n try:\n cursor.execute(\"SELECT * FROM kvs.test\")\n except mariadb.Error as error :\n print(\"Error: {}\".format(error))\n ls = list()\n for idx, a in cursor:\n ls.append({\"idx\":idx, \"a\":a})\n\n self.write(tornado.escape.json_encode({\"result\":0, \"list\":ls}))\n def put(self):\n set_header(self)\n self.write(tornado.escape.json_encode({\"result\":0}))\n\nclass PingHandler(tornado.web.RequestHandler):\n def get(self):\n set_header(self)\n self.write(tornado.escape.json_encode({\"result\":0}))\n\napplication = tornado.web.Application(\n [\n (r\"/test\", TestHandler),\n (r\"/main\", MainHandler),\n (r\"/picture\", PictureHandler),\n (r\"/stats\", StatsHandler),\n (r\"/setting\", SettingHandler),\n (r\"/auth\", AuthHandler),\n (r\"/ping\", PingHandler),\n ]\n )\n\nif __name__ == \"__main__\":\n application.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n" } ]
2
m4rm0k/asciimatics
https://github.com/m4rm0k/asciimatics
2923a2d1f5cda9cfe31c8f76a1661ab034754a26
820d784aada846a10cfadc852a86543c4fdcbd74
74f281fb19de212ff7e4132fffbca2f6ca0e6739
refs/heads/master
2021-05-30T12:29:24.323261
2015-12-26T19:46:26
2015-12-26T19:46:26
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5661478638648987, "alphanum_fraction": 0.5677042603492737, "avg_line_length": 28.204545974731445, "blob_id": "a7c107b7bd7c75af93c4845a302d9e7e2c871f7b", "content_id": "d35560552498b8a9eb494adce9979ce8c8316781", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2570, "license_type": "permissive", "max_line_length": 78, "num_lines": 88, "path": "/asciimatics/scene.py", "repo_name": "m4rm0k/asciimatics", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom builtins import object\n\n\nclass Scene(object):\n \"\"\"\n Class to store the details of a single scene to be displayed. This is\n made up of a set of :py:obj:`.Effect` objects. See the documentation for\n Effect to understand the interaction between the two classes.\n \"\"\"\n\n def __init__(self, effects, duration=0, clear=True):\n \"\"\"\n :param effects: The list of effects to apply to this scene.\n :param duration: The number of frames in this Scene. A value of 0\n means that the Scene should query the Effects to find\n the duration. A value of -1 means don't stop.\n :param clear: Whether to clear the Screen at the start of the Scene.\n \"\"\"\n self._effects = []\n for effect in effects:\n self.add_effect(effect)\n self._duration = duration\n if duration == 0:\n self._duration = max([x.stop_frame for x in effects])\n self._clear = clear\n\n def reset(self):\n \"\"\"\n Reset the scene ready for playing.\n \"\"\"\n for effect in self._effects:\n effect.reset()\n\n def add_effect(self, effect):\n \"\"\"\n Add an effect to the Scene. This can be done at any time - event\n when playing the Scene.\n\n :param effect: The Effect to be added.\n \"\"\"\n effect.register_scene(self)\n self._effects.append(effect)\n\n def remove_effect(self, effect):\n \"\"\"\n Remove an effect from the scene.\n\n :param effect: The effect to remove.\n \"\"\"\n self._effects.remove(effect)\n\n def process_event(self, event):\n \"\"\"\n Process a new input event.\n\n :param event: The Event that has been triggered.\n :returns: None if the Scene processed the event, else the original\n event.\n \"\"\"\n for effect in self._effects:\n event = effect.process_event(event)\n if event is None:\n break\n return event\n\n @property\n def effects(self):\n \"\"\"\n :return: The list of Effects in this Scene.\n \"\"\"\n return self._effects\n\n @property\n def duration(self):\n \"\"\"\n :return: The length of the scene in frames.\n \"\"\"\n return self._duration\n\n @property\n def clear(self):\n \"\"\"\n :return: Whether the Scene should clear at the start.\n \"\"\"\n return self._clear\n" }, { "alpha_fraction": 0.6209262609481812, "alphanum_fraction": 0.6209262609481812, "avg_line_length": 25.5, "blob_id": "4af62f14f4e135b34b0c4f0897c39ff5336e5461", "content_id": "673147590d6be91bae045531d688856d4a770004", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 583, "license_type": "permissive", "max_line_length": 78, "num_lines": 22, "path": "/asciimatics/exceptions.py", "repo_name": "m4rm0k/asciimatics", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\n\nclass ResizeScreenError(Exception):\n \"\"\"\n Asciimatics raises this Exception if the terminal is resized while playing\n a Scene (and the Screen has been told not to ignore a resizing event).\n \"\"\"\n\n def __init__(self, message):\n \"\"\"\n :param message: Error message for this exception.\n \"\"\"\n self._message = message\n\n def __str__(self):\n \"\"\"\n Printable form of the exception.\n \"\"\"\n return self._message\n" }, { "alpha_fraction": 0.47598743438720703, "alphanum_fraction": 0.5194258093833923, "avg_line_length": 34.1229133605957, "blob_id": "da663b40a89f9f9c65303d06e900946b6ed8944f", "content_id": "5265fbd5a9f55942db6130f72b604e1f81a1c07c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 58865, "license_type": "permissive", "max_line_length": 80, "num_lines": 1676, "path": "/asciimatics/screen.py", "repo_name": "m4rm0k/asciimatics", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom builtins import object\nfrom builtins import range\nfrom future.utils import with_metaclass\nimport time\nfrom abc import ABCMeta, abstractmethod\nimport copy\nimport sys\nimport signal\nfrom asciimatics.event import KeyboardEvent, MouseEvent\nfrom .exceptions import ResizeScreenError\n\n\nclass Screen(with_metaclass(ABCMeta, object)):\n \"\"\"\n Class to track basic state of the screen. This constructs the necessary\n resources to allow us to do the ASCII animations.\n\n This is an abstract class that will build the correct concrete class for\n you when you call :py:meth:`.wrapper`.\n\n It is still permitted to call the class methods - e.g.\n :py:meth:`.from_curses` or :py:meth:`.from_blessed`, however these are\n deprecated and may be removed in future major releases.\n\n Note that you need to define the required height for your screen buffer.\n This is important if you plan on using any Effects that will scroll the\n screen vertically (e.g. Scroll). It must be big enough to handle the\n full scrolling of your selected Effect.\n \"\"\"\n\n #: Attribute styles supported by Screen formatting functions\n A_BOLD = 1\n A_NORMAL = 2\n A_REVERSE = 3\n A_UNDERLINE = 4\n\n #: Standard colours supported by Screen formatting functions\n COLOUR_BLACK = 0\n COLOUR_RED = 1\n COLOUR_GREEN = 2\n COLOUR_YELLOW = 3\n COLOUR_BLUE = 4\n COLOUR_MAGENTA = 5\n COLOUR_CYAN = 6\n COLOUR_WHITE = 7\n\n #: Standard extended key codes. \n KEY_ESCAPE = -1\n KEY_F1 = -2\n KEY_F2 = -3\n KEY_F3 = -4\n KEY_F4 = -5\n KEY_F5 = -6\n KEY_F6 = -7\n KEY_F7 = -8\n KEY_F8 = -9\n KEY_F9 = -10\n KEY_F10 = -11\n KEY_F11 = -12\n KEY_F12 = -13\n KEY_F13 = -14\n KEY_F14 = -15\n KEY_F15 = -16\n KEY_F16 = -17\n KEY_F17 = -18\n KEY_F18 = -19\n KEY_F19 = -20\n KEY_F20 = -21\n KEY_F21 = -22\n KEY_F22 = -23\n KEY_F23 = -24\n KEY_F24 = -25\n KEY_PRINT_SCREEN = -100\n KEY_INSERT = -101\n KEY_DELETE = -102\n KEY_HOME = -200\n KEY_END = -201\n KEY_LEFT = -203\n KEY_UP = -204\n KEY_RIGHT = -205\n KEY_DOWN = -206\n KEY_PAGE_UP = -207\n KEY_PAGE_DOWN = -208\n KEY_BACK = -300\n KEY_TAB = -301\n KEY_NUMPAD0 = -400\n KEY_NUMPAD1 = -401\n KEY_NUMPAD2 = -402\n KEY_NUMPAD3 = -403\n KEY_NUMPAD4 = -404\n KEY_NUMPAD5 = -405\n KEY_NUMPAD6 = -406\n KEY_NUMPAD7 = -407\n KEY_NUMPAD8 = -408\n KEY_NUMPAD9 = -409\n KEY_MULTIPLY = -410\n KEY_ADD = -411\n KEY_SUBTRACT = -412\n KEY_DECIMAL = -413\n KEY_DIVIDE = -414\n KEY_CAPS_LOCK = -500\n KEY_NUM_LOCK = -501\n KEY_SCROLL_LOCK = -502\n KEY_SHIFT = -600\n KEY_CONTROL = -601\n KEY_MENU = -602\n\n # Colour palette for 8/16 colour terminals\n _8_palette = [\n 0x00, 0x00, 0x00,\n 0x80, 0x00, 0x00,\n 0x00, 0x80, 0x00,\n 0x80, 0x80, 0x00,\n 0x00, 0x00, 0x80,\n 0x80, 0x00, 0x80,\n 0x00, 0x80, 0x80,\n 0xc0, 0xc0, 0xc0,\n ] + [0x00 for _ in range(248 * 3)]\n\n # Colour palette for 256 colour terminals\n _256_palette = [\n 0x00, 0x00, 0x00,\n 0x80, 0x00, 0x00,\n 0x00, 0x80, 0x00,\n 0x80, 0x80, 0x00,\n 0x00, 0x00, 0x80,\n 0x80, 0x00, 0x80,\n 0x00, 0x80, 0x80,\n 0xc0, 0xc0, 0xc0,\n 0x80, 0x80, 0x80,\n 0xff, 0x00, 0x00,\n 0x00, 0xff, 0x00,\n 0xff, 0xff, 0x00,\n 0x00, 0x00, 0xff,\n 0xff, 0x00, 0xff,\n 0x00, 0xff, 0xff,\n 0xff, 0xff, 0xff,\n 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x5f,\n 0x00, 0x00, 0x87,\n 0x00, 0x00, 0xaf,\n 0x00, 0x00, 0xd7,\n 0x00, 0x00, 0xff,\n 0x00, 0x5f, 0x00,\n 0x00, 0x5f, 0x5f,\n 0x00, 0x5f, 0x87,\n 0x00, 0x5f, 0xaf,\n 0x00, 0x5f, 0xd7,\n 0x00, 0x5f, 0xff,\n 0x00, 0x87, 0x00,\n 0x00, 0x87, 0x5f,\n 0x00, 0x87, 0x87,\n 0x00, 0x87, 0xaf,\n 0x00, 0x87, 0xd7,\n 0x00, 0x87, 0xff,\n 0x00, 0xaf, 0x00,\n 0x00, 0xaf, 0x5f,\n 0x00, 0xaf, 0x87,\n 0x00, 0xaf, 0xaf,\n 0x00, 0xaf, 0xd7,\n 0x00, 0xaf, 0xff,\n 0x00, 0xd7, 0x00,\n 0x00, 0xd7, 0x5f,\n 0x00, 0xd7, 0x87,\n 0x00, 0xd7, 0xaf,\n 0x00, 0xd7, 0xd7,\n 0x00, 0xd7, 0xff,\n 0x00, 0xff, 0x00,\n 0x00, 0xff, 0x5f,\n 0x00, 0xff, 0x87,\n 0x00, 0xff, 0xaf,\n 0x00, 0xff, 0xd7,\n 0x00, 0xff, 0xff,\n 0x5f, 0x00, 0x00,\n 0x5f, 0x00, 0x5f,\n 0x5f, 0x00, 0x87,\n 0x5f, 0x00, 0xaf,\n 0x5f, 0x00, 0xd7,\n 0x5f, 0x00, 0xff,\n 0x5f, 0x5f, 0x00,\n 0x5f, 0x5f, 0x5f,\n 0x5f, 0x5f, 0x87,\n 0x5f, 0x5f, 0xaf,\n 0x5f, 0x5f, 0xd7,\n 0x5f, 0x5f, 0xff,\n 0x5f, 0x87, 0x00,\n 0x5f, 0x87, 0x5f,\n 0x5f, 0x87, 0x87,\n 0x5f, 0x87, 0xaf,\n 0x5f, 0x87, 0xd7,\n 0x5f, 0x87, 0xff,\n 0x5f, 0xaf, 0x00,\n 0x5f, 0xaf, 0x5f,\n 0x5f, 0xaf, 0x87,\n 0x5f, 0xaf, 0xaf,\n 0x5f, 0xaf, 0xd7,\n 0x5f, 0xaf, 0xff,\n 0x5f, 0xd7, 0x00,\n 0x5f, 0xd7, 0x5f,\n 0x5f, 0xd7, 0x87,\n 0x5f, 0xd7, 0xaf,\n 0x5f, 0xd7, 0xd7,\n 0x5f, 0xd7, 0xff,\n 0x5f, 0xff, 0x00,\n 0x5f, 0xff, 0x5f,\n 0x5f, 0xff, 0x87,\n 0x5f, 0xff, 0xaf,\n 0x5f, 0xff, 0xd7,\n 0x5f, 0xff, 0xff,\n 0x87, 0x00, 0x00,\n 0x87, 0x00, 0x5f,\n 0x87, 0x00, 0x87,\n 0x87, 0x00, 0xaf,\n 0x87, 0x00, 0xd7,\n 0x87, 0x00, 0xff,\n 0x87, 0x5f, 0x00,\n 0x87, 0x5f, 0x5f,\n 0x87, 0x5f, 0x87,\n 0x87, 0x5f, 0xaf,\n 0x87, 0x5f, 0xd7,\n 0x87, 0x5f, 0xff,\n 0x87, 0x87, 0x00,\n 0x87, 0x87, 0x5f,\n 0x87, 0x87, 0x87,\n 0x87, 0x87, 0xaf,\n 0x87, 0x87, 0xd7,\n 0x87, 0x87, 0xff,\n 0x87, 0xaf, 0x00,\n 0x87, 0xaf, 0x5f,\n 0x87, 0xaf, 0x87,\n 0x87, 0xaf, 0xaf,\n 0x87, 0xaf, 0xd7,\n 0x87, 0xaf, 0xff,\n 0x87, 0xd7, 0x00,\n 0x87, 0xd7, 0x5f,\n 0x87, 0xd7, 0x87,\n 0x87, 0xd7, 0xaf,\n 0x87, 0xd7, 0xd7,\n 0x87, 0xd7, 0xff,\n 0x87, 0xff, 0x00,\n 0x87, 0xff, 0x5f,\n 0x87, 0xff, 0x87,\n 0x87, 0xff, 0xaf,\n 0x87, 0xff, 0xd7,\n 0x87, 0xff, 0xff,\n 0xaf, 0x00, 0x00,\n 0xaf, 0x00, 0x5f,\n 0xaf, 0x00, 0x87,\n 0xaf, 0x00, 0xaf,\n 0xaf, 0x00, 0xd7,\n 0xaf, 0x00, 0xff,\n 0xaf, 0x5f, 0x00,\n 0xaf, 0x5f, 0x5f,\n 0xaf, 0x5f, 0x87,\n 0xaf, 0x5f, 0xaf,\n 0xaf, 0x5f, 0xd7,\n 0xaf, 0x5f, 0xff,\n 0xaf, 0x87, 0x00,\n 0xaf, 0x87, 0x5f,\n 0xaf, 0x87, 0x87,\n 0xaf, 0x87, 0xaf,\n 0xaf, 0x87, 0xd7,\n 0xaf, 0x87, 0xff,\n 0xaf, 0xaf, 0x00,\n 0xaf, 0xaf, 0x5f,\n 0xaf, 0xaf, 0x87,\n 0xaf, 0xaf, 0xaf,\n 0xaf, 0xaf, 0xd7,\n 0xaf, 0xaf, 0xff,\n 0xaf, 0xd7, 0x00,\n 0xaf, 0xd7, 0x5f,\n 0xaf, 0xd7, 0x87,\n 0xaf, 0xd7, 0xaf,\n 0xaf, 0xd7, 0xd7,\n 0xaf, 0xd7, 0xff,\n 0xaf, 0xff, 0x00,\n 0xaf, 0xff, 0x5f,\n 0xaf, 0xff, 0x87,\n 0xaf, 0xff, 0xaf,\n 0xaf, 0xff, 0xd7,\n 0xaf, 0xff, 0xff,\n 0xd7, 0x00, 0x00,\n 0xd7, 0x00, 0x5f,\n 0xd7, 0x00, 0x87,\n 0xd7, 0x00, 0xaf,\n 0xd7, 0x00, 0xd7,\n 0xd7, 0x00, 0xff,\n 0xd7, 0x5f, 0x00,\n 0xd7, 0x5f, 0x5f,\n 0xd7, 0x5f, 0x87,\n 0xd7, 0x5f, 0xaf,\n 0xd7, 0x5f, 0xd7,\n 0xd7, 0x5f, 0xff,\n 0xd7, 0x87, 0x00,\n 0xd7, 0x87, 0x5f,\n 0xd7, 0x87, 0x87,\n 0xd7, 0x87, 0xaf,\n 0xd7, 0x87, 0xd7,\n 0xd7, 0x87, 0xff,\n 0xd7, 0xaf, 0x00,\n 0xd7, 0xaf, 0x5f,\n 0xd7, 0xaf, 0x87,\n 0xd7, 0xaf, 0xaf,\n 0xd7, 0xaf, 0xd7,\n 0xd7, 0xaf, 0xff,\n 0xd7, 0xd7, 0x00,\n 0xd7, 0xd7, 0x5f,\n 0xd7, 0xd7, 0x87,\n 0xd7, 0xd7, 0xaf,\n 0xd7, 0xd7, 0xd7,\n 0xd7, 0xd7, 0xff,\n 0xd7, 0xff, 0x00,\n 0xd7, 0xff, 0x5f,\n 0xd7, 0xff, 0x87,\n 0xd7, 0xff, 0xaf,\n 0xd7, 0xff, 0xd7,\n 0xd7, 0xff, 0xff,\n 0xff, 0x00, 0x00,\n 0xff, 0x00, 0x5f,\n 0xff, 0x00, 0x87,\n 0xff, 0x00, 0xaf,\n 0xff, 0x00, 0xd7,\n 0xff, 0x00, 0xff,\n 0xff, 0x5f, 0x00,\n 0xff, 0x5f, 0x5f,\n 0xff, 0x5f, 0x87,\n 0xff, 0x5f, 0xaf,\n 0xff, 0x5f, 0xd7,\n 0xff, 0x5f, 0xff,\n 0xff, 0x87, 0x00,\n 0xff, 0x87, 0x5f,\n 0xff, 0x87, 0x87,\n 0xff, 0x87, 0xaf,\n 0xff, 0x87, 0xd7,\n 0xff, 0x87, 0xff,\n 0xff, 0xaf, 0x00,\n 0xff, 0xaf, 0x5f,\n 0xff, 0xaf, 0x87,\n 0xff, 0xaf, 0xaf,\n 0xff, 0xaf, 0xd7,\n 0xff, 0xaf, 0xff,\n 0xff, 0xd7, 0x00,\n 0xff, 0xd7, 0x5f,\n 0xff, 0xd7, 0x87,\n 0xff, 0xd7, 0xaf,\n 0xff, 0xd7, 0xd7,\n 0xff, 0xd7, 0xff,\n 0xff, 0xff, 0x00,\n 0xff, 0xff, 0x5f,\n 0xff, 0xff, 0x87,\n 0xff, 0xff, 0xaf,\n 0xff, 0xff, 0xd7,\n 0xff, 0xff, 0xff,\n 0x08, 0x08, 0x08,\n 0x12, 0x12, 0x12,\n 0x1c, 0x1c, 0x1c,\n 0x26, 0x26, 0x26,\n 0x30, 0x30, 0x30,\n 0x3a, 0x3a, 0x3a,\n 0x44, 0x44, 0x44,\n 0x4e, 0x4e, 0x4e,\n 0x58, 0x58, 0x58,\n 0x62, 0x62, 0x62,\n 0x6c, 0x6c, 0x6c,\n 0x76, 0x76, 0x76,\n 0x80, 0x80, 0x80,\n 0x8a, 0x8a, 0x8a,\n 0x94, 0x94, 0x94,\n 0x9e, 0x9e, 0x9e,\n 0xa8, 0xa8, 0xa8,\n 0xb2, 0xb2, 0xb2,\n 0xbc, 0xbc, 0xbc,\n 0xc6, 0xc6, 0xc6,\n 0xd0, 0xd0, 0xd0,\n 0xda, 0xda, 0xda,\n 0xe4, 0xe4, 0xe4,\n 0xee, 0xee, 0xee,\n ]\n\n # Characters for anti-aliasing line drawing.\n _line_chars = \" ''^.|/7.\\\\|Ywbd#\"\n\n def __init__(self, height, width):\n \"\"\"\n Don't call this constructor directly.\n \"\"\"\n # Initialize base class variables - e.g. those used for drawing.\n self.height = height\n self.width = width\n self.colours = 0\n self._start_line = 0\n self._x = 0\n self._y = 0\n\n @classmethod\n def from_curses(cls, win, height=200):\n \"\"\"\n Construct a new Screen from a curses windows.\n\n :param win: The curses window to use.\n :param height: The buffer height for this window (if using scrolling).\n\n This method is deprecated. Please use :py:meth:`.wrapper` instead.\n \"\"\"\n return _CursesScreen(win, height)\n\n @classmethod\n def from_blessed(cls, terminal, height=200):\n \"\"\"\n Construct a new Screen from a blessed terminal.\n\n :param terminal: The blessed Terminal to use.\n :param height: The buffer height for this window (if using scrolling).\n\n This method is deprecated. Please use :py:meth:`.wrapper` instead.\n \"\"\"\n return _BlessedScreen(terminal, height)\n\n @classmethod\n def from_windows(cls, stdout, stdin, height=200):\n \"\"\"\n Construct a new Screen from a Windows console.\n\n :param stdout: The Windows PyConsoleScreenBufferType for stdout returned\n from win32console.\n :param stdin: The Windows PyConsoleScreenBufferType for stdin returned\n from win32console.\n :param height: The buffer height for this window (if using scrolling).\n\n This method is deprecated. Please use :py:meth:`.wrapper` instead.\n \"\"\"\n return _WindowsScreen(stdout, stdin, height)\n\n @classmethod\n def wrapper(cls, func, height=200):\n \"\"\"\n Construct a new Screen for any platform. This will initialize and tidy\n up the system as required around the underlying console subsystem.\n\n :param func: The function to call once the screen has been created.\n :param height: The buffer height for this window (if using scrolling).\n \"\"\"\n if sys.platform == \"win32\":\n # Clone the standard output buffer so that we can do whatever we\n # need for the application, but restore the buffer at the end.\n # Note that we need to resize the clone to ensure that it is the\n # same size as the original in some versions of Windows.\n old_out = win32console.PyConsoleScreenBufferType(\n win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE))\n info = old_out.GetConsoleScreenBufferInfo()\n win_out = win32console.CreateConsoleScreenBuffer()\n win_out.SetConsoleScreenBufferSize(info['Size'])\n win_out.SetConsoleActiveScreenBuffer()\n\n # Get the standard input buffer.\n win_in = win32console.PyConsoleScreenBufferType(\n win32console.GetStdHandle(win32console.STD_INPUT_HANDLE))\n\n # Hide the cursor.\n (size, visible) = win_out.GetConsoleCursorInfo()\n win_out.SetConsoleCursorInfo(1, 0)\n\n # Disable scrolling\n out_mode = win_out.GetConsoleMode()\n win_out.SetConsoleMode(\n out_mode & ~ win32console.ENABLE_WRAP_AT_EOL_OUTPUT)\n\n # Enable mouse input\n in_mode = win_in.GetConsoleMode()\n win_in.SetConsoleMode(in_mode | win32console.ENABLE_MOUSE_INPUT)\n\n try:\n # Create the screen and invoke the wrapped function.\n win_screen = _WindowsScreen(win_out, win_in, height)\n func(win_screen)\n\n # Only restore the screen if we are genuinely finished - and so\n # have not raised an exception. This stops the restore from\n # overriding any resize events.\n old_out.SetConsoleActiveScreenBuffer()\n win_out = old_out\n finally:\n # Reset the original screen settings.\n win_out.SetConsoleCursorInfo(size, visible)\n win_out.SetConsoleMode(out_mode)\n win_out.SetConsoleTextAttribute(7)\n win_in.SetConsoleMode(in_mode)\n else:\n def _wrapper(win):\n cur_screen = _CursesScreen(win, height)\n func(cur_screen)\n\n curses.wrapper(_wrapper)\n\n @property\n def start_line(self):\n \"\"\"\n :return: The start line of the top of the window in the display buffer.\n \"\"\"\n return self._start_line\n\n @property\n def dimensions(self):\n \"\"\"\n :return: The full dimensions of the display buffer as a (height,\n width) tuple.\n \"\"\"\n return self.height, self.width\n\n @property\n def palette(self):\n \"\"\"\n :return: A palette compatible with the PIL.\n \"\"\"\n if self.colours < 256:\n # Use the ANSI colour set.\n return self._8_palette\n else:\n return self._256_palette\n\n @abstractmethod\n def scroll(self):\n \"\"\"\n Scroll the Screen up one line.\n \"\"\"\n\n @abstractmethod\n def clear(self):\n \"\"\"\n Clear the Screen of all content.\n \"\"\"\n\n @abstractmethod\n def refresh(self):\n \"\"\"\n Refresh the screen.\n \"\"\"\n\n def get_key(self):\n \"\"\"\n Check for a key without waiting. This method is deprecated. Use\n :py:meth:`.get_event` instead.\n \"\"\"\n event = self.get_event()\n if event and isinstance(event, KeyboardEvent):\n return event.key_code\n return None\n\n @abstractmethod\n def get_event(self):\n \"\"\"\n Check for any events (e.g. key-press or mouse movement) without waiting.\n\n :returns: A :py:obj:`.Event` object if anything was detected, otherwise\n it returns None.\n \"\"\"\n\n @abstractmethod\n def has_resized(self):\n \"\"\"\n Check whether the screen has been re-sized.\n\n :returns: True when the screen has been re-sized since the last check.\n \"\"\"\n\n @abstractmethod\n def get_from(self, x, y):\n \"\"\"\n Get the character at the specified location.\n\n :param x: The column (x coord) of the character.\n :param y: The row (y coord) of the character.\n\n :return: A tuple of the ASCII code of the character at the location\n and the colour attributes for that character. The format\n is (<character>, <foreground>, <attribute>, <background>).\n \"\"\"\n\n def getch(self, x, y):\n \"\"\"\n Get the character at a specified location.. This method is deprecated.\n Use :py:meth:`.get_from` instead.\n \"\"\"\n return self.get_from(x, y)\n\n @abstractmethod\n def print_at(self, text, x, y, colour=7, attr=0, bg=0, transparent=False):\n \"\"\"\n Print the text at the specified location using the\n specified colour and attributes.\n\n :param text: The (single line) text to be printed.\n :param x: The column (x coord) for the start of the text.\n :param y: The line (y coord) for the start of the text.\n :param colour: The colour of the text to be displayed.\n :param attr: The cell attribute of the text to be displayed.\n :param bg: The background colour of the text to be displayed.\n :param transparent: Whether to print spaces or not, thus giving a\n transparent effect.\n\n The colours and attributes are the COLOUR_xxx and A_yyy constants\n defined in the Screen class.\n \"\"\"\n\n def putch(self, text, x, y, colour=7, attr=0, bg=0, transparent=False):\n \"\"\"\n Print text at the specified location. This method is deprecated. Use\n :py:meth:`.print_at` instead.\n \"\"\"\n self.putch(text, x, y, colour, attr, bg, transparent)\n\n def centre(self, text, y, colour=7, attr=0, colour_map=None):\n \"\"\"\n Centre the text on the specified line (y) using the optional\n colour and attributes.\n\n :param text: The (single line) text to be printed.\n :param y: The line (y coord) for the start of the text.\n :param colour: The colour of the text to be displayed.\n :param attr: The cell attribute of the text to be displayed.\n :param colour_map: Colour/attribute list for multi-colour text.\n\n The colours and attributes are the COLOUR_xxx and A_yyy constants\n defined in the Screen class.\n \"\"\"\n x = (self.width - len(text)) // 2\n self.paint(text, x, y, colour, attr, colour_map=colour_map)\n\n def paint(self, text, x, y, colour=7, attr=0, bg=0, transparent=False,\n colour_map=None):\n \"\"\"\n Paint multi-colour text at the defined location.\n\n :param text: The (single line) text to be printed.\n :param x: The column (x coord) for the start of the text.\n :param y: The line (y coord) for the start of the text.\n :param colour: The default colour of the text to be displayed.\n :param attr: The default cell attribute of the text to be displayed.\n :param bg: The default background colour of the text to be displayed.\n :param transparent: Whether to print spaces or not, thus giving a\n transparent effect.\n :param colour_map: Colour/attribute list for multi-colour text.\n\n The colours and attributes are the COLOUR_xxx and A_yyy constants\n defined in the Screen class.\n colour_map is a list of tuples (foreground, attribute, background) that\n must be the same length as the passed in text (or None if no mapping is\n required).\n \"\"\"\n if colour_map is None:\n self.print_at(text, x, y, colour, attr, bg, transparent)\n else:\n for i, c in enumerate(text):\n if len(colour_map[i]) > 0 and colour_map[i][0] is not None:\n colour = colour_map[i][0]\n if len(colour_map[i]) > 1 and colour_map[i][1] is not None:\n attr = colour_map[i][1]\n if len(colour_map[i]) > 2 and colour_map[i][2] is not None:\n bg = colour_map[i][2]\n self.print_at(c, x + i, y, colour, attr, bg, transparent)\n\n def is_visible(self, x, y):\n \"\"\"\n Return whether the specified location is on the visible screen.\n\n :param x: The column (x coord) for the location to check.\n :param y: The line (y coord) for the location to check.\n \"\"\"\n return ((x >= 0) and\n (x <= self.width) and\n (y >= self._start_line) and\n (y < self._start_line + self.height))\n\n def play(self, scenes, stop_on_resize=False):\n \"\"\"\n Play a set of scenes.\n\n :param scenes: a list of :py:obj:`.Scene` objects to play.\n :param stop_on_resize: Whether to stop when the screen is resized.\n Default is to carry on regardless - which will typically result\n in an error. This is largely done for back-compatibility.\n\n :raises ResizeScreenError: if the screen is resized (and allowed by\n stop_on_resize).\n \"\"\"\n self.clear()\n while True:\n for scene in scenes:\n frame = 0\n if scene.clear:\n self.clear()\n scene.reset()\n re_sized = skipped = False\n while (scene.duration < 0 or frame < scene.duration) and \\\n not re_sized and not skipped:\n frame += 1\n for effect in scene.effects:\n effect.update(frame)\n if effect.delete_count is not None:\n effect.delete_count -= 1\n if effect.delete_count == 0:\n scene.remove_effect(effect)\n self.refresh()\n event = self.get_event()\n while event is not None:\n event = scene.process_event(event)\n if isinstance(event, KeyboardEvent):\n c = event.key_code\n if c in (ord(\"X\"), ord(\"x\"), ord(\"Q\"), ord(\"q\")):\n return\n if c in (ord(\" \"), ord(\"\\n\")):\n skipped = True\n break\n event = self.get_event()\n re_sized = self.has_resized()\n time.sleep(0.05)\n\n # Break out of the function if mandated by caller.\n if re_sized:\n if stop_on_resize:\n raise ResizeScreenError(\"Resized terminal\")\n\n def move(self, x, y):\n \"\"\"\n Move the drawing cursor to the specified position.\n\n :param x: The column (x coord) for the location to check.\n :param y: The line (y coord) for the location to check.\n \"\"\"\n self._x = int(round(x, 1)) * 2\n self._y = int(round(y, 1)) * 2\n\n def draw(self, x, y, char=None, colour=7, bg=0, thin=False):\n \"\"\"\n Draw a line from drawing cursor to the specified position. This uses a\n modified Bressenham algorithm, interpolating twice as many points to\n render down to anti-aliased characters when no character is specified,\n or uses standard algorithm plotting with the specified character.\n\n :param x: The column (x coord) for the location to check.\n :param y: The line (y coord) for the location to check.\n :param char: Optional character to use to draw the line.\n :param colour: Optional colour for plotting the line.\n :param bg: Optional background colour for plotting the line.\n :param thin: Optional width of anti-aliased line.\n \"\"\"\n # Define line end points.\n x0 = self._x\n y0 = self._y\n x1 = int(round(x, 1)) * 2\n y1 = int(round(y, 1)) * 2\n\n # Remember last point for next line.\n self._x = x1\n self._y = y1\n\n dx = abs(x1 - x0)\n dy = abs(y1 - y0)\n\n sx = -1 if x0 > x1 else 1\n sy = -1 if y0 > y1 else 1\n\n x_range = range(0, 2) if sx > 0 else range(1, -1, -1)\n y_range = range(0, 2) if sy > 0 else range(1, -1, -1)\n\n x = x0\n y = y0\n\n if dx > dy:\n err = dx\n while x != x1:\n next_chars = [0, 0]\n px = x & ~1\n py = y & ~1\n for ix in x_range:\n if y >= py and y - py < 2:\n next_chars[0] |= 2 ** ix * 4 ** (y % 2)\n else:\n next_chars[1] |= 2 ** ix * 4 ** (y % 2)\n if not thin:\n if y + sy >= py and y + sy - py < 2:\n next_chars[0] |= 2 ** ix * 4 ** ((y + sy) % 2)\n else:\n next_chars[1] |= 2 ** ix * 4 ** ((y + sy) % 2)\n err -= 2 * dy\n if err < 0:\n y += sy\n err += 2 * dx\n x += sx\n\n if char is None:\n self.print_at(self._line_chars[next_chars[0]], px//2, py//2,\n colour, bg=bg)\n if next_chars[1] != 0:\n self.print_at(self._line_chars[next_chars[1]],\n px // 2, py // 2 + sy, colour, bg=bg)\n elif char == \" \":\n self.print_at(char, px // 2, py // 2, bg=bg)\n self.print_at(char, px // 2, py // 2 + sy, bg=bg)\n else:\n self.print_at(char, px // 2, py // 2, colour, bg=bg)\n else:\n err = dy\n while y != y1:\n next_chars = [0, 0]\n px = x & ~1\n py = y & ~1\n for iy in y_range:\n if x >= px and x - px < 2:\n next_chars[0] |= 2 ** (x % 2) * 4 ** iy\n else:\n next_chars[1] |= 2 ** (x % 2) * 4 ** iy\n if not thin:\n if x + sx >= px and x + sx - px < 2:\n next_chars[0] |= 2 ** ((x + sx) % 2) * 4 ** iy\n else:\n next_chars[1] |= 2 ** ((x + sx) % 2) * 4 ** iy\n err -= 2 * dx\n if err < 0:\n x += sx\n err += 2 * dy\n y += sy\n\n if char is None:\n self.print_at(self._line_chars[next_chars[0]], px//2, py//2,\n colour, bg=bg)\n if next_chars[1] != 0:\n self.print_at(\n self._line_chars[next_chars[1]], px//2 + sx, py//2,\n colour, bg=bg)\n elif char == \" \":\n self.print_at(char, px // 2, py // 2, bg=bg)\n self.print_at(char, px // 2 + sx, py // 2, bg=bg)\n else:\n self.print_at(char, px // 2, py // 2, colour, bg=bg)\n\n\nclass _BufferedScreen(with_metaclass(ABCMeta, Screen)):\n \"\"\"\n Abstract class to handle screen buffering when not using curses.\n \"\"\"\n\n def __init__(self, height, width, buffer_height):\n \"\"\"\n :param height: The buffer height for this window.\n :param width: The buffer width for this window.\n :param buffer_height: The buffer height for this window.\n \"\"\"\n # Save off the screen details and se up the scrolling pad.\n super(_BufferedScreen, self).__init__(height, width)\n\n # Create screen buffers (required to reduce flicker).\n self._screen_buffer = None\n self._double_buffer = None\n self._buffer_height = buffer_height\n\n # Remember current state so we don't keep programming colours/attributes\n # and move commands unnecessarily.\n self._colour = None\n self._attr = None\n self._bg = None\n self._x = None\n self._y = None\n self._last_start_line = 0\n\n # Reset the screen ready to go...\n self._reset()\n\n def _reset(self):\n \"\"\"\n Reset the internal buffers for the screen.\n \"\"\"\n self._start_line = self._last_start_line = 0\n self._x = self._y = None\n\n # Reset our screen buffer\n line = [(\" \", 7, 0, 0) for _ in range(self.width)]\n self._screen_buffer = [\n copy.deepcopy(line) for _ in range(self._buffer_height)]\n self._double_buffer = copy.deepcopy(self._screen_buffer)\n\n def scroll(self):\n \"\"\"\n Scroll the Screen up one line.\n \"\"\"\n self._start_line += 1\n\n def clear(self):\n \"\"\"\n Clear the Screen of all content.\n \"\"\"\n # Clear the actual terminal\n self._change_colours(self.COLOUR_WHITE, 0, 0)\n self._clear()\n self._reset()\n\n def refresh(self):\n \"\"\"\n Refresh the screen.\n \"\"\"\n # Scroll the screen as required to minimize redrawing.\n for _ in range(self._start_line - self._last_start_line):\n self._scroll()\n self._last_start_line = self._start_line\n\n # Now draw any deltas to the scrolled screen.\n for y in range(self.height):\n for x in range(self.width):\n new_cell = self._double_buffer[y + self._start_line][x]\n if self._screen_buffer[y + self._start_line][x] != new_cell:\n self._change_colours(new_cell[1], new_cell[2], new_cell[3])\n self._print_at(new_cell[0], x, y)\n self._screen_buffer[y + self._start_line][x] = new_cell\n\n def get_from(self, x, y):\n \"\"\"\n Get the character at the specified location.\n\n :param x: The column (x coord) of the character.\n :param y: The row (y coord) of the character.\n\n :return: A 4-tuple of (ascii code, foreground, attributes, background)\n for the character at the location.\n \"\"\"\n if y < 0 or y >= self._buffer_height or x < 0 or x >= self.width:\n return None\n cell = self._double_buffer[y][x]\n return ord(cell[0]), cell[1], cell[2], cell[3]\n\n def print_at(self, text, x, y, colour=7, attr=0, bg=0, transparent=False):\n \"\"\"\n Print the text at the specified location using the\n specified colour and attributes.\n\n :param text: The (single line) text to be printed.\n :param x: The column (x coord) for the start of the text.\n :param y: The line (y coord) for the start of the text.\n :param colour: The colour of the text to be displayed.\n :param attr: The cell attribute of the text to be displayed.\n :param bg: The background colour of the text to be displayed.\n :param transparent: Whether to print spaces or not, thus giving a\n transparent effect.\n\n The colours and attributes are the COLOUR_xxx and A_yyy constants\n defined in the Screen class.\n \"\"\"\n # Trim text to the buffer.\n if y < 0 or y >= self._buffer_height:\n return\n if x < 0:\n text = text[-x:]\n x = 0\n if x + len(text) >= self.width:\n text = text[:self.width - x]\n\n if len(text) > 0:\n for i, c in enumerate(text):\n if c != \" \" or not transparent:\n self._double_buffer[y][x + i] = (c, colour, attr, bg)\n\n @abstractmethod\n def _change_colours(self, colour, attr, bg):\n \"\"\"\n Change current colour if required.\n\n :param colour: New colour to use.\n :param attr: New attributes to use.\n :param bg: New background colour to use.\n \"\"\"\n\n @abstractmethod\n def _print_at(self, text, x, y):\n \"\"\"\n Print string at the required location.\n\n :param text: The text string to print.\n :param x: The x coordinate\n :param y: The Y coordinate\n \"\"\"\n\n @abstractmethod\n def _clear(self):\n \"\"\"\n Clear the window.\n \"\"\"\n\n @abstractmethod\n def _scroll(self):\n \"\"\"\n Scroll the window up one line.\n \"\"\"\n\n @abstractmethod\n def set_title(self, title):\n \"\"\"\n Set the title for this terminal/console session. This will typically\n change the text displayed in the window title bar.\n\n :param title: The title to be set.\n \"\"\"\n\nif sys.platform == \"win32\":\n import win32console\n import win32con\n\n class _WindowsScreen(_BufferedScreen):\n \"\"\"\n Windows screen implementation.\n \"\"\"\n\n # Virtual key code mapping.\n _KEY_MAP = {\n win32con.VK_ESCAPE: Screen.KEY_ESCAPE,\n win32con.VK_F1: Screen.KEY_F1,\n win32con.VK_F2: Screen.KEY_F2,\n win32con.VK_F3: Screen.KEY_F3,\n win32con.VK_F4: Screen.KEY_F4,\n win32con.VK_F5: Screen.KEY_F5,\n win32con.VK_F6: Screen.KEY_F6,\n win32con.VK_F7: Screen.KEY_F7,\n win32con.VK_F8: Screen.KEY_F8,\n win32con.VK_F9: Screen.KEY_F9,\n win32con.VK_F10: Screen.KEY_F10,\n win32con.VK_F11: Screen.KEY_F11,\n win32con.VK_F12: Screen.KEY_F12,\n win32con.VK_F13: Screen.KEY_F13,\n win32con.VK_F14: Screen.KEY_F14,\n win32con.VK_F15: Screen.KEY_F15,\n win32con.VK_F16: Screen.KEY_F16,\n win32con.VK_F17: Screen.KEY_F17,\n win32con.VK_F18: Screen.KEY_F18,\n win32con.VK_F19: Screen.KEY_F19,\n win32con.VK_F20: Screen.KEY_F20,\n win32con.VK_F21: Screen.KEY_F21,\n win32con.VK_F22: Screen.KEY_F22,\n win32con.VK_F23: Screen.KEY_F23,\n win32con.VK_F24: Screen.KEY_F24,\n win32con.VK_PRINT: Screen.KEY_PRINT_SCREEN,\n win32con.VK_INSERT: Screen.KEY_INSERT,\n win32con.VK_DELETE: Screen.KEY_DELETE,\n win32con.VK_HOME: Screen.KEY_HOME,\n win32con.VK_END: Screen.KEY_END,\n win32con.VK_LEFT: Screen.KEY_LEFT,\n win32con.VK_UP: Screen.KEY_UP,\n win32con.VK_RIGHT: Screen.KEY_RIGHT,\n win32con.VK_DOWN: Screen.KEY_DOWN,\n win32con.VK_PRIOR: Screen.KEY_PAGE_UP,\n win32con.VK_NEXT: Screen.KEY_PAGE_DOWN,\n win32con.VK_BACK: Screen.KEY_BACK,\n win32con.VK_TAB: Screen.KEY_TAB,\n }\n\n _EXTRA_KEY_MAP = {\n win32con.VK_NUMPAD0: Screen.KEY_NUMPAD0,\n win32con.VK_NUMPAD1: Screen.KEY_NUMPAD1,\n win32con.VK_NUMPAD2: Screen.KEY_NUMPAD2,\n win32con.VK_NUMPAD3: Screen.KEY_NUMPAD3,\n win32con.VK_NUMPAD4: Screen.KEY_NUMPAD4,\n win32con.VK_NUMPAD5: Screen.KEY_NUMPAD5,\n win32con.VK_NUMPAD6: Screen.KEY_NUMPAD6,\n win32con.VK_NUMPAD7: Screen.KEY_NUMPAD7,\n win32con.VK_NUMPAD8: Screen.KEY_NUMPAD8,\n win32con.VK_NUMPAD9: Screen.KEY_NUMPAD9,\n win32con.VK_MULTIPLY: Screen.KEY_MULTIPLY,\n win32con.VK_ADD: Screen.KEY_ADD,\n win32con.VK_SUBTRACT: Screen.KEY_SUBTRACT,\n win32con.VK_DECIMAL: Screen.KEY_DECIMAL,\n win32con.VK_DIVIDE: Screen.KEY_DIVIDE,\n win32con.VK_CAPITAL: Screen.KEY_CAPS_LOCK,\n win32con.VK_NUMLOCK: Screen.KEY_NUM_LOCK,\n win32con.VK_SCROLL: Screen.KEY_SCROLL_LOCK,\n win32con.VK_SHIFT: Screen.KEY_SHIFT,\n win32con.VK_CONTROL: Screen.KEY_CONTROL,\n win32con.VK_MENU: Screen.KEY_MENU,\n }\n\n # Foreground colour lookup table.\n _COLOURS = {\n Screen.COLOUR_BLACK: 0,\n Screen.COLOUR_RED: win32console.FOREGROUND_RED,\n Screen.COLOUR_GREEN: win32console.FOREGROUND_GREEN,\n Screen.COLOUR_YELLOW: (win32console.FOREGROUND_RED |\n win32console.FOREGROUND_GREEN),\n Screen.COLOUR_BLUE: win32console.FOREGROUND_BLUE,\n Screen.COLOUR_MAGENTA: (win32console.FOREGROUND_RED |\n win32console.FOREGROUND_BLUE),\n Screen.COLOUR_CYAN: (win32console.FOREGROUND_BLUE |\n win32console.FOREGROUND_GREEN),\n Screen.COLOUR_WHITE: (win32console.FOREGROUND_RED |\n win32console.FOREGROUND_GREEN |\n win32console.FOREGROUND_BLUE)\n }\n\n # Background colour lookup table.\n _BG_COLOURS = {\n Screen.COLOUR_BLACK: 0,\n Screen.COLOUR_RED: win32console.BACKGROUND_RED,\n Screen.COLOUR_GREEN: win32console.BACKGROUND_GREEN,\n Screen.COLOUR_YELLOW: (win32console.BACKGROUND_RED |\n win32console.BACKGROUND_GREEN),\n Screen.COLOUR_BLUE: win32console.BACKGROUND_BLUE,\n Screen.COLOUR_MAGENTA: (win32console.BACKGROUND_RED |\n win32console.BACKGROUND_BLUE),\n Screen.COLOUR_CYAN: (win32console.BACKGROUND_BLUE |\n win32console.BACKGROUND_GREEN),\n Screen.COLOUR_WHITE: (win32console.BACKGROUND_RED |\n win32console.BACKGROUND_GREEN |\n win32console.BACKGROUND_BLUE)\n }\n\n # Attribute lookup table\n _ATTRIBUTES = {\n 0: lambda x: x,\n Screen.A_BOLD: lambda x: x | win32console.FOREGROUND_INTENSITY,\n Screen.A_NORMAL: lambda x: x,\n # Windows console uses a bitmap where background is the top nibble,\n # so we can reverse by swapping nibbles.\n Screen.A_REVERSE: lambda x: ((x & 15) * 16) + ((x & 240) // 16),\n Screen.A_UNDERLINE: lambda x: x\n }\n\n def __init__(self, stdout, stdin, buffer_height):\n \"\"\"\n :param stdout: The win32console PyConsoleScreenBufferType object for\n stdout.\n :param stdin: The win32console PyConsoleScreenBufferType object for\n stdin.\n :param buffer_height: The buffer height for this window (if using\n scrolling).\n \"\"\"\n # Save off the screen details and set up the scrolling pad.\n info = stdout.GetConsoleScreenBufferInfo()['Window']\n width = info.Right - info.Left + 1\n height = info.Bottom - info.Top + 1\n super(_WindowsScreen, self).__init__(height, width, buffer_height)\n\n # Save off the console details.\n self._stdout = stdout\n self._stdin = stdin\n self._last_width = None\n self._last_height = None\n\n # Windows is limited to the ANSI colour set.\n self.colours = 8\n\n # Opt for compatibility with Linux by default\n self._map_all = False\n\n def map_all_keys(self, state):\n \"\"\"\n Switch on extended keyboard mapping for this Screen.\n\n :param state: Boolean flag where true means map all keys.\n\n Enabling this setting will allow Windows to tell you when any key\n is pressed, including metakeys (like shift and control) and whether\n the numeric keypad keys have been used.\n\n .. warning::\n\n Using this means your application will not be compatible across\n all platforms.\n \"\"\"\n self._map_all = state\n\n def get_event(self):\n \"\"\"\n Check for any event without waiting.\n \"\"\"\n # Look for a new event and consume it if there is one.\n if len(self._stdin.PeekConsoleInput(1)) > 0:\n event = self._stdin.ReadConsoleInput(1)[0]\n if (event.EventType == win32console.KEY_EVENT and\n event.KeyDown):\n # Translate keys into a KeyboardEvent object.\n key_code = ord(event.Char)\n if event.VirtualKeyCode in self._KEY_MAP:\n key_code = self._KEY_MAP[event.VirtualKeyCode]\n if (self._map_all and\n event.VirtualKeyCode in self._EXTRA_KEY_MAP):\n key_code = self._EXTRA_KEY_MAP[event.VirtualKeyCode]\n return KeyboardEvent(key_code)\n elif event.EventType == win32console.MOUSE_EVENT:\n # Translate into a MouseEvent object.\n button = 0\n if event.EventFlags == 0:\n # Button pressed - translate it.\n if (event.ButtonState &\n win32con.FROM_LEFT_1ST_BUTTON_PRESSED != 0):\n button |= MouseEvent.LEFT_CLICK\n if (event.ButtonState &\n win32con.RIGHTMOST_BUTTON_PRESSED != 0):\n button |= MouseEvent.RIGHT_CLICK\n elif event.EventFlags & win32con.DOUBLE_CLICK != 0:\n button |= MouseEvent.DOUBLE_CLICK\n\n return MouseEvent(event.MousePosition.X,\n event.MousePosition.Y,\n button)\n return None\n\n def has_resized(self):\n \"\"\"\n Check whether the screen has been re-sized.\n \"\"\"\n # Get the current Window dimensions and check them against last\n # time.\n re_sized = False\n info = self._stdout.GetConsoleScreenBufferInfo()['Window']\n width = info.Right - info.Left + 1\n height = info.Bottom - info.Top + 1\n if self._last_width is not None and (\n width != self._last_width or height != self._last_height):\n re_sized = True\n self._last_width = width\n self._last_height = height\n return re_sized\n\n def _change_colours(self, colour, attr, bg):\n \"\"\"\n Change current colour if required.\n\n :param colour: New colour to use.\n :param attr: New attributes to use.\n :param bg: New background colour to use.\n \"\"\"\n # Change attribute first as this will reset colours when swapping\n # modes.\n if colour != self._colour or attr != self._attr or self._bg != bg:\n new_attr = self._ATTRIBUTES[attr](\n self._COLOURS[colour] + self._BG_COLOURS[bg])\n self._stdout.SetConsoleTextAttribute(new_attr)\n self._attr = attr\n self._colour = colour\n self._bg = bg\n\n def _print_at(self, text, x, y):\n \"\"\"\n Print string at the required location.\n\n :param text: The text string to print.\n :param x: The x coordinate\n :param y: The Y coordinate\n \"\"\"\n # Move the cursor if necessary\n if x != self._x or y != self._y:\n self._stdout.SetConsoleCursorPosition(\n win32console.PyCOORDType(x, y))\n\n # Print the text at the required location and update the current\n # position.\n self._stdout.WriteConsole(text)\n self._x = x + len(text)\n self._y = y\n\n def _scroll(self):\n \"\"\"\n Scroll up by one line.\n \"\"\"\n # Scroll the visible screen up by one line\n info = self._stdout.GetConsoleScreenBufferInfo()['Window']\n rectangle = win32console.PySMALL_RECTType(info.Left, info.Top + 1,\n info.Right, info.Bottom)\n new_pos = win32console.PyCOORDType(0, info.Top)\n self._stdout.ScrollConsoleScreenBuffer(\n rectangle, None, new_pos, \" \", 0)\n\n def _clear(self):\n \"\"\"\n Clear the terminal.\n \"\"\"\n info = self._stdout.GetConsoleScreenBufferInfo()['Window']\n width = info.Right - info.Left + 1\n height = info.Bottom - info.Top + 1\n box_size = width * height\n self._stdout.FillConsoleOutputAttribute(\n 0, box_size, win32console.PyCOORDType(0, 0))\n self._stdout.FillConsoleOutputCharacter(\n u\" \", box_size, win32console.PyCOORDType(0, 0))\n self._stdout.SetConsoleCursorPosition(\n win32console.PyCOORDType(0, 0))\n\n def set_title(self, title):\n \"\"\"\n Set the title for this terminal/console session. This will\n typically change the text displayed in the window title bar.\n\n :param title: The title to be set.\n \"\"\"\n win32console.SetConsoleTitle(title)\n\nelse:\n # UNIX compatible platform - use curses\n import curses\n\n class _CursesScreen(_BufferedScreen):\n \"\"\"\n Curses screen implementation.\n \"\"\"\n\n # Virtual key code mapping.\n _KEY_MAP = {\n 27: Screen.KEY_ESCAPE,\n curses.KEY_F1: Screen.KEY_F1,\n curses.KEY_F2: Screen.KEY_F2,\n curses.KEY_F3: Screen.KEY_F3,\n curses.KEY_F4: Screen.KEY_F4,\n curses.KEY_F5: Screen.KEY_F5,\n curses.KEY_F6: Screen.KEY_F6,\n curses.KEY_F7: Screen.KEY_F7,\n curses.KEY_F8: Screen.KEY_F8,\n curses.KEY_F9: Screen.KEY_F9,\n curses.KEY_F10: Screen.KEY_F10,\n curses.KEY_F11: Screen.KEY_F11,\n curses.KEY_F12: Screen.KEY_F12,\n curses.KEY_F13: Screen.KEY_F13,\n curses.KEY_F14: Screen.KEY_F14,\n curses.KEY_F15: Screen.KEY_F15,\n curses.KEY_F16: Screen.KEY_F16,\n curses.KEY_F17: Screen.KEY_F17,\n curses.KEY_F18: Screen.KEY_F18,\n curses.KEY_F19: Screen.KEY_F19,\n curses.KEY_F20: Screen.KEY_F20,\n curses.KEY_F21: Screen.KEY_F21,\n curses.KEY_F22: Screen.KEY_F22,\n curses.KEY_F23: Screen.KEY_F23,\n curses.KEY_F24: Screen.KEY_F24,\n curses.KEY_PRINT: Screen.KEY_PRINT_SCREEN,\n curses.KEY_IC: Screen.KEY_INSERT,\n curses.KEY_DC: Screen.KEY_DELETE,\n curses.KEY_HOME: Screen.KEY_HOME,\n curses.KEY_END: Screen.KEY_END,\n curses.KEY_LEFT: Screen.KEY_LEFT,\n curses.KEY_UP: Screen.KEY_UP,\n curses.KEY_RIGHT: Screen.KEY_RIGHT,\n curses.KEY_DOWN: Screen.KEY_DOWN,\n curses.KEY_PPAGE: Screen.KEY_PAGE_UP,\n curses.KEY_NPAGE: Screen.KEY_PAGE_DOWN,\n curses.KEY_BACKSPACE: Screen.KEY_BACK,\n 9: Screen.KEY_TAB,\n # Terminals translate keypad keys, so no need for a special\n # mapping here.\n\n # Terminals don't transmit meta keys (like control, shift, etc), so\n # there's no translation for them either.\n }\n\n def __init__(self, win, height=200):\n \"\"\"\n :param win: The window object as returned by the curses wrapper\n method.\n :param height: The height of the screen buffer to be used.\n \"\"\"\n # Save off the screen details.\n super(_CursesScreen, self).__init__(\n win.getmaxyx()[0], win.getmaxyx()[1], height)\n self._screen = win\n self._screen.keypad(1)\n\n # Set up basic colour schemes.\n self.colours = curses.COLORS\n\n # Disable the cursor.\n curses.curs_set(0)\n\n # Non-blocking key checks.\n self._screen.nodelay(1)\n\n # Set up signal handler for screen resizing.\n self._re_sized = False\n signal.signal(signal.SIGWINCH, self._resize_handler)\n\n # Enable mouse events\n curses.mousemask(curses.ALL_MOUSE_EVENTS |\n curses.REPORT_MOUSE_POSITION)\n\n # Lookup the necessary escape codes in the terminfo database.\n self._move_y_x = curses.tigetstr(\"cup\")\n self._fg_color = curses.tigetstr(\"setaf\")\n self._bg_color = curses.tigetstr(\"setab\")\n if curses.tigetflag(\"hs\"):\n self._start_title = curses.tigetstr(\"tsl\").decode(\"utf-8\")\n self._end_title = curses.tigetstr(\"fsl\").decode(\"utf-8\")\n else:\n self._start_title = self._end_title = None\n self._a_normal = curses.tigetstr(\"sgr0\").decode(\"utf-8\")\n self._a_bold = curses.tigetstr(\"bold\").decode(\"utf-8\")\n self._a_reverse = curses.tigetstr(\"rev\").decode(\"utf-8\")\n self._a_underline = curses.tigetstr(\"smul\").decode(\"utf-8\")\n self._clear_screen = curses.tigetstr(\"clear\").decode(\"utf-8\")\n\n # Conversion from Screen attributes to curses equivalents.\n self._ATTRIBUTES = {\n Screen.A_BOLD: self._a_bold,\n Screen.A_NORMAL: self._a_normal,\n Screen.A_REVERSE: self._a_reverse,\n Screen.A_UNDERLINE: self._a_underline\n }\n\n # We'll actually break out into low-level output, so flush any\n # high level buffers now.\n self._screen.refresh()\n\n def _resize_handler(self, *_):\n \"\"\"\n Window resize signal handler. We don't care about any of the\n parameters passed in beyond the object reference.\n \"\"\"\n curses.endwin()\n curses.initscr()\n self._re_sized = True\n\n def _scroll(self):\n \"\"\"\n Scroll the Screen up one line.\n \"\"\"\n print(curses.tparm(\n self._move_y_x, self.height - 1, 0).decode(\"utf-8\"))\n\n def _clear(self):\n \"\"\"\n Clear the Screen of all content.\n \"\"\"\n sys.stdout.write(self._clear_screen)\n sys.stdout.flush()\n\n def refresh(self):\n \"\"\"\n Refresh the screen.\n \"\"\"\n super(_CursesScreen, self).refresh()\n try:\n sys.stdout.flush()\n except IOError:\n pass\n\n def get_event(self):\n \"\"\"\n Check for an event without waiting.\n \"\"\"\n key = self._screen.getch()\n if key == curses.KEY_RESIZE:\n # Handle screen resize\n self._re_sized = True\n elif key == curses.KEY_MOUSE:\n # Handle a mouse event\n _, x, y, _, bstate = curses.getmouse()\n buttons = 0\n # Some Linux modes only report clicks, so check for any button\n # down or click events.\n if (bstate & curses.BUTTON1_PRESSED != 0 or\n bstate & curses.BUTTON1_CLICKED != 0):\n buttons |= MouseEvent.LEFT_CLICK\n if (bstate & curses.BUTTON3_PRESSED != 0 or\n bstate & curses.BUTTON3_CLICKED != 0):\n buttons |= MouseEvent.RIGHT_CLICK\n if bstate & curses.BUTTON1_DOUBLE_CLICKED != 0:\n buttons |= MouseEvent.DOUBLE_CLICK\n return MouseEvent(x, y, buttons)\n else:\n # Handle a genuine key press.\n if key in self._KEY_MAP:\n return KeyboardEvent(self._KEY_MAP[key])\n elif key != -1:\n return KeyboardEvent(key)\n return None\n\n def has_resized(self):\n \"\"\"\n Check whether the screen has been re-sized.\n \"\"\"\n re_sized = self._re_sized\n self._re_sized = False\n return re_sized\n\n def _change_colours(self, colour, attr, bg):\n \"\"\"\n Change current colour if required.\n\n :param colour: New colour to use.\n :param attr: New attributes to use.\n :param bg: New background colour to use.\n \"\"\"\n # Change attribute first as this will reset colours when swapping\n # modes.\n if attr != self._attr:\n sys.stdout.write(self._a_normal)\n if attr != 0:\n sys.stdout.write(self._ATTRIBUTES[attr])\n self._attr = attr\n self._colour = None\n self._bg = None\n\n # Now swap colours if required.\n if colour != self._colour:\n sys.stdout.write(curses.tparm(\n self._fg_color, colour).decode(\"utf-8\"))\n self._colour = colour\n if bg != self._bg:\n sys.stdout.write(curses.tparm(\n self._bg_color, bg).decode(\"utf-8\"))\n self._bg = bg\n\n def _print_at(self, text, x, y):\n \"\"\"\n Print string at the required location.\n\n :param text: The text string to print.\n :param x: The x coordinate\n :param y: The Y coordinate\n \"\"\"\n # Move the cursor if necessary\n msg = \"\"\n if x != self._x or y != self._y:\n msg += curses.tparm(self._move_y_x, y, x).decode(\"utf-8\")\n\n msg += text\n\n # Print the text at the required location and update the current\n # position.\n sys.stdout.write(msg)\n\n def set_title(self, title):\n \"\"\"\n Set the title for this terminal/console session. This will\n typically change the text displayed in the window title bar.\n\n :param title: The title to be set.\n \"\"\"\n if self._start_line is not None:\n sys.stdout.write(\"{}{}{}\".format(self._start_title, title,\n self._end_title))\n\n class _BlessedScreen(_BufferedScreen):\n \"\"\"\n Blessed screen implementation. This is deprecated as it doesn't support\n mouse input.\n \"\"\"\n\n #: Conversion from Screen attributes to blessed equivalents.\n ATTRIBUTES = {\n Screen.A_BOLD: lambda term: term.bold,\n Screen.A_NORMAL: lambda term: \"\",\n Screen.A_REVERSE: lambda term: term.reverse,\n Screen.A_UNDERLINE: lambda term: term.underline\n }\n\n def __init__(self, terminal, height):\n \"\"\"\n :param terminal: The blessed Terminal object.\n :param height: The buffer height for this window (if using\n scrolling).\n \"\"\"\n # Save off the screen details and se up the scrolling pad.\n super(_BlessedScreen, self).__init__(\n terminal.height, terminal.width, height)\n\n # Save off terminal.\n self._terminal = terminal\n\n # Set up basic colour schemes.\n self.colours = terminal.number_of_colors\n\n # Set up signal handler for screen resizing.\n self._re_sized = False\n signal.signal(signal.SIGWINCH, self._resize_handler)\n\n def _resize_handler(self, *_):\n \"\"\"\n Window resize signal handler. We don't care about any of the\n parameters passed in beyond the object reference.\n \"\"\"\n self._re_sized = True\n\n def refresh(self):\n \"\"\"\n Refresh the screen.\n \"\"\"\n # Flush screen buffer to get all updates after doing the common\n # processing. Exact timing of the signal can interrupt the\n # flush, raising an EINTR IOError, which we can safely ignore.\n super(_BlessedScreen, self).refresh()\n try:\n sys.stdout.flush()\n except IOError:\n pass\n\n def get_event(self):\n \"\"\"\n Check for any event without waiting.\n\n .. warning::\n\n Blessed does not support mouse events.\n \"\"\"\n key = self._terminal.inkey(timeout=0)\n return KeyboardEvent(ord(key)) if key != \"\" else None\n\n def has_resized(self):\n \"\"\"\n Check whether the screen has been re-sized.\n \"\"\"\n re_sized = self._re_sized\n self._re_sized = False\n return re_sized\n\n def _change_colours(self, colour, attr, bg):\n \"\"\"\n Change current colour if required.\n\n :param colour: New colour to use.\n :param attr: New attributes to use.\n :param bg: New background colour to use.\n \"\"\"\n # Change attribute first as this will reset colours when swapping\n # modes.\n if attr != self._attr:\n sys.stdout.write(\n self._terminal.normal + self._terminal.on_color(0))\n if attr != 0:\n sys.stdout.write(self.ATTRIBUTES[attr](self._terminal))\n self._attr = attr\n self._colour = None\n\n # Now swap colours if required.\n if colour != self._colour:\n sys.stdout.write(self._terminal.color(colour))\n self._colour = colour\n if bg != self._bg:\n sys.stdout.write(self._terminal.on_color(bg))\n self._bg = bg\n\n def _print_at(self, text, x, y):\n \"\"\"\n Print string at the required location.\n\n :param text: The text string to print.\n :param x: The x coordinate\n :param y: The Y coordinate\n \"\"\"\n # Move the cursor if necessary\n msg = \"\"\n if x != self._x or y != self._y:\n msg += self._terminal.move(y, x)\n\n msg += text\n\n # Print the text at the required location and update the current\n # position.\n sys.stdout.write(msg)\n self._x = x + len(text)\n self._y = y\n\n def _scroll(self):\n \"\"\"\n Scroll up by one line.\n \"\"\"\n print(self._terminal.move(self.height - 1, 0))\n\n def _clear(self):\n \"\"\"\n Clear the terminal.\n \"\"\"\n sys.stdout.write(self._terminal.clear())\n\n def set_title(self, title):\n \"\"\"\n Set the title for this terminal/console session. This will\n typically change the text displayed in the window title bar.\n\n :param title: The title to be set.\n \"\"\"\n pass" } ]
3
tianyunzqs/crawler
https://github.com/tianyunzqs/crawler
55221dd3e68d4f18419cfe55741ccc1be4e6a138
0a34504a2838fdedb50fbdb6080c9083e04f004d
09dff7c03709d3eb6c7ca664390b367ba263635c
refs/heads/master
2022-05-30T02:15:51.714353
2022-05-05T06:03:58
2022-05-05T06:03:58
100,120,822
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5141921639442444, "alphanum_fraction": 0.5229257345199585, "avg_line_length": 21.365854263305664, "blob_id": "508f0023b5d7191de9954cd0ebe4363623f65320", "content_id": "90ba39807488b43ebde78aba19b5f8869220a9e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/free_proxy_ip_pool/www_data5u_com.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\n无忧代理 http://www.data5u.com/\n\n'''\n\n\nclass WWW_DATA5U_COM(AbsFreeProxyBase):\n\n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式如下\n IP、端口、匿名度、类型(http/https)、国家、省市、运营商、响应速度、最后验证时间\n [\n [...]\n [...]\n ]\n \"\"\"\n rows = soup.select('.l2')\n result = []\n for row in rows:\n col = [n.string.strip() for n in row.find_all('li')]\n col and result.append(col)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n result.append(ProxyModel(item[4], item[0], item[1], item[2]))\n return result" }, { "alpha_fraction": 0.5274261832237244, "alphanum_fraction": 0.547468364238739, "avg_line_length": 25.33333396911621, "blob_id": "b1bb262e9172715c9788466dd19d1fcdb688facc", "content_id": "5d364d52f84f5b46b20382c5ba96668d7f020fe5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1014, "license_type": "no_license", "max_line_length": 73, "num_lines": 36, "path": "/free_proxy_ip_pool/ip_yqie_com.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\n免费代理IP http://ip.yqie.com/ipproxy.htm\n'''\n\n\nclass IP_YQIE_COM(AbsFreeProxyBase):\n\n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 采集到的数据格式如下\n '183.148.153.200', '9999', '浙江台州', '高匿', 'HTTPS', '1分钟'\n \"\"\"\n regex = re.compile( r'(?<=<td>)(.*)(?=</td>)')\n container = soup.select('.divcenter tr')\n result = []\n for text in [str(n) for n in container]:\n item = regex.findall(text)\n item and result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n result.append(ProxyModel(item[4], item[0], item[1], item[3]))\n return result\n" }, { "alpha_fraction": 0.7065462470054626, "alphanum_fraction": 0.727990984916687, "avg_line_length": 34.439998626708984, "blob_id": "b7315d3e7b22e7d5e8bfb1f716c8f18c78bad83e", "content_id": "c9f1b79ee76b4bfd1766f0b7fe0ab09f1600769a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 886, "license_type": "no_license", "max_line_length": 54, "num_lines": 25, "path": "/free_proxy_ip_pool/__init__.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from urllib.parse import urlparse\nfrom .www_66ip_cn import WWW_66IP_CN\nfrom .ip_ihuan_me import IP_IHUAN_ME\nfrom .ip_yqie_com import IP_YQIE_COM\nfrom .www_89ip_cn import WWW_89IP_CN\nfrom .www_data5u_com import WWW_DATA5U_COM\nfrom .www_goubanjia_com import WWW_GOUBANJIA_COM\nfrom .www_ip3366_net import WWW_IP3366_NET\nfrom .www_kuaidaili_com import WWW_KUAIDAILI_COM\nfrom .www_superfastip_com import WWW_SUPERFASTIP_COM\nfrom .www_xicidaili_com import WWW_XICIDAILI_COM\nfrom .www_xiladaili_com import WWW_XILADAILI_COM\nfrom .www_xsdaili_com import WWW_XSDAILI_COM\nfrom .www_zdaye_com import WWW_ZDAYE_COM\n\n\nclass ProxyFactory:\n\n def create(self, url, code='utf-8', **kwargs):\n netloc = self.__get_netloc(url)\n return eval(netloc)(url, code, **kwargs)\n\n def __get_netloc(self, url):\n result = urlparse(url)\n return result.netloc.replace('.', '_').upper()\n" }, { "alpha_fraction": 0.45570865273475647, "alphanum_fraction": 0.5078740119934082, "avg_line_length": 25.05128288269043, "blob_id": "503b472f0cb130291ebf7a6324e7887973e42c58", "content_id": "1e57b9dc6e2052650023e56ee2f871f1d461a0f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 96, "num_lines": 39, "path": "/free_proxy_ip_pool/www_66ip_cn.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\n66免费代理网 \nhttp://www.66ip.cn/mo.php?sxb=&tqsl=100&port=&export=&ktip=&sxa=&submit=%CC%E1++%C8%A1&textarea=\n'''\n\n\nclass WWW_66IP_CN(AbsFreeProxyBase):\n\n # 初始化\n def __init__(self, url, code='gb2312', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 采集到的数据格式如下\n [\n ('139.199.7.44', '8118'),\n ('212.174.32.244', '80'),\n ('183.129.207.80', '12844')\n ...\n ]\n \"\"\"\n result, regex = [], re.compile(r'([\\d.]+):(\\d+)(?=<br\\s*/>)')\n for item in regex.findall(str(soup)):\n result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for host, port in data:\n result.append(ProxyModel('http', host, port))\n return result\n" }, { "alpha_fraction": 0.5342763662338257, "alphanum_fraction": 0.5484222173690796, "avg_line_length": 24.52777862548828, "blob_id": "3626b0a3a58e221d9bd14707551f2b299775ea5d", "content_id": "fc1ea0e15dda874b4314227ab7396b0925d20d20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 73, "num_lines": 36, "path": "/free_proxy_ip_pool/www_ip3366_net.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n\n'''\n云代理 http://www.ip3366.net/\n'''\n\n\nclass WWW_IP3366_NET(AbsFreeProxyBase):\n\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式如下\n 代理IP地址 \t端口 \t匿名度 \t类型(HTTPS/HTTP) \tget/post支持 \t位置 \t响应速度 \t最后验证时间\n \"\"\"\n regex = re.compile(r'(?<=<td>)(.*)(?=</td>)')\n rows = soup.select('#list tr')\n result = []\n for row in [str(n) for n in rows]:\n item = regex.findall(row)\n item and result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n result.append(ProxyModel(item[3], item[0], item[1], item[2]))\n return result\n" }, { "alpha_fraction": 0.5450000166893005, "alphanum_fraction": 0.550000011920929, "avg_line_length": 26.054054260253906, "blob_id": "4e5ceed9d1078011e779af4d9765eea823859f1f", "content_id": "b77a42285b169e65ff7d4eaa37205a4d8f46cbaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1116, "license_type": "no_license", "max_line_length": 72, "num_lines": 37, "path": "/free_proxy_ip_pool/ip_ihuan_me.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\n小幻HTTP代理 https://ip.ihuan.me/\n'''\n\n\nclass IP_IHUAN_ME(AbsFreeProxyBase):\n \n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式:\n IP地址\t端口\t地理位置\t运营商\tHTTPS(支持/不支持)\tPOST(支持/不支持)\t匿名度\t访问速度\t入库时间\t最后检测\n \"\"\"\n rows = soup.select('.table-bordered tr')\n result = []\n for row in rows:\n cols = row.select('td')\n item = [re.sub(r'\\s', \"\", c.get_text()) for c in cols]\n item and result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n scheme = 'http and https' if item[4] == '支持' else 'http'\n result.append(ProxyModel(scheme, item[0], item[1], item[6]))\n return result" }, { "alpha_fraction": 0.5272904634475708, "alphanum_fraction": 0.5311890840530396, "avg_line_length": 25.30769157409668, "blob_id": "b7af408a011f839cdab0d6bb9c1f59e420410fc7", "content_id": "968b487d7b2ef494137922fa4d856dd546df27aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 76, "num_lines": 39, "path": "/free_proxy_ip_pool/www_goubanjia_com.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\nhttp://www.goubanjia.com/\n全网代理IP \n'''\n\n\nclass WWW_GOUBANJIA_COM(AbsFreeProxyBase):\n\n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式\n IP:PORT \t匿名度 \t类型 \tIP归属地 \t运营商 \t响应速度 \t最后验证时间 \t存活时间\n \"\"\"\n rows = soup.select('.table-hover tr')\n result = []\n for r in rows:\n for p in r.find_all('p'):\n p.extract()\n cols = [re.sub(r'\\s', \"\", c.get_text()) for c in r.select('td')]\n cols and result.append(cols)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n host, port = re.search(r'([\\d.]+):(\\d+)', item[0]).groups()\n result.append(ProxyModel(item[2], host, port, item[1]))\n return result\n" }, { "alpha_fraction": 0.5377358198165894, "alphanum_fraction": 0.544025182723999, "avg_line_length": 24.783782958984375, "blob_id": "f783672fd8f829d2a8d70ae2d584bd0c979496af", "content_id": "b794eb469dbea6eecf9ccfeb8bd748507d5d67a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "no_license", "max_line_length": 73, "num_lines": 37, "path": "/free_proxy_ip_pool/www_superfastip_com.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\nhttp://www.superfastip.com/welcome/freeIP\n'''\n\n\nclass WWW_SUPERFASTIP_COM(AbsFreeProxyBase):\n\n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式:\n \"ip\", \"端口\", \"隐私程度\", \"类型\", \"位置\", \"响应速度\", \"最后验证时间\"\n \"\"\"\n regex = re.compile(r'(?<=\\s<td>)(.*)(?=</td>)')\n rows = soup.select('table:nth-last-child(2) tr')\n result = []\n for row in [str(n) for n in rows]:\n item = regex.findall(row)\n item and result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n result.append(ProxyModel(item[3], item[0], item[1], item[2]))\n return result\n" }, { "alpha_fraction": 0.4830157458782196, "alphanum_fraction": 0.4987572431564331, "avg_line_length": 39.233333587646484, "blob_id": "ff445453fc533f102d7f073d77159b14b7ac8604", "content_id": "1880776c64908d0897671d674ab0413837bef5a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1213, "license_type": "no_license", "max_line_length": 111, "num_lines": 30, "path": "/crawler_example/crawler.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nfrom urllib import request\n\nfor page in range(1, 2):\n print(page)\n url = 'http://www.qiushibaike.com/hot/page/' + str(page)\n user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'\n headers = {'User-Agent': user_agent}\n try:\n req = request.Request(url, headers=headers)\n with request.urlopen(req, timeout=5) as response:\n content = response.read().decode('utf-8')\n print(content)\n pattern = re.compile(\n '<div class=\"article block untagged mb15.*?id=(.*?)>.*?<div.*?<a.*?<img.*?<a.*?<h2>(.*?)</h2>'\\\n '.*?<a.*?<div.*?<span>(.*?)</span>.*?<!-- 图片或gif -->.*?<div(.*?)<span.*?number\">(.*?)</i>'\\\n '.*?<i class=\"number\">(.*?)</i>',\n re.S)\n items = re.findall(pattern, content)\n for item in items:\n if not re.search(\"thumb\", item[3]):\n print(item[0].replace(\"'\", \"\"), item[1].strip(), item[2].strip(), item[4], item[5])\n except request.URLError as e:\n if hasattr(e, \"code\"):\n print(e.code)\n if hasattr(e, \"reason\"):\n print(e.reason)\n" }, { "alpha_fraction": 0.4538690447807312, "alphanum_fraction": 0.4538690447807312, "avg_line_length": 17.69444465637207, "blob_id": "460b8f755ca9de0aa29b68e6415f979ba6ca5098", "content_id": "651a6a5b703c1bf6bcaf1ffb306e88f5bad9a059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 726, "license_type": "no_license", "max_line_length": 81, "num_lines": 36, "path": "/free_proxy_ip_pool/model.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "class ProxyModel:\n def __init__(self, scheme: str, host: int, port: int, anonymity: str = None):\n \"\"\"\n 格式\n Arguments:\n scheme {str} -- 协议\n host {int} -- 地址\n port {int} -- 端口\n anonymity {str} -- 匿名度\n \"\"\"\n self.scheme = scheme\n self.host = host\n self.port = port\n self.anonymity = anonymity\n\n # 获取IP地址\n @property\n def add(self) -> str:\n pass\n\n # 国籍\n @property\n def country(self) -> str:\n pass\n\n # 地区\n def city(self) -> str:\n pass\n\n # 运营商\n def isp(self) -> str:\n pass\n\n # 验证有效性\n def check(self):\n pass" }, { "alpha_fraction": 0.5203768014907837, "alphanum_fraction": 0.5515121221542358, "avg_line_length": 45.689815521240234, "blob_id": "51840d099721cb3e5f2da98b8b5bd76b9d61c1b9", "content_id": "b5f21f7c158b6581c1f01b22e52f9aaeedeaf207", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10663, "license_type": "no_license", "max_line_length": 120, "num_lines": 216, "path": "/crawler_example/train_station_spider.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2021/9/9 22:17\n# @Author : tianyunzqs\n# @Description :\n\nimport re\nimport time\nimport json\nimport requests\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\ndef load_train_stations(path):\n all_station_name, done_province, done_city = [], [], []\n with open(path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n line = re.sub(r'\\\\x1e', '', line).strip()\n line = json.loads(line)\n all_station_name.append(line['station_name'])\n if line['province'] not in done_province:\n done_province.append(line['province'])\n if line['city'] not in done_city:\n done_city.append(line['city'])\n return all_station_name, done_province[:-1], done_city[:-1]\n\n\nstandard_key_name = {\n '中文名': 'chinese_name',\n '改建时间': 'build_time',\n '外文名': 'foreign_name',\n '隶属': 'belong',\n '地址': 'address',\n '邮编': 'postcode',\n}\n\n\ndef get_alive_ip(test_url):\n cnt, max_retries_count = 0, 50\n while True:\n try:\n ip_info = json.loads(requests.get('https://ip.jiangxianli.com/api/proxy_ip').text)['data']\n respond = requests.get(test_url,\n proxies={\"http\": '{0}:{1}'.format(ip_info['ip'], ip_info['port'])},\n timeout=2)\n if respond.status_code == 404:\n return False, ip_info\n cnt += 1\n print('请求 {0} 次 获得可用ip:{1}:{2}'.format(cnt, ip_info['ip'], ip_info['port']))\n return True, ip_info\n except:\n if cnt > max_retries_count:\n raise Exception('Max retries exceeded')\n\n# alive_ip = [\n# '196.10.68.2:80', '222.74.202.230:8080', '222.74.202.234:8081', '51.91.157.66:80', '64.124.38.141:8080',\n# '108.61.26.164:8080', '206.189.89.122:3128', '222.249.238.138:8080', '183.47.237.251:80',\n# '209.141.56.127:80', '153.122.72.63:80'\n# ]\n# alive_ip = [\n# '197.253.7.201:80', '45.152.188.39:3128', '121.78.139.77:80', '136.243.211.104:80', '52.20.205.11:80'\n# ]\n\n\nall_station_names, done_provinces, done_cities = load_train_stations('train_stations.txt')\nprint(all_station_names)\nprint(done_provinces)\nprint(done_cities)\n\n\n_, ip_port = get_alive_ip('http://huochezhan.114piaowu.com')\nchrome_options = Options()\nchrome_options.add_argument('--no-sandbox') # 让Chrome在root权限下跑\nchrome_options.add_argument('--disable-dev-shm-usage')\nchrome_options.add_argument('window-size=1920x3000') # 指定浏览器分辨率\nchrome_options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug\nchrome_options.add_argument('--hide-scrollbars') # 隐藏滚动条, 应对一些特殊页面\nchrome_options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度\nchrome_options.add_argument('--headless') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败\nchrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])\nchrome_options.add_argument(('--proxy-server=http://{0}:{1}'.format(ip_port['ip'], ip_port['port'])))\n\nchrome_options2 = Options()\nchrome_options2.add_argument('--no-sandbox') # 让Chrome在root权限下跑\nchrome_options2.add_argument('--disable-dev-shm-usage')\nchrome_options2.add_argument('window-size=1920x3000') # 指定浏览器分辨率\nchrome_options2.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug\nchrome_options2.add_argument('--hide-scrollbars') # 隐藏滚动条, 应对一些特殊页面\nchrome_options2.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度\nchrome_options2.add_argument('--headless') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败\nchrome_options2.add_experimental_option('excludeSwitches', ['enable-automation'])\nchrome_options2.add_argument(('--proxy-server=http://{0}:{1}'.format(ip_port['ip'], ip_port['port'])))\n\nchrome_options3 = Options()\nchrome_options3.add_argument('--no-sandbox') # 让Chrome在root权限下跑\nchrome_options3.add_argument('--disable-dev-shm-usage')\nchrome_options3.add_argument('window-size=1920x3000') # 指定浏览器分辨率\nchrome_options3.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug\nchrome_options3.add_argument('--hide-scrollbars') # 隐藏滚动条, 应对一些特殊页面\nchrome_options3.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度\nchrome_options3.add_argument('--headless') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败\nchrome_options3.add_experimental_option('excludeSwitches', ['enable-automation'])\nchrome_options3.add_argument(('--proxy-server=http://{0}:{1}'.format(ip_port['ip'], ip_port['port'])))\n\nbrowser = webdriver.Chrome(chrome_options=chrome_options)\nbrowser2 = webdriver.Chrome(chrome_options=chrome_options2)\nbrowser3 = webdriver.Chrome(chrome_options=chrome_options3)\n\nwhile True:\n try:\n browser.get('http://huochezhan.114piaowu.com')\n all_province_stations = browser.find_element_by_id('content').find_elements_by_tag_name('dd')\n break\n except:\n _, ip_port = get_alive_ip('http://huochezhan.114piaowu.com')\n chrome_options.add_argument(('--proxy-server=http://{0}:{1}'.format(ip_port['ip'], ip_port['port'])))\n browser = webdriver.Chrome(chrome_options=chrome_options)\n print('browser---{0}:{1}'.format(ip_port['ip'], ip_port['port']))\n\nwith open('train_stations.txt', 'a', encoding='utf-8') as f:\n for province in all_province_stations:\n province_name = province.find_element_by_tag_name(\"font\").text\n if province_name in done_provinces:\n continue\n print('province_name: ', province_name)\n all_city_stations = province.find_elements_by_tag_name(\"span\")\n for city in all_city_stations:\n city_sites = city.find_elements_by_tag_name(\"a\")\n for city_site in city_sites:\n city_name = city_site.text\n if city_name in done_cities:\n continue\n print('city_name: ', city_name)\n href = city_site.get_attribute(\"href\")\n time.sleep(0.1)\n\n city_flag = True\n while True:\n try:\n browser2.get(href)\n stations_elems = browser2.find_element_by_class_name(\"train_list\").find_element_by_tag_name(\n \"ul\").find_elements_by_tag_name(\"li\")\n break\n except:\n city_flag, ip_port = get_alive_ip(href)\n if not city_flag:\n break\n chrome_options2.add_argument(('--proxy-server=http://{0}:{1}'.format(\n ip_port['ip'], ip_port['port'])))\n browser2 = webdriver.Chrome(chrome_options=chrome_options2)\n print('browser2---{0}:{1}'.format(ip_port['ip'], ip_port['port']))\n if not city_flag:\n continue\n\n for st in stations_elems:\n station_name = st.find_element_by_tag_name(\"dt\").find_element_by_tag_name(\"a\").text\n if station_name in all_station_names:\n continue\n station_href = st.find_element_by_tag_name(\"dt\").find_element_by_tag_name(\"a\").get_attribute('href')\n is_valid_ticket = st.find_element_by_tag_name(\"dd\").find_elements_by_tag_name(\"p\")[0].text\n if re.search('未开通', is_valid_ticket):\n is_valid_ticket = 0\n else:\n is_valid_ticket = 1\n time.sleep(0.1)\n\n station_flag = True\n while True:\n try:\n browser3.get(station_href + '_introduce')\n about = browser3.find_element_by_class_name('about')\n break\n except:\n station_flag, ip_port = get_alive_ip(station_href + '_introduce')\n if not station_flag:\n break\n chrome_options3.add_argument(('--proxy-server=http://{0}:{1}'.format(\n ip_port['ip'], ip_port['port'])))\n browser3 = webdriver.Chrome(chrome_options=chrome_options3)\n print('browser3---{0}:{1}'.format(ip_port['ip'], ip_port['port']))\n if not station_flag:\n continue\n\n pic_url = about.find_element_by_tag_name('img').get_attribute('src')\n try:\n introduce = about.find_element_by_tag_name('p').text\n except:\n introduce = about.text\n introduce = re.sub(r'^[\\s\\S]{0,15}介绍[。,,]?', '', introduce)\n introduce = re.sub('中文名\\n[\\s\\S]*$', '', introduce).strip()\n introduce = re.sub('暂无', '', introduce).strip()\n attrs = about.find_element_by_tag_name('ul').find_elements_by_tag_name('li')\n attrs_json = dict()\n for attr in attrs:\n key = attr.find_element_by_tag_name('span').text.strip()\n value = re.sub(r'^{0}\\s*'.format(key), '', attr.text).strip()\n if key in standard_key_name:\n attrs_json[standard_key_name[key]] = value\n\n station_info = {\n 'province': province_name,\n 'city': city_name,\n 'station_name': station_name,\n 'pic_url': pic_url,\n 'is_valid_ticket': is_valid_ticket,\n 'introduce': introduce,\n }\n station_info.update(attrs_json)\n print(station_info)\n f.write(json.dumps(station_info, ensure_ascii=False))\n f.write('\\n')\n f.flush()\n # result.append(station_info)\n\n# data = pd.DataFrame(result)\n# data.to_csv('train_stations.csv', index=False)\n" }, { "alpha_fraction": 0.47134503722190857, "alphanum_fraction": 0.4851461946964264, "avg_line_length": 42.181819915771484, "blob_id": "30d6db33eb97f574b779b26b6be53dbd1820eaab", "content_id": "bde1b60f379e3fab84e023a4628ca7fa18c607be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4357, "license_type": "no_license", "max_line_length": 119, "num_lines": 99, "path": "/zhihu/crawler_zhihu_whole_more.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nimport re\nfrom urllib import request, parse\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\n\ndef get_grade(url):\n # 匿名爬虫\n driver = webdriver.PhantomJS(executable_path='E:/phantomjs/phantomjs-2.1.1-windows/bin/phantomjs.exe')\n driver.get(url)\n data = driver.page_source\n return data, driver\n\n\n# keyword_list = ['svm', '支持向量机', 'libsvm']\n# keyword_list = ['java']\nkeyword_list = ['核函数', 'kernel', '径向基函数', 'sigmoid', 'tanh', 'rbf']\nfout = open(\"E:/python_file/kernel.txt\", \"w\", encoding=\"utf-8\")\nfor keyword in keyword_list:\n print(keyword)\n # 将中文转换为浏览器可识别字符(HTTP协议是ASCII编码的形式)\n url = 'https://www.zhihu.com/search?type=content&q=' + parse.quote(keyword)\n user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) ' \\\n 'Chrome/39.0.2171.95 Safari/537.36'\n headers = {'User-Agent': user_agent}\n keyword_question_url_list = {}\n try:\n content, driver = get_grade(url)\n\n cnt = 0\n while True:\n try:\n cnt += 1\n print(cnt)\n if cnt > 6:\n break\n aaa = driver.find_element_by_css_selector('.zg-btn-white.zu-button-more')\n except:\n break\n time.sleep(10)\n aaa.click()\n time.sleep(10)\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n all_div = soup.find_all('li', attrs={'class': re.compile('item clearfix.*?')})\n question_url_list = {}\n for e_div in all_div:\n title = e_div.find_all('a', attrs={'class': 'js-title-link',\n 'target': '_blank',\n 'href': re.compile('/question/[0-9]+')})\n if title:\n title = title[0].text\n _id = e_div.find_all('link', attrs={'itemprop': 'url',\n 'href': re.compile('/question/[0-9]+/answer/[0-9]+')})\n href = _id[0].attrs.get('href')\n pattern = re.compile('/question/(.*?)/answer/(.*?)$', re.S)\n items = re.findall(pattern, href)\n question_id = items[0][0]\n question_url_list[title] = 'https://www.zhihu.com/question/' + question_id\n else:\n title_id = e_div.find_all('a', attrs={'class': 'js-title-link',\n 'target': '_blank',\n 'href': re.compile('https://zhuanlan.zhihu.com/p/[0-9]+')})\n if title_id:\n title = title_id[0].text\n href = title_id[0].attrs.get('href')\n question_url_list[title] = href\n else:\n continue\n keyword_question_url_list[keyword] = question_url_list\n except:\n continue\n\n for keyword, question_url_list in keyword_question_url_list.items():\n for question, url in question_url_list.items():\n fout.write(question + \"\\n\")\n try:\n req = request.Request(url, headers=headers)\n content, driver = get_grade(url)\n soup = BeautifulSoup(content, 'html.parser')\n if re.search('https://zhuanlan.zhihu.com/p/[0-9]+', url):\n answer = soup.find_all('div', attrs={'class': 'RichText PostIndex-content av-paddingSide av-card'})\n answer = answer[0].text\n fout.write(answer + \"\\n\")\n elif re.search('https://www.zhihu.com/question/[0-9]+', url):\n all_div = soup.find_all('div', attrs={'class': 'List-item'})\n print(len(all_div))\n for e_div in all_div:\n answer = e_div.find_all('span', attrs={'class': 'RichText CopyrightRichText-richText',\n 'itemprop': 'text'})\n answer = answer[0].text\n fout.write(answer + \"\\n\")\n else:\n continue\n except:\n continue\n" }, { "alpha_fraction": 0.5033538341522217, "alphanum_fraction": 0.5192844867706299, "avg_line_length": 35.51020431518555, "blob_id": "899bc6dca74e704d849f38a6389dff1ba4c2e820", "content_id": "16de41785611507109ccbb292457fc77cfa878dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3578, "license_type": "no_license", "max_line_length": 136, "num_lines": 98, "path": "/crawler_example/concept_stock.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2022/3/30 18:01\n# @Author : tianyunzqs\n# @Description :\n\nimport re\nimport time\nimport json\nimport random\nimport requests\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom tqdm import tqdm\nfrom free_proxy_ip_pool import ProxyFactory\nfrom free_proxy_ip_pool.agent import useragent\n\nfactory = ProxyFactory()\nheaders = {\n 'user-agent': useragent.chrome\n}\n\n\ndef sleep_random(start=1, end=1.5):\n time.sleep(random.randrange(int(start * 100), int(end * 100), step=1) * 0.01)\n\n\ndef get_all_concept_link_page_source():\n link_name = dict()\n with open('dd.txt', 'r', encoding='utf-8') as f:\n for line in f.readlines():\n if line.startswith('#'):\n continue\n link, name = line.strip().split('\\t')\n new_link = link.replace('conceptDetail', 'conceptStock').replace('shtml', 'js')\n link_name[new_link] = name\n # try:\n # # www = factory.create('https://www.kuaidaili.com/free', headers=headers)\n # www = factory.create('http://www.ip3366.net/', 'gbk', headers=headers)\n # # www = factory.create('http://www.goubanjia.com/',headers = headers)\n # # www = factory.create('http://www.data5u.com/', headers=headers)\n # # www = factory.create('http://www.89ip.cn/', headers=headers)\n # # www = factory.create('https://ip.ihuan.me/', headers=headers)\n # # www = factory.create(\n # # 'http://www.66ip.cn/mo.php?sxb=&tqsl=100&port=&export=&ktip=&sxa=&submit=%CC%E1++%C8%A1&textarea=',\n # # 'gbk',\n # # headers=headers)\n # data = www.run()\n # except:\n # return\n for link, name in link_name.items():\n print(name, link)\n with open(name.replace('/', '-') + '.txt', 'w', encoding='utf-8') as f:\n while True:\n try:\n www = factory.create('http://www.ip3366.net/', 'gbk', headers=headers)\n data = www.run()\n except:\n return\n flag = False\n for d in tqdm(data):\n try:\n page_source = requests.get(link, timeout=2, headers=headers, proxies={\"http\": '{0}:{1}'.format(d.host, d.port)})\n json_str = page_source.content.decode('gbk')\n json_str = json_str.replace('var conceptstockdata=', '').rstrip(';')\n result = json.loads(json_str)\n f.write(json.dumps(result, ensure_ascii=False))\n sleep_random()\n except:\n sleep_random()\n continue\n flag = True\n break\n if flag:\n break\n\n\ndef get_alive_ip(test_url):\n alive_ip_list = []\n www = factory.create('https://www.kuaidaili.com/free', headers=headers)\n data = www.run()\n for d in tqdm(data):\n try:\n respond = requests.get(test_url,\n proxies={\"http\": '{0}:{1}'.format(d.host, d.port)},\n timeout=2)\n if respond.status_code == 404:\n continue\n alive_ip_list.append(\"{0}:{1}\".format(d.host, d.port))\n except:\n continue\n return alive_ip_list\n\n\nif __name__ == '__main__':\n # url = 'http://stock.jrj.com.cn/concept/conceptpage.shtml?to=pc'\n # a = get_alive_ip(url)\n # print(a)\n get_all_concept_link_page_source()\n" }, { "alpha_fraction": 0.6325568556785583, "alphanum_fraction": 0.6633388996124268, "avg_line_length": 39.06666564941406, "blob_id": "c6f107342e4a47e00016955b2cc8492820208f68", "content_id": "c3c7b2bf1d9e5df1d1bc9f6acc94943b1ffd1c4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3792, "license_type": "no_license", "max_line_length": 133, "num_lines": 90, "path": "/crawler_example/video.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2022/3/10 10:47\n# @Author : tianyunzqs\n# @Description :\n\nimport re\nimport time\nimport json\nimport requests\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nchrome_options = Options()\nchrome_options.add_argument('--no-sandbox') # 让Chrome在root权限下跑\nchrome_options.add_argument('--disable-dev-shm-usage')\nchrome_options.add_argument('window-size=1920x3000') # 指定浏览器分辨率\nchrome_options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug\nchrome_options.add_argument('--hide-scrollbars') # 隐藏滚动条, 应对一些特殊页面\nchrome_options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度\nchrome_options.add_argument('--headless') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败\nchrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])\nbrowser = webdriver.Chrome(chrome_options=chrome_options)\n\n\ndef download_video(page_url):\n import requests\n import re\n import json\n import base64\n\n user_agent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36\"\n headers = {\n \"User-Agent\": user_agent\n }\n page_content = requests.get(page_url, headers=headers).content.decode(encoding='utf-8')\n # print(page_content)\n\n config_info = re.findall(r'window\\.__pageState=.*\\}</script>', page_content)[0]\n config_info = json.loads(config_info.split('window.__pageState=')[1].replace('</script>', ''))['video']\n\n title = config_info['title']\n\n v_sdk = 'https://vas.snssdk.com/video/openapi/v1/'\n params = {\n 'action': 'GetPlayInfo',\n 'video_id': config_info['vid'],\n 'nobase64': 'false',\n 'ptoken': config_info['businessToken'],\n 'vfrom': 'xgplayer'\n }\n v_header = {\n 'Authorization': config_info['authToken'],\n \"User-Agent\": user_agent\n }\n video_info = json.loads(requests.get(v_sdk, params=params, headers=v_header).content.decode())\n if video_info['code'] == 0:\n h_video = video_info['data']['video_list']['video_' + str(video_info['total'])]\n v_type = h_video['vtype']\n video_url = str(base64.urlsafe_b64decode(h_video['main_url']), encoding='utf-8')\n print(title)\n print(video_url)\n with open('./%s.%s' % (title, v_type), 'wb') as f:\n f.write(requests.get(video_url).content)\n print('下载成功!')\n else:\n print('请求失败!')\n\n\ndef download_file(url, save_path):\n response = requests.get(url, stream=True)\n if response.status_code == 200:\n block_size = 1024 # 1 Kibibyte\n with open(save_path, 'wb') as file:\n for data in response.iter_content(block_size):\n file.write(data)\n else:\n raise Exception(\"Something went wrong while downloading.\")\n\n\n# # browser.get('https://www.ixigua.com/home/6640492251/video/?preActiveKey=hotsoon&list_entrance=userdetail')\n# # browser.get('https://www.ixigua.com/home/6640492251/video')\n# browser.get('https://www.ixigua.com/')\n# # all_videos = browser.find_elements_by_class_name('HorizontalFeedCard')\n# # all_videos = browser.find_elements_by_xpath(\"//div[@class='HorizontalFeedCard__contentWrapper']\")\n# all_videos = browser.find_elements_by_xpath(\"//div[@class='HorizontalFeedCard__contentWrapper']\")\n# for i, video in enumerate(all_videos):\n# video_url = video.find_element_by_xpath(\n# \"//a[@class='HorizontalFeedCard__title color-link-content-primary']\").get_attribute('href')\n# download_file(video_url, './{0}.mp4')\ndownload_video('https://www.ixigua.com/7072272558803911199')\n" }, { "alpha_fraction": 0.7766990065574646, "alphanum_fraction": 0.8058252334594727, "avg_line_length": 16.33333396911621, "blob_id": "a16d87deceaa36bfa69874bd23ad2e5748604a35", "content_id": "41ae565cf62f3d6c39cd355ede59454adac5f29d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 177, "license_type": "no_license", "max_line_length": 30, "num_lines": 6, "path": "/README.md", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "## crawler_example\n糗事百科的爬虫\n## zhihu\n知乎的爬虫,根据输入的关键词爬取知乎的相关问题及其对应的答案\n## phantomhs-2.1.1-windows\nphantomhs" }, { "alpha_fraction": 0.6913580298423767, "alphanum_fraction": 0.7283950448036194, "avg_line_length": 34.63999938964844, "blob_id": "9505293477aa4e390cc0368a77a8527cd2b3c300", "content_id": "223b01c248c21afa03a4db4ac359177653f1bbde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 891, "license_type": "no_license", "max_line_length": 111, "num_lines": 25, "path": "/weibo/weibo_login.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2019/9/18 10:51\n# @Author : tianyunzqs\n# @Description : \n\nimport time\nfrom selenium import webdriver\n\ndriver = webdriver.PhantomJS(executable_path='../phantomjs-2.1.1-windows/bin/phantomjs.exe')\ndriver.get('https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=https%3A%2F%2Fm.weibo.cn%2F')\nprint(driver.page_source)\ntime.sleep(2)\n\nweiboUrl = 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=https%3A%2F%2Fm.weibo.cn%2F'\nuser = '[email protected]'\npassword = 'tianyun618'\ndriver.get(weiboUrl)\ntime.sleep(5)\ndriver.find_element_by_id('loginName').clear()\ndriver.find_element_by_id('loginName').send_keys(user)\ndriver.find_element_by_id('loginPassword').clear()\ndriver.find_element_by_id('loginPassword').send_keys(password)\ndriver.find_element_by_id('loginAction').click()\nprint(\"logined\")\nprint(driver.page_source)\n" }, { "alpha_fraction": 0.5275330543518066, "alphanum_fraction": 0.5319383144378662, "avg_line_length": 23.54054069519043, "blob_id": "957552ddc0b6c2aeac00f78c4b125df9276175da", "content_id": "a7db358a4f6146cf269e283e1449cab10a2b43a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 972, "license_type": "no_license", "max_line_length": 64, "num_lines": 37, "path": "/free_proxy_ip_pool/www_xicidaili_com.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\nhttps://www.xicidaili.com/wt/ 代理\n\n'''\n\n\nclass WWW_XICIDAILI_COM(AbsFreeProxyBase):\n\n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式如下:\n \"ip\", \"端口\", \"协议\", \"存活时间\", \"验证时间\"\n \"\"\"\n regex = re.compile(r'(?<=<td>)(.*)(?=</td>)')\n rows = soup.select('#ip_list tr')\n result = []\n for row in [str(n) for n in rows]:\n item = regex.findall(row)\n item and result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n result.append(ProxyModel(item[2], item[0], item[1]))\n return result\n" }, { "alpha_fraction": 0.611039400100708, "alphanum_fraction": 0.6320206522941589, "avg_line_length": 34.609195709228516, "blob_id": "bb66a6655d19774e05d13ba254b3a9a905d84424", "content_id": "334382ae4f1142e246eacd81ffb8419e8b8a8481", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3380, "license_type": "no_license", "max_line_length": 144, "num_lines": 87, "path": "/crawler_example/douban.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2021/11/5 17:29\n# @Author : tianyunzqs\n# @Description :\n\nimport re\nimport time\nimport json\nimport requests\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n'''\nFunction:\n 豆瓣模拟登录\nAuthor:\n Charles\n微信公众号:\n Charles的皮卡丘\n更新日期:\n 2020-10-29\n'''\nimport requests\n\n\n'''PC端登录豆瓣'''\nclass doubanPC():\n is_callable = True\n def __init__(self, **kwargs):\n for key, value in kwargs.items(): setattr(self, key, value)\n self.info = 'login in douban in pc mode'\n self.session = requests.Session()\n self.__initialize()\n '''登录函数'''\n def login(self, username, password, crack_captcha_func=None, **kwargs):\n # 设置代理\n self.session.proxies.update(kwargs.get('proxies', {}))\n # 初始化cookie\n self.session.get(self.home_url)\n # 模拟登录\n data = {\n 'ck': '',\n 'name': username,\n 'password': password,\n 'remember': 'true',\n 'ticket': ''\n }\n response = self.session.post(self.login_url, data=data)\n response_json = response.json()\n # 登录成功\n if response_json['status'] == 'success':\n print('[INFO]: Account -> %s, login successfully' % username)\n infos_return = {'username': username}\n infos_return.update(response_json)\n return infos_return, self.session\n # 账号或密码错误\n elif response_json['status'] == 'failed' and response_json['message'] == 'unmatch_name_password':\n raise RuntimeError('Account -> %s, fail to login, username or password error' % username)\n # 其他错误\n else:\n raise RuntimeError(response_json.get('description'))\n '''初始化'''\n def __initialize(self):\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',\n 'Host': 'accounts.douban.com',\n 'Origin': 'https://accounts.douban.com',\n 'Referer': 'https://accounts.douban.com/passport/login_popup?login_source=anony'\n }\n self.home_url = 'https://www.douban.com/'\n self.login_url = 'https://accounts.douban.com/j/mobile/login/basic'\n self.session.headers.update(self.headers)\n\n\nchrome_options = Options()\nchrome_options.add_argument('--no-sandbox') # 让Chrome在root权限下跑\nchrome_options.add_argument('--disable-dev-shm-usage')\nchrome_options.add_argument('window-size=1920x3000') # 指定浏览器分辨率\nchrome_options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug\nchrome_options.add_argument('--hide-scrollbars') # 隐藏滚动条, 应对一些特殊页面\nchrome_options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度\nchrome_options.add_argument('--headless') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败\nchrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])\nbrowser = webdriver.Chrome(chrome_options=chrome_options)\ndata = browser.get('https://www.douban.com/group/707650/discussion?start=50')\nprint(data)\nprint(data.content)\n" }, { "alpha_fraction": 0.5112813115119934, "alphanum_fraction": 0.5365349054336548, "avg_line_length": 31.206666946411133, "blob_id": "efed6cc69c031fbf593bed5db248a37b432dc1c0", "content_id": "3243985d82595488dea2be8c151d02308e712aea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4931, "license_type": "no_license", "max_line_length": 102, "num_lines": 150, "path": "/utils/mysql_utils.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2019/3/15 9:52\n# @Author : tianyunzqs\n# @Description : mysql数据库操作工具类\n\nimport datetime\nimport unittest\nimport pymysql\n\n\nclass MysqlClient(object):\n \"\"\"\n mysql数据库操作类\n \"\"\"\n def __init__(self, host, user, password, database, port):\n conf = {\n \"host\": host,\n \"user\": user,\n \"password\": password,\n \"database\": database,\n \"port\": int(port),\n \"cursorclass\": pymysql.cursors.DictCursor,\n \"charset\": \"utf8\"\n }\n self.conn = pymysql.connect(**conf)\n self.cursor = self.conn.cursor()\n\n def query(self, sql):\n self.cursor.execute(sql)\n self.conn.commit()\n row = self.cursor.fetchall()\n return row\n\n def update(self, sql):\n effect_row = self.cursor.execute(sql)\n self.conn.commit()\n return effect_row\n\n def insert_many(self, sql, param):\n effect_row = self.cursor.executemany(sql, param)\n self.conn.commit()\n return effect_row\n\n def __del__(self):\n self.conn.close()\n\n\nclass TestMysqlClient(unittest.TestCase):\n \"\"\"\n 各个方法的单元测试\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(TestMysqlClient, self).__init__(*args, **kwargs)\n self.host = \"10.95.132.15\"\n self.user = \"root\"\n self.password = \"Fhpt2020!\"\n self.database = \"ezhou_police\"\n self.port = \"3306\"\n self.mysql_instance = MysqlClient(host=self.host,\n user=self.user,\n password=self.password,\n database=self.database,\n port=self.port)\n self.test_table_name = 'mysql_test_' + datetime.datetime.now().strftime(\"%Y%m%d%H%M\")\n\n def test_create(self):\n print(\"=\" * 50, \"create test\", \"=\" * 50)\n sql = \"\"\"\n CREATE TABLE {0}(\n ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n NAME VARCHAR(20) NOT NULL,\n AGE INT NOT NULL,\n ADDRESS VARCHAR(50),\n SALARY FLOAT \n );\n \"\"\".format(self.test_table_name)\n rows = self.mysql_instance.update(sql=sql)\n print(rows)\n\n def test_insert(self):\n print(\"=\" * 50, \"insert test\", \"=\" * 50)\n sql = \"\"\"\n INSERT INTO {0} (NAME,AGE,ADDRESS,SALARY) VALUES ('Paul', 32, 'California', 20000.00)\n \"\"\".format(self.test_table_name)\n rows = self.mysql_instance.update(sql=sql)\n print(rows)\n\n def test_query(self):\n print(\"=\" * 50, \"query test\", \"=\" * 50)\n sql = \"\"\"\n SELECT * FROM {0}\n \"\"\".format(self.test_table_name)\n rows = self.mysql_instance.query(sql=sql)\n print(rows)\n\n def test_insert_many(self):\n print(\"=\" * 50, \"insert_many test\", \"=\" * 50)\n values = [\n ('Allen', 25, 'Texas', 15000.00),\n ('Teddy', 23, 'Norway', 20000.00),\n ('Mark', 25, 'Rich-Mond ', 65000.00)\n ]\n sql = \"\"\"\n INSERT INTO {0}(NAME, AGE, ADDRESS, SALARY) VALUES(%s, %s, %s, %s)\n \"\"\".format(self.test_table_name)\n rows = self.mysql_instance.insert_many(sql=sql, param=values)\n print(rows)\n\n def test_update(self):\n print(\"=\" * 50, \"update test\", \"=\" * 50)\n sql = \"\"\"\n UPDATE {0} SET SALARY=20000 WHERE name='Allen'\n \"\"\".format(self.test_table_name)\n rows = self.mysql_instance.update(sql=sql)\n print(rows)\n\n def test_delete(self):\n print(\"=\" * 50, \"delete test\", \"=\" * 50)\n sql = \"\"\"\n DELETE FROM {0} WHERE name='Mark'\n \"\"\".format(self.test_table_name)\n rows = self.mysql_instance.update(sql=sql)\n print(rows)\n\n def test_drop(self):\n print(\"=\" * 50, \"drop test\", \"=\" * 50)\n sql = \"\"\"\n DROP TABLE {0}\n \"\"\".format(self.test_table_name)\n rows = self.mysql_instance.update(sql=sql)\n print(rows)\n\n\nif __name__ == '__main__':\n # 在pycharm中直接运行该测试脚本会报错,请参考https://www.pythonheidong.com/blog/article/493096/c958bb7fc8cf2661b29e/\n # 构造测试集\n suite = unittest.TestSuite()\n suite.addTest(TestMysqlClient('test_create'))\n suite.addTest(TestMysqlClient(\"test_insert\"))\n suite.addTest(TestMysqlClient(\"test_query\"))\n suite.addTest(TestMysqlClient(\"test_insert_many\"))\n suite.addTest(TestMysqlClient(\"test_query\"))\n suite.addTest(TestMysqlClient(\"test_update\"))\n suite.addTest(TestMysqlClient(\"test_query\"))\n suite.addTest(TestMysqlClient(\"test_delete\"))\n suite.addTest(TestMysqlClient(\"test_query\"))\n suite.addTest(TestMysqlClient(\"test_drop\"))\n # 执行测试\n runner = unittest.TextTestRunner()\n runner.run(suite)\n" }, { "alpha_fraction": 0.5459401607513428, "alphanum_fraction": 0.5512820482254028, "avg_line_length": 24.324323654174805, "blob_id": "c4c684367f7052c8d8a91672c65b7ea7ba89c158", "content_id": "2c0bea367fa896797bea460c31a2c29062bb74e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 73, "num_lines": 37, "path": "/free_proxy_ip_pool/www_kuaidaili_com.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\n快代理\nhttps://www.kuaidaili.com/free\n'''\n\n\nclass WWW_KUAIDAILI_COM(AbsFreeProxyBase):\n\n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 格式如下:\n IP \tport(端口) \t匿名度 \t类型(HTTP/https) \t位置 \t响应速度 \t最后验证时间\n \"\"\"\n regex = re.compile(r'<td[^>]*>([^<>]+)</td>')\n rows = soup.select('.table-bordered tr')\n result = []\n for row in [str(n) for n in rows]:\n item = regex.findall(row)\n item and result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n result.append(ProxyModel(item[3], item[0], item[1], item[2]))\n return result" }, { "alpha_fraction": 0.584536075592041, "alphanum_fraction": 0.6257731914520264, "avg_line_length": 32.44827651977539, "blob_id": "1b33681aee0fc114ad0f6e10df2bd794711afddb", "content_id": "77777faa979ced6d405f0429599343eda7abf648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "no_license", "max_line_length": 119, "num_lines": 29, "path": "/zhihu/crawler_zhihu2.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nfrom urllib import request\nfrom bs4 import BeautifulSoup\n\nurl = 'https://www.zhihu.com/question/20981010'\nuser_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) ' \\\n 'Chrome/39.0.2171.95 Safari/537.36'\nheaders = {'User-Agent': user_agent}\n\ntry:\n req = request.Request(url, headers=headers)\n with request.urlopen(req, timeout=10) as response:\n content = response.read().decode('utf-8')\n soup = BeautifulSoup(content, 'html.parser')\n all_div = soup.find_all('div', attrs={'class': 'List-item'})\n for e_div in all_div:\n\n answer = e_div.find_all('span', attrs={'class': 'RichText CopyrightRichText-richText', 'itemprop': 'text'})\n print(answer[0].text)\n break\n\nexcept request.URLError as e:\n if hasattr(e, \"code\"):\n print(e.code)\n if hasattr(e, \"reason\"):\n print(e.reason)\n" }, { "alpha_fraction": 0.5437881946563721, "alphanum_fraction": 0.5560081601142883, "avg_line_length": 38.81081008911133, "blob_id": "e083dc2306d2248aeea7c55b98c0a6529178053b", "content_id": "02817cde235eeac0e54e5b7eaa0c4cf98a84dea5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1473, "license_type": "no_license", "max_line_length": 106, "num_lines": 37, "path": "/crawler_example/crawler2.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nfrom urllib import request\nfrom bs4 import BeautifulSoup\n\n\ndef find_all(item, attr, c):\n return item.find_all(attr, attrs={'class': c}, limit=1)\n\nfor page in range(1, 20):\n print(page)\n url = 'http://www.qiushibaike.com/hot/page/' + str(page)\n user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'\n headers = {'User-Agent': user_agent}\n try:\n req = request.Request(url, headers=headers)\n with request.urlopen(req, timeout=5) as response:\n content = response.read().decode('utf-8')\n soup = BeautifulSoup(content, 'html.parser')\n all_div = soup.find_all('div', attrs={'class': re.compile('article block untagged mb15 .*?')})\n for i, e_div in enumerate(all_div):\n result = {}\n result['id'] = e_div.attrs['id']\n result['name'] = e_div.h2.string.strip()\n cont = e_div.find_all('div', attrs={'class': 'content'})\n result['content'] = cont[0].text.strip()\n silme_comment = e_div.find_all('i', attrs={'class': 'number'})\n result['silme_num'] = int(silme_comment[0].text.strip())\n result['comment_num'] = int(silme_comment[1].text.strip())\n print(result)\n except request.URLError as e:\n if hasattr(e, \"code\"):\n print(e.code)\n if hasattr(e, \"reason\"):\n print(e.reason)\n" }, { "alpha_fraction": 0.5447545647621155, "alphanum_fraction": 0.548604428768158, "avg_line_length": 26.36842155456543, "blob_id": "9262610cd3797c0510ed53082ad4799a55fe4cf1", "content_id": "5ed2db7ad25bfcaff217401ef3bee304f86d199e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 73, "num_lines": 38, "path": "/free_proxy_ip_pool/www_xiladaili_com.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\nhttp://www.xiladaili.com/http/\nhttp://www.xiladaili.com/gaoni/\n'''\n\n\nclass WWW_XILADAILI_COM(AbsFreeProxyBase):\n \n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式\n 代理IP(xxx.xxx.xxx:port) \t代理协议 \tIP匿名度 \t代理位置 \t响应速度 \t存活时间 \t最后验证时间 \t打分\n \"\"\"\n regex = re.compile(r'(?<=<td>)(.*)(?=</td>)')\n rows = soup.select('.fl-table tr')\n result = []\n for row in [str(n) for n in rows]:\n item = regex.findall(row)\n item and result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n host, port = re.search(r'([\\d.]+):(\\d+)', item[0]).groups()\n result.append(ProxyModel(item[1], host, port, item[2]))\n return result" }, { "alpha_fraction": 0.5377258062362671, "alphanum_fraction": 0.5504782199859619, "avg_line_length": 25.885713577270508, "blob_id": "f98a3841121ba96104ce5f1900fada22feb21b99", "content_id": "c2bc7989782ce19023fbbc0fd572f7db5efc7a36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 993, "license_type": "no_license", "max_line_length": 68, "num_lines": 35, "path": "/free_proxy_ip_pool/www_zdaye_com.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n\n'''\nhttps://www.zdaye.com/dayProxy/ip/316788.html\n'''\nclass WWW_ZDAYE_COM(AbsFreeProxyBase):\n \n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式:\n IP,端口,协议,匿名度\n \"\"\"\n regex = re.compile(\n r'([\\d.]+):(\\d+)@(HTTPS?)#\\[([\\u4e00-\\u9fa5]+)\\]', re.I)\n text = soup.select('.cont')\n rows = regex.findall(str(text))\n result = []\n for item in rows:\n item and result.append(item)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for host, port, scheme, anonymity in data:\n result.append(ProxyModel(scheme, host, port, anonymity))\n return result\n" }, { "alpha_fraction": 0.429810494184494, "alphanum_fraction": 0.4496355652809143, "avg_line_length": 45.19528579711914, "blob_id": "ef2fa2c5716d7e1649acec7778827d5ea6219255", "content_id": "0a83045997a19794cd66d5e72e5cab89a9302e98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14200, "license_type": "no_license", "max_line_length": 220, "num_lines": 297, "path": "/crawler_example/xinhua_dictionary.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2022/4/25 15:52\n# @Author : tianyunzqs\n# @Description :\n\nimport os\nimport re\nimport sys\nimport time\nimport random\nimport datetime\nimport collections\nimport requests\nfrom bs4 import BeautifulSoup\nproject_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(project_path)\nfrom free_proxy_ip_pool import ProxyFactory\nfrom free_proxy_ip_pool.agent import useragent\nfrom utils.mysql_utils import MysqlClient\n\nfactory = ProxyFactory()\nheaders = {\n 'user-agent': useragent.chrome\n}\nall_www = [\n # 66免费代理网\n factory.create(\n 'http://www.66ip.cn/mo.php?sxb=&tqsl=100&port=&export=&ktip=&sxa=&submit=%CC%E1++%C8%A1&textarea=',\n 'gbk',\n headers=headers),\n # 小幻HTTP代理\n factory.create('https://ip.ihuan.me/', headers=headers),\n # 89免费代理\n factory.create('http://www.89ip.cn/', headers=headers),\n # 无忧代理\n factory.create('http://www.data5u.com/', headers=headers),\n # 全网代理IP\n factory.create('http://www.goubanjia.com/', headers=headers),\n # 云代理\n factory.create('http://www.ip3366.net/', 'gbk', headers=headers),\n # 快代理\n factory.create('https://www.kuaidaili.com/free', headers=headers),\n]\nall_proxy = []\n\n\ndef get_pinyin_url(path):\n pinyin_url = dict()\n with open(path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n line = line.strip()\n if not line:\n continue\n url, pinyin = line.split(' ', 1)\n pinyin_url[pinyin] = url\n return pinyin_url\n\n\ndef sleep_random(start=1, end=1.5):\n time.sleep(random.randrange(int(start * 100), int(end * 100), step=1) * 0.01)\n\n\ndef get_proxy():\n if all_proxy:\n return all_proxy.pop()\n else:\n while True:\n try:\n www = all_www[random.randrange(0, len(all_www))]\n data = www.run()\n all_proxy.extend(['{0}:{1}'.format(d.host, d.port) for d in data])\n if all_proxy:\n return all_proxy.pop()\n except:\n pass\n\n\ndef get_requests(url, header, one_proxy=None):\n if not one_proxy:\n one_proxy = get_proxy()\n print(one_proxy)\n while True:\n try:\n respond = requests.get(url, timeout=2, headers=header, proxies={\"http\": one_proxy})\n if respond.status_code == 200 and \"Burp Suite Professional\" not in respond.text:\n break\n one_proxy = get_proxy()\n print(one_proxy)\n continue\n except:\n one_proxy = get_proxy()\n print(one_proxy)\n return respond, one_proxy\n\n\ndef load_exist_url():\n mysql_instance = MysqlClient(host='localhost',\n user='root',\n password='dyty2502',\n database='datasets',\n port=3306)\n sql = \"SELECT url FROM xhzd\"\n return set([item['url'] for item in mysql_instance.query(sql)])\n\n\ndef spider_run():\n header = {\n \"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\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Cache-Control\": \"max-age=0\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": \"__gads=ID=042517c3bb15f02e-225eddf29dcc0050:T=1634605271:RT=1634605271:S=ALNI_MZdY0ASGRC8LZ8ZpG-OPZcDFZERlg; __gpi=UID=00000496cfa1f71c:T=1649322191:RT=1649322191:S=ALNI_MbgHTbNGs2kCXMkYJq1N5zoILN_7w\",\n \"Host\": \"xh.5156edu.com\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36\",\n }\n exist_urls = load_exist_url()\n main_url = 'http://xh.5156edu.com'\n result = collections.defaultdict(dict)\n pinyin_url = get_pinyin_url('pinyin_url.txt')\n valid_proxy = get_proxy()\n for pinyin, url in pinyin_url.items():\n respond, valid_proxy = get_requests(url, header, valid_proxy)\n page_source = respond.content.decode('gbk', errors='ignore')\n for item in re.finditer(r\"class='fontbox' href='(?P<href>.*?)'>(?P<char>.)<\", page_source):\n hanzi = item.groupdict()['char']\n char_url = main_url + item.groupdict()['href']\n if char_url in exist_urls:\n print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), hanzi, char_url, \"跳过\")\n continue\n # char_url = main_url + '/html3/1617.html'\n # char_url = main_url + '/html3/7578.html'\n print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), hanzi, char_url)\n result[hanzi] = {\n \"url\": char_url,\n \"拼音\": list(),\n \"笔画\": -1,\n \"部首\": '',\n \"五笔\": '',\n \"笔顺编号\": '',\n \"成语\": set(),\n \"同部首\": set(),\n \"同笔画\": set(),\n \"基本解释\": '',\n \"笔划顺序\": '',\n \"详细解释\": '',\n \"相关词语\": set(),\n }\n char_respond, valid_proxy = get_requests(char_url, header, valid_proxy)\n char_respond.encoding = char_respond.apparent_encoding\n char_soup = BeautifulSoup(char_respond.content.decode('gbk', errors='ignore'), 'html.parser')\n td_tag = char_soup.findAll('tr')\n i = 0\n pinyin_tongyin_dict = collections.defaultdict(set)\n pinyin_pinyin_dict = dict()\n while i < len(td_tag):\n td_tag_text = td_tag[i].text.strip()\n if '相关成语' == td_tag_text:\n i += 1\n if \"更多相关成语\" in td_tag[i].text.strip():\n more_cy_url = main_url + td_tag[i].find('p').find('a').get('href')\n more_cy_respond, valid_proxy = get_requests(more_cy_url, header, valid_proxy)\n more_cy_soup = BeautifulSoup(more_cy_respond.content.decode('gbk', errors='ignore'),\n 'html.parser')\n for sub_soup in more_cy_soup.findAll(name=\"td\", attrs={\"width\": \"25%\"}):\n result[hanzi][\"成语\"].add(sub_soup.text.strip())\n else:\n for sub_soup in td_tag[i].findAll('a'):\n result[hanzi][\"成语\"].add(sub_soup.text.strip())\n elif '同音字' == td_tag_text:\n i += 1\n char_pinyin = ''\n for bb in td_tag[i].findAll():\n if bb.name == 'span':\n char_pinyin = bb.text.strip()\n elif bb.name == 'a':\n pinyin_tongyin_dict[char_pinyin].add(bb.text.strip())\n elif '同部首' == td_tag_text:\n i += 1\n for sub_soup in td_tag[i].findAll('a'):\n result[hanzi][\"同部首\"].add(sub_soup.text.strip())\n elif '同笔画' == td_tag_text:\n i += 1\n for sub_soup in td_tag[i].findAll('a'):\n result[hanzi][\"同笔画\"].add(sub_soup.text.strip())\n elif re.search(r'^拼音[\\s\\S]+笔划', td_tag_text):\n j = 0\n e = td_tag[i].findAll('td')\n while j < len(e):\n if e[j].text.strip() == \"拼音:\":\n j += 1\n pinyin_pinyin_dict = dict()\n for re_pinyin in re.finditer(r'>(?P<p1>[^<>(){}]+?)<(script>xhziplay\\(\"(?P<p2>[a-z1-4]+)\"\\))?', str(e[j])):\n p1, p2 = re_pinyin.groupdict()['p1'], re_pinyin.groupdict()['p2']\n if not p1:\n continue\n p1_list = list(filter(None, [w.strip() for w in p1.split(',')]))\n if not p1_list:\n continue\n for _p1 in p1_list[:-1]:\n pinyin_pinyin_dict[_p1] = _p1\n if p2:\n pinyin_pinyin_dict[p1_list[-1]] = p2\n else:\n pinyin_pinyin_dict[p1_list[-1]] = p1_list[-1]\n\n all_pinyin = list(filter(None, [w.strip() for w in e[j].text.split(',')]))\n if len(all_pinyin) != len(pinyin_pinyin_dict):\n print(\"拼音长度不一致\", char_url)\n elif e[j].text.strip() == \"笔划:\":\n j += 1\n result[hanzi][\"笔画\"] = int(e[j].text.strip())\n j += 1\n elif re.search(r'^部首[\\s\\S]+五笔', td_tag_text):\n j = 0\n e = td_tag[i].findAll('td')\n while j < len(e):\n if e[j].text.strip() == \"部首:\":\n j += 1\n result[hanzi][\"部首\"] = e[j].text.strip()\n elif e[j].text.strip() == \"五笔:\":\n j += 1\n result[hanzi][\"五笔\"] = e[j].text.strip()\n j += 1\n elif re.search(r'^基本解释', td_tag_text) and not result[hanzi][\"相关词语\"]:\n parts = re.split(r'(<b><span class=\"table4\">.*?</font></span></b>:)', str(td_tag[i]))\n j = 0\n while j < len(parts):\n if re.search(r'<b><span class=\"table4\">.*?基本解释.*?</font></span></b>:', parts[j]):\n result[hanzi][\"基本解释\"] = \"\\n\".join(parts[j:j+2])\n j += 1\n elif re.search(r'<b><span class=\"table4\">.*?笔划顺序.*?</font></span></b>:', parts[j]):\n j += 1\n bs_part = BeautifulSoup(parts[j], 'html.parser')\n result[hanzi][\"笔划顺序\"] = main_url + bs_part.find('img').get('src')\n elif re.search(r'<b><span class=\"table4\">.*?详细解释.*?</font></span></b>:', parts[j]):\n result[hanzi][\"详细解释\"] = \"\\n\".join(parts[j:j+2])\n j += 1\n elif re.search(r'<b><span class=\"table4\">.*?相关词语.*?</font></span></b>:', parts[j]):\n j += 1\n bs_part = BeautifulSoup(parts[j], 'html.parser')\n all_relate_words = set()\n for bp in bs_part.findAll('a'):\n if re.search(r\"更多有关.的词语\", bp.text):\n more_words_url = main_url + bp.get('href')\n more_words_respond, valid_proxy = get_requests(more_words_url, header, valid_proxy)\n more_words_soup = BeautifulSoup(\n more_words_respond.content.decode('gbk', errors='ignore'),\n 'html.parser')\n for sub_soup in more_words_soup.findAll(name=\"td\", attrs={\"width\": \"25%\"}):\n all_relate_words.add(sub_soup.text.strip())\n else:\n all_relate_words.add(bp.text)\n result[hanzi][\"相关词语\"] = all_relate_words\n j += 1\n\n re_stroke_number = re.search(r'笔顺编号:(?P<number>[1-9]*)', td_tag_text)\n if re_stroke_number:\n result[hanzi][\"笔顺编号\"] = re_stroke_number.groupdict()['number']\n i += 1\n\n for p1, p2 in pinyin_pinyin_dict.items():\n result[hanzi][\"拼音\"].append({\n \"拼音1\": p1,\n \"拼音2\": p2,\n \"同音字\": pinyin_tongyin_dict[p1]\n })\n\n insert_data = []\n for char, char_info in result.items():\n for char_pinyin in char_info[\"拼音\"]:\n char_py1 = char_pinyin[\"拼音1\"]\n char_py2 = char_pinyin[\"拼音2\"]\n char_tyz = \"; \".join(char_pinyin[\"同音字\"])\n insert_data.append([\n char, char_info[\"url\"], char_py1, char_py2, char_info[\"笔画\"], char_info[\"部首\"],\n char_info[\"五笔\"], char_info[\"笔顺编号\"], \"; \".join(char_info[\"成语\"]), char_tyz,\n \"; \".join(char_info[\"同部首\"]), \"; \".join(char_info[\"同部首\"]), char_info[\"基本解释\"],\n char_info[\"笔划顺序\"], char_info[\"详细解释\"], \"; \".join(char_info[\"相关词语\"])\n ])\n\n mysql_instance = MysqlClient(host='localhost',\n user='root',\n password='dyty2502',\n database='datasets',\n port=3306)\n insert_sql = \"\"\"\n INSERT INTO xhzd(hanzi, url, pinyin, pinyin2, bihuashu, pianpangbushou, wubi, bishunbianhao, chengyu, tongyinzi, tongbushou, tongbihua, jibenjieshi, bihuashunxu, xiangxijieshi, xiangguanciyu) \n VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\"\n mysql_instance.insert_many(insert_sql, param=insert_data)\n result = collections.defaultdict(dict)\n\n\nif __name__ == '__main__':\n spider_run()\n" }, { "alpha_fraction": 0.47561588883399963, "alphanum_fraction": 0.47611865401268005, "avg_line_length": 16, "blob_id": "8497654e04462c9f2871135675f0fe024642d338", "content_id": "a2ee439d6b6ffbe9e8c86dfe4412a2027a304e26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2071, "license_type": "no_license", "max_line_length": 72, "num_lines": 117, "path": "/free_proxy_ip_pool/agent.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "import random\nimport re\nfrom typing import Dict, List\nimport os\n\n\nclass UserAgent:\n '''\n 代理\n '''\n __filepath = 'user-agent.txt'\n\n '''\n 对象实例\n '''\n __instance = None\n\n '''\n 代理浏览器\n '''\n __dict: Dict[str, list] = {}\n\n '''\n 代理浏览器\n '''\n __list: List[str] = []\n\n '''\n 初始化\n '''\n\n def __init__(self):\n reg = re.compile(r'firefox|chrome|msie|opera', re.I)\n with open(self.filepath, 'r', encoding='utf_8_sig') as f:\n for r in f:\n result = reg.search(r) and reg.search(r).group().lower()\n if result and (not result in self.__dict):\n self.__dict[result] = []\n result and self.__dict[result].append(r.strip())\n self.__list.append(r.strip())\n\n @property\n def filepath(self):\n return os.path.join(os.path.dirname(__file__), self.__filepath)\n\n '''\n 单例 - 构造函数\n '''\n\n def __new__(cls):\n if not cls.__instance:\n cls.__instance = super(UserAgent, cls).__new__(cls)\n return cls.__instance\n\n '''\n 谷歌\n '''\n\n @property\n def chrome(self) -> str:\n return random.choice(self.__dict['chrome'])\n\n '''\n 火狐\n '''\n\n @property\n def firefox(self) -> str:\n return random.choice(self.__dict['firefox'])\n\n '''\n IE\n '''\n\n @property\n def ie(self) -> str:\n return random.choice(self.__dict['msie'])\n\n '''\n Opera 浏览器\n '''\n\n @property\n def opera(self) -> str:\n return random.choice(self.__dict['opera'])\n\n '''\n 随机\n '''\n\n def random(self) -> str:\n return random.choice(self.__list)\n\n '''\n 迭代\n '''\n\n def __iter__(self):\n self.__iter = iter(self.__list)\n return self\n\n '''\n 下一个\n '''\n\n def __next__(self):\n return next(self.__iter)\n\n '''\n 索引\n '''\n\n def __getitem__(self, index) -> str or List[str]:\n return self.__list[index]\n\n\nuseragent = UserAgent()\n" }, { "alpha_fraction": 0.4305054247379303, "alphanum_fraction": 0.49548736214637756, "avg_line_length": 24.18181800842285, "blob_id": "b090ca60eaae6c4dfd3cb9c3ef0197eaf95656c0", "content_id": "ab647effb098b800b8b16d3bb21ce9bf8e05bf75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1238, "license_type": "no_license", "max_line_length": 69, "num_lines": 44, "path": "/free_proxy_ip_pool/www_89ip_cn.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from .base import AbsFreeProxyBase\nfrom typing import List\nfrom .model import ProxyModel\nimport re\n'''\nwww.89ip.cn 免费代理爬取\n'''\n\n\nclass WWW_89IP_CN(AbsFreeProxyBase):\n\n '''\n 初始化\n '''\n\n # 初始化\n def __init__(self, url, code='utf-8', **kwargs):\n super().__init__(url, code, **kwargs)\n\n # 解析内容\n def parse_text(self, soup) -> List[list]:\n \"\"\"\n 数据格式如下\n 'IP地址', '端口', '地理位置', '运营商', '最后检测'\n [\n ['222.189.190.242', '9999', '江苏省扬州市', '电信', '2019/11/10'], \n ['58.253.153.206', '9999', '广东省揭阳市', '联通', '2019/11/10'], \n ['183.164.238.17', '9999', '安徽省淮北市', '电信', '2019/11/10'],\n ...\n ]\n \"\"\"\n rows = soup.select('.layui-table tr')\n result = []\n for row in rows:\n col = [n.string.strip() for n in row.find_all('td')]\n col and result.append(col)\n return result\n\n # 格式转换\n def to_proxy(self, data: List[list]) -> List[ProxyModel]:\n result = []\n for item in data:\n result.append(ProxyModel('http', item[0], item[1]))\n return result\n" }, { "alpha_fraction": 0.4699484705924988, "alphanum_fraction": 0.48368632793426514, "avg_line_length": 47.54166793823242, "blob_id": "7e46bc4e025fd01b375795cee630edfa59ab21f8", "content_id": "e12db35d46abee0d7714314524415d57ceb14055", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3552, "license_type": "no_license", "max_line_length": 110, "num_lines": 72, "path": "/zhihu/crawler_zhihu.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nfrom urllib import request, parse\nfrom bs4 import BeautifulSoup\n\nkeyword_list = ['svm', '支持向量机', 'libsvm']\nfout = open(\"E:/python_file/svm.txt\", \"w\", encoding=\"utf-8\")\nfor keyword in keyword_list:\n print(keyword)\n # 将中文转换为浏览器可识别字符(HTTP协议是ASCII编码的形式)\n url = 'https://www.zhihu.com/search?type=content&q=' + parse.quote(keyword)\n user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) ' \\\n 'Chrome/39.0.2171.95 Safari/537.36'\n headers = {'User-Agent': user_agent}\n keyword_question_url_list = {}\n try:\n req = request.Request(url, headers=headers)\n response = request.urlopen(req, timeout=5)\n content = response.read().decode('utf-8')\n soup = BeautifulSoup(content, 'html.parser')\n all_div = soup.find_all('li', attrs={'class': re.compile('item clearfix.*?')})\n question_url_list = {}\n for e_div in all_div:\n title = e_div.find_all('a', attrs={'class': 'js-title-link',\n 'target': '_blank',\n 'href': re.compile('/question/[0-9]+')})\n if title:\n title = title[0].text\n _id = e_div.find_all('link', attrs={'itemprop': 'url',\n 'href': re.compile('/question/[0-9]+/answer/[0-9]+')})\n href = _id[0].attrs.get('href')\n pattern = re.compile('/question/(.*?)/answer/(.*?)$', re.S)\n items = re.findall(pattern, href)\n question_id = items[0][0]\n question_url_list[title] = 'https://www.zhihu.com/question/' + question_id\n else:\n title_id = e_div.find_all('a', attrs={'class': 'js-title-link',\n 'target': '_blank',\n 'href': re.compile('https://zhuanlan.zhihu.com/p/[0-9]+')})\n if title_id:\n title = title_id[0].text\n href = title_id[0].attrs.get('href')\n question_url_list[title] = href\n else:\n continue\n keyword_question_url_list[keyword] = question_url_list\n # for q, d in question_url_list.items():\n # print(q, d)\n except:\n continue\n\n for keyword, question_url_list in keyword_question_url_list.items():\n for question, url in question_url_list.items():\n fout.write(question + \"\\n\")\n try:\n req = request.Request(url, headers=headers)\n with request.urlopen(req, timeout=5) as response:\n content = response.read().decode('utf-8')\n soup = BeautifulSoup(content, 'html.parser')\n all_div = soup.find_all('div', attrs={'class': 'List-item'})\n for e_div in all_div:\n answer = e_div.find_all('span', attrs={'class': 'RichText CopyrightRichText-richText',\n 'itemprop': 'text'})\n answer = answer[0].text\n fout.write(answer + \"\\n\")\n except request.URLError as e:\n if hasattr(e, \"code\"):\n print(e.code)\n if hasattr(e, \"reason\"):\n print(e.reason)" }, { "alpha_fraction": 0.5872453451156616, "alphanum_fraction": 0.5899025797843933, "avg_line_length": 23.042552947998047, "blob_id": "23172253a9aecb379ceddde58f074bbd0d1f4f8d", "content_id": "b9384b9aa3297c21e86cd28db6244f56bdcf2540", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1251, "license_type": "no_license", "max_line_length": 64, "num_lines": 47, "path": "/free_proxy_ip_pool/base.py", "repo_name": "tianyunzqs/crawler", "src_encoding": "UTF-8", "text": "from abc import ABC, abstractmethod\nfrom typing import List\nimport requests\nimport bs4\nfrom .model import ProxyModel\n\n\nclass AbsFreeProxyBase(ABC):\n # 请求\n http = requests\n\n # 初始化\n def __init__(self, url, code, **kwargs):\n \"\"\"\n :param url: 请求地址\n :param code: 页面编码\n :param kw: 附加信息\n \"\"\"\n self.url = url\n self.code = code\n self.kwargs = kwargs\n self.beautifulsoup = bs4.BeautifulSoup\n\n # 模板方法模式\n # 第一步 获取页面内容 第二步 解析内容 第二步 格式化数据\n def run(self) -> List[ProxyModel]:\n text = self.get_page_text()\n soup = self.beautifulsoup(text, 'lxml')\n data = self.parse_text(soup)\n return self.to_proxy(data)\n\n # 获取页面内容\n def get_page_text(self):\n res = AbsFreeProxyBase.http.get(self.url, **self.kwargs)\n if not res.ok:\n res.raise_for_status()\n return res.content.decode(self.code)\n\n # 解析内容\n @abstractmethod\n def parse_text(self, soup: bs4.BeautifulSoup) -> List[list]:\n pass\n\n # 格式转换\n @abstractmethod\n def to_proxy(self, data:List[list]) -> List[ProxyModel]:\n pass" } ]
29
thepeshka/werkzeug
https://github.com/thepeshka/werkzeug
7f4d27716e3fd85b268421de9c15f3d2212cf6b9
cefda55a80368c2876af81358c6be512607a8f8b
35ef6dd544016898f4cbc0922f5cc69226bf5529
refs/heads/master
2020-04-13T10:55:51.182951
2018-12-26T10:38:39
2018-12-26T10:38:39
163,157,875
0
0
BSD-3-Clause
2018-12-26T08:47:25
2018-12-26T08:05:01
2018-12-11T17:23:21
null
[ { "alpha_fraction": 0.5269633531570435, "alphanum_fraction": 0.5526290535926819, "avg_line_length": 38.70610809326172, "blob_id": "c74c15d124b851071f26eb053f205c434e4cb8f6", "content_id": "f722a90d046be88487290038647fbe8c9ea42441", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10403, "license_type": "permissive", "max_line_length": 91, "num_lines": 262, "path": "/tests/contrib/test_fixers.py", "repo_name": "thepeshka/werkzeug", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n tests.fixers\n ~~~~~~~~~~~~\n\n Server / Browser fixers.\n\n :copyright: (c) 2014 by Armin Ronacher.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport pytest\n\nfrom werkzeug.contrib import fixers\nfrom werkzeug.datastructures import ResponseCacheControl\nfrom werkzeug.http import parse_cache_control_header\nfrom werkzeug.routing import Map, Rule\nfrom werkzeug.test import Client, create_environ\nfrom werkzeug.utils import redirect\nfrom werkzeug.wrappers import Request, Response\n\n\[email protected]\ndef path_check_app(request):\n return Response('PATH_INFO: %s\\nSCRIPT_NAME: %s' % (\n request.environ.get('PATH_INFO', ''),\n request.environ.get('SCRIPT_NAME', '')\n ))\n\n\nclass TestServerFixer(object):\n\n def test_cgi_root_fix(self):\n app = fixers.CGIRootFix(path_check_app)\n response = Response.from_app(\n app,\n dict(create_environ(),\n SCRIPT_NAME='/foo',\n PATH_INFO='/bar'))\n assert response.get_data() == b'PATH_INFO: /bar\\nSCRIPT_NAME: '\n\n def test_cgi_root_fix_custom_app_root(self):\n app = fixers.CGIRootFix(path_check_app, app_root='/baz/')\n response = Response.from_app(\n app,\n dict(create_environ(),\n SCRIPT_NAME='/foo',\n PATH_INFO='/bar'))\n assert response.get_data() == b'PATH_INFO: /bar\\nSCRIPT_NAME: baz'\n\n def test_path_info_from_request_uri_fix(self):\n app = fixers.PathInfoFromRequestUriFix(path_check_app)\n for key in 'REQUEST_URI', 'REQUEST_URL', 'UNENCODED_URL':\n env = dict(create_environ(), SCRIPT_NAME='/test', PATH_INFO='/?????')\n env[key] = '/test/foo%25bar?drop=this'\n response = Response.from_app(app, env)\n assert response.get_data() == b'PATH_INFO: /foo%bar\\nSCRIPT_NAME: /test'\n\n @pytest.mark.parametrize(('kwargs', 'base', 'url_root'), (\n pytest.param({}, {\n 'REMOTE_ADDR': '192.168.0.2',\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_FOR': '192.168.0.1',\n }, 'http://spam/', id='for'),\n pytest.param({'x_proto': 1}, {\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_PROTO': 'https',\n }, 'https://spam/', id='proto'),\n pytest.param({'x_host': 1}, {\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_HOST': 'eggs',\n }, 'http://eggs/', id='host'),\n pytest.param({'x_port': 1}, {\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_PORT': '8080',\n }, 'http://spam:8080/', id='port, host without port'),\n pytest.param({'x_port': 1}, {\n 'HTTP_HOST': 'spam:9000',\n 'HTTP_X_FORWARDED_PORT': '8080',\n }, 'http://spam:8080/', id='port, host with port'),\n pytest.param({'x_port': 1}, {\n 'SERVER_NAME': 'spam',\n 'SERVER_PORT': '9000',\n 'HTTP_X_FORWARDED_PORT': '8080',\n }, 'http://spam:8080/', id='port, name'),\n pytest.param({'x_prefix': 1}, {\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_PREFIX': '/eggs',\n }, 'http://spam/eggs/', id='prefix'),\n pytest.param({\n 'x_for': 1, 'x_proto': 1, 'x_host': 1, 'x_port': 1, 'x_prefix': 1\n }, {\n 'REMOTE_ADDR': '192.168.0.2',\n 'HTTP_HOST': 'spam:9000',\n 'HTTP_X_FORWARDED_FOR': '192.168.0.1',\n 'HTTP_X_FORWARDED_PROTO': 'https',\n 'HTTP_X_FORWARDED_HOST': 'eggs',\n 'HTTP_X_FORWARDED_PORT': '443',\n 'HTTP_X_FORWARDED_PREFIX': '/ham',\n }, 'https://eggs/ham/', id='all'),\n pytest.param({'x_for': 2}, {\n 'REMOTE_ADDR': '192.168.0.3',\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_FOR': '192.168.0.1, 192.168.0.2',\n }, 'http://spam/', id='multiple for'),\n pytest.param({'x_for': 0}, {\n 'REMOTE_ADDR': '192.168.0.1',\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_FOR': '192.168.0.2',\n }, 'http://spam/', id='ignore 0'),\n pytest.param({'x_for': 3}, {\n 'REMOTE_ADDR': '192.168.0.1',\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_FOR': '192.168.0.3, 192.168.0.2',\n }, 'http://spam/', id='ignore len < trusted'),\n pytest.param({}, {\n 'REMOTE_ADDR': '192.168.0.2',\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_FOR': '192.168.0.3, 192.168.0.1',\n }, 'http://spam/', id='ignore untrusted'),\n pytest.param({'x_for': 2}, {\n 'REMOTE_ADDR': '192.168.0.1',\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_FOR': ', 192.168.0.3'\n }, 'http://spam/', id='ignore empty'),\n pytest.param({'x_for': 2, 'x_prefix': 1}, {\n 'REMOTE_ADDR': '192.168.0.2',\n 'HTTP_HOST': 'spam',\n 'HTTP_X_FORWARDED_FOR': '192.168.0.1, 192.168.0.3',\n 'HTTP_X_FORWARDED_PREFIX': '/ham, /eggs',\n }, 'http://spam/eggs/', id='prefix < for')\n ))\n def test_proxy_fix_new(self, kwargs, base, url_root):\n @Request.application\n def app(request):\n # for header\n assert request.remote_addr == '192.168.0.1'\n # proto, host, port, prefix headers\n assert request.url_root == url_root\n\n urls = url_map.bind_to_environ(request.environ)\n # build includes prefix\n assert urls.build('parrot') == '/'.join((\n request.script_root, 'parrot'))\n # match doesn't include prefix\n assert urls.match('/parrot')[0] == 'parrot'\n\n return Response('success')\n\n url_map = Map([Rule('/parrot', endpoint='parrot')])\n app = fixers.ProxyFix(app, **kwargs)\n\n base.setdefault('REMOTE_ADDR', '192.168.0.1')\n environ = create_environ(environ_overrides=base)\n # host is always added, remove it if the test doesn't set it\n if 'HTTP_HOST' not in base:\n del environ['HTTP_HOST']\n\n # ensure app request has correct headers\n response = Response.from_app(app, environ)\n assert response.get_data() == b'success'\n\n # ensure redirect location is correct\n redirect_app = redirect(\n url_map.bind_to_environ(environ).build('parrot'))\n response = Response.from_app(redirect_app, environ)\n location = response.headers['Location']\n assert location == url_root + 'parrot'\n\n def test_proxy_fix_deprecations(self):\n app = pytest.deprecated_call(fixers.ProxyFix, None, 2)\n assert app.x_for == 2\n\n with pytest.deprecated_call():\n assert app.num_proxies == 2\n\n with pytest.deprecated_call():\n assert app.get_remote_addr(['spam', 'eggs']) == 'spam'\n\n def test_header_rewriter_fix(self):\n @Request.application\n def application(request):\n return Response(\"\", headers=[\n ('X-Foo', 'bar')\n ])\n application = fixers.HeaderRewriterFix(application, ('X-Foo',), (('X-Bar', '42'),))\n response = Response.from_app(application, create_environ())\n assert response.headers['Content-Type'] == 'text/plain; charset=utf-8'\n assert 'X-Foo' not in response.headers\n assert response.headers['X-Bar'] == '42'\n\n\nclass TestBrowserFixer(object):\n\n def test_ie_fixes(self):\n @fixers.InternetExplorerFix\n @Request.application\n def application(request):\n response = Response('binary data here', mimetype='application/vnd.ms-excel')\n response.headers['Vary'] = 'Cookie'\n response.headers['Content-Disposition'] = 'attachment; filename=foo.xls'\n return response\n\n c = Client(application, Response)\n response = c.get('/', headers=[\n ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')\n ])\n\n # IE gets no vary\n assert response.get_data() == b'binary data here'\n assert 'vary' not in response.headers\n assert response.headers['content-disposition'] == 'attachment; filename=foo.xls'\n assert response.headers['content-type'] == 'application/vnd.ms-excel'\n\n # other browsers do\n c = Client(application, Response)\n response = c.get('/')\n assert response.get_data() == b'binary data here'\n assert 'vary' in response.headers\n\n cc = ResponseCacheControl()\n cc.no_cache = True\n\n @fixers.InternetExplorerFix\n @Request.application\n def application(request):\n response = Response('binary data here', mimetype='application/vnd.ms-excel')\n response.headers['Pragma'] = ', '.join(pragma)\n response.headers['Cache-Control'] = cc.to_header()\n response.headers['Content-Disposition'] = 'attachment; filename=foo.xls'\n return response\n\n # IE has no pragma or cache control\n pragma = ('no-cache',)\n c = Client(application, Response)\n response = c.get('/', headers=[\n ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')\n ])\n assert response.get_data() == b'binary data here'\n assert 'pragma' not in response.headers\n assert 'cache-control' not in response.headers\n assert response.headers['content-disposition'] == 'attachment; filename=foo.xls'\n\n # IE has simplified pragma\n pragma = ('no-cache', 'x-foo')\n cc.proxy_revalidate = True\n response = c.get('/', headers=[\n ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')\n ])\n assert response.get_data() == b'binary data here'\n assert response.headers['pragma'] == 'x-foo'\n assert response.headers['cache-control'] == 'proxy-revalidate'\n assert response.headers['content-disposition'] == 'attachment; filename=foo.xls'\n\n # regular browsers get everything\n response = c.get('/')\n assert response.get_data() == b'binary data here'\n assert response.headers['pragma'] == 'no-cache, x-foo'\n cc = parse_cache_control_header(response.headers['cache-control'],\n cls=ResponseCacheControl)\n assert cc.no_cache\n assert cc.proxy_revalidate\n assert response.headers['content-disposition'] == 'attachment; filename=foo.xls'\n" }, { "alpha_fraction": 0.5595855116844177, "alphanum_fraction": 0.5595855116844177, "avg_line_length": 20.44444465637207, "blob_id": "ca524c5b64e010a8d48735744ef3b8ee7b4e6cb3", "content_id": "fe3e015c26f6e385d112f320c4f4ee90ac93ee05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 193, "license_type": "permissive", "max_line_length": 40, "num_lines": 9, "path": "/docs/contrib/lint.rst", "repo_name": "thepeshka/werkzeug", "src_encoding": "UTF-8", "text": "==========================\nLint Validation Middleware\n==========================\n\n.. currentmodule:: werkzeug.contrib.lint\n\n.. automodule:: werkzeug.contrib.lint\n\n.. autoclass:: LintMiddleware\n" }, { "alpha_fraction": 0.7384823560714722, "alphanum_fraction": 0.7384823560714722, "avg_line_length": 28.520000457763672, "blob_id": "1bd2b6d8998b74447d5dc94ca3315877c72775fe", "content_id": "cc165b7639d8814833bb5ec66e6fef98b6d186de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 738, "license_type": "permissive", "max_line_length": 114, "num_lines": 25, "path": "/Makefile", "repo_name": "thepeshka/werkzeug", "src_encoding": "UTF-8", "text": "documentation:\n\t@(cd docs; make html)\n\nrelease:\n\tpython scripts/make-release.py\n\ntest:\n\tpytest\n\ntox-test:\n\ttox\n\ncoverage:\n\t@(coverage run --module pytest $(TEST_OPTIONS) $(TESTS))\n\ndoctest:\n\t@(cd docs; sphinx-build -b doctest . _build/doctest)\n\nupload-docs:\n\t$(MAKE) -C docs html dirhtml latex\n\t$(MAKE) -C docs/_build/latex all-pdf\n\tcd docs/_build/; mv html werkzeug-docs; zip -r werkzeug-docs.zip werkzeug-docs; mv werkzeug-docs html\n\trsync -a docs/_build/dirhtml/ flow.srv.pocoo.org:/srv/websites/werkzeug.pocoo.org/docs/\n\trsync -a docs/_build/latex/Werkzeug.pdf flow.srv.pocoo.org:/srv/websites/werkzeug.pocoo.org/docs/\n\trsync -a docs/_build/werkzeug-docs.zip flow.srv.pocoo.org:/srv/websites/werkzeug.pocoo.org/docs/werkzeug-docs.zip\n" }, { "alpha_fraction": 0.5666666626930237, "alphanum_fraction": 0.5785714387893677, "avg_line_length": 21.105262756347656, "blob_id": "e2a10e339f411a9dce0d42c2a206ed23078edca6", "content_id": "c46620f0406f6292cab016a99864b4ec50524d68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "permissive", "max_line_length": 80, "num_lines": 19, "path": "/examples/cupoftee/utils.py", "repo_name": "thepeshka/werkzeug", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n cupoftee.utils\n ~~~~~~~~~~~~~~\n\n Various utilities.\n\n :copyright: (c) 2009 by the Werkzeug Team, see AUTHORS for more details.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport re\n\n\n_sort_re = re.compile(r'\\w+', re.UNICODE)\n\n\ndef unicodecmp(a, b):\n x, y = map(_sort_re.search, [a, b])\n return cmp((x.group() if x else a).lower(), (y.group() if y else b).lower())\n" }, { "alpha_fraction": 0.5424896478652954, "alphanum_fraction": 0.5466237664222717, "avg_line_length": 26.91025733947754, "blob_id": "9473750925c16ccb101a61802ce75ef95b709e67", "content_id": "cbcd7b66c0414718547ebab2bf909edaf971b447", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2177, "license_type": "permissive", "max_line_length": 84, "num_lines": 78, "path": "/docs/conf.py", "repo_name": "thepeshka/werkzeug", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom pallets_sphinx_themes import ProjectLink, get_version\n\n# Project --------------------------------------------------------------\n\nproject = 'Werkzeug'\ncopyright = '2007 Pallets Team'\nauthor = 'Pallets Team'\nrelease, version = get_version('Werkzeug')\n\n# General --------------------------------------------------------------\n\nmaster_doc = 'index'\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.doctest',\n 'pallets_sphinx_themes',\n]\n\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3/', None),\n 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None),\n 'jinja': ('http://jinja.pocoo.org/docs/', None),\n}\n\n# HTML -----------------------------------------------------------------\n\nhtml_theme = 'werkzeug'\nhtml_context = {\n 'project_links': [\n ProjectLink('Donate to Pallets', 'https://www.palletsprojects.com/donate'),\n ProjectLink('Werkzeug Website', 'https://palletsprojects.com/p/werkzeug/'),\n ProjectLink('PyPI releases', 'https://pypi.org/project/Werkzeug/'),\n ProjectLink('Source Code', 'https://github.com/pallets/werkzeug/'),\n ProjectLink('Issue Tracker', 'https://github.com/pallets/werkzeug/issues/'),\n ],\n}\nhtml_sidebars = {\n 'index': [\n 'project.html',\n 'versions.html',\n 'searchbox.html',\n ],\n '**': [\n 'localtoc.html',\n 'relations.html',\n 'versions.html',\n 'searchbox.html',\n ]\n}\nsinglehtml_sidebars = {\n \"index\": [\n \"project.html\",\n \"versions.html\",\n \"localtoc.html\",\n ]\n}\nhtml_static_path = ['_static']\nhtml_favicon = '_static/favicon.ico'\nhtml_logo = '_static/werkzeug.png'\nhtml_show_sourcelink = False\n\n# LaTeX ----------------------------------------------------------------\n\nlatex_documents = [\n (master_doc, 'Werkzeug.tex', 'Werkzeug Documentation', author, 'manual'),\n]\nlatex_use_modindex = False\nlatex_elements = {\n 'papersize': 'a4paper',\n 'pointsize': '12pt',\n 'fontpkg': r'\\usepackage{mathpazo}',\n 'preamble': r'\\usepackage{werkzeugstyle}',\n}\nlatex_use_parts = True\nlatex_additional_files = ['werkzeugstyle.sty', 'logo.pdf']\n" } ]
5
flufylobster/neo-python
https://github.com/flufylobster/neo-python
b65bd35dae043ab5a2656010a4c533db57731e6e
b6941e1fbbb552c11438754da7b9af516ae3ad3c
19550f35efc680645c8e3a59da7a237baba5eb07
refs/heads/master
2021-01-01T06:28:34.114590
2017-07-16T23:10:01
2017-07-16T23:10:01
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5575906038284302, "alphanum_fraction": 0.5687475800514221, "avg_line_length": 32.85589599609375, "blob_id": "e416df56a70a38b5a7fb050c80f03c3b76882b53", "content_id": "5de20e7b8c93316eda97694b97eca51e05c76e27", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15506, "license_type": "permissive", "max_line_length": 178, "num_lines": 458, "path": "/neo/Wallets/Wallet.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nDescription:\n Wallet\nUsage:\n from neo.Wallets.Wallet import Wallet\n\"\"\"\n\nfrom neo.Helper import ANTCOIN\nfrom neo.Defaults import TEST_ADDRESS\nfrom neo.Core.TX.Transaction import TransactionOutput,TransactionInput,TransactionType\nfrom neo.Core.CoinState import CoinState\nfrom neo.Core.Blockchain import Blockchain\nfrom neo.Core.CoinReference import CoinReference\nfrom neo.Cryptography.Base58 import b58decode\nfrom neo.Cryptography.Crypto import *\nfrom neo.Cryptography.Helper import *\nfrom neo.Implementations.Wallets.IndexedDBWallet import IndexedDBWallet\nfrom neo.Wallets.Account import Account\nfrom neo.Wallets.Contract import Contract\nfrom neo.Wallets.AddressState import AddressState\nfrom neo.Wallets.Coin import Coin\nfrom neo.Network.RemoteNode import RemoteNode\nfrom neo.IO.MemoryStream import MemoryStream\nfrom neo.IO.BinaryWriter import BinaryWriter\nfrom neo import Settings\n\nimport itertools\nimport hashlib\nfrom ecdsa import SigningKey, NIST256p\nfrom neo.Defaults import TEST_NODE\nfrom bitarray import bitarray\n\nfrom threading import Thread\nfrom threading import Lock\n\n\nfrom Crypto import Random\nfrom Crypto.Cipher import AES\n\nclass Wallet(object):\n\n\n\n AddressVersion = Settings.ADDRESS_VERSION\n\n _path = ''\n _iv = None\n _master_key = None\n _keys = {} #holds keypairs\n _contracts = {} #holds Contracts\n\n _watch_only = set() # holds set of hashes\n _coins = [] #holds Coin References\n\n _current_height=0\n\n _is_running = True\n _db_path = _path\n\n _indexedDB = None\n _node = None\n\n _blockThread = None\n _lock = Lock()\n\n @property\n def WalletHeight(self):\n return self._current_height\n\n\n\n\n \"\"\"docstring for Wallet\"\"\"\n def __init__(self, path, passwordKey, create):\n\n if create:\n self._path = path\n self._iv = bitarray(16)\n self._master_key = bitarray(32)\n self._keys = []\n self._indexedDB= IndexedDBWallet()\n self._node = RemoteNode(url=TEST_NODE)\n\n self._current_height = Blockchain.Default().HeaderHeight + 1 if Blockchain.Default() is not None else 0\n\n self.BuildDatabase()\n\n self._iv = Random.new().read(self._iv)\n self._master_key = Random.new().read(self._master_key)\n\n\n self.SaveStoredData('PasswordHash', hashlib.sha256(passwordKey))\n self.SaveStoredData('IV', self._iv),\n self.SaveStoredData('MasterKey', AES.new(self._master_key, AES.MODE_CBC, self._iv))\n # self.SaveStoredData('Version') { Version.Major, Version.Minor, Version.Build, Version.Revision }.Select(p => BitConverter.GetBytes(p)).SelectMany(p => p).ToArray());\n self.SaveStoredData('Height', self._current_height)\n\n else:\n\n passwordHash = self.LoadStoredData('PasswordHash')\n if passwordHash is not None and passwordHash != hashlib.sha256(passwordKey):\n raise Exception(\"Cryptographic exception\")\n\n self._iv = self.LoadStoredData('IV')\n self._master_key = self.LoadStoredData('MasterKey')\n self._keys = self.LoadKeyPair()\n self._contracts = self.LoadContracts()\n self._watch_only = self.LoadWatchOnly()\n self._coins = self.LoadCoins()\n self._current_height = self.LoadStoredData('Height')\n\n del passwordKey\n\n self._blockThread = Thread(target=self.ProcessBlocks, name='Wallet.ProcessBlocks')\n self._blockThread.start()\n\n def BuildDatabase(self):\n #abstract\n pass\n\n\n def AddContract(self, contract):\n\n# found=False\n# for key in self._key_pair:\n# if key.\n raise NotImplementedError()\n\n def SaveStoredData(self, key, value):\n\n raise NotImplementedError()\n\n def LoadStoredData(self, key):\n raise NotImplementedError()\n\n def LoadKeyPair(self):\n\n# raise NotImplementedError()\n return []\n\n def LoadContracts(self):\n# raise NotImplementedError()\n return []\n\n\n def LoadWatchOnly(self):\n# raise NotImplementedError()\n return set()\n\n def LoadCoins(self):\n# raise NotImplementedError()\n return []\n\n\n def ProcessBlocks(self):\n while self._is_running:\n\n while self._current_height <= Blockchain.Default().Height and self._is_running:\n\n block = Blockchain.Default().GetBlock(self._current_height)\n\n if block is not None:\n self.ProcessNewBlock(block)\n\n for i in range(0, 20):\n if self._is_running:\n time.sleep(1)\n\n def ProcessNewBlock(self, block):\n\n added = set()\n changed = set()\n deleted = set()\n\n self._lock.acquire()\n try:\n\n for tx in block.Transactions:\n\n for index,output in enumerate(tx.outputs):\n\n state = self.CheckAddressState(output.ScriptHash)\n\n if state > 0:\n key = CoinReference(tx.Hash, index )\n\n found=False\n for coin in self._coins:\n if coin.CoinRef.Equals(key):\n coin.State |= CoinState.Confirmed\n changed.add(coin.CoinRef)\n found = True\n if not found:\n newcoin = Coin.CoinFromRef(key, output, state=CoinState.Confirmed )\n self._coins.append(newcoin)\n added.add(newcoin.CoinRef)\n\n if state == AddressState.WatchOnly:\n for coin in self._coins:\n if coin.CoinRef.Equals(key):\n coin.State |= CoinState.WatchOnly\n changed.add(coin.CoinRef)\n\n for tx in block.Transactions:\n\n for input in tx.inputs:\n\n for coin in self._coins:\n if coin.CoinRef.Equals(input):\n\n if coin.TXOutput.AssetId == Blockchain.SystemShare().Hash():\n coin.State |= CoinState.Spent | CoinState.Confirmed\n changed.add(coin.CoinRef)\n else:\n self._coins.remove(coin)\n deleted.add(coin.CoinRef)\n\n for claimTx in [tx for tx in block.Transactions if tx.Type == TransactionType.ClaimTransaction]:\n for ref in claimTx.Claims:\n if ref in self._coins:\n self._coins.remove(ref)\n deleted.add(ref)\n\n self._current_height+=1\n self.OnProcessNewBlock(block, added, changed, deleted)\n\n if len(added) + len(deleted) + len(changed) > 0:\n self.BalanceChanged()\n\n except Exception as e:\n print(\"could not process: %s \" % e)\n finally:\n self._lock.release()\n\n\n def Rebuild(self):\n self._lock.acquire()\n self._coins = []\n self._current_height = 0\n self._lock.release()\n\n\n\n def OnProcessNewBlock(self, block, added, changed, deleted):\n # abstract\n pass\n\n def BalanceChanged(self):\n # abstract\n pass\n\n def CheckAddressState(self, script_hash):\n for contract in self._contracts:\n if contract.ScriptHash == script_hash:\n return AddressState.InWallet\n for watch in self._watch_only:\n if watch.ScriptHash == script_hash:\n return AddressState.WatchOnly\n return AddressState.NoState\n\n @staticmethod\n def ToAddress(scripthash):\n return scripthash_to_address(scripthash)\n\n def ToScriptHash(self, address):\n data = b58decode(address)\n if len(data) != 25:\n raise ValueError('Not correct Address, wrong length.')\n if data[0] != self.AddressVersion:\n raise ValueError('Not correct Coin Version')\n scriptHash = binascii.hexlify(data[1:21])\n if Wallet.ToAddress(scriptHash) == address:\n return scriptHash\n else:\n raise ValueError('Not correct Address, something wrong in Address[-4:].')\n\n def ValidatePassword(self, password):\n return hashlib.sha256(password) == self.LoadStoredData('PasswordHash')\n\n def FindUnSpentCoins(self, scriptHash):\n \"\"\":return: Coin[]\"\"\"\n return self.indexeddb.findCoins(self.ToAddress(scriptHash), status=CoinState.Unspent)\n\n def MakeTransaction(self, tx, account):\n \"\"\"Make Transaction\"\"\"\n if tx.outputs == None:\n raise ValueError('Not correct Address, wrong length.')\n\n if tx.attributes == None:\n tx.attributes = []\n\n coins = self.findUnSpentCoins(account.scriptHash)\n tx.inputs, tx.outputs = self.selectInputs(tx.outputs, coins, account, tx.systemFee)\n\n # Make transaction\n stream = MemoryStream()\n writer = BinaryWriter(stream)\n tx.serializeUnsigned(writer)\n reg_tx = stream.toArray()\n tx.ensureHash()\n txid = tx.hash\n\n # RedeenScript\n contract = Contract()\n contract.CreateSignatureContract(account.publicKey)\n Redeem_script = contract.RedeemScript\n\n # Add Signature\n sk = SigningKey.from_string(binascii.unhexlify(account.privateKey), curve=NIST256p, hashfunc=hashlib.sha256)\n signature = binascii.hexlify(sk.sign(binascii.unhexlify(reg_tx),hashfunc=hashlib.sha256))\n regtx = reg_tx + '014140' + signature + '23' + Redeem_script\n # sendRawTransaction\n print(regtx)\n response = self.node.sendRawTransaction(regtx)\n import json\n print(response)\n return txid\n\n def selectInputs(self, outputs, coins, account, fee):\n\n scripthash = account.scriptHash\n\n if len(outputs) > 1 and len(coins) < 1:\n raise Exception('Not Enought Coins')\n\n # Count the total amount of change\n coin = itertools.groupby(sorted(coins, key=lambda x: x.asset), lambda x: x.asset)\n coin_total = dict([(k, sum(int(x.value) for x in g)) for k,g in coin])\n\n # Count the pay total\n pays = itertools.groupby(sorted(outputs, key=lambda x: x.AssetId), lambda x: x.AssetId)\n pays_total = dict([(k, sum(int(x.Value) for x in g)) for k,g in pays])\n\n if int(fee.f) > 0:\n if ANTCOIN in iter(list(pays_total.keys())):\n pays_total[ANTCOIN] += int(fee.f)\n else:\n pays_total[ANTCOIN] = int(fee.f)\n\n # Check whether there is enough change\n for asset, value in list(pays_total.items()):\n if asset not in coin_total:\n raise Exception('Coins does not contain asset {asset}.'.format(asset=asset))\n\n if coin_total.get(asset) - value < 0:\n raise Exception('Coins does not have enough asset {asset}, need {amount}.'.format(asset=asset, amount=value))\n\n # res: used Coins\n # change: change in outpus\n res = []\n change = []\n\n # Copy the parms\n _coins = coins[:]\n\n # Find whether have the same value of change\n for asset, value in list(pays_total.items()):\n for _coin in _coins:\n if asset == _coin.asset and value == int(_coin.value):\n # Find the coin\n res.append(TransactionInput(prevHash=_coin.txid, prevIndex=_coin.idx))\n _coins.remove(_coin)\n break\n\n else:\n # Find the affordable change\n\n affordable = sorted([i for i in _coins if i.asset == asset and int(i.value) >= value],\n key=lambda x: int(x.value))\n\n # Use the minimum if exists\n if len(affordable) > 0:\n res.append(TransactionInput(prevHash=affordable[0].txid, prevIndex=affordable[0].idx))\n _coins.remove(affordable[0])\n\n # If the amout > value, set the change\n amount = int(affordable[0].value)\n if amount > value:\n change.append(TransactionOutput(AssetId=asset, Value=str(amount-value), ScriptHash=scripthash))\n\n else:\n # Calculate the rest of coins\n rest = sorted([i for i in _coins if i.asset == asset],\n key=lambda x: int(x.value),\n reverse=True)\n\n amount = 0\n for _coin in rest:\n amount += int(_coin.value)\n res.append(TransactionInput(prevHash=_coin.txid, prevIndex=_coin.idx))\n _coins.remove(_coin)\n if amount == value:\n break\n elif amount > value:\n # If the amout > value, set the change\n change.append(TransactionOutput(AssetId=asset, Value=str(amount-value), ScriptHash=scripthash))\n break\n\n return res, outputs + change\n\n def selectCoins(self, coins, outputs):\n \"\"\"the simplest alg of selecting coins\"\"\"\n total = sum([int(out['amount']) for out in outputs])\n cs = sorted(coins,key=lambda c:c.value,reverse=True)\n print(total)\n inputs = []\n # has no enough coins\n if sum([int(c.value) for c in coins]) < total:\n return inputs\n for i in range(len(cs)):\n #step 1: find the coin with value==total\n if cs[i].value == total:\n inputs = [cs[i],]\n break\n #step 2: find the min coin with value>total\n if cs[0].value > total and cs[i].value<total:\n inputs = [cs[i-1],]\n break\n #step 3: find the min(max coins) with sum(coins)>= total\n inputs.append(cs[i])\n if cs[0].value<total and sum([i.value for i in inputs]) >= total:\n break\n return inputs\n\n\ndef __test():\n wallet = Wallet()\n coins = wallet.indexeddb.loadCoins(address=TEST_ADDRESS,asset='dc3d9da12d13a4866ced58f9b611ad0d1e9d5d2b5b1d53021ea55a37d3afb4c9')\n #print coins\n print('test1: select the min max coin')\n outputs = [{'work_id':'12687','amount':80}, {'work_id':'12689','amount':100}]\n inputs = wallet.selectCoins(coins,outputs)\n for i in inputs:\n print(i)\n print('test2: select the equal coin')\n outputs = [{'work_id':'12687','amount':1},]\n inputs = wallet.selectCoins(coins,outputs)\n for i in inputs:\n print(i)\n print('test3: select the min(max coins)')\n outputs = [{'work_id':'12687','amount':232},{'work_id':'12689','amount':10}]\n inputs = wallet.selectCoins(coins,outputs)\n for i in inputs:\n print(i)\n print('test4: select none coin')\n outputs = [{'work_id':'12687','amount':10000},{'work_id':'12689','amount':10}]\n inputs = wallet.selectCoins(coins,outputs)\n for i in inputs:\n print(i)\n print('test5: select the min max coin')\n outputs = [{'work_id':'12687','amount':2},]\n inputs = wallet.selectCoins(coins,outputs)\n for i in inputs:\n print(i)\n\nif __name__ == '__main__':\n __test()\n" }, { "alpha_fraction": 0.5353728532791138, "alphanum_fraction": 0.5736137628555298, "avg_line_length": 16.46666717529297, "blob_id": "18e36a5419177c5e9d12c72f0cddd87788ae81bd", "content_id": "365b0fedd2ceeb6da64bdc9fd55ccb1f802b17d9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 523, "license_type": "permissive", "max_line_length": 53, "num_lines": 30, "path": "/neo/Fixed8.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nDescription:\n Fixed8\nUsage:\n from neo.Fixed8 import Fixed8\n\"\"\"\n\n\nfrom decimal import Decimal as D\nfrom neo.Helper import big_or_little\n\n\nclass Fixed8:\n\n\n\n \"\"\"docstring for Fixed8\"\"\"\n def __init__(self, number):\n self.f = D(str(number))\n\n def getData(self):\n hex_str = hex(int(self.f*D('100000000')))[2:]\n if len(hex_str)%2:\n hex_str = '0' + hex_str\n return big_or_little(hex_str)\n\n @staticmethod\n def Satoshi():\n return Fixed8(1)" }, { "alpha_fraction": 0.6308243870735168, "alphanum_fraction": 0.6375149488449097, "avg_line_length": 27.080537796020508, "blob_id": "c7d3c2d6540d8c209b5f14a68b884263781f490f", "content_id": "2c672e1687f479397fe432286a984e850f3b83b1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4297, "license_type": "permissive", "max_line_length": 158, "num_lines": 149, "path": "/neo/Core/BlockBase.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nfrom neo.Cryptography import *\nfrom neo.IO import *\nfrom neo.Wallets import *\nfrom .Mixins import VerifiableMixin\nfrom neo.Cryptography.Crypto import *\nfrom neo.Core.Blockchain import Blockchain\nfrom neo.Core.Helper import Helper\nimport json\nimport ctypes\nimport hashlib\n\nclass BlockBase(VerifiableMixin):\n\n # <summary>\n # 区块版本\n # </summary>\n Version=None\n # <summary>\n # 前一个区块的散列值\n # </summary>\n PrevHash=None\n # <summary>\n # 该区块中所有交易的Merkle树的根\n # </summary>\n MerkleRoot = None\n # <summary>\n # 时间戳\n # </summary>\n Timestamp = None\n # <summary>\n # 区块高度\n # </summary>\n Index =0\n\n ConsensusData=None\n # <summary>\n # 下一个区块的记账合约的散列值\n # </summary>\n NextConsensus = None\n # <summary>\n # 用于验证该区块的脚本\n # </summary>\n Script = None\n\n __hash = None\n\n\n\n def Hash(self):\n if not self.__hash:\n self.__hash = Crypto.Hash256(self.GetHashData())\n\n return self.__hash\n\n\n def Size(self):\n# sizeof(uint) + PrevHash.Size + MerkleRoot.Size + sizeof(uint) + sizeof(uint) + sizeof(\n# ulong) + NextConsensus.Size + 1 + Script.Size;\n\n uintsize = ctypes.sizeof(ctypes.c_uint)\n ulongsize = ctypes.sizeof(ctypes.c_ulong)\n return uintsize + self.PrevHash.Size() + self.MerkleRoot.Size() + uintsize + uintsize + ulongsize + self.NextConsensus.Size() + 1 + self.Script.Size()\n\n\n def Deserialize(self, reader):\n self.DeserializeUnsigned(reader)\n if reader.ReadByte() != 1:\n raise Exception('Incorrect format')\n self.Script = reader.readSerializableArray(self.scripts)\n\n\n def DeserializeUnsigned(self, reader):\n self.Version = reader.readUInt32()\n self.PrevHash = reader.readSerializableArray()\n self.MerkleRoot = reader.readSerializableArray()\n self.Timestamp = reader.readUInt32()\n self.Index = reader.readUInt32()\n self.ConsensusData = reader.readUInt64()\n self.NextConsensus = reader.readSerializableArray()\n\n def SerializeUnsigned(self, writer):\n writer.writeUInt32(self.Version)\n writer.writeSerializableArray(self.PrevHash)\n writer.writeSerializableArray(self.MerkleRoot)\n writer.writeUInt32(self.Timestamp)\n writer.writeUInt32(self.Index)\n writer.writeUInt64(self.ConsensusData)\n writer.writeSerializableArray(self.NextConsensus)\n\n def GetHashData(self):\n raise NotImplementedError('Not Implemented')\n\n def GetMessage(self):\n return self.GetHashData()\n\n\n def GetScriptHashesForVerifying(self):\n if self.PrevHash == None:\n return [ self.Script.VerificationScript.ToScriptHash()]\n\n prev_header = Blockchain.Default().GetHeader(self.PrevHash)\n if prev_header == None:\n raise Exception('Invalid operation')\n return [ prev_header.NextConsensus ]\n\n\n\n def Serialize(self, writer):\n self.SerializeUnsigned(writer)\n writer.writeByte(1)\n writer.writeSerializableArray(self.Script)\n\n\n\n def ToArray(self):\n raise NotImplementedError()\n\n def ToJson(self):\n json = {}\n json[\"hash\"] = self.__hash.toString()\n\n json[\"size\"] = self.Size\n json[\"version\"] = self.Version\n json[\"previousblockhash\"] = self.PrevHash.ToString()\n json[\"merkleroot\"] = self.MerkleRoot.ToString()\n json[\"time\"] = self.Timestamp\n json[\"index\"] = self.Index\n json[\"nonce\"] = self.ConsensusData.ToString(\"x16\")\n json[\"nextconsensus\"] = self.Wallet.ToAddress(self.NextConsensus)\n json[\"script\"] = self.Script.ToJson()\n return json\n\n def Verify(self):\n if self.Hash == Blockchain.GenesisBlock.Hash: return True\n\n if Blockchain.Default().ContainsBlock(self.Hash): return True\n\n prev_header = Blockchain.Default().GetHeader(self.PrevHash)\n\n if prev_header == None: return False\n\n if prev_header.Index + 1 != self.Index: return False\n\n if prev_header.Timestamp >= self.Timestamp: return False\n\n if not Helper.VerifyScripts(self): return False\n\n return True\n\n" }, { "alpha_fraction": 0.6784090995788574, "alphanum_fraction": 0.6924242377281189, "avg_line_length": 42.278690338134766, "blob_id": "2b4598a7112eafd80f7a7c8b86c9a5323c6c417a", "content_id": "19488abc0a3366850a62c0f8090f7903aab307f8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3116, "license_type": "permissive", "max_line_length": 313, "num_lines": 61, "path": "/neo/Core/TX/RegisterTransaction.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nDescription:\n Register Transaction\nUsage:\n from neo.Core.TX.RegisterTransaction import RegisterTransaction\n\"\"\"\nfrom neo.Fixed8 import Fixed8\nfrom neo.Core.TX.Transaction import Transaction,TransactionType\n\nimport binascii\nfrom neo.Core.AssetType import AssetType\n\nclass RegisterTransaction(Transaction):\n \"\"\"\n # 发行总量,共有2种模式:\n # 1. 限量模式:当Amount为正数时,表示当前资产的最大总量为Amount,且不可修改(股权在未来可能会支持扩股或增发,会考虑需要公司签名或一定比例的股东签名认可)。\n # 2. 不限量模式:当Amount等于-1时,表示当前资产可以由创建者无限量发行。这种模式的自由度最大,但是公信力最低,不建议使用。\n # 在使用过程中,根据资产类型的不同,能够使用的总量模式也不同,具体规则如下:\n # 1. 对于股权,只能使用限量模式;\n # 2. 对于货币,只能使用不限量模式;\n # 3. 对于点券,可以使用任意模式;\n\n\nIn English:\n # Total number of releases, there are 2 modes:\n         # 1. Limited amount: When Amount is positive, it means that the maximum amount of current assets is Amount and can not be modified (the equity may support the expansion or issuance in the future, will consider the need for company signature or a certain percentage of shareholder signature recognition ).\n         # 2. Unlimited mode: When Amount is equal to -1, it means that the current asset can be issued by the creator unlimited. This mode of freedom is the largest, but the credibility of the lowest, not recommended.\n         # In the use of the process, according to the different types of assets, can use the total amount of different models, the specific rules are as follows:\n         # 1. For equity, use only limited models;\n         # 2. For currencies, use only unlimited models;\n         # 3. For point coupons, you can use any pattern;\n\"\"\"\n\n def __init__(self, inputs=[], outputs=[], assettype=AssetType.AntShare, assetname='', amount=Fixed8(0), issuer=None, admin=None):\n super(RegisterTransaction, self).__init__(inputs, outputs)\n self.TransactionType = TransactionType.RegisterTransaction # 0x40\n\n self.AssetType = assettype\n self.Name = binascii.hexlify(\"[{'lang':'zh-CN','name':'%s'}]\" % str(assetname))\n\n self.Amount = Fixed8(amount) # Unlimited Mode: -0.00000001\n self.Issuer = issuer\n self.Admin = admin\n\n def getSystemFee(self):\n return Fixed8(100)\n\n def GetScriptHashesForVerifying(self):\n \"\"\"Get ScriptHash From SignatureContract\"\"\"\n # hashes = {}\n # super(RegisterTransaction, self).getScriptHashesForVerifying()\n pass\n\n\n def SerializeExclusiveData(self, writer):\n writer.writeByte(self.AssetType)\n writer.writeVarBytes(self.Name)\n writer.writeFixed8(self.Amount)\n writer.writeBytes(self.Issuer)\n writer.writeBytes(self.Admin)\n" }, { "alpha_fraction": 0.5498241782188416, "alphanum_fraction": 0.6096131205558777, "avg_line_length": 24.117647171020508, "blob_id": "ca5636dbf1ea86c9fbdd89e21153aeb9c132a523", "content_id": "df0ec0eee4013c3da7bfd8a93f3585e84df9b8d1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "permissive", "max_line_length": 77, "num_lines": 34, "path": "/neo/Helper.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "\"\"\"\nDescription:\n big_or_little\nUsage:\n from neo.Helper import *\n\"\"\"\n\nANTCOIN = 'f252a09a24591e8da31deec970871cc7678cb55023db049551e91f7bac28e27b'\n\n\ndef big_or_little(string):\n arr = bytearray(str(string))\n length = len(arr)\n for idx in range(length/2):\n if idx%2 == 0:\n arr[idx], arr[length-2-idx] = arr[length-2-idx], arr[idx]\n else:\n arr[idx], arr[length - idx] = arr[length - idx], arr[idx]\n return bytes(arr)\n\ndef big_or_little_str(string):\n arr = bytearray(string)\n length = len(arr)\n for index in range(length/2):\n if index%2 == 0:\n arr[index], arr[length-2-index] = arr[length-2-index], arr[index]\n else:\n arr[index], arr[length -index] = arr[length -index], arr[index]\n return str(arr)\n\n\ndef GetVarSize(list):\n\n raise NotImplementedError()" }, { "alpha_fraction": 0.6034985184669495, "alphanum_fraction": 0.6501457691192627, "avg_line_length": 27.5, "blob_id": "1e7aa4fdd0f8af22e571eb5855c2191d05603a13", "content_id": "a32d936c529004edbc7054b8323c6cd3b8797d7e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "permissive", "max_line_length": 77, "num_lines": 12, "path": "/neo/Defaults.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "\nTEST_NODE = \"http://seed1.antshares.org:20333/\"\nTEST_MONGO_HOST = 'localhost'\nTEST_ADDRESS = 'AFsRovA3GyLznpAyAYXiv8ZwDswKj1g5A2'\n\nclass Mongo:\n def __init__(self, host=TEST_MONGO_HOST, port=27017, usr=None, pwd=None):\n self.host = host\n self.port = port\n self.usr = usr\n self.pwd = pwd\n\nBlockChainDB = Mongo()\n" }, { "alpha_fraction": 0.44078946113586426, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 14.199999809265137, "blob_id": "c0605eb50cc90955ae75a86533a79c9475e3453e", "content_id": "920097ee94d51a8db9be26d1f669e082e95afae9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 152, "license_type": "permissive", "max_line_length": 18, "num_lines": 10, "path": "/requirements.txt", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "bitarray==0.8.1\nbitcoin==1.1.42\ncertifi==2017.4.17\nchardet==3.0.4\necdsa==0.13\nidna==2.5\npycrypto==2.6.1\npymongo==3.4.0\nrequests==2.18.1\nurllib3==1.21.1\n" }, { "alpha_fraction": 0.6768332123756409, "alphanum_fraction": 0.6826735734939575, "avg_line_length": 28.634614944458008, "blob_id": "ee79ff17fdef99f2a264f0a5e71029eee8a31e36", "content_id": "96bc6c194bb4c1f3c131a61eca5086e0883ca894", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3082, "license_type": "permissive", "max_line_length": 122, "num_lines": 104, "path": "/neo/Wallets/Contract.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nDescription:\n Contract class in neo.Wallets\n Base class of all contracts\nUsage:\n from neo.Wallets.Contract import Contract\n\"\"\"\n\nfrom neo.Core.Scripts.ScriptOp import *\nfrom neo.Cryptography.Helper import *\nfrom neo.Cryptography.Crypto import *\nfrom neo.IO.Mixins import SerializableMixin\nfrom neo.Wallets.ContractParameterType import ContractParameterType\nfrom neo.Core.Scripts.ScriptBuilder import ScriptBuilder, ScriptOp\n\n\nclass Contract(SerializableMixin):\n \"\"\"docstring for Contract\"\"\"\n\n RedeemScript=None\n ParameterList = None\n PubKeyHash = None\n ScriptHash = None\n\n def __init__(self, redeem_script, param_list, pubkey_hash, script_hash):\n super(Contract, self).__init__()\n\n self.RedeemScript = redeem_script\n self.ParameterList = param_list\n self.PubKeyHash = pubkey_hash\n self.ScriptHash = script_hash\n\n\n @staticmethod\n def Create(publicKeyHash, parameterList, redeemScript):\n\n return Contract(redeemScript, parameterList, publicKeyHash, Contract.RedeemToScripthash(redeemScript))\n\n\n\n @staticmethod\n def CreateMultiSigContract(publickKeyHash, m, publicKeys):\n raise NotImplementedError()\n\n @staticmethod\n def CreateMultiSigRedeemScript(m, publicKeys):\n raise NotImplementedError()\n\n @staticmethod\n def CreateSignatureContract(publicKey):\n result = Contract.RedeemToScripthash(Contract.PubkeyToRedeem(publicKey))\n return Contract.Create(result, [ContractParameterType.Signature], Contract.CreateSignatureRedeemScript(publicKey))\n\n @staticmethod\n def CreateSignatureRedeemScript(publicKey):\n sb = ScriptBuilder()\n sb.push(publicKey)\n sb.add(ScriptOp.CHECKSIG)\n return sb.toArray()\n\n def Equals(self, other):\n if id(self) == id(other):\n return True\n if not isinstance(other, Contract):\n return False\n return self.ScriptHash == other.ScriptHash\n\n def GetAddress(self):\n # TODO\n raise NotImplementedError()\n\n def GetHashCode(self):\n if self.ScriptHash == None:\n self.ScriptHash = Contract.RedeemToScripthash(self.RedeemScript)\n return self.ScriptHash\n\n def ToScriptHash(self):\n return Crypto.Hash160(self.ScriptHash)\n\n def IsStandard(self):\n if len(self.RedeemScript) / 2 != 35:\n return False\n array = self.RedeemScript[:]\n if array[:2] != '21' or array[-2:] != 'ac':\n return False\n return True\n\n def Serialize(self, writer):\n writer.writeBytes(self.ScriptHash)\n writer.writeBytes(self.PubKeyHash)\n writer.writeVarBytes(self.ParameterList) # TODO need check\n writer.writeVarBytes(self.RedeemScript)\n\n def Deserialize(self, reader):\n raise NotImplementedError()\n\n @staticmethod\n def PubkeyToRedeem(pubkey):\n return binascii.unhexlify('21'+ pubkey) + from_int_to_byte(int('ac',16))\n\n @staticmethod\n def RedeemToScripthash(redeem):\n return binascii.hexlify(bin_hash160(redeem))\n" }, { "alpha_fraction": 0.723549485206604, "alphanum_fraction": 0.7303754091262817, "avg_line_length": 17.25, "blob_id": "481e89e70cada0f09e8d38594b5097e9d8e7803b", "content_id": "3eed400e2bb254c8a3f9003dcff4796e7e7bc8a3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 293, "license_type": "permissive", "max_line_length": 54, "num_lines": 16, "path": "/README.md", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "## neo-python: Python SDK for NEO platform\n\nIn progress, please reach out in order to contribute\n\n### Getting started\n\n- make a python 3 virtual environment, and activate it\n```\npython3 -m venv venv\nsource venv/bin/activate\n```\n\n- install requirements\n```\npip install -r requirements.txt\n```\n\n" }, { "alpha_fraction": 0.6983240246772766, "alphanum_fraction": 0.6983240246772766, "avg_line_length": 18.66666603088379, "blob_id": "8b94cb9345227dd67a29745632f60cd065ce7082", "content_id": "aeb308806c151edc6dcd116ac2000aae1ac54810", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "permissive", "max_line_length": 43, "num_lines": 9, "path": "/neo/Network/Mixins.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "\nfrom neo.Core.Mixins import VerifiableMixin\n\nclass InventoryMixin(VerifiableMixin):\n\n hash = None\n inventory_type = None\n\n def Verify(self, mempool=None):\n pass\n\n" }, { "alpha_fraction": 0.6031386256217957, "alphanum_fraction": 0.6054036617279053, "avg_line_length": 29.780000686645508, "blob_id": "801ab04e70db49038c95fc1e087538b3dfa3ca69", "content_id": "60578d55f1ec9923b7a996014d489084db8d93fa", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6569, "license_type": "permissive", "max_line_length": 153, "num_lines": 200, "path": "/neo/Core/Block.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\nfrom neo.Network.Mixins import InventoryMixin\nfrom neo.Network.InventoryType import InventoryType\nfrom neo.Core.BlockBase import BlockBase\nfrom neo.Core.Blockchain import Blockchain\nfrom neo.Core.TX.Transaction import Transaction,TransactionType\nfrom neo.IO.MemoryStream import MemoryStream\nfrom neo.IO.BinaryReader import BinaryReader\nfrom neo.IO.BinaryWriter import BinaryWriter\nfrom neo.Cryptography.MerkleTree import MerkleTree\nfrom json import dumps\nimport sys\n\n# < summary >\n# 区块或区块头\n# < / summary >\nclass Block(BlockBase, InventoryMixin):\n\n # < summary >\n # 交易列表\n # < / summary >\n Transactions = []\n\n # < summary >\n # 该区块的区块头\n # < / summary >\n\n __header = None\n\n # < summary >\n # 资产清单的类型\n # < / summary >\n InventoryType = InventoryType.Block\n\n\n def __init__(self, prevHash=None, timestamp=None, index=None,\n consensusData=None, nextConsensus=None, script=None, transactions=None):\n\n super(Block, self).__init__()\n\n self.PrevHash = prevHash\n self.Timestamp = timestamp\n self.Index = index\n self.ConsensusData = consensusData\n self.NextConsensus = nextConsensus\n self.Script = script\n self.Transactions = transactions\n\n\n def Header(self):\n if not self.__header:\n\n\n self.__header = {\n 'PrevHash' : self.PrevHash,\n 'MerkleRoot' : self.MerkleRoot,\n 'Timestamp' : self.Timestamp,\n 'Index' : self.Index,\n 'ConsensusData' : self.ConsensusData,\n 'NextConsensus' : self.NextConsensus,\n 'Script' : self.Script,\n }\n\n return self.__header\n\n\n def Size(self):\n s = self.Size()\n s = s + sys.getsizeof(self.Transactions)\n\n return s\n\n\n def CalculatneNetFee(self, transactions):\n# Transaction[] ts = transactions.Where(p= > p.Type != TransactionType.MinerTransaction & & p.Type != TransactionType.ClaimTransaction).ToArray();\n# Fixed8 amount_in = ts.SelectMany(p= > p.References.Values.Where(o= > o.AssetId == Blockchain.SystemCoin.Hash)).Sum(p= > p.Value);\n# Fixed8 amount_out = ts.SelectMany(p= > p.Outputs.Where(o= > o.AssetId == Blockchain.SystemCoin.Hash)).Sum(p= > p.Value);\n# Fixed8 amount_sysfee = ts.Sum(p= > p.SystemFee);\n# return amount_in - amount_out - amount_sysfee;\n return 0\n\n\n # < summary >\n # 反序列化\n # < / summary >\n # < param name = \"reader\" > 数据来源 < / param >\n def Deserialize(self, reader):\n super(BlockBase,self).Deserialize(reader)\n self.Transactions = [ Transaction(reader.ReadVarInt(0x10000)),]\n\n if len(self.Transactions) < 1:\n raise Exception('Invalid format')\n\n [tx.DeserializeFrom(reader) for tx in self.Transactions]\n\n if MerkleTree.ComputeRoot( [tx.Hash() for tx in self.Transactions]) != self.MerkleRoot:\n raise Exception('Invalid Format')\n\n\n # < summary >\n # 比较当前区块与指定区块是否相等\n # < / summary >\n # < param name = \"other\" > 要比较的区块 < / param >\n # < returns > 返回对象是否相等 < / returns >\n\n def Equals(self, other):\n\n if other is None: return False\n if other is self: return True\n return self.Hash() == other.Hash()\n\n\n\n @staticmethod\n def FromTrimmedData(bytes, index, transaction_method):\n block = Block()\n# ms = MemoryStream(bytes, index, (len(bytes) - index))\n ms = MemoryStream()\n reader = BinaryReader(ms)\n\n block.DeserializeUnsigned(reader)\n reader.readByte()\n block.Script = reader.readSerializableArray()\n block.Transactions = []\n for i in range(0, reader.readVarInt()):\n block.Transactions[i] = transaction_method( reader.readSerializableArray())\n\n # < summary >\n # 获得区块的HashCode\n # < / summary >\n # < returns > 返回区块的HashCode < / returns >\n def GetHashCode(self):\n return self.Hash().GetHashCode()\n\n # < summary >\n # 根据区块中所有交易的Hash生成MerkleRoot\n # < / summary >\n def RebuildMerkleRoot(self):\n self.MerkleRoot = MerkleTree.ComputeRoot([tx.Hash() for tx in self.Transactions])\n\n # < summary >\n # 序列化\n # < / summary >\n # < param name = \"writer\" > 存放序列化后的数据 < / param >\n def Serialize(self, writer):\n super(BlockBase,self).Serialize(writer)\n writer.writeSerializableArray(self.Transactions)\n\n # < summary >\n # 变成json对象\n # < / summary >\n # < returns > 返回json对象 < / returns >\n def ToJson(self):\n\n return dumps(self)\n\n # < summary >\n # 把区块对象变为只包含区块头和交易Hash的字节数组,去除交易数据\n # < / summary >\n # < returns > 返回只包含区块头和交易Hash的字节数组 < / returns >\n def Trim(self):\n ms = MemoryStream()\n writer = BinaryWriter(ms)\n\n self.SerializeUnsigned(writer)\n writer.writeByte(1)\n writer.writeSerializableArray(self.Script)\n writer.writeSerializableArray([tx.Hash() for tx in self.Transactions])\n\n return ms.toArray()\n\n # < summary >\n # 验证该区块是否合法\n # < / summary >\n # < paramname = \"completely\" > 是否同时验证区块中的每一笔交易 < / param >\n # < returns > 返回该区块的合法性,返回true即为合法,否则,非法。 < / returns >\n def Verify(self, completely=False):\n\n if not self.Verify(): return False\n\n for tx in self.Transactions:\n if tx.Type == TransactionType.MinerTransaction: return False\n \n if completely:\n if self.NextConsensus != Blockchain.GetConsensusAddress(Blockchain.Default().GetValidators(self.Transactions).ToArray()):\n return False\n \n for tx in self.Transactions:\n if not tx.Verify():\n pass\n\n raise NotImplementedError()\n ## do this below!\n #foreach(Transaction tx in Transactions)\n #if (!tx.Verify(Transactions.Where(p = > !p.Hash.Equals(tx.Hash)))) return false;\n #Transaction tx_gen = Transactions.FirstOrDefault(p= > p.Type == TransactionType.MinerTransaction);\n #if (tx_gen?.Outputs.Sum(p = > p.Value) != CalculateNetFee(Transactions)) return false;\n\n return True\n \n " }, { "alpha_fraction": 0.6358209252357483, "alphanum_fraction": 0.6388059854507446, "avg_line_length": 24.125, "blob_id": "ac52adeb40341cd541e09a72b0be7f6b3caaeb3d", "content_id": "b945bf3ce82e4c50c3107497944da9bd6878e87f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1005, "license_type": "permissive", "max_line_length": 75, "num_lines": 40, "path": "/neo/Wallets/Account.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nDescription:\n Account class in neo.Wallets\nUsage:\n from neo.Wallets.Account import Account\n\"\"\"\n\n\nimport binascii\nfrom bitcoin import random\n\nfrom neo.Cryptography.Helper import *\n\n\nclass Account(object):\n \"\"\"docstring for Account\"\"\"\n def __init__(self, privateKey=None):\n super(Account, self).__init__()\n if privateKey == None or len(binascii.unhexlify(privateKey)) != 32:\n self.privateKey = random_to_priv(random_key())\n else:\n self.privateKey = privateKey\n\n self.publicKey = privkey_to_pubkey(self.privateKey)\n redeemScript = pubkey_to_redeem(self.publicKey)\n self.scriptHash = redeem_to_scripthash(redeemScript)\n self.address = scripthash_to_address(self.scriptHash)\n\ndef __test():\n privKey = 'e54aa6d215a97b398f7124aae578f715a6549a40b312d717c7123360832c2387'\n acc = Account(privateKey=privKey)\n print((acc.publicKey))\n print((acc.privateKey))\n print((acc.address))\n print((acc.scriptHash))\n\n\nif __name__ == '__main__':\n __test()\n" }, { "alpha_fraction": 0.6350710988044739, "alphanum_fraction": 0.6407582759857178, "avg_line_length": 21.913043975830078, "blob_id": "da50388c62b93435dd417c960123c1d501134dcc", "content_id": "b8b87ae970ff97c3f7b77eb60ff21fe1fe35b039", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1055, "license_type": "permissive", "max_line_length": 54, "num_lines": 46, "path": "/neo/Core/Header.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\nfrom neo.Core.BlockBase import BlockBase\nfrom neo.IO.MemoryStream import MemoryStream\nfrom neo.IO.BinaryReader import BinaryReader\nfrom bitarray import bitarray\n\nclass Header(BlockBase):\n\n def Size(self):\n return super(Header,self).Size() + 1\n\n def Deserialize(self, reader):\n super(Header, self).Deserialize(reader)\n if reader.readByte() != 0:\n raise Exception('Incorrect Header Format')\n\n def Equals(self, other):\n\n if other is None: return False\n if other is self: return True\n return self.Hash() == other.Hash()\n\n\n def FromTrimmedData(self, data, index):\n\n header = Header()\n\n ms = MemoryStream()\n\n reader = BinaryReader(ms)\n\n self.DeserializeUnsigned(reader)\n reader.readByte()\n header.Script = reader.readSerializableArray()\n\n return header\n\n def GetHashCode(self):\n return self.Hash()\n\n\n def Serialize(self, writer):\n\n super(Header, self).Serialize(writer)\n writer.writeByte(0x00)\n\n" }, { "alpha_fraction": 0.6287015676498413, "alphanum_fraction": 0.6366742849349976, "avg_line_length": 18.46666717529297, "blob_id": "427865bfb45df73265badd6c148f229e28a82499", "content_id": "71bcc2625583a00c3e1d19eba2a7a25b17e0709d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 878, "license_type": "permissive", "max_line_length": 63, "num_lines": 45, "path": "/neo/Core/Helper.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "\nfrom neo.Cryptography.Crypto import *\n\nclass Helper(object):\n\n\n @staticmethod\n def WeightedFilter(list):\n raise NotImplementedError()\n\n @staticmethod\n def WeightedAverage(list):\n raise NotImplementedError()\n\n @staticmethod\n def GetHashData(hashable):\n\n raise NotImplementedError()\n\n\n @staticmethod\n def Sign(signable, keypair):\n\n raise NotImplementedError()\n\n\n @staticmethod\n def ToScriptHash(scripts):\n return Crypto.Hash160(scripts)\n\n @staticmethod\n def VerifyScripts(verifiable):\n\n max_steps = 3000\n hashes = []\n\n try:\n hashes = verifiable.GetScriptHashesForVerifying()\n except Exception as e:\n return False\n\n if len(hashes) != len(verifiable.Scripts): return False\n\n ### @TODO script hash verifying!\n\n raise NotImplementedError()\n\n" }, { "alpha_fraction": 0.7685950398445129, "alphanum_fraction": 0.7685950398445129, "avg_line_length": 16.285715103149414, "blob_id": "6918fc1ce52212cee02cfeacb02c0eb1475876a5", "content_id": "d7545a1a0aecc6d036e9169040d7fdbc8097b206", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "permissive", "max_line_length": 29, "num_lines": 7, "path": "/neo/Wallets/KeyPair.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "from bitarray import bitarray\nimport ecdsa\nfrom ecdsa.keys import e\nclass KeyPair(object):\n\n\n PrivateKey = bitarray()\n" }, { "alpha_fraction": 0.6878612637519836, "alphanum_fraction": 0.7148362398147583, "avg_line_length": 21.60869598388672, "blob_id": "7d5c321aa7eebbadf19856e3ccfef3044ff523da", "content_id": "507d38403682a975dda2a5164106a457ae904d46", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 519, "license_type": "permissive", "max_line_length": 76, "num_lines": 23, "path": "/neo/Cryptography/Helper.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nDescription:\n Cryptography Helper\nUsage:\n from neo.Cryptography.Helper import *\n\"\"\"\n\n\nimport binascii\nfrom bitcoin import *\n\ndef random_to_priv(key):\n return binascii.hexlify(key)\n\ndef pubkey_to_redeem(pubkey):\n return binascii.unhexlify('21'+ pubkey) + from_int_to_byte(int('ac',16))\n\ndef redeem_to_scripthash(redeem):\n return binascii.hexlify(bin_hash160(redeem))\n\ndef scripthash_to_address(scripthash):\n return bin_to_b58check(binascii.unhexlify(scripthash),int('17',16))" }, { "alpha_fraction": 0.6017881631851196, "alphanum_fraction": 0.6642022132873535, "avg_line_length": 44.80315017700195, "blob_id": "249d4bb3a78e87b7ff021a9f68d7b922f436553b", "content_id": "d136dcacbf9ec8eb5f896858770997daf737681a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5838, "license_type": "permissive", "max_line_length": 105, "num_lines": 127, "path": "/neo/Core/Scripts/ScriptOp.py", "repo_name": "flufylobster/neo-python", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nDescription:\n Script OP Code\nUsage:\n from neo.Core.Scripts.ScriptOp import ScriptOp\n\"\"\"\n\nclass ScriptOp(object):\n # Constants\n PUSH0 = 0x00 # An empty array of bytes is pushed onto the stack.\n PUSHF = PUSH0\n PUSHBYTES1 = 0x01 # 0x01-0x4B The next opcode bytes is data to be pushed onto the stack\n PUSHBYTES75 = 0x4B\n PUSHDATA1 = 0x4C # The next byte contains the number of bytes to be pushed onto the stack.\n PUSHDATA2 = 0x4D # The next two bytes contain the number of bytes to be pushed onto the stack.\n PUSHDATA4 = 0x4E # The next four bytes contain the number of bytes to be pushed onto the stack.\n PUSHM1 = 0x4F # The number -1 is pushed onto the stack.\n PUSH1 = 0x51 # The number 1 is pushed onto the stack.\n PUSHT = PUSH1\n PUSH2 = 0x52 # The number 2 is pushed onto the stack.\n PUSH3 = 0x53 # The number 3 is pushed onto the stack.\n PUSH4 = 0x54 # The number 4 is pushed onto the stack.\n PUSH5 = 0x55 # The number 5 is pushed onto the stack.\n PUSH6 = 0x56 # The number 6 is pushed onto the stack.\n PUSH7 = 0x57 # The number 7 is pushed onto the stack.\n PUSH8 = 0x58 # The number 8 is pushed onto the stack.\n PUSH9 = 0x59 # The number 9 is pushed onto the stack.\n PUSH10 = 0x5A # The number 10 is pushed onto the stack.\n PUSH11 = 0x5B # The number 11 is pushed onto the stack.\n PUSH12 = 0x5C # The number 12 is pushed onto the stack.\n PUSH13 = 0x5D # The number 13 is pushed onto the stack.\n PUSH14 = 0x5E # The number 14 is pushed onto the stack.\n PUSH15 = 0x5F # The number 15 is pushed onto the stack.\n PUSH16 = 0x60 # The number 16 is pushed onto the stack.\n\n # Flow control\n NOP = 0x61 # Does nothing.\n JMP = 0x62\n JMPIF = 0x63\n JMPIFNOT = 0x64\n CALL = 0x65\n RET = 0x66\n APPCALL = 0x67\n SYSCALL = 0x68\n TAILCALL = 0x69\n\n # Stack\n DUPFROMALTSTACK = 0x6A\n TOALTSTACK = 0x6B # Puts the input onto the top of the alt stack. Removes it from the main stack.\n FROMALTSTACK = 0x6C # Puts the input onto the top of the main stack. Removes it from the alt stack.\n XDROP = 0x6D\n XSWAP = 0x72\n XTUCK = 0x73\n DEPTH = 0x74 # Puts the number of stack items onto the stack.\n DROP = 0x75 # Removes the top stack item.\n DUP = 0x76 # Duplicates the top stack item.\n NIP = 0x77 # Removes the second-to-top stack item.\n OVER = 0x78 # Copies the second-to-top stack item to the top.\n PICK = 0x79 # The item n back in the stack is copied to the top.\n ROLL = 0x7A # The item n back in the stack is moved to the top.\n ROT = 0x7B # The top three items on the stack are rotated to the left.\n SWAP = 0x7C # The top two items on the stack are swapped.\n TUCK = 0x7D # The item at the top of the stack is copied and inserted before the second-to-top item.\n\n # Splice\n CAT = 0x7E # Concatenates two strings.\n SUBSTR = 0x7F # Returns a section of a string.\n LEFT = 0x80 # Keeps only characters left of the specified point in a string.\n RIGHT = 0x81 # Keeps only characters right of the specified point in a string.\n SIZE = 0x82 # Returns the length of the input string.\n\n # Bitwise logic\n INVERT = 0x83 # Flips all of the bits in the input.\n AND = 0x84 # Boolean and between each bit in the inputs.\n OR = 0x85 # Boolean or between each bit in the inputs.\n XOR = 0x86 # Boolean exclusive or between each bit in the inputs.\n EQUAL = 0x87 # Returns 1 if the inputs are exactly equal 0 otherwise.\n # OP_EQUALVERIFY = 0x88 # Same as OP_EQUAL but runs OP_VERIFY afterward.\n # OP_RESERVED1 = 0x89 # Transaction is invalid unless occuring in an unexecuted OP_IF branch\n # OP_RESERVED2 = 0x8A # Transaction is invalid unless occuring in an unexecuted OP_IF branch\n\n # Arithmetic\n # Note: Arithmetic inputs are limited to signed 32-bit integers but may overflow their output.\n INC = 0x8B # 1 is added to the input.\n DEC = 0x8C # 1 is subtracted from the input.\n SIGN = 0x8D\n NEGATE = 0x8F # The sign of the input is flipped.\n ABS = 0x90 # The input is made positive.\n NOT = 0x91 # If the input is 0 or 1 it is flipped. Otherwise the output will be 0.\n NZ = 0x92 # Returns 0 if the input is 0. 1 otherwise.\n ADD = 0x93 # a is added to b.\n SUB = 0x94 # b is subtracted from a.\n MUL = 0x95 # a is multiplied by b.\n DIV = 0x96 # a is divided by b.\n MOD = 0x97 # Returns the remainder after dividing a by b.\n SHL = 0x98 # Shifts a left b bits preserving sign.\n SHR = 0x99 # Shifts a right b bits preserving sign.\n BOOLAND = 0x9A # If both a and b are not 0 the output is 1. Otherwise 0.\n BOOLOR = 0x9B # If a or b is not 0 the output is 1. Otherwise 0.\n NUMEQUAL = 0x9C # Returns 1 if the numbers are equal 0 otherwise.\n NUMNOTEQUAL = 0x9E # Returns 1 if the numbers are not equal 0 otherwise.\n LT = 0x9F # Returns 1 if a is less than b 0 otherwise.\n GT = 0xA0 # Returns 1 if a is greater than b 0 otherwise.\n LTE = 0xA1 # Returns 1 if a is less than or equal to b 0 otherwise.\n GTE = 0xA2 # Returns 1 if a is greater than or equal to b 0 otherwise.\n MIN = 0xA3 # Returns the smaller of a and b.\n MAX = 0xA4 # Returns the larger of a and b.\n WITHIN = 0xA5 # Returns 1 if x is within the specified range (left-inclusive) 0 otherwise.\n\n # Crypto\n # RIPEMD160 = 0xA6 # The input is hashed using RIPEMD-160.\n SHA1 = 0xA7 # The input is hashed using SHA-1.\n SHA256 = 0xA8 # The input is hashed using SHA-256.\n HASH160 = 0xA9\n HASH256 = 0xAA\n CHECKSIG = 0xAC\n CHECKMULTISIG = 0xAE\n\n # Array\n ARRAYSIZE = 0xC0\n PACK = 0xC1\n UNPACK = 0xC2\n PICKITEM = 0xC3\n SETITEM = 0xC4\n NEWARRAY = 0xC5 # 用作引用類型\n NEWSTRUCT = 0xC6 # 用作值類型" } ]
17
SimplyEpic5/Simply-Epic-Blender-Scripts
https://github.com/SimplyEpic5/Simply-Epic-Blender-Scripts
442a735cb64eb7ec6b92c302c1820eebfa750caa
b0c1ab14601e12af28f7c4b9b97760706ee5784a
80f7602650f9eb0f57bacbac00fe5266ad5ca8a5
refs/heads/main
2023-08-23T01:42:30.042671
2021-09-26T10:14:37
2021-09-26T10:14:37
410,513,374
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8101266026496887, "alphanum_fraction": 0.8101266026496887, "avg_line_length": 52, "blob_id": "5260c4b1864d29ac050fd5ca15173a18f946bc36", "content_id": "bd2188ebf97e419712023c0553709752640e5238", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 158, "license_type": "no_license", "max_line_length": 116, "num_lines": 3, "path": "/README.md", "repo_name": "SimplyEpic5/Simply-Epic-Blender-Scripts", "src_encoding": "UTF-8", "text": "# Simply Epic Blender Scripts\n## Contents\n- AutoDynamics.py - Automatically switch rigid body objects from animated to dynamic based on proximity to an object" }, { "alpha_fraction": 0.6287362575531006, "alphanum_fraction": 0.6339800953865051, "avg_line_length": 41.400001525878906, "blob_id": "d766fdbe03440e78964be0c8dad7759c58a96dcc", "content_id": "4234e6475d82769c9e9d435366e8f85368b4c50c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1907, "license_type": "no_license", "max_line_length": 141, "num_lines": 45, "path": "/scripts/AutoDynamics.py", "repo_name": "SimplyEpic5/Simply-Epic-Blender-Scripts", "src_encoding": "UTF-8", "text": "# AutoDynamics.py - A script that automatically switches rigid body objects from animated \n# to dynamic based on proximity to an object\n\nimport bpy\n\n# Modify these variables to configure the script:\ndynamicsCollectionName = \"AutoDynamics\" # Name of the collection containing the objects you want dynamics auto set for\ntriggerObjName = \"Sphere\" # Name of the object you want to use to trigger dynamics by distance\nresetFrame = 1 # Frame dynamics should be reset before (set to a frame before any objects become dynamic)\ntriggerDistance = 2.8 # Set to the minimum disatnce from the trigger object an object should be before dynamics are set\n\n# ===== Script Begins =====\n\ncollection = bpy.data.collections[dynamicsCollectionName]\ntriggerObj = bpy.data.objects[triggerObjName]\n\nfor obj in collection.all_objects:\n obj[\"isDynamic\"] = 0\n obj.rigid_body.enabled = False\n obj.rigid_body.kinematic = True\n\ndef autoDynamics(scene):\n frame_num = bpy.context.scene.frame_current\n \n if frame_num <= resetFrame:\n for obj in collection.all_objects:\n obj[\"isDynamic\"] = 0\n obj.rigid_body.enabled = False\n obj.rigid_body.kinematic = True\n else:\n for obj in collection.all_objects:\n if not obj[\"isDynamic\"]:\n # If the object is not dynamic, check if it should be set\n loc0 = triggerObj.location\n loc1 = obj.location\n dist = (loc0 - loc1).length\n \n if (dist < triggerDistance):\n # Object is close enough, trigger dynamics\n obj[\"isDynamic\"] = 1\n obj.rigid_body.enabled = True\n obj.rigid_body.kinematic = False\n\nbpy.app.handlers.frame_change_post.clear()\nbpy.app.handlers.frame_change_post.append(autoDynamics)" } ]
2
mirucaaura/SIP
https://github.com/mirucaaura/SIP
b038649003face388755031c696e50117116785a
a154966f4c5563651e7d91e885924e6331c3ed9b
df545c37e6af3db362c2befe2c6d1104d4ad76fb
refs/heads/main
2023-08-11T20:53:48.269920
2021-09-13T05:09:05
2021-09-13T05:09:05
405,790,702
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47707900404930115, "alphanum_fraction": 0.5213084816932678, "avg_line_length": 22.988950729370117, "blob_id": "650a320d3f5a8b3984135fdad6d8b13447ea5c88", "content_id": "4f06d45fae09979ba72820b7f1ac90101df7aa08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4341, "license_type": "no_license", "max_line_length": 104, "num_lines": 181, "path": "/alg2.py", "repo_name": "mirucaaura/SIP", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom scipy import optimize\n\ndef f(x):\n \"\"\"\n x: 3-dim numpy array\n \"\"\"\n return x[2]\n\ndef z(x, t):\n \"\"\"\n x: 3-dim numpy array\n t: scalar\n z: R^3 \\to R^2\n \"\"\"\n ret = np.zeros(2)\n ret[0] = x[0] + x[2] * np.cos(t)\n ret[1] = x[1] + x[2] * np.sin(t)\n return ret\n\ndef c1(z):\n \"\"\"\n z: 2-dim numpy array\n \"\"\"\n return z[0] ** 2 - z[1]\n\ndef c2(z):\n \"\"\"\n z: 2-dim numpy array\n \"\"\"\n# return z[0] ** 2 + 0.5 * z[1] - 1\n return z[0] ** 2 + z[1] - np.sqrt(2)\n\ndef g1(x, t):\n \"\"\"\n x: 3-dim numpy array\n t: scalar\n return: scalar\n \"\"\"\n ret = pow(x[0] + x[2] * np.cos(t), 2) - (x[1] + x[2] * np.sin(t))\n return ret\n\ndef g2(x, t):\n \"\"\"\n x: 3-dim numpy array\n t: scalar\n return: scalar\n \"\"\"\n# ret = pow(x[0] + x[2] * np.cos(t), 2) + 0.5 * (x[1] + x[2] * np.sin(t)) - 1\n ret = pow(x[0] + x[2] * np.cos(t), 2) + (x[1] + x[2] * np.sin(t)) - np.sqrt(2)\n return ret\n\ndef f_eps(x, eps):\n \"\"\"\n x: 3-dim numpy array\n eps: scalar\n \"\"\"\n ret = -f(x) + 0.5 * eps * cp.norm(x) ** 2\n return ret\n\ndef gr1(t, y, gamma):\n \"\"\"\n y: 3-dim numpy array\n t: scalar\n gamma: scalar\n return: scalar\n \"\"\"\n return -(g1(y, t) + gamma)\n\ndef gr2(t, y, gamma):\n \"\"\"\n y: 3-dim numpy array\n t: scalar\n gamma: scalar\n return: scalar\n \"\"\"\n return -(g2(y, t) + gamma)\n\ndef solve_sub(obj, constraints, gamma, eps, delta):\n \"\"\"\n solve RCSIP(T, gamma_k, eps_k)\n \"\"\"\n # set sub-problem\n obj = f_eps(y, eps) # objective function\n constraints = [] # constraints list\n for t in T1:\n constraints += [g1(y, t) <= -gamma]\n for t in T2:\n constraints += [g2(y, t) <= -gamma]\n #--- Step1-1: solve sub-problem\n prob = cp.Problem(cp.Minimize(obj), constraints)\n prob.solve()\n yr = y.value\n return yr\n\ndef find_t(yr, gr, gamma, delta):\n \"\"\"\n find t\n s.t. gr(yr, t) + gamma_k > delta_k\n \"\"\"\n div = 50\n t = np.linspace(0, 2*np.pi, div)\n y = gr(t, yr, gamma)\n x0 = (2 * np.pi / div) * (np.argmin(y) + 1)\n bounds = ((0, 2*np.pi),)\n res = optimize.minimize(gr, x0=x0, bounds=bounds, args=(yr, gamma,), method=\"Nelder-Mead\", tol=1e-6)\n res_fun = -res.fun # caution\n res_t = res.x\n return (res_fun, res_t)\n\n# set problem\ny = cp.Variable((3,), pos=True)\n# initial index set\nT1 = [0, np.pi, 2 * np.pi] # initial index set\nT2 = [0, np.pi, 2 * np.pi] # initial index set\n\n# parameter\nsigma = 1e-2\neps = 1\n \nitemax = 100\nite_inner_max = 10\n\n# main loop\nfor k in range(1, itemax + 1):\n # parameters\n eps *= 3 / 4\n gamma = 1 / (k + 5)\n delta = 101 / (100 * pow(k, 3))\n #--- inner loop\n for r in range(ite_inner_max):\n # set sub-problem\n obj = f_eps(y, eps) # objective function\n constraints = [] # constraints list\n for t in T1:\n constraints += [g1(y, t) <= -gamma]\n for t in T2:\n constraints += [g2(y, t) <= -gamma]\n #--- Step1-1: solve sub-problem\n yr = solve_sub(obj, constraints, gamma, eps, delta)\n #--- Step1-2: search tr \\in T\n res1_fun, res1_t = find_t(yr, gr1, gamma, delta)\n res2_fun, res2_t = find_t(yr, gr2, gamma, delta)\n # criteria\n if res1_fun <= delta and res2_fun <= delta:\n inner = r\n break\n # add index of T\n elif res1_fun > delta:\n T1.append(res1_t)\n elif res2_fun > delta:\n T2.append(res2_t)\n if k<=10: print(k, yr, len(T1), len(T2), inner, gamma >= delta)\n #--- step2\n if max(gamma, delta, eps) < sigma:\n print(\"terminate\", k, \"times\")\n break\nprint(\"the optimal value is\", yr)\n\n# plot\nz1 = np.linspace(-1/np.sqrt(np.sqrt(2)), 1/np.sqrt(np.sqrt(2)), 100)\nf1 = pow(z1, 2)\nf2 = -pow(z1, 2) + np.sqrt(2)\nfig = plt.figure(figsize=(7, 7))\nax = plt.axes()\nplt.xlim([-1, 1])\nplt.ylim([-0.2, 1.8])\nplt.grid(True)\nplt.plot(z1, f1, color=\"k\")\nplt.plot(z1, f2, color=\"k\")\nplt.fill_between(z1, f1, f2, facecolor=\"r\",alpha=0.5)\n# x = np.array([0., 0.70709686, 0.66874631])\nx = yr\nc = patches.Circle(xy=(x[0], x[1]), radius=x[2], color=\"b\", alpha=0.6, fill=True)\nax.add_patch(c)\nax.set_axisbelow(True)\n# plt.savefig(\"ok.jpg\")\nplt.show()" } ]
1
shuto-facengineer/AtCoder
https://github.com/shuto-facengineer/AtCoder
ad4ccc590b2565c8e99c9c58be9f654e5e3a16d8
24e4e2bfd62c937bcd53de2ffb5ff307b825c1e8
4887b92e9654ed7eff9d8f61b02be087bada9e52
refs/heads/master
2022-02-23T11:26:40.412852
2019-10-03T04:40:42
2019-10-03T04:40:42
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5972222089767456, "alphanum_fraction": 0.625, "avg_line_length": 23.33333396911621, "blob_id": "662a8c9bb12f80afd57902a0744129b8a60f5032", "content_id": "2d0a5aec2e174a1aa1d3ec905446397a6b4d9fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 35, "num_lines": 3, "path": "/BS/ABC081A.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_str = input() # 文字列取得\n_count = _str.count(\"1\") # 1の数をカウント\nprint(_count)" }, { "alpha_fraction": 0.5135135054588318, "alphanum_fraction": 0.5315315127372742, "avg_line_length": 21.399999618530273, "blob_id": "c154bc84da98bbb27b21b9b04434cb3b0759a4b9", "content_id": "9b325ca55df1a6276f506fb63dcfd2de89bbc778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "no_license", "max_line_length": 48, "num_lines": 5, "path": "/BS/ABC086A.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_a, _b = map(int, input().split(\" \")) # 二つの整数を取得\nif _a*_b%2 == 0: # 積の偶奇判定\n print(\"Even\")\nelse:\n print(\"Odd\")" }, { "alpha_fraction": 0.4878048896789551, "alphanum_fraction": 0.5226480960845947, "avg_line_length": 26.33333396911621, "blob_id": "c6494967b4b38a9b6829d350e5075ca8b92453d2", "content_id": "2990613df84df8fb965d96a65b46b56fae5df24f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "no_license", "max_line_length": 97, "num_lines": 21, "path": "/BS/ABC049C.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_s = input() # 文字列を取得\n_len = len(_s) # 文字列長\n\n_answer = \"YES\" # 仮にYESとする\n\nwhile(_len != 0):\n # 先頭から見ていき一致していれば削除する\n if _len >= 7 and _s[0:7] == \"dreamer\" and _s[5:10] != \"erase\": # dreamereraseの場合だけ,dreamerを優先する\n _s = _s.replace(\"dreamer\", \"\", 1)\n elif _len >= 6 and _s[0:6] == \"eraser\":\n _s = _s.replace(\"eraser\", \"\", 1)\n elif _len >= 5 and _s[0:5] == \"dream\":\n _s = _s.replace(\"dream\", \"\", 1)\n elif _len >= 5 and _s[0:5] == \"erase\":\n _s = _s.replace(\"erase\", \"\", 1)\n # 何も当てはまらないなら答えはNO\n else:\n _answer = \"NO\"\n break\n _len = len(_s)\nprint(_answer)\n" }, { "alpha_fraction": 0.34663864970207214, "alphanum_fraction": 0.5399159789085388, "avg_line_length": 27.058822631835938, "blob_id": "313611618baa518d5599a6bbd68f09ab1bfff56b", "content_id": "46ffba6d014f61a81e4aa708c0f4434ac42f9566", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 598, "license_type": "no_license", "max_line_length": 61, "num_lines": 17, "path": "/BS/ABC085C.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "from sys import exit\n_n, _sum = map(int, input().split(\" \")) # _n: お札の数, _sum: 合計額\n \nif _sum > 10000*_n:\n # そもそも最大効率でもあり得ない場合\n print(\"-1 -1 -1\")\n exit()\n \nfor _10000 in range(_n + 1):\n for _5000 in range(_n - _10000 + 1):\n # _10000 + _5000 + _1000 = _nの原則で二重ループ\n _1000 = _n - _10000 - _5000\n if _10000*10000 + _5000*5000 + _1000*1000 == _sum:\n # 条件を満たす組み合わせを一つでも見つけたら,出力して終了\n print(\"{} {} {}\".format(_10000, _5000, _1000))\n exit()\nprint(\"-1 -1 -1\")" }, { "alpha_fraction": 0.6056337952613831, "alphanum_fraction": 0.6150234937667847, "avg_line_length": 20.350000381469727, "blob_id": "02306d08c169d767d8112e4cac1cfea827fbeab6", "content_id": "443f82e4d8336164bf65b71e13104d075912ada8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 51, "num_lines": 20, "path": "/BS/ABC085B.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_n = int(input()) # 餅の数\n_rice_cakes = [] # 餅のリスト\nwhile True:\n try:\n _rice_cakes.append(int(input())) # 入力が終わるまで受け取る\n except:\n break\n \n_rice_cakes.sort(reverse = True) # 降順にソート\n \n_min = _rice_cakes[0] # 仮の最小値を先頭から受け取る\n_count = 1 # リスト先頭の一つが既に積んであるため,最初から1\n \nfor _i in range(_n):\n # 今先頭にあるものより小さければ積める\n if _rice_cakes[_i] < _min:\n _min = _rice_cakes[_i] # 仮の最小値を更新\n _count = _count + 1 # 段数を更新\n \nprint(_count)" }, { "alpha_fraction": 0.6984924674034119, "alphanum_fraction": 0.7688442468643188, "avg_line_length": 48.75, "blob_id": "c385a51e2eea6e81a072de239b5d46b07f90da69", "content_id": "78182f6cef028bf916c4abcbe02ea2cb20f92e01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 217, "license_type": "no_license", "max_line_length": 77, "num_lines": 4, "path": "/BS/README.md", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "# AtCoder Begginers Selection\n[ABS](https://atcoder.jp/contests/abs)\n[問題文集](https://atcoder.jp/contests/abs/tasks_print)\n[ブログ記事](https://takuya-shuto-engineer.hatenablog.com/entry/2019/10/01/151501)\n" }, { "alpha_fraction": 0.6310096383094788, "alphanum_fraction": 0.6478365659713745, "avg_line_length": 36.818180084228516, "blob_id": "ae3fa09a49421bf65c264684b0ff60ad0fc7a660", "content_id": "6efd38766c99ea135af218ea6c2c1a6ff1d8da93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1128, "license_type": "no_license", "max_line_length": 80, "num_lines": 22, "path": "/BS/ABC086C.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_n = int(input()) # 計画リスト長\n_coordinates = [[0, 0, 0]] # [時刻t, x座標, y座標]\nwhile True:\n try:\n _coordinates.append(list(map(int, input().split()))) # 標準入力から旅行計画を取得\n except:\n break\n_isPossible = 'Yes' # 出力形式に合わせてBooleanではなくstring\nfor _i in range(_n):\n _action_times = _coordinates[_i + 1][0] - _coordinates[_i][0] # 次の計画までの時刻,行動回数\n _diff_x = abs(_coordinates[_i + 1][1] - _coordinates[_i][1]) # 次の目的地までのx座標の差分\n _diff_y = abs(_coordinates[_i + 1][2] - _coordinates[_i][2]) # 次の目的地までのy座標の差分\n _minimum_action_times = _diff_x + _diff_y # 最低限必要な行動回数\n if _minimum_action_times > _action_times: \n _isPossible = 'No' # 最低限必要な行動回数を確保できていない場合不可能\n break\n elif abs(_action_times - _minimum_action_times) % 2 != 0:\n _isPossible = 'No' # 余った行動回数が奇数なら不可能\n break\n else:\n continue\nprint(_isPossible) # 無事全計画リストの要素間を精査できたら可能\n" }, { "alpha_fraction": 0.4117647111415863, "alphanum_fraction": 0.4117647111415863, "avg_line_length": 22.799999237060547, "blob_id": "d774b8dc96970285b964162b440748067c842669", "content_id": "2dd7bcfc14b3170cb51ee9577e006d74853fda98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 41, "num_lines": 5, "path": "/BS/PracticeA.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_a = int(input()) # A\n_b, _c = map(int, input().split()) # B, C\n_s = input() # S\n \nprint(str(_a + _b + _c) + \" \" + _s)\n" }, { "alpha_fraction": 0.6016483306884766, "alphanum_fraction": 0.6126373410224915, "avg_line_length": 23.266666412353516, "blob_id": "ad17d95f8a5df4e935799cc33f93365c1ea12261", "content_id": "f4357f699154e6bce2952bca9e8753903f8a922e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "no_license", "max_line_length": 62, "num_lines": 15, "path": "/BS/ABC088B.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_n = int(input()) # カードの枚数\n_cards = list(map(int, input().split(\" \"))) # カードリスト\n \n_alice = 0 # アリスの得点\n_bob = 0 # ボブの得点\n_cards.sort(reverse = True) # 最高効率でカードを引くため,カードを降順にソートして先頭から取得\n \nfor _i, _card in enumerate(_cards):\n # アリスとボブが交互にカードを引く\n if _i % 2 == 0:\n _alice = _alice + _card\n else:\n _bob = _bob + _card\n \nprint(_alice - _bob) # アリスがどれくらいボブに差をつけたのか\n" }, { "alpha_fraction": 0.513437032699585, "alphanum_fraction": 0.5275813341140747, "avg_line_length": 23.413793563842773, "blob_id": "3a3259e0113aeb9e54e494b7d5161a730c99f8c6", "content_id": "33fe712473cae431a957139ccb96aa1786f5cc3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "no_license", "max_line_length": 65, "num_lines": 29, "path": "/ABC142/div.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_a, _b = map(int, input().split())\n_common_divisors = []\n_min = min([_a, _b])\n\ndef euclid(a, b):\n _mod = a % b\n if _mod == 0:\n return b\n else:\n return euclid(b, _mod)\n\nfor _i in range(_min):\n _num = _i + 1\n if _a % _num == 0 and _b % _num == 0:\n _common_divisors.append(_num)\n \nprint(\" \".join(map(str, _common_divisors)))\n\"\"\"\n_count = 0\nfor _i in range(len(_common_divisors) - 1):\n for _j in range(len(_common_divisors) - (_i + 1) ):\n _k = _j + 1\n _max = max([_common_divisors[_i], _common_divisors[_i + _k]])\n _min = min([_common_divisors[_i], _common_divisors[_i + _k]])\n _max_divisor = euclid(_max, _min)\n if _max_divisor == 1:\n _count = _count + 1\nprint(_count)\n\"\"\"" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.5092592835426331, "avg_line_length": 20.66666603088379, "blob_id": "f63d346875b622f009075284654a4b1406d3f415", "content_id": "6b6f9352efee0a8240473f1cec4d82ec21fe19a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 39, "num_lines": 15, "path": "/BS/ABC087B.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_a = int(input()) # 500円玉の数\n_b = int(input()) # 100円玉の数\n_c = int(input()) # 50円玉の数\n \n_x = int(input()) # 目標金額\n_count = 0 # 目標金額を満たすパターンのカウント\n \nfor _i in range(_a + 1):\n for _j in range(_b + 1):\n for _k in range(_c + 1):\n # 全パターンを検証\n if _i*500 + _j*100 + _k*50 == _x:\n _count = _count + 1\n \nprint(_count)" }, { "alpha_fraction": 0.5968169569969177, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 21.176469802856445, "blob_id": "886943d9257df244212be6ae52c13f8a84be955d", "content_id": "cec911ff2ceb4a552fd516753958d28048a768de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 50, "num_lines": 17, "path": "/BS/ABC081B.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_n = int(input()) # 系列長\n_list = list(map(int, input().split())) # 数字のリスト\n_count = 0 # 行動回数\n \ndef div(num): # mapに渡すための割り算\n return num / 2\n \ndef mod(num): # mapに渡すための余り計算\n return num % 2\n \nwhile True:\n _mod_list = list(map(mod, _list)) # 2で割った余りを計算する\n if 1 in _mod_list: # 奇数があったら終了\n break\n _list = list(map(div, _list)) # 全て偶数なら2で割る\n _count = _count + 1\nprint(_count)\n" }, { "alpha_fraction": 0.5224719047546387, "alphanum_fraction": 0.5393258333206177, "avg_line_length": 26.461538314819336, "blob_id": "d5a7f9158b7949d0f351c26f0de63f38963409c7", "content_id": "6d272e0828b8861a3f5e6b69dd08c14216e47ad5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 78, "num_lines": 13, "path": "/BS/ABC083B.py", "repo_name": "shuto-facengineer/AtCoder", "src_encoding": "UTF-8", "text": "_n, _a, _b = map(int, input().split(\" \")) # _n: 1以上N以下のN, _a: A以上のA, _b: B以下のB\n \n_total = 0 # 10進法での各桁の和がA以上B以下であるものの総和\nfor _i in range(_n):\n _num = str(_i + 1) # 各桁を参照するためにstrに変換\n _len = len(_num) # 長さを受け取る\n _sum = 0 # 各桁の総和\n for _j in range(_len):\n _sum = _sum + int(_num[_j])\n if _a <= _sum <= _b:\n _total = _total + int(_num)\n \nprint(_total)" } ]
13
PserverHacks/ddos
https://github.com/PserverHacks/ddos
5130e5a975f0af29328b8bad1777ce058fef3192
73750f4854f5bc96b2ee998bdc9666eb6306aa09
6bc231769c2d3510ff321f48190225a05fb51930
refs/heads/main
2023-03-24T22:34:14.563361
2021-03-18T03:32:11
2021-03-18T03:32:11
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 6.5, "blob_id": "7579ccc395287c3d770590707715a9a2065bc7cd", "content_id": "26122a6b723d06d19210eca88592097dca2ea9ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15, "license_type": "no_license", "max_line_length": 7, "num_lines": 2, "path": "/README.md", "repo_name": "PserverHacks/ddos", "src_encoding": "UTF-8", "text": "# ddos\nmy ddos\n" }, { "alpha_fraction": 0.6314972639083862, "alphanum_fraction": 0.6532195210456848, "avg_line_length": 22.01785659790039, "blob_id": "6bdb135dd8da62221a1b4fa08c8f10de5e2bb925", "content_id": "849f2bfec713c9d3f83756c55db810eded30518f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1289, "license_type": "no_license", "max_line_length": 78, "num_lines": 56, "path": "/ddos.py", "repo_name": "PserverHacks/ddos", "src_encoding": "UTF-8", "text": "import socket, time, random, sys, threading, optparse\nfrom colorama import Fore, Style\n\ndef usage():\n\tprint (''' \\033[92m\tmyDos: AL104\n\tWe Dont Have A Law. Feel Free Take Risk.. \\n\n\tusage : python3 ddos.py [-s] [-p] [-t]\n\t-h : help\n\t-t : target ip\n\t-p : port default 80\n\t-a : Ammo/bullet/power default 10 \\033[0m''')\n\tsys.exit()\n\nread = optparse.OptionParser(add_help_option=False,epilog=\"myDos\")\nread.add_option('-t', '--target',dest='target',help='Target IP')\nread.add_option('-a', '--ammo',dest='ammo',help='Enter amount of Ammo/bullet')\nread.add_option('-p', '--port', dest='port')\nread.add_option('-h','--help',dest='help',action='store_true',help='help you')\n(value, key) = read.parse_args()\nif value.help:\n\tusage()\nif value.target is not None:\n\ttarget = value.target\nelse:\n\tusage()\nif value.port is None:\n\tport = 80\nelse:\n\tport = value.port\nif value.ammo is None:\n\tammo = 10\nelse:\n\tammo = value.ammo\n\n\ndef dos():\n\ttry:\n\t\tbytes = random._urandom(1024)\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\tx = 0\n\n\t\twhile True:\n\t\t\tx += 1\n\t\t\ts.sendto(bytes, (target, port))\n\t\t\tprint(f'[{x}] ammo shooting to ==>> {target}')\n\n\texcept:\n\t\tprint('shot miss!!')\n\n\nprint('starting to shoot...')\n\nfor p in range(0, int(ammo)):\n\tthreading.Thread(target=dos).start()\n\nprint('execute done!')\n" } ]
2
acedwards/concussion-test-routine
https://github.com/acedwards/concussion-test-routine
ce5578c03c92383ce182db8cd9c837008af36dbf
197672f6e52b6357b9a7e55c5876a8760137e3a3
8cf8d025e322b5eab615f5e89fad6816a964b8ff
refs/heads/master
2022-10-23T16:47:49.360309
2020-06-15T18:14:49
2020-06-15T18:14:49
264,817,594
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8103896379470825, "alphanum_fraction": 0.8103896379470825, "avg_line_length": 190.5, "blob_id": "603531afcd951c6ed84d6c31eae0dd84ba97de8f", "content_id": "90ad990c1fb3436647594aa1e576e17ea886a4be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 387, "license_type": "no_license", "max_line_length": 355, "num_lines": 2, "path": "/README.md", "repo_name": "acedwards/concussion-test-routine", "src_encoding": "UTF-8", "text": "# concussion-test-routine\r\nThis code was created as part of a capstone engineering project. It is one component of a piece of software that guided users through an antisaccade test while tracking their eye movements and processing the results. The code in this repository is not meant to be run without the rest of the software, but I wanted to document my individual contributions.\r\n" }, { "alpha_fraction": 0.5914633870124817, "alphanum_fraction": 0.6006097793579102, "avg_line_length": 30.238094329833984, "blob_id": "2367b11f0c507eef88491ef892ae919c20e5a95f", "content_id": "276dc7ad9b696266c5f31c20d4835a3c27f02c40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 656, "license_type": "no_license", "max_line_length": 86, "num_lines": 21, "path": "/TestRoutineProcess.py", "repo_name": "acedwards/concussion-test-routine", "src_encoding": "UTF-8", "text": "from TestRoutine.test_routine import Menu, TestSession\nfrom BaseProcess import BaseProcess\n\n# class TestRoutine(BaseProcess):\nclass TestRoutine:\n def __init__(self, queues):\n self.id = 0\n self.name = 'Test Routine'\n self.queues = queues\n self.process_names = {\n 'Test Routine': 0,\n 'Concussion Model': 1,\n 'Pupil Tracking': 2,\n 'Saccade Detector': 3\n }\n\n def run(self):\n self.menu = Menu(self.queues, self.process_names)\n self.test_session = TestSession(self.queues, self.process_names, num_blocks=1)\n self.menu.run()\n self.test_session.run()\n" }, { "alpha_fraction": 0.6360856294631958, "alphanum_fraction": 0.6360856294631958, "avg_line_length": 24.842105865478516, "blob_id": "391d2659e1d241657373c2dc1c0074c80a9bf3f9", "content_id": "6021716741d17a4dc7e46ced2d68b13f90dceaea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 981, "license_type": "no_license", "max_line_length": 53, "num_lines": 38, "path": "/TestMessages.py", "repo_name": "acedwards/concussion-test-routine", "src_encoding": "UTF-8", "text": "from BaseMessage import BaseMessage\n\nclass PatientDataMessage(BaseMessage):\n def __init__(self, sex, age):\n self.sex = sex\n self.age = age\n\n BaseMessage.__init__(self, \"PatientData\")\n\nclass StimLogMessage(BaseMessage):\n def __init__(self, log):\n self.log = log\n\n BaseMessage.__init__(self, \"StimLog\")\n\nclass TestStartMessage(BaseMessage):\n def __init__(self, start_time):\n self.start_time = start_time\n\n BaseMessage.__init__(self, \"TestStart\")\n\nclass TestEndMessage(BaseMessage):\n def __init__(self, end_time):\n self.end_time = end_time\n\n BaseMessage.__init__(self, \"TestEnd\")\n\nclass TestCalibrationMessage(BaseMessage):\n def __init__(self, calibration_time):\n self.calibration_time = calibration_time\n\n BaseMessage.__init__(self, \"TestCalibration\")\n\nclass ShutdownMessage(BaseMessage):\n def __init__(self, time):\n self.time = time\n\n BaseMessage.__init__(self, \"Shutdown\")" }, { "alpha_fraction": 0.6606786251068115, "alphanum_fraction": 0.71257483959198, "avg_line_length": 31.29032325744629, "blob_id": "1fa97593082d7136dafb64cbb6b125ad694686af", "content_id": "fef2add5a4218fdf5f99e8adda0f84361bc829e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 104, "num_lines": 31, "path": "/test_config.py", "repo_name": "acedwards/concussion-test-routine", "src_encoding": "UTF-8", "text": "import sys, math\nfrom PyQt5.QtWidgets import QApplication\nimport pygame\nfrom pygame.locals import *\n\napp = QApplication(sys.argv)\nscreen = app.screens()[0]\nDPI = screen.physicalDotsPerInch()\napp.quit()\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255,0,0)\nDIS_FROM_SCREEN = 55 #cm\nDEG_STIM_OFFSET = 9 #degrees\nDEG_STIM_SIZE = 0.5 #degrees\nSACCADE_REPS = 40\nSACCADE_BLOCKS = 2\nMESSAGE_DELAY = 5000 # how long a message stays up\nSTIM_DELAY = 1000 # how long stim stays up\n\nscreen = pygame.display.set_mode((0,0), FULLSCREEN)\nwidth, height = screen.get_width(), screen.get_height() #in px\ncentre_x, centre_y = width//2, height//2\n\n# stim location setup\nstim_offset = int(DIS_FROM_SCREEN*math.tan(math.radians(DEG_STIM_OFFSET))*DPI/2.54) # 2.54 cm in an inch\nleft_stim_coords = [centre_x - stim_offset, centre_y]\nright_stim_coords = [centre_x + stim_offset, centre_y]\nstim_size = int(DIS_FROM_SCREEN*math.tan(math.radians(DEG_STIM_SIZE))*DPI/2.54) # 2.54 cm in an inch\nstim_radius = int(stim_size/2) " }, { "alpha_fraction": 0.5602794885635376, "alphanum_fraction": 0.5692112445831299, "avg_line_length": 48.201171875, "blob_id": "b5a5e2c26a3870f20a10fa4491a62a68e5e33745", "content_id": "901f315e908da0a4c54f4352a02e6445002d556f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25191, "license_type": "no_license", "max_line_length": 232, "num_lines": 512, "path": "/test_routine.py", "repo_name": "acedwards/concussion-test-routine", "src_encoding": "UTF-8", "text": "from enum import Enum\nimport time\nfrom random import triangular, randint\nimport pygame\nimport cv2\nimport numpy\nfrom pygame.locals import *\nimport pygame_gui\nfrom queue import Empty as QueueEmpty\n\nfrom multiprocessing import Queue\nfrom BaseProcess import BaseProcess\n\nimport TestRoutine.test_config as test_config\nfrom TestRoutine.TestMessages import PatientDataMessage, TestStartMessage, TestEndMessage, TestCalibrationMessage, StimLogMessage, ShutdownMessage\n\nclass BlockType(Enum):\n PRO = 0\n ANTI = 1\n\nclass Location(Enum):\n LEFT = 0\n RIGHT = 1\n CENTRE = 2\n\nclass StimLog:\n def __init__(self, id):\n self.id = id\n self.location = None\n self.start_time = None # time stim appears\n self.end_time = None # time stim disappears\n\nclass SaccadeBlock:\n def __init__(self, total_reps=test_config.SACCADE_REPS, starting_type=BlockType.PRO, num=1):\n self.total_reps = total_reps\n self.reps_complete = 0\n self.block_complete = False\n self.areas_to_update = []\n self.type = starting_type\n self.target_drawn = False\n self.set_in_prog = False\n self.set_start_time = None\n self.current_stim_rect = None\n self.current_stim_log = None\n self.current_delay = None\n self.num = num\n \n def reset_for_next_block(self):\n self.reps_complete = 0\n self.block_complete = False\n self.target_drawn = False\n self.areas_to_update = []\n self.num += 1\n\n def update_reps(self):\n if not self.block_complete:\n self.reps_complete += 1\n if self.reps_complete == self.total_reps:\n self.block_complete = True\n\n def start_set(self):\n # a set being centre target being displayed for random amount of time, followed by stim being displayed for STIM_DELAY\n # reset for new set\n self.current_stim_log = StimLog(self.reps_complete)\n self.current_stim_rect = None\n self.current_delay = self.get_target_delay()\n self.set_start_time = None\n\n if not self.target_drawn:\n self.draw_centre_target()\n else:\n # target is already drawn so time won't be updated when frame is drawn\n self.update_set_start_time()\n self.set_in_prog = True\n \n\n def draw_centre_target(self):\n self.areas_to_update.append(pygame.draw.circle(test_config.screen, test_config.BLACK, [test_config.centre_x, test_config.centre_y], test_config.stim_radius))\n self.target_drawn = True\n\n\n def draw_stimulus(self, stimulus_delay_event):\n if randint(0, 1) == 0:\n self.areas_to_update.append(pygame.draw.circle(test_config.screen, test_config.BLACK, test_config.left_stim_coords, test_config.stim_radius))\n self.current_stim_log.location = Location.LEFT\n else:\n self.areas_to_update.append(pygame.draw.circle(test_config.screen, test_config.BLACK, test_config.right_stim_coords, test_config.stim_radius))\n self.current_stim_log.location = Location.RIGHT\n self.current_stim_rect = self.areas_to_update[-1]\n pygame.time.set_timer(stimulus_delay_event, test_config.STIM_DELAY)\n\n\n def get_target_delay(self):\n # delay between centre target appearing and stimulus appearing should be between 1000 - 3500 ms\n # with an average of 1500 ms - I tried my best! :/\n # https://docs.python.org/2/library/random.html#random.triangular\n delay = int(triangular(1000, 3500, 1200))\n return delay\n \n def update_set_start_time(self):\n self.set_start_time = pygame.time.get_ticks()\n\nclass TestSession:\n test_intro = [\"In order to calibrate our device, please look at the centre target.\", \"When you are focussed on it, press the spacebar.\"]\n antisaccade_instructions = [\"Look at the centre target.\", \"As soon as a new dot appears look in the opposite direction as fast as you can.\", \"\", \"You will probably sometimes make some mistakes,\", \"and this is perfectly normal.\"]\n prosaccade_instructions = [\"Please focus on the centre target. When a dot appears to the left or right, look directly at it.\"]\n test_outro = [\"Thank you for completing the concussion indicator test.\", \"Your results will appear shortly.\"]\n\n instruction_display_time = 8000 # 8 sec\n\n message_delay_event = USEREVENT + 1\n stimulus_delay_event = USEREVENT + 2\n centre_target_delay_event = USEREVENT + 3\n\n message_params = [pygame.font.match_font('timesnewroman'), 22, test_config.BLACK]\n \n def __init__(self, queues, process_names, num_blocks=test_config.SACCADE_BLOCKS):\n self.test_started = False\n self.test_ended = False\n self.received_results = False\n self.block_started = False\n self.current_block = SaccadeBlock(starting_type=BlockType.ANTI)\n self.running = True\n self.waiting_for_delay = False\n self.waiting_for_input = True\n self.stim_log = []\n self.num_blocks = num_blocks\n # multiprocessing\n self.queues = queues\n self.process_names = process_names\n \n def start_test(self):\n if not self.test_started:\n self.display_message(*self.message_params, self.test_intro, 0)\n self.current_block.draw_centre_target()\n self.test_started = True\n self.waiting_for_input = True\n \n # send start time to pupil tracking and saccade detection\n msg = TestStartMessage(time.time())\n self.queues[self.process_names['Pupil Tracking']].put(msg)\n self.queues[self.process_names['Saccade Detector']].put(msg)\n else:\n print('Test already started!')\n \n def end_test(self):\n self.display_message(*self.message_params, self.test_outro, 0)\n self.test_ended = True\n # send end message to saccade detection and pupil tracking\n msg = TestEndMessage(time.time())\n self.queues[self.process_names['Pupil Tracking']].put(msg)\n self.queues[self.process_names['Saccade Detector']].put(msg)\n\n # send stim log to saccade detection\n print(\"[TestRoutine][DEBUG] Sending stim log\")\n msg = StimLogMessage(self.stim_log)\n self.queues[self.process_names['Saccade Detector']].put(msg)\n \n def start_block(self):\n if self.current_block.type == BlockType.ANTI:\n self.display_instructions(self.antisaccade_instructions)\n else:\n self.display_instructions(self.prosaccade_instructions)\n self.block_started = True\n \n def show_results(self, results):\n self.reset_screen()\n\n font_object = pygame.font.Font(pygame.font.match_font('timesnewroman'), 22)\n \n we_predict = font_object.render(\"We have predicted a concussion likelihood of\", True, (test_config.BLACK))\n we_predict_rect = we_predict.get_rect(center=(test_config.centre_x, test_config.centre_y - 125))\n test_config.screen.blit(we_predict, we_predict_rect)\n\n confirm = font_object.render(\"Please confirm this data with a medical professional.\", True, (test_config.BLACK))\n confirm_rect = confirm.get_rect(center=(test_config.centre_x, test_config.centre_y + 30))\n test_config.screen.blit(confirm, confirm_rect)\n\n font_object = pygame.font.Font(pygame.font.match_font('timesnewroman'), 50)\n results_text = font_object.render(str(results.probability)+\"%\", True, (test_config.BLACK))\n results_text_rect = results_text.get_rect(center=(test_config.centre_x, test_config.centre_y - 80))\n test_config.screen.blit(results_text, results_text_rect)\n\n font_object = pygame.font.Font(pygame.font.match_font('timesnewroman'), 14)\n exit_text = font_object.render(\"Press ESC at any time to exit the test\", True, (test_config.BLACK))\n exit_text_rect = exit_text.get_rect(center=(test_config.centre_x, test_config.centre_y + 200))\n test_config.screen.blit(exit_text, exit_text_rect)\n\n pygame.display.update()\n\n def display_instructions(self, instructions):\n self.display_message(*self.message_params, instructions, self.instruction_display_time)\n\n def display_message(self, font, size, colour, messages, display_time):\n self.reset_screen()\n font_object = pygame.font.Font(font, size)\n offset = 40\n for message in messages:\n if message:\n rendered_text = font_object.render(message, True, (colour))\n rendered_text_rect = rendered_text.get_rect(center=(test_config.centre_x, offset))\n test_config.screen.blit(rendered_text, rendered_text_rect)\n offset += 30\n pygame.display.update()\n if display_time != 0:\n pygame.time.set_timer(self.message_delay_event, display_time)\n self.waiting_for_delay = True\n \n def process_events(self):\n for event in pygame.event.get():\n if event.type == QUIT:\n self.running = False\n elif event.type == KEYDOWN:\n if event.key == K_SPACE:\n if self.test_started and self.waiting_for_input:\n #send calibration flag to saccade detector\n msg = TestCalibrationMessage(time.time())\n self.queues[self.process_names['Saccade Detector']].put(msg)\n self.reset_screen()\n self.waiting_for_input = False\n self.current_block.target_drawn = False\n if event.key == K_ESCAPE:\n self.running = False\n elif event.type == self.message_delay_event:\n self.reset_screen()\n pygame.time.set_timer(self.message_delay_event, 0)\n self.waiting_for_delay = False\n elif event.type == self.stimulus_delay_event:\n # stim has been displayed for STIM_DELAY time\n # time to get rid of it\n test_config.screen.blit(test_config.screen, self.current_block.current_stim_rect)\n self.current_block.areas_to_update.append(self.current_block.current_stim_rect)\n \n # reset stim timer, update rep and complete set\n pygame.time.set_timer(self.stimulus_delay_event, 0)\n self.current_block.update_reps()\n self.current_block.set_in_prog = False\n self.waiting_for_delay = False\n self.draw_frame()\n # menu_manager.process_events(event)\n \n def draw_frame(self):\n if (len(self.current_block.areas_to_update) > 0):\n if not self.waiting_for_input: # if not calibrating\n if self.current_block.set_in_prog:\n if not self.current_block.current_stim_rect: #drawing centre target\n self.current_block.update_set_start_time()\n\n elif not self.current_block.current_stim_log.start_time: #drawing stim\n # setting start time when stim is actually drawn for better accuracy\n self.current_block.current_stim_log.start_time = time.time()\n elif self.current_block.current_stim_log.start_time: #removing stim\n self.current_block.current_stim_log.end_time = time.time()\n self.stim_log.append(self.current_block.current_stim_log)\n pygame.display.update(self.current_block.areas_to_update) \n self.current_block.areas_to_update = []\n \n def run(self):\n test_config.screen.fill(test_config.WHITE)\n pygame.display.flip()\n while self.running:\n self.process_events()\n if not self.test_started:\n self.start_test()\n elif self.test_ended and not self.received_results:\n # results = 0\n try:\n results = self.queues[self.process_names['Test Routine']].get_nowait()\n\n if results.id == \"ConcussionProbability\":\n print(\"[TestRoutine][INFO] Received concussion probability\")\n self.received_results = True\n self.show_results(results)\n self.waiting_for_input = True\n except QueueEmpty:\n pass\n \n else:\n if self.waiting_for_input or self.waiting_for_delay:\n # do nothing\n continue\n if not self.block_started:\n # Block hasn't started, display instructions and buckle your seatbelts\n self.start_block()\n elif self.current_block.block_complete:\n # Block is complete.\n if self.current_block.num < self.num_blocks:\n # If there's still another block to go, switch type and start over\n self.current_block.reset_for_next_block()\n self.current_block.type = BlockType.ANTI if self.current_block.type == BlockType.PRO else BlockType.PRO\n self.block_started = False\n else:\n # All blocks are complete. Display test outro.\n self.end_test()\n else:\n # Block is in progress\n if not self.current_block.set_in_prog:\n self.current_block.start_set()\n elif (pygame.time.get_ticks() - self.current_block.set_start_time) >= self.current_block.current_delay:\n # target has been by itself long enough, draw stim\n self.waiting_for_delay = True\n self.current_block.draw_stimulus(self.stimulus_delay_event)\n\n self.draw_frame()\n print('quitting...')\n msg = ShutdownMessage(time.time())\n self.queues[self.process_names['Concussion Model']].put(msg)\n self.queues[self.process_names['Pupil Tracking']].put(msg)\n self.queues[self.process_names['Saccade Detector']].put(msg)\n print('[TestRoutine][INFO] exited at {}'.format(msg.time))\n pygame.display.quit()\n pygame.quit()\n \n def reset_screen(self):\n test_config.screen.fill(test_config.WHITE)\n pygame.display.flip()\n\nclass Menu:\n # gui setup\n pygame.init()\n\n menu_manager = pygame_gui.UIManager((test_config.width, test_config.height))\n BUTTON_WIDTH = 150\n BUTTON_HEIGHT = 50\n BUTTON_SIZE = (BUTTON_WIDTH, BUTTON_HEIGHT)\n loading_event = USEREVENT + 4\n\n def __init__(self, queues, process_names, video_device=0):\n self.queues = queues\n self.process_names = process_names\n self.sex_selection = None\n self.data_entry_elements = []\n self.clock = pygame.time.Clock()\n self.cam = cv2.VideoCapture(video_device) #640x480 by default\n self.cam.set(3,640)\n self.cam.set(4,480)\n self.show_cam = False\n self.cont_button_2 = None\n\n def create_data_entry_elements(self):\n self.sex_dropdown = pygame_gui.elements.UIDropDownMenu(['Male', 'Female'], \n starting_option='Unselected',\n manager=self.menu_manager,\n relative_rect=pygame.Rect((test_config.centre_x, test_config.centre_y - 3*self.BUTTON_HEIGHT+25), self.BUTTON_SIZE)) \n self.data_entry_elements.append(self.sex_dropdown)\n self.dropdown_label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect(test_config.centre_x - 3*self.BUTTON_WIDTH/2, test_config.centre_y - 3*self.BUTTON_HEIGHT+25, 200, 50),\n text='Patient Sex:',\n manager=self.menu_manager)\n self.data_entry_elements.append(self.dropdown_label)\n self.cont_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((test_config.centre_x - 3*self.BUTTON_WIDTH/2, test_config.centre_y + 200), self.BUTTON_SIZE),\n text='Continue',\n manager=self.menu_manager)\n self.data_entry_elements.append(self.cont_button)\n self.age_entry = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect((test_config.centre_x, test_config.centre_y - 15*self.BUTTON_HEIGHT/4), self.BUTTON_SIZE),\n manager=self.menu_manager)\n self.age_entry.set_allowed_characters('numbers')\n self.data_entry_elements.append(self.age_entry)\n self.age_entry_label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect(test_config.centre_x - 3*self.BUTTON_WIDTH/2, test_config.centre_y - 4*self.BUTTON_HEIGHT, 200, 50),\n text='Patient Age:',\n manager=self.menu_manager)\n self.data_entry_elements.append(self.age_entry_label)\n self.data_entry_instructions = pygame_gui.elements.UILabel(relative_rect=pygame.Rect(test_config.centre_x - 225, 100, 450, 50),\n text='Please enter the following information to continue',\n manager=self.menu_manager)\n self.data_entry_elements.append(self.data_entry_instructions)\n\n def data_is_valid(self):\n if not self.age_entry.get_text() or not self.sex_selection:\n # age hasn't been entered or sex not selected\n return False\n else:\n return True\n\n def reset_screen(self):\n test_config.screen.fill(test_config.WHITE)\n pygame.display.flip()\n\n def run(self):\n test_config.screen.fill(test_config.WHITE)\n # wait for pupil tracking to be ready\n loading_message_frames = [\".\", \"..\", \"...\"]\n loading = True\n i = 0\n message = \"Initializing Concussion Detector\"\n font_object = pygame.font.Font(pygame.font.match_font('timesnewroman'), 18)\n rendered_text = font_object.render(message, True, test_config.BLACK)\n rendered_text_rect = rendered_text.get_rect(center=(test_config.centre_x, test_config.centre_y))\n test_config.screen.blit(rendered_text, rendered_text_rect)\n pygame.time.set_timer(self.loading_event, 500)\n while(loading):\n if i > 2:\n i = 0\n try:\n msg = self.queues[self.process_names[\"Test Routine\"]].get_nowait()\n\n if msg.id == \"PupilTrackerReady\":\n print(\"[TestRoutine][INFO] Received ready message from Pupil Tracker\")\n pygame.time.set_timer(self.loading_event, 0)\n loading = False\n except QueueEmpty:\n pass\n\n for event in pygame.event.get():\n if event.type == self.loading_event:\n message = \"Initializing Concussion Detector\" + loading_message_frames[i]\n i += 1\n self.reset_screen()\n rendered_text = font_object.render(message, True, test_config.BLACK)\n rendered_text_rect = rendered_text.get_rect(center=(test_config.centre_x, test_config.centre_y))\n test_config.screen.blit(rendered_text, rendered_text_rect)\n elif event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n self.shutdown()\n\n pygame.display.update()\n\n self.quit_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((test_config.centre_x + self.BUTTON_WIDTH/2, test_config.centre_y + 200), self.BUTTON_SIZE),\n text='Quit',\n manager=self.menu_manager)\n self.start_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((test_config.centre_x - 3*self.BUTTON_WIDTH/2, test_config.centre_y + 200), self.BUTTON_SIZE),\n text='Start Test',\n manager=self.menu_manager)\n self.welcome_text = pygame_gui.elements.UITextBox(html_text=\"<font size=5>Welcome to <b>ProSpecs</b> Concussion Detection</font>\",\n relative_rect=pygame.Rect((test_config.centre_x - 230, 100), (460, 50)),\n manager=self.menu_manager,\n wrap_to_height=True)\n running = True\n data_entry_elements_created = False\n \n while running:\n time_delta = self.clock.tick(60)/1000.0\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n \n if event.type == pygame.USEREVENT:\n if event.user_type == pygame_gui.UI_BUTTON_PRESSED:\n if event.ui_element == self.quit_button:\n if self.show_cam:\n self.cam.release()\n self.shutdown()\n \n if event.ui_element == self.start_button:\n self.start_button.kill()\n self.welcome_text.kill()\n self.create_data_entry_elements()\n\n if event.ui_element == self.cont_button:\n if self.data_is_valid():\n #send data to concussion model\n self.sex_selection = 0 if self.sex_selection=='Male' else 1\n self.queues[self.process_names['Concussion Model']].put(PatientDataMessage(self.sex_selection, self.age_entry.get_text()))\n for element in self.data_entry_elements:\n element.kill()\n self.cont_button_2 = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((test_config.centre_x - 3*self.BUTTON_WIDTH/2, test_config.centre_y + 200), self.BUTTON_SIZE),\n text='Continue',\n manager=self.menu_manager)\n self.camera_label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect(test_config.centre_x - 750/2.0, test_config.centre_y + 100, 750, 50),\n text=\"Please make sure the patient's pupil is within the red square and in focus before proceeding.\",\n manager=self.menu_manager)\n self.show_cam = True\n if event.ui_element == self.cont_button_2:\n self.cam.release()\n self.show_cam = False\n running = False\n \n if event.user_type == pygame_gui.UI_DROP_DOWN_MENU_CHANGED:\n if event.ui_element == self.sex_dropdown:\n self.sex_selection = event.text\n\n self.menu_manager.process_events(event)\n self.menu_manager.update(time_delta)\n\n test_config.screen.fill(test_config.WHITE)\n self.menu_manager.draw_ui(test_config.screen)\n\n if self.show_cam:\n image = self.getCamFrame()\n box_height = 300\n box_width = 350\n pygame.draw.rect(image, test_config.RED, pygame.Rect(image.get_width()/2.0 - box_width/2.0,image.get_height()/2.0 - box_height/2.0, box_width, box_height), 2)\n test_config.screen.blit(image, (test_config.centre_x - image.get_width()/2.0,0))\n\n pygame.display.update()\n \n def getCamFrame(self):\n ret,frame = self.cam.read()\n frame = numpy.rot90(frame)\n frame = pygame.surfarray.make_surface(frame)\n return frame\n \n def shutdown(self):\n msg = ShutdownMessage(time.time())\n self.queues[self.process_names['Concussion Model']].put(msg)\n self.queues[self.process_names['Pupil Tracking']].put(msg)\n self.queues[self.process_names['Saccade Detector']].put(msg)\n pygame.quit()\n quit()\n\nif __name__ == \"__main__\":\n pygame.init()\n process_names = {\n 'Test Routine': 0,\n 'Concussion Model': 1,\n 'Pupil Tracking': 2,\n 'Saccade Detector': 3,\n }\n menu = Menu([Queue(),Queue(), Queue(), Queue()], process_names)\n test = TestSession([Queue(),Queue(), Queue(), Queue()], process_names, num_blocks=1)\n menu.run()\n test.run()\n" } ]
5
rajivpaulsingh/python-codingbat
https://github.com/rajivpaulsingh/python-codingbat
2ac2129891e20f34779bdddf91bc1e6edccf646d
f3ed40ad711297f1b574033429539883078f6803
f7318a5dcc02f34e4c25b44d61d42e7b472df441
refs/heads/main
2023-09-05T22:47:39.354164
2021-11-19T20:52:32
2021-11-19T20:52:32
429,606,544
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5927886962890625, "alphanum_fraction": 0.6414523720741272, "avg_line_length": 27.328571319580078, "blob_id": "3b8640d39e504519f33df28bd13e2df3c2fe8fed", "content_id": "dc6f5ed2b7021f97ab2fb87376313111d0b6a93b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4008, "license_type": "no_license", "max_line_length": 117, "num_lines": 140, "path": "/Logic-2.py", "repo_name": "rajivpaulsingh/python-codingbat", "src_encoding": "UTF-8", "text": "\n# make_bricks\n\"\"\"\nWe want to make a row of bricks that is goal inches long. \nWe have a number of small bricks (1 inch each) and big bricks (5 inches each). \nReturn True if it is possible to make the goal by choosing from the given bricks. \nThis is a little harder than it looks and can be done without any loops. \n\nmake_bricks(3, 1, 8) → True\nmake_bricks(3, 1, 9) → False\nmake_bricks(3, 2, 10) → True\n\"\"\"\ndef make_bricks(small, big, goal):\n return goal%5 >= 0 and goal%5 - small <= 0 and small + 5*big >= goal\n\n\n# lone_sum\n\"\"\"\nGiven 3 int values, a b c, return their sum. \nHowever, if one of the values is the same as another of the values, it does not count towards the sum.\n\nlone_sum(1, 2, 3) → 6\nlone_sum(3, 2, 3) → 2\nlone_sum(3, 3, 3) → 0\n\"\"\"\ndef lone_sum(a, b, c):\n if a == b == c:\n return 0\n elif a == b:\n return c\n elif a == c:\n return b\n elif b == a:\n return a\n elif b == c:\n return a\n else:\n return a + b + c\n\n\n# lucky_sum\n\"\"\"\nGiven 3 int values, a b c, return their sum. \nHowever, if one of the values is 13 then it does not count towards the sum and values to its right do not count. \nSo for example, if b is 13, then both b and c do not count.\n\nlucky_sum(1, 2, 3) → 6\nlucky_sum(1, 2, 13) → 3\nlucky_sum(1, 13, 3) → 1\n\"\"\"\ndef lucky_sum(a, b, c):\n if a == 13:\n return 0\n elif b == 13:\n return a\n elif c == 13:\n return a + b\n else:\n return a + b + c\n\n\n# no_teen_sum\n\"\"\"\nGiven 3 int values, a b c, return their sum. \nHowever, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, \nexcept 15 and 16 do not count as a teens. \nWrite a separate helper \"def fix_teen(n):\"that takes in an int value and returns that value fixed for the teen rule. \nIn this way, you avoid repeating the teen code 3 times (i.e. \"decomposition\").\nDefine the helper below and at the same indent level as the main no_teen_sum().\n\nno_teen_sum(1, 2, 3) → 6\nno_teen_sum(2, 13, 1) → 3\nno_teen_sum(2, 1, 14) → 3\n\"\"\"\ndef no_teen_sum(a, b, c):\n return fix_teen(a) + fix_teen(b) + fix_teen(c)\n\ndef fix_teen(n):\n if n in [13, 14, 17, 18, 19]:\n return 0\n else:\n return n\n\n\n# round_sum\n\"\"\"\nFor this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, \nso 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, \nso 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. \nTo avoid code repetition, write a separate helper \"def round10(num):\" and call it 3 times. \nWrite the helper entirely below and at the same indent level as round_sum().\n\nround_sum(16, 17, 18) → 60\nround_sum(12, 13, 14) → 30\nround_sum(6, 4, 4) → 10\n\"\"\"\ndef round_sum(a, b, c):\n return round10(a) + round10(b) + round10(c)\n\ndef round10(n):\n if n % 10 >= 5:\n return n + 10 - (n % 10)\n return n - (n % 10)\n\n\n# close_far\n\"\"\"\nGiven three ints, a b c, return True if one of b or c is \"close\" (differing from a by at most 1), \nwhile the other is \"far\", differing from both other values by 2 or more. \nNote: abs(num) computes the absolute value of a number.\n\nclose_far(1, 2, 10) → True\nclose_far(1, 2, 3) → False\nclose_far(4, 1, 3) → True\n\"\"\"\ndef close_far(a, b, c):\n cond1 = abs(a-b) <= 1 and abs(b-c) >=2 and abs(a-c) >= 2\n cond2 = abs(a-c) <= 1 and abs(a-b) >=2 and abs(c-b) >= 2\n return cond1 or cond2\n\n\n# make_chocolate\n\"\"\"\nWe want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). \nReturn the number of small bars to use, assuming we always use big bars before small bars. \nReturn -1 if it can't be done.\n\nmake_chocolate(4, 1, 9) → 4\nmake_chocolate(4, 1, 10) → -1\nmake_chocolate(4, 1, 7) → 2\n\"\"\"\ndef make_chocolate(small, big, goal):\n maxBig = goal / 5\n \n if big >= maxBig:\n if small >= (goal - maxBig * 5):\n return goal - maxBig * 5\n if big < maxBig:\n if small >= (goal - big * 5):\n return goal - big * 5\n return -1" }, { "alpha_fraction": 0.6062300205230713, "alphanum_fraction": 0.6182108521461487, "avg_line_length": 21.549549102783203, "blob_id": "ffc71c5d0a7daae175311aa43368d7c0956b3dff", "content_id": "5de46bf923d0c2ad72f69e38d9b29025b6fde515", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2540, "license_type": "no_license", "max_line_length": 104, "num_lines": 111, "path": "/String-2.py", "repo_name": "rajivpaulsingh/python-codingbat", "src_encoding": "UTF-8", "text": "\n# double_char\n\"\"\"\nGiven a string, return a string where for every char in the original, there are two chars.\n\ndouble_char('The') → 'TThhee'\ndouble_char('AAbb') → 'AAAAbbbb'\ndouble_char('Hi-There') → 'HHii--TThheerree'\n\"\"\"\ndef double_char(str):\n result = ''\n \n for char in str:\n result += char * 2\n return result\n\n\n# count_hi\n\"\"\"\nReturn the number of times that the string \"hi\" appears anywhere in the given string.\n\ncount_hi('abc hi ho') → 1\ncount_hi('ABChi hi') → 2\ncount_hi('hihi') → 2\n\"\"\"\ndef count_hi(str):\n count = 0\n \n for i in range(len(str)-1):\n # if str[i:i+2] == 'hi'\n if str[i] + str[i+1] == 'hi':\n count += 1\n return count\n\n\n# cat_dog\n\"\"\"\nReturn True if the string \"cat\" and \"dog\" appear the same number of times in the given string.\n\ncat_dog('catdog') → True\ncat_dog('catcat') → False\ncat_dog('1cat1cadodog') → True\n\"\"\"\ndef cat_dog(str):\n count_cat = 0\n count_dog = 0\n \n for i in range(len(str)-2):\n \n if str[i:i+3] == 'cat':\n count_cat += 1\n if str[i:i+3] == 'dog':\n count_dog += 1\n \n return count_cat == count_dog\n\n\n# count_code\n\"\"\"\nReturn the number of times that the string \"code\" appears anywhere in the given string, \nexcept we'll accept any letter for the 'd', so \"cope\" and \"cooe\" count.\n\ncount_code('aaacodebbb') → 1\ncount_code('codexxcode') → 2\ncount_code('cozexxcope') → 2\n\"\"\"\ndef count_code(str):\n count_code = 0\n \n for i in range(len(str)-3):\n \n if str[i:i+2] == 'co' and str[i+3] == 'e':\n count_code += 1\n \n return count_code\n\n\n# end_other\n\"\"\"\nGiven two strings, return True if either of the strings appears at the very end of the other string, \nignoring upper/lower case differences (in other words, the computation should not be \"case sensitive\"). \nNote: s.lower() returns the lowercase version of a string.\n\nend_other('Hiabc', 'abc') → True\nend_other('AbC', 'HiaBc') → True\nend_other('abc', 'abXabc') → True\n\"\"\"\ndef end_other(a, b):\n \n a = a.lower()\n b = b.lower()\n #return (b.endswith(a) or a.endswith(b))\n return a[-(len(b)):] == b or a == b[-(len(a)):] \n\n\n# xyz_there\n\"\"\"\nReturn True if the given string contains an appearance of \"xyz\" \nwhere the xyz is not directly preceeded by a period (.). So \"xxyz\" counts but \"x.xyz\" does not.\n\nxyz_there('abcxyz') → True\nxyz_there('abc.xyz') → False\nxyz_there('xyz.abc') → True\n\"\"\"\ndef xyz_there(str):\n \n for i in range(len(str)):\n if str[i] != '.' and str[i+1:i+4] == 'xyz':\n return True\n if str[0:3] == 'xyz':\n return True\n return False\n" }, { "alpha_fraction": 0.546145498752594, "alphanum_fraction": 0.6123778223991394, "avg_line_length": 25.066038131713867, "blob_id": "50ea487c9c3dd452fc4ed94cd86b223554b7afc2", "content_id": "562b7092815720cb759ef0d4cdda3cfaf77127f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2799, "license_type": "no_license", "max_line_length": 122, "num_lines": 106, "path": "/List-2.py", "repo_name": "rajivpaulsingh/python-codingbat", "src_encoding": "UTF-8", "text": "\n# count_evens\n\"\"\"\nReturn the number of even ints in the given array. \nNote: the % \"mod\" operator computes the remainder, e.g. 5 % 2 is 1.\n\ncount_evens([2, 1, 2, 3, 4]) → 3\ncount_evens([2, 2, 0]) → 3\ncount_evens([1, 3, 5]) → 0\n\"\"\"\ndef count_evens(nums):\n count = 0\n for element in nums:\n if element % 2 == 0:\n count += 1\n return count\n\n\n# big_diff\n\"\"\"\nGiven an array length 1 or more of ints, return the difference between the largest and smallest values in the array. \nNote: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.\n\nbig_diff([10, 3, 5, 6]) → 7\nbig_diff([7, 2, 10, 9]) → 8\nbig_diff([2, 10, 7, 2]) → 8\n\"\"\"\ndef big_diff(nums):\n \n return max(nums) - min(nums)\n\n\n# centered_average\n\"\"\"\nReturn the \"centered\" average of an array of ints, which we'll say is the mean average of the values, \nexcept ignoring the largest and smallest values in the array. \nIf there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. \nUse int division to produce the final average. You may assume that the array is length 3 or more.\n\ncentered_average([1, 2, 3, 4, 100]) → 3\ncentered_average([1, 1, 5, 5, 10, 8, 7]) → 5\ncentered_average([-10, -4, -2, -4, -2, 0]) → -3\n\"\"\"\ndef centered_average(nums):\n sum = 0\n for element in nums:\n sum += element\n return (sum - min(nums) - max(nums)) / (len(nums)-2) \n\n\n# sum13\n\"\"\"\nReturn the sum of the numbers in the array, returning 0 for an empty array. \nExcept the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.\n\nsum13([1, 2, 2, 1]) → 6\nsum13([1, 1]) → 2\nsum13([1, 2, 2, 1, 13]) → 6\n\"\"\"\ndef sum13(nums):\n if len(nums) == 0:\n return 0\n \n for i in range(0, len(nums)):\n if nums[i] == 13:\n nums[i] = 0\n if i+1 < len(nums): \n nums[i+1] = 0\n return sum(nums)\n\n\n# sum67\n\"\"\"\nReturn the sum of the numbers in the array, except ignore sections of numbers starting with a 6 \nand extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.\n\nsum67([1, 2, 2]) → 5\nsum67([1, 2, 2, 6, 99, 99, 7]) → 5\nsum67([1, 1, 6, 7, 2]) → 4\n\"\"\"\ndef sum67(nums):\n for i in range(0, len(nums)):\n if nums[i] == 6:\n nums[i] = 0\n for j in range(i+1, len(nums)):\n temp = nums[j]\n nums[j] = 0\n if temp == 7:\n i = j + 1\n break\n return sum(nums)\n\n\n# has22\n\"\"\"\nGiven an array of ints, return True if the array contains a 2 next to a 2 somewhere.\n\nhas22([1, 2, 2]) → True\nhas22([1, 2, 1, 2]) → False\nhas22([2, 1, 2]) → False\n\"\"\"\ndef has22(nums):\n for i in range(0, len(nums)-1):\n #if nums[i] == 2 and nums[i+1] == 2:\n if nums[i:i+2] == [2,2]:\n return True \n return False" } ]
3
JulyFan/mq_lib
https://github.com/JulyFan/mq_lib
48d66b1fd4d6ecb4bee32a4bfbe9d2e67e9d976d
5ea4a2a22ba8d74b30b548d62add5000203f8503
519979707436ec8754563bdf29572009b05f98d2
refs/heads/master
2020-03-18T09:33:41.825300
2018-05-23T13:12:20
2018-05-23T13:12:20
134,570,214
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6019047498703003, "alphanum_fraction": 0.6114285588264465, "avg_line_length": 17.75, "blob_id": "6964fb71f7b2f9e8a859c12b90c5f847292db64c", "content_id": "45a72cd5e19a09bfadaf2ac987ba8cd4cb0500cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1050, "license_type": "no_license", "max_line_length": 69, "num_lines": 56, "path": "/mq_logging.py", "repo_name": "JulyFan/mq_lib", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\n\"\"\"\ndescription:\n customize several logger to use at different situation\n\nfunctions:\n alpha\n\n\"\"\"\n# compatible with logging\ntry:\n import colorlog as logging\nexcept:\n import logging\n\n__all__ = ['__version__', 'alpha']\n\n__version__ = '0.0.0.1'\n\ndef alpha():\n \"\"\"\n description:\n logger to console\n\n Returns:\n A logger which prints on terminal window with out time info\n \"\"\"\n try:\n formatter = logging.ColoredFormatter\\\n ('%(log_color)s[%(levelname)s]: %(message)s')\n except:\n formatter = logging.Formatter('[%(levelname)s]: %(message)s')\n\n handler2con = logging.StreamHandler()\n handler2con.setFormatter(formatter)\n handler2con.setLevel('DEBUG')\n\n logger = logging.getLogger('alpha')\n logger.addHandler(handler2con)\n logger.setLevel('DEBUG')\n\n return logger\n\n\ndef main():\n logger = alpha()\n\n logger.error('test %d',5)\n logger.info('test')\n logger.debug('test')\n logger.warning('test')\n\n\nif __name__ == '__main__':\n main()\n" } ]
1
odify/PORT-OF-PYTHON
https://github.com/odify/PORT-OF-PYTHON
d985e1a25ac20072f375ed96b4186279e17f237e
b7335af2c55eb10768e3a0b9ad621e263e1b766d
3af1a0ba485f28ee695c9a95773140b6cfa721f1
refs/heads/main
2023-08-18T06:48:19.103446
2021-10-13T18:37:41
2021-10-13T18:37:41
311,485,221
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6548295617103577, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 25.362499237060547, "blob_id": "df5b49514e4a6131ccb167adf4db3a5069c578fc", "content_id": "7430fa2b95be6f2f19152ffdcede425c5e6ff19f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2112, "license_type": "no_license", "max_line_length": 120, "num_lines": 80, "path": "/Tools/slideshow-tool/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport os\n\n#webtemplate:\n\nprint(\"\"\"<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\n* {box-sizing: border-box;}\nhtml {\n height:740px;\n}\nbody {background-color: Gainsboro;}\n\n.mySlides {display: inline-block;}\n\nimg {vertical-align: middle;position:fixed;top:0px;left:0px;}\n</style>\n</head>\n<body>\n\n<img src=\"https://www.pngkey.com/png/full/339-3396597_2018-honda-civic-type-r-rear-angle-honda.png\"/>\n\n<script>\nvar slideIndex = 0;\nshowSlides();\n\nfunction showSlides() {\n var i;\n var slides = document.getElementsByTagName(\"img\");\nslides[0].style.opacity = \"0\";\n for (i = 1; i < slides.length; i++) {\n slides[i].style.display = \"none\"; \n }\n slideIndex++;\n if (slideIndex > slides.length) {slideIndex = 1} \n slides[slideIndex-1].style.display = \"block\"; \n \n setTimeout(showSlides, 1000); // Change image every 3 seconds\n}\n\n</script>\n\n</body>\n</html>\n\"\"\")\n\n\n\nimport urllib.request as req\nurl = 'https://de.cdn.mazda.media/3c7c7d9c041d45e7a96d3f619d02c132/99f5ef746f8c43cc83165518ba4b01a6.png?rnd=49bc43'\nreq.urlretrieve(url, 'river.png')\n\nimport urllib.request as req1\nurl = 'https://i.pinimg.com/originals/77/f9/a8/77f9a84b36bcc511df0f6be1c465c38b.png'\nreq1.urlretrieve(url, 'fuji.png');\n\nimport urllib.request as req2\nurl = 'https://smartcdn.prod.postmedia.digital/driving/wp-content/uploads/2021/05/chrome-image-413700.png'\nreq2.urlretrieve(url, 'palm.png');\n\nimport urllib.request as req3\nurl = 'https://freepngimg.com/thumb/honda/32430-8-honda-civic-transparent.png'\nreq3.urlretrieve(url, 'boats.png');\n\nimport urllib.request as req4\nurl = 'https://www.ford.ru/content/dam/guxeu/ru/ru_ru/vehicle-images/ecosport/Ford-Ecosport-ru-__-16x9-2160x1215-fc.png'\nreq4.urlretrieve(url, 'field.png');\n\nimport urllib.request as req5\nurl = 'https://www.pngall.com/wp-content/uploads/2016/05/Mercedes-Benz-Free-Download-PNG.png'\nreq5.urlretrieve(url, 'teahub.png');\n\nimport urllib.request as req6\nurl = 'https://freepngimg.com/thumb/chevrolet/32548-8-chevrolet-camaro-photo-thumb.png'\nreq6.urlretrieve(url, 'flowers.png');\n\n\n\n" }, { "alpha_fraction": 0.6764705777168274, "alphanum_fraction": 0.6764705777168274, "avg_line_length": 33, "blob_id": "406d42e4469289b9d5d83a457c8879b037a4b9ea", "content_id": "6196bd0cb4e6b7555334bb9830487e5ae73966c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 34, "license_type": "no_license", "max_line_length": 33, "num_lines": 1, "path": "/API/gmail-api/readme.md", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "Lorem ipsum dolor sit ametz......\n" }, { "alpha_fraction": 0.32350674271583557, "alphanum_fraction": 0.342196524143219, "avg_line_length": 26.97206687927246, "blob_id": "a54b504f0955c359c00adefc250167a1639399ab", "content_id": "5e037cf6bfe021f81b457a6a90585a7ff69107a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5190, "license_type": "no_license", "max_line_length": 118, "num_lines": 179, "path": "/GUI/translator-gui/translator01.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\r\n\r\nfrom tkinter import *\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom googletrans import Translator\r\nfrom tkinter import messagebox\r\n\r\nroot = tk.Tk()\r\nroot.title(' Translator V 0.1 ')\r\n\r\nroot.geometry('550x450')\r\n\r\nroot.maxsize(1400,900)\r\n\r\nroot.minsize(410,530)\r\n\r\n\r\ndef translate():\r\n language_1 = t1.get(\"1.0\",\"end-1c\")\r\n cl = choose_langauge.get()\r\n\r\n if language_1 == '':\r\n messagebox.showerror('INPUT')\r\n else:\r\n translator = Translator()\r\n output = translator.translate(language_1, dest=cl)\r\n t2.insert('end',output.text)\r\n\r\ndef clear():\r\n\r\n t1.delete(1.0,'end')\r\n t2.delete(1.0,'end')\r\n \r\n\r\n\r\na = tk.StringVar() \r\nauto_detect = ttk.Combobox(root, width = 30, textvariable = a, state='readonly',font=('verdana',11,'bold'),)\r\n\r\n\r\nauto_detect['values'] = (\r\n 'German',\r\n\r\n'Odia',\r\n'Hebrew',\r\n'English',\r\n'Persian',\r\n'Polish',\r\n'Russian',\r\n'Dutch',\r\n'Auto Detect',\r\n ) \r\n \r\nauto_detect.place(x=30,y=70)\r\nauto_detect.current(0) \r\n\r\nl = tk.StringVar() \r\nchoose_langauge = ttk.Combobox(root, width = 30, textvariable = l, state='readonly',font=('verdana',11)) \r\n \r\n\r\n# TRANSLATIONS ARRAY\r\n\r\nchoose_langauge['values'] = (\r\n 'Hebrew',\r\n 'Afrikaans',\r\n 'Albanian',\r\n 'Arabic',\r\n 'Armenian',\r\n ' Azerbaijani',\r\n 'Basque',\r\n 'Belarusian',\r\n 'Bengali',\r\n 'Bosnian',\r\n 'Bulgarian',\r\n 'Cebuano',\r\n 'Chichewa',\r\n 'Chinese',\r\n 'Corsican',\r\n 'Croatian',\r\n ' Czech',\r\n 'Danish',\r\n 'Dutch',\r\n 'English',\r\n 'Esperanto',\r\n 'Estonian',\r\n 'Finnish',\r\n 'French',\r\n 'Frisian',\r\n 'Georgian',\r\n 'German',\r\n 'Greek',\r\n 'Gujarati',\r\n 'Hausa',\r\n 'Hindi',\r\n 'Hungarian',\r\n 'Indonesian',\r\n 'Irish',\r\n 'Italian',\r\n 'Japanese',\r\n 'Javanese',\r\n 'Kazakh',\r\n 'Khmer',\r\n 'Kinyarwanda',\r\n 'Korean',\r\n 'Kurdish',\r\n 'Latin',\r\n 'Latvian',\r\n 'Lithuanian',\r\n 'Macedonian',\r\n 'Malagasy',\r\n 'Malay',\r\n 'Malayalam',\r\n 'Maltese',\r\n 'Maori',\r\n 'Marathi',\r\n 'Mongolian',\r\n 'Myanmar',\r\n 'Nepali',\r\n 'Norwegian'\r\n 'Odia',\r\n 'Pashto',\r\n 'Persian',\r\n 'Polish',\r\n 'Portuguese',\r\n 'Punjabi',\r\n 'Romanian',\r\n 'Russian',\r\n 'Samoan',\r\n 'Scots Gaelic',\r\n 'Serbian',\r\n 'Sesotho',\r\n 'Shona',\r\n 'Sindhi',\r\n 'Slovak',\r\n 'Slovenian',\r\n 'Somali',\r\n 'Spanish',\r\n 'Sundanese',\r\n 'Swahili',\r\n 'Swedish',\r\n 'Tajik',\r\n 'Tamil',\r\n 'Tatar',\r\n 'Telugu',\r\n 'Thai',\r\n 'Turkish',\r\n 'Turkmen',\r\n 'Urdu',\r\n 'Uzbek',\r\n 'Vietnamese',\r\n 'Welsh',\r\n 'Yiddish',\r\n 'Yoruba',\r\n 'Zulu',\r\n ) \r\n\r\n\r\nchoose_langauge.place(x=290,y=70)\r\nchoose_langauge.current(0) \r\n\r\n\r\nt1 = Text(root,width=30,height=7,borderwidth=4,relief=RIDGE)\r\nt1.place(x=10,y=100)\r\n\r\nt2 = Text(root,width=30,height=7,borderwidth=4,relief=RIDGE)\r\nt2.place(x=260,y=100)\r\n\r\n\r\nbutton = Button(root,text=\"TRANSLATE\",relief=RIDGE,borderwidth=3,font=('verdana',11),cursor=\"hand2\",command=translate)\r\n\r\nbutton.place(x=280,y=280)\r\n\r\n\r\nclear = Button(root,text=\"RESET\",relief=RIDGE,borderwidth=3,font=('verdana',14,'bold'),cursor=\"hand2\",command=clear)\r\nclear.place(x=80,y=280)\r\n\r\n\r\nroot.mainloop()\r\n\r\n\r\n" }, { "alpha_fraction": 0.6513460278511047, "alphanum_fraction": 0.6979645490646362, "avg_line_length": 27.203702926635742, "blob_id": "1ca1dc6619e7bf6a097c2e36716990e92acb6563", "content_id": "fde270edca391b854697a5ce9b7377603e0aebb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1523, "license_type": "no_license", "max_line_length": 86, "num_lines": 54, "path": "/GUI/musicplayer-gui/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\n\nfrom tkinter import *\nfrom tkinter import ttk,filedialog\nimport os\nfrom pygame import mixer\n \n \ndef play_song():\n mixer.music.load(play_list.get(ACTIVE))\n mixer.music.play()\n \ndef set_vol(val):\n mixer.music.set_volume(float(val)/100)\n \ndef open_folder():\n path = filedialog.askdirectory()\n if(path):\n os.chdir(path)\n songs = os.listdir(path)\n for song in songs:\n if(song.endswith(\".mp3\") or song.endswith(\".wav\")):\n play_list.insert(END,song)\n \nroot = Tk()\nmixer.init()\nroot.geometry(\"300x160\")\nroot.title(\"Mini Music Player\")\nroot.configure(bg='white')\ns = ttk.Style(root)\ns.theme_use('vista')\n \n\nttk.Button(root,text=\"Play\",width=10,command=play_song).place(x=10,y=10)\nttk.Button(root,text=\"Stop\",width=10,command=mixer.music.stop).place(x=10,y=40)\nttk.Button(root,text=\"Pause\",width=10,command=mixer.music.pause).place(x=10,y=70)\nttk.Button(root,text=\"UnPause\",width=10,command=mixer.music.unpause).place(x=10,y=100)\nttk.Button(root,text=\"Open\",width=10,command=open_folder).place(x=10,y=130)\n \nmusic_frame = Frame(root,bd=2,relief=RIDGE)\nmusic_frame.place(x=90,y=10,width=200,height=110)\nscroll_y = ttk.Scrollbar(music_frame)\nplay_list = Listbox(music_frame,width=29,yscrollcommand=scroll_y.set)\nscroll_y.config(command= play_list.yview)\nscroll_y.pack(side=RIGHT,fill=Y)\nplay_list.pack(side=LEFT,fill=BOTH)\n \nvol = ttk.Scale(root,from_ = 0, to_= 100,length=180,command=set_vol)\nvol.set(50)\nvol.place(x=100,y=130)\n \nroot.mainloop()\n" }, { "alpha_fraction": 0.6245387196540833, "alphanum_fraction": 0.6273062825202942, "avg_line_length": 24.809524536132812, "blob_id": "2f5296b0793e01f8f27c4122ce28d75408ffce11", "content_id": "144d9a75ea2a8c5bbf15d48d57d0d7a6fd047aa9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1084, "license_type": "no_license", "max_line_length": 61, "num_lines": 42, "path": "/API/github-repos-api/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport requests\nimport sys\nfrom github import Github\n\n\nusername = sys.argv[1]\n\nurl = f\"https://api.github.com/users/{username}\"\n\nuser_data = requests.get(url).json()\n\ndef repository_names(user):\n repo_names = []\n for repo in user.get_repos():\n repo_names.append(repo)\n return(repo_names)\n\n\ndef repository_details(user):\n all_repo_details = []\n repo_names = repository_names(user)\n for repo in repo_names:\n repo_details = {}\n repo_details['Name'] = repo.full_name.split('/')[1]\n repo_details['Description'] = repo.description\n repo_details['Created on'] = repo.created_at\n repo_details['Programming language'] = repo.language\n repo_details['Forked'] = str(repo.forks) + \" time(s)\"\n all_repo_details.append(repo_details)\n return(all_repo_details)\n\nuser = Github().get_user(username)\n\nRD = repository_details(user)\n\nif __name__ == \"__main__\":\n for content in RD:\n for title, description in content.items():\n print(title, \": \", description)\n print('\\n ')\n" }, { "alpha_fraction": 0.5778027772903442, "alphanum_fraction": 0.6704161763191223, "avg_line_length": 22.394737243652344, "blob_id": "c98881e28c1bdcbe84f48720b19f62f0ce3cd995", "content_id": "2f7b14b9d0fc0771b254b96a95e6634088cccdae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2667, "license_type": "no_license", "max_line_length": 162, "num_lines": 114, "path": "/GUI/contacts-gui/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nfrom tkinter import *\nimport tkinter.messagebox\nroot=Tk()\nroot.geometry('500x600')\nroot.title(\"Contacts GUI\")\nroot.configure(background=\"#3DD7AC\")\n\n\n\n\ntextin=StringVar()\n\n\n\nexlist={\n'Ali':'Ali Mohammad Musti\\[email protected]\\n01575-22930947717',\n'Chris':'Cristian Tahle\\[email protected]\\n01575-22930947751',\n'Emily':'Emily Klass\\[email protected]\\n01575-22930947752',\n'Franco':'Franco da Silva\\[email protected]\\n01575-22930947753',\n'Guilia':'Guilia Monza\\[email protected]\\n01575-22930947754',\n'Laura':'Laura Siebert\\[email protected]\\n01575-22930947755',\n'Mohammad':'Mohammad Mustiman\\[email protected]\\n01575-22930947756',\n'Suna':'Suna Agyar\\[email protected]\\n01575-229309477577',\n'Sameth':'Sameth Yilmaz\\[email protected]\\n01575-22930947758',\n'Viviane':'Viviane Logan\\[email protected]\\n01575-22930947759'}\n\n\n\ndef clk():\n entered = ent.get()\n output.delete(0.0,END)\n try:\n textin = exlist[entered]\n except:\n textin = 'SORRY NO INFO \\n AVAILABLE!!!!!!!!\\n'\n output.insert(0.0,textin)\n\ndef ex():\n tkinter.messagebox.showinfo(\"Program\",'Exit')\n exit()\n \ndef exitt():\n tkinter.messagebox.showinfo(\"Program\",'Exit')\n exit() \n\ndef me():\n text='\\n WHAT? \\n Ok Bro... \\n Easy (Y)'\n saveFile=open('text.txt','w')\n saveFile.write(text)\n print('This are the entries::',text)\n \n \ndef hel():\n help(tkinter)\n\ndef cont():\n tkinter.messagebox.showinfo(\"Conatcts:\",'\\n 1.Ali\\n 2.Chris \\n 3.Emily \\n 4.Franco \\n 5.Guilia \\n 6.Laura \\n 7.Mohammad \\n 8.Suna \\n 6.Sameth \\n 10.Viviane')\n \n \ndef clr():\n textin.set(\" \")\n \n\nmenu = Menu(root)\nroot.config(menu=menu)\n\nsubm = Menu(menu)\nmenu.add_cascade(label=\"File\",menu=subm)\nsubm.add_command(label=\"Memo\",command=me)\nsubm.add_command(label=\"Save\")\nsubm.add_command(label=\"Save As\")\nsubm.add_command(label=\"Print\")\nsubm.add_command(label=\"Exit\",command=ex)\n\nsubm1 = Menu(menu)\nmenu.add_cascade(label=\"Contacts\",menu=subm1)\nsubm1.add_command(label=\"to select:\",command=cont)\n\n\n\nlab=Label(root,text='Name :',font=('none 20 bold'))\nlab.grid(row=0,column=1,sticky=W)\n\n\nent=Entry(root,width=20,font=('none 17 bold'),textvar=textin,bg='white')\nent.grid(row=0,column=2,sticky=W)\n\n\nbut=Button(root,padx=2,pady=2,text='Submit',command=clk,bg='powder blue',font=('none 18 bold'))\nbut.place(x=100,y=90)\n\n\nbut4=Button(root,padx=2,pady=2,text='Clear',font=('none 18 bold'),bg='powder blue',command=clr)\nbut4.place(x=220,y=90)\n\n\n\noutput=Text(root,width=20,height=8,font=('Time 20 bold'),fg=\"black\")\noutput.place(x=100,y=200)\n\n\nlabb=Label(root,text='Results',font=('non 16 bold'))\nlabb.place(x=0,y=180)\n\n\nbut1=Button(root,padx=2,pady=2,text='Exit',command=exitt,bg='powder blue',font=('none 18 bold'))\nbut1.place(x=200,y=470)\n\n\n\nroot.mainloop()\n" }, { "alpha_fraction": 0.5483871102333069, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 14.5, "blob_id": "3eb4dd09fc23ee2984a207e504cc15ca655aea8d", "content_id": "cccaf7f941d4cb7f26754e7882b305ebffd7ec44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 31, "license_type": "no_license", "max_line_length": 16, "num_lines": 2, "path": "/CLI/wikipedia-cli/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "pyfiglet==0.8\nwikipedia==1.4.0\n" }, { "alpha_fraction": 0.6262626051902771, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 12.454545021057129, "blob_id": "ea864a04917729240e318ab242306cad6cb9c044", "content_id": "232188649f8b4b37d670b7aafd78d6a60f8a862e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 31, "num_lines": 22, "path": "/Tools/json-samples/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport json\n\n\n# read a JSON file\n# 1st option\nfile_name = \"xy.json\"\nwith open(file_name) as f:\n data = json.load(f)\n \nprint(data)\n# 2nd option\nfile_name = \"xy.json\"\nwith open(file_name) as f:\n data = json.loads(f.read())\n\nprint(data)\n\n\n# MAKE read.py , write.py \n" }, { "alpha_fraction": 0.7431192398071289, "alphanum_fraction": 0.752293586730957, "avg_line_length": 20.799999237060547, "blob_id": "45500374099fd1c468f252dea71d98be79ecdfe1", "content_id": "2a8fd7a07d0087ede29a214f516af76b3447db3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "no_license", "max_line_length": 41, "num_lines": 5, "path": "/Tools/auto-keys/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import keyboard\n\nevent = keyboard.record(until='ctrl + z')\nkeyboard.play(event, speed_factor=1)\nprint(event)\n" }, { "alpha_fraction": 0.5415878891944885, "alphanum_fraction": 0.5453686118125916, "avg_line_length": 20.59183692932129, "blob_id": "a1386c7be4c7fd74cb891a7565a8dd2001fab47c", "content_id": "19e7b802e248701a88111cf215a14e867a4c833a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1058, "license_type": "no_license", "max_line_length": 70, "num_lines": 49, "path": "/CLI/metas-cli/metaextractor.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python3\nfrom colored import stylize, fg\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS\n\n\n# EXTRACT METADATA FROM IMG\n\n\n\nclass Metadata:\n def __init__(self, file):\n self.file = file\n\n def __repr__(self):\n metadata = self.extract_metadata(self.file)\n if len(metadata) == 0:\n return stylize(f\"\\n{self.file} No metadata.\\n\", fg(\"red\"))\n else:\n print(stylize(f\"\\nMetadata of {self.file}:\\n\", fg(\"red\")))\n for data in metadata:\n print(data)\n return \"\"\n\n def extract_metadata(self, file):\n\n image = Image.open(file)\n\n\n exifdata = image.getexif()\n\n metadata = []\n\n for tag_id in exifdata:\n tag = TAGS.get(tag_id, tag_id)\n data = exifdata.get(tag_id)\n\n if isinstance(data, bytes):\n data = data.decode()\n\n metadata.append(f\"{tag:25}: {data}\")\n\n return metadata\n\n\nif __name__ == \"__main__\":\n filename = input(\"Filename: \")\n\n print(Metadata(filename))\n" }, { "alpha_fraction": 0.6369137763977051, "alphanum_fraction": 0.6520423889160156, "avg_line_length": 25.440000534057617, "blob_id": "4db01822f848f5b912d8bc18cd5255f2d8b898fd", "content_id": "9dd000b1eb3a92563af1993d272db11197074b61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 100, "num_lines": 25, "path": "/API/haveibeenpwd-api/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport hashlib\nimport getpass\nimport requests\n\npassword = input('Password:')\n\n\nHASH_SHA1 = hashlib.sha1(str(password).encode('utf-8'))\nhash = HASH_SHA1.hexdigest()\nURL = \"https://api.pwnedpasswords.com/range/{}\".format(hash[0:5])\nr = requests.get(url=URL)\ndata = list(str(r.text).split('\\n'))\nbool_pwned = False\nfor i in data:\n tranform_data = str(i).replace(\"\\r\",\"\").split(\":\")\n if hash.upper()[5::] == tranform_data[0]:\n bool_pwned = True\n break\n\nif bool_pwned:\n print(\"\\nOh No - pwned! This Password has been seen {} times before\\n\".format(tranform_data[1]))\nelse:\n print(\"\\nGood news — no pwnage found!\\n\")\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.761904776096344, "avg_line_length": 9.5, "blob_id": "4953b72cf0c18714aadeb14ce1238bf0a5e54613", "content_id": "234594e7a3b35e372fe25bca8508244ee6d405dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 21, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/CLI/passwordgen-cli/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "pyfiglet==0.8\nrandom\n" }, { "alpha_fraction": 0.7185430526733398, "alphanum_fraction": 0.7218543291091919, "avg_line_length": 14.894737243652344, "blob_id": "f39843a987a3aefc5ec2c2b98696b919645f27e1", "content_id": "b992f3b5cab6aa3157cc6d28a0fb0bffc9a1c68c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 47, "num_lines": 19, "path": "/CLI/url-shorter-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport pyshorteners\nimport os\nimport datetime\nimport pyfiglet\n\n\nresult = pyfiglet.figlet_format(\"URL Shorter\")\nprint(result)\nos.system(\"date\")\nprint(\"\\n\") # describtion-row\n\n\n\nurl = input(\"Enter URL\")\n\ns = pyshorteners.Shortener().tinyurl.short(url)\nprint(\"Shorted URL -->\", s)\n" }, { "alpha_fraction": 0.45088016986846924, "alphanum_fraction": 0.48438388109207153, "avg_line_length": 22.743244171142578, "blob_id": "4bc2f96768c51f59ab4b67129f708a97760da249", "content_id": "555ce861093137e1f130abf7819a4e4600a59cef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1761, "license_type": "no_license", "max_line_length": 114, "num_lines": 74, "path": "/Tools/Proxy/.py/sqli.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import sqlite3\n\nconnect = sqlite3.connect(':memory:')\n\ncursor = connect.cursor()\n\npeople_data = {\n 1:('Kuba S', 37),\n 2:('Lara C', 24),\n 3:('Tomy D', 23),\n 4:('Nora B', 34),\n 5:('Zack S', 44),\n 6:('Rana S', 38),\n 7:('Rose M', 32),\n 8:('Ania L', 28)\n}\n\n\ndef create():\n sqlstr = 'CREATE TABLE PEOPLE(ID int AUTO_INCREMENT, Name varchar(255), Age int)'\n cursor.execute(sqlstr)\n connect.commit()\n\n\n\n\n\ndef insert(id, name, age):\n sqlstr = 'INSERT INTO PEOPLE(ID, Name, Age) VALUES (\"' + str(id) + '\", \"' + str(name) + '\", ' + str(age) + ')'\n cursor.execute(sqlstr)\n connect.commit()\n\n\n\ndef filter(f):\n sqlstr = 'SELECT * FROM PEOPLE WHERE ' + f + ' ORDER BY Name'\n print ('Database filtered by:', sqlstr, '\\n')\n print ('ID', 'Name ', ' Age')\n print (\"-----------------------------\")\n for row in cursor.execute(sqlstr):\n print(('{0:{width}}'.format(row[0], width=2)),\n ('{0:{width}}'.format(row[1], width=20)),\n ('{0:{width}}'.format(row[2], width=2)))\n print('-----------------------------\\n')\n\n\ndef display_all():\n sqlstr = 'SELECT * FROM PEOPLE'\n print ('Showing the whole database')\n print ('ID', 'Name ', ' Age')\n print (\"-----------------------------\")\n for row in cursor.execute(sqlstr):\n print(('{0:{width}}'.format(row[0], width=2)),\n ('{0:{width}}'.format(row[1], width=20)),\n ('{0:{width}}'.format(row[2], width=2)))\n print('-----------------------------\\n')\n\n\ncreate()\nfor k, v in people_data.items():\n insert(k, v[0], v[1])\n\nfilter('Age>25')\nprint('* ' * 19, '\\n')\nfilter('Name LIKE \"%k%\"')\nprint('* ' * 19, '\\n')\ndisplay_all()\n\n\ncursor.close()\n\n# n = name\n# a = age\n# insert(9, n, a) 4 new records\n\n\n\n\n" }, { "alpha_fraction": 0.6619318127632141, "alphanum_fraction": 0.6676136255264282, "avg_line_length": 13.666666984558105, "blob_id": "20b858f210ef92a4e2c532b2e645012c67b349f7", "content_id": "7c00e4a992d3a9edf848d652b8a0d70ad709eb42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 352, "license_type": "no_license", "max_line_length": 46, "num_lines": 24, "path": "/Tools/ftp-tool/download.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\n# DOWNLOAD \"myfile.txt\"\n\nimport ftplib\n\n\nFTP_HOST = \" YOUR FTP HOSTNAME \"\nFTP_USER = \" YOUR FTP USERNAME \"\nFTP_PASS = \" PASSWORD \"\n\n\nftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS)\nftp.encoding = \"utf-8\"\n\n\nfilename = \"myfile.txt\"\nwith open(filename, \"wb\") as file:\n\nftp.retrbinary(f\"RETR {filename}\", file.write)\n\n\nftp.quit()\n" }, { "alpha_fraction": 0.659375011920929, "alphanum_fraction": 0.668749988079071, "avg_line_length": 20.200000762939453, "blob_id": "f094078d778ca28da9d356476103c789ab8634c1", "content_id": "0927ec15a877b989716e069106e4e8283f8f9f15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 54, "num_lines": 15, "path": "/GUI/cryptocurrency-gui/btc.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport requests\n\nURL = \"https://www.google.com/search?q=\"\nQUERY = \"bitcoin+price+in+usd\"\n\n\ndef scrape():\n r = requests.get(URL+QUERY)\n s = BeautifulSoup(r.text, 'html.parser')\n ans = s.find(\"div\", class_ =\"BNeawe iBp4i AP7Wnd\")\n return ans.text\n\nprice = scrape()\nprint(price)\n\n\n" }, { "alpha_fraction": 0.5880979895591736, "alphanum_fraction": 0.5892648696899414, "avg_line_length": 29.60714340209961, "blob_id": "ac8867375d1e7645fc7f8d57f2308bef33a375f7", "content_id": "753fd7d7f0f3397ba1fbf978c8d1f97fe0d12c04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "no_license", "max_line_length": 163, "num_lines": 28, "path": "/CLI/story-cli/story.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nfrom random import choice\nimport pyfiglet\n\nresult = pyfiglet.figlet_format(\"Story generator\")\nprint(result)\n# print(\"\\n\") # describtion-row\nprint(\"------------------------------------\")\n\ndef story_gen():\n\n wer = ['Ferdi', 'Rene', 'Malina', 'Sarah']\n was = ['aß Obstsalat mit Stäbchen', 'flog nach China', 'kam zu spät zum Treffpunkt', 'musste sich übergeben']\n wann = ['vor ein paar Tagen', 'gestern', 'grade eben', 'vorgestern']\n action = ['aber leider regnete es mal wieder', 'und wurde somit zum Held des Tages', 'wahrscheinlich unter größter Anstrengung', 'und war total in partylaune']\n\n\n\n return print(choice(wer) + ' ' + choice(was) + ' ' + choice(wann) + ' ' + choice(action))\n\ndef print_story():\n story_gen()\n print('------------------------------------')\n\nif __name__ == '__main__':\n print_story()\n" }, { "alpha_fraction": 0.3870967626571655, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 14.5, "blob_id": "d7db25f0701e928095d90bef10a2d349c7cd4a94", "content_id": "8bfaf070d91f010f3183ebd81a611d50fd2a2fca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 31, "license_type": "no_license", "max_line_length": 16, "num_lines": 2, "path": "/GUI/cryptocurrency-gui/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "requests==2.22.0\nPyQt5==5.15.1\n" }, { "alpha_fraction": 0.7111111283302307, "alphanum_fraction": 0.7481481432914734, "avg_line_length": 21.5, "blob_id": "254b4ed8d71127d33426787d9e38988893bfbacb", "content_id": "583e4ebeee774e7d113f90907118841538cd05c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 135, "license_type": "no_license", "max_line_length": 60, "num_lines": 6, "path": "/Tools/mongodb-samples/collection.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import pymongo\n\nmyclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\nmydb = myclient[\"newdatabase\"]\n\nmycol = mydb[\"customers\"]\n" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.800000011920929, "avg_line_length": 11.5, "blob_id": "521b7c53de454d540a970b400e6eb6e9d360dbe9", "content_id": "b954463b2ee40be149d573de53fc343b5e763d0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 25, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/CLI/cut+conv-cli/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "pyfiglet==0.8\nsubprocess\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.8148148059844971, "avg_line_length": 12.5, "blob_id": "6c4c2ec26769771276f13e7e7ce6a5a0d214a7b6", "content_id": "244fea7e59aa35cf3c80161e6812fe23944c1307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 27, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/CLI/url-shorter-cli/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "pyfiglet==0.8\npyshorteners\n" }, { "alpha_fraction": 0.5471698045730591, "alphanum_fraction": 0.7358490824699402, "avg_line_length": 16.66666603088379, "blob_id": "b0753d1acad91e751779fdde8db866ff7b25c2b1", "content_id": "580a443309c39f7beed44d46ad132bbd7b23107c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 53, "license_type": "no_license", "max_line_length": 21, "num_lines": 3, "path": "/CLI/horoscope-cli/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "pyfiglet==0.8\nbeautifulsoup4==4.8.2\nrequests==2.22.0\n" }, { "alpha_fraction": 0.7151162624359131, "alphanum_fraction": 0.7248061895370483, "avg_line_length": 23.571428298950195, "blob_id": "dd9431e34d3404c40b380b338fcf1f0d9d5f45be", "content_id": "fe66a617b229d14c0c5e79be7ef8aac9b490efe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 516, "license_type": "no_license", "max_line_length": 81, "num_lines": 21, "path": "/API/openface-api/_test/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport openface\n\n\n\n\n\nalign = openface.AlignDlib(args.dlibFacePredictor)\nnet = openface.TorchNeuralNet(args.networkModel, args.imgDim, cuda=args.cuda)\n\n# `img` is a numpy matrix containing the RGB pixels of the image.\nbb = align.getLargestFaceBoundingBox(img)\nalignedFace = align.align(args.imgDim, img, bb,\n landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)\nrep1 = net.forward(alignedFace)\n\n# `rep2` obtained similarly.\nd = rep1 - rep2\ndistance = np.dot(d, d)\n" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 13, "blob_id": "157446fa78ae2961d6359cf2594a856e96c1a0be", "content_id": "dab94a6234b8918b067d907016f454e28f91d66e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 15, "license_type": "no_license", "max_line_length": 13, "num_lines": 1, "path": "/GUI/filemanager-gui/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "pyfiglet==0.8\n\n" }, { "alpha_fraction": 0.5856573581695557, "alphanum_fraction": 0.5956175327301025, "avg_line_length": 19.079999923706055, "blob_id": "fcd238cc0ee2c851f5732a8dee8133b10c043538", "content_id": "29e75740d35509d6ec3f374f73da116747b183b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "no_license", "max_line_length": 55, "num_lines": 25, "path": "/CLI/passwordgen-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport string\nfrom random import *\nimport pyfiglet\n\n\nresult = pyfiglet.figlet_format(\"Password:\")\nprint(result)\nprint(\"----------------------------------------------\")\n\nletters = string.ascii_letters\ndigits = string.digits\nsymbols = string.punctuation\nchars = letters + digits + symbols\n\nmin_lenght = 13\nmax_lenght = 19\n\npassword = \"\".join(choice(chars) for x in \nrange(randint(min_lenght, max_lenght)))\n\nprint(password)\nprint(\"----------------------------------------------\")\n" }, { "alpha_fraction": 0.6255999803543091, "alphanum_fraction": 0.6496000289916992, "avg_line_length": 18.53125, "blob_id": "4a22814b335472bd2f2f957a9d230a95154eba19", "content_id": "106b262c7f4cb55dba014979db51c528514ab340", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 625, "license_type": "no_license", "max_line_length": 73, "num_lines": 32, "path": "/GUI/recorder-gui/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport sounddevice as sd\nimport soundfile as sf\nfrom tkinter import *\nimport datetime\nimport pyfiglet\n\n\nresult = pyfiglet.figlet_format(\"Soundrecorder\")\nprint(result)\nprint(\"\\n\") # describtion-row\nos.system(\"date\")\nprint(\"-----------------------------------------\")\n\n\ndef Voice_rec():\n fs = 48000\n\n duration = 5\n myrecording = sd.write('my_Audio.flac', myrecording, fs)\n\nmaster = Tk()\n\nLabel(master, text=\" Sound Recorder : \").grid(row=0, sticky=W, rowspan=5)\n\n\n\nb = Button(master, text=\"Start\", command=Voice_rec)\nb.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5)\n\nmainloop()\n" }, { "alpha_fraction": 0.5370370149612427, "alphanum_fraction": 0.5370370149612427, "avg_line_length": 19.769229888916016, "blob_id": "240029dea5241dca91958f886f3850d27e1e42c0", "content_id": "ce5639f3ce2d5aaed17c81b55ed51f0040ef774d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 38, "num_lines": 13, "path": "/Tools/auto-keys/onpress.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import keyboard\n\n\nwhile True:\n if keyboard.read_key() == 'c':\n print('Pressed C')\n break\n elif keyboard.read_key() == 'esc':\n print('Closing program..')\n break\n elif keyboard.is_pressed('w'):\n print('Pressed W')\n break\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.739130437374115, "avg_line_length": 14.666666984558105, "blob_id": "9863134825b05c485510cb384bb120cfe329cab4", "content_id": "e0a8194b3235c1ee02ef9567d37fc3f0e8fb3c99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 46, "license_type": "no_license", "max_line_length": 16, "num_lines": 3, "path": "/API/R&M-api/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "pyfiglet==0.8\nurllib3==1.25.10\njsonpatch==1.26" }, { "alpha_fraction": 0.3668639063835144, "alphanum_fraction": 0.37278106808662415, "avg_line_length": 14.720930099487305, "blob_id": "a42f39dfc3e04f85290c835793aa7733094dced7", "content_id": "f3b8ff16b227769a7a13c13108c272041c5b575f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 676, "license_type": "no_license", "max_line_length": 50, "num_lines": 43, "path": "/Tools/progressbars/main2.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3 \n\n\nimport os\nimport datetime\nimport time\nimport progressbar\nfrom progress.bar import IncrementalBarimport time\nfrom progress.bar import IncrementalBar\n\nprint(\"-------------------------------------\")\n\nprint(\"_____________________________________\")\nprint(\"\\n\")\nprint(\"\\n\")\nanimation = [\n\"[ ]\",\n\"[= ]\",\n\"[=== ]\",\n\"[==== ]\",\n\"[===== ]\",\n\"[====== ]\",\n\"[======= ]\",\n\"[========]\",\n\"[ =======]\",\n\"[ ======]\",\n\"[ =====]\",\n\"[ ====]\",\n\"[ ===]\",\n\"[ ==]\",\n\"[ =]\",\n\"[ ]\",\n\"[ ]\"\n]\n\nnotcomplete = True\n\ni = 0\n\nwhile notcomplete:\n print(animation[i % len(animation)], end='\\r')\n time.sleep(.1)\n i += 1\n" }, { "alpha_fraction": 0.6462395787239075, "alphanum_fraction": 0.6573815941810608, "avg_line_length": 17.736841201782227, "blob_id": "51b96707e164fbbeaa636250c9388833bbc70ee7", "content_id": "d180c3e1bc1998d62f7c89befc96de4f1f99726e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 359, "license_type": "no_license", "max_line_length": 34, "num_lines": 19, "path": "/CLI/img-metadatas-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS\nimport sys\n\nimagename = sys.argv[1]\n\nimage = Image.open(imagename)\n\nexifdata = image.getexif()\n\nfor tag_id in exifdata:\n tag = TAGS.get(tag_id, tag_id)\n data = exifdata.get(tag_id)\n if isinstance(data, bytes):\n data = data.decode()\n print(f\"{tag:25}: {data}\")\n\n\n\n" }, { "alpha_fraction": 0.6005917191505432, "alphanum_fraction": 0.6035503149032593, "avg_line_length": 20, "blob_id": "8467aff0b511a57546bd78f2e244ad4b505bd36e", "content_id": "4ed52abd38549ce7be2b3d822d50ab534d6986a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 53, "num_lines": 16, "path": "/Tools/email-crawler/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport requests\nimport re\n\nurl = input('YOUR URL (include `http://`): ')\n\nwebsite = requests.get(url)\n\nhtml = website.text\nlinks = re.findall('\"((http|ftp)s?://.*?)\"', html)\nemails = re.findall('([\\w\\.,]+@[\\w\\.,]+\\.\\w+)', html)\n\nprint(\"\\nFound {} links\".format(len(links)))\nfor email in emails:\n print(email)\n\n\n" }, { "alpha_fraction": 0.6212121248245239, "alphanum_fraction": 0.6484848260879517, "avg_line_length": 11.185185432434082, "blob_id": "8ef3bc3198174b164db93dad0b91fef8d5f18656", "content_id": "fa67c928c20d9bed03200b425d75fa9e08756c65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 330, "license_type": "no_license", "max_line_length": 39, "num_lines": 27, "path": "/CLI/mp4player-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\n\n\ncap = cv2.VideoCapture('test.mp4')\n\nif (cap.isOpened()== False):\nprint(\"Error\")\n\nwhile(cap.isOpened()):\n\t\nret, frame = cap.read()\nif ret == True:\n\n\tcv2.imshow('Frame', frame)\n\n\t# Press Q to exit\n\tif cv2.waitKey(25) & 0xFF == ord('q'):\n\tbreak\n\nelse:\n\tbreak\n\ncap.release()\n\ncv2.destroyAllWindows()\n\n" }, { "alpha_fraction": 0.6976377964019775, "alphanum_fraction": 0.7015748023986816, "avg_line_length": 22.962265014648438, "blob_id": "de22e38f23473fee1696a97fba80d0c6c0a36403", "content_id": "c97690935d10389fbd8e84cf17c217693c9aea3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1270, "license_type": "no_license", "max_line_length": 89, "num_lines": 53, "path": "/Tools/quick-starter/flask/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport pyautogui\nimport time\n\n\nterminal = ''\ndir = ''\nfolder = ''\nproject = 'test'\nnew = 'app'\n\n\npyautogui.press('win')\npyautogui.typewrite(terminal)\npyautogui.typewrite(['enter'])\npyautogui.typewrite('cd ./' + dir + ' &&' + ' mkdir ' + folder + ' && ' + 'cd ' + folder)\npyautogui.typewrite(['enter'])\npyautogui.typewrite('create-flask-app ' + project)\npyautogui.typewrite(['enter'])\npyautogui.typewrite(['flaskproject'])\n# pyautogui.typewrite('cd ' + project + ' &&' + ' python3 manage.py startapp ' + new)\npyautogui.typewrite(['enter'])\n\npyautogui.typewrite(['space'])\npyautogui.typewrite(['enter'])\n\n\n\ntime.sleep(1)\n\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['space'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['space'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['down'])\npyautogui.typewrite(['space'])\n\n\n# pyautogui.typewrite('python3 manage.py migrate')\n# pyautogui.typewrite(['enter'])\n# pyautogui.typewrite('python3 manage.py runserver')\n# pyautogui.typewrite(['enter'])\n" }, { "alpha_fraction": 0.6215053796768188, "alphanum_fraction": 0.6344085931777954, "avg_line_length": 15.034482955932617, "blob_id": "4b1e3d73c9a7791fc8a76a7b84b5da24a67c2c9b", "content_id": "6e802b705d736d3a6e7a9b28ba69945300144743", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 465, "license_type": "no_license", "max_line_length": 66, "num_lines": 29, "path": "/CLI/mp3player-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport pyaudio\nimport wave\nimport sys\n\nfilename = sys.argv[1]\nchunk = 1024\n\nwf = wave.open(filename, \"rb\")\np = pyaudio.PyAudio()\n\nstream = p.open(format=p.get_format_from_width(wf.getsampwidth()),\n channels=wf.getnchannels(),\n rate=wf.getframerate(),\n output=True)\n\ndata = wf.readframes(chunk)\n\n\n\nwhile data:\n stream.write(data)\n data = wf.readframes(chunk)\n\n\nstream.close()\np.terminate()\n" }, { "alpha_fraction": 0.5196687579154968, "alphanum_fraction": 0.5224292874336243, "avg_line_length": 27.979999542236328, "blob_id": "c0a11b8ad18da76a7f19d91e360196f6c6d5d7e1", "content_id": "148aed792ee6ad8fdfdaee290cad22ae3c7a6623", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1449, "license_type": "no_license", "max_line_length": 102, "num_lines": 50, "path": "/API/R&M-api/rickandmortyapi.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\n#PY 2: RICK AND MORTY API\n\nimport os\nimport datetime\nimport pyfiglet\nfrom urllib.request import urlopen as url_open\nimport urllib\nimport json\n#from PIL import Image\n\nresult = pyfiglet.figlet_format(\"XYZ X.Y\")\nprint(result)\nos.system(\"date\")\nprint(\"\\n\") # describtion-row\n\n\n\n\ndef rmAPI_search(search_query):\n URL = 'https://rickandmortyapi.com/api/character/?name=' + search_query\n IRRELEVANT = ['episode', 'url', 'created', 'image']\n \n try:\n opened = url_open(URL).read().decode('utf-8')\n info_json = json.loads(opened)\n for result in info_json['results']: \n\n#'results' : [{'key': value}, {'key' : {'key': value}}] -> format of the json return from the API call\n\n for key in result:\n if key not in IRRELEVANT:\n value = result[key]\n if key == \"origin\" or key == \"location\":\n value = result[key]['name']\n try:\n print('{}: {}'.format(key, value))\n #Image.open(url_open(result['image']))\n except:\n value = value.encode('utf-8')\n print('{}: {}'.format(key, value))\n #Image.open(url_open(result['image']))\n print(\"\\n\") \n \n except:\n print('{}: No such character found'.format(search_query))\n \nrmAPI_search('morty')\n" }, { "alpha_fraction": 0.5533225536346436, "alphanum_fraction": 0.604538083076477, "avg_line_length": 24.92436981201172, "blob_id": "3d7af37e93e270b49a3450b36c93e078d771e511", "content_id": "4a0402e67eec3d3c2e83ba472acc078f2a8177ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3085, "license_type": "no_license", "max_line_length": 99, "num_lines": 119, "path": "/Tools/Proxy/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\n\nimport requests\nimport random\nfrom bs4 import BeautifulSoup as bs\n\ndef get_free_proxies():\n url = \"https://free-proxy-list.net/\"\n # get the HTTP response and construct soup object\n soup = bs(requests.get(url).content, \"html.parser\")\n proxies = []\n for row in soup.find(\"table\", attrs={\"id\": \"proxylisttable\"}).find_all(\"tr\")[1:]:\n tds = row.find_all(\"td\")\n try:\n ip = tds[0].text.strip()\n port = tds[1].text.strip()\n host = f\"{ip}:{port}\"\n proxies.append(host)\n except IndexError:\n continue\n return proxies\n\n\ndef get_session(proxies):\n # construct an HTTP session\n session = requests.Session()\n # choose one random proxy\n proxy = random.choice(proxies)\n session.proxies = {\"http\": proxy, \"https\": proxy}\n return session\n\n\nif __name__ == \"__main__\":\n # proxies = get_free_proxies()\n proxies = [\n '167.172.248.53:3128',\n '194.226.34.132:5555',\n '203.202.245.62:80',\n '141.0.70.211:8080',\n '118.69.50.155:80',\n '201.55.164.177:3128',\n '51.15.166.107:3128',\n '91.205.218.64:80',\n '128.199.237.57:8080',\n ]\n for i in range(5):\n s = get_session(proxies)\n try:\n print(\"Request page with IP:\", s.get(\"http://icanhazip.com\", timeout=1.5).text.strip())\n except Exception as e:\n continue\n\n\nMULTI_TOR=\n\nimport requests\nfrom stem.control import Controller\nfrom stem import Signal\n\ndef get_tor_session():\n # initialize a requests Session\n session = requests.Session()\n # setting the proxy of both http & https to the localhost:9050 \n # (Tor service must be installed and started in your machine)\n session.proxies = {\"http\": \"socks5://localhost:9050\", \"https\": \"socks5://localhost:9050\"}\n return session\n\ndef renew_connection():\n with Controller.from_port(port=9051) as c:\n c.authenticate()\n # send NEWNYM signal to establish a new clean connection through the Tor network\n c.signal(Signal.NEWNYM)\n\n\nif __name__ == \"__main__\":\n s = get_tor_session()\n ip = s.get(\"http://icanhazip.com\").text\n print(\"IP:\", ip)\n renew_connection()\n s = get_tor_session()\n ip = s.get(\"http://icanhazip.com\").text\n print(\"IP:\", ip)\n\n\nTOR=\n\nimport requests\n\n\ndef get_tor_session():\n # initialize a requests Session\n session = requests.Session()\n # this requires a running Tor service in your machine and listening on port 9050 (by default)\n session.proxies = {\"http\": \"socks5://localhost:9050\", \"https\": \"socks5://localhost:9050\"}\n return session\n\n\nif __name__ == \"__main__\":\n s = get_tor_session()\n ip = s.get(\"http://icanhazip.com\").text\n print(\"IP:\", ip)\n\n\nCRAWLERA=\n\nimport requests\n\nurl = \"http://icanhazip.com\"\nproxy_host = \"proxy.crawlera.com\"\nproxy_port = \"8010\"\nproxy_auth = \":\"\nproxies = {\n \"https\": f\"https://{proxy_auth}@{proxy_host}:{proxy_port}/\",\n \"http\": f\"http://{proxy_auth}@{proxy_host}:{proxy_port}/\"\n}\n\nr = requests.get(url, proxies=proxies, verify=False)\n" }, { "alpha_fraction": 0.5780436992645264, "alphanum_fraction": 0.6040582656860352, "avg_line_length": 14.626016616821289, "blob_id": "7c36a437701e8f16a147d53211d1b99d22f63aca", "content_id": "41d07598eee09874b8cbf47fa01df0c851b49ce6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1922, "license_type": "no_license", "max_line_length": 70, "num_lines": 123, "path": "/Tools/Proxy/.py/2nd/simple.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import psycopg2\n\n\ndef connect():\n\n\ttry:\n\n\t\tconn = psycopg2.connect(database =\"test\",\n\t\t\t\t\t\t\tuser = \"admin123\",\n\t\t\t\t\t\t\tpassword = \"123password\",\n\t\t\t\t\t\t\thost = \"localhost\",\n\t\t\t\t\t\t\tport = \"5432\")\n\n\t\tcur = conn.cursor()\n\t\n\texcept (Exception, psycopg2.DatabaseError) as error:\n\t\t\n\t\tprint (\"Error\", error)\n\t\n\n\treturn conn, cur\n\n\ndef create_table():\n\n\n\tconn, cur = connect()\n\n\ttry:\n\t\t# the test database contains a table called emp\n\t\t# the schema : (id INTEGER PRIMARY KEY,\n\t\t# name VARCHAR(10), salary INT, dept INT)\n\t\t# create the emp table\n\n\t\tcur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10),\n\t\t\t\t\t\t\t\t\tsalary INT, dept INT)')\n\n\t\t# the commit function permanently\n\t\t# saves the changes made to the database\n\t\t# the rollback() function can be used if\n\t\t# there are any undesirable changes and\n\t\t# it simply undoes the changes of the\n\t\t# previous query\n\t\n\texcept:\n\n\t\tprint('error')\n\n\tconn.commit()\n\ndef insert_data(id = 1, name = '', salary = 1000, dept = 1):\n\n\tconn, cur = connect()\n\n\ttry:\n\t\tcur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)',\n\t\t\t\t\t\t\t\t\t(id, name, salary, dept))\n\t\n\texcept Exception as e:\n\n\t\tprint('error', e)\n\tconn.commit()\n\n\ndef fetch_data():\n\n\tconn, cur = connect()\n\n\ttry:\n\t\tcur.execute('SELECT * FROM emp')\n\t\n\texcept:\n\t\tprint('error !')\n\n\tdata = cur.fetchall()\n\n\n\treturn data\n\ndef print_data(data):\n\n\tprint('Query result: ')\n\tprint()\n\n\tfor row in data:\n\n\n\t\tprint('id: ', row[0])\n\t\tprint('name: ', row[1])\n\t\tprint('salary: ', row[2])\n\t\tprint('dept: ', row[3])\n\t\tprint('--------------------------------')\n\n\ndef delete_table():\n\n\tconn, cur = connect()\n\n\ttry:\n\n\t\tcur.execute('DROP TABLE emp')\n\n\texcept Exception as e:\n\t\tprint('error', e)\n\n\tconn.commit()\n\n\nif __name__ == '__main__':\n\n\n\tcreate_table()\n\n\tinsert_data(1, 'xy', 1000, 2)\n\tinsert_data(2, 'xxy', 100000, 2)\n\tinsert_data(3, 'xxxy', 100, 3)\n\tinsert_data(4, 'xxxxy', 10000, 4)\n\n\tdata = fetch_data()\n\n\tprint_data(data)\n\n\tdelete_table()\n" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7664884328842163, "avg_line_length": 23.39130401611328, "blob_id": "7280bdd660c38f76175eef7e6c1a2e90aeed03ef", "content_id": "2b6966e21a3266f0c3bf7b9bc9b74e2193c76445", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 561, "license_type": "no_license", "max_line_length": 85, "num_lines": 23, "path": "/Tools/pdf-creator/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom pathlib import Path\n\nfrom borb.pdf.canvas.layout.page_layout.multi_column_layout import SingleColumnLayout\nfrom borb.pdf.canvas.layout.text.paragraph import Paragraph\nfrom borb.pdf.document import Document\nfrom borb.pdf.page.page import Page\nfrom borb.pdf.pdf import PDF\n\n\npdf = Document()\npage = Page()\n\npdf.append_page(page)\nlayout = SingleColumnLayout(page)\nlayout.add(Paragraph(\"Hello world ! Lets create some pdf\"))\n\n\nwith open(Path(\"test.pdf\"), \"wb\") as pdf_file_handle:\n PDF.dumps(pdf_file_handle, pdf)\n\n#pip install borb\n" }, { "alpha_fraction": 0.5722891688346863, "alphanum_fraction": 0.5903614163398743, "avg_line_length": 7.736842155456543, "blob_id": "d49ec475b53f09d103dda7cb243b0353bf6745ff", "content_id": "40763bfa3b9e7d517b078e8d4668474ce5b2a858", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 22, "num_lines": 19, "path": "/Tools/json-samples/create/create.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport json\n\nx = {\n \"name\": \"ferdi\",\n \"age\": 29,\n \"city\": \"Langenfeld\"\n}\n\n\n#Convert into JSON\n\ny = json.dumps(x)\n\n#JSON CREATED\n\nprint(y)\n" }, { "alpha_fraction": 0.6416666507720947, "alphanum_fraction": 0.6621212363243103, "avg_line_length": 27.69565200805664, "blob_id": "03c9b22d321cd01893516fe22003ab9f63added2", "content_id": "34ed0d67a67a2a5a404244d80f4d2ede73c52f0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1320, "license_type": "no_license", "max_line_length": 66, "num_lines": 46, "path": "/API/geo-api/geo-api.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen as OPEN\nfrom urllib.parse import urlencode as ENCODE\nfrom xml.etree import ElementTree as XML\n\napi_url = 'http://maps.googleapis.com/maps/api/geocode/xml?'\n\naddress = input('Enter location: ')\nif len(address) < 1:\n address = \"Langenfeld, Germany\"\nurl = api_url + ENCODE({'sensor': 'false', 'address': address})\nprint ('\\nRetrieving location for:', address)\ndata = OPEN(url).read()\ntree = XML.fromstring(data)\n\nres = tree.findall('result')\n\nlat = res[0].find('geometry').find('location').find('lat').text\nlng = res[0].find('geometry').find('location').find('lng').text\nlat = float(lat)\nlng = float(lng)\nif lat < 0:\n lat_c = chr(167)+'S'\nelse:\n lat_c = chr(167)+'N'\nif lng < 0:\n lng_c = chr(167)+'W'\nelse:\n lng_c = chr(167)+'E'\n\nlocation = res[0].find('formatted_address').text\nlocation_type = res[0].find('geometry').find('location_type').text\nplace_id = res[0].find('place_id').text\n\nurl = 'http://maps.googleapis.com/maps/api/place/details/xml?'\n\ndata = OPEN(url).read()\ntree = XML.fromstring(data)\nres = tree.findall('status')[0].text\n\n\nprint(\"\\n==>\", location, \"<==\")\nprint('Latitude: {0:.3f}{1}'.format(abs(lat), lat_c))\nprint('Longitude: {0:.3f}{1}'.format(abs(lng), lng_c))\nprint('Location type:', location_type)\nprint('Place ID:', place_id)\nprint('Rating:', res)\n" }, { "alpha_fraction": 0.5882353186607361, "alphanum_fraction": 0.5927602052688599, "avg_line_length": 16, "blob_id": "de841da9196e407812f3e0b57432253b0f2ba7fb", "content_id": "c56f566cc26be93fabe4fe601af025fc10ac1200", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 221, "license_type": "no_license", "max_line_length": 46, "num_lines": 13, "path": "/CLI/ipcheck-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport os\nimport datetime\nimport pyfiglet\n\n\nresult = pyfiglet.figlet_format(\"XYZ X.Y\")\nprint(result)\nprint(\"\\n\") # describtion-row\nos.system(\"date\")\nprint(\"-------------------------------------\")\n" }, { "alpha_fraction": 0.6822034120559692, "alphanum_fraction": 0.6864407062530518, "avg_line_length": 13.75, "blob_id": "0bdfa5b2358226c9d1967564ee646e45f71df9b1", "content_id": "f68ead89e3199d28895d2da5c5be9e297cfb428f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 33, "num_lines": 16, "path": "/CLI/qrcode-cli/qrcode.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import pyqrcode\nimport png\nfrom pyqrcode import QRCode\n\n\nprint(\"Enter text to convert\")\ns=input(\": \")\n\n# Name of QR code\nprint(\"Enter image name to save\")\nn=input(\": \")\nd=n+\".png\"\n\nurl=pyqrcode.create(s)\nurl.show()\nurl.png(d, scale =6)\n" }, { "alpha_fraction": 0.6749672293663025, "alphanum_fraction": 0.7057667374610901, "avg_line_length": 18.316455841064453, "blob_id": "f5afe19dea5b6083aa860233154dbda35dd951f4", "content_id": "e71c7ac0763a86f693e4b4cee061e938eaabe177", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1526, "license_type": "no_license", "max_line_length": 78, "num_lines": 79, "path": "/CLI/image-processing-cli/_test/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nfrom PIL import Image, ImageDraw, ImageFont,ImageEnhance, ImageFilter,ImageOps\nimport PIL\n\n\n#import a picture and rename it to 'image.jpg'\n\nimg = PIL.Image.open('image.jpg')\n\n\nimage_file = img.convert('1')\n#or import multiple images\n\n#edit the script for your optional processing\n\nimage_file.save('b+w.png')\n\nconverter = PIL.ImageEnhance.Brightness(img).enhance(4.5)\nconverter.save('brightness.jpg')\n\nconverter = PIL.ImageEnhance.Color(img).enhance(4.5)\nconverter.save('colorful.jpg')\n\nblur = img.filter(ImageFilter.GaussianBlur(radius = 10)) \nblur.save('blur.jpg') \n\n\nconverter = PIL.ImageEnhance.Contrast(img).enhance(4.5)\nconverter.save('highcontrast.jpg')\n\n\nim = ImageOps.posterize(img, 3) \nim.save('posterized.jpg')\n\n\ninverted_image = PIL.ImageOps.invert(img)\ninverted_image.save('invert.png')\n\n\ncrop = img.crop((0, 0, 2500, 2500))\ncrop.save('cropped.jpg')\n\n\nrotate = img.rotate(180)\nrotate.save('rotated.jpg')\n\n\nim_mirror = ImageOps.mirror(img)\nim_mirror.save('mirror.jpg')\n\n\nheight,width = img.size\nimage_data = img.load()\nfor loop1 in range(height):\n for loop2 in range(width):\n r,g,b = image_data[loop1,loop2]\n image_data[loop1,loop2] = 0,g,0\nimg.save('changecolor.jpeg')\n\n\n#draw = ImageDraw.Draw(img)\n#font = ImageFont.truetype('arial.ttf', size=80)\n#draw.text((50, 50), 'hello world',fill = 'rgb(0, 0, 0)', font=font)\n#img.save('draw.jpg')\n\n\n\n\ntil = Image.open('pin.png')\nimg.paste(til,(00,10))\nimg.save('paste.jpg')\n\n\n\n\n\nimg.save(\"compress.jpg\",optimize=True,quality=10)\n" }, { "alpha_fraction": 0.7143782377243042, "alphanum_fraction": 0.7240932583808899, "avg_line_length": 58.38461685180664, "blob_id": "eafca45e0e6f9bc43fe279538b35cc0cff85f8e3", "content_id": "2132d1a6011bcadae7aae42d9d98586b2d22ceba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1551, "license_type": "no_license", "max_line_length": 629, "num_lines": 26, "path": "/CLI/typewriter-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport pyfiglet\nimport pyautogui\n\n\n\nresult = pyfiglet.figlet_format(\"TYPEWRITER\")\nprint(result)\n\nprint(\"-------------------------------------\")\nprint(\"-------------------------------------\")\n\n\npyautogui.typewrite('Hello world of python', interval=0.19 )\n\npyautogui.typewrite('...................', interval=0.08 )\n\npyautogui.typewrite('„Lorem ipsum dolor sit amet, consectetur adipisici elit, …\" ist ein Blindtext, der nichts bedeuten soll, sondern als Platzhalter im Layout verwendet wird, um einen Eindruck vom fertigen Dokument zu erhalten. ', interval=0.33 )\n\npyautogui.typewrite('Die Verteilung der Buchstaben und der Wortlängen des pseudo-lateinischen Textes entspricht in etwa der natürlichen lateinischen Sprache. Der Text ist absichtlich unverständlich, damit der Betrachter nicht durch den Inhalt abgelenkt wird.', interval=0.5 )\n\npyautogui.typewrite('Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet', interval=0.83 )\n\nprint(\"-------------------------------------\")\n" }, { "alpha_fraction": 0.671875, "alphanum_fraction": 0.671875, "avg_line_length": 18.200000762939453, "blob_id": "c2824a291717dfd940d57f97681bb76b4f397584", "content_id": "65a8e3f163bbee5302701d58f5f2b6ab9d578d90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "no_license", "max_line_length": 39, "num_lines": 10, "path": "/API/fake-api-cli/fake-cli.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\nurl = 'https://api.namefake.com/'\n\nresponse = requests.get(url)\njson_data = json.loads(response.text)\n\nfor i in json_data:\n print(i+ ' : ' + str(json_data[i]))\n" }, { "alpha_fraction": 0.6553672552108765, "alphanum_fraction": 0.6610169410705566, "avg_line_length": 13.15999984741211, "blob_id": "abe7da672e9f66e91bd0e24f2de0ca47e18f5d7c", "content_id": "76dab47a9213f82642451ea9036380cea4af9701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 46, "num_lines": 25, "path": "/Tools/ftp-tool/upload.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\n# UPLOAD \"myfile.txt\"\n\nimport ftplib\n\n\nFTP_HOST = \" YOUR FTP HOSTNAME \"\nFTP_USER = \" YOUR FTP USERNAME \"\nFTP_PASS = \" PASSWORD \"\n\n\nftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS)\nftp.encoding = \"utf-8\"\n\n\nfilename = \"myfile.txt\"\nwith open(filename, \"rb\") as file:\n\nftp.storbinary(f\"STOR {filename}\", file)\n\nftp.dir()\n\nftp.quit()\n" }, { "alpha_fraction": 0.5952380895614624, "alphanum_fraction": 0.6279761791229248, "avg_line_length": 16.6842098236084, "blob_id": "b7dc6234c0ceddaaa661ed6820cb2799ef962296", "content_id": "e34fdc43fff9dadcd64c2ab39412079f0abc4f54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 336, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/GUI/numpy-gui/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = {'Xyz':50, 'X':10, 'Y':5, 'Z':2, }\n\ncourses = list(data.keys())\nvalues = list(data.values())\n\nfig = plt.figure(figsize = (2, 4))\n\n\n\nplt.bar(courses, values, color ='red',\n width = 0.25)\n\nplt.xlabel(\"x-label\")\nplt.ylabel(\"y-label\")\nplt.title(\"Simple diagram\")\nplt.show()\n" }, { "alpha_fraction": 0.6267748475074768, "alphanum_fraction": 0.6298174262046814, "avg_line_length": 22.4761905670166, "blob_id": "0b375f0692cbcdb54ce29a19ff5031b3e1249247", "content_id": "9a3c6ae54cafdef4097cdeb230ea9c7ceda8ce6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 986, "license_type": "no_license", "max_line_length": 119, "num_lines": 42, "path": "/Tools/pdf-writer/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom docx import Document\nfrom pdf2docx import parse\nimport subprocess\nimport os\n\n\ndef pdf_to_word(pdf_file):\n word_file = 'word.docx'\n parse(pdf_file, word_file)\n\n\ndef edit_word(find, replacement):\n\n word_file = Document('word.docx')\n replace = {find: replacement}\n\n for x in replace:\n for line in word_file.paragraphs:\n if line.text.find(x) >= 0:\n line.text = line.text.replace(x, replace[x])\n\n word_file.save('converted.docx')\n\n\ndef word_to_pdf():\n\n subprocess.run([\"libreoffice\", \"--headless\", \"--convert-to\", \"pdf\", 'converted.docx'])\n if os.path.exists(\"word.docx\"):\n os.remove(\"word.docx\")\n if os.path.exists(\"converted.docx\"):\n os.remove(\"converted.docx\")\n\n\nif __name__ == \"__main__\":\n\n file, find, replacement = input(\"Your settings (format: file_name.pdf text_to_replace replacement_text): \").split()\n\n pdf_to_word(file)\n edit_word(find, replacement)\n word_to_pdf()\n" }, { "alpha_fraction": 0.5265241265296936, "alphanum_fraction": 0.5463182926177979, "avg_line_length": 19.322580337524414, "blob_id": "875145def2d52c4b43a3fcf4d096ae387e86b724", "content_id": "71c1f56661daf060d000568e0a83a4392c6c440b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1263, "license_type": "no_license", "max_line_length": 65, "num_lines": 62, "path": "/Tools/progressbars/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3 \n\n\nimport os\nimport datetime\nimport time\nimport progressbar\nfrom progress.bar import IncrementalBarimport time\nfrom progress.bar import IncrementalBar\n\nprint(\"-------------------------------------\")\n\nprint(\"_____________________________________\")\nprint(\"\\n\")\nprint(\"\\n\")\n\n\nmylist = [1,2,3,4,5,6,7,8,9]\nbar = IncrementalBar('Countdown', max = len(mylist))\nfor item in mylist:\n bar.next()\n time.sleep(1)\nbar.finish()\n\n\n#bar = IncrementalBar('Countdown', max = len(mylist))\n#for item in mylist:\n# bar.next()\n# time.sleep(1)\n# bar.finish()\n\n#def animated_marker():\n# widgets = ['Loading: ', progressbar.AnimatedMarker()]\n# bar = progressbar.ProgressBar(widgets=widgets).start()\n# for i in range(43):\n# time.sleep(0.13)\n# bar.update(i)\n#animated_marker()\n\n#widgets = [' [',\n# progressbar.Timer(format= 'elapsed time: %(elapsed)s'),\n# '] ',\n# progressbar.Bar('*'),' (',\n# progressbar.ETA(), ') ',\n# ]\n#bar = progressbar.ProgressBar(max_value=200, \n# widgets=widgets).start()\n#for i in range(200):\n# time.sleep(0.1)\n# bar.update(i)\n\n\n\n\n\nos.system(\"date\")\nprint(\"\\n\")\n\nprint(\"-------------------------------------\")\n\nprint(\"\\n\")\nprint(\"\\n\")\n\n\n\n" }, { "alpha_fraction": 0.554347813129425, "alphanum_fraction": 0.717391312122345, "avg_line_length": 17.399999618530273, "blob_id": "49915f7683bc472d39163263043c77672a9d7d46", "content_id": "c25f0bc92dff66e6a052fd3661b5bacda6d2e7f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 92, "license_type": "no_license", "max_line_length": 25, "num_lines": 5, "path": "/GUI/translator-gui/requirements.txt", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "pyfiglet==0.8\ngoogletrans==3.0.0\ntk==0.1.0\ntk-html-widgets==0.4.0\nTkinterExtensions==1.4.23\n" }, { "alpha_fraction": 0.5573440790176392, "alphanum_fraction": 0.5875251293182373, "avg_line_length": 21.590909957885742, "blob_id": "c00347cd45d8173ccda702cafdf3b21dc1be4acf", "content_id": "920011322e84fe9b790e32161f71efdb629a7b9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "no_license", "max_line_length": 58, "num_lines": 22, "path": "/CLI/alarm-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import time\nfrom playsound import playsound\n\n\n\ndef countdown(t):\n\n min_sec = input_time.split(sep=':')\n time_in_sec = (int(min_sec[0]) * 60) + int(min_sec[1])\n while time_in_sec:\n mins, secs = divmod(time_in_sec,60)\n timer = f\"{mins}:{secs}\"\n print('\\r', timer, end=\"\")\n time.sleep(1)\n time_in_sec -= 1\n\n playsound('audio.mp3')\n\ninput_time = input(print(\"Countdown: (MM:SS) - \"))\ncountdown(input_time)\n\n# INPUT FORMAT: MM:SS FOR EXSAMPLE 00:10 = 10s\n" }, { "alpha_fraction": 0.6368421316146851, "alphanum_fraction": 0.6368421316146851, "avg_line_length": 18, "blob_id": "2572256474d2782f17f76d17a044207ee111f590", "content_id": "991d6a929c19cc2b22e07cf41a7391f0eaba20b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 41, "num_lines": 10, "path": "/Tools/Proxy/ssl.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "from scraper import Scraper\n\n\nif __name__ == '__main__':\n scraper = Scraper() \n proxies = scraper.scrape(protocol='SSL')\n \n while proxies.qsize:\n proxy = proxies.get()\n print(proxy)\n" }, { "alpha_fraction": 0.6556016802787781, "alphanum_fraction": 0.680497944355011, "avg_line_length": 19.08333396911621, "blob_id": "3b4c471f2f51a58de079779905f313480d74359a", "content_id": "f9eba18ccda1550604885b5f392fb7c5f7521d95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 241, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/GUI/translator-gui/README.md", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "<body>\n<h2>Python Translator</h2>\n<hr>\n<h5>Simple tkinter GUI for Google-translations</h5>\n<p>Quickstart</p>\n<ol>\n<li>git clone [URL]</li>\n<li>cd [xyz]</li>\n<li>pip install requirements.txt</li>\n<li>python translator01.py</li>\n</ol>\n</body>\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 16, "blob_id": "80dd4f39e09b04614f1d1c1171be1d829e728175", "content_id": "118b4ef27c8912af0d960682a4898eecce993a7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/README.md", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "# PORT-OF-PYTHON\n" }, { "alpha_fraction": 0.6815642714500427, "alphanum_fraction": 0.6885474920272827, "avg_line_length": 21.375, "blob_id": "516474c88963322de93b7698b0152f1bc8950e56", "content_id": "e99d2b6934da3dc1e890dfc9e9c8ece89a0358cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "no_license", "max_line_length": 89, "num_lines": 32, "path": "/Tools/quick-starter/django/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport pyautogui\nimport time\n\n\n\nterminal = ''\ndir = ''\nfolder = ''\nproject = 'test'\nnew = 'app'\n\n\n\npyautogui.press('win')\npyautogui.typewrite(terminal)\npyautogui.typewrite(['enter'])\npyautogui.typewrite('cd ./' + dir + ' &&' + ' mkdir ' + folder + ' && ' + 'cd ' + folder)\npyautogui.typewrite(['enter'])\npyautogui.typewrite('django-admin.py startproject ' + project)\npyautogui.typewrite(['enter'])\npyautogui.typewrite('cd ' + project + ' &&' + ' python3 manage.py startapp ' + new)\npyautogui.typewrite(['enter'])\n\ntime.sleep(1)\n\npyautogui.typewrite('python3 manage.py migrate')\npyautogui.typewrite(['enter'])\npyautogui.typewrite('python3 manage.py runserver')\npyautogui.typewrite(['enter'])\n" }, { "alpha_fraction": 0.5790960192680359, "alphanum_fraction": 0.5819209218025208, "avg_line_length": 17.63157844543457, "blob_id": "ef5da14043a0a97d425ac73ac260f46246f6feb0", "content_id": "bda725822c80fe4244d202999f0a7f2be3ae8da8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 45, "num_lines": 19, "path": "/CLI/email-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nimport random\nimport smtplib\n\n\ndef automatic_email():\n user = input(\" name >>: \")\n email = input(\" email ID>>: \")\n\n\n s = smtplib.SMTP('smtp.gmail.com', #PORT)\n s.starttls()\n s.login(\"Your Gmail Account\", \"PW \")\n s.sendmail('&&&&&&&&&&&', email, message)\n print(\"Email Sent!\")\n \nautomatic_email()\n" }, { "alpha_fraction": 0.6138107180595398, "alphanum_fraction": 0.6649616360664368, "avg_line_length": 19.578947067260742, "blob_id": "4c302a01825ed29d43bc0bdd2f8d86c1ef9540d9", "content_id": "4dfc8fe7b5ce6af428946288018f6286eaf34917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 391, "license_type": "no_license", "max_line_length": 54, "num_lines": 19, "path": "/CLI/img-extractor-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import cv2\nimport pytesseract\n\n\n\n\nimg =cv2.imread('img.png')\nimg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n\nhI,wI,k=img.shape\nprint(pytesseract.image_to_string(img))\nboxes=pytesseract.image_to_boxes(img)\nfor b in boxes.splitlines():\n b=b.split(' ')\n x,y,w,h=int(b[1]),int(b[2]),int(b[3]),int(b[4])\n cv2.rectangle(img,(x,hI-y),(w,hI-h),(0,0,255),0.2)\n\ncv2.imshow('img',img)\ncv2.waitKey(0)\n" }, { "alpha_fraction": 0.5587301850318909, "alphanum_fraction": 0.5608465671539307, "avg_line_length": 22.04878044128418, "blob_id": "021bced98116b747bf9be025d7ee367c5cd445ae", "content_id": "ffb9f226f743436e8e195f842fc1981223e50592", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "no_license", "max_line_length": 65, "num_lines": 41, "path": "/CLI/zipper-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nfrom zipfile import ZipFile\nimport datetime\nimport pyfiglet\n\n\nresult = pyfiglet.figlet_format(\"Zipper CLI\")\nprint(result)\nos.system(\"date\")\nprint(\"-------------------------------------\")\n\n\ndef zip_me(path):\n \"\"\" Your folder path & name \"\"\"\n folder_name = path.split(\"\\\\\")[-1]\n rel_path = path.strip(folder_name)\n\n \"\"\" Save to the target folder path \"\"\"\n os.chdir(rel_path)\n\n parse = ZipFile(f\"{folder_name}.zip\", \"w\")\n\n\n for root, dirs, files in os.walk(folder_name, topdown=False):\n \"\"\" Files in sub-folders \"\"\"\n for name in files:\n file = os.path.join(root, name)\n parse.write(file)\n\n \"\"\" Sub-folders in target folder \"\"\"\n for name in dirs:\n folders = os.path.join(root, name)\n parse.write(folders)\n parse.close()\n \n\nif __name__ == \"__main__\":\n path = input(r\"Path to target folder: \")\n zip_me(path)\n" }, { "alpha_fraction": 0.6504992842674255, "alphanum_fraction": 0.6847360730171204, "avg_line_length": 24.962963104248047, "blob_id": "957142d38247abfffc610eb66022c4c1565c56e3", "content_id": "586a2b2ed6abae4c08f6f18e95f33395ece736bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 701, "license_type": "no_license", "max_line_length": 80, "num_lines": 27, "path": "/API/news-api/newsapi.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport requests\nimport os\nimport datetime\nimport pyfiglet\n\n\nresult = pyfiglet.figlet_format(\"News API\\n\")\nprint(result)\nos.system(\"date\")\nprint(\"\\n\") # describtion-row\n\n\n_NEWS_API = \"https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=\"\n\n\ndef fetch_bbc_news(bbc_news_api_key: str) -> None:\n # fetching a list of articles in json format\n bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json()\n # each article in the list is a dict\n for news, article in enumerate(bbc_news_page[\"articles\"], 1):\n print(f\"{news}.) {article['title']}\")\n\n\nif __name__ == \"__main__\":\n fetch_bbc_news(bbc_news_api_key=\"f6a267260a564dc08d40a90e1a8be145\")\n" }, { "alpha_fraction": 0.608315110206604, "alphanum_fraction": 0.6105032563209534, "avg_line_length": 17.95833396911621, "blob_id": "875b132ef7e43b38c340654a0de14eb783345d42", "content_id": "f2c7af7429c48f6f2e116a61d2befd0eb4f7dc77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 457, "license_type": "no_license", "max_line_length": 51, "num_lines": 24, "path": "/CLI/wikipedia-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\n\nimport wikipedia\nimport os\nimport datetime\nimport pyfiglet\n\n\nresult = pyfiglet.figlet_format(\"Wikipedia cli\")\nprint(result)\n# print(\"\\n\") # describtion-row\nos.system(\"date\")\nprint(\"------------------------------------\")\n\ndef searcher(question):\n answer = wikipedia.summary(question).split(\".\")\n for line in answer:\n print(line)\n\nif __name__ == \"__main__\":\n question = input(\"Search now: \")\n searcher(question)\n\n\n" }, { "alpha_fraction": 0.5148355960845947, "alphanum_fraction": 0.5380914211273193, "avg_line_length": 24.97916603088379, "blob_id": "8ec3f47ae022e5cfedac0bf2e87697cdd26e0632", "content_id": "e473e3ef5f14b0b89f797510a3df7db883235057", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 68, "num_lines": 48, "path": "/CLI/tags-cli/tags.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "tags = \"\"\"\n#tag1 #tag2 #tag3 #tag4 #tag5 #tag6 #tag7 #tag8 \n#tag9 #tag10 #tag11 #tag12 #tag13 #tag14 #tag15 #tag16 #tag17 #tag18\n\"\"\"\n\nclass Tag_Generator(object):\n def __init__(self, tag_list):\n self.tag_list = tag_list\n\n def sort_function(self):\n sorted_list = []\n _split = self.tag_list.split(\"#\")\n \n for item in _split:\n item = item.strip(\"\\n\").strip()\n if item not in sorted_list:\n sorted_list.append(item)\n sorted_list = sorted(sorted_list)\n return sorted_list\n\n\n def tag_generator(self):\n sorted_list = self.sort_function()\n generated_tags = []\n while len(generated_tags) < 30:\n tag = random.choice(sorted_list)\n tag = \"#\" + tag\n if tag not in generated_tags:\n generated_tags.append(tag)\n return generated_tags\n\n\n def __repr__(self):\n tags = self.tag_generator()\n list = \"\"\n for element in tags:\n list += f\"{element} \"\n return list\n\n\nif __name__ == \"__main__\":\n import random\n\n tag = Tag_Generator(tags)\n print(tag)\n\n print(f\"\\nTotal tags: {len(tag.tag_list)}\")\n print(f\"Unique tags: {len(tag.sort_function())}\")\n" }, { "alpha_fraction": 0.678185760974884, "alphanum_fraction": 0.6803455948829651, "avg_line_length": 24.61111068725586, "blob_id": "6c2bb7b9ecb70a616cf29a7491aad7ffc3bc7ea4", "content_id": "c089fa44e54e3f92c50af1b797efffa6de30ff1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 463, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/CLI/facebook-cli/chatter.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import fbchat \nfrom getpass import getpass\n\n\n\n\nusername = str(raw_input(\"Username: \")) \nclient = fbchat.Client(username, getpass()) \nno_of_friends = int(raw_input(\"Number of friends: \")) \n\nfor i in xrange(no_of_friends): \n\tname = str(raw_input(\"Name: \")) \n\tfriends = client.searchForUsers(name) # return a list of names \n\tfriend = friends[0] \n\tmsg = str(raw_input(\"Message: \")) \n\tsent = client.sendMessage(msg, thread_id=friend.uid) \n\tif sent: \n\t\tprint(\"done\") \n\n" }, { "alpha_fraction": 0.6898396015167236, "alphanum_fraction": 0.6951871514320374, "avg_line_length": 36.400001525878906, "blob_id": "dd09707f1ccd4140e90d0a145b2e80f9e6495127", "content_id": "bcfa90da9b86befca922a2a4986e17733676d4e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "no_license", "max_line_length": 141, "num_lines": 10, "path": "/Tools/Proxy/.py/install.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "import os\n\nprint(\" INSTALL...\")\n\nos.system(\"sudo sh -c 'echo \"deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main\" > /etc/apt/sources.list.d/pgdg.list'\")\nos.system(\"wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add\")\nos.system(\"sudo apt-get update\")\nos.system(\"sudo apt-get -y install postgresql\")\n\nprint(\" DONE \")\n" }, { "alpha_fraction": 0.5936883687973022, "alphanum_fraction": 0.6074950695037842, "avg_line_length": 18.701297760009766, "blob_id": "64d4e6441e56808b816d351e22b36bbc351d1812", "content_id": "54d78edf151361a7456e36dd293db66f56e83089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1521, "license_type": "no_license", "max_line_length": 89, "num_lines": 77, "path": "/CLI/wifi-scan-cli/main.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\n# howto use: sudo python3 main.py [YOUR-WIFI-INTERFACE e.g wlan0]\n\nimport os\nimport sys\nimport pandas\nimport datetime\nimport pyfiglet\nimport time\n\nfrom scapy.all import *\nfrom threading import Thread\n\nresult = pyfiglet.figlet_format(\"WiFi Scan Cli\")\n\nprint(result)\nprint(\"\\n\")\nprint(\"-----------------------------------------\")\nprint(\"\\n\")\n\nnetworks = pandas.DataFrame(columns=[\"BSSID\", \"SSID\", \"dBm_Signal\", \"Channel\", \"Crypto\"])\nnetworks.set_index(\"BSSID\", inplace=True)\n\ndef callback(packet):\n if packet.haslayer(Dot11Beacon):\n\n bssid = packet[Dot11].addr2\n ssid = packet[Dot11Elt].info.decode()\n try:\n dbm_signal = packet.dBm_AntSignal\n except:\n dbm_signal = \"N/A\"\n\n\n stats = packet[Dot11Beacon].network_stats()\n\n channel = stats.get(\"channel\")\n crypto = stats.get(\"crypto\")\n networks.loc[bssid] = (ssid, dbm_signal, channel, crypto)\n\n\n\n\ndef print_all():\n while True:\n os.system(\"clear\")\n print(networks)\n time.sleep(0.7)\n\n\ndef change_channel():\n ch = 1\n while True:\n os.system(f\"iwconfig {interface} channel {ch}\")\n ch = ch % 14 + 1\n time.sleep(0.7)\n\n\n\nif __name__ == \"__main__\":\n\n\n interface = sys.argv[1]\n printer = Thread(target=print_all)\n printer.daemon = True\n printer.start()\n\n\n\n channel_changer = Thread(target=change_channel)\n channel_changer.daemon = True\n channel_changer.start()\n\n\n sniff(prn=callback, iface=interface)\n\n\n\n\n" }, { "alpha_fraction": 0.6404494643211365, "alphanum_fraction": 0.6516854166984558, "avg_line_length": 16.799999237060547, "blob_id": "578479adb372bedabca3db513d178ac84ab64999", "content_id": "58cb4a41446d4bcc0fde667645e09243a0a8cc5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 35, "num_lines": 10, "path": "/Tools/Proxy/10random.py", "repo_name": "odify/PORT-OF-PYTHON", "src_encoding": "UTF-8", "text": "from scraper import Scraper \n\n\nif __name__ == '__main__':\nscraper = Scraper() \nproxies = scraper.scrape(size=10) \n\nwhile proxies.qsize:\nproxy = proxies.get()\nprint(proxy)\n" } ]
65
kimichen123/learngit
https://github.com/kimichen123/learngit
685b330c36a734f79a445f6252573fb1ed0d8ce1
c80954d1be51c4801197d6d6e4965f7f8ded56e9
c9d5270cd783b196c409a427877e0dd866021b4e
refs/heads/master
2020-05-19T20:54:33.444600
2015-09-04T07:08:30
2015-09-04T07:08:30
41,894,673
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8142076730728149, "alphanum_fraction": 0.8142076730728149, "avg_line_length": 25.14285659790039, "blob_id": "b37c946ce186b8b7df5389ca36d7215cceb5c119", "content_id": "268f821dfa139a516276a1c942d50d518145168f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 183, "license_type": "no_license", "max_line_length": 43, "num_lines": 7, "path": "/readme.txt", "repo_name": "kimichen123/learngit", "src_encoding": "UTF-8", "text": "git is a distributed version control system\ngit has an mutable index called stage\ngit tracks changes of files\ncreate a new branch is quick and simple\nadd merge\nbug fixedss:\nfixed bug\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 6.5, "blob_id": "c1a62c6a5cb7d922f3b58dde9ba0df6eaab9d5fc", "content_id": "842314560e0b5baf6341a4d25a3023a279ec02eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15, "license_type": "no_license", "max_line_length": 7, "num_lines": 2, "path": "/hello.py", "repo_name": "kimichen123/learngit", "src_encoding": "UTF-8", "text": "he:llo2\nhi all\n" } ]
2
larry1994/Kaggle-Bag-of-Words-Meets-Bags-of-Popcorn
https://github.com/larry1994/Kaggle-Bag-of-Words-Meets-Bags-of-Popcorn
0f44c3d76db295a007aec2ef1f43fb4b766db833
ba022ee844b029734bc0747fe6c7a4c55b1d3c1e
e54801ce569143f4dff0c36e104b117dc51f531f
refs/heads/master
2016-09-21T00:29:11.004589
2016-09-04T04:28:06
2016-09-04T04:28:06
67,275,475
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8118811845779419, "alphanum_fraction": 0.8267326951026917, "avg_line_length": 27.85714340209961, "blob_id": "1f594ba0ab708b7b449eb15f84995da7727dc7e0", "content_id": "ff95629227542fb666931a117000ee3205742035", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 370, "license_type": "no_license", "max_line_length": 69, "num_lines": 7, "path": "/README.md", "repo_name": "larry1994/Kaggle-Bag-of-Words-Meets-Bags-of-Popcorn", "src_encoding": "UTF-8", "text": "# Kaggle-Bag-of-Words-Meets-Bags-of-Popcorn\n\n这是kaggle上的一道题目,网址:https://www.kaggle.com/c/word2vec-nlp-tutorial/data\n\n提供的训练集train.csv里有电影的编号,用户的评论,还有用1和0代表用户对电影的喜欢或不喜欢。\n\n本程序用的是朴素贝叶斯法,用训练集训练模型,接着对测试集进行预测。\n" }, { "alpha_fraction": 0.674210250377655, "alphanum_fraction": 0.6845827698707581, "avg_line_length": 22.285715103149414, "blob_id": "8f62d02462aed73cbd7db02fae7c5a0050a966c5", "content_id": "4eedf299aa98688aa0886c264777306c3a49f1a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2297, "license_type": "no_license", "max_line_length": 83, "num_lines": 91, "path": "/bayes.py", "repo_name": "larry1994/Kaggle-Bag-of-Words-Meets-Bags-of-Popcorn", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n\n\nimport re\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\n\n#把评论转化为词序列\n\ndef review_to_wordlist(review):\n review_text=BeautifulSoup(review).get_text()\n review_text=re.sub('[^a-zA-Z]',' ',review_text)\n words=review_text.lower().split()\n return words\n\n\n# 导入数据\n\ntrain=pd.read_csv('/home/larry/Documents/bagword/labeledTrainData.tsv',\n header=0,delimiter='\\t',quoting=3)\ntest=pd.read_csv('/home/larry/Documents/bagword/testData.tsv',\n header=0,delimiter='\\t',quoting=3)\n\n\n\n\ny_train=train['sentiment']\ntrain_data=[]\nfor i in range(0,len(train['review'])):\n train_data.append(' '.join(review_to_wordlist(train['review'][i])))\n\ntest_data=[]\nfor i in range(0,len(test['review'])):\n test_data.append(' '.join(review_to_wordlist(test['review'][i])))\n \n\n\n\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer as TFIV\n#初始化TFIV,去停用词,加2元语言模型\ntfv=TFIV(min_df=3, max_features=None, strip_accents='unicode', \n analyzer='word',token_pattern=r'\\w{1,}',ngram_range=(1, 2),\n use_idf=1,smooth_idf=1,sublinear_tf=1, \n stop_words = 'english')\n\n#合并训练集和测试集以进行tfidf向量化操作\nX_all=train_data+test_data\nlen_train=len(train_data)\n\ntfv.fit(X_all)\nX_all=tfv.transform(X_all)\n#恢复成训练集和测试集\nX_train=X_all[:len_train]\nX_test=X_all[len_train:]\n\n\n# 训练贝叶斯模型\n\nfrom sklearn.naive_bayes import MultinomialNB as MNB\n\nmodel_NB=MNB()\nmodel_NB.fit(X_train,y_train)\n\n\n# 20折交叉验证\n\nfrom sklearn.cross_validation import cross_val_score\nimport numpy as np\n\nscore=np.mean(cross_val_score(model_NB,X_train,y_train,cv=20,\n scoring='roc_auc'))\nprint('多项式贝叶斯分类器20折交叉验证得分:%f' %(score))\n\n#预测\nprediction=model_NB.predict(X_text)\n\n#保存\n\nsubmission_sample=pd.read_csv('/home/larry/Documents/bagword/sampleSubmission.csv')\nids=submission_sample['id']\nimport csv as csv\ndef csvSave(filename, ids, predicted):\n with open(filename, 'w') as mycsv:\n mywriter = csv.writer(mycsv)\n mywriter.writerow(['id','sentiment'])\n mywriter.writerows(zip(ids, predicted))\n\ncsvSave('/home/larry/Documents/bagword/submission.csv', ids, prediction)\n\n" } ]
2
ShwetaRamesh08/Arya_Classification_Model
https://github.com/ShwetaRamesh08/Arya_Classification_Model
df5b9c6ea45ecc39059fb6346ed26ce1e84be55d
a6b31b7a88e4cb42cb30db533c5061276f9304aa
b9d09e9482904871f31a6093ec586f899c30a19f
refs/heads/main
2023-08-15T10:38:17.168412
2021-09-30T11:06:08
2021-09-30T11:06:08
412,018,069
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5861111283302307, "alphanum_fraction": 0.5989583134651184, "avg_line_length": 34.06097412109375, "blob_id": "3656b130272730110e41bfe294a162994c8b3ba2", "content_id": "dbb15d82a9f4725bd19c993b3a6a40957c0a76ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2880, "license_type": "no_license", "max_line_length": 106, "num_lines": 82, "path": "/FirthRegression.py", "repo_name": "ShwetaRamesh08/Arya_Classification_Model", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport sys\nimport warnings\nimport math\nimport statsmodels\nimport statsmodels.api as sm\nimport numpy as np\nfrom scipy import stats\nimport pandas as pd\n\ndef firth_likelihood(beta, logit):\n return -(logit.loglike(beta) + 0.5*np.log(np.linalg.det(-logit.hessian(beta))))\n\n# Do firth regression\ndef fit_firth(y, X, start_vec=None, step_limit=1000, convergence_limit=0.0001):\n\n logit_model = sm.Logit(y, X)\n \n if start_vec is None:\n start_vec = np.zeros(X.shape[1])\n \n beta_iterations = []\n beta_iterations.append(start_vec)\n for i in range(0, step_limit):\n pi = logit_model.predict(beta_iterations[i])\n W = np.diagflat(np.multiply(pi, 1-pi))\n var_covar_mat = np.linalg.pinv(-logit_model.hessian(beta_iterations[i]))\n\n # build hat matrix\n rootW = np.sqrt(W)\n H = np.dot(np.transpose(X), np.transpose(rootW))\n H = np.matmul(var_covar_mat, H)\n H = np.matmul(np.dot(rootW, X), H)\n\n # penalised score\n U = np.matmul(np.transpose(X), y - pi + np.multiply(np.diagonal(H), 0.5 - pi))\n new_beta = beta_iterations[i] + np.matmul(var_covar_mat, U)\n\n # step halving\n j = 0\n while firth_likelihood(new_beta, logit_model) > firth_likelihood(beta_iterations[i], logit_model):\n new_beta = beta_iterations[i] + 0.5*(new_beta - beta_iterations[i])\n j = j + 1\n if (j > step_limit):\n sys.stderr.write('Firth regression failed\\n')\n return None\n\n beta_iterations.append(new_beta)\n if i > 0 and (np.linalg.norm(beta_iterations[i] - beta_iterations[i-1]) < convergence_limit):\n break\n\n return_fit = None\n if np.linalg.norm(beta_iterations[i] - beta_iterations[i-1]) >= convergence_limit:\n sys.stderr.write('Firth regression failed\\n')\n else:\n # Calculate stats\n fitll = -firth_likelihood(beta_iterations[-1], logit_model)\n intercept = beta_iterations[-1][0]\n beta = beta_iterations[-1][1:].tolist() # coefficients\n bse = np.sqrt(np.diagonal(np.linalg.pinv(-logit_model.hessian(beta_iterations[-1])))) # errors\n beta_1 = [intercept] + beta # Coefficients of the features along with the intercept\n \n # Calculate wald-p\n waldp = []\n for beta_val, bse_val in zip(beta_1, bse):\n waldp.append(round(2 * (1 - stats.norm.cdf(abs(beta_val/bse_val))),4))\n \n # Create a summary of the variables involved, their coefficients, p-value, and the std error\n data = {'Variables': X.columns.tolist(), \n 'Coeff': beta_1,\n 'Wald_p': waldp,\n 'bse': bse}\n summary = pd.DataFrame(data)\n print(summary)\n return_fit = intercept, beta, bse, fitll,summary\n\n return return_fit\n \n\n" }, { "alpha_fraction": 0.4406779706478119, "alphanum_fraction": 0.6355932354927063, "avg_line_length": 14.857142448425293, "blob_id": "cd38833ebcb0e1955b89e7c1f2334fd15c0f27c7", "content_id": "805935ba94510cffb6a2b3a6558d945809717105", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 118, "license_type": "no_license", "max_line_length": 19, "num_lines": 7, "path": "/requirements.txt", "repo_name": "ShwetaRamesh08/Arya_Classification_Model", "src_encoding": "UTF-8", "text": "matplotlib==3.2.2\r\nstatsmodels==0.12.2\r\npandas==1.0.5\r\n~umpy==1.18.5\r\nscipy==1.7.1\r\nnumpy==1.21.2\r\nscikit_learn==1.0\r\n" }, { "alpha_fraction": 0.725904107093811, "alphanum_fraction": 0.7401407361030579, "avg_line_length": 76.35443115234375, "blob_id": "8bceade7965edb2c163430a7c325dfc8ae9d290d", "content_id": "ecf7f29468ac82e9357a87ddf3d7853c0c2f53cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6119, "license_type": "no_license", "max_line_length": 374, "num_lines": 79, "path": "/README.md", "repo_name": "ShwetaRamesh08/Arya_Classification_Model", "src_encoding": "UTF-8", "text": "# Problem Statement\nBinary Classification - Do an exploratory analysis of the dataset provided, decide on feature selection, preprocessing before training a model to classify as class ‘0’ or class ‘1’.\n\n## Datasets Given : \n1.\ttraining_set.csv - To be used as training and validation set - 3910 records, 57 features, 1 output\n2.\ttest_set.csv (without Ground Truth) - 691 records, 57 features\n\n\n# Approach: \n\n1. **EDA/Data Preprocessing:**\n\n * As part of the EDA and Data Preprocessing, we first look at the datasets given to us and check if there are any additional columns that we wouldn't need for building/testing the model. We find that there's an Unnamed column in both the train as well as the test data, which just contains the row numbers. Since that doesn't add any new information, we drop the column.\n \n * We then look for missing values in both the datasets. We find that there are no missing values.\n \n * We check if the given training dataset is balanced. To do this, we do a value count of 0s and 1s in the target variable. We find that the proportion is around 60-40, hence the dataset seems to be balanced.\n \n * We check the distribution of each feature using histograms. We find that the distribution of each feature is heavily skewed. We try to transform the features to Normality by using the **YeoJohnson transformation**. Since a number of observations are 0, Box-Cox transformation fails to work.\n \n * We also check the class-wise distribution of the features to check if any pattern is being observed. Post that, we create a correlation matrix to see if the features are correlated to each other. We find that there is some correlation between the variables. To make sure that this doesn't affect our model, we perform feature selection.\n \n \n2. **Feature Selection:**\n \n * We check for multicollinearity using the Variance Inflation Factor (VIF). A feature with VIF value > 5 suggests that it can be expressed as a function of the other features, and hence doesn't provide much information on its own to the model. Hence the features with VIF > 5 are dropped one by one. \n \n * We then create a benchmark Logistic regression model consisting of all the features except the ones dropped in the previous step, to check the Wald-p values. The variables with a p-value > 0.05 are considered to be insignificant and hence are dropped. The dataset is first split into a train and validation set in the ratio 4:1.\n \n * While creating the benchmark logistic model, we find that some separation exists in the data. Thus the maximum likelihood estimate does not exist. \n \n * We then apply a penalized likelihood regression technique named the Firth Regression Technique. Since this technique does not exist in either the statsmodels or the sklearn libraries, John Lee's implementation of the same (link : https://gist.github.com/johnlees/3e06380965f367e4894ea20fbae2b90d) is used, with minor modifications.\n \n * We further drop the features with p-values > 0.05, and come up with a list of significant features that can be used to build the model.\n \n \n3. **Model building and Validation:**\n \n * We use the Firth Regression to identify the coefficients of the selected features and then use those coefficients to predict the Y values using the logistic function. \n \n * We use a default threshold of 0.5 to classify the predicted values as either 0 or 1.\n \n * We then analyse the performance of the model based on various metrics (using the confusion matrix). We consider the following \n \n * TP (True Positive): Actual value = 1, predicted value = 1\n * TN (True negative): Actual value = 0, predicted value = 0\n * FP (False Positive): Actual value = 0, predicted value = 1\n * FN (False Negative): Actual value = 1, predicted value = 0\n \n * We use the following metrics to test the performance:\n 1. Accuracy: Measures the proportion of correct predictions to the total number of predictions.\n * formula : (TP + TN)/(TP + TN + FP + FN)\n 2. Sensitivity: The ability of the model to correctly identify a positive. Also known as Recall.\n * formula : (TP)/(TP + FN)\n 3. Specificity: The ability of the model to correctly identify a negative.\n * formula : (TN)/(TN + FP)\n 4. Precision: Proportion of true positives to the total number of positives predicted\n * formula : (TP)/(TP + FP)\n 5. F1-Score: The harmonic mean of Prediction and Recall (Sensitivity). The F1-score is high when there is a balance between Precision and Recall.\n * formula : 2xPrecisionxRecall/(Precision + Recall)\n\n\n4. **Predictions on the test set:**\n\n * We first select only those features that are required for predicting the model.\n * We then transform the data to Normality using the YeoJohnson transformation. \n * We then make predictions based on the coefficients determined earlier.\n\n# Files in this project:\n Along with this readme file, this project also contains the following files:\n 1. EDA_Data_Preprocessing.ipynb : A python Notebook containing the approach and codes used for EDA and Feature Selection.\n 2. FirthRegression.py : A script for the Firth Regression Algorithm based on the code implemented by John Lee.\n 3. model_performance.ipynb : A python Notebook containing the approach and codes used for testing the model on the validation set and making predictions on the test set.\n 4. training_set.csv : The csv for the train set as provided in the problem statement.\n 5. test_set.csv: The csv for the test set as provided in the problem statement.\n 6. modified_train_set.csv : The train set generated after data preprocessing, feature selection, and the train-test split.\n 7. Validation_set.csv : The validation set generated after data preprocessing and the train-test split.\n 8. predictions.csv : The original test set, with an additional column of predicted Y.\n 9. requirements.txt : A file containing the list of libraries/dependencies along with their versions, used to run this code.\n" } ]
3
dheijmans/rsa-prime-factorization
https://github.com/dheijmans/rsa-prime-factorization
b5a1551c417d3b6f78664fd8c0316dc5bc38b52f
9b88a5621c98c2dcec84a0c5f7234462d904e965
9c4870853d2618fd0640df033081bb3507ef0549
refs/heads/main
2023-01-19T03:12:44.870621
2020-11-26T23:04:49
2020-11-26T23:04:49
315,742,475
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5030864477157593, "alphanum_fraction": 0.5061728358268738, "avg_line_length": 23.037036895751953, "blob_id": "6b9a017065ec6562a144ebd2edbdac794b029a74", "content_id": "cf2bdcb5f66970992e4e2289608eba60bc300dda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "permissive", "max_line_length": 79, "num_lines": 27, "path": "/rsa_prime_factorizer.py", "repo_name": "dheijmans/rsa-prime-factorization", "src_encoding": "UTF-8", "text": "import math\nimport time\n\ndef factorize(n):\n start = time.time()\n for p in range(2, int(math.sqrt(n))):\n if n % p == 0:\n end = time.time()\n q = int(n / p);\n elapsed = end - start\n print(\"Results: p =\", p, \"and q =\", q)\n print(\"Time elapsed:\", elapsed, \"seconds\")\n f = open(\"data.csv\", \"a\")\n f.write(str(p) + \",\" + str(q) + \",\" + str(n) + \",\" + str(elapsed) + \"\\n\")\n f.close()\n return\n\ndef main():\n print(\"Select two prime numbers p and q\")\n p = int(input(\"p: \"))\n q = int(input(\"q: \"))\n n = p * q\n print(\"n = p * q =\", n)\n print(\"The factorization of n has started...\")\n factorize(n)\n\nmain();" }, { "alpha_fraction": 0.8399999737739563, "alphanum_fraction": 0.8399999737739563, "avg_line_length": 25, "blob_id": "87549845fbbfdd3de28ab6ebe4a28b1db4ccd03b", "content_id": "e0953276fcc9b7215ec951b64abd817ea6327767", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "permissive", "max_line_length": 25, "num_lines": 1, "path": "/README.md", "repo_name": "dheijmans/rsa-prime-factorization", "src_encoding": "UTF-8", "text": "# rsa-prime-factorization" } ]
2
YeSeul-0w0/cafe-price-of-jeju
https://github.com/YeSeul-0w0/cafe-price-of-jeju
b9a4b912625685cb6c0c7f9d938161c508e6461c
43cce8cb6bb551eb120f12ad47dd86f1a7aae313
f046497024a53e89c8dcd1563c630b456d4b5519
refs/heads/master
2023-04-13T17:33:58.838793
2023-04-09T09:24:58
2023-04-09T09:24:58
258,383,813
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5720548033714294, "alphanum_fraction": 0.6139334440231323, "avg_line_length": 39.55555725097656, "blob_id": "e4b22a546a9a1786d5ba80198de506fbea09a944", "content_id": "852cd616cf44d572f864e0eac47b887edbb91c03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15087, "license_type": "no_license", "max_line_length": 128, "num_lines": 315, "path": "/README.md", "repo_name": "YeSeul-0w0/cafe-price-of-jeju", "src_encoding": "UTF-8", "text": "# 제주시 카페 음료 가격과 밀도간 상관관계 알아보기\n\n\n>제주시의 카페의 음료(아메리카노)의 가격과 가격을 결정하는데 영향을 주리라 생각되는 요소와의 상관관계를 알아본다.<br>\n> 이디야 - 스타벅스 외 여러 체인점 위치별 분석 <br>(https://github.com/corazzon/OpenDataWrangling/blob/master/store_location_by_folium.ipynb),<br>\nmatplotlib 상에서 한글 출력 (http://corazzon.github.io/matplotlib_font_setting) 을 참고함.\n\n## 0. 필요 모듈 설치\n\n\n```python\nimport numpy as np #수치계산 관련\nimport pandas as pd #데이터 관리\nimport seaborn as sns #데이터 관리2\nimport matplotlib as mpl #데이터 시각화\nimport matplotlib.pyplot as plt\nimport folium #지도 사용시 필요\n```\n\n## 1. 한글 폰트 적용\n\n\n```python\n#나눔 고딕으로 폰트 적용\nmpl.rcParams['axes.unicode_minus'] = False\nplt.rcParams[\"font.family\"] = 'Malgun Gothic'\nplt.rcParams[\"font.size\"] = 15\nplt.rcParams[\"figure.figsize\"] = (14,4)\n```\n\n## 2. 데이터 불러오기\n\n### 2.1 주변 카페 수 세기\n>haversine을 활용해 주변 250m내 카페 수를 세어 csv파일에 추가했다.(수동)\n\n### 2.2 데이터 불러오기\n\n\n```python\n#haversine.py\nfrom haversine import haversine\nimport pandas as pd\n\ndata=pd.read_csv('cafe_data.csv', encoding='cp949')\n\nfor i in data.index:\n count=-1 #셀 때 자기 자신도 포함하므로 기본값을 -1로 설정.\n for j in data.index:\n point1 = ( data.loc[i,'위도'], data.loc[i, '경도']) #기준점\n point2 = ( data.loc[j,'위도'], data.loc[j, '경도']) #비교할위치\n if haversine(point1,point2) <= 0.25: #1=1km 0.5=500m\n count = count+1\n print(count)\n```\n\n\n```python\ndata=pd.read_csv('cafe_data.csv', encoding='cp949')\nprint(data.columns)\nprint(data.head(5))\n```\n\n>데이터 설명\n>1. 업소명 : 카페 이름을 표기\n>2. 아메리카노 : 카페의 기본 메뉴인 아메리카노의 가격을 표기.\n>3. 경도, 위도 : 위치정보를 표기. 지도 출력에 쓰인다\n>4. 면적 : 카페의 면적을 표기\n>5. 동 : 동을 숫자로 표기\n >> 1 - 이도동. 2 - 삼도동, 3 - 연동, 4 - 아라동, 5 - 노형동,<br>\n >> 6 - 일도동, 7 - 용담동, 8 - 도두동, 9 - 화북동, 10 - 삼양동,<br>\n >> 11 - 애월읍, 12 - 조천읍, 13 - 한림읍, 14 - 구좌읍, 15 - 한경면,<br>\n >> 16 - 이호동, 17 - 오라동, 18 - 외도동, 19 - 봉개동\n>6. 근처 카페 - haversine.py 에서 구한 250m내의 카페 수\n>7. 동 면적 : 해당 동의 면적을 표기\n>8. 인구 : 해당 동의 인구수 표기\n>9. 동 카페 수 : 동 내 카페수 표기\n>10. 체인점 : 체인점 여부를 표기. 0 - 체인점 아님/1-체인점\n>11. 가격 : 가격 정보를 단계별로 표기.\n0부터 6까지 있으며 0은 가격 정보가 없는 카페이며 1부터는 1000원 단위로 끊었다.(1-1000원대, 2-2000원대, ... 6-6000원대)\n>12. 카페 밀도 : 해당 동의 카페 밀도를 표기\n>13. 인구 밀도 : 해당 동의 인구 밀도를 표기\n\n\n\n> * 상위 5개 데이터 출력\n![dataoutput](img/dataoutput.PNG)\n\n## 3. 데이터 시각화 및 분석\n### 3.1 그래프 상 카페 위치 출력\n\n\n```python\nsns.relplot(data=data, x=\"경도\", y=\"위도\", hue=\"동\", palette=sns.color_palette(\"colorblind\", 19))\nplt.title('위도, 경도별 카페 분포',fontsize=20)\nplt.show()\n```\n\n> * 출력결과 <br>\n![relplot](img/relplot.PNG)\n\n ### 3.2 히트맵 출력\n>* 전체 히트맵(아메리카노, 근처 카페 수, 면적, 카페밀도, 인구밀도, 동 카페 수)\n\n\n```python\nplt.subplot(2, 2, 1)\ndata_heatmap = data[[\"아메리카노\", \"근처 카페 수\", \"면적\", \"카페밀도\", \"인구밀도\", \"동 카페 수\"]].copy()\nplt.title('위도, 경도별 카페 분포 - 전체',fontsize=12)\nsns.heatmap(data_heatmap.corr(), annot=True,cmap=\"YlGnBu\",annot_kws={\"size\": 10})\n```\n\n>* 체인점인 카페를 제외한 히트맵\n\n\n```python\nplt.subplot(2, 2, 2)\ndata_heatmap1 = data_heatmap[(data[\"체인점\"]==0)].copy()\nplt.title('위도, 경도별 카페 분포 - 체인점 제외',fontsize=12)\nsns.heatmap(data_heatmap1.corr(), annot=True,cmap=\"YlGnBu\",annot_kws={\"size\": 10})\n```\n\n>* 가격정보 없는 카페를 제외한 히트맵\n\n\n```python\nplt.subplot(2, 2, 3)\ndata_heatmap2 = data_heatmap[(data['아메리카노']!=0) ].copy()\nplt.title('위도, 경도별 카페 분포 - 가격정보無 제외',fontsize=12)\nsns.heatmap(data_heatmap2.corr(), annot=True,cmap=\"YlGnBu\",annot_kws={\"size\": 10})\n```\n\n>* 체인점인 카페, 가격정보 없는 카페 둘 다 제외한 히트맵\n\n\n```python\nplt.subplot(2, 2, 4)\ndata_heatmap3 = data_heatmap1[(data['아메리카노']!=0) ].copy()\nplt.title('위도, 경도별 카페 분포 - 체인점, 가격정보無 제외',fontsize=12)\nsns.heatmap(data_heatmap3.corr(), annot=True,cmap=\"YlGnBu\",annot_kws={\"size\": 10})\nplt.show()\n```\n\n> * 히트맵 출력 결과 <br>\n![heatmap](img/heatmap.PNG)\n\n## 4. 지도 제작\n### 4.1 전체 지도\n> * 위도 경도 값 받을 list 생성 <br>\n> * marker popup 내용 설정(카페 이름 + 커피 가격)\n\n\n```python\nmap_alt=[] #위도 값이 들어갈 list\nmap_long=[] #경도 값이 들어갈 list\nfor i in range(len(data)):\n map_alt.append(data['위도'].iloc[i])\n map_long.append(data['경도'].iloc[i])\n \n# popup 창에 가격을 띄우려고 했더니 숫자형은 불가능하다고 해서 int형인 아메리카노 가격을 string으로 바꿈\n# 아메리카노 가격을 제대로 인식하지 못해 데이터 index값을 저장하는 리스트를 만들어서 casting과 동시에 index 정보도 저장함.\nstring_price=[]\nindex_list = []\nfor a in range(len(data)):\n index_list.append(a)\n temp=str(data['아메리카노'].iloc[i])\n string_price.append((temp))\n```\n\n> * 동 별 카페 분포 표시(동마다 마커의 색을 다르게 함)\n\n\n```python\nmap_dong=folium.Map(location=[data['위도'].iloc[0], data['경도'].iloc[0]], zoom_start=13)\nfor index in range(len(index_list)):\n i=index_list[index]\n if(data['동'].iloc[i]==1):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#FF0000', fill_color='#FF0000')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==2):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#F29661', fill_color='#F29661')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==3):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#980000', fill_color='#980000')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==4):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#FFBB00', fill_color='#FFBB00')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==5):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#E5D85C', fill_color='#E5D85C')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==6):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#997000', fill_color='#997000')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==7):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#1F3456', fill_color='#1F3456')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==8):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#ABF200', fill_color='#ABF200')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==9):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#86E57F', fill_color='#86E57F')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==10):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#6B9900', fill_color='#6B9900')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==11):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#00D8FF', fill_color='#00D8FF')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==12):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#6799FF', fill_color='#6799FF')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==13):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#008299', fill_color='#008299')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==14):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#0100FF', fill_color='#0100FF')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==15):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#A566FF', fill_color='#A566FF')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==16):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#D26C9F', fill_color='#D26C9F')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==17):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#FF00DD', fill_color='#FF00DD')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==18):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#F361A6', fill_color='#F361A6')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n if(data['동'].iloc[i]==19):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#990085', fill_color='#990085')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\n\nmap_dong.save('map_dong.html', encoding='utf-8')\n```\n\n> * 출력결과<br>\n![map_all](img/map_all.PNG)\n\n> * 커피 가격 표시(가격대는 1000원대~6000원대로 가격이 비쌀 수록 가격을 짙게 함. 가격 정보가 없는 것은 하얀색으로 표기)\n\n\n```python\nmap_dong_price=folium.Map(location=[data['위도'].iloc[0], data['경도'].iloc[0]], zoom_start=13)\nfor index in range(len(index_list)):\n i=index_list[index]\n if(data['가격'].iloc[i]==1):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#FFA46C', fill_color='#FFA46C')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\n if(data['가격'].iloc[i]==2):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#CF6E36', fill_color='#CF6E36')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\n if(data['가격'].iloc[i]==3):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#993800', fill_color='#993800')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\n if(data['가격'].iloc[i]==4):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#630200', fill_color='#630200')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\n if(data['가격'].iloc[i]==5):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#2D0000', fill_color='#2D0000')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\n if(data['가격'].iloc[i]==6):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#1B0000', fill_color='#1B0000')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\n if(data['가격'].iloc[i]==0):\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#FFFFFF', fill_color='#FFFFFF')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\n \nmap_dong_price.save('map_all.html', encoding='utf-8') \n```\n\n> * 출력결과<br>\n![map_price](img/map_price.PNG)\n\n> * 각 동별로 카페 커피 가격을 표시\n\n\n```python\nindex_list = []\nfor i in range(len(data)):\n if(data['동'].iloc[i]==14):\n index_list.append(i) \n map_alt.append(data['위도'].iloc[i])\n map_long.append(data['경도'].iloc[i])\n\npoint=index_list[0]\n\nfor i in range(len(data)):\n if(data['가격'].iloc[i]==1):\n folium.CircleMarker([data['위도'].iloc[i],data['경도'].iloc[i]],radius=10, color='#FFA46C', fill_color='#FFA46C')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map)\n if(data['가격'].iloc[i]==2):\n folium.CircleMarker([data['위도'].iloc[i],data['경도'].iloc[i]],radius=10, color='#CF6E36', fill_color='#CF6E36')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map)\n if(data['가격'].iloc[i]==3):\n folium.CircleMarker([data['위도'].iloc[i],data['경도'].iloc[i]],radius=10, color='#993800', fill_color='#993800')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map)\n if(data['가격'].iloc[i]==4):\n folium.CircleMarker([data['위도'].iloc[i],data['경도'].iloc[i]],radius=10, color='#630200', fill_color='#630200')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map)\n if(data['가격'].iloc[i]==5):\n folium.CircleMarker([data['위도'].iloc[i],data['경도'].iloc[i]],radius=10, color='#2D0000', fill_color='#2D0000')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map)\n if(data['가격'].iloc[i]==6):\n folium.CircleMarker([data['위도'].iloc[i],data['경도'].iloc[i]],radius=10, color='#1B0000', fill_color='#1B0000')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map)\n if(data['가격'].iloc[i]==0):\n folium.CircleMarker([data['위도'].iloc[i],data['경도'].iloc[i]],radius=10, color='#FFFFFF', fill_color='#FFFFFF')\n .add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map)\n\nmap.save('map_1.html', encoding='utf-8')\n```\n\n> * 출력결과(예시로 이도동만 출력)\n![map_ido](img/map_ido.PNG)\n" }, { "alpha_fraction": 0.602534830570221, "alphanum_fraction": 0.6405572295188904, "avg_line_length": 59.66197204589844, "blob_id": "ff64b360ad8d839dd9663821fe509585b455f120", "content_id": "55181a917a6b6852c3238ce353769bdbbb4df613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9628, "license_type": "no_license", "max_line_length": 192, "num_lines": 142, "path": "/cafe_analysis.py", "repo_name": "YeSeul-0w0/cafe-price-of-jeju", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\nimport matplotlib.font_manager as fm\r\nimport folium\r\nfrom folium import plugins\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nwarnings.filterwarnings('ignore', 'This pattern has match groups')\r\nwarnings.filterwarnings('ignore', 'The iterable function was deprecated in Matplotlib')\r\n\r\n# 데이터 로딩\r\ndata=pd.read_csv('cafe_data.csv', encoding='cp949')\r\n#print(data.columns)\r\n#print(data.head(5))\r\n\r\n# 한글 인식을 위한 작업\r\nmpl.rcParams['axes.unicode_minus'] = False\r\nplt.rcParams[\"font.family\"] = 'Malgun Gothic'\r\nplt.rcParams[\"font.size\"] = 10\r\nplt.rcParams[\"figure.figsize\"] = (14,4)\r\n\r\ndata[['위도', '경도']].describe(include=np.number)\r\ndata['위도']=data['위도'].astype(float)\r\ndata['경도']=data['경도'].astype(float)\r\n\r\n\r\n# 그래프상에서 카페 위치 출력\r\nsns.relplot(data=data, x=\"경도\", y=\"위도\", hue=\"동\", palette=sns.color_palette(\"colorblind\", 19))\r\nplt.title('위도, 경도별 카페 분포',fontsize=20)\r\nplt.show()\r\n\r\n\r\n# 위도 경도 정보 저장\r\nmap_alt=[] #위도 값가 들어갈 list\r\nmap_long=[] #경도 값이 들어갈 list\r\nfor i in range(len(data)):\r\n map_alt.append(data['위도'].iloc[i])\r\n map_long.append(data['경도'].iloc[i])\r\n\r\n\r\n# popup 창에 가격을 띄우려고 했더니 숫자형은 불가능하다고 해서 int형인 아메리카노 가격을 string으로 바꿈\r\n# 아메리카노 가격을 제대로 인식하지 못해 데이터 index값을 저장하는 리스트를 만들어서 casting과 동시에 index 정보도 저장함.\r\nstring_price=[]\r\nindex_list = []\r\nfor a in range(len(data)):\r\n index_list.append(a)\r\n temp=str(data['아메리카노'].iloc[i])\r\n string_price.append((temp))\r\n\r\n\r\n# 동 별로 다른 색으로 카페 위치 지도에 표시\r\nmap_dong=folium.Map(location=[data['위도'].iloc[0], data['경도'].iloc[0]], zoom_start=13)\r\nfor index in range(len(index_list)):\r\n i=index_list[index]\r\n if(data['동'].iloc[i]==1):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#FF0000', fill_color='#FF0000').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==2):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#F29661', fill_color='#F29661').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==3):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#980000', fill_color='#980000').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==4):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#FFBB00', fill_color='#FFBB00').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==5):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#E5D85C', fill_color='#E5D85C').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==6):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#997000', fill_color='#997000').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==7):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#1F3456', fill_color='#1F3456').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==8):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#ABF200', fill_color='#ABF200').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==9):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#86E57F', fill_color='#86E57F').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==10):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#6B9900', fill_color='#6B9900').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==11):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#00D8FF', fill_color='#00D8FF').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==12):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#6799FF', fill_color='#6799FF').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==13):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#008299', fill_color='#008299').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==14):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#0100FF', fill_color='#0100FF').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==15):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#A566FF', fill_color='#A566FF').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==16):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#D26C9F', fill_color='#D26C9F').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==17):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#FF00DD', fill_color='#FF00DD').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==18):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#F361A6', fill_color='#F361A6').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n if(data['동'].iloc[i]==19):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7,popup=i, color='#990085', fill_color='#990085').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong)\r\n\r\nmap_dong.save('map_dong.html', encoding='utf-8')\r\n\r\n\r\n# 아메리카노 가격에 따른 지도 위에 마커 표시\r\n# 가격이 비쌀 수록 진한 색으로 표기\r\nmap_dong_price=folium.Map(location=[data['위도'].iloc[0], data['경도'].iloc[0]], zoom_start=13)\r\nfor index in range(len(index_list)):\r\n i=index_list[index]\r\n if(data['가격'].iloc[i]==1):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#FFA46C', fill_color='#FFA46C').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\r\n if(data['가격'].iloc[i]==2):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#CF6E36', fill_color='#CF6E36').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\r\n if(data['가격'].iloc[i]==3):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#993800', fill_color='#993800').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\r\n if(data['가격'].iloc[i]==4):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#630200', fill_color='#630200').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\r\n if(data['가격'].iloc[i]==5):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#2D0000', fill_color='#2D0000').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\r\n if(data['가격'].iloc[i]==6):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#1B0000', fill_color='#1B0000').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\r\n if(data['가격'].iloc[i]==0):\r\n folium.CircleMarker([map_alt[i],map_long[i]],radius=7, color='#FFFFFF', fill_color='#FFFFFF').add_child(folium.Popup(data['업소명'].iloc[i]+\"\\n\"+string_price[i])).add_to(map_dong_price)\r\nmap_dong_price.save('map_all.html', encoding='utf-8') \r\n\r\n\r\n# 히트맵 출력\r\nplt.subplot(2, 2, 1)\r\ndata_heatmap = data[[\"아메리카노\", \"근처 카페 수\", \"면적\", \"카페밀도\", \"인구밀도\", \"동 카페 수\"]].copy()\r\nplt.title('위도, 경도별 카페 분포 - 전체',fontsize=12)\r\nsns.heatmap(data_heatmap.corr(), annot=True,cmap=\"YlGnBu\",annot_kws={\"size\": 10})\r\n\r\nplt.subplot(2, 2, 2)\r\ndata_heatmap1 = data_heatmap[(data[\"체인점\"]==0)].copy()\r\nplt.title('위도, 경도별 카페 분포 - 체인점 제외',fontsize=12)\r\nsns.heatmap(data_heatmap1.corr(), annot=True,cmap=\"YlGnBu\",annot_kws={\"size\": 10})\r\n\r\nplt.subplot(2, 2, 3)\r\ndata_heatmap2 = data_heatmap[(data['아메리카노']!=0) ].copy()\r\nplt.title('위도, 경도별 카페 분포 - 가격정보無 제외',fontsize=12)\r\nsns.heatmap(data_heatmap2.corr(), annot=True,cmap=\"YlGnBu\",annot_kws={\"size\": 10})\r\n\r\nplt.subplot(2, 2, 4)\r\ndata_heatmap3 = data_heatmap1[(data['아메리카노']!=0) ].copy()\r\nplt.title('위도, 경도별 카페 분포 - 체인점, 가격정보無 제외',fontsize=12)\r\nsns.heatmap(data_heatmap3.corr(), annot=True,cmap=\"YlGnBu\",annot_kws={\"size\": 10})\r\nplt.show()\r\n\r\n" }, { "alpha_fraction": 0.5313901305198669, "alphanum_fraction": 0.5762332081794739, "avg_line_length": 30, "blob_id": "62393a3218ffc268f265c220ce6af5f196c948d2", "content_id": "1e1a54dc42b6d4c2071c53283154e4dc510e782f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "no_license", "max_line_length": 72, "num_lines": 14, "path": "/haversiine.py", "repo_name": "YeSeul-0w0/cafe-price-of-jeju", "src_encoding": "UTF-8", "text": "#주변 카페 수 세기\r\nfrom haversine import haversine\r\nimport pandas as pd\r\n\r\ndata=pd.read_csv('cafe_data.csv', encoding='cp949')\r\n\r\nfor i in data.index:\r\n count=-1 #본인도 같이 세므로 -1\r\n for j in data.index:\r\n point1 = ( data.loc[i,'위도'], data.loc[i, '경도']) #기준점\r\n point2 = ( data.loc[j,'위도'], data.loc[j, '경도']) #비교할위치\r\n if haversine(point1,point2) <= 0.25: #거리 구해서 비교 / 1=1km 0.5=500m\r\n count = count+1\r\n print(count)" } ]
3
jin-fhg/inventory
https://github.com/jin-fhg/inventory
f72c0ef539f4c8b258ff2987db678d7fbf8c7550
8d117937d42349ec59606ef134c72823e2e5b4d2
f7951f1f2f72aa5a4189aad54c2a5009aa14b312
refs/heads/master
2023-02-13T05:41:47.141427
2021-01-05T19:24:49
2021-01-05T19:24:49
299,177,024
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.581615149974823, "alphanum_fraction": 0.6099656224250793, "avg_line_length": 40.57143020629883, "blob_id": "2a6e3dab02a18964ac6d5a8a84f25c44f5c78a13", "content_id": "006293c472ac619d9d91c71afa7753eec360e8dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 145, "num_lines": 28, "path": "/inventory/webInventory/migrations/0002_audittrail.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-09-18 02:14\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AuditTrail',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('action', models.CharField(blank=True, max_length=50, null=True)),\n ('what', models.CharField(blank=True, max_length=100, null=True)),\n ('how_many', models.CharField(blank=True, max_length=100, null=True)),\n ('action_from', models.CharField(blank=True, max_length=100, null=True)),\n ('action_to', models.CharField(blank=True, max_length=100, null=True)),\n ('created_on', models.DateTimeField(default=datetime.datetime.now)),\n ('profile', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='webInventory.Profile')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5514168739318848, "alphanum_fraction": 0.5538792014122009, "avg_line_length": 39.29133987426758, "blob_id": "66510debff722283ab2f3422cc637ef3586319d2", "content_id": "4fafaf0ed4b9f6ddde0e792d832668da5ee724ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25585, "license_type": "no_license", "max_line_length": 125, "num_lines": 635, "path": "/inventory/webInventory/views.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect, HttpResponse\n\nfrom django.http import JsonResponse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nimport logging\nfrom django.contrib.auth.models import User, Group\nfrom django.contrib import messages\nfrom .models import Profile, ItemFolder, Item, Tag, ItemTag, AuditTrail, Role, UserRole, companyInformation, UserCompany\nfrom . import common\nfrom datetime import datetime\nimport json\n\n#Email User Activation\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.template.loader import render_to_string\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom .tokens import account_activation_token\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.core.mail import EmailMessage\n\n# Create your views here.\n\nlogger = logging.getLogger(__name__)\n\n\n\ndef findLength(number):\n newNum = len(str(number))\n if newNum == 1:\n pass\n return newNum\n\ndef login_view(request):\n x = findLength(123)\n print(x)\n if request.method == 'POST':\n user = authenticate(request, username=request.POST['uname'], password=request.POST['pword'])\n if user is not None:\n login(request, user)\n AuditTrail.objects.create(action='Login', profile_name = request.user.profile.name)\n if not 'remember' in request.POST:\n request.session.set_expiry(0)\n return redirect('home')\n else:\n messages.error(request, f'Login Failed. Incorrect Username or Password.')\n return redirect('login')\n else:\n messages.error(request, f'Please Login')\n return render(request, 'webInventory/login.html')\n\ndef logout_view(request):\n if not request.user.is_anonymous:\n if request.method == 'POST':\n user = authenticate(request, username=request.POST['uname'], password=request.POST['pword'])\n if user is not None:\n login(request, user)\n AuditTrail.objects.create(action='Login', user_id=request.user.id, profile_name=request.user.profile.name)\n if not 'remember' in request.POST:\n request.session.set_expiry(0)\n return redirect('home')\n else:\n messages.error(request, f'Login Failed. Incorrect Username or Password.')\n return redirect('login')\n\n else:\n AuditTrail.objects.create(action='Logout', user_id=request.user.id, profile_name=request.user.profile.name)\n messages.success(request, f'You are now logged out.')\n logout(request)\n return render(request, 'webInventory/login.html')\n\n\n@login_required\ndef index(request):\n companyDetails = common.getCompany(request)\n barcodeOptions = common.getCompanyOptions()\n all_foldersCount = len(ItemFolder.objects.all())\n latest_audits = AuditTrail.objects.all().order_by('-created_on')[0:4]\n logger.error(latest_audits)\n if request.method == 'POST':\n logger.error(request.POST)\n\n context = {\n 'barcodeOptions': barcodeOptions,\n 'companyDetails': companyDetails,\n 'countFolder' : all_foldersCount,\n 'countItemFolders' : common.countFolderItemsAll(),\n 'audits': latest_audits,\n }\n\n logger.error(common.AllFolderAndItems(2))\n\n return render(request, 'webInventory/index.html', context)\n\n\n@login_required\ndef inventoryList(request):\n all_folders = ItemFolder.objects.all()\n companyDetails = common.getCompany(request)\n barcodeOptions = common.getCompanyOptions()\n\n #New Technique - Make the queryset a normal list so that you can update it\n folder_list = [{'id': x.id, 'name': x.name, 'description': x.description, 'created': x.created_on} for x in all_folders]\n\n #Add the number of items in the folder_list\n for folder in folder_list:\n all_itemsCount = len(Item.objects.filter(itemFolder_id=folder['id']))\n folder['itemCount'] = all_itemsCount\n\n if request.method == 'POST':\n if 'btnSave' in request.POST:\n newFolder = ItemFolder.objects.create(name=request.POST['newFolder'],\n description=request.POST['folderDescription'],\n created_by_id= request.user.id,\n created_by_name= request.user.profile.name)\n\n AuditTrail.objects.create(action='Added', what='Item Storage:' + newFolder.name,\n profile_name=request.user.profile.name,\n user_id = request.user.id)\n\n messages.success(request, f'Folder Added Successfully')\n return redirect('inventoryList')\n elif 'saveDeleteOption' in request.POST:\n folder = ItemFolder.objects.get(id = request.POST['deleteOptionId'])\n\n AuditTrail.objects.create(action='Deleted', what='Item Storage:' + folder.name,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n folder.delete()\n messages.success(request, f'Folder Deleted Successfully')\n return redirect('inventoryList')\n else:\n logger.error(\"No POST\")\n context = {\n 'barcodeOptions': barcodeOptions,\n 'companyDetails': companyDetails,\n 'folders' : folder_list,\n }\n\n return render(request, 'webInventory/inventoryList.html', context)\n\n\n@login_required\ndef itemList(request, pk):\n provided_bars = ['code39', 'code128', 'ean', 'ean13', 'ean8', 'gs1', 'gtin',\n 'isbn', 'isbn10', 'isbn13', 'issn', 'jan', 'pzn', 'upc', 'upca']\n folder = ItemFolder.objects.get(id=pk)\n companyDetails = common.getCompany(request)\n barcodeOptions = common.getCompanyOptions()\n itemList = Item.objects.filter(itemFolder_id=pk)\n\n if request.method == 'POST':\n if 'btnAddItem' in request.POST:\n logger.error(request.POST['itemTags'])\n tags = common.Convert(request.POST['itemTags']) # Converted to Array using the custom Method\n print(tags,'Converted')\n\n\n item = Item.objects.create(itemFolder_id = pk, name = request.POST['name'], price = request.POST['price'],\n quantity = request.POST['quantity'], minQuantity= request.POST['min-quantity'],\n description = request.POST['description'])\n newBar = common.create_barcode(item, request)\n item.barcode = newBar\n item.save()\n AuditTrail.objects.create(action='Added', what=item.name + ' to Folder ' + folder.name,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n messages.success(request, f'Item Added Successfully')\n # Add Tag Relationship\n for tag in tags:\n try:\n relationTag = Tag.objects.get(name=tag)\n ItemTag.objects.create(item_id= item.id, tag_id= relationTag.id)\n except(Tag.DoesNotExist):\n print('This object ' + tag + ' Does not Exist')\n\n return redirect('itemList', pk)\n\n elif 'saveDeleteOption' in request.POST:\n item = Item.objects.get(id=request.POST['deleteOptionId'])\n item.delete()\n messages.success(request, f'Item Successfully Deleted')\n return redirect('itemList', pk)\n\n #ean = common.create_barcode(1)\n #logger.error(ean)\n context = {\n 'barcodeOptions': barcodeOptions,\n 'companyDetails': companyDetails,\n 'folder': folder,\n 'itemList': itemList,\n 'bars': provided_bars\n }\n\n return render(request, 'webInventory/itemList.html', context)\n\n@login_required\ndef itemDetails(request, pk):\n item = Item.objects.get(id=pk)\n companyDetails = common.getCompany(request)\n barcodeOptions = common.getCompanyOptions()\n # Get Tags from Items Related to the Tags\n itemTags = ItemTag.objects.filter(item_id=pk)\n x = []\n if itemTags:\n for tag in itemTags:\n obj = Tag.objects.get(id=tag.tag_id)\n x.append(obj.name)\n context = {\n 'barcodeOptions': barcodeOptions,\n 'companyDetails': companyDetails,\n 'item': item,\n 'itemTags': x\n }\n if request.method == 'POST':\n logger.error(request.POST)\n if 'itemTags' in request.POST:\n tags = common.Convert(request.POST['itemTags'])\n logger.error(tags)\n itemTags.delete()\n\n if tags:\n for tag in tags:\n try:\n relationTag = Tag.objects.get(name=tag)\n ItemTag.objects.create(item_id=item.id, tag_id=relationTag.id)\n except(Tag.DoesNotExist):\n print('This object ' + tag + ' Does not Exist')\n\n return redirect('item-details', pk)\n #tags = tags.replace(\"'\\'\", '')\n #context['tags'] = tags\n #logger.error(context)\n return render(request, 'webInventory/itemDetails.html', context)\n\n\ndef tagList(request):\n tags = Tag.objects.all()\n companyDetails = common.getCompany(request)\n barcodeOptions = common.getCompanyOptions()\n if request.method == 'POST':\n if 'addTag' in request.POST:\n tag_name = request.POST['tagName']\n if tag_name:\n if not Tag.objects.filter(name=tag_name).exists():\n newTag = Tag.objects.create(name=tag_name, created_by_id=request.user.id,\n created_by_name=request.user.profile.name)\n\n AuditTrail.objects.create(action='Added', what='Tag:' + newTag.name,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n\n messages.success(request, f'Tag Added Successfully')\n return redirect('tagList')\n\n else:\n messages.error(request, f'Tag already exist')\n return redirect('tagList')\n elif 'deleteOptionId' and 'saveDeleteOption' in request.POST:\n tag = Tag.objects.get(id=request.POST['deleteOptionId'])\n\n AuditTrail.objects.create(action='Deleted', what='Tag:' + tag.name,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n\n tag.delete()\n messages.success(request, f'Tag has been Deleted')\n return redirect('tagList')\n\n context = {\n 'barcodeOptions': barcodeOptions,\n 'companyDetails': companyDetails,\n 'tags': tags,\n }\n return render(request, 'webInventory/tagList.html', context)\n\n@login_required\ndef manageUsers(request):\n companyDetails = common.getCompany(request)\n barcodeOptions = common.getCompanyOptions()\n if request.method == 'POST':\n logger.error(request.POST)\n if 'addUser' in request.POST:\n if not User.objects.filter(username=request.POST['UserName']).exists():\n if not User.objects.filter(email=request.POST['email']).exists():\n if 'setPass' in request.POST:\n if not len(request.POST['password']) < 8:\n if request.POST['password'] == request.POST['password2']:\n newUser = User.objects.create_user(request.POST['UserName'],\n request.POST['email'], request.POST['password'])\n newUser.is_staff = False\n newUser.is_superuser = False\n newUser.is_active = True\n newUser.save()\n\n messages.success(request, f'New User Named: ' + newUser.username + ' is created.')\n else:\n messages.error(request, f'Password is too short. It should be at least 8 characters')\n return redirect('manageUsers')\n\n else:\n logger.error(\"Sending Email\")\n newUser = User.objects.create_user(request.POST['UserName'],\n request.POST['email'], 'Password100')\n newUser.is_staff = False\n newUser.is_superuser = False\n newUser.is_active = False\n newUser.save()\n current_site = get_current_site(request)\n mail_subject = 'Activate your Account.'\n message = render_to_string('webInventory/acc_active_email.html', {\n 'user': newUser,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(newUser.id)),\n 'token': account_activation_token.make_token(newUser),\n })\n email = EmailMessage(\n mail_subject, message, '[email protected]', [newUser.email],\n )\n email.send()\n\n messages.success(request, f'An Email has been sent to ' + newUser.email + ' to activate his Account')\n\n newProfile = Profile.objects.create(name=request.POST['ProfName'],\n address=request.POST['address'],\n phone=request.POST['phone'],\n email=request.POST['email'],\n user_id=newUser.id)\n\n AuditTrail.objects.create(action='Created', what='User',\n action_from='UserName:' + newUser.username +\n ' Profile:' + newProfile.name,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n\n if 'isAdmin' in request.POST:\n #role = UserRole.objects.create(role_id=1, user_id=newUser.id)\n newProfile.role = 1\n newProfile.save()\n else:\n #role = UserRole.objects.create(role_id=2, user_id=newUser.id)\n newProfile.role = 2\n newProfile.save()\n return redirect('manageUsers')\n else:\n messages.error(request, f'User with email ' + request.POST['email'] + ' already exists')\n return redirect('manageUsers')\n else:\n messages.error(request, f'User '+ request.POST['UserName'] +' already exists')\n return redirect('manageUsers')\n elif 'saveDeleteOption' in request.POST:\n try:\n user = User.objects.get(id=request.POST['deleteOptionId'])\n user.delete()\n messages.success(request, f'User Deleted Successfully')\n return redirect('manageUsers')\n except(User.DoesNotExist):\n messages.error(request, f'User No Longer Exists')\n elif 'saveUpdate' in request.POST:\n try:\n user = User.objects.get(id=request.POST['db_id'])\n profile = Profile.objects.get(user_id=request.POST['db_id'])\n profile.name = request.POST['profileName']\n profile.address = request.POST['profileAddress']\n profile.phone = request.POST['profilePhone']\n profile.email = request.POST['profileEmail']\n user.email = request.POST['profileEmail']\n if 'isAdmin' in request.POST:\n profile.role = 1\n else:\n profile.role = 2\n profile.save()\n user.save()\n messages.success(request, f'User Profile Updated Successfully')\n return redirect('manageUsers')\n except(Profile.DoesNotExist):\n messages.error(request, f'Error Occured: User No Longer Exists')\n\n\n users = User.objects.all()\n profiles_temp = []\n profiles = []\n for user in users:\n profiles_temp.append(user.id)\n profiles_temp.append(user.username)\n profiles_temp.append(Profile.objects.get(user_id=user.id).name)\n profiles_temp.append(user.is_active)\n profiles_temp.append(Profile.objects.get(user_id=user.id).role)\n profiles_temp.append(Profile.objects.get(user_id=user.id).created_on)\n profiles.append(profiles_temp)\n profiles_temp = []\n\n logger.error(profiles)\n\n\n\n context = {\n 'barcodeOptions': barcodeOptions,\n 'companyDetails': companyDetails,\n 'users': profiles,\n }\n return render(request, 'webInventory/manageUsers.html', context)\n\n\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user)\n # return redirect('home')\n return redirect('password-setup')\n else:\n return HttpResponse('Activation link is invalid!')\n\n@login_required\ndef passwordSetup(request):\n if request.method == 'POST':\n if request.POST['pword'] == request.POST['pword2']:\n request.user.set_password(request.POST['pword2'])\n request.user.save()\n messages.success(request, f'Password Setup Successful. Please Login.')\n return redirect('home')\n else:\n messages.error(request, f'Password does not match. Please try again.')\n\n return render(request, 'webInventory/passwordSetup.html')\n\n@login_required\ndef auditTrail(request):\n companyDetails = common.getCompany(request)\n barcodeOptions = common.getCompanyOptions()\n\n if request.method == 'POST':\n audits = AuditTrail.objects.filter(created_on__range=[str(request.POST['dateFrom']) + ' 00:00:00',\n str(request.POST['dateTo']) + ' 23:59:59']).order_by('-id')\n logger.error(audits)\n else:\n audits = AuditTrail.objects.all().order_by('-id')\n\n context = {\n 'barcodeOptions': barcodeOptions,\n 'companyDetails': companyDetails,\n 'audits': audits,\n }\n return render(request, 'webInventory/auditTrail.html', context)\n\n#Ajaxes\n@login_required\ndef updateFolder(request):\n if request.method == 'POST':\n if request.is_ajax and request.user.is_authenticated:\n folder = ItemFolder.objects.get(id=request.POST['id'])\n if request.POST.get('value'):\n folder_from = folder.name\n folder.name = request.POST['value']\n\n AuditTrail.objects.create(action='Updated', what= 'Folder Name',\n action_from = folder_from,\n action_to = folder.name,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n folder.save()\n logger.error(\"Update Successful\")\n return HttpResponse(\"Update is Successful\")\n else:\n return HttpResponse(\"Error: No New Value Detected\")\n return HttpResponse(None)\n\n@login_required\ndef updateFolderDesc(request, pk):\n if request.method == 'POST':\n if request.is_ajax and request.user.is_authenticated:\n folder = ItemFolder.objects.get(id=request.POST['id'])\n whatToupdate = request.POST['update']\n if whatToupdate == 'name':\n if request.POST.get('value'):\n folder_from = folder.name\n folder.name = request.POST['value']\n\n AuditTrail.objects.create(action='Updated', what= 'Folder Name',\n action_from = folder_from,\n action_to = folder.name,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n\n folder.save()\n logger.error(\"Update Successful\")\n return HttpResponse(\"Update is Successful\")\n else:\n return HttpResponse(\"Update Not Successful\")\n elif whatToupdate == 'description':\n folder_from = folder.description\n folder.description = request.POST['value']\n\n AuditTrail.objects.create(action='Updated', what='Folder Description ',\n action_from=folder_from,\n action_to = folder.description,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n\n folder.save()\n logger.error(\"Update Successful\")\n return HttpResponse(\"Update is Successful\")\n return HttpResponse(None)\n\n\n\n@login_required\ndef updateTagName(request):\n if request.method == 'POST' and request.is_ajax:\n if request.POST['update'] == 'tagNameUpdate' and request.POST['value']:\n tag = Tag.objects.get(id = request.POST['id'])\n tag_from = tag.name\n tag.name = request.POST['value']\n\n AuditTrail.objects.create(action='Updated', what='Tag Name ',\n action_from=tag_from,\n action_to= tag.name,\n profile_name=request.user.profile.name,\n user_id=request.user.id)\n\n tag.save()\n logger.error(\"Success\")\n return HttpResponse(\"Success\")\n return HttpResponse(None)\n\n\n@login_required\ndef loadChart(request, *args, **kwargs):\n data = common.AllFolderAndItems(2)\n return JsonResponse(data)\n\n@login_required\ndef profileUpdate(request):\n user = User.objects.get(id=request.GET.get('id'))\n logger.error(user.profile.name)\n\n data = {\n 'uname': user.username,\n 'name': user.profile.name,\n 'address': user.profile.address,\n 'phone': user.profile.phone,\n 'email': user.profile.email,\n 'role': user.profile.role,\n }\n return JsonResponse(data)\n\n#This is the method when the admin tries to reset another user's password\n@login_required\ndef resetPass(request):\n user = User.objects.get(id=request.GET.get('id'))\n logger.error(user.profile.name)\n current_site = get_current_site(request)\n mail_subject = 'Password Reset'\n message = render_to_string('webInventory/passreset-admin.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.id)),\n 'token': account_activation_token.make_token(user),\n })\n email = EmailMessage(\n mail_subject, message, '[email protected]', [user.email],\n )\n email.send()\n\n data = {\n 'email': user.profile.email\n }\n return JsonResponse(data)\n\n@login_required\ndef deactivateUser(request):\n if request.method == 'POST':\n user = User.objects.get(id=request.POST['id'])\n if user.is_active:\n user.is_active = False\n user.save()\n status = \"User is now Inactive\"\n else:\n user.is_active = True\n user.save()\n status = \"User is now Active\"\n data = {\n 'status': status\n }\n return JsonResponse(data)\n\n@login_required\ndef getTags(request, pk):\n all_tags = Tag.objects.all()\n tags = []\n for item in all_tags:\n tags.append(item.name)\n data = {\n 'tags': tags\n }\n return JsonResponse(data)\n\n\n@login_required\ndef updateItem(request, pk):\n if request.method == 'POST' and request.is_ajax:\n item = Item.objects.get(id=pk)\n if request.POST['updateWhat'] == 'itemName':\n\n item.name = request.POST['value']\n\n\n elif request.POST['updateWhat'] == 'itemDesc':\n\n item.description = request.POST['value']\n\n elif request.POST['updateWhat'] == 'itemPrice':\n\n item.price = request.POST['value']\n\n elif request.POST['updateWhat'] == 'itemQuantity':\n\n item.quantity = request.POST['value']\n\n elif request.POST['updateWhat'] == 'itemMinQuantity':\n\n item.minQuantity = request.POST['value']\n\n else:\n print('No Change')\n return None\n\n item.save()\n return JsonResponse({'status': 200})\n" }, { "alpha_fraction": 0.5123152732849121, "alphanum_fraction": 0.5911329984664917, "avg_line_length": 21.55555534362793, "blob_id": "b0e69be17d865d986c35f16a26ff8596452cf93d", "content_id": "1e1a96361a1f489e5f508680fa395a898ff9ad3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 72, "num_lines": 18, "path": "/inventory/webInventory/migrations/0010_item_sku.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2020-09-28 18:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0009_auto_20200920_0924'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='item',\n name='sku',\n field=models.CharField(blank=True, max_length=7, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.4861259460449219, "alphanum_fraction": 0.48772677779197693, "avg_line_length": 25.77142906188965, "blob_id": "164a77233b81c6ff35bc07be51a86c3ee9a903b4", "content_id": "a88d551fb4f231c8b242ce471865041978d7d44f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1874, "license_type": "no_license", "max_line_length": 85, "num_lines": 70, "path": "/inventory/webInventory/static/webInventory/js/itemDetails.js", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "$(function(){\n console.log('Item Details')\n /*Highhlight the current page in NavBar*/\n $('.nav-link').each(function(index){\n\n if (index == 1) {\n $(this).addClass('active'); $(this).parents('li').addClass('active');\n }\n });\n\n\n $('.fieldContainer').hover(\n function(){\n $(this).closest('div').find('i').show()\n },\n\n function(){\n $(this).closest('div').find('i').hide()\n },\n\n )\n\n /*Adjust side of SideBar*/\n body = $('body').height()/1.4\n $('.bodyNav').css('height', body)\n /*End Adjust side of SideBar*/\n\n $('[data-toggle=\"tooltip\"]').tooltip();\n\n/* Get Array from the text area tagify\n $('.submit').on('click', function(e){\n e.preventDefault()\n values = []\n $('.tagify__tag-text').each(function(index){\n console.log($(this).text() + \" value \",index)\n values.push($(this).text())\n })\n console.log(values, \"All Values\")\n console.log($('.itemTags').val(), 'Logged')\n });*/\n\n\n $('.btnEdit').on('click', function(){\n $(this).closest('div').find('span, input').toggle();\n $(this).closest('div').find('input').focus();\n })\n\n $('input').on('blur', function(){\n $(this).closest('div').find('span, input').toggle();\n var csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();\n var updateWhat = $(this).attr('name')\n var value = $(this).val()\n $(this).closest('div').find('.field').text(value);\n console.log(\"This \" + csrfmiddlewaretoken + ' ' + updateWhat)\n $.ajax({\n type: 'POST',\n url: 'edit/',\n data: {\n csrfmiddlewaretoken: csrfmiddlewaretoken,\n updateWhat: updateWhat,\n value: value,\n }\n\n })\n })\n\n\n\n\n});\n" }, { "alpha_fraction": 0.6979560852050781, "alphanum_fraction": 0.6994701027870178, "avg_line_length": 45.26315689086914, "blob_id": "9394f1e6316224c59448adab45bdd09c198bad56", "content_id": "8ef9cab52814ba870d095bfe7ae17e50987504e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2642, "license_type": "no_license", "max_line_length": 86, "num_lines": 57, "path": "/inventory/webInventory/urls.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "from django.urls import path, re_path\nfrom django.contrib.auth import views as auth_views\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\n#For Static Files\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\n\nurlpatterns = [\n path('login/', views.login_view, name='login'),\n path('home/', views.index, name='home'),\n path('logout/', views.logout_view, name='logout'),\n path('list/', views.inventoryList, name='inventoryList'),\n path('item-list/<pk>/', views.itemList, name='itemList'),\n path('tag-list/', views.tagList, name='tagList'),\n path('manage-users/', views.manageUsers, name='manageUsers'),\n path('audit-trail/',views.auditTrail, name='auditTrail'),\n path('item-details/<pk>/', views.itemDetails, name='item-details'),\n path('password-setup/', views.passwordSetup, name='password-setup'),\n path('activate/<slug:uidb64>/<slug:token>/',\n views.activate, name='activate'),\n\n\n #Json Responses and Ajaxes\n path('home/chart-format/', views.loadChart, name='loadChart'),\n path('list/update/', views.updateFolder, name='updateFolder'),\n path('item-list/<pk>/update/', views.updateFolderDesc, name='updateFolderDesc'),\n path('tag-list/update/', views.updateTagName, name='tagUpdate'),\n path('manage-users/profile/', views.profileUpdate, name='viewProfile'),\n path('manage-users/reset/', views.resetPass, name='adminpass-reset'),\n path('manage-users/disable/', views.deactivateUser, name='admin-disable'),\n path('item-list/<pk>/tags/', views.getTags, name='gettags'),\n path('item-details/<pk>/tags/', views.getTags, name='gettagsDetails'),\n path('item-details/<pk>/edit/', views.updateItem, name='item-update'),\n\n #Password Reset\n\n path('password-reset/', auth_views.PasswordResetView.as_view(\n template_name='webInventory/passReset/passReset.html'), #Get User Email\n name='reset_password'),\n\n path('password-reset-done/', auth_views.PasswordResetDoneView.as_view(\n template_name='webInventory/passReset/passResetDone.html'\n ),\n name='password_reset_done'), #Success Message After Submit Email\n\n path('password/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(\n template_name='webInventory/passReset/passResetConfirm.html'),\n name='password_reset_confirm'), #Receiving Email to Reset Password\n\n path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(\n template_name='webInventory/passReset/passResetComplete.html'),\n name='password_reset_complete'), #Notification Message that the reset is done\n\n]\n\n\n\n\n\n" }, { "alpha_fraction": 0.5929203629493713, "alphanum_fraction": 0.6172566413879395, "avg_line_length": 29.133333206176758, "blob_id": "8581de716f99bd362997fb39ce160020cff7e695", "content_id": "a52e0c20a92cfa4bf7e2f8d13d341400032a7afa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 904, "license_type": "no_license", "max_line_length": 136, "num_lines": 30, "path": "/inventory/webInventory/migrations/0012_auto_20200930_0419.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2020-09-29 20:19\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 dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('webInventory', '0011_tag_created_by_name'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='audittrail',\n name='profile',\n ),\n migrations.AddField(\n model_name='audittrail',\n name='profile_name',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n migrations.AddField(\n model_name='audittrail',\n name='user',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.6336336135864258, "alphanum_fraction": 0.6469802856445312, "avg_line_length": 34.8982048034668, "blob_id": "c12f4accc9075d8dc1bdaacd6e15776c587877f9", "content_id": "006aae08e39d41df5a693ee676bfd776d131f9f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5994, "license_type": "no_license", "max_line_length": 145, "num_lines": 167, "path": "/inventory/webInventory/common.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "from .models import *\nimport barcode\nfrom barcode.writer import ImageWriter\n\n#This is for the most common Functions\n\n#This count the item per folder individually\ndef countFolderItems(id):\n folder = ItemFolder.objects.get(id=id)\n itemCount = len(models.Item.objects.filter(itemFolder_id=folder.id))\n return itemCount\n\n#This returns the total items of all folders\ndef countFolderItemsAll():\n all_folders = ItemFolder.objects.all()\n folder_list = [{'id': x.id} for x in all_folders]\n itemCount = 0\n for folder in folder_list:\n itemCount += len(Item.objects.filter(itemFolder_id=folder['id']))\n\n return itemCount\n\n\n#This returns the name, id, and item quantity\ndef AllFolderAndItems(option):\n all_folders = ItemFolder.objects.all()\n\n if option == 1:\n folder_list = [{'id': x.id, 'name': x.name} for x in all_folders]\n for folder in folder_list:\n itemCount = len((Item.objects.filter(itemFolder_id=folder['id'])))\n folder['countItems'] = itemCount\n folder['barColor'] = '#2DAF36'\n folder['borderColor'] = '#285E70'\n elif option == 2:\n folder_id = []\n folder_names = []\n itemCountList = []\n barColor = []\n borderColor = []\n for x in all_folders:\n itemCount = len((Item.objects.filter(itemFolder_id=x.id)))\n folder_id.append(x.id)\n folder_names.append(x.name)\n itemCountList.append(itemCount)\n barColor.append('#2DAF36')\n borderColor.append('#285E70')\n\n folder_list = {\n 'ids' : folder_id,\n 'names': folder_names,\n 'itemCountList': itemCountList,\n 'barColors': barColor,\n 'borderColors': borderColor\n }\n\n return folder_list\n\n\ndef getCompanyOptions():\n options = ['EAN8', 'EAN13', 'EAN14']\n #barcode to be supported in the future 'UPCA', 'JAN', 'ISBN10', 'ISBN13', 'ISSN', 'Code39', 'Code128', 'PZN'\n return options\n\n\n#Ipagpaliban na muna\n#Generate barcode using Item tag and ITem ID. Format is EAN13\ndef create_barcode(item, request):\n country_code = 63\n companyDetails = getCompany(request)\n country_code_length = len(str(country_code))\n\n #Check what barcode Type is in the selection to Identify the length\n if str.upper(companyDetails.barcodeType) == 'EAN8':\n barlength = 8\n elif str.upper(companyDetails.barcodeType) == 'EAN13':\n barlength = 13\n elif str.upper(companyDetails.barcodeType) == 'EAN14':\n barlength = 14\n\n #If Company Prefix is Not Null\n if companyDetails.companyPrefix:\n #Get the length of the Prefix\n companyPrefix_length = len(str(companyDetails.companyPrefix))\n # Shorten the String for universal usage\n companyPrefix = companyDetails.companyPrefix\n\n #If Company Prefix is NULL\n else:\n #Creates a Company Prefix Default that looks like 0000\n companyPrefixDefault = ''\n if str.upper(companyDetails.barcodeType) == 'EAN13':\n companyPrefix_length = int((barlength - 3) / 2)\n else:\n companyPrefix_length = (barlength - 2) / 2\n companyPrefix_length = int(companyPrefix_length)\n\n for i in range(companyPrefix_length):\n companyPrefixDefault = companyPrefixDefault + '0'\n # Shorten the String for universal usage\n companyPrefix = companyPrefixDefault\n\n #Get the Product Code Length based on the length of the Company Prefix and Country code and barlength\n productCode_length = barlength - (companyPrefix_length + country_code_length)\n\n if str.upper(companyDetails.barcodeType) == 'EAN13':\n productCode_length = productCode_length-1\n\n #Deduct the item id length from the product code length\n productCode_length = productCode_length - len(str(item.id))\n\n #Product Code String always starts with 1\n productCode_string = '1'\n\n if productCode_length > 0:\n for x in range(productCode_length - 1):\n productCode_string = productCode_string + '0'\n\n productCode_string = productCode_string + str(item.id)\n\n # print(productCode_string)\n item_barcode = str(country_code) + companyPrefix + productCode_string\n #ean = barcode.get(companyDetails.barcodeType,\n #str(country_code) + companyPrefix + productCode_string,\n #writer=ImageWriter())\n elif productCode_length == 0:\n item_barcode = str(country_code) + companyPrefix + str(item.id)\n\n else:\n default = ''\n for x in range(barlength):\n default = default + '0'\n\n item_barcode = default\n\n #ean = barcode.get(companyDetails.barcodeType,\n #default,\n #writer=ImageWriter())\n\n #filename = ean.save('media/ean13')\n\n if str.upper(companyDetails.barcodeType) == 'EAN13':\n item_barcode = '0' + item_barcode\n\n return item_barcode\n\n\ndef generate_barcode(item, request):\n companyDetails = getCompany(request)\n ean = barcode.get(companyDetails.barcodeType, item.barcode, writer=ImageWriter())\n filename = ean.save('media/ean13')\n return filename\n\ndef getCompany(request):\n companyDesignation = UserCompany.objects.filter(user_id=request.user.id).order_by('-assigned_date')[0]\n companyDetails = companyInformation.objects.get(id=companyDesignation.company_id)\n return companyDetails\n\ndef Convert(string):\n # Use split to the string to return the data as an array and to capture the desired string\n li = string.split(\":\") #split the String into an array using the : char on the string\n convertedData = []\n for item in range(1, len(li)):\n str = li[item].split('\"') #split again starting from the second element, this time, it uses the \" character in the string of the element\n convertedData.append(str[1])\n #print(str[1], \"Print from Function\") #print the 1st element and return it\n return convertedData" }, { "alpha_fraction": 0.5778781175613403, "alphanum_fraction": 0.6207674741744995, "avg_line_length": 22.3157901763916, "blob_id": "d7ac10d00f9bf8780eacd1616c118a5e46610b7d", "content_id": "2d587c2cb4ff1e49bb918863596d846f150beff2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 443, "license_type": "no_license", "max_line_length": 93, "num_lines": 19, "path": "/inventory/webInventory/migrations/0015_profile_created_on.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2020-10-04 23:11\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0014_userrole'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='profile',\n name='created_on',\n field=models.DateTimeField(blank=True, default=datetime.datetime.now, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.4695431590080261, "alphanum_fraction": 0.4830795228481293, "avg_line_length": 25.288888931274414, "blob_id": "d69da38980f51c9feef7513ea04d8a0daff389bb", "content_id": "1d885a5a2e05718756a59f79b8d3153ef77e8c46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1182, "license_type": "no_license", "max_line_length": 89, "num_lines": 45, "path": "/inventory/webInventory/static/webInventory/js/login.js", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "$(function (){\n console.log(\"Java Script Works\")\n\n /*Check if the login page is blank*/\n $('.logCred').on('blur', function (){\n if(!$.trim(this.value).length){\n $(this).addClass('warning')\n }else {\n $(this).removeClass('warning')\n }\n })\n\n /*For Alert*/\n $(\".alert-danger\").fadeTo(2000, 500).slideUp(500, function(){\n $(\".alert-danger\").slideUp(500);\n\n });\n\n //For Set Password\n\n $('.pword').keyup(function (){\n if($(this).val().length < 8 ){\n console.log(\"Password is too short\")\n $('.errors').text(\"Password is too short. It should be atleast 8 characters\")\n $('.btnreset').attr('disabled', true)\n }else{\n $('.errors').text(\"\")\n $('.btnreset').attr('disabled', false)\n }\n\n })\n\n $('.pword2').keyup(function (){\n if($(this).val() !== $('.pword').val()){\n console.log(\"Password Does not Match\")\n $('.errors').text(\"Password Does not Match\")\n $('.btnreset').attr('disabled', true)\n }else{\n $('.errors').text(\"\")\n $('.btnreset').attr('disabled', false)\n }\n\n })\n\n});" }, { "alpha_fraction": 0.4653363525867462, "alphanum_fraction": 0.4700678884983063, "avg_line_length": 27.940475463867188, "blob_id": "58bc26963b41c06078e7896eb5f733d4164e8e0d", "content_id": "6fc27436f84853e215724f71323459c8b652cea1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4861, "license_type": "no_license", "max_line_length": 102, "num_lines": 168, "path": "/inventory/webInventory/static/webInventory/js/manageUsers.js", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "$(function (){\n console.log(\"Manage Users\")\n /*Highhlight the current page in NavBar*/\n $('.nav-link').each(function(){\n if ($(this).prop('href') == window.location.href) {\n $(this).addClass('active'); $(this).parents('li').addClass('active');\n }\n });\n\n /*Adjust side of SideBar*/\n body = $('body').height()/1.4\n $('.bodyNav').css('height', body)\n /*End Adjust side of SideBar*/\n\n $('.btnEditName, .btnDelete, .btnReset').hover(\n function (){\n $(this).css('color', 'gray')\n },\n function (){\n $(this).css('color', 'black')\n }\n\n )\n\n $('[data-toggle=\"tooltipEdit\"]').tooltip();\n $('[data-toggle=\"tooltipDelete\"]').tooltip();\n $('[data-toggle=\"tooltipReset\"]').tooltip();\n $('[data-toggle=\"tooltipActivate\"]').tooltip();\n\n\n var viewUsers = $('.user-table').DataTable({\n bFilter: true,\n bInfo: false,\n bLengthChange: true,\n bSort: true,\n pageLength: 10,\n language: { searchPlaceholder: \"Search..\"},\n });\n\n $('.addUser').on('click', function (){\n $('.frmAddUser').fadeToggle();\n });\n\n $('input[type=search]').add('select').on('focus', function (){\n\n $(this).css('border', '3px solid powderblue')\n });\n\n $('select').add('input[type=search]').on('blur focusOut', function (){\n $(this).css('border', '')\n });\n\n\n\n $('#setPass').on('click', function (){\n if($(this).is(':checked')){\n $('input[type=password]').slideToggle()\n $('input[type=password]').attr('required', true);\n }else{\n $('input[type=password]').slideToggle()\n $('input[type=password]').attr('required', false);\n }\n })\n\n $(\".alert-success, .alert-danger\").fadeTo(2000, 500).slideUp(500, function(){\n $(\".alert-success, .alert-danger\").slideUp(500);\n });\n\n //Passing ID for Delete\n $('.user-table').on('click', '.btnDelete' ,function (){\n db_id =$(this).closest('tr').find('.handleId').val()\n $('.deleteOptionId').val(db_id)\n })\n\n //Passing ID for Edit\n $('.user-table').on('click', '.btnEditName' ,function (){\n db_id =$(this).closest('tr').find('.handleId').val()\n $('.idHandlerUpdate').val(db_id)\n $.ajax({\n type: 'GET',\n url: 'profile/',\n data: {\n id: db_id,\n },\n success: function (data){\n $('.userName').text(data['uname'])\n $('.profileName').val(data['name'])\n $('.profileAddress').val(data['address'])\n $('.profilePhone').val(data['phone'])\n $('.profileEmail').val(data['email'])\n\n if( data['role'] == String(1)){\n $('#isAdminEdit').attr('checked', true);\n }else if(data['role'] == String(2)){\n $('#isAdminEdit').attr('checked', false);\n }\n }\n\n })\n });\n\n $('.user-table').on('click', '.btnReset' ,function(){\n $('.resetMessage').text(\"Loading...\")\n $('.modal-footer').css('display', 'none')\n db_id =$(this).closest('tr').find('.handleId').val()\n $.ajax({\n type: 'GET',\n url: 'reset/',\n data: {\n id: db_id\n },\n success: function(data){\n console.log(\"Email Sent to \" + data.email)\n $('.resetMessage').text(\"Password Reset Email was Successfully Sent to \" + data.email)\n $('.modal-footer').css('display', 'block')\n },\n })\n });\n\n\n $('.user-table').on('click', '.disableUser' ,function(){\n db_id =$(this).closest('tr').find('.handleId').val()\n var csrfmiddlewaretoken = $(this).closest('tr').find('input[name=csrfmiddlewaretoken]').val();\n\n $.ajax({\n type: 'POST',\n url: 'disable/',\n data: {\n id: db_id,\n csrfmiddlewaretoken: csrfmiddlewaretoken,\n },\n success: function(data){\n console.log(data)\n location.reload();\n },\n })\n })\n\n //For Set Password\n\n $('.pword').keyup(function (){\n if($(this).val().length < 8 ){\n console.log(\"Password is too short\")\n $('.errors').text(\"Password is too short. It should be atleast 8 characters\")\n $('.btnreset').attr('disabled', true)\n }else{\n $('.errors').text(\"\")\n $('.btnreset').attr('disabled', false)\n }\n\n })\n\n $('.pword2').keyup(function (){\n if($(this).val() !== $('.pword').val()){\n console.log(\"Password Does not Match\")\n $('.errors').text(\"Password Does not Match\")\n\n }else{\n $('.errors').text(\"\")\n\n }\n\n })\n\n\n\n\n})" }, { "alpha_fraction": 0.4642172157764435, "alphanum_fraction": 0.4686611294746399, "avg_line_length": 56.41078186035156, "blob_id": "48d83bd1b9a25ff7b66c8a2d47da722f062b1027", "content_id": "7ebe7d6e7b6d89ad94ebdc5ec8c8db532133ad3e", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "JavaScript", "length_bytes": 75609, "license_type": "no_license", "max_line_length": 760, "num_lines": 1317, "path": "/inventory/webInventory/static/webInventory/js/tagify.min.js", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "/**\n * Tagify (v3.20.3) - tags input component\n * By Yair Even-Or\n * Don't sell this code. (c)\n * https://github.com/yairEO/tagify\n */\n! function(t, e) {\n \"object\" == typeof exports && \"undefined\" != typeof module ? module.exports = e() : \"function\" == typeof define && define.amd ? define(e) : (t = \"undefined\" != typeof globalThis ? globalThis : t || self).Tagify = e()\n}(this, (function() {\n \"use strict\";\n\n function t(e) {\n return (t = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(t) {\n return typeof t\n } : function(t) {\n return t && \"function\" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? \"symbol\" : typeof t\n })(e)\n }\n\n function e(t, e, i) {\n return e in t ? Object.defineProperty(t, e, {\n value: i,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : t[e] = i, t\n }\n\n function i(t, e) {\n var i = Object.keys(t);\n if (Object.getOwnPropertySymbols) {\n var s = Object.getOwnPropertySymbols(t);\n e && (s = s.filter((function(e) {\n return Object.getOwnPropertyDescriptor(t, e).enumerable\n }))), i.push.apply(i, s)\n }\n return i\n }\n\n function s(t) {\n for (var s = 1; s < arguments.length; s++) {\n var n = null != arguments[s] ? arguments[s] : {};\n s % 2 ? i(Object(n), !0).forEach((function(i) {\n e(t, i, n[i])\n })) : Object.getOwnPropertyDescriptors ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(n)) : i(Object(n)).forEach((function(e) {\n Object.defineProperty(t, e, Object.getOwnPropertyDescriptor(n, e))\n }))\n }\n return t\n }\n\n function n(t) {\n return function(t) {\n if (Array.isArray(t)) return a(t)\n }(t) || function(t) {\n if (\"undefined\" != typeof Symbol && Symbol.iterator in Object(t)) return Array.from(t)\n }(t) || function(t, e) {\n if (!t) return;\n if (\"string\" == typeof t) return a(t, e);\n var i = Object.prototype.toString.call(t).slice(8, -1);\n \"Object\" === i && t.constructor && (i = t.constructor.name);\n if (\"Map\" === i || \"Set\" === i) return Array.from(t);\n if (\"Arguments\" === i || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)) return a(t, e)\n }(t) || function() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\")\n }()\n }\n\n function a(t, e) {\n (null == e || e > t.length) && (e = t.length);\n for (var i = 0, s = new Array(e); i < e; i++) s[i] = t[i];\n return s\n }\n var o = function(t, e, i) {\n return i ? t == e : (\"\" + t).toLowerCase() == (\"\" + e).toLowerCase()\n };\n\n function r(t) {\n var e = Object.prototype.toString.call(t).split(\" \")[1].slice(0, -1);\n return t === Object(t) && \"Array\" != e && \"Function\" != e && \"RegExp\" != e && \"HTMLUnknownElement\" != e\n }\n\n function l(t) {\n var e = document.createElement(\"div\");\n return t.replace(/\\&#?[0-9a-z]+;/gi, (function(t) {\n return e.innerHTML = t, e.innerText\n }))\n }\n\n function d(t) {\n return t.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\").replace(/`|'/g, \"&#039;\")\n }\n\n function c(t, e, i) {\n function s(t, e) {\n for (var i in e) e.hasOwnProperty(i) && (r(e[i]) ? r(t[i]) ? s(t[i], e[i]) : t[i] = Object.assign({}, e[i]) : t[i] = e[i])\n }\n return t instanceof Object || (t = {}), s(t, e), i && s(t, i), t\n }\n\n function h(t) {\n return String.prototype.normalize ? \"string\" == typeof t ? t.normalize(\"NFD\").replace(/[\\u0300-\\u036f]/g, \"\") : void 0 : t\n }\n var g = {\n init: function() {\n this.DOM.dropdown = this.parseTemplate(\"dropdown\", [this.settings]), this.DOM.dropdown.content = this.DOM.dropdown.querySelector(\".\" + this.settings.classNames.dropdownWrapper)\n },\n show: function(t) {\n var e, i, s, n = this,\n a = this.settings,\n l = window.getSelection(),\n d = \"mix\" == a.mode && !a.enforceWhitelist,\n c = !a.whitelist || !a.whitelist.length,\n h = \"manual\" == a.dropdown.position;\n if (t = void 0 === t ? this.state.inputText : t, (!c || d || a.templates.dropdownItemNoMatch) && !1 !== a.dropdown.enable && !this.state.isLoading) {\n if (clearTimeout(this.dropdownHide__bindEventsTimeout), this.suggestedListItems = this.dropdown.filterListItems.call(this, t), t && !this.suggestedListItems.length && (this.trigger(\"dropdown:noMatch\", t), a.templates.dropdownItemNoMatch && (s = a.templates.dropdownItemNoMatch.call(this, {\n value: t\n }))), !s) {\n if (this.suggestedListItems.length) t && d && !this.state.editing.scope && !o(this.suggestedListItems[0].value, t) && this.suggestedListItems.unshift({\n value: t\n });\n else {\n if (!t || !d || this.state.editing.scope) return this.input.autocomplete.suggest.call(this), void this.dropdown.hide.call(this);\n this.suggestedListItems = [{\n value: t\n }]\n }\n i = \"\" + (r(e = this.suggestedListItems[0]) ? e.value : e), a.autoComplete && i && 0 == i.indexOf(t) && this.input.autocomplete.suggest.call(this, e)\n }\n this.dropdown.fill.call(this, s), a.dropdown.highlightFirst && this.dropdown.highlightOption.call(this, this.DOM.dropdown.content.children[0]), this.state.dropdown.visible || setTimeout(this.dropdown.events.binding.bind(this)), this.state.dropdown.visible = t || !0, this.state.dropdown.query = t, this.state.selection = {\n anchorOffset: l.anchorOffset,\n anchorNode: l.anchorNode\n }, h || setTimeout((function() {\n n.dropdown.position.call(n), n.dropdown.render.call(n)\n })), setTimeout((function() {\n n.trigger(\"dropdown:show\", n.DOM.dropdown)\n }))\n }\n },\n hide: function(t) {\n var e = this,\n i = this.DOM,\n s = i.scope,\n n = i.dropdown,\n a = \"manual\" == this.settings.dropdown.position && !t;\n if (n && document.body.contains(n) && !a) return window.removeEventListener(\"resize\", this.dropdown.position), this.dropdown.events.binding.call(this, !1), s.setAttribute(\"aria-expanded\", !1), n.parentNode.removeChild(n), setTimeout((function() {\n e.state.dropdown.visible = !1\n }), 100), this.state.dropdown.query = this.state.ddItemData = this.state.ddItemElm = this.state.selection = null, this.state.tag && this.state.tag.value.length && (this.state.flaggedTags[this.state.tag.baseOffset] = this.state.tag), this.trigger(\"dropdown:hide\", n), this\n },\n render: function() {\n var t, e, i, s = this,\n n = (t = this.DOM.dropdown, (i = t.cloneNode(!0)).style.cssText = \"position:fixed; top:-9999px; opacity:0\", document.body.appendChild(i), e = i.clientHeight, i.parentNode.removeChild(i), e),\n a = this.settings;\n return this.DOM.scope.setAttribute(\"aria-expanded\", !0), document.body.contains(this.DOM.dropdown) || (this.DOM.dropdown.classList.add(a.classNames.dropdownInital), this.dropdown.position.call(this, n), a.dropdown.appendTarget.appendChild(this.DOM.dropdown), setTimeout((function() {\n return s.DOM.dropdown.classList.remove(a.classNames.dropdownInital)\n }))), this\n },\n fill: function(t) {\n var e;\n t = \"string\" == typeof t ? t : this.dropdown.createListHTML.call(this, t || this.suggestedListItems), this.DOM.dropdown.content.innerHTML = (e = t) ? e.replace(/\\>[\\r\\n ]+\\</g, \"><\").replace(/(<.*?>)|\\s+/g, (function(t, e) {\n return e || \" \"\n })) : \"\"\n },\n refilter: function(t) {\n t = t || this.state.dropdown.query || \"\", this.suggestedListItems = this.dropdown.filterListItems.call(this, t), this.suggestedListItems.length ? this.dropdown.fill.call(this) : this.dropdown.hide.call(this), this.trigger(\"dropdown:updated\", this.DOM.dropdown)\n },\n position: function(t) {\n if (\"manual\" != this.settings.dropdown.position) {\n var e, i, s, n, a, o, r, l = this.DOM.dropdown,\n d = document.documentElement.clientHeight,\n c = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) > 480 ? this.settings.dropdown.position : \"all\",\n h = this.DOM[\"input\" == c ? \"input\" : \"scope\"];\n t = t || l.clientHeight, this.state.dropdown.visible && (\"text\" == c ? (n = (i = this.getCaretGlobalPosition()).bottom, s = i.top, a = i.left, o = \"auto\") : (r = function(t) {\n for (var e = 0, i = 0; t;) e += t.offsetLeft || 0, i += t.offsetTop || 0, t = t.parentNode;\n return {\n left: e,\n top: i\n }\n }(this.settings.dropdown.appendTarget), s = (i = h.getBoundingClientRect()).top + 2 - r.top, n = i.bottom - 1 - r.top, a = i.left - r.left, o = i.width + \"px\"), s = Math.floor(s), n = Math.ceil(n), e = d - i.bottom < t, l.style.cssText = \"left:\" + (a + window.pageXOffset) + \"px; width:\" + o + \";\" + (e ? \"top: \" + (s + window.pageYOffset) + \"px\" : \"top: \" + (n + window.pageYOffset) + \"px\"), l.setAttribute(\"placement\", e ? \"top\" : \"bottom\"), l.setAttribute(\"position\", c))\n }\n },\n events: {\n binding: function() {\n var t = !(arguments.length > 0 && void 0 !== arguments[0]) || arguments[0],\n e = this.dropdown.events.callbacks,\n i = this.listeners.dropdown = this.listeners.dropdown || {\n position: this.dropdown.position.bind(this),\n onKeyDown: e.onKeyDown.bind(this),\n onMouseOver: e.onMouseOver.bind(this),\n onMouseLeave: e.onMouseLeave.bind(this),\n onClick: e.onClick.bind(this),\n onScroll: e.onScroll.bind(this)\n },\n s = t ? \"addEventListener\" : \"removeEventListener\";\n \"manual\" != this.settings.dropdown.position && (window[s](\"resize\", i.position), window[s](\"keydown\", i.onKeyDown)), this.DOM.dropdown[s](\"mouseover\", i.onMouseOver), this.DOM.dropdown[s](\"mouseleave\", i.onMouseLeave), this.DOM.dropdown[s](\"mousedown\", i.onClick), this.DOM.dropdown.content[s](\"scroll\", i.onScroll)\n },\n callbacks: {\n onKeyDown: function(t) {\n var e = this.DOM.dropdown.querySelector(\"[class$='--active']\"),\n i = e;\n switch (t.key) {\n case \"ArrowDown\":\n case \"ArrowUp\":\n case \"Down\":\n case \"Up\":\n var s;\n t.preventDefault(), i && (i = i[(\"ArrowUp\" == t.key || \"Up\" == t.key ? \"previous\" : \"next\") + \"ElementSibling\"]), i || (i = (s = this.DOM.dropdown.content.children)[\"ArrowUp\" == t.key || \"Up\" == t.key ? s.length - 1 : 0]), this.dropdown.highlightOption.call(this, i, !0);\n break;\n case \"Escape\":\n case \"Esc\":\n this.dropdown.hide.call(this);\n break;\n case \"ArrowRight\":\n if (this.state.actions.ArrowLeft) return;\n case \"Tab\":\n if (\"mix\" != this.settings.mode && i && !this.settings.autoComplete.rightKey && !this.state.editing) {\n t.preventDefault();\n var n = i.getAttribute(\"tagifySuggestionIdx\"),\n a = n ? this.suggestedListItems[+n] : \"\";\n return this.input.autocomplete.set.call(this, a.value || a), !1\n }\n return !0;\n case \"Enter\":\n t.preventDefault(), this.dropdown.selectOption.call(this, e);\n break;\n case \"Backspace\":\n if (\"mix\" == this.settings.mode || this.state.editing.scope) return;\n var o = this.state.inputText.trim();\n \"\" != o && 8203 != o.charCodeAt(0) || (!0 === this.settings.backspace ? this.removeTags() : \"edit\" == this.settings.backspace && setTimeout(this.editTag.bind(this), 0))\n }\n },\n onMouseOver: function(t) {\n var e = t.target.closest(\".\" + this.settings.classNames.dropdownItem);\n e && this.dropdown.highlightOption.call(this, e)\n },\n onMouseLeave: function(t) {\n this.dropdown.highlightOption.call(this)\n },\n onClick: function(t) {\n var e = this;\n if (0 == t.button && t.target != this.DOM.dropdown) {\n var i = t.target.closest(\".\" + this.settings.classNames.dropdownItem);\n this.state.actions.selectOption = !0, setTimeout((function() {\n return e.state.actions.selectOption = !1\n }), 50), this.settings.hooks.suggestionClick(t, {\n tagify: this,\n suggestionElm: i\n }).then((function() {\n i && e.dropdown.selectOption.call(e, i)\n })).catch((function(t) {\n return t\n }))\n }\n },\n onScroll: function(t) {\n var e = t.target,\n i = e.scrollTop / (e.scrollHeight - e.parentNode.clientHeight) * 100;\n this.trigger(\"dropdown:scroll\", {\n percentage: Math.round(i)\n })\n }\n }\n },\n highlightOption: function(t, e) {\n var i, s = this.settings.classNames.dropdownItemActive;\n if (this.state.ddItemElm && (this.state.ddItemElm.classList.remove(s), this.state.ddItemElm.removeAttribute(\"aria-selected\")), !t) return this.state.ddItemData = null, this.state.ddItemElm = null, void this.input.autocomplete.suggest.call(this);\n i = this.suggestedListItems[this.getNodeIndex(t)], this.state.ddItemData = i, this.state.ddItemElm = t, t.classList.add(s), t.setAttribute(\"aria-selected\", !0), e && (t.parentNode.scrollTop = t.clientHeight + t.offsetTop - t.parentNode.clientHeight), this.settings.autoComplete && (this.input.autocomplete.suggest.call(this, i), this.dropdown.position.call(this))\n },\n selectOption: function(t) {\n var e = this,\n i = this.settings.dropdown,\n n = i.clearOnSelect,\n a = i.closeOnSelect;\n if (!t) return this.addTags(this.state.inputText, !0), void(a && this.dropdown.hide.call(this));\n var o = t.getAttribute(\"tagifySuggestionIdx\"),\n r = (o ? this.suggestedListItems[+o] : \"\") || this.state.inputText;\n if (this.trigger(\"dropdown:select\", {\n data: r,\n elm: t\n }), this.state.editing ? this.onEditTagDone(this.state.editing.scope, s(s(s({}, this.state.editing.scope.__tagifyTagData), {}, {\n value: r.value\n }, r instanceof Object ? r : {}), {}, {\n __isValid: !0\n })) : this.addTags([r], n), setTimeout((function() {\n e.DOM.input.focus(), e.toggleFocusClass(!0)\n })), a) return this.dropdown.hide.call(this);\n this.dropdown.refilter.call(this)\n },\n selectAll: function() {\n return this.suggestedListItems.length = 0, this.dropdown.hide.call(this), this.addTags(this.dropdown.filterListItems.call(this, \"\"), !0), this\n },\n filterListItems: function(t) {\n var e, i, s, n, a, o = this,\n l = this.settings,\n d = l.dropdown,\n c = [],\n g = l.whitelist,\n u = d.maxItems || 1 / 0,\n p = d.searchKeys,\n f = 0;\n if (!t || !p.length) return (l.duplicates ? g : g.filter((function(t) {\n return !o.isTagDuplicate(r(t) ? t.value : t)\n }))).slice(0, u);\n\n function m(t, e) {\n return e.toLowerCase().split(\" \").every((function(e) {\n return t.includes(e.toLowerCase())\n }))\n }\n for (a = d.caseSensitive ? \"\" + t : (\"\" + t).toLowerCase(); f < g.length && (e = g[f] instanceof Object ? g[f] : {\n value: g[f]\n }, d.fuzzySearch ? (s = p.reduce((function(t, i) {\n return t + \" \" + (e[i] || \"\")\n }), \"\").toLowerCase(), d.accentedSearch && (s = h(s), a = h(a)), i = m(s, a)) : i = p.some((function(t) {\n var i = \"\" + (e[t] || \"\");\n return d.accentedSearch && (i = h(i), a = h(a)), d.caseSensitive || (i = i.toLowerCase()), 0 == i.indexOf(a)\n })), n = !l.duplicates && this.isTagDuplicate(r(e) ? e.value : e), i && !n && u-- && c.push(e), 0 != u); f++);\n return c\n },\n createListHTML: function(t) {\n var e = this;\n return t.map((function(t, i) {\n \"string\" != typeof t && \"number\" != typeof t || (t = {\n value: t\n });\n var s = e.settings.dropdown.mapValueTo,\n n = s ? \"function\" == typeof s ? s(t) : t[s] : t.value,\n a = c({}, t, {\n value: n && \"string\" == typeof n ? d(n) : n,\n tagifySuggestionIdx: i\n });\n return e.settings.templates.dropdownItem.call(e, a)\n })).join(\"\")\n }\n },\n u = {\n delimiters: \",\",\n pattern: null,\n tagTextProp: \"value\",\n maxTags: 1 / 0,\n callbacks: {},\n addTagOnBlur: !0,\n duplicates: !1,\n whitelist: [],\n blacklist: [],\n enforceWhitelist: !1,\n keepInvalidTags: !1,\n mixTagsAllowedAfter: /,|\\.|\\:|\\s/,\n mixTagsInterpolator: [\"[[\", \"]]\"],\n backspace: !0,\n skipInvalid: !1,\n editTags: {\n clicks: 2,\n keepInvalid: !0\n },\n transformTag: function() {},\n trim: !0,\n mixMode: {\n insertAfterTag: \" \"\n },\n autoComplete: {\n enabled: !0,\n rightKey: !1\n },\n classNames: {\n namespace: \"tagify\",\n input: \"tagify__input\",\n focus: \"tagify--focus\",\n tag: \"tagify__tag\",\n tagNoAnimation: \"tagify--noAnim\",\n tagInvalid: \"tagify--invalid\",\n tagNotAllowed: \"tagify--notAllowed\",\n inputInvalid: \"tagify__input--invalid\",\n tagX: \"tagify__tag__removeBtn\",\n tagText: \"tagify__tag-text\",\n dropdown: \"tagify__dropdown\",\n dropdownWrapper: \"tagify__dropdown__wrapper\",\n dropdownItem: \"tagify__dropdown__item\",\n dropdownItemActive: \"tagify__dropdown__item--active\",\n dropdownInital: \"tagify__dropdown--initial\",\n scopeLoading: \"tagify--loading\",\n tagLoading: \"tagify__tag--loading\",\n tagEditing: \"tagify__tag--editable\",\n tagFlash: \"tagify__tag--flash\",\n tagHide: \"tagify__tag--hide\",\n hasMaxTags: \"tagify--hasMaxTags\",\n hasNoTags: \"tagify--noTags\",\n empty: \"tagify--empty\"\n },\n dropdown: {\n classname: \"\",\n enabled: 2,\n maxItems: 10,\n searchKeys: [\"value\", \"searchBy\"],\n fuzzySearch: !0,\n caseSensitive: !1,\n accentedSearch: !0,\n highlightFirst: !1,\n closeOnSelect: !0,\n clearOnSelect: !0,\n position: \"all\",\n appendTarget: null\n },\n hooks: {\n beforeRemoveTag: function() {\n return Promise.resolve()\n },\n suggestionClick: function() {\n return Promise.resolve()\n }\n }\n };\n var p = {\n customBinding: function() {\n var t = this;\n this.customEventsList.forEach((function(e) {\n t.on(e, t.settings.callbacks[e])\n }))\n },\n binding: function() {\n var t, e = !(arguments.length > 0 && void 0 !== arguments[0]) || arguments[0],\n i = this.events.callbacks,\n s = e ? \"addEventListener\" : \"removeEventListener\";\n if (!this.state.mainEvents || !e)\n for (var n in this.state.mainEvents = e, e && !this.listeners.main && (this.DOM.input.addEventListener(this.isIE ? \"keydown\" : \"input\", i[this.isIE ? \"onInputIE\" : \"onInput\"].bind(this)), this.settings.isJQueryPlugin && jQuery(this.DOM.originalInput).on(\"tagify.removeAllTags\", this.removeAllTags.bind(this))), t = this.listeners.main = this.listeners.main || {\n focus: [\"input\", i.onFocusBlur.bind(this)],\n blur: [\"input\", i.onFocusBlur.bind(this)],\n keydown: [\"input\", i.onKeydown.bind(this)],\n click: [\"scope\", i.onClickScope.bind(this)],\n dblclick: [\"scope\", i.onDoubleClickScope.bind(this)],\n paste: [\"input\", i.onPaste.bind(this)]\n })(\"blur\" != n || e) && this.DOM[t[n][0]][s](n, t[n][1])\n },\n callbacks: {\n onFocusBlur: function(t) {\n var e = t.target ? this.trim(t.target.textContent) : \"\",\n i = this.settings,\n s = t.type,\n n = i.dropdown.enabled >= 0,\n a = {\n relatedTarget: t.relatedTarget\n },\n o = this.state.actions.selectOption && (n || !i.dropdown.closeOnSelect),\n r = this.state.actions.addNew && n,\n l = window.getSelection();\n if (\"blur\" == s) {\n if (t.relatedTarget === this.DOM.scope) return this.dropdown.hide.call(this), void this.DOM.input.focus();\n this.postUpdate(), this.triggerChangeEvent()\n }\n if (!o && !r)\n if (this.state.hasFocus = \"focus\" == s && +new Date, this.toggleFocusClass(this.state.hasFocus), \"mix\" != i.mode) {\n if (\"focus\" == s) return this.trigger(\"focus\", a), void(0 === i.dropdown.enabled && this.dropdown.show.call(this));\n \"blur\" == s && (this.trigger(\"blur\", a), this.loading(!1), (\"select\" == this.settings.mode ? !this.value.length || this.value[0].value != e : e && !this.state.actions.selectOption && i.addTagOnBlur) && this.addTags(e, !0)), this.DOM.input.removeAttribute(\"style\"), this.dropdown.hide.call(this)\n } else \"focus\" == s ? this.trigger(\"focus\", a) : \"blur\" == t.type && (this.trigger(\"blur\", a), this.loading(!1), this.dropdown.hide.call(this), this.state.dropdown.visible = void 0, this.state.selection = {\n anchorOffset: l.anchorOffset,\n anchorNode: l.anchorNode\n }, l.getRangeAt && l.rangeCount && (this.state.selection.range = l.getRangeAt(0)))\n },\n onKeydown: function(t) {\n var e = this,\n i = this.trim(t.target.textContent);\n if (this.trigger(\"keydown\", {\n originalEvent: this.cloneEvent(t)\n }), \"mix\" == this.settings.mode) {\n switch (t.key) {\n case \"Left\":\n case \"ArrowLeft\":\n this.state.actions.ArrowLeft = !0;\n break;\n case \"Delete\":\n case \"Backspace\":\n if (this.state.editing) return;\n var s, n = document.getSelection(),\n a = \"Delete\" == t.key && n.anchorOffset == (n.anchorNode.length || 0),\n o = 1 == n.anchorNode.nodeType || !n.anchorOffset && n.anchorNode.previousElementSibling,\n r = l(this.DOM.input.innerHTML),\n d = this.getTagElms();\n if (\"BR\" == n.anchorNode.nodeName) return;\n if ((a || o) && 1 == n.anchorNode.nodeType ? s = 0 == n.anchorOffset ? a ? d[0] : null : d[n.anchorOffset - 1] : a ? s = n.anchorNode.nextElementSibling : o && (s = o), 3 == n.anchorNode.nodeType && !n.anchorNode.nodeValue && n.anchorNode.previousElementSibling && t.preventDefault(), (o || a) && !this.settings.backspace) return void t.preventDefault();\n if (\"Range\" != n.type && s && s.hasAttribute(\"readonly\")) return void this.placeCaretAfterNode(function(t, e) {\n for (e = e || \"previous\"; t = t[e + \"Sibling\"];)\n if (3 == t.nodeType) return t\n }(s));\n this.isFirefox && 1 == n.anchorNode.nodeType && 0 != n.anchorOffset && (this.removeTags(), this.placeCaretAfterNode(this.setRangeAtStartEnd())), setTimeout((function() {\n var t = document.getSelection(),\n i = l(e.DOM.input.innerHTML),\n s = t.anchorNode.previousElementSibling;\n if (i.length >= r.length && s && !s.hasAttribute(\"readonly\") && (e.removeTags(s), e.fixFirefoxLastTagNoCaret(), 2 == e.DOM.input.children.length && \"BR\" == e.DOM.input.children[1].tagName)) return e.DOM.input.innerHTML = \"\", e.value.length = 0, !0;\n e.value = [].map.call(d, (function(t, i) {\n var s = e.tagData(t);\n if (t.parentNode || s.readonly) return s;\n e.trigger(\"remove\", {\n tag: t,\n index: i,\n data: s\n })\n })).filter((function(t) {\n return t\n }))\n }), 50)\n }\n return !0\n }\n switch (t.key) {\n case \"Backspace\":\n this.state.dropdown.visible && \"manual\" != this.settings.dropdown.position || \"\" != i && 8203 != i.charCodeAt(0) || (!0 === this.settings.backspace ? this.removeTags() : \"edit\" == this.settings.backspace && setTimeout(this.editTag.bind(this), 0));\n break;\n case \"Esc\":\n case \"Escape\":\n if (this.state.dropdown.visible) return;\n t.target.blur();\n break;\n case \"Down\":\n case \"ArrowDown\":\n this.state.dropdown.visible || this.dropdown.show.call(this);\n break;\n case \"ArrowRight\":\n var c = this.state.inputSuggestion || this.state.ddItemData;\n if (c && this.settings.autoComplete.rightKey) return void this.addTags([c], !0);\n break;\n case \"Tab\":\n if (i && t.preventDefault(), !i || \"select\" == this.settings.mode) return !0;\n case \"Enter\":\n if (this.state.dropdown.visible || 229 == t.keyCode) return;\n t.preventDefault(), setTimeout((function() {\n e.state.actions.selectOption || e.addTags(i, !0)\n }))\n }\n },\n onInput: function(t) {\n if (\"mix\" == this.settings.mode) return this.events.callbacks.onMixTagsInput.call(this, t);\n var e = this.input.normalize.call(this),\n i = e.length >= this.settings.dropdown.enabled,\n s = {\n value: e,\n inputElm: this.DOM.input\n };\n s.isValid = this.validateTag({\n value: e\n }), this.trigger(\"input\", s), this.state.inputText != e && (this.input.set.call(this, e, !1), -1 != e.search(this.settings.delimiters) ? this.addTags(e) && this.input.set.call(this) : this.settings.dropdown.enabled >= 0 && this.dropdown[i ? \"show\" : \"hide\"].call(this, e))\n },\n onMixTagsInput: function(t) {\n var e, i, s, n, a, o, r, l, d = this,\n h = this.settings,\n g = this.value.length,\n u = this.getTagElms(),\n p = document.createDocumentFragment(),\n f = window.getSelection().getRangeAt(0),\n m = [].map.call(u, (function(t) {\n return d.tagData(t).value\n }));\n if (this.value.slice().forEach((function(t) {\n t.readonly && !m.includes(t.value) && p.appendChild(d.createTagElem(t))\n })), p.childNodes.length && (f.insertNode(p), this.setRangeAtStartEnd(!1, p.lastChild)), u.length != g) return this.value = [].map.call(this.getTagElms(), (function(t) {\n return d.tagData(t)\n })), void this.update({\n withoutChangeEvent: !0\n });\n if (this.hasMaxTags()) return !0;\n if (window.getSelection && (o = window.getSelection()).rangeCount > 0 && 3 == o.anchorNode.nodeType) {\n if ((f = o.getRangeAt(0).cloneRange()).collapse(!0), f.setStart(o.focusNode, 0), s = (e = f.toString().slice(0, f.endOffset)).split(h.pattern).length - 1, (i = e.match(h.pattern)) && (n = e.slice(e.lastIndexOf(i[i.length - 1]))), n) {\n if (this.state.actions.ArrowLeft = !1, this.state.tag = {\n prefix: n.match(h.pattern)[0],\n value: n.replace(h.pattern, \"\")\n }, this.state.tag.baseOffset = o.baseOffset - this.state.tag.value.length, l = this.state.tag.value.match(h.delimiters)) return this.state.tag.value = this.state.tag.value.replace(h.delimiters, \"\"), this.state.tag.delimiters = l[0], this.addTags(this.state.tag.value, h.dropdown.clearOnSelect), void this.dropdown.hide.call(this);\n a = this.state.tag.value.length >= h.dropdown.enabled;\n try {\n r = (r = this.state.flaggedTags[this.state.tag.baseOffset]).prefix == this.state.tag.prefix && r.value[0] == this.state.tag.value[0], this.state.flaggedTags[this.state.tag.baseOffset] && !this.state.tag.value && delete this.state.flaggedTags[this.state.tag.baseOffset]\n } catch (t) {}(r || s < this.state.mixMode.matchedPatternCount) && (a = !1)\n } else this.state.flaggedTags = {};\n this.state.mixMode.matchedPatternCount = s\n }\n setTimeout((function() {\n d.update({\n withoutChangeEvent: !0\n }), d.trigger(\"input\", c({}, d.state.tag, {\n textContent: d.DOM.input.textContent\n })), d.state.tag && d.dropdown[a ? \"show\" : \"hide\"].call(d, d.state.tag.value)\n }), 10)\n },\n onInputIE: function(t) {\n var e = this;\n setTimeout((function() {\n e.events.callbacks.onInput.call(e, t)\n }))\n },\n onClickScope: function(t) {\n var e = this.settings,\n i = t.target.closest(\".\" + e.classNames.tag),\n s = +new Date - this.state.hasFocus;\n if (t.target != this.DOM.scope) {\n if (!t.target.classList.contains(e.classNames.tagX)) return i ? (this.trigger(\"click\", {\n tag: i,\n index: this.getNodeIndex(i),\n data: this.tagData(i),\n originalEvent: this.cloneEvent(t)\n }), void(1 !== e.editTags && 1 !== e.editTags.clicks || this.events.callbacks.onDoubleClickScope.call(this, t))) : void(t.target == this.DOM.input && (\"mix\" == e.mode && this.fixFirefoxLastTagNoCaret(), s > 500) ? this.state.dropdown.visible ? this.dropdown.hide.call(this) : 0 === e.dropdown.enabled && \"mix\" != e.mode && this.dropdown.show.call(this) : \"select\" == e.mode && !this.state.dropdown.visible && this.dropdown.show.call(this));\n this.removeTags(t.target.parentNode)\n } else this.state.hasFocus || this.DOM.input.focus()\n },\n onPaste: function(t) {\n var e;\n t.preventDefault(), this.settings.readonly || (e = (t.clipboardData || window.clipboardData).getData(\"Text\"), this.injectAtCaret(e, window.getSelection().getRangeAt(0)), \"mix\" != this.settings.mode && this.addTags(this.DOM.input.textContent, !0))\n },\n onEditTagInput: function(t, i) {\n var s = t.closest(\".\" + this.settings.classNames.tag),\n n = this.getNodeIndex(s),\n a = this.tagData(s),\n o = this.input.normalize.call(this, t),\n r = s.innerHTML != s.__tagifyTagData.__originalHTML,\n l = this.validateTag(e({}, this.settings.tagTextProp, o));\n r || !0 !== t.originalIsValid || (l = !0), s.classList.toggle(this.settings.classNames.tagInvalid, !0 !== l), a.__isValid = l, s.title = !0 === l ? a.title || a.value : l, o.length >= this.settings.dropdown.enabled && (this.state.editing.value = o, this.dropdown.show.call(this, o)), this.trigger(\"edit:input\", {\n tag: s,\n index: n,\n data: c({}, this.value[n], {\n newValue: o\n }),\n originalEvent: this.cloneEvent(i)\n })\n },\n onEditTagFocus: function(t) {\n this.state.editing = {\n scope: t,\n input: t.querySelector(\"[contenteditable]\")\n }\n },\n onEditTagBlur: function(t) {\n if (this.state.hasFocus || this.toggleFocusClass(), this.DOM.scope.contains(t)) {\n var i = this.settings,\n s = t.closest(\".\" + i.classNames.tag),\n n = this.input.normalize.call(this, t),\n a = this.tagData(s).__originalData,\n o = c({}, a, e({}, i.tagTextProp, n)),\n r = s.innerHTML != s.__tagifyTagData.__originalHTML,\n l = this.validateTag(e({}, i.tagTextProp, n));\n if (!n) return this.removeTags(s), void this.onEditTagDone(null, o);\n if (r) {\n if (i.transformTag.call(this, o), !0 !== (l = this.validateTag(e({}, i.tagTextProp, o[i.tagTextProp])))) {\n if (this.trigger(\"invalid\", {\n data: o,\n tag: s,\n message: l\n }), i.editTags.keepInvalid) return;\n o = a\n } else if (o = this.getWhitelistItem(n) || o.__preInvalidData || o, !0 !== (l = this.validateTag(o))) {\n if (this.trigger(\"invalid\", {\n data: o,\n tag: s,\n message: l\n }), s.classList.toggle(i.classNames.tagInvalid, !0), i.editTags.keepInvalid) return;\n o = a\n }\n this.onEditTagDone(s, o)\n } else this.onEditTagDone(s, a)\n }\n },\n onEditTagkeydown: function(t, e) {\n switch (this.trigger(\"edit:keydown\", {\n originalEvent: this.cloneEvent(t)\n }), t.key) {\n case \"Esc\":\n case \"Escape\":\n e.innerHTML = e.__tagifyTagData.__originalHTML;\n case \"Enter\":\n case \"Tab\":\n t.preventDefault(), t.target.blur()\n }\n },\n onDoubleClickScope: function(t) {\n var e, i, s = t.target.closest(\".\" + this.settings.classNames.tag),\n n = this.settings;\n s && (e = s.classList.contains(this.settings.classNames.tagEditing), i = s.hasAttribute(\"readonly\"), \"select\" == n.mode || n.readonly || e || i || !this.settings.editTags || this.editTag(s), this.toggleFocusClass(!0), this.trigger(\"dblclick\", {\n tag: s,\n index: this.getNodeIndex(s),\n data: this.tagData(s)\n }))\n }\n }\n };\n\n function f(e, i) {\n return e ? e.previousElementSibling && e.previousElementSibling.classList.contains(\"tagify\") ? (console.warn(\"Tagify: \", \"input element is already Tagified\", e), this) : (c(this, function(e) {\n var i = document.createTextNode(\"\");\n\n function s(t, e, s) {\n s && e.split(/\\s+/g).forEach((function(e) {\n return i[t + \"EventListener\"].call(i, e, s)\n }))\n }\n return {\n off: function(t, e) {\n return s(\"remove\", t, e), this\n },\n on: function(t, e) {\n return e && \"function\" == typeof e && s(\"add\", t, e), this\n },\n trigger: function(s, n) {\n var a;\n if (s)\n if (e.settings.isJQueryPlugin) \"remove\" == s && (s = \"removeTag\"), jQuery(e.DOM.originalInput).triggerHandler(s, [n]);\n else {\n try {\n var o = c({}, \"object\" === t(n) ? n : {\n value: n\n });\n if (o.tagify = this, n instanceof Object)\n for (var r in n) n[r] instanceof HTMLElement && (o[r] = n[r]);\n a = new CustomEvent(s, {\n detail: o\n })\n } catch (t) {\n console.warn(t)\n }\n i.dispatchEvent(a)\n }\n }\n }\n }(this)), this.isFirefox = \"undefined\" != typeof InstallTrigger, this.isIE = window.document.documentMode, this.applySettings(e, i || {}), this.state = {\n inputText: \"\",\n editing: !1,\n actions: {},\n mixMode: {},\n dropdown: {},\n flaggedTags: {}\n }, this.value = [], this.listeners = {}, this.DOM = {}, this.build(e), this.getCSSVars(), this.loadOriginalValues(), this.events.customBinding.call(this), this.events.binding.call(this), void(e.autofocus && this.DOM.input.focus())) : (console.warn(\"Tagify: \", \"input element not found\", e), this)\n }\n return f.prototype = {\n dropdown: g,\n TEXTS: {\n empty: \"empty\",\n exceed: \"number of tags exceeded\",\n pattern: \"pattern mismatch\",\n duplicate: \"already exists\",\n notAllowed: \"not allowed\"\n },\n DEFAULTS: u,\n customEventsList: [\"change\", \"add\", \"remove\", \"invalid\", \"input\", \"click\", \"keydown\", \"focus\", \"blur\", \"edit:input\", \"edit:updated\", \"edit:start\", \"edit:keydown\", \"dropdown:show\", \"dropdown:hide\", \"dropdown:select\", \"dropdown:updated\", \"dropdown:noMatch\"],\n trim: function(t) {\n return this.settings.trim ? t.trim() : t\n },\n parseHTML: function(t) {\n return (new DOMParser).parseFromString(t.trim(), \"text/html\").body.firstElementChild\n },\n templates: {\n wrapper: function(t, e) {\n return '<tags class=\"'.concat(e.classNames.namespace, \" \").concat(e.mode ? \"\".concat(e.classNames.namespace, \"--\").concat(e.mode) : \"\", \" \").concat(t.className, '\"\\n ').concat(e.readonly ? \"readonly\" : \"\", \"\\n \").concat(e.required ? \"required\" : \"\", '\\n tabIndex=\"-1\">\\n <span ').concat(e.readonly && \"mix\" == e.mode ? \"\" : \"contenteditable\", ' data-placeholder=\"').concat(e.placeholder || \"&#8203;\", '\" aria-placeholder=\"').concat(e.placeholder || \"\", '\"\\n class=\"').concat(e.classNames.input, '\"\\n role=\"textbox\"\\n aria-autocomplete=\"both\"\\n aria-multiline=\"').concat(\"mix\" == e.mode, '\"></span>\\n </tags>')\n },\n tag: function(t) {\n return '<tag title=\"'.concat(t.title || t.value, \"\\\"\\n contenteditable='false'\\n spellcheck='false'\\n tabIndex=\\\"-1\\\"\\n class=\\\"\").concat(this.settings.classNames.tag, \" \").concat(t.class ? t.class : \"\", '\"\\n ').concat(this.getAttributes(t), \">\\n <x title='' class=\\\"\").concat(this.settings.classNames.tagX, \"\\\" role='button' aria-label='remove tag'></x>\\n <div>\\n <span class=\\\"\").concat(this.settings.classNames.tagText, '\">').concat(t[this.settings.tagTextProp] || t.value, \"</span>\\n </div>\\n </tag>\")\n },\n dropdown: function(t) {\n var e = t.dropdown,\n i = \"manual\" == e.position,\n s = \"\".concat(t.classNames.dropdown);\n return '<div class=\"'.concat(i ? \"\" : s, \" \").concat(e.classname, '\" role=\"listbox\" aria-labelledby=\"dropdown\">\\n <div class=\"').concat(t.classNames.dropdownWrapper, '\"></div>\\n </div>')\n },\n dropdownItem: function(t) {\n return \"<div \".concat(this.getAttributes(t), \"\\n class='\").concat(this.settings.classNames.dropdownItem, \" \").concat(t.class ? t.class : \"\", '\\'\\n tabindex=\"0\"\\n role=\"option\">').concat(t.value, \"</div>\")\n },\n dropdownItemNoMatch: null\n },\n parseTemplate: function(t, e) {\n return t = this.settings.templates[t] || t, this.parseHTML(t.apply(this, e))\n },\n applySettings: function(t, e) {\n this.DEFAULTS.templates = this.templates;\n var i = this.settings = c({}, this.DEFAULTS, e);\n if (i.readonly = t.hasAttribute(\"readonly\"), i.placeholder = t.getAttribute(\"placeholder\") || i.placeholder || \"\", i.required = t.hasAttribute(\"required\"), this.isIE && (i.autoComplete = !1), [\"whitelist\", \"blacklist\"].forEach((function(e) {\n var s = t.getAttribute(\"data-\" + e);\n s && (s = s.split(i.delimiters)) instanceof Array && (i[e] = s)\n })), \"autoComplete\" in e && !r(e.autoComplete) && (i.autoComplete = this.DEFAULTS.autoComplete, i.autoComplete.enabled = e.autoComplete), \"mix\" == i.mode && (i.autoComplete.rightKey = !0, i.delimiters = e.delimiters || null), t.pattern) try {\n i.pattern = new RegExp(t.pattern)\n } catch (t) {}\n if (this.settings.delimiters) try {\n i.delimiters = new RegExp(this.settings.delimiters, \"g\")\n } catch (t) {}\n \"select\" == i.mode && (i.dropdown.enabled = 0), i.dropdown.appendTarget = e.dropdown && e.dropdown.appendTarget ? e.dropdown.appendTarget : document.body\n },\n getAttributes: function(t) {\n if (\"[object Object]\" != Object.prototype.toString.call(t)) return \"\";\n var e, i, s = Object.keys(t),\n n = \"\";\n for (i = s.length; i--;) \"class\" != (e = s[i]) && t.hasOwnProperty(e) && void 0 !== t[e] && (n += \" \" + e + (void 0 !== t[e] ? '=\"'.concat(t[e], '\"') : \"\"));\n return n\n },\n getCaretGlobalPosition: function() {\n var t = document.getSelection();\n if (t.rangeCount) {\n var e, i, s = t.getRangeAt(0),\n n = s.startContainer,\n a = s.startOffset;\n if (a > 0) return (i = document.createRange()).setStart(n, a - 1), i.setEnd(n, a), {\n left: (e = i.getBoundingClientRect()).right,\n top: e.top,\n bottom: e.bottom\n };\n if (n.getBoundingClientRect) return n.getBoundingClientRect()\n }\n return {\n left: -9999,\n top: -9999\n }\n },\n getCSSVars: function() {\n var t, e = getComputedStyle(this.DOM.scope, null);\n this.CSSVars = {\n tagHideTransition: function(t) {\n var e = t.value;\n return \"s\" == t.unit ? 1e3 * e : e\n }(function(t) {\n if (!t) return {};\n var e = (t = t.trim().split(\" \")[0]).split(/\\d+/g).filter((function(t) {\n return t\n })).pop().trim();\n return {\n value: +t.split(e).filter((function(t) {\n return t\n }))[0].trim(),\n unit: e\n }\n }((t = \"tag-hide-transition\", e.getPropertyValue(\"--\" + t))))\n }\n },\n build: function(t) {\n var e = this.DOM;\n this.settings.mixMode.integrated ? (e.originalInput = null, e.scope = t, e.input = t) : (e.originalInput = t, e.scope = this.parseTemplate(\"wrapper\", [t, this.settings]), e.input = e.scope.querySelector(\".\" + this.settings.classNames.input), t.parentNode.insertBefore(e.scope, t)), this.settings.dropdown.enabled >= 0 && this.dropdown.init.call(this)\n },\n destroy: function() {\n this.DOM.scope.parentNode.removeChild(this.DOM.scope), this.dropdown.hide.call(this, !0), clearTimeout(this.dropdownHide__bindEventsTimeout)\n },\n loadOriginalValues: function(t) {\n var e, i = this.settings;\n if (t = t || (i.mixMode.integrated ? this.DOM.input.textContent : this.DOM.originalInput.value))\n if (this.removeAllTags(), \"mix\" == i.mode) this.parseMixTags(t.trim()), (e = this.DOM.input.lastChild) && \"BR\" == e.tagName || this.DOM.input.insertAdjacentHTML(\"beforeend\", \"<br>\");\n else {\n try {\n JSON.parse(t) instanceof Array && (t = JSON.parse(t))\n } catch (t) {}\n this.addTags(t).forEach((function(t) {\n return t && t.classList.add(i.classNames.tagNoAnimation)\n }))\n }\n else this.postUpdate();\n this.state.lastOriginalValueReported = i.mixMode.integrated ? \"\" : this.DOM.originalInput.value, this.state.loadedOriginalValues = !0\n },\n cloneEvent: function(t) {\n var e = {};\n for (var i in t) e[i] = t[i];\n return e\n },\n loading: function(t) {\n return this.state.isLoading = t, this.DOM.scope.classList[t ? \"add\" : \"remove\"](this.settings.classNames.scopeLoading), this\n },\n tagLoading: function(t, e) {\n return t && t.classList[e ? \"add\" : \"remove\"](this.settings.classNames.tagLoading), this\n },\n toggleFocusClass: function(t) {\n this.DOM.scope.classList.toggle(this.settings.classNames.focus, !!t)\n },\n triggerChangeEvent: function() {\n if (!this.settings.mixMode.integrated) {\n var t = this.DOM.originalInput,\n e = this.state.lastOriginalValueReported !== t.value,\n i = new CustomEvent(\"change\", {\n bubbles: !0\n });\n e && (this.state.lastOriginalValueReported = t.value, i.simulated = !0, t._valueTracker && t._valueTracker.setValue(Math.random()), t.dispatchEvent(i), this.trigger(\"change\", this.state.lastOriginalValueReported), t.value = this.state.lastOriginalValueReported)\n }\n },\n events: p,\n fixFirefoxLastTagNoCaret: function() {},\n placeCaretAfterNode: function(t) {\n if (t) {\n var e = t.nextSibling,\n i = window.getSelection(),\n s = i.getRangeAt(0);\n i.rangeCount && (s.setStartBefore(e || t), s.setEndBefore(e || t), i.removeAllRanges(), i.addRange(s))\n }\n },\n insertAfterTag: function(t, e) {\n if (e = e || this.settings.mixMode.insertAfterTag, t && e) return e = \"string\" == typeof e ? document.createTextNode(e) : e, t.appendChild(e), t.parentNode.insertBefore(e, t.nextSibling), e\n },\n editTag: function(t, e) {\n var i = this;\n t = t || this.getLastTag(), e = e || {}, this.dropdown.hide.call(this);\n var s = this.settings;\n\n function n() {\n return t.querySelector(\".\" + s.classNames.tagText)\n }\n var a = n(),\n o = this.getNodeIndex(t),\n r = this.tagData(t),\n l = this.events.callbacks,\n d = this,\n h = !0;\n if (a) {\n if (!(r instanceof Object && \"editable\" in r) || r.editable) return a.setAttribute(\"contenteditable\", !0), t.classList.add(s.classNames.tagEditing), this.tagData(t, {\n __originalData: c({}, r),\n __originalHTML: t.innerHTML\n }), a.addEventListener(\"focus\", l.onEditTagFocus.bind(this, t)), a.addEventListener(\"blur\", (function() {\n setTimeout((function() {\n return l.onEditTagBlur.call(d, n())\n }))\n })), a.addEventListener(\"input\", l.onEditTagInput.bind(this, a)), a.addEventListener(\"keydown\", (function(e) {\n return l.onEditTagkeydown.call(i, e, t)\n })), a.focus(), this.setRangeAtStartEnd(!1, a), e.skipValidation || (h = this.editTagToggleValidity(t, r.value)), a.originalIsValid = h, this.trigger(\"edit:start\", {\n tag: t,\n index: o,\n data: r,\n isValid: h\n }), this\n } else console.warn(\"Cannot find element in Tag template: .\", s.classNames.tagText)\n },\n editTagToggleValidity: function(t, e) {\n var i, s = t.__tagifyTagData;\n if (s) return i = !(!s.__isValid || 1 == s.__isValid), t.classList.toggle(this.settings.classNames.tagInvalid, i), s.__isValid;\n console.warn(\"tag has no data: \", t, s)\n },\n onEditTagDone: function(t, e) {\n this.state.editing = !1, e = e || {};\n var i = {\n tag: t = t || this.state.editing.scope,\n index: this.getNodeIndex(t),\n data: e\n };\n this.trigger(\"edit:beforeUpdate\", i), delete e.__originalData, delete e.__originalHTML, t && (this.editTagToggleValidity(t), this.replaceTag(t, e)), this.trigger(\"edit:updated\", i), this.dropdown.hide.call(this), this.settings.keepInvalidTags && this.reCheckInvalidTags()\n },\n replaceTag: function(t, e) {\n e && e.value || (e = t.__tagifyTagData), e.__isValid && 1 != e.__isValid && c(e, this.getInvalidTagAttrs(e, e.__isValid));\n var i = this.createTagElem(e);\n t.parentNode.replaceChild(i, t), this.updateValueByDOMTags()\n },\n updateValueByDOMTags: function() {\n var t = this;\n this.value.length = 0, [].forEach.call(this.getTagElms(), (function(e) {\n e.classList.contains(t.settings.classNames.tagNotAllowed) || t.value.push(t.tagData(e))\n })), this.update()\n },\n setRangeAtStartEnd: function(t, e) {\n t = \"number\" == typeof t ? t : !!t, e = (e = e || this.DOM.input).lastChild || e;\n var i = document.getSelection();\n try {\n i.rangeCount >= 1 && [\"Start\", \"End\"].forEach((function(s) {\n return i.getRangeAt(0)[\"set\" + s](e, t || e.length)\n }))\n } catch (t) {\n console.warn(\"Tagify: \", t)\n }\n },\n injectAtCaret: function(t, e) {\n if (e = e || this.state.selection.range) return \"string\" == typeof t && (t = document.createTextNode(t)), e.deleteContents(), e.insertNode(t), this.setRangeAtStartEnd(!1, t), this.updateValueByDOMTags(), this.update(), this\n },\n input: {\n set: function() {\n var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : \"\",\n e = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1],\n i = this.settings.dropdown.closeOnSelect;\n this.state.inputText = t, e && (this.DOM.input.innerHTML = t), !t && i && this.dropdown.hide.bind(this), this.input.autocomplete.suggest.call(this), this.input.validate.call(this)\n },\n validate: function() {\n var t = !this.state.inputText || !0 === this.validateTag({\n value: this.state.inputText\n });\n return this.DOM.input.classList.toggle(this.settings.classNames.inputInvalid, !t), t\n },\n normalize: function(t) {\n var e = t || this.DOM.input,\n i = [];\n e.childNodes.forEach((function(t) {\n return 3 == t.nodeType && i.push(t.nodeValue)\n })), i = i.join(\"\\n\");\n try {\n i = i.replace(/(?:\\r\\n|\\r|\\n)/g, this.settings.delimiters.source.charAt(0))\n } catch (t) {}\n return i = i.replace(/\\s/g, \" \"), this.settings.trim && (i = i.replace(/^\\s+/, \"\")), i\n },\n autocomplete: {\n suggest: function(t) {\n if (this.settings.autoComplete.enabled) {\n \"string\" == typeof(t = t || {}) && (t = {\n value: t\n });\n var e = t.value ? \"\" + t.value : \"\",\n i = e.substr(0, this.state.inputText.length).toLowerCase(),\n s = e.substring(this.state.inputText.length);\n e && this.state.inputText && i == this.state.inputText.toLowerCase() ? (this.DOM.input.setAttribute(\"data-suggest\", s), this.state.inputSuggestion = t) : (this.DOM.input.removeAttribute(\"data-suggest\"), delete this.state.inputSuggestion)\n }\n },\n set: function(t) {\n var e = this.DOM.input.getAttribute(\"data-suggest\"),\n i = t || (e ? this.state.inputText + e : null);\n return !!i && (\"mix\" == this.settings.mode ? this.replaceTextWithNode(document.createTextNode(this.state.tag.prefix + i)) : (this.input.set.call(this, i), this.setRangeAtStartEnd()), this.input.autocomplete.suggest.call(this), this.dropdown.hide.call(this), !0)\n }\n }\n },\n getTagIdx: function(t) {\n return this.value.findIndex((function(e) {\n return JSON.stringify(e) == JSON.stringify(t)\n }))\n },\n getNodeIndex: function(t) {\n var e = 0;\n if (t)\n for (; t = t.previousElementSibling;) e++;\n return e\n },\n getTagElms: function() {\n for (var t = arguments.length, e = new Array(t), i = 0; i < t; i++) e[i] = arguments[i];\n var s = [\".\" + this.settings.classNames.tag].concat(e).join(\".\");\n return [].slice.call(this.DOM.scope.querySelectorAll(s))\n },\n getLastTag: function() {\n var t = this.DOM.scope.querySelectorAll(\".\".concat(this.settings.classNames.tag, \":not(.\").concat(this.settings.classNames.tagHide, \"):not([readonly])\"));\n return t[t.length - 1]\n },\n tagData: function(t, e) {\n return t ? (e && (t.__tagifyTagData = c({}, t.__tagifyTagData || {}, e)), t.__tagifyTagData) : (console.warn(\"tag elment doesn't exist\", t, e), e)\n },\n isTagDuplicate: function(t, e) {\n var i = this,\n s = this.settings;\n return \"select\" != s.mode && this.value.reduce((function(n, a) {\n return o(i.trim(\"\" + t), a.value, e || s.dropdown.caseSensitive) ? n + 1 : n\n }), 0)\n },\n getTagIndexByValue: function(t) {\n var e = this,\n i = [];\n return this.getTagElms().forEach((function(s, n) {\n o(e.trim(s.textContent), t, e.settings.dropdown.caseSensitive) && i.push(n)\n })), i\n },\n getTagElmByValue: function(t) {\n var e = this.getTagIndexByValue(t)[0];\n return this.getTagElms()[e]\n },\n flashTag: function(t) {\n var e = this;\n t && (t.classList.add(this.settings.classNames.tagFlash), setTimeout((function() {\n t.classList.remove(e.settings.classNames.tagFlash)\n }), 100))\n },\n isTagBlacklisted: function(t) {\n return t = this.trim(t.toLowerCase()), this.settings.blacklist.filter((function(e) {\n return (\"\" + e).toLowerCase() == t\n })).length\n },\n isTagWhitelisted: function(t) {\n return !!this.getWhitelistItem(t)\n },\n getWhitelistItem: function(t, e, i) {\n e = e || \"value\";\n var s, n = this.settings,\n a = (i = i || n.whitelist, n.dropdown.caseSensitive);\n return i.some((function(i) {\n var n = \"string\" == typeof i ? i : i[e];\n if (o(n, t, a)) return s = \"string\" == typeof i ? {\n value: i\n } : i, !0\n })), s || \"value\" != e || \"value\" == n.tagTextProp || (s = this.getWhitelistItem(t, n.tagTextProp, i)), s\n },\n validateTag: function(t) {\n var e = this.settings,\n i = \"value\" in t ? \"value\" : e.tagTextProp,\n s = this.trim(t[i] + \"\");\n return (t[i] + \"\").trim() ? e.pattern && e.pattern instanceof RegExp && !e.pattern.test(s) ? this.TEXTS.pattern : !e.duplicates && this.isTagDuplicate(s, this.state.editing) ? this.TEXTS.duplicate : !(this.isTagBlacklisted(s) || e.enforceWhitelist && !this.isTagWhitelisted(s)) || this.TEXTS.notAllowed : this.TEXTS.empty\n },\n getInvalidTagAttrs: function(t, e) {\n return {\n \"aria-invalid\": !0,\n class: \"\".concat(t.class || \"\", \" \").concat(this.settings.classNames.tagNotAllowed).trim(),\n title: e\n }\n },\n hasMaxTags: function() {\n return this.value.length >= this.settings.maxTags && this.TEXTS.exceed\n },\n setReadonly: function(t) {\n var e = this.settings;\n document.activeElement.blur(), e.readonly = t, this.DOM.scope[(t ? \"set\" : \"remove\") + \"Attribute\"](\"readonly\", !0), \"mix\" == e.mode && (this.DOM.input.contentEditable = !t)\n },\n normalizeTags: function(t) {\n var i = this,\n s = this.settings,\n a = s.whitelist,\n o = s.delimiters,\n r = s.mode,\n l = s.tagTextProp,\n d = [],\n c = !!a && a[0] instanceof Object,\n h = t instanceof Array,\n g = function(t) {\n return (t + \"\").split(o).filter((function(t) {\n return t\n })).map((function(t) {\n return e({}, l, i.trim(t))\n }))\n };\n if (\"number\" == typeof t && (t = t.toString()), \"string\" == typeof t) {\n if (!t.trim()) return [];\n t = g(t)\n } else if (h) {\n var u;\n t = (u = []).concat.apply(u, n(t.map((function(t) {\n return t.value ? t : g(t)\n }))))\n }\n return c && (t.forEach((function(t) {\n var e = d.map((function(t) {\n return t.value\n })),\n s = i.dropdown.filterListItems.call(i, t[l]).filter((function(t) {\n return !e.includes(t.value)\n })),\n n = i.getWhitelistItem(t[l], null, s);\n n && n instanceof Object ? d.push(n) : \"mix\" != r && (null == t.value && (t.value = t[l]), d.push(t))\n })), d.length && (t = d)), t\n },\n parseMixTags: function(t) {\n var e = this,\n i = this.settings,\n s = i.mixTagsInterpolator,\n n = i.duplicates,\n a = i.transformTag,\n o = i.enforceWhitelist,\n r = i.maxTags,\n l = i.tagTextProp,\n d = [];\n return t = t.split(s[0]).map((function(t, i) {\n var c, h, g, u = t.split(s[1]),\n p = u[0],\n f = d.length == r;\n try {\n if (p == +p) throw Error;\n h = JSON.parse(p)\n } catch (t) {\n h = e.normalizeTags(p)[0]\n }\n if (f || !(u.length > 1) || o && !e.isTagWhitelisted(h.value) || !n && e.isTagDuplicate(h.value)) {\n if (t) return i ? s[0] + t : t\n } else a.call(e, h), h[c = h[l] ? l : \"value\"] = e.trim(h[c]), g = e.createTagElem(h), d.push(h), g.classList.add(e.settings.classNames.tagNoAnimation), u[0] = g.outerHTML, e.value.push(h);\n return u.join(\"\")\n })).join(\"\"), this.DOM.input.innerHTML = t, this.DOM.input.appendChild(document.createTextNode(\"\")), this.DOM.input.normalize(), this.getTagElms().forEach((function(t, i) {\n return e.tagData(t, d[i])\n })), this.update({\n withoutChangeEvent: !0\n }), t\n },\n replaceTextWithNode: function(t, e) {\n if (this.state.tag || e) {\n e = e || this.state.tag.prefix + this.state.tag.value;\n var i, s, n = window.getSelection(),\n a = n.anchorNode,\n o = this.state.tag.delimiters ? this.state.tag.delimiters.length : 0;\n return a.splitText(n.anchorOffset - o), i = a.nodeValue.lastIndexOf(e), s = a.splitText(i), t && a.parentNode.replaceChild(t, s), !0\n }\n },\n selectTag: function(t, e) {\n if (!this.settings.enforceWhitelist || this.isTagWhitelisted(e.value)) return this.input.set.call(this, e.value, !0), this.state.actions.selectOption && setTimeout(this.setRangeAtStartEnd.bind(this)), this.getLastTag() ? this.replaceTag(this.getLastTag(), e) : this.appendTag(t), this.value[0] = e, this.trigger(\"add\", {\n tag: t,\n data: e\n }), this.update(), [t]\n },\n addEmptyTag: function(t) {\n var e = c({\n value: \"\"\n }, t || {}),\n i = this.createTagElem(e);\n this.tagData(i, e), this.appendTag(i), this.editTag(i, {\n skipValidation: !0\n })\n },\n addTags: function(t, e) {\n var i = this,\n s = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : this.settings.skipInvalid,\n n = [],\n a = this.settings;\n return t && 0 != t.length ? (t = this.normalizeTags(t), \"mix\" == a.mode ? this.addMixTags(t) : (\"select\" == a.mode && (e = !1), this.DOM.input.removeAttribute(\"style\"), t.forEach((function(t) {\n var e, o = {},\n r = Object.assign({}, t, {\n value: t.value + \"\"\n });\n if ((t = Object.assign({}, r)).__isValid = i.hasMaxTags() || i.validateTag(t), a.transformTag.call(i, t), !0 !== t.__isValid) {\n if (s) return;\n c(o, i.getInvalidTagAttrs(t, t.__isValid), {\n __preInvalidData: r\n }), t.__isValid == i.TEXTS.duplicate && i.flashTag(i.getTagElmByValue(t.value))\n }\n if (t.readonly && (o[\"aria-readonly\"] = !0), e = i.createTagElem(c({}, t, o)), n.push(e), \"select\" == a.mode) return i.selectTag(e, t);\n i.appendTag(e), t.__isValid && !0 === t.__isValid ? (i.value.push(t), i.update(), i.trigger(\"add\", {\n tag: e,\n index: i.value.length - 1,\n data: t\n })) : (i.trigger(\"invalid\", {\n data: t,\n index: i.value.length,\n tag: e,\n message: t.__isValid\n }), a.keepInvalidTags || setTimeout((function() {\n return i.removeTags(e, !0)\n }), 1e3)), i.dropdown.position.call(i)\n })), t.length && e && this.input.set.call(this), this.dropdown.refilter.call(this), n)) : (\"select\" == a.mode && this.removeAllTags(), n)\n },\n addMixTags: function(t) {\n var e, i = this,\n s = this.settings,\n n = this.state.tag.delimiters;\n return s.transformTag.call(this, t[0]), t[0].prefix = t[0].prefix || this.state.tag ? this.state.tag.prefix : (s.pattern.source || s.pattern)[0], e = this.createTagElem(t[0]), this.replaceTextWithNode(e) || this.DOM.input.appendChild(e), setTimeout((function() {\n return e.classList.add(i.settings.classNames.tagNoAnimation)\n }), 300), this.value.push(t[0]), this.update(), !n && setTimeout((function() {\n var t = i.insertAfterTag(e) || e;\n i.placeCaretAfterNode(t)\n }), this.isFirefox ? 100 : 0), this.state.tag = null, this.trigger(\"add\", c({}, {\n tag: e\n }, {\n data: t[0]\n })), e\n },\n appendTag: function(t) {\n var e = this.DOM.scope.lastElementChild;\n e === this.DOM.input ? this.DOM.scope.insertBefore(t, e) : this.DOM.scope.appendChild(t)\n },\n createTagElem: function(t) {\n var e, i = c({}, t, {\n value: d(t.value + \"\")\n });\n return this.settings.readonly && (t.readonly = !0),\n function(t) {\n for (var e, i = document.createNodeIterator(t, NodeFilter.SHOW_TEXT); e = i.nextNode();) e.textContent.trim() || e.parentNode.removeChild(e)\n }(e = this.parseTemplate(\"tag\", [i])), this.tagData(e, t), e\n },\n reCheckInvalidTags: function() {\n var t = this,\n e = this.settings,\n i = \".\".concat(e.classNames.tag, \".\").concat(e.classNames.tagNotAllowed),\n s = this.DOM.scope.querySelectorAll(i);\n [].forEach.call(s, (function(e) {\n var i = t.tagData(e),\n s = e.getAttribute(\"title\") == t.TEXTS.duplicate,\n n = !0 === t.validateTag(i);\n s && n && (i = i.__preInvalidData ? i.__preInvalidData : {\n value: i.value\n }, t.replaceTag(e, i))\n }))\n },\n removeTags: function(t, e, i) {\n var s, n = this;\n t = t && t instanceof HTMLElement ? [t] : t instanceof Array ? t : t ? [t] : [this.getLastTag()], s = t.reduce((function(t, e) {\n return e && \"string\" == typeof e && (e = n.getTagElmByValue(e)), e && t.push({\n node: e,\n idx: n.getTagIdx(n.tagData(e)),\n data: n.tagData(e, {\n __removed: !0\n })\n }), t\n }), []), i = \"number\" == typeof i ? i : this.CSSVars.tagHideTransition, \"select\" == this.settings.mode && (i = 0, this.input.set.call(this)), 1 == s.length && s[0].node.classList.contains(this.settings.classNames.tagNotAllowed) && (e = !0), s.length && this.settings.hooks.beforeRemoveTag(s, {\n tagify: this\n }).then((function() {\n function t(t) {\n t.node.parentNode && (t.node.parentNode.removeChild(t.node), e ? this.settings.keepInvalidTags && this.trigger(\"remove\", {\n tag: t.node,\n index: t.idx\n }) : (this.trigger(\"remove\", {\n tag: t.node,\n index: t.idx,\n data: t.data\n }), this.dropdown.refilter.call(this), this.dropdown.position.call(this), this.DOM.input.normalize(), this.settings.keepInvalidTags && this.reCheckInvalidTags()))\n }\n i && i > 10 && 1 == s.length ? function(e) {\n e.node.style.width = parseFloat(window.getComputedStyle(e.node).width) + \"px\", document.body.clientTop, e.node.classList.add(this.settings.classNames.tagHide), setTimeout(t.bind(this), i, e)\n }.call(n, s[0]) : s.forEach(t.bind(n)), e || (s.forEach((function(t) {\n var e = Object.assign({}, t.data);\n delete e.__removed;\n var i = n.getTagIdx(e);\n i > -1 && n.value.splice(i, 1)\n })), n.update())\n })).catch((function(t) {}))\n },\n removeAllTags: function() {\n this.value = [], \"mix\" == this.settings.mode ? this.DOM.input.innerHTML = \"\" : Array.prototype.slice.call(this.getTagElms()).forEach((function(t) {\n return t.parentNode.removeChild(t)\n })), this.dropdown.position.call(this), \"select\" == this.settings.mode && this.input.set.call(this), this.update()\n },\n postUpdate: function() {\n var t = this.settings.classNames,\n e = \"mix\" == this.settings.mode ? this.settings.mixMode.integrated ? this.DOM.input.textContent : this.DOM.originalInput.value : this.value.length;\n this.DOM.scope.classList.toggle(t.hasMaxTags, this.value.length >= this.settings.maxTags), this.DOM.scope.classList.toggle(t.hasNoTags, !this.value.length), this.DOM.scope.classList.toggle(t.empty, !e)\n },\n update: function(t) {\n var e, i, s = this.DOM.originalInput,\n n = (t || {}).withoutChangeEvent,\n a = (e = this.value, i = [\"__isValid\", \"__removed\"], e.map((function(t) {\n var e = {};\n for (var s in t) i.indexOf(s) < 0 && (e[s] = t[s]);\n return e\n })));\n this.settings.mixMode.integrated || (s.value = \"mix\" == this.settings.mode ? this.getMixedTagsAsString(a) : a.length ? this.settings.originalInputValueFormat ? this.settings.originalInputValueFormat(a) : JSON.stringify(a) : \"\"), this.postUpdate(), !n && this.state.loadedOriginalValues && this.triggerChangeEvent()\n },\n getMixedTagsAsString: function() {\n var t = \"\",\n e = this,\n i = this.settings.mixTagsInterpolator;\n return function s(n) {\n n.childNodes.forEach((function(n) {\n if (1 == n.nodeType) {\n if (n.classList.contains(e.settings.classNames.tag) && e.tagData(n)) {\n if (e.tagData(n).__removed) return;\n return void(t += i[0] + JSON.stringify(n.__tagifyTagData) + i[1])\n }\n \"BR\" != n.tagName || n.parentNode != e.DOM.input && 1 != n.parentNode.childNodes.length ? \"DIV\" != n.tagName && \"P\" != n.tagName || (t += \"\\r\\n\", s(n)) : t += \"\\r\\n\"\n } else t += n.textContent\n }))\n }(this.DOM.input), t\n }\n }, f.prototype.removeTag = f.prototype.removeTags, f\n}));" }, { "alpha_fraction": 0.5047129392623901, "alphanum_fraction": 0.596401035785675, "avg_line_length": 32.342857360839844, "blob_id": "b8389877d9f5601f0df19e12dfd54fe4a4bb2424", "content_id": "ce8531cf94b78c2a2f2630181a901a59f3d98a1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1167, "license_type": "no_license", "max_line_length": 111, "num_lines": 35, "path": "/inventory/webInventory/migrations/0006_auto_20200919_0554.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-09-18 21:54\n\nimport datetime\nfrom django.db import migrations, models\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0005_auto_20200919_0553'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='audittrail',\n name='created_on',\n field=models.DateTimeField(default=datetime.datetime(2020, 9, 18, 21, 54, 29, 538384, tzinfo=utc)),\n ),\n migrations.AlterField(\n model_name='item',\n name='created_on',\n field=models.DateTimeField(default=datetime.datetime(2020, 9, 18, 21, 54, 29, 537387, tzinfo=utc)),\n ),\n migrations.AlterField(\n model_name='itemfolder',\n name='created_on',\n field=models.DateTimeField(default=datetime.datetime(2020, 9, 18, 21, 54, 29, 536355, tzinfo=utc)),\n ),\n migrations.AlterField(\n model_name='tag',\n name='created_on',\n field=models.DateTimeField(default=datetime.datetime(2020, 9, 18, 21, 54, 29, 537387, tzinfo=utc)),\n ),\n ]\n" }, { "alpha_fraction": 0.5521327257156372, "alphanum_fraction": 0.6042653918266296, "avg_line_length": 22.44444465637207, "blob_id": "36c629c556e463ff7baf7847229ebdca9e8e46da", "content_id": "fd9a055f21b94329d2c02cec06865c9f00144e22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 422, "license_type": "no_license", "max_line_length": 74, "num_lines": 18, "path": "/inventory/webInventory/migrations/0017_audittrail_user_id.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2020-10-19 16:33\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0016_remove_audittrail_user'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='audittrail',\n name='user_id',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5313432812690735, "alphanum_fraction": 0.5880597233772278, "avg_line_length": 18.705883026123047, "blob_id": "46e618254921112cb6e1bc2ec89103342ede1352", "content_id": "b67b93ff8ffd34f3cfdd9966af7fbc3ea8b49529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/inventory/webInventory/migrations/0016_remove_audittrail_user.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2020-10-18 23:19\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0015_profile_created_on'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='audittrail',\n name='user',\n ),\n ]\n" }, { "alpha_fraction": 0.5534883737564087, "alphanum_fraction": 0.604651153087616, "avg_line_length": 22.88888931274414, "blob_id": "cac48d87629c60fcc03cb1029597525b1846d846", "content_id": "010dbb23dc41e586d8fb19ea0a11540f80fd7bc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 94, "num_lines": 18, "path": "/inventory/webInventory/migrations/0009_auto_20200920_0924.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-09-20 01:24\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0008_item_last_update'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='item',\n name='price',\n field=models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.7023835778236389, "alphanum_fraction": 0.7182000279426575, "avg_line_length": 41.358489990234375, "blob_id": "2b3f44f9418f5d1816609c3c6c18cae61a3f83d6", "content_id": "8ccc6ebd141dcaa873fb9e0e4922f3859a14fae1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4489, "license_type": "no_license", "max_line_length": 96, "num_lines": 106, "path": "/inventory/webInventory/models.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User, Group\nfrom datetime import datetime, timedelta\n\n# Create your models here.\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n name = models.CharField(max_length=100, blank=True, null= True)\n emp_id = models.CharField(max_length=100, blank=True, null= True)\n email = models.CharField(max_length=50, blank=True, null= True)\n phone = models.CharField(max_length=50, blank=True, null=True)\n alt_phone = models.CharField(max_length=50, blank=True, null=True)\n address = models.CharField(max_length=200, blank=True, null=True)\n created_on = models.DateTimeField(default=datetime.now, null=True, blank=True)\n role = models.CharField(max_length=2, blank=True, null=True)\n\n def __str__(self):\n return self.name\n\n\nclass companyInformation(models.Model):\n companyName = models.CharField(max_length=250, blank=True, null=True)\n barcodeType = models.CharField(max_length=20, blank=True, null=True)\n companyPrefix = models.CharField(max_length=6, blank=True, null=True)\n logo = models.ImageField(null=True, blank=True, upload_to='logo/')\n\n def __str__(self):\n return self.companyName\n\n\nclass UserCompany(models.Model):\n company = models.ForeignKey(companyInformation, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n assigned_date = models.DateTimeField(default=datetime.now)\n\n\n\nclass ItemFolder(models.Model):\n name = models.CharField(max_length=30, blank=True, null= True)\n barcode = models.BigIntegerField(null=True, blank=True, default=0)\n description = models.CharField(max_length=500, null=True, blank=True)\n created_on = models.DateTimeField(default=datetime.now)\n created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING)\n created_by_name = models.CharField(max_length=100, blank=True, null= True)\n\n def __str__(self):\n return self.name\n\nclass Item(models.Model):\n itemFolder = models.ForeignKey(ItemFolder, on_delete=models.CASCADE, null= True, blank=True)\n name = models.CharField(max_length=60, null=True, blank=True)\n sku = models.CharField(max_length=7, null=True, blank=True)\n barcode = models.BigIntegerField(null=True, blank=True, default=0)\n description = models.CharField(max_length=500, null=True, blank=True)\n price = models.DecimalField(max_digits= 12, decimal_places= 2, null=True, blank= True)\n quantity = models.IntegerField(null=True, blank=True, default=0)\n minQuantity = models.IntegerField(null=True, blank=True, default=0)\n created_on = models.DateTimeField(default=datetime.now)\n last_update = models.DateTimeField(null=True, blank=True)\n created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True)\n\n def __str__(self):\n return self.name\n\nclass Tag(models.Model):\n name = models.CharField(max_length=50, blank=True, null= True)\n created_on = models.DateTimeField(default=datetime.now)\n created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True)\n created_by_name = models.CharField(max_length=100, blank=True, null=True)\n def __str__(self):\n return self.name\n\n\n\nclass ItemTag(models.Model):\n item = models.ForeignKey(Item, on_delete=models.CASCADE, null= True, blank= True)\n tag = models.ForeignKey(Tag, on_delete=models.CASCADE, null= True, blank= True)\n\n\nclass AuditTrail(models.Model):\n action = models.CharField(max_length=50, blank=True, null= True)\n what = models.CharField(max_length=100, blank=True, null= True)\n how_many = models.CharField(max_length=100, blank=True, null= True)\n action_from = models.CharField(max_length=100, blank=True, null=True)\n action_to = models.CharField(max_length=100, blank=True, null=True)\n user_id = models.CharField(max_length=100, blank=True, null=True)\n profile_name = models.CharField(max_length=100, null= True, blank=True)\n created_on = models.DateTimeField(default=datetime.now)\n\n\nclass Role(models.Model):\n name = models.CharField(max_length=100, null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n\nclass UserRole(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n role = models.ForeignKey(Role, on_delete=models.CASCADE)\n created_on = models.DateTimeField(default=datetime.now)\n\n def __str__(self):\n return self.user.username + ' ' + self.role.name" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 18.799999237060547, "blob_id": "3f9274e285712bf41026a92e037c749d8949f4d0", "content_id": "28f4e5a10e8417c2538bcfa20f11250376cd2f7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "no_license", "max_line_length": 36, "num_lines": 5, "path": "/inventory/webInventory/apps.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass WebinventoryConfig(AppConfig):\n name = 'webInventory'\n" }, { "alpha_fraction": 0.554347813129425, "alphanum_fraction": 0.5916149020195007, "avg_line_length": 29.66666603088379, "blob_id": "cfda40f017f9532091f8e93d1251ea17cd60dcf9", "content_id": "c4c50b3ff58d7b43e4a34c5a0ead03c119467466", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 644, "license_type": "no_license", "max_line_length": 114, "num_lines": 21, "path": "/inventory/webInventory/migrations/0019_companyinformation.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2020-11-23 23:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0018_profile_role'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='companyInformation',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('companyName', models.CharField(blank=True, max_length=250, null=True)),\n ('barcodeType', models.CharField(blank=True, max_length=20, null=True)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5523316264152527, "alphanum_fraction": 0.5844559669494629, "avg_line_length": 27.382352828979492, "blob_id": "fc9573e82423d7d35114d2b4e74e3e08d287c7de", "content_id": "e2ddfe61a5b996751f42581c2d4196d0b27dca38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 965, "license_type": "no_license", "max_line_length": 70, "num_lines": 34, "path": "/inventory/webInventory/migrations/0007_auto_20200919_0601.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-09-18 22:01\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0006_auto_20200919_0554'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='audittrail',\n name='created_on',\n field=models.DateTimeField(default=datetime.datetime.now),\n ),\n migrations.AlterField(\n model_name='item',\n name='created_on',\n field=models.DateTimeField(default=datetime.datetime.now),\n ),\n migrations.AlterField(\n model_name='itemfolder',\n name='created_on',\n field=models.DateTimeField(default=datetime.datetime.now),\n ),\n migrations.AlterField(\n model_name='tag',\n name='created_on',\n field=models.DateTimeField(default=datetime.datetime.now),\n ),\n ]\n" }, { "alpha_fraction": 0.5174672603607178, "alphanum_fraction": 0.5240174531936646, "avg_line_length": 23.13157844543457, "blob_id": "16553ab913aa2f886c406cbe34d2b686614a1484", "content_id": "708c24e029673e657d90fb6baaaea5d87d667d1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 916, "license_type": "no_license", "max_line_length": 85, "num_lines": 38, "path": "/inventory/webInventory/static/webInventory/js/auditTrail.js", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "$(function (){\n console.log(\"Audit Trail\")\n /*Highhlight the current page in NavBar*/\n $('.nav-link').each(function(index){\n if (index == 0) {\n $(this).addClass('active'); $(this).parents('li').addClass('active');\n }\n });\n\n /*Adjust side of SideBar*/\n body = $('body').height()/1.4\n $('.bodyNav').css('height', body)\n /*End Adjust side of SideBar*/\n\n\n var auditTrail = $('.auditTable').DataTable({\n bFilter: true,\n bInfo: false,\n bLengthChange: true,\n bSort: true,\n pageLength: 10,\n language: { searchPlaceholder: \"Keywords..\"},\n });\n\n $('input[type=search], input[type=date]').add('select').on('focus', function (){\n\n $(this).css('border', '3px solid powderblue')\n });\n\n $('select').add('input[type=search]').on('blur focusOut', function (){\n $(this).css('border', '')\n });\n\n\n\n\n\n})" }, { "alpha_fraction": 0.5890052318572998, "alphanum_fraction": 0.6004283428192139, "avg_line_length": 52.871795654296875, "blob_id": "30837af2d7bf276a12e58b5a6dbe94ee9825c909", "content_id": "791d87e799892f689d15734dfc674334fca7c9f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4202, "license_type": "no_license", "max_line_length": 150, "num_lines": 78, "path": "/inventory/webInventory/migrations/0001_initial.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-09-18 01:56\n\nimport datetime\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='Item',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(blank=True, max_length=60, null=True)),\n ('barcode', models.BigIntegerField(blank=True, default=0, null=True)),\n ('description', models.CharField(blank=True, max_length=500, null=True)),\n ('price', models.DecimalField(blank=True, decimal_places=2, max_digits=6, null=True)),\n ('quantity', models.IntegerField(blank=True, default=0, null=True)),\n ('minQuantity', models.IntegerField(blank=True, default=0, null=True)),\n ('created_on', models.DateTimeField(default=datetime.datetime.now)),\n ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(blank=True, max_length=50, null=True)),\n ('created_on', models.DateTimeField(default=datetime.datetime.now)),\n ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Profile',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(blank=True, max_length=100, null=True)),\n ('emp_id', models.CharField(blank=True, max_length=100, null=True)),\n ('email', models.CharField(blank=True, max_length=50, null=True)),\n ('phone', models.CharField(blank=True, max_length=50, null=True)),\n ('alt_phone', models.CharField(blank=True, max_length=50, null=True)),\n ('address', models.CharField(blank=True, max_length=200, null=True)),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='ItemTag',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('item', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='webInventory.Item')),\n ('tag', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='webInventory.Tag')),\n ],\n ),\n migrations.CreateModel(\n name='ItemFolder',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(blank=True, max_length=30, null=True)),\n ('barcode', models.BigIntegerField(blank=True, default=0, null=True)),\n ('description', models.CharField(blank=True, max_length=500, null=True)),\n ('created_on', models.DateTimeField(default=datetime.datetime.now)),\n ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='item',\n name='itemFolder',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='webInventory.ItemFolder'),\n ),\n ]\n" }, { "alpha_fraction": 0.593478262424469, "alphanum_fraction": 0.6173912882804871, "avg_line_length": 29.66666603088379, "blob_id": "41424cb6aa0ab3c2e7ae11e7aa6c1bf67864f4fa", "content_id": "e5b36905f53dea42feb995e7cfffed4d68a93bb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 920, "license_type": "no_license", "max_line_length": 113, "num_lines": 30, "path": "/inventory/webInventory/migrations/0003_auto_20200919_0454.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-09-18 20:54\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 dependencies = [\n ('webInventory', '0002_audittrail'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='itemfolder',\n name='created_by_name',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n migrations.AlterField(\n model_name='itemfolder',\n name='created_by',\n field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL),\n ),\n migrations.AlterField(\n model_name='profile',\n name='user',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.8217821717262268, "alphanum_fraction": 0.8217821717262268, "avg_line_length": 32.66666793823242, "blob_id": "5045b47a37ec175112f84f692041baf1c998ab70", "content_id": "16a8b2d7bf94ca8161cbe11b074d5bae837e66d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 99, "num_lines": 12, "path": "/inventory/webInventory/admin.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Profile, ItemFolder, Item, Tag, UserRole, Role, companyInformation, UserCompany\n\n# Register your models here.\nadmin.site.register(Profile)\nadmin.site.register(ItemFolder)\nadmin.site.register(Item)\nadmin.site.register(Tag)\nadmin.site.register(Role)\nadmin.site.register(UserRole)\nadmin.site.register(companyInformation)\nadmin.site.register(UserCompany)\n" }, { "alpha_fraction": 0.4880000054836273, "alphanum_fraction": 0.6919999718666077, "avg_line_length": 15.666666984558105, "blob_id": "ee7fc12382e393eebc22800219eb4c02a3c00ea5", "content_id": "eceb86f86105dc9613754aecdffc3e95543dd6b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 250, "license_type": "no_license", "max_line_length": 22, "num_lines": 15, "path": "/requirements.txt", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "asgiref==3.2.10\ncolorama==0.4.3\ndj-database-url==0.5.0\nDjango==3.1.1\ndjango-heroku==0.3.1\ngunicorn==20.0.4\nmysqlclient==2.0.1\nPillow==7.2.0\npsycopg2==2.8.6\npython-barcode==0.13.1\npytz==2020.1\nqrcode==6.1\nsix==1.15.0\nsqlparse==0.3.1\nwhitenoise==5.2.0\n" }, { "alpha_fraction": 0.4728390872478485, "alphanum_fraction": 0.4793303608894348, "avg_line_length": 28.57575798034668, "blob_id": "62c726a9befe55e96a41eb1e059f3e5504ac38fd", "content_id": "98e70915bcd370da6534d3d2e28c9626031a5369", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2927, "license_type": "no_license", "max_line_length": 109, "num_lines": 99, "path": "/inventory/webInventory/static/webInventory/js/tagList.js", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "$(function (){\n console.log(\"Tag List\")\n /*Highhlight the current page in NavBar*/\n $('.nav-link').each(function(){\n if ($(this).prop('href') == window.location.href) {\n $(this).addClass('active'); $(this).parents('li').addClass('active');\n }\n });\n\n /*Adjust side of SideBar*/\n body = $('body').height()/1.4\n $('.bodyNav').css('height', body)\n /*End Adjust side of SideBar*/\n\n $('.btnEditName, .btnDelete').hover(\n function (){\n $(this).css('color', 'gray')\n },\n function (){\n $(this).css('color', 'black')\n }\n\n )\n\n $('[data-toggle=\"tooltip\"]').tooltip();\n\n /*DataTable Declaration*/\n var viewTags = $('#tagList').DataTable({\n bFilter: true,\n bInfo: false,\n bLengthChange: true,\n bSort: true,\n pageLength: 10,\n language: { searchPlaceholder: \"Search..\"},\n });\n\n\n\n $('.addTag').on('click', function (){\n $('.frmAddTag').fadeToggle();\n });\n\n\n $('input[type=search]').add('select').on('focus', function (){\n\n $(this).css('border', '3px solid powderblue')\n });\n\n $('select').add('input[type=search]').on('blur focusOut', function (){\n $(this).css('border', '')\n });\n\n\n\n $('#tagList').on('click', '.btnEditName' ,function (){\n txt = $(this).closest('tr').find('p').text()\n $(this).closest('tr').find('.txtEditTagName').val(txt)\n $(this).closest('tr').find('.txtEditTagName, p').toggle()\n $(this).closest('tr').find('.txtEditTagName, p').focus()\n })\n\n $('#tagList').on('blur focusOut','.txtEditTagName' ,function (){\n if($(this).val() == '') {\n alert(\"Please Enter a Value\")\n $(this).css('border-bottom', '2px solid red')\n }\n else{\n $(this).closest('tr').find('p,.txtEditTagName').toggle();\n $(this).closest('tr').find('p').text($(this).val());\n var db_id = $(this).attr('db_id')\n var txtVal = $(this).val()\n var csrfmiddlewaretoken = $(this).closest('tr').find('input[name=csrfmiddlewaretoken]').val();\n console.log(db_id, txtVal, csrfmiddlewaretoken)\n $.ajax({\n type: 'POST',\n url: 'update/',\n data: {\n update: 'tagNameUpdate',\n id: db_id,\n value: txtVal,\n csrfmiddlewaretoken: csrfmiddlewaretoken,\n }\n })\n }\n });\n\n $('#tagList').on('click','.btnDelete', function (){\n tag_id = $(this).closest('tr').find('.txtEditTagName').attr('db_id')\n $('.deleteOptionId').val(tag_id)\n })\n\n /*For Alert*/\n $(\".alert-success, .alert-danger\").fadeTo(2000, 500).slideUp(500, function(){\n $(\".alert-success\").slideUp(500);\n });\n\n\n\n})" }, { "alpha_fraction": 0.5636792182922363, "alphanum_fraction": 0.6132075190544128, "avg_line_length": 22.55555534362793, "blob_id": "ff183f16302696d74052175c308c19a8037739e4", "content_id": "67a2531fcbf963a12df2431d9de6bbf73395c673", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/inventory/webInventory/migrations/0022_companyinformation_companyprefix.py", "repo_name": "jin-fhg/inventory", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2020-11-26 00:46\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webInventory', '0021_usercompany'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='companyinformation',\n name='companyPrefix',\n field=models.CharField(blank=True, max_length=20, null=True),\n ),\n ]\n" } ]
26
EverardoG/HMC-Research
https://github.com/EverardoG/HMC-Research
0689ab9bd4ae1f9391bbd9de84555d2f7d0eae06
3f92882747b1bc97e66492b1441ce293422d1e25
2748a33d28e8c708c7bc2bd1704b1c8d0f7ddbed
refs/heads/master
2020-03-23T05:44:40.397481
2019-07-01T19:11:31
2019-07-01T19:19:51
141,163,854
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6314378976821899, "alphanum_fraction": 0.6450315713882446, "avg_line_length": 27.845714569091797, "blob_id": "646f56df60633ddc9e5628430faa5e082442f019", "content_id": "d2711371a2691d905da6181b543a5c5b2fa97b10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5223, "license_type": "no_license", "max_line_length": 95, "num_lines": 175, "path": "/day4/iris.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\r\n#\r\n# iris.py\r\n#\r\n#\r\n\r\n#IMPORTANT NOTE: I used the ipybn file to do this assignment. This python file is empty\r\n\r\n\r\nimport numpy as np\r\nfrom sklearn import cross_validation\r\nimport pandas as pd\r\n\r\nprint(\"+++ Start of pandas +++\\n\")\r\n# For Pandas's read_csv, use header=0 when you know row 0 is a header row\r\n# df here is a \"dataframe\":\r\ndf = pd.read_csv('iris.csv', header=0) # read the file\r\ndf.head() # print first five lines\r\ndf.info() # print column details\r\n\r\n# There are many more features to pandas... Too many to cover here\r\n\r\n# One important feature is the conversion from string to numeric datatypes!\r\n# As input features, numpy and scikit-learn need numeric datatypes\r\n# You can define a transformation function, to help out...\r\ndef transform(s):\r\n \"\"\" from string to number\r\n setosa -> 0\r\n versicolor -> 1\r\n virginica -> 2\r\n \"\"\"\r\n d = { 'unknown':-1, 'setosa':0, 'versicolor':1, 'virginica':2 }\r\n return d[s]\r\n\r\n#\r\n# this applies the function transform to a whole column\r\n#\r\ndf['irisname'] = df['irisname'].map(transform) # apply the function to the column\r\n\r\nprint(\"+++ End of pandas +++\\n\")\r\n\r\nprint(\"+++ Start of numpy/scikit-learn +++\")\r\n# Data needs to be in numpy arrays - these next two lines convert to numpy arrays\r\nX_data_full = df.iloc[:,0:4].values # iloc == \"integer locations\" of rows/cols\r\ny_data_full = df[ 'irisname' ].values # individually addressable columns (by name)\r\n\r\n\r\n#\r\n# we can drop the initial (unknown) rows -- if we want to test with known data\r\nX_data_full = X_data_full[9:,:] # 2d array\r\ny_data_full = y_data_full[9:] # 1d column\r\n\r\n\r\n#\r\n# we can scramble the remaining data if we want - only if we know the test set's labels\r\n#\r\nindices = np.random.permutation(len(X_data_full)) # this scrambles the data each time\r\nX_data_full = X_data_full[indices]\r\ny_data_full = y_data_full[indices]\r\n\r\n\r\n\r\n#\r\n# The first nine are our test set - the rest are our training\r\n#\r\nX_test = X_data_full[0:9,0:4] # the final testing data\r\nX_train = X_data_full[9:,0:4] # the training data\r\n\r\ny_test = y_data_full[0:9] # the final testing outputs/labels (unknown)\r\ny_train = y_data_full[9:] # the training outputs/labels (known)\r\n\r\n\r\n\r\n#\r\n# feature engineering...\r\n#\r\n\r\n\r\n# here is where you can re-scale/change column values...\r\n# X_data[:,0] *= 100 # maybe the first column is worth 100x more!\r\n# X_data[:,3] *= 100 # maybe the fourth column is worth 100x more!\r\n\r\n\r\n\r\n\r\n#\r\n# create a kNN model and tune its parameters (just k!)\r\n# here's where you'll loop to run 5-fold (or 10-fold cross validation)\r\n# and loop to see which value of n_neighbors works best (best cv testing-data score)\r\n#\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nknn = KNeighborsClassifier(n_neighbors=1) # 7 is the \"k\" in kNN\r\n\r\n#\r\n# cross-validate (use part of the training data for training - and part for testing)\r\n# first, create cross-validation data (here 3/4 train and 1/4 test)\r\ncv_data_train, cv_data_test, cv_target_train, cv_target_test = \\\r\n cross_validation.train_test_split(X_train, y_train, test_size=0.25) # random_state=0\r\n\r\n# fit the model using the cross-validation data\r\n# typically cross-validation is used to get a sense of how well it works\r\n# and tune any parameters, such as the k in kNN (3? 5? 7? 41?, etc.)\r\nknn.fit(cv_data_train, cv_target_train)\r\nprint(\"KNN cv training-data score:\", knn.score(cv_data_train,cv_target_train))\r\nprint(\"KNN cv testing-data score:\", knn.score(cv_data_test,cv_target_test))\r\n\r\n\r\n\r\n#\r\n# now, train the model with ALL of the training data... and predict the labels of the test set\r\n#\r\n\r\n# this next line is where the full training data is used for the model\r\nknn.fit(X_train, y_train)\r\nprint(\"\\nCreated and trained a knn classifier\") #, knn\r\n\r\n# here are some examples, printed out:\r\nprint(\"iris_X_test's predicted outputs are\")\r\nprint(knn.predict(X_test))\r\n\r\n# and here are the actual labels (iris types)\r\nprint(\"and the actual labels are\")\r\nprint(y_test)\r\n\r\n\r\n#\r\n# here is where you'll more elegantly format the output - for side-by-side comparison\r\n# then paste your results for the unknown irises below\r\n#\r\n\r\n\r\n\r\n\r\n\r\n#\r\n# for testing values typed in\r\n#\r\ndef test_by_hand(knn):\r\n \"\"\" allows the user to enter values and predict the\r\n label using the knn model passed in\r\n \"\"\"\r\n print()\r\n Arr = np.array([[0,0,0,0]]) # correct-shape array\r\n T = Arr[0]\r\n T[0] = float(input(\"sepal length? \"))\r\n T[1] = float(input(\"sepal width? \"))\r\n T[2] = float(input(\"petal length? \"))\r\n T[3] = float(input(\"petal width? \"))\r\n prediction = knn.predict(Arr)[0]\r\n print(\"The prediction is\", prediction)\r\n print()\r\n\r\n\r\n# import sys # easy to add break points...\r\n# sys.exit(0)\r\n\r\n\r\n\"\"\"\r\nComments and results:\r\n\r\nBriefly mention how this went:\r\n + what value of k did you decide on for your kNN?\r\n + how smoothly did this kNN workflow go...\r\n\r\n\r\n\r\nThen, include the predicted labels of the first 9 irises (with \"unknown\" type)\r\nPaste those labels (or both data and labels here)\r\nYou'll have 9 lines:\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n" }, { "alpha_fraction": 0.6259109377861023, "alphanum_fraction": 0.6384615302085876, "avg_line_length": 18.245901107788086, "blob_id": "6c3486f3c17f469d46fd8353494c83ad8ac75c80", "content_id": "c2885f538c332cc1f33b0e497656a38422300a9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "no_license", "max_line_length": 97, "num_lines": 122, "path": "/day4/digits.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\r\n#\r\n# digits.py\r\n#\r\n#\r\n\r\nimport numpy as np\r\nfrom sklearn import cross_validation\r\nimport pandas as pd\r\n\r\n# For Pandas's read_csv, use header=0 when you know row 0 is a header row\r\n# df here is a \"dataframe\":\r\ndf = pd.read_csv('digits.csv', header=0)\r\n\r\n# Convert feature columns as needed...\r\n# You may define a function, to help out:\r\ndef transform(s):\r\n \"\"\" from number to string\r\n \"\"\"\r\n return 'digit ' + str(s)\r\n\r\ndf['label'] = df['64'].map(transform) # apply the function to the column\r\nprint(df['label'])\r\nprint(\"+++ End of pandas +++\\n\")\r\n# import sys\r\n# sys.exit(0)\r\n\r\nprint(\"+++ Start of numpy/scikit-learn +++\")\r\n\r\n# We'll stick with numpy - here's the conversion to a numpy array\r\nX_data = df.iloc[:,0:64].values # iloc == \"integer locations\" of rows/cols\r\ny_data = df[ 'label' ].values # also addressable by column name(s)\r\n\r\n#\r\n# you can divide up your dataset as you see fit here...\r\n#\r\n\r\n\r\n#\r\n# feature display - use %matplotlib to make this work smoothly\r\n#\r\nfrom matplotlib import pyplot as plt\r\n\r\ndef show_digit( Pixels ):\r\n \"\"\" input Pixels should be an np.array of 64 integers (from 0 to 15)\r\n there's no return value, but this should show an image of that\r\n digit in an 8x8 pixel square\r\n \"\"\"\r\n print(Pixels.shape)\r\n Patch = Pixels.reshape((8,8))\r\n plt.figure(1, figsize=(4,4))\r\n plt.imshow(Patch, cmap=plt.cm.gray_r, interpolation='nearest') # cm.gray_r # cm.hot\r\n plt.show()\r\n\r\n# try it!\r\nrow = 3\r\nPixels = X_data[row:row+1,:]\r\nshow_digit(Pixels)\r\nprint(\"That image has the label:\", y_data[row])\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#\r\n# feature engineering...\r\n#\r\n\r\n\r\n\r\n\r\n\r\n#\r\n# here, you'll implement the kNN model\r\n#\r\n\r\n\r\n#\r\n# run cross-validation\r\n#\r\n\r\n\r\n#\r\n# and then see how it does on the two sets of unknown-label data... (!)\r\n#\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\nComments and results:\r\n\r\nBriefly mention how this went:\r\n + what value of k did you decide on for your kNN?\r\n + how smoothly were you able to adapt from the iris dataset to here?\r\n + how high were you able to get the average cross-validation (testing) score?\r\n\r\n\r\n\r\nThen, include the predicted labels of the 12 digits with full data but no label:\r\nPast those labels (just labels) here:\r\nYou'll have 12 lines:\r\n\r\n\r\n\r\n\r\nAnd, include the predicted labels of the 10 digits that are \"partially erased\" and have no label:\r\nMention briefly how you handled this situation!?\r\n\r\nPast those labels (just labels) here:\r\nYou'll have 10 lines:\r\n\r\n\r\n\r\n\"\"\"\r\n" }, { "alpha_fraction": 0.5799319744110107, "alphanum_fraction": 0.6129251718521118, "avg_line_length": 23.81012725830078, "blob_id": "c2942ba7a95f6aa087d978415020fea3cabd81cb", "content_id": "6e6c8b1a64e3061c7775a11d88232a61f1d118de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5880, "license_type": "no_license", "max_line_length": 89, "num_lines": 237, "path": "/day3/hw3pr1.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# hw3pr1.py\n#\n# lab problem - matplotlib tutorial (and a bit of numpy besides...)\n#\n# this asks you to work through the first part of the tutorial at\n# www.labri.fr/perso/nrougier/teaching/matplotlib/\n# + then try the scatter plot, bar plot, and one other kind of \"Other plot\"\n# from that tutorial -- and create a distinctive variation of each\n#\n# include screenshots or saved graphics of your variations of those plots with the names\n# + plot_scatter.png, plot_bar.png, and plot_choice.png\n#\n# Remember to run %matplotlib at your ipython prompt!\n#\n\n#\n# in-class examples...\n#\n\ndef inclass1():\n \"\"\"\n Simple demo of a scatter plot.\n \"\"\"\n import numpy as np\n import matplotlib.pyplot as plt\n\n\n N = 50\n x = np.random.rand(N)\n y = np.random.rand(N)\n colors = np.random.rand(N)\n area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses\n\n plt.scatter(x, y, s=area, c=colors, alpha=0.5)\n plt.show()\n\n\n\n#\n# First example from the tutorial/walkthrough\n#\n\n\n#\n# Feel free to replace this code as you go -- or to comment/uncomment portions of it...\n#\n\ndef example1():\n import numpy as np\n import matplotlib.pyplot as plt\n import matplotlib.cm as cm\n\n X = np.linspace(-np.pi, np.pi, 256, endpoint=True)\n C,S = np.cos(X), np.sin(X)\n\n plt.plot(X,C)\n plt.plot(X,S)\n\n plt.show()\n\n\n\n\n\n\n#\n# Here is a larger example with many parameters made explicit\n#\n\ndef example2():\n import numpy as np\n import matplotlib.pyplot as plt\n import matplotlib.cm as cm\n\n # Create a new figure of size 8x6 points, using 100 dots per inch\n plt.figure(figsize=(8,6), dpi=80)\n\n # Create a new subplot from a grid of 1x1\n plt.subplot(111)\n\n X = np.linspace(-np.pi, np.pi, 256,endpoint=True)\n C,S = np.cos(X), np.sin(X)\n\n # Plot cosine using blue color with a continuous line of width 1 (pixels)\n plt.plot(X, C, color=\"blue\", linewidth=1.0, linestyle=\"-\")\n\n # Plot sine using green color with a continuous line of width 1 (pixels)\n plt.plot(X, S, color=\"green\", linewidth=1.0, linestyle=\"-\")\n\n # Set x limits\n plt.xlim(-4.0,4.0)\n\n # Set x ticks\n plt.xticks(np.linspace(-4,4,9,endpoint=True))\n\n # Set y limits\n plt.ylim(-1.0,1.0)\n\n # Set y ticks\n plt.yticks(np.linspace(-1,1,5,endpoint=True))\n\n # Save figure using 72 dots per inch\n # savefig(\"../figures/exercice_2.png\",dpi=72)\n\n # Show result on screen\n plt.show()\n\ndef import_things():\n \"\"\"This just imports useful libraries\"\"\"\n import numpy as np\n import matplotlib.pyplot as plt\n import matplotlib.cm as cm\n\ndef scatter_plot():\n import numpy as np\n import matplotlib.pyplot as plt\n import matplotlib.cm as cm\n # New figure with white background\n fig = plt.figure(figsize=(6,6), facecolor='white')\n\n # New axis over the whole figure, no frame and a 1:1 aspect ratio\n ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1)\n\n # Number of ring\n n = 50\n size_min = 50\n size_max = 50*50\n\n # Ring position\n P = np.random.uniform(0,1,(n,2))\n\n # Ring colors\n C = np.ones((n,4)) * (0,0,0,1)\n # Alpha color channel goes from 0 (transparent) to 1 (opaque)\n C[:,3] = np.linspace(0,1,n)\n\n # Ring sizes\n S = np.linspace(size_min, size_max, n)\n\n # Scatter plot\n scat = ax.scatter(P[:,0], P[:,1], s=S, lw = 0.5,\n edgecolors = C, facecolors='None')\n\n # Ensure limits are [0,1] and remove ticks\n ax.set_xlim(0,1), ax.set_xticks([])\n ax.set_ylim(0,1), ax.set_yticks([])\n\n plt.show()\n\ndef scatter_challenge():\n \"\"\"This is the code for making the complex scatter starting with the starter code\"\"\"\n import numpy as np\n import matplotlib.pyplot as plt\n import matplotlib.cm as cm\n\n n = 1024\n X = np.random.normal(-1,1,n)\n Y = np.random.normal(-1,1,n)\n\n color = np.arctan2(Y,X)\n\n # plt.scatter(X,Y,color = C,cmap = 'jet')\n ax = plt.subplot(111)\n the_plot = ax.scatter(X,Y,c = color, cmap = 'hsv', alpha = 0.5)\n\n plt.show()\n\ndef bar_challenge():\n \"\"\"This is the code for making the complex bar plot starting with the starter code\"\"\"\n import numpy as np\n import matplotlib.pyplot as plt\n\n n = 12\n X = np.arange(n)\n Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)\n Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)\n\n plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')\n plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')\n\n for x,y in zip(X,Y1):\n plt.text(x, y+0.05, '%.2f' % y, ha='center', va= 'bottom')\n\n for x,y in zip(X,-Y2):\n plt.text(x, y-0.05, '%.2f' % y, ha = 'center', va = 'top')\n\n plt.ylim(-1.25,+1.25)\n plt.show()\n\ndef contour_challenge():\n \"\"\"This is the code for making the contour plot work properly\"\"\"\n import numpy as np\n import matplotlib.pyplot as plt\n def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)\n\n n = 256\n x = np.linspace(-3,3,n)\n y = np.linspace(-3,3,n)\n X,Y = np.meshgrid(x,y)\n\n plt.contourf(X, Y, f(X,Y), 8, alpha=.75, cmap='hot')\n C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidths=.5)\n plt.clabel(C)\n plt.show()\n\ndef neat_scatter():\n import numpy as np\n import matplotlib.pyplot as plt\n\n\n # Compute areas and colors\n N = 1024\n r = np.linspace(0,1,N)\n theta = np.linspace(0,360,N)\n area = 200 * r**2\n\n ax = plt.subplot(111, projection='polar')\n c = ax.scatter(theta, r, c=theta, s=50, cmap='hsv', alpha=0.75)\n\n plt.show()\n\ndef main():\n \"\"\"This is just where all the code goes\"\"\"\n neat_scatter()\n scatter_challenge()\n bar_challenge()\n contour_challenge()\n\nif __name__ == \"__main__\":\n main()\n#\n# using style sheets:\n# # be sure to import matplotlib\n# # list of all of them: matplotlib.style.available\n# # example of using one: matplotlib.style.use( 'seaborn-paper' )\n#\n" }, { "alpha_fraction": 0.6421052813529968, "alphanum_fraction": 0.6526315808296204, "avg_line_length": 18, "blob_id": "9b393a5ff665f866c69b55bfd81a811877383521", "content_id": "040a3492d48b3cd8d3572aecad3425d6c8d08554", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "no_license", "max_line_length": 41, "num_lines": 5, "path": "/day2/tests.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "import re\nfrom copy import deepcopy\n\nif \"## The 5Cs: a list\".startswith(\"##\"):\n print(True)\n" }, { "alpha_fraction": 0.5637173056602478, "alphanum_fraction": 0.5834724307060242, "avg_line_length": 28.211381912231445, "blob_id": "3b219605839d706d7680293a0970501fdf78b482", "content_id": "c4cddacd68ecf6df4a2e05e69437058746d23b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3594, "license_type": "no_license", "max_line_length": 88, "num_lines": 123, "path": "/day1/hw1pr2.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# starting examples for cs35, week2 \"Web as Input\"\n#\n\nimport requests\nimport string\nimport json\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#\n# Problem 2 starter code\n#\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n#\n#\n#\n\ndef apple_api(artist_name):\n \"\"\" \n \"\"\"\n ### Use the search url to get an artist's itunes ID\n search_url = \"https://itunes.apple.com/search\"\n parameters = {\"term\":artist_name,\"entity\":\"musicArtist\",\"media\":\"music\",\"limit\":200}\n result = requests.get(search_url, params=parameters)\n data = result.json()\n\n # save to a local file so we can examine it\n filename_to_save = \"appledata.json\"\n f = open( filename_to_save, \"w\" ) # opens the file for writing\n string_data = json.dumps( data, indent=2 ) # this writes it to a string\n f.write(string_data) # then, writes that string to a file...\n f.close() # and closes the file\n print(\"\\nfile\", filename_to_save, \"written.\")\n\n # Here, you should return the artist id:\n #\n # Note: it's helpful to find the iTunes artistId and return it here\n # (this hasn't been done yet... try it!) \n\n return 42 # This is probably _not_ the correct answer...\n\n\n#\n# \n#\ndef apple_api_lookup(artistId):\n \"\"\" \n Takes an artistId and grabs a full set of that artist's albums.\n \"The Beatles\" has an id of 136975\n \"Kendrick Lamar\" has an id of 368183298\n \"Taylor Swift\" has an id of 159260351\n\n Then saves the results to the file \"appledata_full.json\"\n\n This function is complete, though you'll likely have to modify it\n to write more_productive( , ) ...\n \"\"\"\n lookup_url = \"https://itunes.apple.com/lookup\" \n parameters = {\"entity\":\"album\",\"id\":artistId} \n result = requests.get(lookup_url, params=parameters)\n data = result.json()\n\n # save to a file to examine it...\n filename_to_save=\"appledata_full.json\"\n f = open( filename_to_save, \"w\" ) # opens the file for writing\n string_data = json.dumps( data, indent=2 ) # this writes it to a string\n f.write(string_data) # then, writes that string to a file...\n f.close() # and closes the file\n print(\"\\nfile\", filename_to_save, \"written.\")\n\n # we'll leave the processing to another function...\n return\n\n\n\n#\n#\n#\ndef apple_api_lookup_process():\n \"\"\" example opening and accessing a large appledata_full.json file...\n You'll likely want to do more!\n \"\"\"\n filename_to_read=\"appledata_full.json\"\n f = open( filename_to_read, \"r\" )\n string_data = f.read()\n data = json.loads( string_data )\n print(\"the raw json data is\\n\\n\", data, \"\\n\")\n\n # for live investigation, here's the full data structure\n return data\n\n\n\n#\n# main() for testing problem 2's functions...\n#\ndef main():\n \"\"\" a top-level function for testing things... \"\"\"\n # routine for getting the artistId\n if 0:\n #artistId = apple_api(\"The Beatles\") # should return 136975\n #artistId = apple_api(\"Kendrick Lamar\") # should return 368183298\n #artistId = apple_api(\"Taylor Swift\") # should return 159260351\n print(\"artistId is\", artistId)\n\n if 0:\n apple_api_lookup(368183298)\n data = apple_api_lookup_process()\n\n # more_productive( \"Katy Perry\", \"Steve Perry\" )\n # get each one's id\n # get each one's file\n # compare number of albums! Done!\n # then ask two of your own questions\n\n\n#\n# passing the mic (of control) over to Python here...\n#\nif __name__ == \"__main__\":\n main()\n\n" }, { "alpha_fraction": 0.6308079361915588, "alphanum_fraction": 0.6396200656890869, "avg_line_length": 41.417476654052734, "blob_id": "04dee829d3fa8b91eb6fdbc9bfe750de73c80084", "content_id": "c0c3cd9502dc7cd4dccaac614d1d17e1cf5da1e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8738, "license_type": "no_license", "max_line_length": 163, "num_lines": 206, "path": "/interview_analysis/analyze.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "import string\nimport operator\nimport requests\nfrom os import path\nfrom wordcloud import WordCloud, STOPWORDS\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport numpy as np\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nanalyzer = SentimentIntensityAnalyzer()\nimport random\n\ndef string_conversion(txt_file):\n \"\"\"Take a text file in the same folder as frequency.py and conver it into\n a string\"\"\"\n with open(txt_file, 'r') as myfile:\n data=myfile.read().replace('\\n', ' ')\n return data\n\ndef list_conversion(data_string):\n \"\"\"Take in a string of all of the responses and return a list of all of the responses\"\"\"\n\n data_string = data_string\n c_num = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n response_list = []\n\n response = \"\" #initialize current reponse string\n count = 0\n while count < len(data_string)-1:\n if data_string[count] in c_num:\n if data_string[count+1] == \"/\":\n response_list.append(response)\n response = \"\"\n temp_count = 0 #initialize a new temporary counter\n found = False #set the state of M being found to false\n while found == False: #while M is not found\n if data_string[count+temp_count] == \"M\": #if the next character in the data string is M\n temp_count += 1\n count += temp_count#add the temporary counter to the main counter\n found = True #set the found state to true to break the loop\n temp_count += 1 #add one to the temporary counter\n else:\n response += data_string[count]\n count += 1\n else:\n response += data_string[count]\n count += 1\n return response_list\n\ndef convert_to_word_list(response_list):\n \"\"\"Start with the list of responses where each element is a response and return a list where each element is a nested\n list containing the frequency of a word accross all responses as the first element, and the word as the second\"\"\"\n\n responses = \" \".join(response_list)\n responses = responses.lower()\n for c in string.punctuation:\n responses = responses.replace(c,\"\")\n word_list = responses.split()\n freq_dict = {}\n for word in word_list:\n if word in freq_dict:\n freq_dict[word] += 1\n else:\n freq_dict[word] = 1\n freq_list = []\n for key in freq_dict:\n temp_list = []\n temp_list.append(freq_dict[key])\n temp_list.append(key)\n freq_list.append(temp_list)\n sorted_list = sorted(freq_list, key=lambda entry: entry[0],reverse = True)\n return sorted_list\n\ndef filter_list(sorted_list):\n \"\"\"This takes the sorted list where each element is a nested list where the first element is the number of times a word is used and the second\n is the word itself, and returns a filtered sorted list with all the common words removed\"\"\"\n filtered_list = []\n\n for nested_list in sorted_list:\n if nested_list[1] not in STOPWORDS:\n filtered_list.append(nested_list)\n\n return filtered_list\n\ndef print_n_most_freq(sorted_list, n):\n \"\"\"This takes the list of nested lists of words along with how many times the word was mentioned and prints out\n the n most frequent words, how frequent each word was, and numbers them based on how frequent each was.\"\"\"\n temp_list = sorted_list[0:n]\n count = 1\n for word in temp_list:\n print(str(count)+\": \"+word[1]+\", used \"+ str(word[0]) + \" times\")\n count+=1\n\ndef get_wc_string(data_string):\n \"\"\"Starts with a string that is the direct conversion from the text file and returns a string with no capitalization,\n puncuation, or unnecessary headers\"\"\"\n c_num = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n wc_string = \"\"\n\n count = 0\n while count < len(data_string)-1:\n if data_string[count] in c_num:\n if data_string[count+1] == \"/\":\n temp_count = 0 #initialize a new temporary counter\n found = False #set the state of M being found to false\n while found == False: #while M is not found\n if data_string[count+temp_count] == \"M\": #if the next character in the data string is M\n temp_count += 1\n count += temp_count#add the temporary counter to the main counter\n found = True #set the found state to true to break the loop\n temp_count += 1 #add one to the temporary counter\n else:\n wc_string += data_string[count]\n count += 1\n else:\n wc_string += data_string[count]\n count += 1\n wc_string = wc_string.lower()\n for c in string.punctuation:\n wc_string = wc_string.replace(c,\"\")\n return wc_string\n\ndef generate_wordcloud(responses):\n \"\"\"Starts with a string of all the words used in the responses and plots the word clouds of that data\"\"\"\n wordcloud = WordCloud().generate(responses)\n plt.imshow(wordcloud, interpolation = 'bilinear')\n plt.axis(\"off\")\n\n wordcloud = WordCloud(max_font_size = 50).generate(responses)\n plt.figure()\n\n plt.imshow(wordcloud,interpolation='bilinear')\n plt.axis(\"off\")\n\n plt.show()\n\ndef grey_color_func(word, font_size, position, orientation, random_state=None,\n **kwargs):\n\n return \"hsl(49, 97%, 54%)\"\n\ndef generate_mask_word_cloud(responses, image):\n \"\"\"This will generate a word cloud of the reponses in the shape given\"\"\"\n d = path.dirname(__file__)\n\n image_mask = np.array(Image.open(path.join(d,image)))\n stopwords = set(STOPWORDS)\n stopwords.add(\"said\")\n\n wc = WordCloud(background_color=\"green\", max_words=2000, mask=image_mask,stopwords = stopwords,max_font_size = 160)\n\n wc.generate(responses)\n #wc.to_file(path.join(d,\"word_heart.png\"))\n plt.imshow(wc, interpolation = 'bilinear')\n plt.axis(\"off\")\n plt.figure()\n plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3),\n interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.show()\n\ndef find_sent(sentence_list):\n \"\"\"This will take a list of sentences as input. It will return the average sentiment expressed accross all of the sentences.\"\"\"\n total_sentences = len(sentence_list) #the total sentences contained in this list\n total_dict = {'pos':float(0),'neg':float(0),'neu':float(0),'compound':float(0)} #creating a dictionary that will contain all of the totals\n avg_dict = {} #initalize the dictionary to conatin all of the average sentiments\n\n for sentence in sentence_list: #for every sentence that mentions the target word\n sentiment_dict = analyzer.polarity_scores(sentence) #analyze the sentiment expressed in this sentence\n for sentiment in sentiment_dict: #for every sentiment in the dictionary for sentiment\n total_dict[sentiment] += sentiment_dict[sentiment] #add the value for that sentiment to the total value for that sentiment\n\n for sentiment in total_dict: #for every sentiment total in the totals dictionary\n avg_sentiment = total_dict[sentiment] / total_sentences #calculate the average value for that sentiment\n avg_dict[sentiment] = avg_sentiment #append the average sentiment into the average dictionary under the corresponding sentiment key\n\n return avg_dict\n\ndef print_sent(avg_sent):\n \"\"\"This will take the sentiment dictionary containing all of the averages as an input and return the percentage of positive vs negative sentiments expressed\"\"\"\n total = avg_sent['pos'] + avg_sent['neg']\n pos_ratio = avg_sent['pos'] / total\n neg_ratio = avg_sent['neg'] / total\n pos_percent = int(pos_ratio * 100)\n neg_percent = int(neg_ratio * 100)\n\n print(\"positive ratio: \"+str(pos_ratio) + \"\\n\" + \"negative ratio: \" + str(neg_ratio))\n print(\"positive percentage: \"+str(pos_percent)+\"%\" + \"\\n\" + \"negative percentage: \" + str(neg_percent)+\"%\")\n\ndef analyze(questions, images):\n for answers in questions:\n image = images[questions.index(answers)]\n data_string = string_conversion(answers)\n response_list = list_conversion(data_string)\n sorted_list = convert_to_word_list(response_list)\n filtered_list = filter_list(sorted_list)\n avg_sent = find_sent(response_list)\n print_sent(avg_sent)\n print_n_most_freq(filtered_list,20)\n responses = get_wc_string(data_string)\n generate_wordcloud(responses)\n \nif __name__ == '__main__':\n questions = 'q3.txt','q4.txt','q6.txt'\n images = 'plus_mask.jpg','greater_mask1.jpg','division_mask.jpg'\n analyze(questions,images)\n" }, { "alpha_fraction": 0.594792366027832, "alphanum_fraction": 0.6036152243614197, "avg_line_length": 27.863353729248047, "blob_id": "ef701c4da972cc095212efa673ae1c8d9b884fa2", "content_id": "2291b25c2b0f9a7f6bdc33642e10f5d00f838287", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4647, "license_type": "no_license", "max_line_length": 139, "num_lines": 161, "path": "/day1/hw1pr1.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# starting examples for cs35, week1 \"Web as Input\"\n#\n\nimport requests\nimport string\nimport json\n\n\"\"\"\nExamples to run for problem 1:\n\nWeb scraping, the basic command (Thanks, Prof. Medero!)\n\n#\n# basic use of requests:\n#\nurl = \"https://www.cs.hmc.edu/~dodds/demo.html\" # try it + source\nresult = requests.get(url)\ntext = result.text # provides the source as a large string...\n\n#\n# try it for another site...\n#\n\n\n\n\n#\n# let's try the Open Google Maps API -- also provides JSON-formatted data\n# See the webpage for the details and allowable use\n#\n# Try this one by hand - what are its parts?\n# http://maps.googleapis.com/maps/api/distancematrix/json?origins=%22Claremont,%20CA%22&destinations=%22Seattle,%20WA%22&mode=%22walking%22\n#\n# Take a look at the result -- perhaps using this nice site for editing + display:\n#\n# A nice site for json display and editing: https://jsoneditoronline.org/\n#\n#\n\"\"\"\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#\n# Problem 1\n#\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n#\n# example of calling the google distance API\n#\ndef google_api(Sources, Dests):\n \"\"\" Inputs: Sources is a list of starting places\n Dests is a list of ending places\n\n This function uses Google's distances API to find the distances\n from all Sources to all Dests.\n It saves the result to distances.json\n\n Problem: right now it only works with the FIRST of each list!\n \"\"\"\n print(\"Start of google_api\")\n\n url=\"http://maps.googleapis.com/maps/api/distancematrix/json\"\n\n if len(Sources) < 1 or len(Dests) < 1:\n print(\"Sources and Dests need to be lists of >= 1 city each!\")\n return\n\n start = ('|').join(Sources)\n end = ('|').join(Dests)\n my_mode=\"driving\" # walking, biking\n\n inputs={\"origins\":start,\"destinations\":end,\"mode\":my_mode}\n result = requests.get(url,params=inputs)\n print('\\n\\n\\n The json contains\\n',result.text,'\\n\\n\\n')\n data = result.json()\n\n #\n # save this json data to the file named distances.json\n #\n filename_to_save = \"distances.json\"\n f = open( filename_to_save, \"w\" ) # opens the file for writing\n string_data = json.dumps( data, indent=2 ) # this writes it to a string\n f.write(string_data) # then, writes that string to a file\n f.close() # and closes the file\n print(\"\\nFile\", filename_to_save, \"written.\\n\")\n # no need to return anything, since we're better off reading it from file later...\n return\n\n\n\n#\n# example of handling json data via Python's json dictionary\n#\ndef json_process():\n \"\"\" This function reads the json data from \"distances.json\"\n\n It should build a formatted table of all pairwise distances.\n _You_ decide how to format that table (better than JSON!)\n \"\"\"\n filename_to_read = \"distances.json\"\n f = open( filename_to_read, \"r\" )\n string_data = f.read()\n JD = json.loads( string_data ) # JD == \"json dictionary\"\n\n num_starts = len(JD[\"rows\"])\n num_ends = len(JD[\"rows\"][0][\"elements\"])\n\n start_list = JD[\"origin_addresses\"]\n end_list = JD[\"destination_addresses\"]\n\n print(\"Getting some distances:\\n\")\n row_count = 0\n for n in range(num_starts):\n element_count = 0\n print(\"From \"+start_list[row_count])\n\n for m in range(num_ends):\n print(\" ... to \"+end_list[element_count]+\" == \"+JD[\"rows\"][row_count][\"elements\"][element_count][\"distance\"][\"text\"])\n element_count += 1\n\n row_count += 1\n\n print(\"\\nGetting some travel times:\\n\")\n row_count = 0\n for n in range(num_starts):\n element_count = 0\n print(\"From \"+start_list[row_count])\n\n for m in range(num_ends):\n print(\" ... to \"+end_list[element_count]+\" == \"+JD[\"rows\"][row_count][\"elements\"][element_count][\"duration\"][\"text\"])\n element_count += 1\n\n row_count += 1\n\n # we may want to continue operating on the whole json dictionary\n # so, we return it:\n return JD\n\n#\n# a main function for lab problem 1 (the multicity distance problem)\n#\ndef main():\n \"\"\" top-level function for testing problem 1\n \"\"\"\n\n Dests = ['Seattle,WA','Miami,FL','Boston,MA'] # starts\n Sources = ['Claremont,CA','Seattle,WA','Philadelphia,PA'] # ends\n #if 1: # do we want to run the API call?\n google_api(Sources, Dests) # get file\n json_process()\n\n Dests1 = [\"Needham,MA\",\"Saint Louis,MI\"]\n Sources1 = [\"Long Beach,CA\",\"Claremont,CA\"]\n\n google_api(Sources1, Dests1)\n json_process()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6264615654945374, "alphanum_fraction": 0.6313846111297607, "avg_line_length": 25.950000762939453, "blob_id": "3c4f757526ceef4f368846d631e1c5dc51be1820", "content_id": "c0cb29e59a3c7d8088bf97456dcef7badb28a548", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1625, "license_type": "no_license", "max_line_length": 82, "num_lines": 60, "path": "/day5/owndata.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# your own data modeling... \n#\n\nimport numpy as np \nimport pandas as pd\n\nfrom sklearn import tree # for decision trees\nfrom sklearn import ensemble # for random forests\n\ntry: # different imports for different versions of scikit-learn\n from sklearn.model_selection import cross_val_score # simpler cv this week\nexcept ImportError:\n try:\n from sklearn.cross_validation import cross_val_score\n except:\n print(\"No cross_val_score!\")\n\n\n#\n# Let us know which data you're using \n# + and which columns you're considering features/labels!\n#\n\n#\n# This is taken from the titanic example...\n#\nprint(\"+++ Start of pandas' datahandling +++\\n\")\n# df here is a \"dataframe\":\ndf = pd.read_csv('titanic5.csv', header=0) # read the file w/header row #0\n#\n# drop columns here\n#\ndf = df.drop('name', axis=1) # axis = 1 means column\n\ndf.head() # first five lines\ndf.info() # column details\n\n# One important one is the conversion from string to numeric datatypes!\n# You need to define a function, to help out...\ndef tr_mf(s):\n \"\"\" from string to number\n \"\"\"\n d = { 'male':0, 'female':1 }\n return d[s]\n\ndf['sex'] = df['sex'].map(tr_mf) # apply the function to the column\n#\n# end of conversion to numeric data...\n# drop rows with missing data!\ndf = df.dropna()\n#\nprint(\"\\n+++ End of pandas +++\\n\")\n\n#\n\nprint(\"+++ Start of numpy/scikit-learn +++\\n\")\n# Data needs to be in numpy arrays - these next two lines convert to numpy arrays \nX_all = df.drop('survived', axis=1).values \ny_all = df[ 'survived' ].values \n\n\n" }, { "alpha_fraction": 0.6035598516464233, "alphanum_fraction": 0.6278316974639893, "avg_line_length": 25.855072021484375, "blob_id": "af01211ba67e92303dc28884b9d03ebcb5039c13", "content_id": "331614f325f2d1bd7f958b5e8acc47a6dde173b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1854, "license_type": "no_license", "max_line_length": 82, "num_lines": 69, "path": "/day5/titanic5.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# titanic5: modeling the Titanic data with DTs and RFs\n#\n\nimport numpy as np \nimport pandas as pd\n\nfrom sklearn import tree # for decision trees\nfrom sklearn import ensemble # for random forests\n\ntry: # different imports for different versions of scikit-learn\n from sklearn.model_selection import cross_val_score # simpler cv this week\nexcept ImportError:\n try:\n from sklearn.cross_validation import cross_val_score\n except:\n print(\"No cross_val_score!\")\n\n\n#\n# The \"answers\" to the 30 unlabeled passengers:\n#\nanswers = [0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,\n 1,0,1,1,1,1,0,0,0,1,1,0,1,0]\n\n#\n\nprint(\"+++ Start of pandas' datahandling +++\\n\")\n# df here is a \"dataframe\":\ndf = pd.read_csv('titanic5.csv', header=0) # read the file w/header row #0\n#\n# drop columns here\n#\ndf = df.drop('name', axis=1) # axis = 1 means column\n\ndf.head() # first five lines\ndf.info() # column details\n\n# One important one is the conversion from string to numeric datatypes!\n# You need to define a function, to help out...\ndef tr_mf(s):\n \"\"\" from string to number\n \"\"\"\n d = { 'male':0, 'female':1 }\n return d[s]\n\ndf['sex'] = df['sex'].map(tr_mf) # apply the function to the column\n#\n# end of conversion to numeric data...\n# drop rows with missing data!\ndf = df.dropna()\n#\nprint(\"\\n+++ End of pandas +++\\n\")\n\n#\n\nprint(\"+++ Start of numpy/scikit-learn +++\\n\")\n# Data needs to be in numpy arrays - these next two lines convert to numpy arrays \nX_all = df.drop('survived', axis=1).values \ny_all = df[ 'survived' ].values \n\n\n\n#\n# now, building from iris5.py and/or digits5.py\n# create DT and RF models on the Titanic dataset!\n# Goal: find feature importances (\"explanations\")\n# Challenge: can you get over 80% CV accuracy?\n# \n" }, { "alpha_fraction": 0.6048005819320679, "alphanum_fraction": 0.6222572326660156, "avg_line_length": 35.495574951171875, "blob_id": "a417e38eeb53fdaaec5841dada506eeccf1c61bb", "content_id": "4e463554ff98c36368ac312016a1a0caa2884bd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8249, "license_type": "no_license", "max_line_length": 96, "num_lines": 226, "path": "/day1/hw1pr3.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n#\n# Here is an example of using the Web's Wisdom to answer the question\n#\n# Who will win the superbowl next weekend... ?\n#\n# Note: not limited to next weekend's teams!\n# Another note: gambling on future outcomes using this technique _not_ recommended!\n# \n# use/alter main() to find out the results of our predictions! :-)\n#\n\"\"\"\n# 2016:\n# team_1 = 'carolina-panthers' \n# team_2 = 'denver-broncos' \n\n# 2017:\n# team_1 = 'new-england-patriots'\n# team_2 = 'atlanta-falcons'\n\n# 2018:\n# team_1 = 'new-england-patriots'\n# team_2 = 'philadelphia-eagles'\n\n# \n# Here is our \"web scavenging\" approach to the winner and the score:\n#\n# 1. first we grab the pages that define each team's colors\n# 2. then, use bs4 to parse those pages and return a list of colors\n# 3. then, grab the page that defines the popularity of team colors\n# 4. finally, use bs4 to compute a score for each team based on its colors\n#\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n#\n# get_color_page()\n#\ndef get_color_page():\n \"\"\" This function requests the most-popular-colors page\n and parses it with Beautiful Soup, returning the resulting\n Beautiful Soup object, soup\n \"\"\"\n color_popularity_url = \"http://www.thetoptens.com/top-ten-favorite-colors/\"\n response = requests.get(color_popularity_url) # request the page\n\n if response.status_code == 404: # page not found\n print(\"There was a problem with getting the page:\")\n print(color_popularity_url)\n\n data_from_url = response.text # the HTML text from the page\n soup = BeautifulSoup(data_from_url,\"lxml\") # parsed with Beautiful Soup\n return soup\n\n\n\n#\n# find_color_score( color, soup )\n#\ndef find_color_score( color_name, soup ):\n \"\"\" find_color_score takes in color_name (a string represnting a color)\n and soup, a Beautiful Soup object returned from a successful run of\n get_color_page\n \n find_color_score returns our predictive model's number of points in\n a potential match up involving a team with that color\n \n the number of points is 21 - ranking, where ranking is from 1 (most\n popular color) to 20 (least popular color) or 21, representing all\n of the others\n \"\"\"\n ListOfDivs = soup.findAll('div', {'class':\"i\"}) # the class name happens to be 'i' here...\n\n for div in ListOfDivs:\n # print(div.em, div.b) # checking the subtags named em and b\n this_divs_color = div.b.text.lower() # getting the text from them (lowercase)\n this_divs_ranking_as_str = div.em.text # this is the _string_ of the ranking\n \n this_divs_ranking = 21 # the deafult (integer) ranking: 21\n try:\n this_divs_ranking = int(div.em.text) # try to convert it to an integer\n except: # if it fails\n pass # do nothing and leave it at 21\n \n if color_name == this_divs_color: # check if we need to return this one\n return this_divs_ranking\n \n # if we ran through the whole for loop without finding a match, the ranking is 21\n return 21\n\n\n#\n# get_team_colors_page(team)\n#\ndef get_team_colors_page(team):\n \"\"\" get_team_colors_page takes in a string with a \"city-mascot\" formatted team name\n such as atlanta-falcons or carolina-panthers or philadelphia-eagles\n \n it tried to request the appropriate page from teamcolorcodes.com and parse\n it with Beautiful Soup - and it should return that soup object\n \"\"\"\n team_color_url = \"http://teamcolorcodes.com/\" + team + \"-color-codes/\"\n response = requests.get(team_color_url) # request the page\n \n if response.status_code == 404: # page not found\n print(\"For the team\", team, \"There was a problem with getting the page\")\n print(team_color_url)\n \n data_from_url = response.text # the HTML text from the page\n soup = BeautifulSoup(data_from_url,\"lxml\") # parsed with Beautiful Soup\n return soup\n\n\n\n#\n# extract_team_colors( team )\n#\ndef extract_team_colors(soup):\n \"\"\" extract_team_colors takes in a beautiful soup object, soup\n and uses Beautiful Soup to extract a list of all of that team's colors\n \n it return that list of colors\n \n (Note that for different teams, you'll need to run the get_team_colors_page\n to obtain soup objects for each page.)\n \"\"\"\n AllDivs = soup.findAll('div', {'class':\"colorblock\"}) # find all divs of the right class\n \n list_of_team_colors = []\n for div in AllDivs:\n # LoClasses = div.get('class') # get the list of classes for this tag\n # print(\" \",div.text) # debugging line (one of many...)\n # example: RedHex Color: #cc122cRGB: (204,18,44)CMYK: (13,100,93,4)\n if 'Hex' not in div.text: continue # doens't match the above model, skip it\n Words = div.text.split('Hex') \n # splits around 'Hex': ['Red', 'Color: #cc122cRGB: (204,18,44)CMYK: (13,100,93,4)']\n color = Words[0] # the word _before_ 'Hex'\n Words = color.split() # check if there are more than one words in the color\n if len(Words) > 1: color = Words[-1] # if so, the color is the final word!\n # e.g. midnight green -> green\n color = color.lower() # make lower case\n list_of_team_colors.append( color )\n if len(list_of_team_colors) > 2: break # use at most three colors!\n\n # That's it - return the list (hopefully there are some colors!)\n return list_of_team_colors\n\n\n\n#\n# put it all together!\n#\ndef main():\n \"\"\"\n # Here is an example of using the Web's Wisdom to answer the question\n #\n # Who will win the superbowl next weekend... ?\n #\n # Not limited to last weekend's teams!\n \"\"\"\n # 2016\n # team_1 = 'carolina-panthers' \n # team_2 = 'denver-broncos' \n\n # 2017:\n # team_1 = 'new-england-patriots'\n # team_2 = 'atlanta-falcons'\n\n # 2018:\n team_1 = 'new-england-patriots'\n team_2 = 'philadelphia-eagles'\n # team_2 = 'pittsburgh-steelers'\n\n # \n # Here is our \"web scavenging\" approach:\n #\n # 1. first we grab the pages that define each team's colors\n # 2. then, use bs4 to parse those pages and return a list of colors\n # 3. then, grab the page that defines the popularity of team colors\n # 4. finally, use bs4 to compute a score for each team based on its colors\n #\n\n # we get the team colors page for each team\n # and we return a BeautifulSoup \"soup\" object for each!\n team_soup_1 = get_team_colors_page(team_1)\n team_soup_2 = get_team_colors_page(team_2)\n print(\"Done scraping the team colors.\\n\")\n\n # We have a function that actually grabs the colors from the page...\n team_colors_1 = extract_team_colors( team_soup_1 )\n team_colors_2 = extract_team_colors( team_soup_2 )\n print(\"Team 1 (\" + team_1 + \") colors:\", team_colors_1)\n print(\"Team 2 (\" + team_2 + \") colors:\", team_colors_2)\n\n\n # Next, we grab the color-popularity page (and parse it into\n # a BeautifulSoup object...\n # \n color_popularity_soup = get_color_page()\n print(\"\\nDone scraping the color-popularity page.\\n\")\n\n # Finally, we convert the team colors into total scores\n # which will reveal our predicted result\n # Admittedly, our \"points\" are simply the ranking of how popular a color is.\n\n # let's use a list comprehension as a reminder of how those work...\n team_1_scores = [ find_color_score(clr, color_popularity_soup) for clr in team_colors_1 ]\n team_2_scores = [ find_color_score(clr, color_popularity_soup) for clr in team_colors_2 ]\n print(\"Team 1 (\" + team_1 + \") scores:\", team_1_scores)\n print(\"Team 2 (\" + team_2 + \") scores:\", team_2_scores)\n print()\n print(\"Team 1 (\" + team_1 + \") predicted final score:\", sum(team_1_scores))\n print(\"Team 2 (\" + team_2 + \") predicted score:\", sum(team_2_scores))\n\n\n # that's it!\n return\n\n#\n# our conditional, kicking off all execution...\n#\nif __name__ == \"__main__\":\n main() # hike!\n\n" }, { "alpha_fraction": 0.645309567451477, "alphanum_fraction": 0.6699107885360718, "avg_line_length": 32.32432556152344, "blob_id": "3b9a1293130424fa34188785d7d4ed52a9330c97", "content_id": "c068f593de36bcf5178f49dd1ea05d8012e38474", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3699, "license_type": "no_license", "max_line_length": 97, "num_lines": 111, "path": "/day7/digits_nn.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "# !conda update scikit-learn\n\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import fetch_mldata\nfrom sklearn.neural_network import MLPClassifier\n\nimport numpy as np\nimport pandas as pd\n\nprint(\"+++ Start of digits example +++\\n\")\ndf = pd.read_csv('digits.csv',header = 0)\ndf.head()\ndf.info()\n\nprint(\"+++ Converting to numpy arrays... +++\")\n# Data needs to be in numpy arrays - these next two lines convert to numpy arrays\nX_data_complete = df.iloc[:,0:64].values # iloc == \"integer locations\" of rows/cols\ny_data_complete = df[ '64' ].values # individually addressable columns (by name)\n\nX_unknown = X_data_complete[:22,:]\ny_unknown = y_data_complete[:22]\nactual_digits = [0,0,0,1,7,2,3,4,0,1,9,9,5,5,6,5,0,9,8,9,8,4]\n\nX_known = X_data_complete[22:,:]\ny_known = y_data_complete[22:]\n\nKNOWN_SIZE = len(y_known)\nindices = np.random.permutation(KNOWN_SIZE) # this scrambles the data each time\nX_known = X_known[indices]\ny_known = y_known[indices]\n\n#\n# from the known data, create training and testing datasets\n#\nTRAIN_FRACTION = 0.85\nTRAIN_SIZE = int(TRAIN_FRACTION*KNOWN_SIZE)\nTEST_SIZE = KNOWN_SIZE - TRAIN_SIZE # not really needed, but...\nX_train = X_known[:TRAIN_SIZE]\ny_train = y_known[:TRAIN_SIZE]\n\nX_test = X_known[TRAIN_SIZE:]\ny_test = y_known[TRAIN_SIZE:]\n\n#\n# it's important to keep the input values in the 0-to-1 or -1-to-1 range\n# This is done through the \"StandardScaler\" in scikit-learn\n#\nUSE_SCALER = True\nif USE_SCALER == True:\n from sklearn.preprocessing import StandardScaler\n scaler = StandardScaler()\n scaler.fit(X_train) # Fit only to the training dataframe\n # now, rescale inputs -- both testing and training\n X_train = scaler.transform(X_train)\n X_test = scaler.transform(X_test)\n X_unknown = scaler.transform(X_unknown)\n\n# scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html\n#\n# mlp = MLPClassifier(hidden_layer_sizes=(100, 100), max_iter=400, alpha=1e-4,\n# solver='sgd', verbose=10, tol=1e-4, random_state=1)\nmlp = MLPClassifier(hidden_layer_sizes=(100,100), max_iter=200, alpha=1e-4,\n solver='sgd', verbose=True, shuffle=True, early_stopping = False, # tol=1e-4,\n random_state=None, # reproduceability\n learning_rate_init=.03, learning_rate = 'adaptive')\n\nprint(\"\\n\\n++++++++++ TRAINING +++++++++++++++\\n\\n\")\nmlp.fit(X_train, y_train)\n\n\nprint(\"\\n\\n++++++++++++ TESTING +++++++++++++\\n\\n\")\nprint(\"Training set score: %f\" % mlp.score(X_train, y_train))\nprint(\"Test set score: %f\" % mlp.score(X_test, y_test))\n\n# let's see the coefficients -- the nnet weights!\n# CS = [coef.shape for coef in mlp.coefs_]\n# print(CS)\n\n# predictions:\npredictions = mlp.predict(X_test)\nfrom sklearn.metrics import classification_report,confusion_matrix\nprint(\"\\nConfusion matrix:\")\nprint(confusion_matrix(y_test,predictions))\n\nprint(\"\\nClassification report\")\nprint(classification_report(y_test,predictions))\n\n# unknown data rows...\n#\nunknown_predictions = list(mlp.predict(X_unknown))\nprint(\"Unknown predictions:\")\nprint(\" Correct values: \", actual_digits)\nprint(\" Our predictions: \", unknown_predictions)\n\ni = 0\ntotal_right = 0\nfor digit in actual_digits:\n if actual_digits[i] == unknown_predictions[i]:\n total_right += 1\n i += 1\navg_right = total_right/len(actual_digits)\nprint(\"\\nScore on Unkown: \",avg_right*100, \"%\")\n\nif False:\n L = [5.2, 4.1, 1.5, 0.1]\n row = np.array(L) # makes an array-row\n row = row.reshape(1,4) # makes an array of array-row\n if USE_SCALER == True:\n row = scaler.transform(row)\n print(\"\\nrow is\", row)\n print(\"mlp.predict_proba(row) == \", mlp.predict_proba(row))\n" }, { "alpha_fraction": 0.6476351618766785, "alphanum_fraction": 0.650337815284729, "avg_line_length": 33.82352828979492, "blob_id": "bdd019da7cb96ac9b22769b9f8c553e02bf4b87b", "content_id": "33c8d8218c76eb17e341b35de88878d1aa60a44e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2960, "license_type": "no_license", "max_line_length": 103, "num_lines": 85, "path": "/day0/recipes/hw0pr3.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#importing helpful libraries\nimport os\nimport os.path\nimport shutil\n\n#defining useful functions\ndef get_all_txt_files(path = \".\"):\n \"\"\"This function walks through the subdirectories of the given path and returns a list of all\n the text file directories nested in this path as well as text files within the initial directory\"\"\"\n AllFiles = list(os.walk(path)) #getting all files into a data structure\n all_txt_files = []\n file_list = []\n\n for dir_tuple in AllFiles:\n file_list = dir_tuple[2]\n for file_name in file_list:\n if file_name[-3:] == 'txt':\n all_txt_files.append(dir_tuple[0]+'/'+file_name)\n return all_txt_files\n\ndef sweet_or_savory(path = '.'):\n \"\"\"\n Input:\n path - this is the directory the function will sift through\n\n Outputs:\n sweet_list - this is a list of paths for sweet pie recipes\n savory_list - this is a list of paths for savory pie recipes\n mystery_list - this is a list of paths for recipes that could be sweet or savory\n\n This function iterates through all of the recipes in the given directory and\n nested subdirectories. It organizes the recipes accordingly\"\"\"\n all_txt_files = get_all_txt_files(path)\n sweet_words = ['sweet']\n savory_words = ['savory']\n\n sweet_list = []\n savory_list = []\n mystery_list = []\n\n for recipe in all_txt_files:\n f = open(recipe,'r',encoding = 'latin1')\n contents = f.read()\n lower_key_words = contents.lower()\n key_words_list = lower_key_words.split()\n if any(x in sweet_words for x in key_words_list):\n sweet_list.append(recipe)\n elif any(x in savory_words for x in key_words_list):\n savory_list.append(recipe)\n else:\n mystery_list.append(recipe)\n\n return sweet_list, savory_list, mystery_list\n\ndef organize_sweet_savory(sweet_list,savory_list,path='.'):\n \"\"\"\n Inputs:\n sweet_list - list of directories for sweet pie recipes\n savory_list - list of directories for savory pie recipes\n path - directory to organize\n\n Outputs:\n None\n\n This function goes organizes all of the sweet and savory pie recipes into\n respective subdirectories sweet_pie_recipes and savory_pie_recipes\n \"\"\"\n if os.path.exists('./sweet_pie_recipes') == False:\n os.mkdir('./sweet_pie_recipes')\n if os.path.exists('./savory_pie_recipes') == False:\n os.mkdir('./savory_pie_recipes')\n\n for recipe in sweet_list:\n shutil.copyfile(recipe,'./sweet_pie_recipes'+\"/\"+recipe.split(\"/\")[-1])\n for recipe in savory_list:\n shutil.copyfile(recipe,'./savory_pie_recipes'+\"/\"+recipe.split(\"/\")[-1])\n\ndef main():\n \"\"\"This is the main function that runs all relevant code to organize all\n of the pies by sweet or savory to their respective folders.\"\"\"\n list_tuple = sweet_or_savory()\n organize_sweet_savory(list_tuple[0],list_tuple[1])\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6465620994567871, "alphanum_fraction": 0.6614394783973694, "avg_line_length": 20.834861755371094, "blob_id": "3f80334eeedbed78b93ac9088f771215ebf2edd2", "content_id": "6765fcc30a5a56ddc95f56112998014031f497fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2487, "license_type": "no_license", "max_line_length": 97, "num_lines": 109, "path": "/day4/titanic.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\r\n#\r\n# titanic.py\r\n#\r\n#\r\n\r\nimport numpy as np\r\nfrom sklearn import datasets\r\nfrom sklearn import cross_validation\r\nimport pandas as pd\r\n\r\n# For Pandas's read_csv, use header=0 when you know row 0 is a header row\r\n# df here is a \"dataframe\":\r\ndf = pd.read_csv('titanic.csv', header=0)\r\ndf.head()\r\ndf.info()\r\n\r\n# let's drop columns with too few values or that won't be meaningful\r\n# Here's an example of dropping the 'body' column:\r\ndf = df.drop('body', axis=1) # axis = 1 means column\r\n\r\n# let's drop all of the rows with missing data:\r\ndf = df.dropna()\r\n\r\n# let's see our dataframe again...\r\n# I ended up with 1001 rows (anything over 500-600 seems reasonable)\r\ndf.head()\r\ndf.info()\r\n\r\n\r\n\r\n# You'll need conversion to numeric datatypes for all input columns\r\n# Here's one example\r\n#\r\ndef tr_mf(s):\r\n \"\"\" from string to number\r\n \"\"\"\r\n d = { 'male':0, 'female':1 }\r\n return d[s]\r\n\r\ndf['sex'] = df['sex'].map(tr_mf) # apply the function to the column\r\n\r\n# let's see our dataframe again...\r\ndf.head()\r\ndf.info()\r\n\r\n\r\n# you will need others!\r\n\r\n\r\nprint(\"+++ end of pandas +++\\n\")\r\n\r\n# import sys\r\n# sys.exit(0)\r\n\r\nprint(\"+++ start of numpy/scikit-learn +++\")\r\n\r\n# We'll stick with numpy - here's the conversion to a numpy array\r\n\r\n# extract the underlying data with the values attribute:\r\nX_data = df.drop('survived', axis=1).values # everything except the 'survival' column\r\ny_data = df[ 'survived' ].values # also addressable by column name(s)\r\n\r\n#\r\n# you can take away the top 42 passengers (with unknown survival/perish data) here:\r\n#\r\n\r\n\r\n\r\n# feature engineering...\r\n#X_data[:,0] *= 100 # maybe the first column is worth much more!\r\n#X_data[:,3] *= 100 # maybe the fourth column is worth much more!\r\n\r\n\r\n\r\n\r\n#\r\n# the rest of this model-building, cross-validation, and prediction will come here:\r\n# build from the experience and code in the other two examples...\r\n#\r\n\r\n\r\n\r\n\r\n\"\"\"\r\nComments and results:\r\n\r\nBriefly mention how this went:\r\n + what value of k did you decide on for your kNN?\r\n + how high were you able to get the average cross-validation (testing) score?\r\n\r\n\r\n\r\nThen, include the predicted labels of the 12 digits with full data but no label:\r\nPast those labels (just labels) here:\r\nYou'll have 12 lines:\r\n\r\n\r\n\r\n\r\nAnd, include the predicted labels of the 10 digits that are \"partially erased\" and have no label:\r\nMention briefly how you handled this situation!?\r\n\r\nPast those labels (just labels) here:\r\nYou'll have 10 lines:\r\n\r\n\r\n\r\n\"\"\"" }, { "alpha_fraction": 0.600562334060669, "alphanum_fraction": 0.6048626899719238, "avg_line_length": 35.86585235595703, "blob_id": "a185d73efc3b53a95c20bcddb6581cb1cb57fc07", "content_id": "af2387a7f276606b6f15de5233d55c11d0358518", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6046, "license_type": "no_license", "max_line_length": 151, "num_lines": 164, "path": "/interview_analysis/interview_analysis.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "from os import listdir, path\nfrom csv import reader\nfrom string import punctuation\nfrom collections import defaultdict\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport numpy as np\nimport sys\n\nclass data():\n def __init__(self):\n self.interview_directory = sys.argv[1]\n # print(self.interview_direct\n self.interview_csvs = list(filter(lambda x: x[-3:] == \"csv\",listdir(\"./\"+self.interview_directory))) #filter out csv files\n # ^this is a list of all csv files in the same dir as script\n self.num_questions = None\n self.get_num_questions()\n self.notes_list = []\n self.word_frequency_lists = []\n self.filtered_lists = [] #The extended name is filtered_word_frequency_lists\n self.questions_asked = []\n self.stopwords = None\n self.set_stopwords()\n self.extract_all_notes()\n self.extract_questions()\n self.standardize_notes()\n self.sort_words()\n self.filter_words()\n\n def set_stopwords(self):\n self.stopwords = set(STOPWORDS)\n self.stopwords.add(\"thing\")\n self.stopwords.add(\"things\")\n self.stopwords.add(\"stuff\")\n self.stopwords.add('nono')\n self.stopwords.remove('no')\n\n def get_num_questions(self):\n \"\"\"\n This function goes through the csv file and counts how many questions were asked.\n This number is saved as an int in num_questions\n \"\"\"\n\n csv_file = self.read_csv(self.interview_csvs[0])\n num_questions = -1 #initialize num_questions at -1 to compensate for header row\n for row in csv_file:\n if row[1] != '':\n num_questions +=1\n self.num_questions = num_questions\n\n\n def extract_questions(self):\n \"\"\"\n This function stores the questions asked in a list called questions_asked\n \"\"\"\n csv_file = self.read_csv(self.interview_csvs[0])\n for i in range(self.num_questions):\n self.questions_asked.append(csv_file[1+i][1])\n\n def extract_notes(self,question_num):\n \"\"\"\n This function stores the notes taken on a given question in notes_list\n question_num (int): indexing starts at 1, this is the question you want notes on\n\n Returns: None\n \"\"\"\n all_notes = []\n\n for csv_file in self.interview_csvs:\n csv_aslist = self.read_csv(csv_file)\n notes = csv_aslist[question_num][2] + csv_aslist[question_num][3]\n all_notes.append(notes)\n\n self.notes_list.append(all_notes)\n\n def read_csv(self,file):\n \"\"\"\n This function opens a csv file and reads its rows into a list of lists,\n each inner list containing all the info for one row\n \"\"\"\n open_file = open(\"./\"+self.interview_directory+\"/\"+file, newline='')\n file_reader = reader(open_file)\n file_data = []\n for row in file_reader:\n file_data.append(row)\n return file_data\n\n def extract_all_notes(self):\n \"\"\"\n This function iterates through the number of questions asked of interviewees\n and stores the notes taken in notes_list\n num_questions (int): number of quesitons to iterate through\n \"\"\"\n for counter in range(self.num_questions):\n self.extract_notes(counter+1)\n\n def standardize_notes(self):\n \"\"\"\n This function standardizes our notes in notes_list so that we can turn them into word clouds\n \"\"\"\n for note_list in self.notes_list:\n for note in note_list:\n note.lower()\n for c in punctuation:\n note = note.replace(c,\"\")\n\n def sort_words(self):\n \"\"\"\n This function finds the most frequent words used in the notes for all the questions\n n (int): number of most frequent words to find\n \"\"\"\n for note_list in self.notes_list:\n all_notes = \" \".join(note_list)\n word_list = all_notes.split()\n freq_dict = defaultdict(int)\n for word in word_list:\n freq_dict[word] += 1\n freq_list = freq_dict.items()\n sorted_list = sorted(freq_list, key=lambda entry: entry[1],reverse = True)\n self.word_frequency_lists.append(sorted_list)\n\n def filter_words(self):\n \"\"\"\n This function iterates through the list in word_frequency_lists\n and removes any useless words, i.e. a, and, the, etc.\n \"\"\"\n for frequency_list in self.word_frequency_lists:\n filtered_freq_list = []\n for frequency_tuple in frequency_list:\n if frequency_tuple[0] not in self.stopwords:\n filtered_freq_list.append(frequency_tuple)\n self.filtered_lists.append(filtered_freq_list)\n\n def generate_wordcloud(self):\n\n \"\"\"\n This function takes the words and their frequencies and generates a word\n cloud from them\n \"\"\"\n\n image_array = np.array(Image.open('softdes.jpg'))\n image_colors = ImageColorGenerator(image_array)\n # print(image_colors)\n for count,note_list in enumerate(self.notes_list):\n all_notes = \" \".join(note_list)\n wordcloud = WordCloud(stopwords=self.stopwords, mask=image_array, background_color=\"white\", color_func=colour_function).generate(all_notes)\n plt.title(self.questions_asked[count])\n plt.imshow(wordcloud.recolor(color_func=image_colors))\n plt.axis('off')\n plt.savefig(str(count)+\".png\")\n print(\"finished image\"+str(count))\n # plt.show()\n\ndef colour_function(word, font_size, position, orientation, random_state=None,\n **kwargs):\n return \"hsl(198, 100%, 44%)\"\n\nif __name__ == '__main__':\n interview_data = data()\n interview_data.generate_wordcloud()\n # interview_data.generate_wordcloud()\n\n # print(interview_data.filtered_lists[0])\n" }, { "alpha_fraction": 0.6280726194381714, "alphanum_fraction": 0.6496669054031372, "avg_line_length": 31.007352828979492, "blob_id": "9ff5f5adcdde95af5eb8ce34dd7fbe376ec7a400", "content_id": "c1dbfce9aaded5aff02d0bcb44d4c7a7f88374af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4353, "license_type": "no_license", "max_line_length": 130, "num_lines": 136, "path": "/day5/jane.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# digits5: modeling the digits data with DTs and RFs\n#\n\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn import tree # for decision trees\nfrom sklearn import ensemble # for random forests\n\ntry: # different imports for different versions of scikit-learn\n from sklearn.model_selection import cross_val_score # simpler cv this week\nexcept ImportError:\n try:\n from sklearn.cross_validation import cross_val_score\n except:\n print(\"No cross_val_score!\")\n\n#\n# The \"answers\" to the 20 unknown digits, labeled -1:\n#\nall_answers = [9,9,5,5,6,5,0,9,8,9,8,4,0,1,2,3,4,5,6,7]\nanswers = all_answers[0:9]\n\n\nprint(\"+++ Start of pandas' datahandling +++\\n\")\n# df here is a \"dataframe\":\ndf = pd.read_csv('digits5.csv', header=0) # read the file w/header row #0\nprint(df.head())\nprint(df.info())\n# remove_rows = np.linspace(0,19,20)\n# df = df_og.drop(remove_rows)\n# print(df.head())\n# print(df.head()) # first five lines\n# df.info() # column details\nprint(\"\\n+++ End of pandas +++\\n\")\n\n\nprint(\"+++ Start of numpy/scikit-learn +++\\n\")\n# Data needs to be in numpy arrays - these next two lines convert to numpy arrays\nX_all = df.iloc[:,0:64].values # iloc == \"integer locations\" of rows/cols\ny_all = df[ '64' ].values # individually addressable columns (by name)\n\nX_data_full = X_all[0:,:] #\ny_data_full = y_all[0:] #\n\n#This is all of the code for a decision tree classifier\nscores_avgs = []\nmax_depths = []\nfor max_depth in range(1,30):\n # create our classifier\n dtree = tree.DecisionTreeClassifier(max_depth=max_depth)\n #\n # cross-validate to tune our model (this week, all-at-once)\n #\n scores = cross_val_score(dtree, X_data_full, y_data_full, cv=15) #This function separates training and testing data on its own\n average_cv_score = scores.mean()\n scores_avgs.append(average_cv_score)\n max_depths.append(max_depth)\n # print(\"For depth=\", max_depth, \"average CV score = \", average_cv_score)\n\nimport matplotlib.pyplot as plt\nplt.xkcd()\nplt.plot(max_depths,scores_avgs)\nplt.xkcd()\nplt.xlabel('Max Depth')\nplt.xkcd()\nplt.ylabel('Average Score')\n\nplt.show()\nimport matplotlib.pyplot as plt\nplt.xkcd()\nplt.plot(max_depths,scores_avgs)\nplt.xkcd()\nplt.xlabel('Max Depth')\nplt.xkcd()\nplt.ylabel('Average Score')\n\nplt.show()\n# plt.savefig('neat_graph.png')\n\ntry:\n best_depth_ind = scores_avgs.index(max(scores_avgs))[0]\nexcept:\n best_depth_ind = scores_avgs.index(max(scores_avgs))\nbest_depth = max_depths[best_depth_ind]\n\nMAX_DEPTH = best_depth # choose a MAX_DEPTH based on cross-validation...\nprint(\"\\nChoosing MAX_DEPTH =\", MAX_DEPTH, \" at \",max(scores_avgs)*100,'% accuracy')\n\n#Splitting up Training and Testing Data\nX_unknown = X_all[0:9,0:63] # the final testing data\nX_train = X_all[9:,0:63] # the training data\n\ny_unknown = y_all[0:9] # the final testing outputs/labels (unknown)\ny_train = y_all[9:] # the training outputs/labels (known)\n\n# our decision-tree classifier...\ndtree = tree.DecisionTreeClassifier(max_depth=MAX_DEPTH)\ndtree = dtree.fit(X_train, y_train)\n\n#Here we can see how accurate it is\nprint(\"Decision-tree predictions:\\n\")\npredicted_labels = dtree.predict(X_unknown)\nanswer_labels = answers\n#\n# formatted printing! (docs.python.org/3/library/string.html#formatstrings)\n#\ns = \"{0:<11} | {1:<11}\".format(\"Predicted\",\"Answer\")\n# arg0: left-aligned, 11 spaces, string, arg1: ditto\nprint(s)\ns = \"{0:<11} | {1:<11}\".format(\"-------\",\"-------\")\nprint(s)\n# the table...\nfor p, a in zip( predicted_labels, answer_labels ):\n s = \"{0:<11} | {1:<11}\".format(p,a)\n print(s)\n\nfeature_names = []\ntarget_names = []\nfor i in np.linspace(1,63,63):\n feature_names.append(str(i))\nfor i in range(10):\n target_names.append(str(i))\n\n#This is the script saving the best decision tree as a dot file\nfilename = 'tree_for_digits5_depth' + str(max_depth) + '.dot'\ntree.export_graphviz(dtree, out_file=filename, # the filename constructed above...!\n feature_names=feature_names, filled=True,\n rotate=False, # LR vs UD\n class_names=target_names,\n leaves_parallel=True ) # lots of options!\n#\n# now, model from iris5.py to try DTs and RFs on the digits dataset!\n#\n" }, { "alpha_fraction": 0.6965226531028748, "alphanum_fraction": 0.7017913460731506, "avg_line_length": 25.27777862548828, "blob_id": "e9812a318d6ca1f54d05380be363c51235b412d1", "content_id": "613c35570a263b1fe962d1a161d88eb0ce2761f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 949, "license_type": "no_license", "max_line_length": 104, "num_lines": 36, "path": "/day8/hw8/hw9pr2.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "# ## Homework _9_ (not 8): Problem 2, steganography\n# \n# This question asks you to write two functions, likely with some helper functions, that will enable you\n# to embed arbitrary text (string) messages into an image (if there is enough room!)\n\n# For extra credit, the challenge is to be\n# able to extract/embed an image into another image...\n\n#\n# You'll want to borrow from hw8pr1 for\n# + opening the file\n# + reading the pixels\n# + create some helper functions!\n# + also, check out the slides :-) \n#\n# Happy steganographizing, everyone!\n#\n\n\n\n\n\n# Part A: here is a signature for the decoding\n# remember - you will want helper functions!\ndef desteg_string( image ):\n \"\"\" be sure to include a better docstring here! \"\"\"\n pass\n\n\n\n\n# Part B: here is a signature for the encoding/embedding\n# remember - you will want helper functions!\ndef steganographize( image, message ):\n \"\"\" be sure to include a better docstring here! \"\"\"\n pass\n\n\n\n" }, { "alpha_fraction": 0.6430598497390747, "alphanum_fraction": 0.6505860686302185, "avg_line_length": 31.550201416015625, "blob_id": "f0095bca3b1f8212b98bb30ed2c64009d523dfc3", "content_id": "c4d581c77d72c57a047bdfd78771200e91188d66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8105, "license_type": "no_license", "max_line_length": 221, "num_lines": 249, "path": "/day3/hw3pr2.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# hw3pr2.py\n#\n# Person or machine? The rps-string challenge...\n#\n# This file should include your code for\n# + extract_features( rps ), returning a dictionary of features from an input rps string\n# + score_features( dict_of_features ), returning a score (or scores) based on that dictionary\n# + read_data( filename=\"rps.csv\" ), returning the list of datarows in rps.csv\n#\n# Be sure to include a short description of your algorithm in the triple-quoted string below.\n# Also, be sure to include your final scores for each string in the rps.csv file you include,\n# either by writing a new file out or by pasting your results into the existing file\n# And, include your assessment as to whether each string was human-created or machine-created\n#\n#\n\n\"\"\"\nShort description of (1) the features you compute for each rps-string and\n (2) how you score those features and how those scores relate to \"humanness\" or \"machineness\"\n\n\n\n\n\n\"\"\"\n\n\n# Here's how to machine-generate an rps string.\n# You can create your own human-generated ones!\n\nimport random\n\ndef gen_rps_string( num_characters ):\n \"\"\" return a uniformly random rps string with num_characters characters \"\"\"\n result = ''\n for i in range( num_characters ):\n result += random.choice( 'rps' )\n return result\n\n# Here are two example machine-generated strings:\nrps_machine1 = gen_rps_string(200)\nrps_machine2 = gen_rps_string(200)\n# print those, if you like, to see what they are...\nprint(rps_machine1)\nprint(rps_machine2)\n\n#this space is being used to test theories about the machine generated strings\n\ndef analyze(rps_machine_str):\n \"\"\"This function is being used to test some theories about the rps_machine strings\"\"\"\n r_count = len(list(filter(lambda x: x==\"r\",rps_machine_str)))\n p_count = len(list(filter(lambda x: x==\"p\",rps_machine_str)))\n s_count = len(list(filter(lambda x: x==\"s\",rps_machine_str)))\n # print(\"\\n\",\"r count is\",r_count,\"\\n\",\"p count is\",p_count,\"\\n\",\"s count is\",s_count)\n\n try:\n rp_ratio = r_count/p_count\n except:\n rp_ratio = 1000\n try:\n ps_ratio = p_count/s_count\n except:\n ps_ratio = 1000\n try:\n rs_ratio = r_count/s_count\n except:\n rs_ratio = 1000\n # print(\"\\n\",\"rp ratio is\",rp_ratio,\"\\n\",\"ps ratio is\",ps_ratio,\"\\n\",\"rs_ratio is\",rs_ratio)\n return r_count,p_count,s_count,rp_ratio,ps_ratio,rs_ratio\n\ndef get_results(num_iterations = 1000):\n \"\"\"This fuction will generate num_iterations rps strings and save their info to a csv file\"\"\"\n csv_info = []\n # labels = [\"rps_string\",\"r_count\",\"p_count\",\"s_count\",\"rp_ratio\",\"ps_ratio\",\"rs_ratio\"]\n # csv_info.append(labels)\n for i in range(1000):\n rps_machine_str = gen_rps_string(200)\n r_count,p_count,s_count,rp_ratio,ps_ratio,rs_ratio = analyze(rps_machine_str)\n csv_row = [i,r_count,p_count,s_count,rp_ratio,ps_ratio,rs_ratio]\n csv_info.append(csv_row)\n\n return csv_info\n\ndef store_results(csv_info,csv_name = \"results.csv\"):\n \"\"\"\n Inputs:\n csv_info - list of nested lists where each nested list contains important data for one datapoint\n csv_name - name of the csv this function will write to\n Output:\n None\n\n This function takes in a list of nested lists and writes them to a csv file\"\"\"\n import csv\n with open(csv_name,'w') as csvfile:\n writer = csv.writer(csvfile)\n for row in csv_info:\n writer.writerow(row)\n\ndef read_in_csv(csv_name = \"results.csv\"):\n \"\"\"\n Inputs:\n csv_name - directory path to the csv file to be read in\n Output:\n csv_data - data read in from csv file as a list of lists\n\n This function reads in data from a csv file as a list of lists\n \"\"\"\n\n import csv\n csv_data = []\n with open(csv_name) as csv_file:\n reader = csv.reader(csv_file)\n for row in reader:\n csv_data.append(row)\n return csv_data\n\ncsv_info = get_results(100000000)\nstore_results(csv_info)\ncsv_data = read_in_csv()\n\nimport numpy as np\nrp_ratio = []\nps_ratio = []\nrs_ratio = []\n\nfor row in csv_data:\n rp_ratio.append(float(row[4]))\n ps_ratio.append(float(row[5]))\n rs_ratio.append(float(row[6]))\n\nprint(\"\\n\")\nprint(\"max rp_ratio is\", max(rp_ratio))\nprint(\"min rp_ratio is\", min(rp_ratio))\nprint(\"avg rp_ratio is\", np.average(rp_ratio))\nprint(\"standard deviation for rp_ratio is\", np.std(rp_ratio))\n\nprint(\"\\n\")\nprint(\"max ps_ratio is\", max(ps_ratio))\nprint(\"min ps_ratio is\", min(ps_ratio))\nprint(\"avg ps_ratio is\", np.average(ps_ratio))\nprint(\"standard deviation for ps_ratio is\", np.std(ps_ratio))\n\nprint(\"\\n\")\nprint(\"max rs_ratio is\", max(rs_ratio))\nprint(\"min rs_ratio is\", min(rs_ratio))\nprint(\"avg rs_ratio is\", np.average(rs_ratio))\nprint(\"standard deviation for rs_ratio is\", np.std(rs_ratio))\n\n# machine_info = ([max(rp_ratio),min(rp_ratio),np.average(rp_ratio),np.std(rp_ratio)],[max(ps_ratio),min(ps_ratio),np.average(ps_ratio),np.std(ps_ratio)],[max(rs_ratio),min(rs_ratio),np.average(rs_ratio),np.std(rs_ratio)]\nmachine_info = [rp_ratio,ps_ratio,rs_ratio]\ncsv_actual_info = read_in_csv(\"rps18.csv\")\n\ndef classify(rps_str,machine_info,t = 1):\n \"\"\"\n Inputs:\n rps_str - this is an rps string either human or machine generated\n machine_info - simulation generated data on how a machine generates an rps string\n t - the threshold within the rps string is machine\n Outputs:\n True or False - True is Human, False is Machine\n\n This function classifies a string as human generated or machine generated\"\"\"\n rp_ratio_list = machine_info[0]\n ps_ratio_list = machine_info[1]\n rs_ratio_list = machine_info[2]\n\n r_count,p_count,s_count,rp_ratio,ps_ratio,rs_ratio = analyze(rps_str)\n\n if np.average(rp_ratio_list) - t*np.std(rp_ratio_list) <= rp_ratio <= np.average(rp_ratio_list) + t*np.std(rp_ratio_list):\n if np.average(ps_ratio_list) - t*np.std(ps_ratio_list) <= rp_ratio <= np.average(ps_ratio_list) + t*np.std(ps_ratio_list):\n if np.average(rs_ratio_list) - t*np.std(rs_ratio_list) <= rp_ratio <= np.average(rs_ratio_list) + t*np.std(rs_ratio_list):\n return True\n else:\n return False\n else:\n return False\n else:\n return False\n\nM_or_H = []\nfor row in csv_actual_info:\n M_or_H.append(classify(row[1],machine_info))\n\nnum_H = len(list(filter(lambda x: x==True,M_or_H)))\nprint(\"Number of human rps_strings:\",num_H)\nnum_M = len(list(filter(lambda x: x==False,M_or_H)))\nprint(\"Number of machine rps_strings:\",num_M)\n\n\n\n\n# from collections import defaultdict\n#\n# #\n# # extract_features( rps ): extracts features from rps into a defaultdict\n# #\n# def extract_features( rps ):\n# \"\"\" <include a docstring here!>\n# \"\"\"\n# d = defaultdict( float ) # other features are reasonable\n# number_of_s_es = rps.count('s') # counts all of the 's's in rps\n# d['s'] = 42 # doesn't use them, however\n# return d # return our features... this is unlikely to be very useful, as-is\n#\n#\n#\n#\n#\n#\n# #\n# # score_features( dict_of_features ): returns a score based on those features\n# #\n# def score_features( dict_of_features ):\n# \"\"\" <include a docstring here!>\n# \"\"\"\n# d = dict_of_features\n# random_value = random.uniform(0,1)\n# score = d['s'] * random_value\n# return score # return a humanness or machineness score\n#\n#\n#\n#\n#\n#\n#\n# #\n# # read_data( filename=\"rps.csv\" ): gets all of the data from \"rps.csv\"\n# #\n# def read_data( filename=\"rps.csv\" ):\n# \"\"\" <include a docstring here!>\n# \"\"\"\n# # you'll want to look back at reading a csv file!\n# List_of_rows = [] # for now...\n# return List_of_rows\n#\n#\n#\n#\n#\n# #\n# # you'll use these three functions to score each rps string and then\n# # determine if it was human-generated or machine-generated\n# # (they're half and half with one mystery string)\n# #\n# # Be sure to include your scores and your human/machine decision in the rps.csv file!\n# # And include the file in your hw3.zip archive (with the other rows that are already there)\n# #\n" }, { "alpha_fraction": 0.6836363673210144, "alphanum_fraction": 0.7563636302947998, "avg_line_length": 26.5, "blob_id": "a453e2287f90c8608411b0c59feb21657da16945", "content_id": "020fa50ff2f96d40f908293869d7b1fcb61c79bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 55, "num_lines": 10, "path": "/day8/hw8/tests.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "from hw8pr1 import *\n\n\nraw_image1 = cv2.imread('g_dawg.jpeg',cv2.IMREAD_COLOR)\nimage1 = cv2.cvtColor(raw_image1,cv2.COLOR_RGB2BGR)\n\nraw_image2 = cv2.imread('yoda.jpeg',cv2.IMREAD_COLOR)\nimage2 = cv2.cvtColor(raw_image2,cv2.COLOR_RGB2BGR)\n\ntry_two_image_filter(image2,image1)\n" }, { "alpha_fraction": 0.5710822343826294, "alphanum_fraction": 0.5768128633499146, "avg_line_length": 32.11678695678711, "blob_id": "774d2c21752915f2c7624a0899ddb6d835e8b5c9", "content_id": "b96fc54635e8ae07eb0d99a1b18483935a571232", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4537, "license_type": "no_license", "max_line_length": 168, "num_lines": 137, "path": "/day2/hw2pr2.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# starter file for hw1pr2, cs35 spring 2017...\n#\n\nimport csv\nimport numpy\n\n#\n# readcsv is a starting point - it returns the rows from a standard csv file...\n#\ndef readcsv( csv_file_name ):\n \"\"\" readcsv takes as\n + input: csv_file_name, the name of a csv file\n and returns\n + output: a list of lists, each inner list is one row of the csv\n all data items are strings; empty cells are empty strings\n \"\"\"\n try:\n csvfile = open( csv_file_name, newline='' ) # open for reading\n csvrows = csv.reader( csvfile ) # creates a csvrows object\n\n all_rows = [] # we need to read the csv file\n for row in csvrows: # into our own Python data structure\n all_rows.append( row ) # adds only the word to our list\n\n del csvrows # acknowledge csvrows is gone!\n csvfile.close() # and close the file\n return all_rows # return the list of lists\n\n except FileNotFoundError as e:\n print(\"File not found: \", e)\n return []\n\n\n\n#\n# write_to_csv shows how to write that format from a list of rows...\n# + try write_to_csv( [['a', 1 ], ['b', 2]], \"smallfile.csv\" )\n#\ndef write_to_csv( list_of_rows, filename ):\n \"\"\" readcsv takes as\n + input: csv_file_name, the name of a csv file\n and returns\n + output: a list of lists, each inner list is one row of the csv\n all data items are strings; empty cells are empty strings\n \"\"\"\n try:\n csvfile = open( filename, \"w\", newline='' )\n filewriter = csv.writer( csvfile, delimiter=\",\")\n for row in list_of_rows:\n filewriter.writerow( row )\n csvfile.close()\n\n except:\n print(\"File\", filename, \"could not be opened for writing...\")\n\ndef csv_analysis(csv_file=\"wds.csv\"):\n \"\"\"\n Inputs:\n csv_file - csv where each row is some word info, the first element is the word, and the second is the amount of times it shows up\n Outputs:\n rel_freq_dict - this is a dicitonary containing letters of the alphabet as keys and their relative frequency as values\n \"\"\"\n\n csv_list = readcsv(csv_file)\n\n data = numpy.array(csv_list) #turning data into numpy array\n total = numpy.sum(data[:,1].astype(float)) #this is the total amount of times all words are used\n\n # data[:,1] = data[:,1].astype(numpy.float32) #This was an attempt at a more elegant solution, but for whatever reason I can't get all the numbers to be float types\n # print(\"data[:,1] is\\n\",data[:,1])\n #test_count = 0\n letter_dict = {}\n for row in data:\n letter = row[0][0]\n rel_freq = float(row[1])/total\n try:\n letter_dict[letter] += rel_freq\n except:\n letter_dict[letter] = rel_freq\n #test_count += rel_freq #The purpose of test_count was to be sure all the values added up to 1. They do :)\n #print(test_count)\n return letter_dict\n\n#\n# csv_to_html_table_starter\n#\n# Shows off how to create an html-formatted string\n# Some newlines are added for human-readability...\n#\ndef csv_to_html_table_starter( csvdata ):\n \"\"\" csv_to_html_table_starter\n + an example of a function that returns an html-formatted string\n Run with\n + result = csv_to_html_table_starter( \"example_chars.csv\" )\n Then run\n + print(result)\n to see the string in a form easy to copy-and-paste...\n \"\"\"\n # probably should use the readcsv function, above!\n\n csv_file = readcsv(csvdata)\n\n html_string = '<table>\\n' # start with the table tag\n for row in csv_file:\n html_string+=\"<tr>\\n\"\n for element in row:\n html_string += \"<th>\"+element+\"</th>\\n\"\n html_string += \"</tr>\\n\"\n html_string +=\"</table>\\n\"\n\n # html_string += '<tr>\\n'\n #\n #\n # html_string += \"place your table rows and data here!\\n\" # from list_of_rows !\n #\n # html_string += '</tr>\\n'\n html_string += '</table>\\n'\n return html_string\n\n\ndef main():\n \"\"\" run this file as a script \"\"\"\n # LoL = readcsv( \"wds.csv\" )\n # print(LoL[:10])\n #\n # # test writing\n # write_to_csv( LoL[:10], \"tenrows.csv\" )\n #\n # # text csv_to_html_table_starter\n # output_html = csv_to_html_table_starter( \"wds.csv\" )\n # print(\"output_html is\", output_html)\n\n print(csv_analysis())\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6539402604103088, "alphanum_fraction": 0.677924633026123, "avg_line_length": 33.62711715698242, "blob_id": "e2649dbbe934eac72e00429a0ab498ad53dd732e", "content_id": "bf958c7518317f61d7b24bb7f59221f39e29bd46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2043, "license_type": "no_license", "max_line_length": 87, "num_lines": 59, "path": "/day8/hw8/hw8pr2.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "# ## Problem 2: green-screening!\n#\n# This question asks you to write one function that takes in two images:\n# + orig_image (the green-screened image)\n# + new_bg_image (the new background image)\n#\n# It also takes in a 2-tuple (corner = (0,0)) to indicate where to place the upper-left\n# corner of orig_image relative to new_bg_image\n#\n# The challenge is to overlay the images -- but only the non-green pixels of\n# orig_image...\n#\n\n#\n# Again, you'll want to borrow from hw7pr1 for\n# + opening the files\n# + reading the pixels\n# + create some helper functions\n# + defining whether a pixel is green is the key helper function to write!\n# + then, creating an output image (start with a copy of new_bg_image!)\n#\n# Happy green-screening, everyone! Include at least TWO examples of a background!\n#\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport cv2\n\n# Here is a signature for the green-screening...\n# remember - you will want helper functions!\ndef change_location( orig_image, new_bg_image, corner=(0,0) ):\n \"\"\"This takes in two images and splices them together really poorly\"\"\"\n\n height1, width1, channels = orig_image.shape\n height2, width2, channels = new_bg_image.shape\n heights = [height1,height2]\n widths = [width1,width2]\n\n new_image = new_bg_image.copy()\n num_rows, num_cols, num_chans = new_image.shape\n for row in range(min(heights)):\n for col in range(min(widths)):\n r1, g1, b1 = orig_image[row,col]\n r2, g2, b2 = new_bg_image[row,col]\n if r1 < 80 and g1 >150 and b1 < 80:\n new_image[row,col] = [r2 , g2, b2 ]\n else:\n new_image[row,col] = [r1,g1,b1]\n\n return new_image\n\nraw_background = cv2.imread('weird.jpg',cv2.IMREAD_COLOR)\nbackground = cv2.cvtColor(raw_background, cv2.COLOR_BGR2RGB)\n\nraw_foreground = cv2.imread('useful_thing.jpg',cv2.IMREAD_COLOR)\nforeground = cv2.cvtColor(raw_foreground, cv2.COLOR_BGR2RGB)\n\nnew_image = change_location(foreground,background)\nplt.imshow(new_image)\nplt.show()\n" }, { "alpha_fraction": 0.5986374616622925, "alphanum_fraction": 0.6060426831245422, "avg_line_length": 27.854700088500977, "blob_id": "d4ad8d5ac83f22e19b3d54aeeba12c34778b2a61", "content_id": "238a28f83dfcd8dae3ff2d2bc5941f856db3b78c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3376, "license_type": "no_license", "max_line_length": 97, "num_lines": 117, "path": "/day0/hw0pr2.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# hw0pr2.py ~ phonebook analysis\n#\n# Name(s):\n#\n\n#\n# be sure your file runs from this location,\n# relative to the \"phonebook\" directories\n#\n\nimport os\nimport os.path\nimport shutil\n\n\ndef how_many_txt_files(path):\n \"\"\" walks a whole directory structure\n and returns how many txt files are in it!\n\n call it with: how_many_txt_files(\".\")\n\n the (v1) (v2) etc. are different versions, to illustrate\n the process of _trying things out_ and _taking small steps_\n \"\"\"\n # return 42 # just to check that it's working (v1)\n\n AllFiles = list(os.walk(path))\n # print(AllFiles) # just to check out what's up (v2)\n\n print(\"AllFiles has length: \", len(AllFiles), \"\\n\")\n\n for item in AllFiles:\n # print(\"item is\", item, \"\\n\") (v3)\n foldername, LoDirs, LoFiles = item # cool!\n print(\"In\", foldername, \"there are\", end=\" \")\n\n count = 0\n for dir_tuple in AllFiles:\n list_of_files = dir_tuple[2]\n for file_name in list_of_files:\n if file_name[-3:] == \"txt\":\n count += 1\n print(count, \".txt files\")\n return count # fixed!\n\ndef get_depth(path):\n \"\"\"\n This function takes in a file path and spits out how far into the subdirectories\n this path is\n \"\"\"\n return path.count('/')\n\ndef find_deepest_dir(path):\n \"\"\"\n This function walks through an entire directory and all subdirectories\n to find the subdirectory the deepest into the starting path\n \"\"\"\n AllFiles = list(os.walk(path)) #getting all files\n max_depth = 0 #initializing values\n deepest_dir = '.'\n\n for dir_tuple in AllFiles:\n depth = get_depth(dir_tuple[0])\n if depth > max_depth:\n max_depth = depth\n deepest_dir = dir_tuple[0]\n return deepest_dir\n\ndef get_all_txt_files(path = \".\"):\n \"\"\"This function walks through the subdirectories of the given path and returns a list of all\n the text file directories nested in this path\"\"\"\n AllFiles = list(os.walk(path)) #getting all files into a data structure\n all_txt_files = []\n file_list = []\n\n for dir_tuple in AllFiles:\n file_list = dir_tuple[2]\n for file_name in file_list:\n if file_name[-3:] == 'txt':\n all_txt_files.append(dir_tuple[0]+\"/\"+file_name)\n return all_txt_files\n\ndef find_most_digits(path = \".\"):\n \"\"\"\n This function will walk through the given directory and all of its subdirectories\n to find the phone number in the directory with the greatest number of digits\n \"\"\"\n phone_files = list(filter(lambda x: x[2:13] == 'phone_files', all_txt_files))\n most_digits = 0\n longest_number = \"This variable is intentionally left blank\"\n\n for phone_file in phone_files:\n f = open(phone_file,'r',encoding = 'latin1')\n contents = f.read()\n num_digits = count_digits_alt(contents)\n\n if num_digits > most_digits:\n most_digits = num_digits\n longest_number = phone_file\n return longest_number\n\ndef main():\n \"\"\" overall function to run all examples \"\"\"\n\n print(\"Start of main()\\n\")\n\n # num_txt_files = how_many_txt_files(\".\")\n # print(\"num_txt_files in . and all subdirectories is\", num_txt_files)\n\n print(find_deepest_dir('.'),'\\n'*3)\n\n print(\"End of main()\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.8177874088287354, "alphanum_fraction": 0.8199566006660461, "avg_line_length": 152.6666717529297, "blob_id": "0d626a87caa5812c82fa796852e67e9e48ab5a28", "content_id": "fe1c8f2364455e2e5b7c586f7b081a7f42a486e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 461, "license_type": "no_license", "max_line_length": 422, "num_lines": 3, "path": "/interview_analysis/README.md", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "# Interview Analysis for SoftDes Pt2\n\nThis repository is being used to analyze information from interviews conducted for my summer research project with Lydia Hodges and Professor Paul Ruvolo. We aim to take qualitative information about computation at Olin College and turn it into information we can more easily visualize. The overarching purpose of this project is to promote computational skills as part of a common literacy at Olin College and the rest of the world.\n" }, { "alpha_fraction": 0.6305131912231445, "alphanum_fraction": 0.633841872215271, "avg_line_length": 26.730770111083984, "blob_id": "6286e2db3eb33e55b94780f10bbf04a9fd26a52c", "content_id": "6eddab8b1abca72afb48a4b3db639198399ab28d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3605, "license_type": "no_license", "max_line_length": 81, "num_lines": 130, "path": "/day0/hw0pr1b.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# hw0pr1b.py\n#\n\nimport os\nimport os.path\nimport shutil\nimport doctest\n\n# Example 1: How many top-level directories are there in the inclass folder\n#\ndef find_dirs():\n \"\"\" returns the number of directories in the \".\" folder,\n which is the \"inclass folder\"\n \"\"\"\n path = \".\"\n # get ALL contents\n ListOfContents = os.listdir( path )\n print(\"Contents of\", path, \":\")\n print(ListOfContents)\n\n # check for directories\n ListOfDirectories = [] # start empty...\n for item in ListOfContents:\n newpath = path + \"/\" + item # create path name: ./item\n if os.path.isdir( newpath ):\n print(\"Found a directory:\", newpath)\n ListOfDirectories.append( item ) # add to our list!\n\n # yay!\n return ListOfDirectories\n\n# Example 1: How many top-level directories are there in the inclass folder\n#\ndef find_dirs1(path):\n \"\"\" returns the number of directories in the path folder,\n Note how close this is to the above!\n \"\"\"\n # get ALL contents\n ListOfContents = os.listdir( path )\n print(\"Contents of\", path, \":\")\n print(ListOfContents)\n\n # check for directories\n ListOfDirectories = [] # start empty...\n for item in ListOfContents:\n newpath = path + \"/\" + item # create path name: ./item\n if os.path.isdir( newpath ):\n print(\"Found a directory:\", newpath)\n ListOfDirectories.append( item ) # add to our list!\n\n # yay!\n return ListOfDirectories\n\ndef num_top_level_files():\n \"\"\"\n Input: None\n Output: number of files in the day1 folder\n This function counts the number of _files_ present in the top level folder.\n \"\"\"\n list_dir = os.listdir(\".\")\n list_files = list(filter(lambda x: os.path.isfile(x), list_dir))\n num_files = len(list_files)\n return num_files\n\ndef num_top_level_files_arg(directory):\n \"\"\"\n Input: directory - file path for folder\n Output: number of top level files in specified folder\n This function finds the number of top level files in the specified folder\n >>> num_top_level_files_arg(\".\")\n 4\n \"\"\"\n list_dir = os.listdir(directory)\n list_files = list(filter(lambda x: os.path.isfile(x), list_dir))\n num_files = len(list_files)\n return num_files\n\ndef find_most_files(current_dir,most = 0):\n \"\"\"\n Inputs:\n current_dir - the current directory\n most - the current highest number of files in a folder\n Output:\n new_dir - the directory with the highest number of files\n new_most - the highest number of files in a directory\n \"\"\"\n list_dir = os.listdir(current_dir)\n list_files = list(filter(lambda x: os.path.isfile(x), list_dir))\n list_subdir = list(filter(lambda x: os.path.isfile(x) == False, list_dir))\n num_files = len(list_files)\n\n if num_files > most:\n new_most = num_files\n new_dir = os.path.abspath(current_dir)\n print(new_dir)\n\n else:\n new_most = most\n new_dir = current_dir\n\n for subdir in list_subdir:\n find_most_files(subdir,new_most)\n\n return new_dir, new_most\n\n# An example main() function - to keep everything organized!\n#\ndef main():\n \"\"\" main function for organizing -- and printing -- everything \"\"\"\n\n # sign on\n print(\"\\n\\nStart of main()\\n\\n\")\n\n find_most_files(\".\")\n\n # sign off\n print(\"\\n\\nEnd of main()\\n\\n\")\n\n# This conditional will run main() when this file is executed:\n#\nif __name__ == \"__main__\":\n main()\n\n# ++ The challenges: Create and test as many of these five functions as you can.\n#\n# These are the lab challenges:\n\n# hw0pr1b.py\n# Displaying hw0pr1b.py.\n" }, { "alpha_fraction": 0.6008787155151367, "alphanum_fraction": 0.6081628203392029, "avg_line_length": 31.63773536682129, "blob_id": "5e4106895a51a2d0103d25416693fcaf304bbde6", "content_id": "1b2fed75da53d1fe9f0572bfdf93cf4c1df83a4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8649, "license_type": "no_license", "max_line_length": 98, "num_lines": 265, "path": "/day6/hw6pr3movies.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "## Import all of the libraries and data that we will need.\nimport nltk\nimport textblob\nfrom nltk.corpus import names # see the note on installing corpora, above\nfrom nltk.corpus import opinion_lexicon\nfrom nltk.corpus import movie_reviews\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nimport random\nimport math\n\nfrom sklearn.feature_extraction import DictVectorizer\nimport sklearn\nimport sklearn.tree\nfrom sklearn.metrics import confusion_matrix\n\nfrom datamuse import datamuse\nimport itertools\nimport string\napi = datamuse.Datamuse()\n\ndef get_list(dictionary):\n rel_words = []\n for d in dictionary:\n w = d['word']\n rel_words.append(w)\n return rel_words\n\ndef get_antonym(key_word):\n try:\n antonym = get_list(api.words(rel_ant = key_word,max = 1))[0]\n except IndexError:\n antonym = key_word\n return antonym\n\ndef clear_not_ambiguity(TB):\n for sentence in TB.sentences:\n sentence_ind = TB.sentences.index(sentence)\n word_list = sentence.split(\" \")\n for word in word_list:\n if word == 'not':\n w_ind = word_list.index(word)\n ind = w_ind+1\n found_punc = False\n list_ant = []\n\n while found_punc == False:\n key_word = word_list[ind]\n antonym = get_antonym(key_word)\n list_ant.append(antonym)\n ind+=1\n if key_word in string.punctuation:\n found_punc = True\n\n new_words = word_list[0:w_ind] + list_ant + word_list[ind:len(word_list)]\n text_blob_sentence = textblob.TextBlob(' '.join(new_words)).sentences[0]\n TB.sentences[sentence_ind]=text_blob_sentence\n return TB\n\n\n#####################\n#\n## Problem 4: Movie Review Sentiment starter code...\n#\n#####################\n\n# a boolean to turn on/off the movie-review-sentiment portion of the code...\nRUN_MOVIEREVIEW_CLASSIFIER = True\nif RUN_MOVIEREVIEW_CLASSIFIER == True:\n\n ## Read all of the opinion words in from the nltk corpus.\n #\n pos=list(opinion_lexicon.words('positive-words.txt'))\n neg=list(opinion_lexicon.words('negative-words.txt'))\n\n ## Store them as a set (it'll make our feature extractor faster).\n #\n pos_set = set(pos)\n neg_set = set(neg)\n\n\n\n ## Read all of the fileids in from the nltk corpus and shuffle them.\n #\n pos_ids = [(fileid, \"pos\") for fileid in movie_reviews.fileids('pos')[:20]]\n neg_ids = [(fileid, \"neg\") for fileid in movie_reviews.fileids('neg')[:20]]\n labeled_fileids = pos_ids + neg_ids\n\n ## Here, we \"seed\" the random number generator with 0 so that we'll all\n ## get the same split, which will make it easier to compare results.\n random.seed(0) # we'll use the seed for reproduceability...\n random.shuffle(labeled_fileids)\n\n\n\n ## Define the feature function\n # Problem 4's central challenge is to modify this to improve your classifier's performance...\n #\n def opinion_features(fileid):\n \"\"\" starter feature engineering for movie reviews... \"\"\"\n # many features are counts!\n positive_count=0\n negative_count=0\n for word in movie_reviews.words(fileid):\n if word in pos_set:\n positive_count += 1\n elif word in neg_set:\n negative_count += 1\n #Here's some sentiment analysis stuff\n sid = SentimentIntensityAnalyzer()\n\n # Note: movie_reviews.raw(fileid) is the whole review!\n # create a TextBlob with\n rawtext = movie_reviews.raw(fileid)\n TB_amb = textblob.TextBlob( rawtext )\n TB = clear_not_ambiguity(TB_amb)\n # now, you can use TB.words and TB.sentences...\n total_sub = 0 #initializing subjectivity\n total_pol = 0 #initializing polarity\n total_pos = 0\n total_neg = 0\n total_neu = 0\n total_compound = 0\n for sentence in TB.sentences:\n total_sub += sentence.sentiment.polarity\n total_pol += sentence.sentiment.polarity\n ss = sid.polarity_scores(str(sentence))\n total_pos += ss['pos']\n total_neg += ss['neg']\n total_compound += ss['compound']\n total_neu += ss['neu']\n\n avg_sub = total_sub/len(TB.sentences)\n avg_pol = total_pol/len(TB.sentences)\n avg_pos = total_pos/len(TB.sentences)\n avg_neg = total_neg/len(TB.sentences)\n avg_compound = total_compound/len(TB.sentences)\n avg_neu = total_neu/len(TB.sentences)\n\n # here is the dictionary of features...\n features = {} # could also use a default dictionary!\n\n # features['positive'] = positive_count\n # features['negative_count'] = negative_count\n # features['avg_pol'] = avg_pol\n features['avg_sub'] = avg_sub\n features['avg_neg'] = avg_neg\n features['avg_pos'] = avg_pos\n features['avg_compound'] = avg_compound\n features['avg_neu'] = avg_neu\n # try:\n # features['ratio'] = negative_count/positive_count\n # except ZeroDivisionError:\n # features['ratio'] = 1000\n # try:\n # features['ratio'] =avg_neg/avg_pos\n # except ZeroDivisionError:\n # features['ratio'] = 1000\n return features\n\n\n #\n ## Ideas for improving this!\n #\n # count both positive and negative words...\n # is the ABSOUTE count what matters?\n #\n # other ideas:\n #\n # feature ideas from the TextBlob library:\n # * part-of-speech, average sentence length, sentiment score, subjectivity...\n # feature ideas from TextBlob or NLTK (or just Python):\n # average word length\n # number of parentheses in review\n # number of certain punctuation marks in review\n # number of words in review\n # words near or next-to positive or negative words: \"not excellent\" ?\n # uniqueness\n #\n # many others are possible...\n\n\n ## Extract features for all of the movie reviews\n #\n print(\"Creating features for all reviews...\", end=\"\", flush=True)\n features = [opinion_features(fileid) for (fileid, opinion) in labeled_fileids]\n labels = [opinion for (fileid, opinion) in labeled_fileids]\n fileids = [fileid for (fileid, opinion) in labeled_fileids]\n print(\" ... feature-creation done.\", flush=True)\n\n\n ## Change the dictionary of features into an array\n #\n print(\"Transforming from dictionaries of features to vectors...\", end=\"\", flush=True)\n v = DictVectorizer(sparse=False)\n X = v.fit_transform(features)\n print(\" ... vectors completed.\", flush=True)\n\n ## Split the data into train, devtest, and test\n\n X_test = X[:5,:]\n Y_test = labels[:5]\n fileids_test = fileids[:5]\n\n X_devtest = X[5:10,:]\n Y_devtest = labels[5:10]\n fileids_devtest = fileids[1:2]\n\n X_train = X[10:20,:]\n Y_train = labels[10:20]\n fileids_train = fileids[10:20]\n\n ## Train the decision tree classifier - perhaps try others or add parameters\n #\n dt = sklearn.tree.DecisionTreeClassifier()\n dt.fit(X_train,Y_train)\n\n ## Evaluate on the devtest set; report the accuracy and also\n ## show the confusion matrix.\n #\n print(\"Score on devtest set: \", dt.score(X_devtest, Y_devtest))\n Y_guess = dt.predict(X_devtest)\n CM = confusion_matrix(Y_guess, Y_devtest)\n print(\"Confusion Matrix:\\n\", CM)\n\n ## Get a list of errors to examine more closely.\n #\n errors = []\n\n for i in range(len(fileids_devtest)):\n this_fileid = fileids_devtest[i]\n this_features = X_devtest[i:i+1,:]\n this_label = Y_devtest[i]\n guess = dt.predict(this_features)[0]\n if guess != this_label:\n errors.append((this_label, guess, this_fileid))\n\n PRINT_ERRORS = False\n if PRINT_ERRORS == True:\n num_to_print = 15 # #15 is L.A. Confidential\n count = 0\n\n for actual, predicted, fileid in errors:\n print(\"Actual: \", actual, \"Predicted: \", predicted, \"fileid:\", fileid)\n count += 1\n if count > num_to_print: break\n\n PRINT_REVIEW = False\n if PRINT_REVIEW == True:\n print(\"Printing the review with fileid\", fileid)\n text = movie_reviews.raw(fileid)\n print(text)\n\n ## Finally, score on the test set:\n print(\"Score on test set: \", dt.score(X_test, Y_test))\n\n\n #\n # ## Reflections/Analysis\n #\n # Include a short summary of\n # (a) how well your final set of features did!\n # (b) what other features you tried and which ones seemed to\n # help the most/least\n #\n" }, { "alpha_fraction": 0.6203956604003906, "alphanum_fraction": 0.6330150365829468, "avg_line_length": 30.869565963745117, "blob_id": "ac20757f4752055332ea298720af48413a354bd3", "content_id": "077634550a1f1dbeb858e9c3bec576df100e8d6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5864, "license_type": "no_license", "max_line_length": 717, "num_lines": 184, "path": "/day9/hw9/hw9pr2.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "# ## Homework _9_ (not 8): Problem 2, steganography\n#\n# This question asks you to write two functions, likely with some helper functions, that will enable you\n# to embed arbitrary text (string) messages into an image (if there is enough room!)\n\n# For extra credit, the challenge is to be\n# able to extract/embed an image into another image...\n\n#\n# You'll want to borrow from hw8pr1 for\n# + opening the file\n# + reading the pixels\n# + create some helper functions!\n# + also, check out the slides :-)\n#\n# Happy steganographizing, everyone!\n#\n\n\n\n\n\n# Part A: here is a signature for the decoding\n# remember - you will want helper functions!\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom binascii import *\n\ndef int_to_bin(integer):\n \"\"\"\n Input: integer - one digit integer type\n Output: final_bin - binary version of integer with leading zeros\n such that it is 8 digits long as a string\n \"\"\"\n binary = bin(integer)[2:]\n leading_zeros = (8-len(binary))*str(0)\n final_bin = leading_zeros + binary\n return final_bin\n\ndef msg_to_bin( image ):\n \"\"\"\n Input: image object that needs to be decoded\n Output: String of the message encoded in the image in binary\n \"\"\"\n\n #initializing binary string\n binary_str = \"\"\n\n #getting image dimensions\n height, width, channels = image.shape\n\n #below is some cursed syntax. Nested while loops with nested if statements...\n row = 0\n decoding_finished = False\n while decoding_finished == False:\n end_row = False\n print(\"On row \",row)\n col = 0\n while end_row == False:\n print(\"On column \",col)\n\n rb = int_to_bin(image[row,col][0])[-1:]\n binary_str += rb\n if len(binary_str)%8 == 0 and binary_str[-8:] == \"0\"*8:\n decoding_finished = True\n break\n\n gb = int_to_bin(image[row,col][1])[-1:]\n binary_str += gb\n if len(binary_str)%8 == 0 and binary_str[-8:] == \"0\"*8:\n decoding_finished = True\n break\n\n bb = int_to_bin(image[row,col][2])[-1:]\n binary_str += bb\n if len(binary_str)%8 == 0 and binary_str[-8:] == \"0\"*8:\n decoding_finished = True\n break\n\n if col == width-1:\n end_row = True\n col+=1\n\n row+=1\n\n return binary_str\n\ndef desteg_string(image):\n binary_msg = msg_to_bin(image)\n split_bin = [binary_msg[i:i+8] for i in range(0, len(binary_msg), 8)]\n decoded_msg = \"\"\n for encoded_ascii in split_bin[:-1]:\n integer = int(encoded_ascii,2)\n character = chr(integer)\n decoded_msg+=character\n\n return decoded_msg\n\n\n# IMAGE_NAME = \"./small_flag_with_message_bgr.png\"\n# image_bgr = cv2.imread(IMAGE_NAME, cv2.IMREAD_COLOR)\n# image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n# decoded_msg = desteg_string(image)\n# print(decoded_msg)\n\n\n\n\n# Part B: here is a signature for the encoding/embedding\n# remember - you will want helper functions!\ndef load_image(file_path):\n \"\"\"This loads in an image\"\"\"\n image_bgr = cv2.imread(file_path,cv2.IMREAD_COLOR)\n image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n return image\n\ndef char_to_bin(character):\n \"\"\"\n Input: character - a string consisting of a single ascii character\n Output: char_bin - a string representing this ascii character in binary\n \"\"\"\n small_bin = bin(ord(character))[2:]\n num_zeros = 8 - len(small_bin)\n char_bin = num_zeros*str(0)+small_bin\n return char_bin\n\ndef string_to_bin(msg):\n \"\"\"\n Input: msg - a string of ascii characters\n Output: bin_msg - a string of binary represnting these ascii characters\n \"\"\"\n bin_msg = \"\"\n for character in msg:\n char_bin = char_to_bin(character)\n bin_msg +=char_bin\n return bin_msg\n\ndef steganographize( image, msg, new_image_name=\"Ooohhh, a spooky encoded image!\" ):\n \"\"\"\n Inputs:\n image - 3D numpy array representing an image\n msg - a string representing the message to be encoded\n Output:\n encoded_image - this is a 3D numpy array represnting the original image\n with the encoded message\n \"\"\"\n # bin_msg = \"\"\n # for character in msg:\n # bin_msg += bin(ord(character))[2:]\n #\n # bin_msg += str(0)*8\n\n bin_msg = string_to_bin(msg)\n print(bin_msg)\n image_vec = np.reshape(image,image.shape[0]*image.shape[1]*image.shape[2])\n\n i = 0\n for bit in bin_msg:\n print(\"og\",image_vec[i])\n image_vec[i] = int(bin(image_vec[i])[2:-1]+bin_msg[i],2)\n print('new',image_vec[i])\n\n i+=1\n image_vec[i:i+8]=str(0)*8\n new_image = np.reshape(image_vec,image.shape)\n image_to_save = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)\n cv2.imwrite(new_image_name, image_to_save)\n\n return new_image\n\ndef display_image(image):\n \"\"\"This displays an image\"\"\"\n plt.figure()\n plt.axis('off')\n plt.imshow(image)\n plt.show()\n\nimage_dir = 'art.png'\nimage = load_image(image_dir)\nimage_name = image_dir + \"_encoded.png\"\nnew_image = steganographize( image,\"hey there buddy chum pal friend buddy pal chum bud friend fella bruther amigo pal buddy friend chummy chum chum pal i don't mean to be rude my friend pal home slice bread slice dawg but i gotta warn ya if u take one more diddly darn step right there im going to have to diddly darn snap ur neck and wowza wouldn't that be a crummy juncture, huh? do yuo want that? do wish upon yourself to come into physical experience with a crummy juncture? because friend buddy chum friend chum pally pal chum friend if you keep this up well gosh diddly darn i just might have to get not so friendly with u my friendly friend friend pal friend buddy chum pally friend chum buddy...\", image_name)\nprint(desteg_string(new_image))\n" }, { "alpha_fraction": 0.6150895357131958, "alphanum_fraction": 0.6360979080200195, "avg_line_length": 31.97590446472168, "blob_id": "5904ac8c99596a42b5b4be77894388bd4e530d96", "content_id": "cd0b25a7f358571825350325272cd168a0f03f1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5474, "license_type": "no_license", "max_line_length": 100, "num_lines": 166, "path": "/day7/modsim.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "# !conda update scikit-learn\n\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import fetch_mldata\nfrom sklearn.neural_network import MLPClassifier\n\nimport numpy as np\nimport pandas as pd\n\nprint(\"+++ Start of digits example +++\\n\")\ndf = pd.read_csv('digits.csv',header = 0)\n# df.head()\n# df.info()\n\nprint(\"+++ Converting to numpy arrays... +++\")\n# Data needs to be in numpy arrays - these next two lines convert to numpy arrays\nX_data_complete = df.iloc[:,0:64].values # iloc == \"integer locations\" of rows/cols\ny_data_complete = df[ '64' ].values # individually addressable columns (by name)\n\nX_unknown = X_data_complete[:22,:]\ny_unknown = y_data_complete[:22]\nactual_digits = [0,0,0,1,7,2,3,4,0,1,9,9,5,5,6,5,0,9,8,9,8,4]\n\nX_known = X_data_complete[22:,:]\ny_known = y_data_complete[22:]\n\nKNOWN_SIZE = len(y_known)\nindices = np.random.permutation(KNOWN_SIZE) # this scrambles the data each time\nX_known = X_known[indices]\ny_known = y_known[indices]\n\n#\n# from the known data, create training and testing datasets\n#\nTRAIN_FRACTION = 0.85\nTRAIN_SIZE = int(TRAIN_FRACTION*KNOWN_SIZE)\nTEST_SIZE = KNOWN_SIZE - TRAIN_SIZE # not really needed, but...\nX_train = X_known[:TRAIN_SIZE]\ny_train = y_known[:TRAIN_SIZE]\n\nX_test = X_known[TRAIN_SIZE:]\ny_test = y_known[TRAIN_SIZE:]\n\n#\n# it's important to keep the input values in the 0-to-1 or -1-to-1 range\n# This is done through the \"StandardScaler\" in scikit-learn\n#\nUSE_SCALER = True\nif USE_SCALER == True:\n from sklearn.preprocessing import StandardScaler\n scaler = StandardScaler()\n scaler.fit(X_train) # Fit only to the training dataframe\n # now, rescale inputs -- both testing and training\n X_train = scaler.transform(X_train)\n X_test = scaler.transform(X_test)\n X_unknown = scaler.transform(X_unknown)\n\navg_train_scores = []\navg_test_scores = []\navg_pred_scores = []\nn_range = []\nn_max = 300\n\nfor n in range(200,n_max+5,5):\n print(\"\\n+++ Running Simulation Number \"+str(n+1)+\" +++\\n\")\n mlp = MLPClassifier(hidden_layer_sizes=(100,n+1), max_iter=200, alpha=1e-4,\n solver='sgd', verbose=False, shuffle=True, early_stopping = False, # tol=1e-4,\n random_state=None, # reproduceability\n learning_rate_init=.03, learning_rate = 'adaptive')\n sim_train_scores = []\n sim_test_scores = []\n sim_pred_scores = []\n for m in range(10):\n mlp.fit(X_train, y_train)\n sim_train_scores.append( mlp.score(X_train, y_train) )\n sim_test_scores.append( mlp.score(X_test,y_test) )\n unknown_predictions = list(mlp.predict(X_unknown))\n i = 0\n total_right = 0\n for digit in actual_digits:\n if actual_digits[i] == unknown_predictions[i]:\n total_right += 1\n i += 1\n sim_pred_scores.append( total_right/len(actual_digits) )\n\n avg_train_scores.append( sum(sim_train_scores)/len(sim_train_scores) )\n avg_test_scores.append( sum(sim_test_scores)/len(sim_test_scores) )\n avg_pred_scores.append( sum(sim_pred_scores)/len(sim_pred_scores) )\n n_range.append(n+1)\n\nplt.xkcd()\nplt.plot(n_range,avg_pred_scores)\nplt.xlabel('Number of neurons in Second Layer,\\n100 in first')\nplt.xkcd()\nplt.ylabel('Accuracy on Unknown Numbers')\nplt.xkcd()\nplt.title('For 2 Hidden Layers')\nplt.xlim((1,n_max))\nplt.ylim((0,1))\nplt.show()\n\nplt.xkcd()\nplt.plot(n_range,avg_pred_scores)\nplt.xlabel('Number of neurons in Second Layer,\\n100 in first')\nplt.xkcd()\nplt.ylabel('Accuracy on Unknown Numbers')\nplt.xkcd()\nplt.title('For 2 Hidden Layers')\nplt.xlim((1,n_max))\nplt.ylim((0,1))\nplt.show()\n\n# avg_train_scores = []\n# avg_test_scores = []\n# avg_pred_scores = []\n# n_range = []\n# n_max = 20\n#\n# for n in range(n_max):\n# print(\"\\n+++ Running Simulation Number \"+str(n+1+n_max)+\" +++\\n\")\n# mlp = MLPClassifier(hidden_layer_sizes=(n+1,n+1), max_iter=200, alpha=1e-4,\n# solver='sgd', verbose=False, shuffle=True, early_stopping = False, # tol=1e-4,\n# random_state=None, # reproduceability\n# learning_rate_init=.03, learning_rate = 'adaptive')\n# sim_train_scores = []\n# sim_test_scores = []\n# sim_pred_scores = []\n# for m in range(10):\n# mlp.fit(X_train, y_train)\n# sim_train_scores.append( mlp.score(X_train, y_train) )\n# sim_test_scores.append( mlp.score(X_test,y_test) )\n# unknown_predictions = list(mlp.predict(X_unknown))\n# i = 0\n# total_right = 0\n# for digit in actual_digits:\n# if actual_digits[i] == unknown_predictions[i]:\n# total_right += 1\n# i += 1\n# sim_pred_scores.append( total_right/len(actual_digits) )\n#\n# avg_train_scores.append( sum(sim_train_scores)/len(sim_train_scores) )\n# avg_test_scores.append( sum(sim_test_scores)/len(sim_test_scores) )\n# avg_pred_scores.append( sum(sim_pred_scores)/len(sim_pred_scores) )\n# n_range.append(n+1)\n#\n# plt.xkcd()\n# plt.plot(n_range,avg_pred_scores)\n# plt.xlabel('Number of neurons per layer')\n# plt.xkcd()\n# plt.ylabel('Accuracy on Unknown Numbers')\n# plt.xkcd()\n# plt.title('For 2 Hidden Layers')\n# plt.xlim((1,n_max))\n# plt.ylim((0,1))\n# plt.show()\n#\n# plt.xkcd()\n# plt.plot(n_range,avg_pred_scores)\n# plt.xlabel('Number of neurons per layer')\n# plt.xkcd()\n# plt.ylabel('Accuracy on Unknown Numbers')\n# plt.xkcd()\n# plt.title('For 2 Hidden Layers')\n# plt.xlim((1,n_max))\n# plt.ylim((0,1))\n# plt.show()\n" }, { "alpha_fraction": 0.527563750743866, "alphanum_fraction": 0.5373443961143494, "avg_line_length": 28.858407974243164, "blob_id": "9b63e24df756d828111305767e884d6c065d72ca", "content_id": "be962951bc7a7aee65a998866f4c93d17a6691a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3374, "license_type": "no_license", "max_line_length": 114, "num_lines": 113, "path": "/day2/hw2pr1.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# hw2pr1.py - write-your-own-web-engine...\n#\n# then, improve the page's content and styling!\n#\n\n\nimport re\nfrom copy import deepcopy\n\ndef subtract(a, b):\n return \"\".join(a.split(b)[1:])\n\ndef apply_headers( OriginalLines ):\n \"\"\" should apply headers, h1-h5, as tags\n \"\"\"\n # loop for all headings: h1-h5\n\n html_head = [(\"<h1>\",\"</h1>\"),(\"<h2>\",\"</h2>\"),(\"<h3>\",\"</h3>\"),(\"<h4>\",\"</h4>\"),(\"<h5>\",\"</h5>\")]\n md_head = [\"#\",\"##\",\"###\",\"####\",\"#####\"]\n\n NewLines =[]\n for line in OriginalLines:\n for head in md_head:\n if line.split(\" \")[0]==head:\n line = html_head[md_head.index(head)][0] + subtract(line,head) + html_head[md_head.index(head)][1]\n # if line.startswith(\"#\"):\n # line = \"<h1>\" + line[1:] + \"</h1>\"\n\n NewLines += [ line ]\n\n\n return NewLines\n\ndef apply_wordstyling( OriginalLines ):\n \"\"\" should apply wordstyling here...\n \"\"\"\n # loop for the word-stylings: here, ~word~\n NewLines =[]\n for line in OriginalLines:\n # regular expression example!\n line = re.sub(r\"~(.*)~\", r\"<i>\\1</i>\", line)\n line = re.sub(r\"[*](.*)[*]\",r\"<b>\\1</b>\",line)\n line = re.sub(r\"[_](.*)[_]\",r\"<u>\\1</u>\",line)\n line = re.sub(r\"[@](.*)[@]\",r\"<a href=\\1> Link </a>\",line)\n if \"color:\" in line:\n line = re.sub(r\"color:(.*):\",r\"<font color =\\1>\",line)\n line += \"</font>\"\n # let's practice some others...!\n # regular expressions: https://docs.python.org/3.4/library/re.html\n NewLines += [ line ]\n return NewLines\n # Your task: add at least\n # *bold*\n # @link@ (extra: use a regular expression to match a link!)\n # _underscore_\n # extra-credit! BLINKING (working!) or strikethrough\n # remember for many special symbols, you need to \"backslash\" them...\n\n\ndef listify(OriginalLines):\n \"\"\" convert lists beginning with \" +\" into HTML \"\"\"\n NewLines = []\n list_start = True\n # loop for lists\n for line in OriginalLines:\n if line.startswith(\" +\"):\n if list_start == True:\n NewLines.append(\"<ul>\")\n list_start = False\n NewLines.append(\"<li>\"+ line[4:] +\"</li>\")\n else:\n if list_start == False:\n NewLines.append('</ul>')\n list_start = True\n NewLines.append(line)\n\n # line = \"<ul>\\n<li>\" + line[4:] + \"</li>\\n</ul>\"\n # note - this is wrong: your challenge: fix it!\n return NewLines\n\n\n\ndef main():\n \"\"\" handles the conversion from the human-typed file to the HTML output \"\"\"\n\n HUMAN_FILENAME = \"starter.txt\"\n OUTPUT_FILENAME = \"starter.html\"\n\n f = open(HUMAN_FILENAME, \"r\", encoding=\"latin1\")\n contents = f.read()\n f.close()\n\n print(\"Original contents were\\n\", contents, \"\\n\")\n\n OriginalLines = contents.split(\"\\n\") # split to create a list of lines\n NewLines = apply_headers( OriginalLines )\n NewLines = apply_wordstyling(NewLines)\n NewLines = listify(NewLines)\n\n # finally, we join everything with newlines...\n final_html = '\\n'.join(NewLines)\n\n print(\"\\nFinal contents are\\n\", final_html, \"\\n\")\n\n f = open(OUTPUT_FILENAME, \"w\") # write this out to a file...\n f.write( final_html )\n f.close()\n # then, render in your browser...\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5853618383407593, "alphanum_fraction": 0.6031249761581421, "avg_line_length": 30.832460403442383, "blob_id": "c4cd1a39e4891d5242b9fb95319a79dbe29643d3", "content_id": "8fa694f47ff9dc10474d4e0d2dd3672af577a2e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6080, "license_type": "no_license", "max_line_length": 97, "num_lines": 191, "path": "/day9/hw9/hw9pr1.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# coding: utf-8\n#\n# hw8pr1.py - the k-means algorithm -- with pixels...\n#\n\n# import everything we need...\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nimport utils\nimport cv2\nimport numpy as np\n\ndef fried_chicken_or_doggo():\n #Fried Chicken or Doggo?\n # choose an image...\n # IMAGE_NAME = \"./jp.png\" # Jurassic Park\n # IMAGE_NAME = \"./batman.png\"\n # IMAGE_NAME = \"./hmc.png\"\n # IMAGE_NAME = \"./thematrix.png\"\n # IMAGE_NAME = \"./fox.jpg\"\n IMAGE_NAME = \"./doggo.jpeg\"\n image = cv2.imread(IMAGE_NAME, cv2.IMREAD_COLOR)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # reshape the image to be a list of pixels\n image_pixels = image.reshape((image.shape[0] * image.shape[1], 3))\n\n # # choose k (the number of means) in NUM_MEANS\n # # and cluster the pixel intensities\n #\n # NUM_MEANS = 5\n # clusters = KMeans(n_clusters = NUM_MEANS)\n # clusters.fit(image_pixels)\n #\n # # After the call to fit, the key information is contained\n # # in clusters.cluster_centers_ :\n # count = 0\n # for center in clusters.cluster_centers_:\n # print(\"Center #\", count, \" == \", center)\n # # note that the center's values are floats, not ints!\n # center_integers = [int(p) for p in center]\n # print(\" and as ints:\", center_integers)\n # count += 1\n #\n # # build a histogram of clusters and then create a figure\n # # representing the number of pixels labeled to each color\n # hist = utils.centroid_histogram(clusters)\n # bar = utils.plot_colors(hist, clusters.cluster_centers_)\n #\n #\n # # in the first figure window, show our image\n plt.figure()\n plt.axis(\"off\")\n plt.imshow(image)\n\n bars = []\n for i in range(4):\n NUM_MEANS = 3 + i\n clusters = KMeans(n_clusters = NUM_MEANS)\n clusters.fit(image_pixels)\n count = 0\n for center in clusters.cluster_centers_:\n center_integers = [int(p) for p in center]\n count += 1\n hist = utils.centroid_histogram(clusters)\n bar = utils.plot_colors(hist, clusters.cluster_centers_)\n bars.append(bar)\n # in the second figure window, show the pixel histograms\n # this starter code has a single value of k for each\n # your task is to vary k and show the resulting histograms\n # this also illustrates one way to display multiple images\n # in a 2d layout (fig == figure, ax == axes)\n #\n num_rows = 2\n num_cols = 4\n fig, ax = plt.subplots(nrows=num_rows, ncols=num_cols, sharex=False, sharey=False)\n titles = []\n i=0\n for bar in bars:\n title = str(i+3)+\" means\"\n titles.append(title)\n i+=1\n\n ax[0,0].imshow(bars[0]); ax[0,0].set_title(titles[0])\n ax[0,1].imshow(bars[1]); ax[0,1].set_title(titles[1])\n ax[1,0].imshow(bars[2]); ax[1,0].set_title(titles[2])\n ax[1,1].imshow(bars[3]); ax[1,1].set_title(titles[3])\n\n IMAGE_NAME = \"./legs.jpg\"\n image = cv2.imread(IMAGE_NAME, cv2.IMREAD_COLOR)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # reshape the image to be a list of pixels\n image_pixels = image.reshape((image.shape[0] * image.shape[1], 3))\n\n plt.figure()\n plt.axis(\"off\")\n plt.imshow(image)\n\n bars = []\n for i in range(4):\n NUM_MEANS = 3 + i\n clusters = KMeans(n_clusters = NUM_MEANS)\n clusters.fit(image_pixels)\n count = 0\n for center in clusters.cluster_centers_:\n center_integers = [int(p) for p in center]\n count += 1\n hist = utils.centroid_histogram(clusters)\n bar = utils.plot_colors(hist, clusters.cluster_centers_)\n bars.append(bar)\n # in the second figure window, show the pixel histograms\n # this starter code has a single value of k for each\n # your task is to vary k and show the resulting histograms\n # this also illustrates one way to display multiple images\n # in a 2d layout (fig == figure, ax == axes)\n #\n\n titles = []\n i=0\n for bar in bars:\n title = str(i+3)+\" means\"\n titles.append(title)\n i+=1\n\n ax[0,2].imshow(bars[0]); ax[0,2].set_title(titles[0])\n ax[0,3].imshow(bars[1]); ax[0,3].set_title(titles[1])\n ax[1,2].imshow(bars[2]); ax[1,2].set_title(titles[2])\n ax[1,3].imshow(bars[3]); ax[1,3].set_title(titles[3])\n\n\n\n\n for row in range(num_rows):\n for col in range(num_cols):\n ax[row,col].axis('off')\n plt.show(fig)\n\ndef posterize():\n IMAGE_NAME = \"./mffn.jpg\"\n image = cv2.imread(IMAGE_NAME, cv2.IMREAD_COLOR)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # reshape the image to be a list of pixels\n image_pixels = image.reshape((image.shape[0] * image.shape[1], 3))\n\n NUM_MEANS = 5\n clusters = KMeans(n_clusters = NUM_MEANS)\n clusters.fit(image_pixels)\n count = 0\n for center in clusters.cluster_centers_:\n center_integers = [int(p) for p in center]\n count += 1\n hist = utils.centroid_histogram(clusters)\n bar = utils.plot_colors(hist, clusters.cluster_centers_)\n # print(clusters.cluster_centers_)\n plt.figure()\n plt.axis(\"off\")\n plt.imshow(image)\n\n height,width,channels = image.shape\n poster = image.copy()\n for row in range(height):\n for col in range(width):\n distances = []\n for point in clusters.cluster_centers_:\n r,g,b = image[row,col]\n distances.append(np.sqrt( (point[0]-r)**2 + (point[1]-g)**2 + (point[2]-b)**2 ) )\n min_distance_ind = distances.index(min(distances))\n # print(distances)\n # print(min_distance_ind)\n poster[row,col] = clusters.cluster_centers_[min_distance_ind]\n plt.figure()\n plt.axis('off')\n plt.imshow(poster)\n plt.show()\nposterize()\n\n#\n# comments and reflections on hw8pr1, k-means and pixels\n\"\"\"\n + Which of the paths did you take:\n + posterizing or\n + algorithm-implementation\n\n + How did it go? Which file(s) should we look at?\n + Which function(s) should we try...\n\"\"\"\n#\n#\n" }, { "alpha_fraction": 0.5800331830978394, "alphanum_fraction": 0.5838273763656616, "avg_line_length": 29.34532356262207, "blob_id": "1dd2553fcee7bc576918783402ba0ebe6ae68170", "content_id": "23bfc99960859886ee0033dc36522f5a4d5b2118", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4217, "license_type": "no_license", "max_line_length": 88, "num_lines": 139, "path": "/day2/hw2pr3.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# starter file for hw1pr3, cs35 spring 2017...\n# \n\nimport csv\n\n#\n# readcsv is a starting point - it returns the rows from a standard csv file...\n#\ndef readcsv( csv_file_name ):\n \"\"\" readcsv takes as\n + input: csv_file_name, the name of a csv file\n and returns\n + output: a list of lists, each inner list is one row of the csv\n all data items are strings; empty cells are empty strings\n \"\"\"\n try:\n csvfile = open( csv_file_name, newline='' ) # open for reading\n csvrows = csv.reader( csvfile ) # creates a csvrows object\n\n all_rows = [] # we need to read the csv file\n for row in csvrows: # into our own Python data structure\n all_rows.append( row ) # adds only the word to our list\n\n del csvrows # acknowledge csvrows is gone!\n csvfile.close() # and close the file\n return all_rows # return the list of lists\n\n except FileNotFoundError as e:\n print(\"File not found: \", e)\n return []\n\n\n\n#\n# write_to_csv shows how to write that format from a list of rows...\n# + try write_to_csv( [['a', 1 ], ['b', 2]], \"smallfile.csv\" )\n#\ndef write_to_csv( list_of_rows, filename ):\n \"\"\" readcsv takes as\n + input: csv_file_name, the name of a csv file\n and returns\n + output: a list of lists, each inner list is one row of the csv\n all data items are strings; empty cells are empty strings\n \"\"\"\n try:\n csvfile = open( filename, \"w\", newline='' )\n filewriter = csv.writer( csvfile, delimiter=\",\")\n for row in list_of_rows:\n filewriter.writerow( row )\n csvfile.close()\n\n except:\n print(\"File\", filename, \"could not be opened for writing...\")\n\n\n\n\n#\n# annotate_text_starter\n#\n# Shows off how to style portions of an input text\n# This does not actually use the annotations dictionary (but you will...)\n#\ndef annotate_text_starter( text, annotations ):\n \"\"\" this is a letter-by-letter (instead of word-by-word)\n text-annotater. It makes the 'z' characters in the input text bright red.\n It also changes the '\\n' characters to \"<br>\"\n\n It does not use the annotations dictionary (but you'll want to!)\n It is not general (but you'll build a general template engine!)\n\n try with \n + text = \"Bees that buzz -\\nand kids that blow dandelion fuzz...\"\n \"\"\"\n new_html_string = ''\n for c in text: # letter-by-letter!\n if c == 'z':\n # we use Python's cool \"text-formatting\" ability...\n new_c = '<span style=\"color:{0};\">{1}</span>'.format(\"red\", c)\n elif c == '\\n': # handle new lines...\n new_c = \"<br>\"\n else:\n new_c = c\n\n # add the new character, new_c\n new_html_string += new_c \n\n # finished!\n return new_html_string\n\n\ndef main():\n \"\"\" running this file as a script \"\"\"\n text = \"Bees that buzz -\\nand kids that blow dandelion fuzz...\"\n d = {} # no annotations, yet...\n output_html = annotate_text_starter( text, d )\n print(\"output_html is\\n\", output_html)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n# Larger example for testing...\n\n\n#\n# Here are the text and dictionary of substitutions used in hamlet_substitution.html\n#\n# Note that we don't give away the template engine here (there'd be nothing left!) \n#\n# Inspired by\n# http://nfs.sparknotes.com/hamlet/page_50.html\n#\n\nHAMLET_A1S4 = \"\"\"\nThe king doth wake tonight and takes his rouse,\nKeeps wassail and the swaggering upspring reels,\nAnd, as he drains his draughts of Rhenish down,\nThe kettle-drum and trumpet thus bray out\nThe triumph of his pledge.\n\"\"\"\n\n#\n# this would be read in from a csv file and constructed\n#\n# Again, we don't give that function (it's the hw!)\nHAMLET_SUBS = { \"doth\":\"does\", \"rouse\":\"partying\", \n \"wassail\":\"drinks\",\n \"reels\":\"dances\", \"rhenish\":\"wine\", \n \"bray\":\"blare\", \"pledge\":\"participation\"}\n\n\n\n#\n# You can see the desired output in hamlet_substitution.html\n#" }, { "alpha_fraction": 0.6402226686477661, "alphanum_fraction": 0.6947343945503235, "avg_line_length": 30.933332443237305, "blob_id": "b5c6b3c5763109a58e7dfb460ac03f28535f3201", "content_id": "0fa41872b4a87a567333c7a201d5c9e3b34b7d55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4311, "license_type": "no_license", "max_line_length": 116, "num_lines": 135, "path": "/Social Justice hw/G1starter.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors as mcolors\nimport math\nimport statistics\n\nMean_Rent = {\"Bay Ridge\":[1338,1651], \"Bedford-Stuyvesant\":[1314, 2037], \"Boerum Hill\":[2027,2820],\n\"Buschwick\": [1764, 2134], \"Clinton Hill\": [1868, 2389],\n\"Cobble Hill\": [2011, 2767], \"Crown Heights\": [1123, 1894], \"DUMBO\": [3282, 4088],\n\"Fort Greene\": [2233, 3032], \"Greenpoint\": [2092, 2559], \"Park Slope\": [2036, 2616],\n\"Williamsburg\": [2356, 3217]}\n\npercent_of_POC_2010 = {\"Bay Ridge\": 34, \"Bedford-Stuyvesant\":74, \"Boerum Hill\":58,\n\"Buschwick\": 90, \"Clinton Hill\": 64,\n\"Cobble Hill\": 25, \"Crown Heights\": 86, \"DUMBO\": 56,\n\"Fort Greene\": 28, \"Greenpoint\": 23, \"Park Slope\": 33,\n\"Williamsburg\": 14}\n\npercent_of_POC_2016 = {\"Bay Ridge\":28, \"Bedford-Stuyvesant\":84, \"Boerum Hill\":43,\n\"Buschwick\": 58, \"Clinton Hill\": 53,\n\"Cobble Hill\":21, \"Crown Heights\":21, \"DUMBO\":36,\n\"Fort Greene\": 58, \"Greenpoint\": 31, \"Park Slope\": 23,\n\"Williamsburg\": 31}\n\ndef percent_increase(initial_dict, final_dict):\n \"\"\"\n finds the percent increase in mean rent of different zip codes in\n Brooklyn from 2010 to 2016\n\n output: a dictionary with a key of zip codes and values of percent increase of mean rents\"\"\"\n increase_dict = {}\n for key, value in initial_dict.items():\n initial_value = initial_dict[key]\n final_value = final_dict[key]\n percent_increase = (final_value-initial_value)/initial_value * 100\n increase_dict[key] = percent_increase\n return increase_dict\n\ndef graph_percent_increase(initial_dict, final_dict):\n \"\"\"\n graphs the percent increae in mean rent of different zip codes in\n Brooklyn from 2010 to 2016\n \"\"\"\n dictionary = plt.figure()\n\n D = percent_increase(initial_dict, final_dict)\n\n plt.bar(range(len(D)), D.values(), align='center', color='steelblue')\n plt.xticks(range(len(D)), D.keys(), rotation='vertical')\n plt.xlabel('Percent Difference')\n plt.ylabel('Brooklyn Neighborhoods')\n plt.title('Percent Increase of Rent in Brooklyn between 2010 and 2016')\n plt.tight_layout()\n plt.show()\n\n'''\nWhich area experienced the largest increase in Rent?\n\nWilliamsburg\n'''\n\ndef max_percent_increase(increase_dict):\n \"\"\"\n finds the zip code that experienced the largest percent increase\n input (dict): increase_dict - dictionary of percent increases\n output: The zip code whose rent increased the most by percent value.\n \"\"\"\n increase_list = list(d.values())\n largest_increase = max(increase_list)\n\n\n\n\ndef remove_least_POC(threshold, dict):\n \"\"\"\n input: a dictionary, dict, that contains percentage of POC in different Brookly neighborhoods\n a value, threshold, which represents a percentage\n output: a dictionary with the elements of dict whose values are higher than threshold\n \"\"\"\n\n return_dict = dict.copy()\n for values in dict:\n if return_dict[values] < threshold:\n del return_dict[values]\n\n return return_dict\n\n\"\"\"\n1. Which neighborhoods had a population consisting of more than 50% minorities in 2010?\n WRITE ANSWER HERE\n\n2. Which neighborhoods then had a population of consisting more than 50% minorities in 2016?\n WRITE ANSWER HERE\n\n3. Is it all the same neighborhoods for 2010 and 2016? If not, what reasons do you think contributed to this change?\n WRITE ANSWER HERE\n\"\"\"\n\n\n\n\ndef percent_diff_POC():\n \"\"\"\n output: returns a dictionary with Brooklyn neighborhoods as keys and values being the difference\n in people of color between 2010 and 2016.\n \"\"\"\n\n\ndef find_diff(neighborhood):\n \"\"\"\n input: neighborhood, a string that is a key in Mean_Rent\n output: a 2-tuple with the first entry being the percent increase in rent and the second entry being\n the percent difference in people of color\n \"\"\"\n\n\n\ndef graph_POC_diff():\n \"\"\"\n graphs the difference in percent of people of color of different zip codes in\n Brooklyn from 2010 to 2016\n \"\"\"\n\n\n\"\"\"\nWhich neighborhood experienced the largest decrease in the percentage of people of color?\n\nFor this neighborhood, what was the percentage increase of rent (HINT: Use find_diff())?\n\"\"\"\n\n\"\"\"\nANSWER REFLECTION QUESTIONS HERE\n\"\"\"\nprint(percent_increase(percent_of_POC_2010,percent_of_POC_2016))\ngraph_percent_increase(percent_of_POC_2010,percent_of_POC_2016)\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.6026182174682617, "avg_line_length": 31, "blob_id": "43dc235fb584951eaee5a9d7625fa8273f48a9e0", "content_id": "adb03a177fa9c868d9b5e3dccc35854b138ce5d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2368, "license_type": "no_license", "max_line_length": 103, "num_lines": 74, "path": "/day0/hw0pr5.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "import os\nimport os.path\nimport csv\n\n\"\"\"\nThis code goes through all of the phone book files and stores all of the information found\ninto a csv\n\"\"\"\n\ndef get_all_txt_files(path = \".\"):\n \"\"\"This function walks through the subdirectories of the given path and returns a list of all\n the text file directories nested in this path as well as text files within the initial directory\"\"\"\n AllFiles = list(os.walk(path)) #getting all files into a data structure\n all_txt_files = []\n file_list = []\n\n for dir_tuple in AllFiles:\n file_list = dir_tuple[2]\n for file_name in file_list:\n if file_name[-3:] == 'txt':\n all_txt_files.append(dir_tuple[0]+'/'+file_name)\n return all_txt_files\n\ndef create_phone_book_csv(dir = \"./phone_book.csv\"):\n \"\"\"\n This function goes through all of the text files in a given directory and\n the nested subdirectories and stores all relevant phone book information\n in a single csv file\"\"\"\n all_phone_files = get_all_txt_files(\"./phone_files\")\n\n all_phone_info = []\n\n for phone_file in all_phone_files:\n f = open(phone_file,'r',encoding = 'latin1')\n contents = f.read()\n content_list = contents.split()\n\n if content_list[-2][-1] == \",\":\n last_name = content_list[-2][:-1]\n first_name = content_list[-1]\n else:\n last_name = content_list[-1]\n first_name = content_list[-2]\n\n numbers = ['0','1','2','3','4','5','6','7','8','9']\n phone_number = \"\"\n for item in content_list:\n for character in item:\n if character in numbers:\n phone_number += character\n\n phone_info = (last_name,first_name,phone_number)\n all_phone_info.append(phone_info)\n\n download_dir = \"./phone_book.csv\"\n csv = open(download_dir, \"w\")\n\n column_title_row = \"Last Name, First Name, Phone Number (Digits Only)\\n\"\n csv.write(column_title_row)\n\n for phone_info in all_phone_info:\n csv_info = ','.join(map(str,phone_info))+\"\\n\"\n csv.write(csv_info)\n\ndef print_phone_book_csv(dir = \"./phone_book.csv\"):\n \"\"\"\n This function prints out line by line, the contents of\n a specified csv file\"\"\"\n with open(download_dir, 'rt') as f:\n reader = csv.reader(f)\n for row in reader:\n print(row)\n\ndef main(dir):\n" }, { "alpha_fraction": 0.6092380881309509, "alphanum_fraction": 0.6253222227096558, "avg_line_length": 30.28709602355957, "blob_id": "edf51bd424fceff4e2e1bd85b6a930f4571c89cd", "content_id": "288a8acfa5a222e34b3a93c7c8977bf0fffadea7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9699, "license_type": "no_license", "max_line_length": 119, "num_lines": 310, "path": "/day5/iris5.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "#\n# read iris data\n#\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn import tree # for decision trees\nfrom sklearn import ensemble # for random forests\n\ntry: # different imports for different versions of scikit-learn\n from sklearn.model_selection import cross_val_score # simpler cv this week\nexcept ImportError:\n try:\n from sklearn.cross_validation import cross_val_score\n except:\n print(\"No cross_val_score!\")\n\n\n#\n# Here are the correct answers to the csv's \"unknown\" flowers\n#\nanswers = [ 'virginica', # index 0 (row 1 in the csv)\n 'virginica', # index 1 (row 2 in the csv)\n 'versicolor', # and so on...\n 'versicolor',\n 'setosa',\n 'setosa',\n 'virginica',\n 'versicolor',\n 'setosa']\n\n\n\nprint(\"+++ Start of pandas' datahandling +++\\n\")\n\n# df is a \"dataframe\":\ndf = pd.read_csv('iris5.csv', header=0) # read the file w/header row #0\n\n# Now, let's take a look at a bit of the dataframe, df:\ndf.head() # first five lines\ndf.info() # column details\n\n# One important feature is the conversion from string to numeric datatypes!\n# For _input_ features, numpy and scikit-learn need numeric datatypes\n# You can define a transformation function, to help out...\ndef transform(s):\n \"\"\" from string to number\n setosa -> 0\n versicolor -> 1\n virginica -> 2\n \"\"\"\n d = { 'unknown':-1, 'setosa':0, 'versicolor':1, 'virginica':2 }\n return d[s]\n\n#\n# this applies the function transform to a whole column\n#\n# df['irisname'] = df['irisname'].map(transform) # apply the function to the column\n\nprint(\"\\n+++ End of pandas +++\\n\")\n\nprint(\"+++ Start of numpy/scikit-learn +++\\n\")\n\nprint(\" +++++ Decision Trees +++++\\n\\n\")\n\n# Data needs to be in numpy arrays - these next two lines convert to numpy arrays\n# import sys\n# print(\"bye!\")\n# sys.exit(0)\nX_all = df.iloc[:,0:4].values # iloc == \"integer locations\" of rows/cols\ny_all = df[ 'irisname' ].values # individually addressable columns (by name)\n\nX_labeled = X_all[9:,:] # make the 10 into 0 to keep all of the data\ny_labeled = y_all[9:] # same for this line\n\n#\n# we can scramble the data - but only the labeled data!\n#\nindices = np.random.permutation(len(X_labeled)) # this scrambles the data each time\nX_data_full = X_labeled[indices]\ny_data_full = y_labeled[indices]\n\nX_train = X_data_full\ny_train = y_data_full\n\n#\n# some labels to make the graphical trees more readable...\n#\nprint(\"Some labels for the graphical tree:\")\nfeature_names = ['sepallen', 'sepalwid', 'petallen', 'petalwid']\ntarget_names = ['setosa', 'versicolor', 'virginica']\n\n#\n# show the creation of three tree files (at three max_depths)\n#\n# for max_depth in [1,2,3,4,5,6,7,8,9,10]:\n# # the DT classifier\n# dtree = tree.DecisionTreeClassifier(max_depth=max_depth)\n#\n# # train it (build the tree)\n# dtree = dtree.fit(X_train, y_train)\n#\n# # write out the dtree to tree.dot (or another filename of your choosing...)\n# filename = 'tree' + str(max_depth) + '.dot'\n# tree.export_graphviz(dtree, out_file=filename, # the filename constructed above...!\n# feature_names=feature_names, filled=True,\n# rotate=False, # LR vs UD\n# class_names=target_names,\n# leaves_parallel=True ) # lots of options!\n# #\n# # Visualize the resulting graphs (the trees) at www.webgraphviz.com\n# #\n# print(\"Wrote the file\", filename)\n# #\n\n\n#\n# cross-validation and scoring to determine parameter: max_depth\n#\nfor max_depth in range(1,20):\n # create our classifier\n dtree = tree.DecisionTreeClassifier(max_depth=max_depth)\n #\n # cross-validate to tune our model (this week, all-at-once)\n #\n scores = cross_val_score(dtree, X_train, y_train, cv=5)\n average_cv_score = scores.mean()\n print(\"For depth=\", max_depth, \"average CV score = \", average_cv_score)\n # print(\" Scores:\", scores)\n\n# import sys\n# print(\"bye!\")\n# sys.exit(0)\n\nMAX_DEPTH = 7 # choose a MAX_DEPTH based on cross-validation...\nprint(\"\\nChoosing MAX_DEPTH =\", MAX_DEPTH, \"\\n\")\n\n#\n# now, train the model with ALL of the training data... and predict the unknown labels\n#\n\nX_unknown = X_all[0:9,0:4] # the final testing data\nX_train = X_all[9:,0:4] # the training data\n\ny_unknown = y_all[0:9] # the final testing outputs/labels (unknown)\ny_train = y_all[9:] # the training outputs/labels (known)\n\n# our decision-tree classifier...\ndtree = tree.DecisionTreeClassifier(max_depth=MAX_DEPTH)\ndtree = dtree.fit(X_train, y_train)\n\n#\n# and... Predict the unknown data labels\n#\nprint(\"Decision-tree predictions:\\n\")\npredicted_labels = dtree.predict(X_unknown)\nanswer_labels = answers\n\n#\n# formatted printing! (docs.python.org/3/library/string.html#formatstrings)\n#\ns = \"{0:<11} | {1:<11}\".format(\"Predicted\",\"Answer\")\n# arg0: left-aligned, 11 spaces, string, arg1: ditto\nprint(s)\ns = \"{0:<11} | {1:<11}\".format(\"-------\",\"-------\")\nprint(s)\n# the table...\nfor p, a in zip( predicted_labels, answer_labels ):\n s = \"{0:<11} | {1:<11}\".format(p,a)\n print(s)\n\n#\n# feature importances!\n#\nprint()\nprint(\"dtree.feature_importances_ are\\n \", dtree.feature_importances_)\nprint(\"Order:\", feature_names[0:4])\n\n\n#\n# now, show off Random Forests!\n#\n\nprint(\"\\n\\n\")\nprint(\" +++++ Random Forests +++++\\n\\n\")\n\n#\n# The data is already in good shape -- let's start from the original dataframe:\n#\nX_all = df.iloc[:,0:4].values # iloc == \"integer locations\" of rows/cols\ny_all = df[ 'irisname' ].values # individually addressable columns (by name)\n\nX_labeled = X_all[9:,:] # just the input features, X, that HAVE output labels\ny_labeled = y_all[9:] # here are the output labels, y, for X_labeled\n\n#\n# we can scramble the data - but only the labeled data!\n#\nindices = np.random.permutation(len(X_labeled)) # this scrambles the data each time\nX_data_full = X_labeled[indices]\ny_data_full = y_labeled[indices]\n\nX_train = X_data_full\ny_train = y_data_full\n\n\n#\n# cross-validation to determine the Random Forest's parameters (max_depth and n_estimators)\n#\n\nimport numpy as np\nc = 0\nscores_avgs = []\ndepths = []\nn_s = []\n\nm_range = [1,2,3,4,5,6,7,8,9,10]\nn_range = [1,2,3,4,5,6,7,8,9,10]#np.linspace(2,100,50)\nfor m in m_range:\n for n in n_range:\n # create the random forest\n rforest = ensemble.RandomForestClassifier(max_depth=int(m), n_estimators=int(n))\n\n # cross validate the forest\n scores = cross_val_score(rforest, X_train, y_train, cv=15)\n # print(\"Max Depth: \",str(m),\" \"*5,\"n_estimators: \",str(n))\n # print(\"CV scores:\", scores)\n # print(\"CV scores' average:\", scores.mean())\n scores_avgs.append(scores.mean())\n depths.append(m)\n n_s.append(n)\n c+=1\n print(\"Loading... \", (c/(10*10))*100 , \"Percent\")\ntry:\n best_score = max(scores_avgs)[0]\nexcept:\n best_score = max(scores_avgs)\n\nbest_score_index = scores_avgs.index(best_score)\nbest_depth = depths[best_score_index]\nbest_n = n_s[best_score_index]\nprint(\"The best score was: \",str(best_score),\"\\nwith max depth of \",str(best_depth),\"\\nand n_estimators: \",str(best_n))\n\n\n\n# Lab task! Your goal:\n# + loop over a number of values of max_depth (m)\n# + loop over different numbers of trees/n_estimators (n)\n# -> to find a pair of values that results in a good average CV score\n#\n# use the decision-tree code above as a template for this...\n#\n\n# you'll want to take the average of these...\n\n\n\n#\n# now, train the model with ALL of the training data... and predict the labels of the test set\n#\n\nX_test = X_all[0:9,0:4] # the final testing data\nX_train = X_all[9:,0:4] # the training data\n\ny_test = y_all[0:9] # the final testing outputs/labels (unknown)\ny_train = y_all[9:] # the training outputs/labels (known)\n\n# these next lines is where the full training data is used for the model\nMAX_DEPTH = best_depth #depth of 6 and n of 10 works well\nNUM_TREES = best_n\nprint()\nprint(\"Using MAX_DEPTH=\", MAX_DEPTH, \"and NUM_TREES=\", NUM_TREES)\nrforest = ensemble.RandomForestClassifier(max_depth=MAX_DEPTH, n_estimators=NUM_TREES)\nrforest = rforest.fit(X_train, y_train)\n\nfor el in rforest.estimators_:\n i = rforest.estimators_.index(el)\n filename = 'tree' + '-' + str(i) + '_' + str(MAX_DEPTH) + '-' + str(NUM_TREES) + '.dot'\n tree.export_graphviz(rforest.estimators_[i], out_file=filename, # the filename constructed above...!\n feature_names=feature_names, filled=True,\n rotate=False, # LR vs UD\n class_names=target_names,\n leaves_parallel=True ) # lots of options!\n\n# here are some examples, printed out:\nprint(\"Random-forest predictions:\\n\")\npredicted_labels = rforest.predict(X_test)\nanswer_labels = answers # note that we're \"cheating\" here!\n\n#\n# formatted printing again (see above for reference link)\n#\ns = \"{0:<11} | {1:<11}\".format(\"Predicted\",\"Answer\")\n# arg0: left-aligned, 11 spaces, string, arg1: ditto\nprint(s)\ns = \"{0:<11} | {1:<11}\".format(\"-------\",\"-------\")\nprint(s)\n# the table...\nfor p, a in zip( predicted_labels, answer_labels ):\n s = \"{0:<11} | {1:<11}\".format(p,a)\n print(s)\n\n#\n# feature importances\n#\nprint(\"\\nrforest.feature_importances_ are\\n \", rforest.feature_importances_)\nprint(\"Order:\", feature_names[0:4])\n\n# The individual trees are in rforest.estimators_ [a list of decision trees!]\n" }, { "alpha_fraction": 0.6119440793991089, "alphanum_fraction": 0.6213468909263611, "avg_line_length": 29.960630416870117, "blob_id": "c04575d4a78a9034d1eb9ff4a3ab2a4c6de4d93b", "content_id": "81e243734f076e5a463189f8f4098aad5f930b5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7870, "license_type": "no_license", "max_line_length": 92, "num_lines": 254, "path": "/day6/hw6pr3names.py", "repo_name": "EverardoG/HMC-Research", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n# Problem 4: machine-learning and NLP\n#\n# Name-classification\n#\n# This problem asks you to model whether a name is more likely to be\n# identified as female or male, based on user-defined features...\n#\n# It creates a confusion matrix of the results -- and shares some of the mis-classifications\n#\n\n\"\"\"\n###########\n#\n# Note: for the example and problem below, you will need\n# three of the \"language corpora\" (large sourcetexts)\n# from NLTK. To make sure you've downloaded them,\n# run the following:\n#\n# import nltk\n# nltk.download('names')\n# nltk.download('movie_reviews')\n# nltk.download('opinion_lexicon')\n# \n# others are available, e.g.\n# nltk.download('stopwords')\n#\n###########\n\"\"\"\n\n## Import all of the libraries and data that we will need.\nimport nltk\nfrom nltk.corpus import names # see the note on installing corpora, above\nfrom nltk.corpus import opinion_lexicon\nfrom nltk.corpus import movie_reviews\n\nimport random\nimport math\n\nfrom sklearn.feature_extraction import DictVectorizer\nimport sklearn\nimport sklearn.tree\nfrom sklearn.metrics import confusion_matrix\nfrom collections import defaultdict\n\n\n#\n# experiments showing how the feature vectorizer in scikit-learn works...\n#\nTRY_FEATURE_VECTORIZER = False\nif TRY_FEATURE_VECTORIZER == True:\n # converts from dictionaries to feature arrays (vectors)\n v = DictVectorizer(sparse=False)\n FEATS = [{'foo': 1, 'bar': 2}, {'foo': 3, 'baz': 1}]\n X = v.fit_transform(FEATS)\n\n print(\"FEATS are\\n\", FEATS, \"\\n\")\n print(\"v is\", v)\n print(\"X is\\n\", X, \"\\n\")\n print(\"Forward: \", v.transform({'foo': 4, 'unseen_feature': 3}), \"\\n\")\n print(\"Inverse: \", v.inverse_transform(X),\"\\n\")\n\n\n\n#\n# Language-modeling example: is a name female or male?\n#\n\n# a boolean to turn on/off the name-classifier portion of the code...\nRUN_NAME_CLASSIFIER = True\nif RUN_NAME_CLASSIFIER == True:\n\n ## Read all of the names in from the nltk corpus and organize them with labels\n female_names = [(name,'f') for name in names.words('female.txt')]\n male_names = [(name,'m') for name in names.words('male.txt')]\n labeled_names = male_names + female_names\n\n ## Shuffle all of the labeled names\n # random.seed(0) # RNG seed: use this for \"reproduceable random numbers\"\n random.shuffle(labeled_names)\n\n\n #\n # Here is where the \"art\" of feature-development happens...\n #\n\n # \n ## Define the feature function; we'll modify this to improve\n ## the classifier's performance. \n #\n def gender_features(word):\n \"\"\" feature function for the female/male names example\n This function should return a dictionary of features,\n which can really be anything we might compute from the input word...\n \"\"\"\n features = {}\n features['last_letter'] = word[-1].lower()\n return features\n\n\n\n #\n # This is a better set of features -- Try it! \n #\n def gender_features_2(word):\n \"\"\" feature function for the female/male names example\n This function should return a dictionary of features,\n which can really be anything we might compute from the input word...\n \"\"\"\n features = {}\n features['last_letter'] = word[-1].lower()\n features['first_letter'] = word[0].lower()\n return features\n\n\n #\n # This is an EVEN better set of features -- Try it! \n #\n def gender_features_2(word):\n \"\"\" feature function for the female/male names example\n This function should return a dictionary of features,\n which can really be anything we might compute from the input word...\n \"\"\"\n features = defaultdict(int)\n\n features['s'] = word.count('s')\n features['y'] = word.count('y')\n features['last-letter'] = word[-1]\n\n for l in 'aeiouy':\n features['vowels'] += word.count(l)\n\n for l0 in 'aeiouy':\n for l1 in 'aeiouy':\n if (l0+l1 in word):\n features['double-vowel'] += 1\n\n return features\n\n\n\n #\n # Here is where the _reproduceable_ part of the classification happens:\n #\n\n ## Compute features and extract labels and names for the whole dataset\n features = [gender_features(name) for (name, gender) in labeled_names]\n labels = [gender for (name, gender) in labeled_names]\n names = [name for (name, gender) in labeled_names]\n\n\n ## Change the dictionary of features into an array with DictVectorizer\n ## then, create our vector of input features, X (our usual name for it...)\n v = DictVectorizer(sparse=False)\n X = v.fit_transform(features)\n\n\n ## Split the input features into train, devtest, and test sets\n X_test = X[:500,:]\n X_devtest = X[500:1500,:] # sometimes called a \"validation\" set\n X_train = X[1500:,:]\n\n ## Split the output (labels) into train, devtest, and test sets\n y_test = labels[:500]\n y_devtest = labels[500:1500]\n y_train = labels[1500:]\n\n ## Split the names themselves into train, devtest, and test sets (for reference)\n names_test = names[:500]\n names_devtest = names[500:1500]\n names_train = names[1500:]\n\n\n\n ############\n #\n # All of the set-up for the name-classification task is now ready...\n #\n ############\n\n ## Train a decision tree classifier\n #\n dt = sklearn.tree.DecisionTreeClassifier()\n dt.fit(X_train, y_train) # fit with the training data!\n\n ## Evaluate on the devtest set (with known labels) and report the accuracy\n print(\"Score on devtest set: \", dt.score(X_devtest, y_devtest))\n\n ## Predict the results for the devtest set and show the confusion matrix.\n y_guess = dt.predict(X_devtest)\n CM = confusion_matrix(y_guess, y_devtest, labels=['f','m'])\n print(\"Confusion Matrix:\\n\", CM)\n\n ## a function to predict individual names...\n def classify( name, model, feature_vectorizer, feature_function ):\n \"\"\" predictor! \"\"\"\n features = feature_function(name)\n X = feature_vectorizer.transform(features)\n guess = model.predict(X)[0]\n return guess\n\n # Example to try out...\n LoN = [ \"Zach\", \"Julie\", \"Colleen\", \"Melissa\", \"Ran\", \"Geoff\", \"Bob\", \"Jessica\" ]\n for name in LoN:\n guess = classify( name, dt, v, gender_features )\n print(guess,name)\n\n\n ## Get a list of errors to examine more closely.\n errors = []\n for i in range(len(names_devtest)):\n this_name = names_devtest[i]\n this_features = X_devtest[i:i+1,:] # slice of all features for name i\n this_label = y_devtest[i]\n guess = dt.predict(this_features)[0] # predict (guess) from the features...\n #\n # if the guess was incorrect (wrong label), remember it!\n #\n if guess != this_label:\n errors.append((this_label, guess, this_name))\n\n \n # Now, print out the results: the incorrect guesses\n # Create a flag to turn this printing on/off...\n # \n PRINT_ERRORS = False\n if PRINT_ERRORS == True:\n SE = sorted(errors)\n print(\"There were\", len(SE), \"errors:\")\n print('Name: guess (actual)')\n num_to_print = 10\n for (actual, guess, name) in SE:\n if actual == 'm' and guess == 'f': # adjust these as needed...\n print(' {0:>10}: {1} ({2})'.format(name, guess, actual))\n num_to_print -= 1\n if num_to_print == 0: break\n print()\n\n\n ## Finally, score on the test set:\n print(\"Score on test set: \", dt.score(X_test, y_test))\n\n ## Don't actually tune the algorithm for the test set, however!\n\n ## Reflection / Analysis for the name-classification example\n # \n\n \"\"\"\n Try different features, e.g.,\n + other letters\n + vowel/nonvowel in certain positions\n + presence or absence of one (or more)-letter strings ...\n \"\"\"\n\n\n\n\n\n\n" } ]
33
oylz/caffe-tensorflow
https://github.com/oylz/caffe-tensorflow
f3ec5b2916cca6d34a80d3f5e71f1995a61181c7
bb33d0d66443ffb0af900bdf9b7b87484f0cffe0
7fe189bbc9321a721225001ced455eb5b1435ae7
refs/heads/master
2021-08-30T06:20:57.035016
2017-12-16T12:41:30
2017-12-16T12:41:30
111,302,621
0
0
null
2017-11-19T14:30:51
2017-11-19T12:25:45
2016-12-06T20:54:39
null
[ { "alpha_fraction": 0.7289719581604004, "alphanum_fraction": 0.7476635575294495, "avg_line_length": 16.33333396911621, "blob_id": "863a493c82ff428fb77b9225f18e3a80c8559dd0", "content_id": "b2b45bca9d137a01a3927b8ccdbc463283b9df1a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 107, "license_type": "permissive", "max_line_length": 68, "num_lines": 6, "path": "/examples/mnist/r.sh", "repo_name": "oylz/caffe-tensorflow", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nexport PYTHONPATH=/home/xyz/code1/test4/caffe-tensorflow:$PYTHONPATH\n\n\n./finetune_mnist.py\n\n\n\n" }, { "alpha_fraction": 0.7394136786460876, "alphanum_fraction": 0.7524430155754089, "avg_line_length": 24.33333396911621, "blob_id": "82a14a2da6a8067ad8d54757ec1d3b73cafe37b9", "content_id": "6d0bdab4a5679a9edd76e714bf2719dc1204124b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 307, "license_type": "permissive", "max_line_length": 80, "num_lines": 12, "path": "/topb.sh", "repo_name": "oylz/caffe-tensorflow", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nexport LD_LIBRARY_PATH=/home/xyz/code1/caffe-xyz/distribute/lib:$LD_LIBRARY_PATH\nexport PYTHONPATH=/home/xyz/code1/caffe-xyz/distribute/python:$PYTHONPATH\nexport PYTHONPATH=/home/xyz/code1/test4/cf/oylz/caffe-tensorflow:$PYTHONPATH\n\n\n\n\npython q.py \\\n--model_dir ./out \\\n--export_path ./out\n\n\n\n" }, { "alpha_fraction": 0.6798469424247742, "alphanum_fraction": 0.6970663070678711, "avg_line_length": 22.590909957885742, "blob_id": "b64ca8ec67e4504829d82bade5180219fab9a980", "content_id": "cab159521779ad09d8ee5500ed6b5d2ccfdbbd67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1568, "license_type": "permissive", "max_line_length": 87, "num_lines": 66, "path": "/r.sh", "repo_name": "oylz/caffe-tensorflow", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n\nexport LD_LIBRARY_PATH=/usr/local/cuda-8.0-cudnn6.0/lib64/:$LD_LIBRARY_PATH\necho $LD_LIBRARY_PATH\n\nfunction F1(){\n\texport LD_LIBRARY_PATH=/home/xyz/code1/caffe-ssd/distribute/lib:$LD_LIBRARY_PATH\n\texport PYTHONPATH=/home/xyz/code1/caffe-ssd/distribute/python:$PYTHONPATH\n\techo \"PYTHONPATH:\"$PYTHONPATH\n}\n\n\nfunction Attr(){\n\tpython convert.py /home/xyz/code/face-models/AttrNet/tt.prototxt \\\n\t--caffemodel=/home/xyz/code/face-models/AttrNet/AttrNet_v1.0.caffemodel \\\n\t--data-output-path=./out/attrnet.npy \\\n\t--code-output-path=./out/attrnet.py\n\t#echo \"from .attrnet import AttrNet\" > out/__init__.py\n}\n\n\nfunction Sfd(){\n\tpython convert.py /home/xyz/code1/test4/sfd_models/deploy.prototxt \\\n\t--caffemodel=/home/xyz/code1/test4/sfd_models/SFD.caffemodel \\\n\t--data-output-path=./out/sfd.npy \\\n\t--code-output-path=./out/sfd.py\n}\n\n\nfunction Det(){\n\tII=$1\n\n\tpython convert.py /home/xyz/code1/test4/cf/oaid-caffe/mtcnn/models/det\"$II\".prototxt \\\n\t--caffemodel=/home/xyz/code1/test4/cf/oaid-caffe/mtcnn/models/det\"$II\".caffemodel \\\n\t--data-output-path=./out/det\"$II\".npy \\\n\t--code-output-path=./out/det\"$II\".py \n\t#echo \"from .det1 import PNet\" > out/__init__.py\n}\n\nfunction DDet(){\n\tII=$1\n\n\tpython convert.py /home/xyz/code/face-models/mtcnn/det\"$II\".prototxt \\\n\t--caffemodel=/home/xyz/code/face-models/mtcnn/det\"$II\".caffemodel \\\n\t--data-output-path=./out/det\"$II\".npy \\\n\t--code-output-path=./out/det\"$II\".py \n\t#echo \"from .det1 import PNet\" > out/__init__.py\n}\n\n\n\nsource ./chgpath\n\n\nF1\n#rm out -rf\n#mkdir out\n\n#Attr\n\nSfd\n\n#DDet 1\n#DDet 2\n#DDet 3\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7295082211494446, "alphanum_fraction": 0.7377049326896667, "avg_line_length": 25.478260040283203, "blob_id": "8cdeca84692aa9142a70331c9216b17b22b3f637", "content_id": "c6aa6c8611f29e69755e07a5f91ce7125d2c984f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 610, "license_type": "permissive", "max_line_length": 113, "num_lines": 23, "path": "/README.md", "repo_name": "oylz/caffe-tensorflow", "src_encoding": "UTF-8", "text": "# Caffe to TensorFlow\n\nConvert [Caffe](https://github.com/BVLC/caffe/) models to [TensorFlow](https://github.com/tensorflow/tensorflow).\n\n## Usage\n\nModify `r.sh` and run it to convert an existing Caffe model to TensorFlow.\n\nMake sure you have set pythonpath with caffe, and install tensorflow(1.4.0) to python.\n\nThe output consists of two files:\n\n1. A data file (in NumPy's native format) containing the model's learned parameters.\n2. A Python class that constructs the model's graph.\n\n### Examples\n\n\n./r.sh is an script for `convert the result to npy`\n\n\n\n./topb.sh is an script for `convert the npy to pb`\n\n" }, { "alpha_fraction": 0.4394785761833191, "alphanum_fraction": 0.4461824893951416, "avg_line_length": 46.105262756347656, "blob_id": "4bb30421188fd6f581cc622117fa51d50dd9a920", "content_id": "25ac5ec0765d05679b041427cfec08847612ad46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2685, "license_type": "permissive", "max_line_length": 120, "num_lines": 57, "path": "/q.py", "repo_name": "oylz/caffe-tensorflow", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport argparse\nimport tensorflow as tf\nfrom tensorflow.python.saved_model import builder as saved_model_builder\n\nfrom rr import aa \n\n\n\ndef export_binary_model(caffe_model_dir, export_path):\n print('Converting mtcnn model from caffe to binary')\n if not os.path.isdir(export_path):\n os.makedirs(export_path)\n model_file = os.path.join(export_path, 'attrnet.pb')\n with tf.Graph().as_default():\n sess = tf.Session(config=tf.ConfigProto(log_device_placement=False))\n with sess.as_default():\n #_, _, _ = nn.create_mtcnn(sess, caffe_model_dir)\n #output_graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def,\n # output_node_names=['pnet/prob1',\n # 'pnet/conv4-2/BiasAdd',\n # 'rnet/prob1',\n # 'rnet/conv5-2/conv5-2',\n # 'onet/prob1',\n # 'onet/conv6-2/conv6-2',\n # 'onet/conv6-3/conv6-3'])\n\n\n _ = aa.create_mtcnn(sess, caffe_model_dir)\n output_graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def,\n output_node_names=['attrnet/pose/pose',\n 'attrnet/blur/blur'])\n with tf.gfile.FastGFile(model_file, mode='wb') as f:\n f.write(output_graph_def.SerializeToString())\n print('save model to %s' % model_file)\n\n\ndef Do(args):\n export_binary_model(args.model_dir, args.export_path)\n\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--model_dir', type=str,\n help='Directory containing caffe model(.npy)')\n parser.add_argument('--export_path', type=str,\n help='Directory for model to export')\n parser.add_argument('--export_version', type=int,\n help='version number of the export model.')\n\n return parser.parse_args(argv)\n\n\nif __name__ == '__main__':\n Do(parse_arguments(sys.argv[1:]))\n" } ]
5
evorick/pendo-consulting-rick
https://github.com/evorick/pendo-consulting-rick
1c3000c9bee32375fc4b7a90c6c9b59d9ce4c0fb
992f00441a5772a38b6b50dc835a17e66d7ca825
214078413422550dc3c6632ba412fbb9350a0c50
refs/heads/master
2019-08-14T14:10:36.078835
2017-01-04T19:59:39
2017-01-04T19:59:39
68,208,448
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.692307710647583, "avg_line_length": 20, "blob_id": "5c4aba64811fb918bad4461fca3e4bc703f6ec90", "content_id": "035d24b0eeeac676cc42d47566993c5e95a637d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "no_license", "max_line_length": 36, "num_lines": 5, "path": "/opt_launcher/launcherify.py", "repo_name": "evorick/pendo-consulting-rick", "src_encoding": "UTF-8", "text": "import json\n\ntemplate = open(\"/dev/stdin\").read()\ndata = { 'template': template }\nprint json.dumps(data)" }, { "alpha_fraction": 0.7032418847084045, "alphanum_fraction": 0.7107232213020325, "avg_line_length": 39.20000076293945, "blob_id": "4d7d132e2f811c3fd97ff9c305f0a69a9dfbd2cf", "content_id": "377f0ac628e8ae224512ff0e47b0579208f7b4cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 401, "license_type": "no_license", "max_line_length": 84, "num_lines": 10, "path": "/guide_link_page_change.js", "repo_name": "evorick/pendo-consulting-rick", "src_encoding": "UTF-8", "text": "/* On the second to the last guide */\nfunction pendoPageChange() {\n pendo.onGuideAdvanced();\n $('span.filter-navigation a').click()\n}\n\n/* On the last guide (which should be completly hidden and only contain logic) */\n/* To make it hidden, you'll need a display:none; on the ._pendo_guide_container_ */\npendo.onGuideAdvanced();\npendo.findGuideById('HvMHIfU1pPnOEyiJ7yVZGccplm4').launch();" }, { "alpha_fraction": 0.5121951103210449, "alphanum_fraction": 0.5182926654815674, "avg_line_length": 32, "blob_id": "9a0ea50e9fcf52edb9bd84be4b4c0641f56318a6", "content_id": "90d6c8eef36fe113ddac8d6ee1beabf6b35ad3bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 164, "license_type": "no_license", "max_line_length": 52, "num_lines": 5, "path": "/dual-launcher/general_dual-launcher.js", "repo_name": "evorick/pendo-consulting-rick", "src_encoding": "UTF-8", "text": "$( \".tabs div\" ).click(function() {\n $( \".toggle2\" ).toggle();\n/* $( \"._pendo-launcher-search-box_\" ).toggle();*/\n $( \".tabs div\" ).toggleClass( \"active\" );\n});" }, { "alpha_fraction": 0.4895038306713104, "alphanum_fraction": 0.4948711693286896, "avg_line_length": 29.05017852783203, "blob_id": "4785c740953c8224ea004b5e0e2e2a4fbe619d0d", "content_id": "75d7d5b9f8910ca7662da53c137eed8863308cdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8384, "license_type": "no_license", "max_line_length": 132, "num_lines": 279, "path": "/opt_launcher/launcher_improvements_x.js", "repo_name": "evorick/pendo-consulting-rick", "src_encoding": "UTF-8", "text": "/*$( \".tabs div\" ).click(function() {\n $( \".toggle2\" ).toggle();\n //$( \"._pendo-launcher-search-box_\" ).toggle();\n $( \".tabs div\" ).toggleClass( \"active\" );\n});*/ \n/*The above section is for the two tab launcher.*/\n\n/*$('#somelink').on('submit',function(e) {\n if($('#id_1').val() == \"some_value\"){ //Sample error check\n e.preventDefault();\n alert($('#id_1').val());\n }\n });*/\n\n/* case #4535 */\n(function(){if ( pendo.getURL().indexOf('/v2/') !== -1 ){\n pendo.Sizzle('.\\_pendo-launcher-bottom-left\\_')[0].style.marginBottom = '190px';\n pendo.Sizzle('.\\_pendo-launcher-bottom-left\\_')[0].style.marginLeft = '15px';\n pendo.dom('._pendo-launcher-badge_').addClass('hideLauncher');\n}})();\n\n(function(){\n var _ = pendo._;\n if (pendo.log.getActiveContexts().indexOf('optimizely') > -1){\n debugger;\n }\n\n pendo.Guides = new Guides;\n\n function Guides(){\n\n /* External API*/\n this.turnOff = function(){\n flow.stop();\n };\n this.turnOn = function(){\n flow.start();\n flow.showLauncher();\n };\n this.isOn = function(){\n return isPendoEnabled();\n };\n\n var flow = new OnboardingFlow;\n\n if (this.isOn()){\n flow.start();\n }\n\n }\n\n /* XXX need this to be provided by\n Optimizely*/\n function isPendoEnabled(){\n return true;\n }\n\n function OnboardingFlow(){\n var DISMISSED = 'dismissed';\n\n var INTRO_GUIDE_X_ID = \"nUYF2cGUlr4wk3Y7mkkUYy-ejP0\";\n var INTRO_GUIDE_X_MIG_ID = \"8h6k-hEGVVAsGOALDFGS8Dv3HQI\";\n var INTRO_GUIDES = [INTRO_GUIDE_X_ID, INTRO_GUIDE_X_MIG_ID];\n /*var STEP1_GUIDE_X_ID = \"\";\n var STEP1_GUIDE_X_MIG_ID = \"\";\n var STEP1_GUIDES = [STEP1_GUIDE_X_ID, STEP1_GUIDE_X_MIG_ID];\n var DISMISS_GUIDE_X_ID = \"\";\n var DISMISS_GUIDE_X_MIG_ID = \"\";\n var DISMISS_GUIDES = [DISMISS_GUIDE_X_ID, DISMISS_GUIDE_X_MIG_ID];*/\n\n\n var Launcher = new LauncherUI;\n\n this.start = function(){\n pendo.setGuidesDisabled(false);\n pendo.startGuides();\n\n Launcher.enable();\n\n this.run();\n };\n\n this.stop = function(){\n pendo.setGuidesDisabled(true);\n pendo.stopGuides();\n\n Launcher.disable();\n\n /* if a guide is active, than dismiss it*/\n if (pendo.isGuideShown()) {\n pendo.onGuideDismissed();\n }\n };\n\n this.run = function(){\n var status = this.getStatus();\n if (status == DISMISSED) {\n /* don't show launcher list\n don't show guides*/\n } else {\n /* The below line was altered */\n /*var dismissGuide = findDismissedGuide();\n if (dismissGuide) {\n var dismissFn = pendo.onGuideDismissed;\n pendo.onGuideDismissed = function(){\n pendo.onGuideDismissed = dismissFn;\n dismissFn();\n _.defer(function(){\n dismissGuide.show();\n });\n };\n }*/\n\n this.runActive();\n }\n };\n\n /* active, dismissed, advanced*/\n this.getStatus = function(){\n return pendo.lastGuideStepSeen.state;\n };\n\n this.showLauncher = function(){\n Launcher.enable(true);\n };\n\n this.runActive = function(){\n var launcher = pendo.guideWidget;\n\n if (!hasIntroBeenSeen()) {\n /*pendo.findGuideById(INTRO_GUIDE_ID).show();*/\n showIntroGuide();\n return;\n }\n\n if (detectGuideInProgress()) {\n /* don't engage onboarding*/\n return;\n }\n\n startOnboarding();\n\n /* New functions are below. They allow for the first !null to be returned. */ \n function findIntroGuide(){\n var guides = _.map(INTRO_GUIDES, pendo.findGuideById); // returns array of guides\n return _.find(guides, function(g){return g != null;});\n }\n\n /* TODO check this code. */\n function showIntroGuide(){\n var introG = findIntroGuide();\n introG.show();\n }\n\n /*function findStep1Guide(){\n return _.find(\n _.map(STEP1_GUIDES, function(id){ \n return pendo.findGuideById(id); \n }), // [GUIDE, null] || [null,GUIDE]\n function(g){return g != null;});\n }\n\n function findDismissedGuide(){\n return _.find(\n _.map(DISMISS_GUIDES, function(id){ \n return pendo.findGuideById(id); \n }), // [GUIDE, null] || [null,GUIDE]\n function(g){return g != null;});\n }*/\n\n function hasIntroBeenSeen(){\n /*return pendo.findGuideById(INTRO_GUIDE_ID).hasBeenSeen()*/\n return findIntroGuide().hasBeenSeen();\n /*return _.any(INTRO_GUIDES, function(id){\n var g = pendo.findGuideById(id);\n if (!g) return false;\n return g.hasBeenSeen();\n });*/\n }\n\n /*function startOnboarding(){\n var step1 = findStep1Guide();\n // pendo.findGuideById(STEP1_GUIDE_ID);\n\n if (!step1) return;\n\n var state = launcher.guideStatus(step1);\n\n if (state != 'complete') {\n step1.show();\n } else {\n Launcher.showList();\n }\n }*/\n\n function detectGuideInProgress(){\n if (pendo.isGuideShown())\n return true;\n\n var lastGuideId = pendo.lastGuideStepSeen.guideId;\n if (!lastGuideId)\n return false;\n\n var lastGuide = pendo.findGuideById(lastGuideId);\n\n if (!lastGuide)\n return false;\n\n return launcher.guideStatus(lastGuide) == 'in-progress';\n }\n };\n } /* End of the onboarding flow */\n\n /*NOTE:\n building it this way b/c it might be useful in the future\n if / when we want to add optimizely help docs to this too.*/\n\n function LauncherUI (){\n var LAUNCHER_ELEM = 'img._pendo-launcher-badge_';\n \n _.defer(initUI);\n\n this.enable = function(autoOpenList){\n $(LAUNCHER_ELEM).show();\n\n if (autoOpenList)\n this.showList();\n };\n this.disable = function(){\n this.hideList();\n $(LAUNCHER_ELEM).hide();\n };\n\n this.showList = function(){\n pendo.showLauncher();\n };\n\n this.hideList = function(){\n pendo.hideLauncher();\n };\n \n function initUI() {\n $('._pendo-launcher-guide-listing_').css('height', '260px');\n $('#turn-off-help-link')\n .click(function(){\n alert('TODO: show guide about disabling all guides. also, implement persistenting this value in Optimizely.');\n return false;\n });\n }\n }\n \n/*Pendo Onboarding adjustments*/\nvar launcher = pendo.guideWidget,\n guideStatus = launcher.guideStatus;\nlauncher.guideStatus = function(guide) {\n if (pendo._.isFunction(this.getOnboardingState)) {\n return this.getOnboardingState(guide);\n } else {\n return guideStatus(guide)\n }\n};\n\n})();\n\n\n// activating a editor loading error\n// guide through the launcher\n// contact [email protected] \n// if not working correctly or feel free to remove code completely after notifying\nwindow.myInterval = setInterval(function() {\n if ($(\".loading-message\").text().indexOf('Sorry,') > -1) {\n window.console.log('pendo flow is on');\n pendo.showGuideByName('Editor Loading Error');\n clearInterval(myInterval);\n } else if ($('.iframe-parent').css('visibility') === 'visible') {\n window.console.log('pendo flow is OFF');\n clearInterval(myInterval);\n }\n}, 50);\n" }, { "alpha_fraction": 0.5682087540626526, "alphanum_fraction": 0.5688018798828125, "avg_line_length": 50.121212005615234, "blob_id": "2dd929b9eeaa3c895c2f33f5a49a25761326a9fd", "content_id": "0b6d2356b6b2e9287c2f9a872960f9900202d400", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1686, "license_type": "no_license", "max_line_length": 116, "num_lines": 33, "path": "/item_polling_guide_transition.js", "repo_name": "evorick/pendo-consulting-rick", "src_encoding": "UTF-8", "text": "<% if (template.transitionText) { %>\n function pendoTransitionOnText() {\n <% if (template.textElementOverride) { %>\n elementPathRule = '<%= template.textElementOverride %>';\n <% } else { %>\n elementPathRule = pendo.findGuideById('<%= guide.id %>').findStepById('<%= step.id %>').elementPathRule;\n <% } %>\n $(elementPathRule).on('input.pendo propertychange.pendo keydown.pendo change.pendo', function() {\n if ($.trim($(this).val().toLowerCase()) == '<%= template.transitionText %>'.toLowerCase()) {\n pendo.onGuideAdvanced();\n $(this).off('.pendo');\n }\n });\n }\n pendoTransitionOnText();\n<% } %>\n<% if (template.listElementPathRule && template.listTransitionMatch ) { %>\n console.log('<%= template.listTransitionMatch %>'.toLowerCase());\n console.log(\"<%= template.listElementPathRule %>\");\n /* Clear out namespace to prevent duplicates, this guide may re-render due to elements changing on the page */\n $(\"<%= template.listElementPathRule %>\").off('.pendo');\n $(\"<%= template.listElementPathRule %>\").on('select2-selecting.pendo', function(e){\n console.log(e.object.text.toLowerCase());\n console.log('<%= template.listTransitionMatch %>'.toLowerCase());\n if (e.object.text.toLowerCase() == '<%= template.listTransitionMatch %>'.toLowerCase()){\n pendo.onGuideAdvanced();\n $(this).off('.pendo');\n }\n })\n<% } %>\n<% if (template.onClickPath) { %>\n $('<%= template.onClickPath %>').one('click', function(){pendo.onGuideAdvanced();})\n<% } %>" } ]
5
julliffbistu/rosmsg_maskrcnn_batchreName
https://github.com/julliffbistu/rosmsg_maskrcnn_batchreName
658087b619edef8c64fc6e5836a7d841f75bd752
a5cfa8dda753d350351651240506bd80b260e332
356f2ce0327f0810c506117ca4bb97ae5238e71f
refs/heads/master
2022-11-10T00:39:51.779502
2020-06-23T08:26:36
2020-06-23T08:26:36
274,351,052
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5898778438568115, "alphanum_fraction": 0.5898778438568115, "avg_line_length": 25.045454025268555, "blob_id": "2fa9be11d8cdaf91b09f16ab3900451bef15e40c", "content_id": "cf6a529527db0b282c131980c70e5fd21c8613b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 72, "num_lines": 22, "path": "/rosselfmsg/test_msgs/gettest.py", "repo_name": "julliffbistu/rosmsg_maskrcnn_batchreName", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport rospy\nfrom test_msgs.msg import Test\n \ndef callback(data):\n print(\"-----------\",data.name)\n print(\"-----------\",data.vel)\n print(\"-----------\",data.pose.position.x)\n print(\"-----------\",data.pose.position.y)\n rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.data)\n \ndef listener():\n \n rospy.init_node('listener', anonymous=True)\n \n rospy.Subscriber(\"chatter\", Test, callback)\n \n # spin() simply keeps python from exiting until this node is stopped\n rospy.spin()\n \nif __name__ == '__main__':\n listener()\n" }, { "alpha_fraction": 0.5661538243293762, "alphanum_fraction": 0.5907692313194275, "avg_line_length": 23.9743595123291, "blob_id": "50954c58260cec3b09ecb174aefcdcc1e24481b7", "content_id": "f7e3abe3e8b7d51580290e115dd9131d4c3d64a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1093, "license_type": "no_license", "max_line_length": 57, "num_lines": 39, "path": "/rosselfmsg/test_msgs/test.py", "repo_name": "julliffbistu/rosmsg_maskrcnn_batchreName", "src_encoding": "UTF-8", "text": "# -*- coding:UTF-8 -*-\n#!/usr/bin/env python\n\nimport rospy\n#from后边是自己的包.msg,也就是自己包的msg文件夹下,test是我的msg文件名test.msg\nfrom test_msgs.msg import Test\n\n\n\ndef talker():\n pub = rospy.Publisher('chatter', Test, queue_size=10)\n rospy.init_node('talker', anonymous=True)\n rate = rospy.Rate(10) # 10hz\n while not rospy.is_shutdown():\n test=Test()\n \t#temp为到时候要用于传输的信息\n test.vel = 21.0\n test.name = \"hello\"\n test.data = [10.0]\n test.pose.position.x = 1\n test.pose.position.y = 2\n test.pose.position.z = 3\n\n test.pose.orientation.x = 0.1\n test.pose.orientation.y = 0.2\n test.pose.orientation.z = 0.3\n test.pose.orientation.w = 0.4\n\n #这里test就像构造函数般使用,若有多个msg,那么写成test(a,b,c,d...)\n #rospy.loginfo(Test.name=temp)\n print(test)\n pub.publish(test)\n rate.sleep()\n\nif __name__ == '__main__':\n try:\n talker()\n except rospy.ROSInterruptException:\n pass\n\n" } ]
2
Paras880/visibilityenhancer
https://github.com/Paras880/visibilityenhancer
ab5c723cd56888b74b367ce53435585feac0046c
12d974b2f099d445efaf00a9c2c0e0fc25ffadb4
d1feefe96e086aa1ae7412b57f1944f6c7dd458d
refs/heads/master
2023-08-17T04:23:02.895908
2021-09-20T11:49:48
2021-09-20T11:49:48
408,088,884
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.506553590297699, "alphanum_fraction": 0.5435620546340942, "avg_line_length": 36.05714416503906, "blob_id": "55797a79f0cefc69dc8a10ae64253f38f4fbb02f", "content_id": "f81bc56c3e8bf1f1d9eb0f388c705a1f14160c3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1297, "license_type": "no_license", "max_line_length": 117, "num_lines": 35, "path": "/ImageDehazer/migrations/0002_psnr_ssim.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-05-03 15:45\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ImageDehazer', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='PSNR',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('imageID', models.CharField(max_length=200)),\n ('dcp', models.FloatField(max_length=200)),\n ('gf', models.FloatField(max_length=200)),\n ('cyclicgan', models.FloatField(max_length=200)),\n ('NovelIdea', models.FloatField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='SSIM',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('imageID', models.CharField(max_length=100)),\n ('dcp', models.FloatField(max_length=200)),\n ('gf', models.FloatField(max_length=200)),\n ('cyclicgan', models.FloatField(max_length=200)),\n ('NovelIdea', models.FloatField(max_length=200)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5243619680404663, "alphanum_fraction": 0.596287727355957, "avg_line_length": 21.6842098236084, "blob_id": "671f961cad234cc44879682dcb0888a3ea4e3ddb", "content_id": "faf9f74c1df4db436a7e567ce6e252a9b89178f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 52, "num_lines": 19, "path": "/ImageDehazer/migrations/0012_myuploadfile_specialid.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-05-12 01:27\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ImageDehazer', '0011_auto_20210508_0141'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='myuploadfile',\n name='specialId',\n field=models.IntegerField(default=0),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5768667459487915, "alphanum_fraction": 0.584187388420105, "avg_line_length": 27.5, "blob_id": "e50a1d774c58c3abb4e1bc1aa47c2ddacd5952d2", "content_id": "5f513b2678f33dcb6aa99a464575a38a0a8c32a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 683, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/ImageDehazer/templates/ImageDehazer/index.html", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<body>\n <form action=\"uploads\" method=\"POST\" enctype=\"multipart/form-data\">\n <input type=\"text\" name=\"filename\" placeholder=\"enter your file name\" >\n <input type=\"file\" multiple name=\"uploadfoles\" >\n {% csrf_token %}\n <button type=\"submit\">File Upload</button>\n </form>\n\n {% for d in data %}\n \n <p> {{d.f_name}} ---- <img width=\"50\" src=\"{{d.myfiles.url}}\"></p>\n \n {% endfor %}\n \n</body>\n</html>" }, { "alpha_fraction": 0.5996835231781006, "alphanum_fraction": 0.6028481125831604, "avg_line_length": 29.095237731933594, "blob_id": "8f08a98ef1cd0d1f36233a8dadf2cdc508d33468", "content_id": "aeee70a304e5ecf54a893b5c574daef860c4509a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 632, "license_type": "no_license", "max_line_length": 86, "num_lines": 21, "path": "/ImageDehazer/static/ImageDehazer/dataset.js", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "$(function() {\n\n $('[data-toggle=\"modal\"]').hover(function() {\n var modalId = $(this).data('target');\n $(modalId).modal('show');\n \n });\n \n });\n\n // var modal = document.getElementById('#basicExampleModal');\n\n // // Get the image and insert it inside the modal - use its \"alt\" text as a caption\n // var img = document.getElementById('myImg');\n // var modalImg = document.getElementById(\"img01\");\n // var captionText = document.getElementById(\"caption\");\n // img.onclick = function(){\n // modal.style.display = \"block\";\n // modalImg.src = this.src;\n // captionText.innerHTML = this.alt;\n // }\n" }, { "alpha_fraction": 0.5347431898117065, "alphanum_fraction": 0.5891238451004028, "avg_line_length": 18.47058868408203, "blob_id": "4a9249b910d7df9d5a61c7b23b02c26de31c0200", "content_id": "005972fcbbe696e12b5b58989a390f99507caa87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "no_license", "max_line_length": 46, "num_lines": 17, "path": "/ImageDehazer/migrations/0010_remove_myuploadfile_f_name.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-05-07 20:10\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ImageDehazer', '0009_myuploadfile'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='myuploadfile',\n name='f_name',\n ),\n ]\n" }, { "alpha_fraction": 0.6660616993904114, "alphanum_fraction": 0.7074410319328308, "avg_line_length": 44.91666793823242, "blob_id": "ea1f9cd13ad3e2d76318fbfd3678f4ece49035ec", "content_id": "f3c25e8798256e47a6087fa7e03e99a8d192cb86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2755, "license_type": "no_license", "max_line_length": 80, "num_lines": 60, "path": "/ImageDehazer/models.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nclass Image(models.Model):\n photo = models.ImageField(upload_to = \"myimage\")\n date = models.DateTimeField(auto_now_add=True)\n\nclass myuploadfile(models.Model):\n specialId = models.IntegerField()\n name = models.CharField(null= True ,max_length=200)\n myfiles = models.FileField(upload_to=\"myimage\")\n dcp = models.FileField(upload_to=\"myimage\")\n gf = models.FileField(upload_to=\"myimage\" )\n cyclicgan = models.FileField(upload_to=\"myimage\")\n NovelIdea = models.FileField(upload_to=\"myimage\")\n dcp_psnr = models.FloatField(max_length=200, null= True)\n gf_psnr = models.FloatField(max_length=200 , null= True)\n cyclicgan_psnr = models.FloatField(default = 0, max_length=200 , null= True)\n NovelIdea_psnr = models.FloatField(default = 0, max_length=200 , null= True)\n dcp_ssim = models.FloatField(max_length=200 , null= True)\n gf_ssim = models.FloatField(max_length=200 , null= True)\n cyclicgan_ssim = models.FloatField(default = 0, max_length=200 , null= True)\n NovelIdea_ssim = models.FloatField(default = 0, max_length=200 , null= True)\n\n\nclass PSNR(models.Model):\n imageID = models.CharField(primary_key = True , max_length=200)\n dcp = models.FloatField(max_length=200)\n gf = models.FloatField(max_length=200)\n cyclicgan = models.FloatField(default = 0, max_length=200 , null= True)\n NovelIdea = models.FloatField(default = 0, max_length=200 , null= True)\n\n\nclass SSIM(models.Model):\n imageID = models.CharField(primary_key = True , max_length=200)\n dcp = models.FloatField(max_length=200)\n gf = models.FloatField(max_length=200)\n cyclicgan = models.FloatField(default = 0, max_length=200 , null= True)\n NovelIdea = models.FloatField(default = 0, max_length=200 , null= True)\n\nclass PARAMS(models.Model):\n imageID = models.CharField(primary_key = True , max_length=200)\n pdcp = models.FloatField(max_length=200)\n pgf = models.FloatField(max_length=200)\n pcyclicgan = models.FloatField(default = 0, max_length=200 , null= True)\n pNovelIdea = models.FloatField(default = 0, max_length=200 , null= True)\n sdcp = models.FloatField(max_length=200)\n sgf = models.FloatField(max_length=200)\n scyclicgan = models.FloatField(default = 0, max_length=200 , null= True)\n sNovelIdea = models.FloatField(default = 0, max_length=200 , null= True)\n\nclass Feedback(models.Model):\n Name = models.CharField(max_length=200)\n Email = models.CharField(max_length=200, null = True)\n Message = models.CharField(max_length=200) \n\nclass Contact(models.Model):\n Name = models.CharField(max_length=200)\n Email = models.CharField(max_length=200, null = True)\n Message = models.CharField(max_length=200) " }, { "alpha_fraction": 0.6863496899604797, "alphanum_fraction": 0.6863496899604797, "avg_line_length": 39.78125, "blob_id": "1bf7a361cf5420ff120e243125a7e4c92313ac27", "content_id": "83303fafc0d5866680544c61fc034215015f9304", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1304, "license_type": "no_license", "max_line_length": 224, "num_lines": 32, "path": "/ImageDehazer/admin.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Feedback, Image, PARAMS, PSNR, SSIM, myuploadfile, Feedback, Contact \nfrom import_export.admin import ImportExportModelAdmin\n\n# Register your models here.\[email protected](Image)\nclass ImageAdmin(admin.ModelAdmin):\n list_display = ['id' , 'photo' , 'date']\n\[email protected](PSNR)\nclass PSNRAdmin(admin.ModelAdmin):\n list_display = ['imageID' , 'dcp' , 'gf' , 'cyclicgan' , 'NovelIdea']\n\[email protected](SSIM)\nclass SSIMAdmin(admin.ModelAdmin):\n list_display = ['imageID' , 'dcp' , 'gf' , 'cyclicgan' , 'NovelIdea']\n\[email protected](PARAMS)\nclass PARAMSAdmin(admin.ModelAdmin):\n list_display = ['imageID' , 'pdcp' , 'pgf' , 'pcyclicgan' , 'pNovelIdea', 'sdcp' , 'sgf' , 'scyclicgan' , 'sNovelIdea']\n\[email protected](myuploadfile)\nclass myuploadfileAdmin(admin.ModelAdmin):\n list_display = ['id' ,'name' , 'specialId','myfiles' , 'dcp', 'gf' , 'cyclicgan' , 'NovelIdea', 'dcp_psnr' , 'gf_psnr' , 'cyclicgan_psnr' , 'NovelIdea_psnr' , 'dcp_ssim' , 'gf_ssim' , 'cyclicgan_ssim' , 'NovelIdea_ssim']\n\[email protected](Feedback)\nclass FeedbackAdmin(admin.ModelAdmin):\n list_display = ['id' , 'Name' , 'Email' , 'Message']\n\[email protected](Contact)\nclass ContactAdmin(admin.ModelAdmin):\n list_display = ['id' , 'Name' , 'Email' , 'Message']" }, { "alpha_fraction": 0.5361056327819824, "alphanum_fraction": 0.5637511014938354, "avg_line_length": 32.364341735839844, "blob_id": "dece9b9a05afb0963cf014c628a3cbd182887c08", "content_id": "97fb3d6db0c6e9bb081329c656c2f56498e36e52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25827, "license_type": "no_license", "max_line_length": 339, "num_lines": 774, "path": "/ImageDehazer/views.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .forms import ImageForm\nfrom .models import Image, PARAMS\nfrom .models import PSNR\nfrom .models import SSIM , myuploadfile , Feedback, Contact\nfrom .resources import PSNRResource\nfrom .resources import SSIMResource\nfrom .resources import PARAMSResource\nfrom tablib import Dataset\nfrom .utils import get_plot\nfrom django.db.models import Q\n# from IO import StringIO\n# import cStringIO as cs\nimport zipfile as z\nfrom zipfile import ZipFile\nimport random\nfrom PIL import Image as im\nimport cv2;\nimport math;\nimport numpy as np;\nimport sys\nimport os\nimport datetime\n# Create your views here.\n\nfrom . models import myuploadfile\n\n# pdf file viewer\n\nfrom django.http import HttpResponse\nfrom django.views.generic import View\n\nfrom .utils import render_to_pdf #created in step 4\n\n\n# Create your views here.\n# def download(request): \n \n# f = cs.StringIO() # or a file on disk in write-mode\n# zf = z.ZipFile(f, 'w', z.ZIP_DEFLATED)\n\n# # in_memory = StringIO()\n# # zip = ZipFile(in_memory, \"a\")\n\n# dcpphoto = request.POST.get(\"dcpphoto\")\n# gfphoto = request.POST.get(\"gfphoto\") \n \n# zf.writestr(dcpphoto , \"darkchannelprior\")\n# zf.writestr(gfphoto , \"guidedfilter\")\n \n# # fix for Linux zip files read in Windows\n# for file in zf.filelist:\n# file.create_system = 0 \n \n# zf.close()\n\n# response = HttpResponse(mimetype=\"application/zip\")\n# response[\"Content-Disposition\"] = \"attachment; filename=two_files.zip\"\n \n# # in_memory.seek(0) \n# # response.write(in_memory.read())\n \n# return response\ndef contact(request):\n if request.method == \"POST\" :\n name = request.POST.get(\"name\")\n EmailAddress = request.POST.get(\"email\")\n message = request.POST.get(\"message\")\n \n if (name != None and EmailAddress != None and message != None):\n Contact(Name = name , Email = EmailAddress , Message= message).save()\n \n return render(request, \"ImageDehazer/index1.html\")\n\ndef feedback(request):\n if request.method == \"POST\" :\n name = request.POST.get(\"name\")\n EmailAddress = request.POST.get(\"email\")\n message = request.POST.get(\"message\")\n print(name , EmailAddress , message)\n\n\n if (name != None and EmailAddress != None and message != None):\n Feedback(Name = name , Email = EmailAddress , Message= message).save()\n \n return render(request, \"ImageDehazer/index1.html\")\n\n\n\n\n\ndef index(request):\n context = {\n \"data\":myuploadfile.objects.all(),\n }\n return render(request,\"ImageDehazer/index.html\",context)\n\ndef Psnr(img1, img2):\n # img1 and img2 have range [0, 255]\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n mse = np.mean((img1 - img2)**2)\n if mse == 0:\n return float('inf')\n return 20 * math.log10(255.0 / math.sqrt(mse))\n\ndef Ssim(img1, img2):\n C1 = (0.01 * 255)**2\n C2 = (0.03 * 255)**2\n\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n kernel = cv2.getGaussianKernel(11, 1.5)\n window = np.outer(kernel, kernel.transpose())\n\n mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid\n mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]\n mu1_sq = mu1**2\n mu2_sq = mu2**2\n mu1_mu2 = mu1 * mu2\n sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq\n sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq\n sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *\n (sigma1_sq + sigma2_sq + C2))\n return ssim_map.mean()\n\n\ndef calculate_ssim(img1, img2):\n '''calculate SSIM\n the same outputs as MATLAB's\n img1, img2: [0, 255]\n '''\n if not img1.shape == img2.shape:\n raise ValueError('Input images must have the same dimensions.')\n if img1.ndim == 2:\n return ssim(img1, img2)\n elif img1.ndim == 3:\n if img1.shape[2] == 3:\n ssims = []\n for i in range(3):\n ssims.append(ssim(img1, img2))\n return np.array(ssims).mean()\n elif img1.shape[2] == 1:\n return ssim(np.squeeze(img1), np.squeeze(img2))\n else:\n raise ValueError('Wrong input image dimensions.')\n\n\n\ndef DarkChannel(im,sz):\n b,g,r = cv2.split(im)\n #print(b , g , r)\n dc = cv2.min(cv2.min(r,g),b);\n #print(dc)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(sz,sz))\n dark = cv2.erode(dc,kernel)\n return dark\n\ndef AtmLight(im,dark):\n [h,w] = im.shape[:2]\n imsz = h*w\n numpx = int(max(math.floor(imsz/1000),1))\n darkvec = dark.reshape(imsz);\n imvec = im.reshape(imsz,3);\n\n indices = darkvec.argsort();\n indices = indices[imsz-numpx::]\n\n atmsum = np.zeros([1,3])\n for ind in range(1,numpx):\n atmsum = atmsum + imvec[indices[ind]]\n\n A = atmsum / numpx;\n return A\n\ndef TransmissionEstimate(im,A,sz):\n omega = 0.95;\n im3 = np.empty(im.shape,im.dtype);\n\n for ind in range(0,3):\n im3[:,:,ind] = im[:,:,ind]/A[0,ind]\n\n transmission = 1 - omega*DarkChannel(im3,sz);\n return transmission\n\ndef Guidedfilter(im,p,r,eps):\n mean_I = cv2.boxFilter(im,cv2.CV_64F,(r,r));\n mean_p = cv2.boxFilter(p, cv2.CV_64F,(r,r));\n mean_Ip = cv2.boxFilter(im*p,cv2.CV_64F,(r,r));\n cov_Ip = mean_Ip - mean_I*mean_p;\n\n mean_II = cv2.boxFilter(im*im,cv2.CV_64F,(r,r));\n var_I = mean_II - mean_I*mean_I;\n\n a = cov_Ip/(var_I + eps);\n b = mean_p - a*mean_I;\n\n mean_a = cv2.boxFilter(a,cv2.CV_64F,(r,r));\n mean_b = cv2.boxFilter(b,cv2.CV_64F,(r,r));\n\n q = mean_a*im + mean_b;\n return q;\n\ndef TransmissionRefine(im,et):\n gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY);\n gray = np.float64(gray)/255;\n r = 60;\n eps = 0.0001;\n t = Guidedfilter(gray,et,r,eps);\n\n return t;\n\ndef Recover(im,t,A,tx = 0.1):\n res = np.empty(im.shape,im.dtype);\n t = cv2.max(t,tx);\n\n for ind in range(0,3):\n res[:,:,ind] = (im[:,:,ind]-A[0,ind])/t + A[0,ind]\n\n return res\n\noriginal = \"\"\nname = \"\"\npsnr = 0\nssim = 0\nmethod = \"\"\n\ndef send_files(request):\n if request.method == \"POST\" :\n name = request.POST.get(\"filename\")\n myfile = request.FILES.getlist(\"uploadfoles\")\n method = request.POST.get(\"method\")\n print(\"method - \", method)\n if (len(myfile) == 1 and method != \"all\"):\n Image(photo=myfile[0]).save()\n img = Image.objects.all()\n originalpdf = img.last().photo.path\n original = img.last().photo.url\n src = cv2.imread(\".\" + img.last().photo.url);\n I = src.astype('float64')/255;\n\n dark = DarkChannel(I,15);\n A = AtmLight(I,dark);\n te = TransmissionEstimate(I,A,15);\n t = TransmissionRefine(src,te);\n\n if(method == \"DCP\"):\n J = Recover(I,te,A,0.1);\n elif(method == \"GUIDED\"):\n J = Recover(I,t,A,0.1);\n\n \n name = \".\"+ img.last().photo.url.split(\".\")[0] + str(random.randint(0,9)) + \".png\"\n a = originalpdf.split(\"\\\\\")\n print(a)\n imagename = name.split(\"/\")[-1]\n a[-1] = name.split(\"/\")[-1]\n dehazedpdf = \"\\\\\".join(a)\n\n print(\"Exception\")\n print(dehazedpdf)\n print(originalpdf)\n print(\"exceptin\")\n cv2.imwrite(name,J*255);\n\n psnr = round(Psnr(src , J*255) , 3)\n ssim = round(Ssim(src , J*255) , 3)\n print(imagename)\n return render(request , \"ImageDehazer/Single-Results.html\" , {'imagename':imagename , 'dehazedpdf':dehazedpdf , 'originalpdf': originalpdf , 'dehazedphoto' : name , 'originalphoto' : original , 'psnr': psnr , 'ssim' :ssim , \"method\": method})\n\n else:\n new_id = random.randint(1,1000000)\n no_files = len(myfile)\n for f in myfile:\n myuploadfile(specialId = new_id , name = f, myfiles=f).save()\n \n \n new_images = myuploadfile.objects.filter(specialId = new_id)\n \n for i in new_images:\n \n src = cv2.imread(\".\" + i.myfiles.url);\n I = src.astype('float64')/255;\n\n dark = DarkChannel(I,15);\n A = AtmLight(I,dark);\n te = TransmissionEstimate(I,A,15);\n t = TransmissionRefine(src,te);\n\n if(method == \"DCP\"):\n J = Recover(I,te,A,0.1);\n elif(method == \"GUIDED\"):\n J = Recover(I,t,A,0.1);\n elif(method == \"all\"):\n #DCP\n J = Recover(I,te,A,0.1);\n name = i.myfiles.url.split(\"/\")[-2] + \"/\" +i.myfiles.url.split(\"/\")[-1] + \"DCP\" + \".jpeg\"\n save_name = \"./media/\"+name\n cv2.imwrite(save_name,J*255)\n procecssed = myuploadfile.objects.get(myfiles = i.myfiles)\n procecssed.dcp = name\n procecssed.dcp_psnr = round(Psnr(src , J*255) , 3)\n procecssed.dcp_ssim = round(Ssim(src , J*255) , 3)\n procecssed.save()\n\n #GUIDED FILTER\n J = Recover(I,t,A,0.1);\n name = i.myfiles.url.split(\"/\")[-2] + \"/\" +i.myfiles.url.split(\"/\")[-1] + \"GF\" + \".jpeg\"\n save_name = \"./media/\"+name\n cv2.imwrite(save_name,J*255)\n procecssed = myuploadfile.objects.get(myfiles = i.myfiles)\n procecssed.gf = name\n procecssed.gf_psnr = round(Psnr(src , J*255) , 3)\n procecssed.gf_ssim = round(Ssim(src , J*255) , 3)\n procecssed.save()\n print(\"one\")\n\n if(len(myfile) == 1):\n all_images = myuploadfile.objects.filter(specialId = new_id)\n print(all_images)\n return render(request , \"ImageDehazer/Multiple-Results.html\" , {\"files\" : all_images[0]} )\n \n if(method != \"all\"):\n print(\"all\")\n name = i.myfiles.url.split(\"/\")[-2] + \"/\" +i.myfiles.url.split(\"/\")[-1] + method + \".jpeg\"\n save_name = \"./media/\"+name\n \n cv2.imwrite(save_name,J*255)\n procecssed = myuploadfile.objects.get(myfiles = i.myfiles)\n print(procecssed)\n\n if(method == \"DCP\"):\n procecssed.dcp = name\n procecssed.dcp_psnr = round(Psnr(src , J*255) , 3)\n procecssed.dcp_ssim = round(Ssim(src , J*255) , 3)\n elif(method == \"GUIDED\"):\n procecssed.gf = name\n procecssed.gf_psnr = round(Psnr(src , J*255) , 3)\n procecssed.gf_ssim = round(Ssim(src , J*255) , 3)\n procecssed.save()\n\n dcp_images = myuploadfile.objects.filter(specialId = new_id)\n if(method == \"all\"):\n Everything = myuploadfile.objects.filter(specialId = new_id)\n return render(request , \"ImageDehazer/Multiplemethods.html\" , {\"files\" : Everything} )\n else:\n return render(request , \"ImageDehazer/Singlemethod.html\" , {\"method\" : method , \"files\" : dcp_images} )\n # uploaded_dataset.append(f)\n # print(uploaded_dataset)\n \n # for img in myuploadfile.objects.all():\n # print(img)\n # if img.myfiles in uploaded_dataset:\n # print(img.myfiles)\n \n # src = cv2.imread(\".\" + myuploadfile.myfiles.name );\n # I = src.astype('float64')/255;\n\n # dark = DarkChannel(I,15);\n # A = AtmLight(I,dark);\n # te = TransmissionEstimate(I,A,15);\n # t = TransmissionRefine(src,te);\n # J = Recover(I,te,A,0.1);\n # Jgf = Recover(I,t,A,0.1);\n \n # name = \".\"+ img.last().photo.url.split(\".\")[0] + str(random.randint(0,9)) + \".png\"\n # cv2.imwrite(name,J*255);\n # cv2.imwrite(name,J*255);\n\n # psnr = Psnr(src , J*255)\n # ssim = Ssim(src , J*255)\n return redirect(\"/\")\n\ndef simple_upload(request):\n if request.method == 'POST':\n ssim_resource = SSIMResource()\n dataset = Dataset()\n new_ssim = request.FILES['myFile']\n print(new_ssim)\n\n imported_data = dataset.load(new_ssim.read(),format='xlsx')\n #print(imported_data)\n for data in imported_data:\n print(data)\n value = SSIM(\n \t\t data[0],\n \t\t data[1],\n data[2],\n \t\t data[3],\n \t\t data[4],\n )\n value.save() \n \n #result = person_resource.import_data(dataset, dry_run=True) # Test the data import\n\n #if not result.has_errors():\n # person_resource.import_data(dataset, dry_run=False) # Actually import now\n\n return render(request, 'ImageDehazer/upload.html')\n\ndef upload(request):\n return render(request , \"ImageDehazer/upload.html\")\n\n# def home(request):\n# form = ImageForm()\n# # img = Image.objects.all()\n# #print(\"images\" , img[0].photo)\n# return render(request , \"ImageDehazer/form.html\" ,{'form':form })\ndef home(request):\n first = Feedback.objects.get(id = 2)\n \n feed = Feedback.objects.filter(~Q(id=2))\n\n return render(request, \"ImageDehazer/index1.html\" , {\"first\":first , \"feed\":feed})\n \ndef Dehazingmethods(request):\n\n return render(request, \"ImageDehazer/Dehazing-Methods.html\")\n \n\ndef datasets1(request):\n List = os.listdir(\"C:/Users/PARAS/Desktop/hello_django/ImageDehazer/static/ImageDehazer/SOTS/indoor/hazy\")\n images = []\n for i in List:\n images.append(\"ImageDehazer/SOTS/indoor/hazy/\" + i)\n length = len(images)\n image = zip(images , List)\n params = PARAMS.objects.all()\n return render(request,'ImageDehazer/Reside-Dataset.html', {'image' : image , \"params\" : params})\ndef datasets2(request):\n List = os.listdir(\"C:/Users/PARAS/Desktop/hello_django/ImageDehazer/static/ImageDehazer/SOTS/outdoor/hazy\")\n images = []\n for i in List:\n images.append(\"ImageDehazer/SOTS/outdoor/hazy/\" + i)\n length = len(images)\n image = zip(images , List)\n params = PARAMS.objects.all()\n return render(request,'ImageDehazer/Reside-Dataset.html', {'image' : image , \"params\" : params})\n\ndef dataseth1(request):\n List = os.listdir(\"C:/Users/PARAS/Desktop/hello_django/ImageDehazer/static/ImageDehazer/HSTS/real-world\")\n images = []\n for i in List:\n images.append(\"ImageDehazer/HSTS/real-world/\" + i)\n length = len(images)\n image = zip(images , List)\n params = PARAMS.objects.all()\n return render(request,'ImageDehazer/Reside-Dataset.html', {'image' : image , \"params\" : params})\n\ndef dataseth2(request):\n List = os.listdir(\"C:/Users/PARAS/Desktop/hello_django/ImageDehazer/static/ImageDehazer/HSTS/synthetic/synthetic\")\n images = []\n for i in List:\n images.append(\"ImageDehazer/HSTS/synthetic/synthetic/\" + i)\n length = len(images)\n image = zip(images , List)\n params = PARAMS.objects.all()\n return render(request,'ImageDehazer/Reside-Dataset.html', {'image' : image , \"params\" : params})\n\ndef enlarge(request):\n imageId = request.POST.get('imageId')\n print(imageId)\n imageId = imageId[8:]\n splitwords = imageId.split(\"/\")\n image = splitwords[-1]\n params = PARAMS.objects.all()\n\n valssim1 = 0\n valssim2 = 0\n valpsnr1 = 0\n valpsnr2 = 0\n print(image)\n\n for i in params:\n print(i)\n if i.imageID == image:\n valpsnr1 = i.pdcp\n valpsnr2 = i.pgf\n valssim1 = i.sdcp\n valssim2 = i.sgf\n\n base = \"C:\\\\Users\\\\PARAS\\\\Desktop\\\\hello_django\\\\ImageDehazer\\\\static\\\\ImageDehazer\"\n # algo for attaching corresponding image results\n imagepdf = \"\"\n imagedcp = \"\"\n imagedcppdf = \"\"\n imagegf = \"\"\n imagegfpdf = \"\"\n\n if (splitwords[-3] == \"HSTS\" or splitwords[-3] == \"synthetic\"):\n if (splitwords[-2] == \"real-world\"):\n imagepdf = base + \"\\\\HSTS\\\\real-world\"+ image\n splitwords[-2] = \"real-worldoutputdcp\"\n imagedcp ='/'.join(splitwords)\n imagedcppdf = base + \"\\\\HSTS\\\\real-worldoutputdcp\\\\\"+image\n splitwords[-2] = \"real-worldoutputgf\"\n imagegf ='/'.join(splitwords)\n imagegfpdf = base + \"\\\\HSTS\\\\real-worldoutputgf\\\\\"+ image\n elif (splitwords[-2] == \"synthetic\"):\n imagepdf = base + \"\\\\HSTS\\\\synthetic\\\\synthetic\\\\\"+image\n splitwords[-2] = \"syntheticoutputdcp\"\n imagedcp ='/'.join(splitwords)\n imagedcppdf = base + \"\\\\HSTS\\\\synthetic\\\\syntheticoutputdcp\\\\\"+image\n splitwords[-2] = \"syntheticoutputgf\"\n imagegf ='/'.join(splitwords)\n imagegfpdf = base + \"\\\\HSTS\\\\synthetic\\\\syntheticoutputgf\\\\\"+image\n elif (splitwords[-3] == \"outdoor\" or splitwords[-3] == \"indoor\"):\n if (splitwords[-3] == \"outdoor\"):\n imagepdf = base + \"\\\\SOTS\\\\outdoor\\\\hazy\\\\\"+image\n if(splitwords[-2] == \"hazyoutputdcp\"):\n imagedcppdf = base +\"\\\\SOTS\\\\outdoor\\\\hazyoutputdcp\\\\\"+image\n elif(splitwords[-2] == \"hazyoutputgf\"):\n imagegfpdf = base +\"\\\\SOTS\\\\outdoor\\\\hazyoutputgf\\\\\"+image\n elif (splitwords[-3] == \"indoor\"):\n imagepdf = base + \"\\\\SOTS\\\\indoor\\\\hazy\\\\\"+image\n if(splitwords[-2] == \"hazyoutputdcp\"):\n imagedcppdf = base +\"\\\\SOTS\\\\indoor\\\\hazyoutputdcp\\\\\"+image\n elif(splitwords[-2] == \"hazyoutputgf\"):\n imagegfpdf = base +\"\\\\SOTS\\\\indoor\\\\hazyoutputgf\\\\\"+image\n splitwords[-2] = \"hazyoutputdcp\"\n imagedcp ='/'.join(splitwords)\n splitwords[-2] = \"hazyoutputgf\"\n imagegf ='/'.join(splitwords)\n\n\n print(imageId)\n print(imagedcp)\n print(imagegf)\n\n # qs = PARAMS.objects.filter(imageID = image)\n # x = [qs[0].pdcp , qs[0].pgf , 0 , 0]\n # y = [qs[0].sdcp , qs[0].sgf , 0 , 0] \n # chart = get_plot(x ,y)\n # print(chart)\n chart = \"\"\n return render(request,'ImageDehazer/Dataset-Results.html' , { \"chart\" : chart , \"imagegfpdf\":imagegfpdf , \"imagedcppdf\" :imagedcppdf , \"imagepdf\":imagepdf , \"imagename\" : image , \"imageId\" : imageId , \"imagedcp\" : imagedcp , \"imagegf\" : imagegf , \"psnrdcp\" : valpsnr1 , \"psnrgf\" : valpsnr2 , \"ssimdcp\": valssim1 , \"ssimgf\" : valssim2})\n\ndef new(request):\n method = request.POST.get('method')\n print(method)\n return render(request,'ImageDehazer/Upload-Image (2).html' ,{'method': method})\n\ndef Psnr(img1, img2):\n # img1 and img2 have range [0, 255]\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n mse = np.mean((img1 - img2)**2)\n if mse == 0:\n return float('inf')\n return 20 * math.log10(255.0 / math.sqrt(mse))\n\ndef Ssim(img1, img2):\n C1 = (0.01 * 255)**2\n C2 = (0.03 * 255)**2\n\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n kernel = cv2.getGaussianKernel(11, 1.5)\n window = np.outer(kernel, kernel.transpose())\n\n mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid\n mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]\n mu1_sq = mu1**2\n mu2_sq = mu2**2\n mu1_mu2 = mu1 * mu2\n sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq\n sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq\n sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *\n (sigma1_sq + sigma2_sq + C2))\n return ssim_map.mean()\n\n\ndef calculate_ssim(img1, img2):\n '''calculate SSIM\n the same outputs as MATLAB's\n img1, img2: [0, 255]\n '''\n if not img1.shape == img2.shape:\n raise ValueError('Input images must have the same dimensions.')\n if img1.ndim == 2:\n return ssim(img1, img2)\n elif img1.ndim == 3:\n if img1.shape[2] == 3:\n ssims = []\n for i in range(3):\n ssims.append(ssim(img1, img2))\n return np.array(ssims).mean()\n elif img1.shape[2] == 1:\n return ssim(np.squeeze(img1), np.squeeze(img2))\n else:\n raise ValueError('Wrong input image dimensions.')\n\n\n\ndef DarkChannel(im,sz):\n b,g,r = cv2.split(im)\n #print(b , g , r)\n dc = cv2.min(cv2.min(r,g),b);\n #print(dc)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(sz,sz))\n dark = cv2.erode(dc,kernel)\n return dark\n\ndef AtmLight(im,dark):\n [h,w] = im.shape[:2]\n imsz = h*w\n numpx = int(max(math.floor(imsz/1000),1))\n darkvec = dark.reshape(imsz);\n imvec = im.reshape(imsz,3);\n\n indices = darkvec.argsort();\n indices = indices[imsz-numpx::]\n\n atmsum = np.zeros([1,3])\n for ind in range(1,numpx):\n atmsum = atmsum + imvec[indices[ind]]\n\n A = atmsum / numpx;\n return A\n\ndef TransmissionEstimate(im,A,sz):\n omega = 0.95;\n im3 = np.empty(im.shape,im.dtype);\n\n for ind in range(0,3):\n im3[:,:,ind] = im[:,:,ind]/A[0,ind]\n\n transmission = 1 - omega*DarkChannel(im3,sz);\n return transmission\n\ndef Guidedfilter(im,p,r,eps):\n mean_I = cv2.boxFilter(im,cv2.CV_64F,(r,r));\n mean_p = cv2.boxFilter(p, cv2.CV_64F,(r,r));\n mean_Ip = cv2.boxFilter(im*p,cv2.CV_64F,(r,r));\n cov_Ip = mean_Ip - mean_I*mean_p;\n\n mean_II = cv2.boxFilter(im*im,cv2.CV_64F,(r,r));\n var_I = mean_II - mean_I*mean_I;\n\n a = cov_Ip/(var_I + eps);\n b = mean_p - a*mean_I;\n\n mean_a = cv2.boxFilter(a,cv2.CV_64F,(r,r));\n mean_b = cv2.boxFilter(b,cv2.CV_64F,(r,r));\n\n q = mean_a*im + mean_b;\n return q;\n\ndef TransmissionRefine(im,et):\n gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY);\n gray = np.float64(gray)/255;\n r = 60;\n eps = 0.0001;\n t = Guidedfilter(gray,et,r,eps);\n\n return t;\n\ndef Recover(im,t,A,tx = 0.1):\n res = np.empty(im.shape,im.dtype);\n t = cv2.max(t,tx);\n\n for ind in range(0,3):\n res[:,:,ind] = (im[:,:,ind]-A[0,ind])/t + A[0,ind]\n\n return res\n\noriginal = \"\"\nname = \"\"\npsnr = 0\nssim = 0\nmethod = \"\"\n\ndef dehaze(request):\n\n if request.method == 'POST':\n print(request.POST)\n print(request.FILES)\n form = ImageForm(request.POST , request.FILES)\n print(form)\n if form.is_valid():\n form.save()\n \n\n dcp = request.POST.get('dcp' , \"off\")\n print(dcp)\n guidedfilter = request.POST.get('guidedfilter' , \"off\")\n print(guidedfilter)\n nonlocalprior = request.POST.get('nonlocalprior' , \"off\")\n print(nonlocalprior)\n # try:\n # fn = sys.argv[1] \n # except:\n # fn = photo\n img = Image.objects.all()\n print(\"nbn nmn\")\n print(img)\n def nothing(*argv):\n pass\n\n print(img.last().photo.path)\n originalpdf = img.last().photo.path\n original = img.last().photo.url\n src = cv2.imread(\".\" + img.last().photo.url);\n I = src.astype('float64')/255;\n\n dark = DarkChannel(I,15);\n A = AtmLight(I,dark);\n te = TransmissionEstimate(I,A,15);\n t = TransmissionRefine(src,te);\n\n if(dcp == \"on\"):\n method = \"DCP\"\n J = Recover(I,te,A,0.1);\n elif(guidedfilter == \"on\"):\n method = \"GUIDED FILTER\"\n J = Recover(I,t,A,0.1);\n \n name = \".\"+ img.last().photo.url.split(\".\")[0] + str(random.randint(0,9)) + \".png\"\n a = originalpdf.split(\"\\\\\")\n print(a)\n print(name.split(\"/\")[-1])\n a[-1] = name.split(\"/\")[-1]\n dehazedpdf = \"\\\\\".join(a)\n\n print(\"Exception\")\n print(dehazedpdf)\n print(originalpdf)\n print(\"exceptin\")\n cv2.imwrite(name,J*255);\n\n psnr = Psnr(src , J*255)\n ssim = Ssim(src , J*255)\n\n return render(request , \"ImageDehazer/Single-Results.html\" , {'dehazedpdf':dehazedpdf , 'originalpdf': originalpdf , 'dehazedphoto' : name , 'originalphoto' : original , 'psnr': psnr , 'ssim' :ssim , \"method\": method})\n \ndef get(request):\n originalphoto = request.POST.get('originalphoto')\n dehazedphoto = request.POST.get('dehazedphoto')\n method = request.POST.get('method')\n psnr = request.POST.get('psnr')\n ssim = request.POST.get('ssim')\n imagename = request.POST.get('imagename')\n # originalphoto = originalphoto[1:]\n # dehazedphoto = dehazedphoto[2:]\n print(originalphoto , dehazedphoto , psnr , ssim , method)\n pdf = render_to_pdf('ImageDehazer/invoice.html',{'imagename' :imagename , 'dehazedphoto' : dehazedphoto , 'originalphoto' : originalphoto , 'psnr': psnr , 'ssim' :ssim , \"method\": method})\n return HttpResponse(pdf, content_type='application/pdf')\n\ndef datasetpdf(request):\n originalphoto = request.POST.get('originalphoto')\n imagename = request.POST.get('imagename')\n dcpphoto = request.POST.get('dcpphoto')\n gfphoto = request.POST.get('gfphoto')\n\n params = PARAMS.objects.all()\n \n for i in params:\n if (i.imageID == imagename):\n localparam = i\n\n\n pdf = render_to_pdf('ImageDehazer/MultipleImageReport.html',{'imagename' :imagename ,\"originalphoto\" : originalphoto , \"dcpphoto\" :dcpphoto , \"gfphoto\" : gfphoto , \"local\" : localparam})\n return HttpResponse(pdf, content_type='application/pdf')\n\n\ndef qa(request):\n params = PARAMS.objects.all()\n print(\"fnkldslkvndkvn\")\n return render(request, \"ImageDehazer/Quantitative-Analysis.html\" , {\"params\" : params}) " }, { "alpha_fraction": 0.5859031081199646, "alphanum_fraction": 0.6090308427810669, "avg_line_length": 27.390625, "blob_id": "b09b9ba271e3ef5cde50d0711a5da903d2b3fa7a", "content_id": "e154c554ee05240868f6bedd18a3e4de81d49e39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1816, "license_type": "no_license", "max_line_length": 78, "num_lines": 64, "path": "/ImageDehazer/utils.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "from ImageDehazer.models import Image\nfrom io import BytesIO\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template\nimport matplotlib.pyplot as plt\nimport base64\nimport random\nimport numpy as np\n\nfrom xhtml2pdf import pisa\n\ndef render_to_pdf(template_src, context_dict={}):\n template = get_template(template_src)\n html = template.render(context_dict)\n result = BytesIO()\n pdf = pisa.pisaDocument(BytesIO(html.encode(\"ISO-8859-1\")), result)\n if not pdf.err:\n return HttpResponse(result.getvalue(), content_type='application/pdf')\n return None\n\n# def get_graph():\n# buffer = BytesIO()\n# plt.savefig(buffer , format ='png')\n# buffer.seek(0)\n# image_png = buffer.getvalue()\n# print(image_png)\n# graph = base64.b64decode(image_png)\n# print(\"____________encoded______________________\")\n# print(graph)\n# graph = graph.decode('ISO-8859-1')\n# print(\"____________encoded______________________\")\n# print(graph)\n# buffer.close()\n# return graph\n\n# def get_plot(x,y):\n# plt.switch_backend('AGG')\n# plt.figure(figsize=(5,2))\n# plt.title('PSNR Values')\n# plt.ylabel(\"Dehazing Methods\")\n# plt.bar(x, y)\n# plt.xticks(rotation =45)\n# name = \"/media/myimage/\"+ str(random.randint(1,11111)) +\".png\"\n# plt.savefig(\".\"+ name)\n# return name\n\ndef get_plot(x,y):\n\n X = ['Dcp','Gf','Cyclic-GAN','NovelIdea']\n\n X_axis = np.arange(len(X))\n\n plt.grid(which=\"both\")\n plt.bar(X_axis - 0.2, x, 0.4, label = 'PSNR')\n plt.bar(X_axis + 0.2, y, 0.4, label = 'SSIM')\n \n plt.xticks(X_axis, X)\n plt.xlabel(\"Dehazing Methods\")\n plt.title(\"Evaluation Parameters\")\n plt.legend()\n\n name = \"./media/myimage/\"+ str(random.randint(1,11111)) +\".png\"\n plt.savefig(name)\n return name" }, { "alpha_fraction": 0.6545623540878296, "alphanum_fraction": 0.6620111465454102, "avg_line_length": 43.79166793823242, "blob_id": "9ac127c6794667f277b01148d432a6732aaaa297", "content_id": "f946f86595d45b0c3ccffad1c5e95f5448a188d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1074, "license_type": "no_license", "max_line_length": 75, "num_lines": 24, "path": "/ImageDehazer/urls.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom ImageDehazer import views\n\nurlpatterns = [\n path(\"\", views.home, name=\"home\"),\n path(\"feedback\", views.feedback, name=\"feedaback\"),\n path(\"contact\", views.contact, name=\"contact\"),\n path(\"qa\", views.qa, name=\"qa\"),\n path(\"Dehazingmethods\", views.Dehazingmethods, name=\"Dehazingmethods\"),\n #path(\"\",views.index),\n path(\"get\",views.get , name = \"get\"),\n path(\"datasetpdf\",views.datasetpdf , name = \"datasetpdf\"),\n # path(\"download\",views.download , name = \"download\"),\n path(\"uploads\",views.send_files,name=\"uploads\"),\n path(\"n\", views.new, name=\"new\"),\n path(\"Sotsindoor\", views.datasets1, name=\"datasets1\"),\n path(\"Sotsoutdoor\", views.datasets2, name=\"datasets2\"),\n path(\"hstsreal\", views.dataseth1, name=\"dataseth1\"),\n path(\"hstssynth\", views.dataseth2, name=\"dataseth2\"),\n path(\"enlarge\", views.enlarge, name=\"enlarge\"),\n path(\"dehaze\", views.dehaze, name=\"dehaze\"),\n path(\"upload\", views.upload, name=\"upload\"),\n path(\"simple_upload\", views.simple_upload, name=\"simple_upload\"),\n]" }, { "alpha_fraction": 0.5287907719612122, "alphanum_fraction": 0.575815737247467, "avg_line_length": 37.592594146728516, "blob_id": "da3e9a925c0f22f737776cf7dce82969d99419ae", "content_id": "89bbaa096aee1f70c501d71824a5bc7558d6f067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1042, "license_type": "no_license", "max_line_length": 97, "num_lines": 27, "path": "/ImageDehazer/migrations/0013_params.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-05-12 13:28\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ImageDehazer', '0012_myuploadfile_specialid'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='PARAMS',\n fields=[\n ('imageID', models.CharField(max_length=200, primary_key=True, serialize=False)),\n ('pdcp', models.FloatField(max_length=200)),\n ('pgf', models.FloatField(max_length=200)),\n ('pcyclicgan', models.FloatField(default=0, max_length=200, null=True)),\n ('pNovelIdea', models.FloatField(default=0, max_length=200, null=True)),\n ('sdcp', models.FloatField(max_length=200)),\n ('sgf', models.FloatField(max_length=200)),\n ('scyclicgan', models.FloatField(default=0, max_length=200, null=True)),\n ('sNovelIdea', models.FloatField(default=0, max_length=200, null=True)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.8326693177223206, "alphanum_fraction": 0.8326693177223206, "avg_line_length": 82, "blob_id": "1218543648d3ce3309419796c72e7bc30d5a9e1d", "content_id": "68f5de3d7ec6ad56ad34689011d43b36950d8c6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 251, "license_type": "no_license", "max_line_length": 141, "num_lines": 3, "path": "/README.md", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# visibilityenhancer\nWebsite for researcher for Dehazing datasets and producing its quantitative analysis on the Datasets using state of the Art dehazing methods.\nMoreover you can also view the RESIDE dataset and also see its quantitative analysis.\n\n\n" }, { "alpha_fraction": 0.5589496493339539, "alphanum_fraction": 0.5666309595108032, "avg_line_length": 43.42856979370117, "blob_id": "3aaa65e1fea7f0be393c82c5fefb57875a992fb5", "content_id": "b82ce2a438b15fcd9b58ee68c9c41d858336b637", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 5598, "license_type": "no_license", "max_line_length": 202, "num_lines": 126, "path": "/ImageDehazer/templates/ImageDehazer/dataset.html", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang =\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Dehaze the image</title>\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">\n\n <link href=\"https://fonts.googleapis.com/css?family=Open+Sans:400,700\" rel=\"stylesheet\">\n <link rel = \"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css\">\n {% load static %}\n <link rel = \"stylesheet\" type=\"text/css\" href=\"{% static 'ImageDehazer/style.css' %}\" >\n {% load static %}\n <link rel = \"stylesheet\" type=\"text/css\" href=\"{% static 'ImageDehazer/newdataset.css' %}\" >\n</head>\n<body>\n\n<nav class=\"navbar navbar-expand-lg navbar-light bg-light\">\n <a class=\"navbar-brand\" href=\"#\">Navbar</a>\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n\n <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\">\n <ul class=\"navbar-nav mr-auto\">\n <li class=\"nav-item active\">\n <a class=\"nav-link\" href=\"/n\">Home <span class=\"sr-only\">(current)</span></a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"/a\">Reside Dateset</a>\n </li>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" href=\"#\" id=\"navbarDropdown\" role=\"button\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n Dropdown\n </a>\n <div class=\"dropdown-menu\" aria-labelledby=\"navbarDropdown\">\n <a class=\"dropdown-item\" href=\"#\">Action</a>\n <a class=\"dropdown-item\" href=\"#\">Another action</a>\n <div class=\"dropdown-divider\"></div>\n <a class=\"dropdown-item\" href=\"#\">Something else here</a>\n </div>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link disabled\" href=\"#\">Disabled</a>\n </li>\n </ul>\n <form class=\"form-inline my-2 my-lg-0\">\n <input class=\"form-control mr-sm-2\" type=\"search\" placeholder=\"Search\" aria-label=\"Search\">\n <button class=\"btn btn-outline-success my-2 my-sm-0\" type=\"submit\">Search</button>\n </form>\n </div>\n </nav>\n\n{% comment %} \n <div class = \"container\"> {% endcomment %}\n {% comment %} {% load static %}\n <image src = \"{% static 'ImageDehazer/hazy/1400_1.png' %}\" width=\"100\" height=\"100\"> {% endcomment %}\n {% comment %} {% for i in images %} {% endcomment %}\n {% comment %} <div class = \"col-sm-4\"> {% endcomment %}\n {% comment %} <div class=\"box\">\n {% comment %} {% load static %}\n <img class=\"card-img-top\" src = \"{% static i %}\" alt=\"Card image cap\" data-toggle=\"modal\" data-target=\"#myModal\"> {% endcomment %}\n {% comment %} </div> {% endcomment %} \n {% comment %} </div> {% endcomment %}\n{% comment %} \n {% endfor %} {% endcomment %}\n \n {% comment %} </div>\n <div class=\"container\">\n\t<div class=\"box\"></div>\n\t<div class=\"box\"></div>\n\t<div class=\"box\"></div>\n\t<div class=\"box\"></div>\n\t<div class=\"box\"></div>\n </div> {% endcomment %}\n\n{% for i in images %}\n <div class=\"image\">\n {% load static %}\n <img class=\"image__img\" src=\"{% static i %}\" alt=\"Bricks\">\n <div class=\"image__overlay image__overlay--primary\">\n <div class=\"image__title\">Bricks</div>\n {% load static %}\n <img class=\"image__description\" src = \"{% static 'ImageDehazer/download.png' %}\" >\n \n </div>\n </div>\n{% endfor %} \n\n{% comment %} <!-- Modal -->\n<div id=\"myModal\" class=\"modal fade\" role=\"dialog\">\n <span id=\"my\">&times;</span>\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header card-header-title\">\n <h4 class=\"modal-title card-element-title\">pick your locker side</h4>\n {% comment %} <span class = \"my\" aria-hidden=\"true\">&times;</span> {% endcomment %}\n \n {% comment %} </div>\n\n <div class=\"modal-body\">\n <div class=\"card-content clearfix\">\n {% comment %} <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button> {% endcomment %}\n {% comment %} <div id=\"A\" class=\"card left-half\">a</div>\n <div id=\"B\" class=\"card right-half\">b</div>\n <div id=\"C\" class=\"card left-half\">c</div>\n <div id=\"D\" class=\"card right-half\">d</div>\n </div>\n </div>\n </div>\n </div> {% endcomment %}\n\n\n\n<script src = \"https://cldup.com/S6Ptkwu_qA.js\"></script>\n{% load static %}\n<script src=\"{% static 'ImageDehazer/script.js' %} \"type=\"text/javascript\"></script>\n{% load static %}\n<script src=\"{% static 'ImageDehazer/dataset.js' %} \"type=\"text/javascript\"></script>\n<script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"></script>\n<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"></script>\n\n</body>\n</html> " }, { "alpha_fraction": 0.734246551990509, "alphanum_fraction": 0.734246551990509, "avg_line_length": 21.875, "blob_id": "71844ae9898e7c1793d9db9115e427f58368040f", "content_id": "0585ee78e729ebc5717e929abddda43bc4211729", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "no_license", "max_line_length": 46, "num_lines": 16, "path": "/ImageDehazer/resources.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "from import_export import resources\nfrom .models import PSNR\nfrom .models import SSIM\nfrom .models import PARAMS\n\nclass PSNRResource(resources.ModelResource):\n class Meta:\n model = PSNR\n\nclass SSIMResource(resources.ModelResource):\n class Meta:\n model = SSIM\n\nclass PARAMSResource(resources.ModelResource):\n class Meta:\n model = PARAMS" }, { "alpha_fraction": 0.5469905138015747, "alphanum_fraction": 0.5659978985786438, "avg_line_length": 27.696969985961914, "blob_id": "392d37b6737d9bb23d8dcaabbb93f93478be4d9d", "content_id": "ac305be1ccb541b5156b87ba936c2af9c30520e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 947, "license_type": "no_license", "max_line_length": 67, "num_lines": 33, "path": "/ImageDehazer/migrations/0011_auto_20210508_0141.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-05-07 20:11\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ImageDehazer', '0010_remove_myuploadfile_f_name'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='myuploadfile',\n name='NovelIdea',\n field=models.FileField(null=True, upload_to='myimage'),\n ),\n migrations.AlterField(\n model_name='myuploadfile',\n name='cyclicgan',\n field=models.FileField(null=True, upload_to='myimage'),\n ),\n migrations.AlterField(\n model_name='myuploadfile',\n name='dcp',\n field=models.FileField(null=True, upload_to='myimage'),\n ),\n migrations.AlterField(\n model_name='myuploadfile',\n name='gf',\n field=models.FileField(null=True, upload_to='myimage'),\n ),\n ]\n" }, { "alpha_fraction": 0.5414052605628967, "alphanum_fraction": 0.5796737670898438, "avg_line_length": 47.30303192138672, "blob_id": "70069980a8a0cf0ece73cb1e9e9abcdd85e10911", "content_id": "1890c4c5fe3c3d28108f47068d9cd235a9d44434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1594, "license_type": "no_license", "max_line_length": 117, "num_lines": 33, "path": "/ImageDehazer/migrations/0009_myuploadfile.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-05-07 19:15\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ImageDehazer', '0008_auto_20210507_1157'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='myuploadfile',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('f_name', models.CharField(max_length=255)),\n ('myfiles', models.FileField(upload_to='myimage')),\n ('dcp', models.FileField(null=True, upload_to='myimage/dcp')),\n ('gf', models.FileField(null=True, upload_to='myimage/gf')),\n ('cyclicgan', models.FileField(null=True, upload_to='myimage/cg')),\n ('NovelIdea', models.FileField(null=True, upload_to='myimage/ni')),\n ('dcp_psnr', models.FloatField(max_length=200, null=True)),\n ('gf_psnr', models.FloatField(max_length=200, null=True)),\n ('cyclicgan_psnr', models.FloatField(default=0, max_length=200, null=True)),\n ('NovelIdea_psnr', models.FloatField(default=0, max_length=200, null=True)),\n ('dcp_ssim', models.FloatField(max_length=200, null=True)),\n ('gf_ssim', models.FloatField(max_length=200, null=True)),\n ('cyclicgan_ssim', models.FloatField(default=0, max_length=200, null=True)),\n ('NovelIdea_ssim', models.FloatField(default=0, max_length=200, null=True)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5306603908538818, "alphanum_fraction": 0.6084905862808228, "avg_line_length": 22.55555534362793, "blob_id": "d643071a5db833a5b7aa32e2bd8b9e37b680cc6a", "content_id": "c5d71867ff1f2b3b61b4873c338b11c402b28233", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 86, "num_lines": 18, "path": "/ImageDehazer/migrations/0004_alter_ssim_imageid.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-05-03 15:47\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ImageDehazer', '0003_auto_20210503_2117'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='ssim',\n name='imageID',\n field=models.CharField(max_length=200, primary_key=True, serialize=False),\n ),\n ]\n" }, { "alpha_fraction": 0.5168918967247009, "alphanum_fraction": 0.5810810923576355, "avg_line_length": 24.7391300201416, "blob_id": "e10fe7ecc05ef0d4e0e65253ba25909f30d50467", "content_id": "19d1b8c049edefb521abf271acf6946aa2b7da3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 592, "license_type": "no_license", "max_line_length": 74, "num_lines": 23, "path": "/ImageDehazer/migrations/0008_auto_20210507_1157.py", "repo_name": "Paras880/visibilityenhancer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-05-07 06:27\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ImageDehazer', '0007_auto_20210507_1049'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='ssim',\n name='NovelIdea',\n field=models.FloatField(default=0, max_length=200, null=True),\n ),\n migrations.AlterField(\n model_name='ssim',\n name='cyclicgan',\n field=models.FloatField(default=0, max_length=200, null=True),\n ),\n ]\n" } ]
18
Zipp0/Pygame-mcgyver
https://github.com/Zipp0/Pygame-mcgyver
53702131fc4bba4d3df58d157e223231c8b084ff
52b6c03b94205fcee7000d4156aa737133f42538
d6e37116d5a74b3abf0f122d0a87eb679f183945
refs/heads/master
2020-04-19T09:47:10.188862
2019-07-26T16:36:05
2019-07-26T16:36:05
168,120,573
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7066666483879089, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 14, "blob_id": "40aabb4967782e743cad438765bb6896dc571003", "content_id": "3138b982e42e779d53fac896554f6486dd6dcf1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "no_license", "max_line_length": 35, "num_lines": 5, "path": "/README.md", "repo_name": "Zipp0/Pygame-mcgyver", "src_encoding": "UTF-8", "text": "# Pygame-mcgyver\n\nRepo du projet 3 => parcours Python\n\nAidez Mcgyver à s'echapper\n" }, { "alpha_fraction": 0.541317343711853, "alphanum_fraction": 0.5494610667228699, "avg_line_length": 27.209789276123047, "blob_id": "4b510e0fdd7430a066d42093810e83b4159b6b23", "content_id": "6ecfe6d948e16cc9985bc40cfe5498f5de321294", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4188, "license_type": "no_license", "max_line_length": 64, "num_lines": 143, "path": "/position.py", "repo_name": "Zipp0/Pygame-mcgyver", "src_encoding": "UTF-8", "text": "import pygame\r\nimport random\r\nfrom pygame.locals import *\r\nfrom constant import *\r\n\r\n\r\n\r\nclass Niveau:\r\n \"\"\"Classe permettant de créer un niveau\"\"\"\r\n def __init__(self, fichier, fenetre):\r\n self.fichier = fichier\r\n self.structure = 0\r\n self.taille_sprite = 20\r\n self.fenetre = fenetre\r\n \r\n \r\n \r\n def generer(self):\r\n\r\n with open(self.fichier, \"r\") as fichier:\r\n structure_niveau = []\r\n for ligne in fichier:\r\n ligne_niveau = []\r\n \r\n for sprite in ligne:\r\n #pass \\n\r\n if sprite != '\\n':\r\n ligne_niveau.append(sprite)\r\n structure_niveau.append(ligne_niveau)\r\n self.structure = structure_niveau\r\n \r\n \r\n \r\n def display(self, fenetre):\r\n wall = pygame.image.load(\"wall.png\").convert()\r\n arrive = pygame.image.load(\"guard.png\").convert()\r\n \r\n #lecture liste \r\n num_ligne = 0\r\n for ligne in self.structure:\r\n num_case=0\r\n for sprite in ligne:\r\n #calcul position to pixels\r\n x = num_case * self.taille_sprite\r\n y = num_ligne * self.taille_sprite\r\n if sprite == \"#\":\r\n self.fenetre.blit(wall, (x,y))\r\n \r\n \r\n elif sprite == \"G\":\r\n self.fenetre.blit(arrive, (x,y))\r\n num_case += 1\r\n num_ligne += 1 \r\n \r\n \r\n def map(self):\r\n niveau = Niveau(fichier, fenetre)\r\n niveau.map.generer()\r\n niveau.display(fenetre)\r\n \r\n\r\nclass Perso:\r\n\t#Classe permettant de créer un personnage\r\n\tdef __init__(self, path, niveau):\r\n\t\t#Sprites du personnage\r\n\t\tself.droite = \"macgyver.png\"\r\n\t\t#Position du personnage en cases et en pixels\r\n\t\tself.case_x = 0\r\n\t\tself.case_y = 0\r\n\t\tself.items = 0\r\n\t\tself.x = 0\r\n\t\tself.y = 0\r\n\t\t#Direction par défaut\r\n\t\tself.direction = self.droite\r\n\t\t#Niveau dans lequel le personnage se trouve \r\n\t\tself.niveau = niveau\r\n\t\tself.sprite= pygame.image.load(path).convert_alpha()\r\n\r\n\tdef chgsprite(self, path):\r\n\t\tself.sprite = pygame.image.load(path).convert_alpha()\r\n\t\r\n\t\r\n\tdef deplacer(self, direction):\r\n\t\t\"\"\"Methode permettant de déplacer le personnage\"\"\"\r\n\t\t#nombre_sprite_cote = 15\r\n\t\t#taille_sprite = 20\r\n\t\t#Déplacement vers la droite\r\n\t\tif direction == 'droite':\r\n\t\t\t#Pour ne pas dépasser l'écran\r\n\t\t\tif self.case_x < (nombre_sprite_cote - 1):\r\n\t\t\t\t#On vérifie que la case de destination n'est pas un mur\r\n\t\t\t\tif self.niveau.structure[self.case_y][self.case_x+1] != '#':\r\n\t\t\t\t\t#Déplacement d'une case\r\n\t\t\t\t\tself.case_x += 1\r\n\t\t\t\t\t#Calcul de la position \"réelle\" en pixel\r\n\t\t\t\t\tself.x = self.case_x * taille_sprite\r\n\t\t\t\r\n\t\t\r\n\t\t#Déplacement vers la gauche\r\n\t\tif direction == 'gauche':\r\n\t\t\tif self.case_x > 0:\r\n\t\t\t\tif self.niveau.structure[self.case_y][self.case_x-1] != '#':\r\n\t\t\t\t\tself.case_x -= 1\r\n\t\t\t\t\tself.x = self.case_x * taille_sprite\r\n\t\t\t\r\n\t\t\r\n\t\t#Déplacement vers le haut\r\n\t\tif direction == 'haut':\r\n\t\t\tif self.case_y > 0:\r\n\t\t\t\tif self.niveau.structure[self.case_y-1][self.case_x] != '#':\r\n\t\t\t\t\tself.case_y -= 1\r\n\t\t\t\t\tself.y = self.case_y * taille_sprite\r\n\t\t\t\t\t\r\n\t\t#Déplacement vers le bas\r\n\t\tif direction == 'bas':\r\n\t\t\tif self.case_y < (nombre_sprite_cote - 1):\r\n\t\t\t\tif self.niveau.structure[self.case_y+1][self.case_x] != '#':\r\n\t\t\t\t\tself.case_y += 1\r\n\t\t\t\t\tself.y = self.case_y * taille_sprite\r\n\t\t\r\nclass Items:\r\n\tdef __init__(self, name, path, niveau):\r\n\t\tself.id = name\r\n\t\tself.niveau = niveau\r\n\t\trand_x, rand_y = self.randpos()\r\n\t\tself.x = rand_x * taille_sprite\r\n\t\tself.y = rand_y * taille_sprite\r\n\t\tself.sprite = pygame.image.load(path).convert_alpha()\r\n\t\t\r\n\r\n\tdef randpos(self):\r\n\t\twhile True:\r\n\t\t\trand_x = random.randrange(0, 14)\r\n\t\t\trand_y = random.randrange(0, 14)\r\n\t\t\tif self.niveau.structure[rand_y][rand_x] == '.':\r\n\t\t\t\tself.niveau.structure[rand_y][rand_x] = self.id\r\n\t\t\t\tbreak\r\n\r\n\t\treturn rand_x, rand_y\r\n\r\n\tdef display(self, fenetre):\r\n\t\t\tprint(self.x, self.y)\r\n\t\t\tfenetre.blit(self.sprite, (self.x, self.y))" }, { "alpha_fraction": 0.6382352709770203, "alphanum_fraction": 0.6591176390647888, "avg_line_length": 23.578947067260742, "blob_id": "052ce319ef8525f8501bd91e730af56f723869b0", "content_id": "90d67e937a4e619cb66bf17774fcf14c03341ee2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3402, "license_type": "no_license", "max_line_length": 85, "num_lines": 133, "path": "/lab.py", "repo_name": "Zipp0/Pygame-mcgyver", "src_encoding": "UTF-8", "text": "import pygame\r\nimport random\r\nfrom pygame.locals import * \r\nfrom constant import *\r\nfrom position import*\r\npygame.init()\r\n\r\nfichier = \"lab.txt\"\r\n\r\n#ouverture de la fenetre pygame\r\nnombre_sprite_cote = 15\r\ntaille_sprite = 20\r\ncote = nombre_sprite_cote * taille_sprite\r\nfenetre = pygame.display.set_mode((cote, cote))\r\n#élément graphique\r\nfond = pygame.image.load(\"background.jpg\").convert()\r\nfenetre.blit(fond, (0, 10))\r\nwall = pygame.image.load(\"wall.png\").convert()\r\narrive = pygame.image.load(\"guard.png\").convert()\r\nfenetre.blit(wall,(0, 40))\r\nniveau = Niveau(fichier, fenetre)\r\nniveau.generer()\r\nniveau.display(fenetre)\r\n\r\n\r\n#objet\r\nc_ether = \"ether.png\"\r\nether = Items(\"E\", c_ether, niveau)\r\nether.display(fenetre)\r\nc_tube = \"tube.png\"\r\ntube = Items(\"T\", c_tube, niveau)\r\ntube.display(fenetre)\r\nc_needle =\"needle.png\"\r\nneedle = Items(\"N\", c_needle, niveau)\r\nneedle.display(fenetre)\r\n\r\n\r\n#titre\r\npygame.display.set_caption(\"EscapeMacGyver\")\r\ntaille_perso = taille_sprite * taille_sprite\r\n\r\n\r\npygame.display.flip()\r\npygame.key.set_repeat(400,30)\r\n\r\n\r\ncontinuer_jeu = 1\r\n\r\nTubeNotPicked = True\r\nEtherNotPicked = True\r\nNeedleNotPicked = True\r\n\r\nGAME_WON = False\r\nGAME_LOOSE = False\r\n\r\nguard = pygame.image.load(\"guard.png\").convert_alpha()\r\nmac = Perso(\"macgyver.png\", niveau)\r\nfenetre.blit(mac.sprite, (mac.x, mac.y))\r\n\r\n\r\nwhile continuer_jeu:\r\n\tpygame.display.flip()\r\n\tpygame.time.Clock().tick(60)\r\n\tfor event in pygame.event.get():\r\n\t\tif event.type == pygame.QUIT:\r\n\t\t\tcontinuer_jeu = 0\r\n\t\tif event.type == pygame.KEYDOWN:\r\n\t\t\tif event.key == pygame.K_DOWN:\r\n\t\t\t\tmac.deplacer(\"bas\")\r\n\t\t\tif event.key == pygame.K_UP:\r\n\t\t\t\tmac.deplacer(\"haut\")\r\n\t\t\tif event.key == pygame.K_LEFT:\r\n\t\t\t\tmac.deplacer(\"gauche\")\r\n\t\t\tif event.key == pygame.K_RIGHT:\r\n\t\t\t\tmac.deplacer(\"droite\")\r\n\r\n\t\r\n\tfenetre.blit(fond, (0, 0))\r\n\tniveau.display(fenetre)\r\n\tfenetre.blit(mac.sprite, (mac.x, mac.y))\r\n\r\n\t\r\n\tif TubeNotPicked:\r\n\t\tfenetre.blit(tube.sprite, (tube.x, tube.y))\r\n\tif (mac.x, mac.y) == (tube.x, tube.y):\r\n\t\tTubeNotPicked = False\r\n\tif TubeNotPicked == False:\r\n\t\ttube.x, tube.y = 10, 0\r\n\t\tfenetre.blit(tube.sprite, (10, 0))\r\n\r\n\t\t\r\n\tif NeedleNotPicked:\r\n\t\tfenetre.blit(needle.sprite, (needle.x, needle.y))\r\n\tif (mac.x, mac.y) == (needle.x, needle.y):\r\n\t\tNeedleNotPicked = False\r\n\tif NeedleNotPicked == False:\r\n\t\tneedle.x, needle.y = 30, 0\r\n\t\tfenetre.blit(needle.sprite, (30, 0))\r\n\r\n\t\t\r\n\tif EtherNotPicked:\r\n\t\tfenetre.blit(ether.sprite, (ether.x, ether.y))\r\n\tif (mac.x, mac.y) == (ether.x, ether.y):\r\n\t\tEtherNotPicked = False\r\n\tif EtherNotPicked == False:\r\n\t\tether.x, ether.y = 50, 0\r\n\t\tfenetre.blit(ether.sprite, (50, 0))\r\n\t\r\n\r\n\t#Endgame condition\r\n\tif niveau.structure[mac.case_y][mac.case_x] == 'G': \r\n\t\tif TubeNotPicked is False and NeedleNotPicked is False and EtherNotPicked is False:\r\n\t\t\tGAME_WON = True\r\n\t\telse:\r\n\t\t\tGAME_LOOSE = True\r\n\t\t\r\n\t\t\r\n\tif GAME_WON is True:\r\n\t\tfenetre.blit(fond, (0, 0))\r\n\t\tfont = pygame.font.Font(None, 25)\r\n\t\ttext = font.render(\"You won! you escaped from these walls !\", 1, (255, 255, 255))\r\n\t\ttextrect = text.get_rect()\r\n\t\ttextrect.centerx, textrect.centery = cote / 2, cote / 2\r\n\t\tfenetre.blit(text, textrect)\r\n\r\n\t\r\n\tif GAME_LOOSE is True:\r\n\t\tfenetre.blit(fond, (0, 0))\r\n\t\tfont = pygame.font.Font(None, 25)\r\n\t\ttext = font.render(\"You died.\", 1, (255 , 255, 255))\r\n\t\ttextrect = text.get_rect()\r\n\t\ttextrect.centerx, textrect.centery = cote / 2, cote / 2\r\n\t\tfenetre.blit(text, textrect)" }, { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 20.5, "blob_id": "83d2057175044b0123f17a653753e4a7f87156c5", "content_id": "261883077e08841cd55415c5693873bd2835053b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43, "license_type": "no_license", "max_line_length": 25, "num_lines": 2, "path": "/constant.py", "repo_name": "Zipp0/Pygame-mcgyver", "src_encoding": "UTF-8", "text": "number_sprite_inline = 15\r\nsprite_size = 20" } ]
4
VonSdite/barrage_bilibil
https://github.com/VonSdite/barrage_bilibil
98d2e27eb92e522514a8efb56d2d933989ad3cc5
7f70343d1667f90787ec81a1d844beb593aa518c
ba93799adeafe7bbad4af4fa714d6d2e2d410c17
refs/heads/master
2021-04-27T08:14:17.709690
2018-02-24T03:15:13
2018-02-24T03:15:13
122,651,086
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6052871346473694, "alphanum_fraction": 0.6435734033584595, "avg_line_length": 24.465116500854492, "blob_id": "537f8d211870a4ce58adcef40f5301ece978ba48", "content_id": "ed425b6f8313258dafb552a8ff51860081140c14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1705, "license_type": "permissive", "max_line_length": 81, "num_lines": 43, "path": "/README.md", "repo_name": "VonSdite/barrage_bilibil", "src_encoding": "UTF-8", "text": "# barrage_bilibil\nb站弹幕测试\n\n## 使用\n- 修改脚本 第7行的 av_code 为你所要发送的b站av号 \n- 先手动发一次弹幕进行抓包:\n + 获取rnd值,修改脚本 第16行的 rnd\n + 获取csrf值,修改脚本 第20行的 csrf\n + 获取cookie,修改脚本 第27行的 cookie, 这里cookie用一个list下面**Mark**做解释\n\n## 用途\n- 该脚本可以用于发....发弹幕(看你怎么用啦。。我只是用来循环刷弹幕....) \n\n## Mark\n\n- mark1: b站发弹幕cookie值, rnd值, csrf值是要对应的, csrf包含在cookie中(csrf是跨站请求伪造,应该是防范刷礼物之类用的)\n- mark2: 当你每隔5s发一条弹幕(隔10+s和5s是一样的)达15条之后,b站需要你等待300s,可能是300s吧..\n- mark3: 当出现mark2时, 你手动再去b站发一条弹幕,b站会给你重新分配一个cookie\n- mark4: 新的cookie的包里的rnd是变了的,但却还能成功发弹幕, 神奇\n- mark5: b站cookie时效可能是一天或者半天\n\n- *至于cookie作为list*: 由mark2可知, 我只要在达到15条弹幕之后,自己手动再去获取多一个cookie,那么后续使用就很方便了嘛\n\n## Demo\n**在参数设置好的前提下**\n\n```python\nif __name__ == '__main__':\n for play_time in range(0, 250):\n index = 0\n while -1 == send_barrage(\n message='Hello world {time}s'.format(time=play_time), \n av_code=av_code, \n play_time=str(play_time), \n color='ff0000'):\n\n index = (index + 1) % len(cookie) # index为cookie池的游标,初始值为0\n headers['Cookie'] = cookie[index]\n\n time.sleep(5)\n\n time.sleep(5)\n```\n\n\n" }, { "alpha_fraction": 0.4727078080177307, "alphanum_fraction": 0.5033892393112183, "avg_line_length": 27.31313133239746, "blob_id": "eb3fc69de6b86f755e4f1c17a7cbca36dc92f99a", "content_id": "9511368707c84ebd5b3b714607d80e46c12f0cec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3391, "license_type": "permissive", "max_line_length": 135, "num_lines": 99, "path": "/barrage.py", "repo_name": "VonSdite/barrage_bilibil", "src_encoding": "UTF-8", "text": "import requests\nimport random\nimport time\nimport sys\nimport re\n\nav_code = 'the av code that you want to send' # 发送的av号\n\n################################################\n# 需要修改的值在这里 #\n# 这三个值通过自己发一次弹幕抓包获取 #\n# 注意这三个值容易变更 #\n################################################\n\n# 你的rnd\nrnd = 'your_rnd'\n\n# 你的csrf\n# 这个csrf有比较长的时效\ncsrf = 'your_csrf'\n\n# 你的cookie, 以下算是一个cookie池,你可以自己多次采集多个cookie来用\n# mark1: 当你每隔5s(隔10+s和5s是一样的)发一条弹幕达15条之后,b站需要你等待300s\n# mark2: 当出现mark1时, 你手动再去b站发一条弹幕,b站会给你重新分配一个cookie\n# mark3: 新的cookie的包里的rnd是变了的,但却还能成功发弹幕, 神奇\n# mark4: b站cookie时效可能是一天或者半天\ncookie = ['cookie1', 'cookie2', 'cookie3']\n\n\n################################################\n\nsession = requests.Session()\nbase_url = 'https://interface.bilibili.com/dmpost?cid={cid}&aid={av_code}&pid=1&ct=1'\ndata = {\n 'pool': '0',\n 'mode': '1',\n\n 'message': '', # 弹幕的内容\n 'playTime': '0', # 弹幕的发送所在的进度条时间, 以秒为基准,可带小数\n 'fontsize': '25', # 弹幕字体大小\n 'color': '16777215', # 弹幕字体颜色\n 'date': '2018-02-23 20:17:59', # 弹幕发送的时间\n\n 'rnd': rnd,\n 'cid': '',\n 'csrf': csrf # 你的csrf\n}\nheaders = {\n 'Cookie': cookie[0],\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'\n}\npattern = re.compile(r'cid=(.+?)&')\n\n\ndef get_cid(av_code):\n url = 'https://www.bilibili.com/video/av{av_code}/'.format(av_code=av_code)\n try:\n text = session.get(url=url, timeout=2).text\n cid = pattern.findall(text)[0]\n except:\n cid = ''\n return cid\n\ncid = ''\n\n\ndef send_barrage(message, av_code='', play_time='0', font_size='25', color='ffffff'):\n if type(av_code) != type(str):\n av_code = str(av_code)\n global cid\n if cid == '':\n # 第一次获取的话,cid是'' 空值,需要获取\n cid = get_cid(av_code)\n\n if cid == '':\n # 若获取后cid仍为空值,失败,返回\n print('发送失败', 'cid获取失败')\n return -1\n\n url = base_url.format(cid=cid, av_code=av_code)\n data['message'] = message # 弹幕内容\n data['playTime'] = play_time # 弹幕所在的时间戳\n data['fontsize'] = font_size # 弹幕字体大小\n data['color'] = str(int(color, 16)) # 弹幕字体颜色\n data['date'] = time.strftime('%F %X') # 设置弹幕发送的时间\n data['cid'] = cid\n\n result = eval(session.post(url=url, data=data,\n headers=headers).text).get('message', '')\n if result == '':\n print('发送成功')\n return 0\n else:\n print('发送失败', result)\n return -1\n\n\nif __name__ == '__main__':\n send_barrage(message='hello world', av_code=av_code)\n" } ]
2
angel29526/Python
https://github.com/angel29526/Python
9583a2d527d91c99bd17d0dbb34430ec1a1ea4dc
976adfa1c387fe17af2de9a53b5df675d2baf9e8
1e8221667f3fee92f34222ca2a8f334eae2e0e1e
refs/heads/main
2022-12-19T17:07:08.712380
2020-10-07T16:42:41
2020-10-07T16:42:41
302,097,803
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7066681385040283, "alphanum_fraction": 0.7115206122398376, "avg_line_length": 55.010887145996094, "blob_id": "a465ec4abee4d0e8ffeebe353c247ec768bad3cb", "content_id": "887c491e7d374bdbffda3c3fcf98bd7e8651da63", "detected_licenses": [ "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37672, "license_type": "permissive", "max_line_length": 192, "num_lines": 643, "path": "/Reto.py", "repo_name": "angel29526/Python", "src_encoding": "UTF-8", "text": "#Treasure quest.\r\n#Programa/Juego creado por Ángel Flores Bermúdez.\r\n#Programa/Juego de Rol que planea mejorar la comprensión lectora.\r\n\r\nimport random\r\nimport shelve\r\nimport sys\r\n\r\nhp=100\r\npuntos=0\r\n\r\n\r\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n#Todas las preguntas con su respuesta correspondiente.\r\nRelacionPreguntas={'''El barquito cabeceó, se ladeó, volvió a enderezarse en medio de traicioneros remolinos y\r\ncontinuó su marcha por Witcham Street hacia el cruce de ésta y Jackson. El semáforo de la\r\nesquina estaba a oscuras y también todas las casas, en aquella tarde de otoño de 1957. Llovía sin\r\ncesar desde hacía una semana y dos días atrás habían llegado los vientos. Desde entonces, la\r\nmayor parte de Derry había quedado sin corriente eléctrica y aún seguía así.\r\n\r\nTeniendo en cuenta el texto anteror. ¿Cuál es el ambiente en Derry?''':'Lúgubre',\r\n#2\r\n'''George fue en busca de esas cosas. Oyó que su madre seguía tocando el piano, pero ya no\r\nera Para Elisa, sino algo que no le gustaba tanto, algo que sonaba seco y alborotado; oyó la lluvia\r\nazotando las ventanas de la cocina. Ese sonido era reconfortante, pero no así la idea de bajar al\r\nsótano. No le gustaba el sótano ni le gustaba bajar por sus escaleras porque siempre imaginaba\r\nque allí abajo, en la oscuridad, había algo. Era una tontería, por supuesto, lo decía su padre, lo\r\ndecía su madre, y, aún más importante, lo decía Bill, pero aun así...\r\n\r\nTeniendo en cuenta el texto anterior. ¿Por qué George cree que hay algo en el sótano?''':'Superstición',\r\n#3 \r\n'''No le gustaba siquiera abrir la puerta para encender la luz, porque temía (era algo tan\r\nestúpido que no se atrevía a contárselo a nadie) que, mientras tanteaba en busca del interruptor,\r\nuna garra espantosa se posara sobre su muñeca... y lo arrebatara hacia esa oscuridad que olía a\r\nsuciedad, humedad y hortalizas podridas\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo se le llama a lo que siente ?''':'Pavor',\r\n#4\r\n'''Aquella mañana abrió la puerta para tantear interminablemente en busca del interruptor,\r\nsujetando el marco de la puerta con la fuerza de siempre, los ojos apretados, la punta de la lengua\r\nasomando por la comisura de los labios como una raicilla agonizante buscando agua en un sitio de\r\nsequía. ¿Gracioso? ¡Claro! \\\"Mira a Georgie ¡Georgie le tiene miedo a la oscuridad! ¡Vaya tonto!\\\"\r\n \r\nTeniendo en cuenta el texto anterior. ¿Por qué la gente se burlaría de Georgie?''':'Degradar',\r\n#5\r\n'''George rió. El miedo había desaparecido, se había desprendido de él tan fácilmente como\r\nuna pesadilla se desprende del hombre que despierta con la piel fría y el aliento agitado\r\npalpándose el cuerpo y mirando alrededor para asegurarse de que nada ha ocurrido en realidad:\r\nolvida la mitad cuando sus pies tocan el suelo; las tres cuartas partes, cuando sale de la ducha y\r\ncomienza a secarse con la toalla; y la totalidad cuando termina el desayuno. Desaparecida por\r\ncompleto... hasta la próxima vez, cuando en el puño de la pesadilla todos los miedos volverán a\r\nrecordarse\r\n \r\nTeniendo en cuenta el texto anterior. ¿Qué siente George después de ese proceso?''':'Alivio',\r\n#6\r\n'''El piano reinició Para Elisa. Bill el Tartaja no olvidaría jamás esa pieza, y aún muchos años\r\ndespués no podría escucharla sin que se le pusiera carne de gallina, el corazón le daba un vuelco y\r\nrecordaba: \\\"Mi madre estaba tocando eso el día en que murió Georgie.\\\"\r\n\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué siente Bill al escuchar \\\"Para Elisa\\\"?''':'Pánico',\r\n#7\r\n'''Forzó el paso y, por un momento, pareció que iba a alcanzarlo. Pero George resbaló y cayó\r\ndespatarrado con un grito de dolor. Desde su nueva perspectiva, a la altura del pavimento, vio que\r\nel barco giraba en redondo dos veces, atrapado en otro remolino, antes de desaparecer.\r\n —¡Mierda y mierda! –volvió a chillar, golpeando el pavimento con el puño.\r\nEso también le dolió, y se echó a sollozar. ¡Qué manera tan estúpida de perder el barco!\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué siente George después de perder el barco?''':'Tristesa',\r\n#8\r\n'''Se dirigió hacia la boca de tormenta y allí se dejó caer de rodillas, para mirar el interior. El\r\nagua hacía un ruido hueco al caer en la oscuridad. Ese sonido le dio escalofríos. Hacía pensar en...\r\n —¡Eh! –exclamó de pronto, y retrocedió.\r\nAllí adentro había unos ojos amarillos. Ese tipo de ojos que él siempre imaginaba, sin verlos\r\nnunca, en la oscuridad del sótano. \\\"Es un animal –pensó–; eso es todo: un animal; a lo mejor un\r\ngato que quedó atrapado...\\\"\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué sintió George después de escuchar la exclamación?''':'Sorpresa',\r\n#9\r\n'''De todos modos, estaba por echar a correr a causa del espanto que le produjeron aquellos\r\nojos amarillos y brillantes. Sintió la áspera superficie del pavimento bajo los dedos y el agua fría\r\nque corría alrededor. Se vio a sí mismo levantándose y retrocediendo. Y fue entonces cuando una\r\nvoz, una voz razonable y bastante simpática, le habló desde dentro de la boca de tormenta:\r\n—Hola, George. \r\n \r\nTeniendo en cuenta el texto anterior. ¿Qué supone que alguien hable desde dentro de una \\\"Boca de tormenta\\\" (Drenaje)?''':'Peligro',\r\n#10\r\n'''El payaso sostenía en una mano un manojo de globos de colores, como tentadora fruta\r\nmadura. En la otra, el barquito de papel de George.\r\n —¿Quieres tu barquito, Georgie? –El payaso sonreía.\r\n George también sonrió, sin poder evitarlo.\r\n —Si, lo quiero.\r\n El payaso se echó a reír.\r\n —¡Así me gusta! ¿Y un globo? ¿Quieres un globo?\r\n —Bueno... sí, por supuesto. –Alargó la mano pero de inmediato la retiró–. No debo coger\r\nnada que me ofrezca un desconocido. Lo dice mi papá.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué trataba de transmitirle el payaso a Georgie?''':'Seguridad',\r\n#11\r\n'''—Y tu papá tiene mucha razón –replicó el payaso sonriendo. George se preguntó cómo\r\npodía haber creído que sus ojos eran amarillos, si eran de un azul brillante como los de su mamá y\r\nde Bill–. Muchísima razón, ya lo creo. Por lo tanto, voy a presentarme. George, soy el señor Bob\r\nGray, también conocido como Pennywise el Payaso. Pennywise, te presento a George Denbrough.\r\nGeorge, te presento a Pennywise. Ahora ya nos conocemos. Yo no soy un desconocido y tú\r\ntampoco. ¿Correcto?\r\n George soltó una risita\r\n \r\nTeniendo en cuenta el texto anterior. ¿Qué siente George después de esa conversación?''':'Alegía',\r\n#12\r\n'''—Correcto. –Volvió a estirar la mano... y a retirarla–. ¿Cómo te has metido ahí adentro?\r\n –La tormenta me trajo volaaaando –dijo Pennywise el Payaso–. Se llevó todo el circo. ¿No\r\nsientes olor a circo, George?\r\n George se inclinó hacia adelante. ¡De pronto olía a cacahuetes! ¡Cacahuetes tostados! ¡Y\r\nvinagre blanco, del que se pone en las patatas fritas! Y olía a algodón de azúcar, a buñuelos, y\r\ntambién a estiércol de animales salvajes. Olía el aroma regocijante del aserrín. Y sin embargo...\r\n Sin embargo, bajo todo eso olía a inundación, a hojas deshechas y a oscuras sombras en\r\nbocas de tormenta. Era un olor húmedo y pútrido. El olor del sótano.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué significa que debajo de esos olores de gozo haya uno pútrido?''':'Engaño',\r\n#13\r\n'''Pero los otros olores eran más fuertes.\r\n —Sí, lo huelo –dijo.\r\n —¿Quieres tu barquito, George? Te lo pregunto otra vez porque no pareces desearlo mucho.\r\n Y se lo enseñó, sonriendo. Llevaba un traje de seda abolsado con grandes botones color\r\nnaranja. Una corbata brillante, de color azul eléctrico, le caía por la pechera. En las manos llevaba\r\ngrandes guantes blancos, como Mickey y Donald.\r\n —Sí, claro –dijo George, mirando el interior de la boca de tormenta.\r\n —¿Y un globo? Los tengo rojos, verdes, amarillos, azules...\r\n —¿Flotan?\r\n —¿Que si flotan? –La sonrisa del payaso se acentuó–. Oh, sí, claro que sí. ¡Flotan! También\r\ntengo algodón de azúcar...\r\n George estiró la mano.\r\n \r\nTeniendo en cuenta el texto anterior. ¿Qué quiere lograr el payaso al ofrecer objetos?''':'Aproximar',\r\n#14\r\n'''El payaso le sujetó el brazo.\r\n Y entonces George vio cómo la cara del payaso se convertía en algo tan horripilante que lo\r\npeor que había imaginado sobre la cosa del sótano parecía un dulce sueño. Lo que vio destruyó su\r\ncordura de un zarpazo.\r\n —Flotan –croó la cosa de la alcantarilla con una voz que reía como entre coágulos.\r\n \r\nTeniendo en cuenta el texto anterior. 'Qué le causó a George observar aquella cosa?''':'Trauma',\r\n#15\r\n'''Sujetaba el brazo de George con su puño grueso y agusanado. Tiró de él hacia aquella\r\nhorrible oscuridad por donde el agua corría y rugía y aullaba llevando hacia el mar los desechos de\r\nla tormenta. George intentó apartarse de esa negrura definitiva y empezó a gritar como un loco\r\nhacia el gris cielo otoñal de aquel día de otoño de 1957. Sus gritos eran agudos y penetrantes y a\r\nlo largo de toda la calle, la gente se asomó a las ventanas y salió a los porches.\r\n —Flotan –gruñó la cosa–, flotan, Georgie. Y cuando estés aquí abajo, conmigo, tú también\r\nflotarás.\r\n\r\nTeniendo en cuenta el texto anterior, ¿Qué significa para George todo lo sucedido?''':'Fatalidad',\r\n#16\r\n'''El hombro de George chocó contra el bordillo. Dave Gardener, que ese día no había ido a\r\ntrabajar al Shoeboat debido a la inundación, vio sólo a un niño de impermeable amarillo, un niño\r\nque gritaba y se retorcía en el arroyo mientras el agua lodosa le corría sobre la cara haciendo que\r\nsus alaridos sonaran burbujeantes.\r\n —Aquí abajo todo flota –susurró aquella voz nauseabunda, riendo, y de pronto sonó un\r\ndesgarro y hubo un destello de agonía y George Denbrough dejó de existir.\r\n \r\nTeniendo en cuenta el texto anterior, ¿Qué significan los últimos parrafos?''':'Muerte',\r\n#17\r\n'''Dave Gardener fue el primero en llegar. Aunque llegó sólo cuarenta y cinco segundos\r\ndespués del primer grito, George Denbrough ya había muerto. Gardener lo agarró por el\r\nimpermeable, tiró de él hacia la calle... y al girar el cuerpo de George, también él empezó a gritar.\r\nEl lado izquierdo del impermeable del niño estaba de un rojo intenso. La sangre fluía hacia la\r\nalcantarilla desde el agujero donde había estado el brazo izquierdo. Un trozo de hueso,\r\nhorriblemente brillante, asomaba por la tela rota.\r\n Los ojos del niño miraban fijamente el cielo y mientras Dave retrocedía a tropezones hacia\r\nlos otros que ya corrían por la calle, empezaron a llenarse de lluvia.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué sintió Dave Gardener al voltear a George?''':'Horror',\r\n#18\r\n'''Los habitantes de Derry consideraban que el Festival del Canal, que se desarrolló entre el 15\r\ny el 21 de julio, había sido un gran éxito, algo bueno para la moral, la imagen de la ciudad... y el\r\nbolsillo. Los festejos de esa semana celebraban el centenario de la inauguración del canal que\r\ncorría por el centro de la ciudad. Había sido ese canal el que abriera plenamente a Derry al\r\ncomercio de la madera, entre 1884 y 1910, dando origen a los años de bonanza de Derry.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué se esperaba de Derry al abrir el canal?''':'Prosperidad',\r\n#19\r\n'''En el parque había una carpa enorme de lona a rayas donde se vendían refrescos; todas las\r\nnoches, una banda daba un concierto. En el parque Bassey se instaló una feria con atracciones y\r\njuegos administrados por los vecinos. Un tranvía especial recorría las zonas históricas de la\r\nciudad, de hora en hora, terminando el recorrido en la feria.\r\n\r\nTeniendo en cuenta el texto anterior, ¿Cómo era el ambiente en el parque?''':'Jovial',\r\n#20\r\n'''Sus ojos recorrieron el vestíbulo, hasta el pie de la amplia escalera, y\r\nHallorann dejó escapar un grito ahogado. La alfombra estaba salpicada de\r\nsangre. Sobre ella había un trozo de tela rosada. El rastro de sangre conducía a\r\nla escalera. En el pasamanos también se veían manchas de sangre.\r\n—Oh, Dios —murmuró Hallorann, y volvió a levantar la voz—: ¡Danny!\r\n¡DANNY!\r\nParecía que el silencio del hotel se mofara de él con sus ecos, malignos,\r\nretorcidos.\r\n(¿Danny? ¿Quién es Danny? ¿Hay alguien aquí que conozca a Danny? Danny, Danny,\r\n¿quién tiene el Danny? ¿Alguien quiere jugar a busquemos el Danny? ¿A ponerle la cola al\r\nDanny? Vete de aquí, negro, que aquí nadie conoce a Danny desde Adán.) \r\n \r\nTeniendo en cuenta el texto anterior. ¿Cómo describirías el estado mental de Hallorann?''':'Locura',\r\n#21\r\n'''Jesús, ¿acaso habría pasado por todo eso para en definitiva llegar\r\ndemasiado tarde? ¿Se había consumado ya todo?\r\nSubió la escalera de dos en dos peldaños y se detuvo al llegar a la\r\nprimera planta. El rastro de sangre conducía al apartamento del vigilante. El\r\nhorror se le infiltró lentamente en las venas y en el cerebro, mientras empezaba\r\na andar por el corto pasillo. Los animales del seto habían sido algo tremendo,\r\npero esto era peor, íntimamente, sabía lo que iba a encontrar cuando llegara. \r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué sentía mientras recorría el rastro?''':'Intranquilidad',\r\n#22\r\n'''Hallorann oyó el murmullo y empezó a darse la vuelta, al tiempo que se\r\nagachaba, pero el mazo de roque bajó silbando. La capucha del chaquetón\r\namortiguó el golpe, pero no lo suficiente. Sintió como si en la cabeza le estallara\r\nun cohete, deshaciéndose en un rastro de estrellas... y después, nada.\r\nTambaleante, retrocedió contra la pared empapelada, y Jack volvió a\r\ngolpearlo; esta vez, el mazo le acertó de costado y le hizo astillas el pómulo, al\r\nmismo tiempo que le rompía la mayor parte de los dientes del lado izquierdo de\r\nla mandíbula. Hallorann se desplomó, inerte.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué sentia el agresor de Hallorann para hacer todo eso?''':'Placer',\r\n#23\r\n'''Tres minutos más tarde, la puerta del ascensor se abría estrepitosamente\r\nen la penumbra de la tercera planta. Sólo Jack Torrance estaba en él. La caja se\r\nhabía detenido antes de llegar a la puerta, y Jack Torrance tuvo que izarse hasta\r\nel nivel del pasillo, retorciéndose penosamente de dolor. Tras él arrastraba el\r\nastillado mazo de roque. Afuera, en los aleros, el viento aullaba y rugía. Los ojos\r\nde Jack giraban salvajemente en las órbitas. Tenía el pelo sucio de sangre y\r\nconfeti.\r\n\r\nTeniendo en cuenta el texto anterior, ¿Qué es Jack?''':'Asesino',\r\n#24\r\n'''Allí arriba estaba su hijo, allí arriba en alguna parte. Jack lo percibía. Sin\r\nnadie que lo controlara, sería capaz de cualquier cosa. De garrapatear con sus\r\npasteles de colores el carísimo empapelado sedoso, de estropear los muebles,\r\nde romper las ventanas. Era un mentiroso, un falso, a quien había que castigar...\r\nseveramente.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué cree Jack que es su hijo?''':'Malicia',\r\n#25\r\n'''Oscuridad y pasillos. Danny andaba perdido por una oscuridad y unos\r\npasillos que eran como los que había dentro del hotel, pero de algún modo\r\ndiferentes. Las paredes, revestidas con su papel sedoso, se elevaban\r\ninterminablemente sin que Danny, por más que estirara el cuello, alcanzara a ver\r\nel techo. Estaba perdido en la oscuridad. Todas las puertas tenían echada la\r\nllave, y también ellas se perdían en la oscuridad. Debajo de las mirillas (que en\r\nesas puertas gigantescas tenían el tamaño de miras de armas de fuego), en vez,\r\nde leerse el número de la habitación, en cada puerta había una minúscula\r\ncalavera con las libias cruzadas.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué sentía Danny?''':'Confusion',\r\n#26\r\n'''Se detuvo, un niño que aún no hacía tres años había dejado los pañales,\r\ny ahí estaba, solo para intentar decidir dónde se encontraba, dónde podía estar.\r\nLe daba miedo, pero era un miedo que podía soportar. Ya hacía dos meses que\r\nvivía todos los días con miedo, con un miedo que variaba desde una inquietud\r\nsorda a un terror embrutecedor y directo. Eso se podía soportar. Pero quería\r\nsaber por que había venido Tony, por qué estaba pronunciando quedamente su\r\nnombre en ese pasillo que no era parte de las cosas reales ni tampoco del país\r\nde los sueños donde a veces Tony le mostraba cosas. Por qué, dónde...\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo se había sentido ultimamente el niño?''':'Angustiado',\r\n#27\r\n'''—Ya viene... —repitió Danny en un susurro aterrado, y le pareció que esa\r\nresonancia de golpes sordos, irregulares, estaba más cerca, se oía con más\r\nfuerza. El terror, que un momento antes era algo frío y distante, se convirtió en\r\nuna cosa inmediata. Ahora ya lograba entender las palabras, roncas, mezquinas,\r\narticuladas en una burda imitación de la voz de su padre, pero eso no era papá.\r\nAhora Danny lo sabía. Sabia.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué comprendió Danny?''':'Usurpación',\r\n#28\r\n'''¿Qué era? Danny casi lo sabía. ¿Algo que podía salvarlos, a él y a su\r\nmadre? Pero Tony había dicho que tendría que hacerlo todo él solo. ¿Qué era?\r\nSe apoyó contra la pared, tratando desesperadamente de pensar. Era tan\r\ndifícil... con el hotel que seguía intentando metérsele en la cabeza... con la\r\nimagen de esa forma oscura, encorvada, que blandía el mazo a izquierda y\r\nderecha, destrozando el empapelado... haciendo volar bocanadas de polvo de\r\nyeso.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué le hace sentir a Danny aquello que puede salvarlos?''':'Esperanza',\r\n#29\r\n'''En algún punto del laberinto de corredores que el chico iba dejando tras\r\nde sí, el ascensor se detuvo. Se oyó un ruido metálico al correrse la puerta. Y\r\ndespués una voz, que ya no estaba en su cabeza, sino que era terriblemente\r\nreal: \r\n—¿Danny? Danny, ven aquí un minuto, ¿quieres? Te has portado mal y\r\nquiero que vengas y te tomes tu medicina como un hombre. ¿Danny? ¡Danny!\r\n\r\nTeniendo en cuenta el texto anterior. ¿A qué cosa se refiere como laberinto?''':'Hotel', \r\n#30\r\n'''La obediencia estaba tan profundamente arraigada en él que llegó a dar\r\ndos pasos, automáticamente, hacia donde lo llamaba la voz antes de detenerse.\r\nJunto al cuerpo, los puños se le tensaron con violencia.\r\n(¡No eres real! ¡Cara falsa! ¡Ya sé lo que eres! ¡Quítate la máscara!)\r\n—¡Danny! —se reiteró el rugido—. ¡Ven aquí, cachorro! ¡Ven aquí y\r\ntómatela como un hombre!\r\nUn retumbar profundo y hueco, el del mazo al abatirse contra la pared.\r\nCuando la voz volvió a tronar su nombre, había cambiado de lugar: ahora estaba\r\nmás cerca. En el mundo de las cosas reales, la cacería comenzaba.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo es realmente Danny?''':'Educado', \r\n#31\r\n'''Danny escapó. Sin hacer ruido sobre la espesa alfombra, pasó corriendo\r\nfrente a las puertas cerradas, a lo largo del sedoso papel estampado, junto al\r\nextintor de incendios asegurado a la esquina de la pared. Tras una breve\r\nvacilación, echó a correr por el último pasillo. Al final no había nada más que una\r\npuerta cerrada; ya no quedaba por dónde escapar.\r\nPero el palo seguía allí, todavía apoyado contra la pared, donde lo había\r\ndejado papá.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo se le llama a la situación en la que Danny se encuentra?''':'Acorralado',\r\n#32\r\n'''Danny lo atrapó, lo levantó, estiró el cuello para mirar la trampilla. En el\r\nextremo del palo había un gancho que había que ensartar en una argolla fija en\r\nla trampilla. Y entonces...\r\nDe la trampilla pendía un candado «Yale», flamante. Era el que Jack\r\nTorrance había colocado en el cerrojo después de instalar las ratoneras para el\r\ncaso de que a su hijo se le ocurriera algún día la idea de hacer una exploración\r\npor allí.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo es realmente Jack?''':'Atento', \r\n#33\r\n'''Un candado. El terror lo invadió.\r\nTras él, aquello venía, torpemente, tambaleándose, ya a la altura de la\r\nsuite presidencial, haciendo silbar malignamente en el aire el mazo de roque.\r\nDanny retrocedió contra la última puerta, infranqueable, y lo esperó.\r\n\r\nTeniendo en cuenta el texto anterio. ¿Qué está haciendo Jack?''':'Buscando',\r\n#34\r\n'''Wendy volvió en sí poco a poco; el agotamiento gris se disipó y fue\r\nremplazándole el dolor: en la espalda, en la pierna, en el costado... no creyó que\r\nsería capaz de moverse. Hasta los dedos le dolían, y en el primer momento no\r\nsabía por qué.\r\n(Por la hojita de afeitar, por eso.)\r\n\r\nTeniendo en cuenta el texto anterior. ¿En qué estado se encuentra Wendy?''':'Miserable',\r\n#35\r\n'''El pelo rubio, ahora pegoteado y enredado, le caía sobre los ojos. Se lo\r\napartó con la mano y sintió que las costillas rotas se le clavaban por dentro,\r\nhaciéndola gemir. Empezó a ver el campo azul y blanco del colchón, manchado\r\nde sangre. De ella, o tal vez de Jack. En todo caso, era sangre fresca. No había\r\nestado mucho tiempo sin conocimiento, y eso era importante porque...\r\n(¿Por qué?)\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué sucedio con quien relata y con Jack?''':'Enfrentamiento',\r\n#36\r\n'''Porque...\r\nLo primero que recordó fue el zumbido, como de insecto, de un motor.\r\nDurante un momento se quedó estúpidamente detenida en el recuerdo y\r\ndespués, en una especie de picada vertiginosa y nauseabunda, su mente\r\nretrocedió y le hizo ver todo en una sola mirada.\r\nHallorann. Debía de haber sido Hallorann. ¿Por qué, si no, podría\r\nhaberse ido Jack tan de improviso, sin haber terminado con... sin haber\r\nterminado con ella?\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo se le llama al estado en el que estaba quien narra?''':'Trance',\r\n#37\r\n'''De alguna manera se las arregló para ponerse de pie, ir tambaleándose\r\npor el dormitorio y, a través de las ruinas del cuarto de estar, hasta la destrozada\r\npuerta del apartamento. La abrió de un empujón y salió al pasillo.\r\n—¡Danny! —gritó, aunque el dolor en el pecho la hacía estremecer—.\r\n¡Señor Hallorann! ¿Hay alguien ahí? ¿Hay alguien?\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué era lo que estaba sintiendo quien narra?''':'Dolor', \r\n#38\r\n'''El ascensor, que se había puesto otra vez en movimiento, se detuvo.\r\nWendy oyó el choque metálico de la puerta plegable al correrse, y después le\r\npareció oír una voz. Tal vez hubiera sido su imaginación. El ruido del viento era\r\ndemasiado fuerte para estar segura, en realidad.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cuál es la razón de que escuchara una voz?''':'Imaginación', \r\n#39\r\n'''Recostándose contra la pared, se dirigió lentamente hacia la intersección\r\ncon el pasillo corto. Cuando estaba a punto de llegar allí, la dejó helada el grito\r\nque subió por el hueco del ascensor y por el de la escalera:\r\n—¡Danny! ¡Ven aquí, cachorro! ¡Ven aquí y tómala como un hombre!\r\nJack. En la segunda o en la tercera planta. Buscando a Danny.\r\nAl llegar a la esquina, Wendy tropezó y estuvo a punto de caerse. El\r\naliento se le heló en la garganta. Había algo\r\n(¿alguien?)\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo se siente quien narra?''':'Desconcertado', \r\n#40\r\n'''Era el señor Hallorann. Había venido, después de todo.\r\nCuidadosamente, Wendy se arrodilló junto a él, rogando en una\r\nincoherente plegaria que no estuviera muerto. Le sangraba la nariz, y de la boca\r\nle había salido un terrible coágulo de sangre. Un lado de la cara era un solo\r\nmagullón hinchado y purpúreo. Pero respiraba, a Dios gracias. Eran bocanadas\r\nlargas y difíciles que lo sacudían todo entero.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo se sintío quien narra al ver que Hallorann sigue con vida?''' :'Consolado',\r\n#41\r\n'''No quedaba tiempo para pensarlo. Wendy sacudió a Hallorann, con la\r\ncara contraída por el dolor de las costillas rotas, que sentía en el costado como\r\nuna masa ardiente, hinchada y magullada.\r\n(¿Y si me desgarran el pulmón cada vez que me muevo?)\r\nTampoco eso había manera de evitarlo. Si Jack encontraba a Danny, lo\r\nmataría, lo golpearía con el mazo hasta matarlo, como había intentado hacer\r\ncon ella.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo se siente quien narra?''':'Preocupado', \r\n#42\r\n'''Danny se quedó de espaldas contra la puerta, mirando hacia la\r\nintersección donde los dos pasillos se cortaban en ángulo recto. El ruido\r\nconstante, irregular, retumbante del mazo contra las paredes se oía cada vez,\r\nmás. Aquello que lo perseguía aullaba, vociferaba y maldecía. Sueño y realidad\r\nse habían unido sin fisura alguna.\r\nAhora apareció ante sus ojos.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo es quien se acerca a Danny?''':'Irracional', \r\n#43\r\n'''En cierto sentido, lo que sintió Danny fue alivio. Eso no era su padre. La\r\nmáscara del rostro y del cuerpo, desgarrada, hecha pedazos, era una triste\r\nparodia. Eso no era su papá, ese horror de los programas de televisión\r\nterroríficos del sábado por la noche, con los ojos en blanco, los hombros\r\nencorvados, la camisa empapada de sangre. No era su papá.\r\n—Ahora, por Dios —jadeó aquello y se enjugó los labios con una mano\r\ntemblorosa—. Ahora vas a ver quién es el que manda aquí. Ya verás. No es a ti\r\na quien quieren, es a mí. ¡A mí, a mí!\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué empieza a surgir dentro de Danny?''':'Vigor', \r\n#44\r\n'''—A ver si me sales con alguno de tus trucos ahora —farfulló—. No nací\r\nayer, ¿sabes? No acabo de caerme de la higuera, por Dios. Y voy a cumplir mis\r\ndeberes de padre contigo, muchachito.\r\n—Tú no eres mi padre —declaró Danny.\r\nAquello se detuvo. Durante un momento pareció indeciso, como si en\r\nrealidad no estuviera seguro de quién —o qué— era. Después empezó a andar\r\nde nuevo. El mazo descendió silbando y se estrelló contra una puerta, que\r\nrespondió con un ruido hueco.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Por qué dudó el \\\"padre\\\" de Danny?''':'Recuerdos',\r\n#45\r\n'''—Eres un mentiroso —respondió—. ¿Quién soy, si no? Tengo las dos\r\nmarcas de nacimiento, el ombligo hundido y la picha, muchachito. Pregúntale a\r\ntu madre.\r\n—Tú eres una máscara —insistió Danny—. Una cara falsa. La única\r\nrazón que tiene el hotel para usarte es que no estás tan muerto como los otros.\r\nPero cuando el hotel haya terminado contigo, no quedará nada de ti. A mí no me\r\nasustas.\r\n\r\nTeniendo en cuenta el texto anterior. ¿Qué es el hotel?''':'Titiretero', \r\n#46\r\n'''—¡Pues ya te asustaré! —fue un aullido. El mazo silbó ferozmente al\r\ndescender y se estrelló sobre la alfombra, entre los pies de Danny. El chico no\r\nretrocedió—. ¡Tú me mentiste! ¡Te conchabaste con ella! ¡Conspirasteis contra\r\nmí! Además, ¡hiciste trampa! ¡Copiaste el examen final! —bajo las cejas\r\npobladas, los ojos lo miraban furiosamente con un resplandor de lunática\r\nastucia—. Pero ya lo encontraré, también. Está por ahí en alguna parte, en el\r\nsótano. Ya yo encontraré. Me prometieron que podía buscar todo lo que quisiera\r\n—el mazo volvió a alzarse en el aire.\r\n\r\nTeniendo en cuenta el texto anterior. Quien grita, ¿qué grita?''':'Conspiraciones', \r\n#47\r\n'''Hallorann había empezado a reaccionar, pero de pronto Wendy dejó de\r\ndarle suaves golpes en la mejilla. Hacía un momento que por el hueco del\r\nascensor, casi inaudibles entre el rugido del viento, habían llegado unas\r\npalabras:\r\n—¡Hiciste trampa! ¡Copiaste el examen final!\r\n\r\nTeniendo en cuenta el texto anterior. 'Qué le pasó a Hallorann?''':'Despertó',\r\n#48\r\n'''Venían desde algún lugar muy alejado del ala oeste. Wendy estaba casi\r\nconvencida de que estaban en la tercera planta, y de que Jack—o aquello que\r\nhabía tomado posesión de Jack— había encontrado a Danny. Ni ella ni\r\nHallorann podían hacer nada ahora.\r\n—Oh, doc —murmuró, y las lágrimas le velaron los ojos.\r\n—El hijo de puta me rompió la mandíbula —masculló turbiamente\r\nHallorann—. Y la cabeza... —trabajosamente, se sentó.\r\nTeniendo en cuenta el texto. ¿Cómo se tornó el ambiente?''':'Relajado', \r\n#49\r\n'''—Mienten —repitió Danny. Con la rapidez relampagueante de un\r\nmeteoro, demasiado rápido para echarle mano y detenerlo, algo le había pasado\r\npor la cabeza. No le quedaban más que algunas palabras de la idea.\r\n(está por ahí en alguna parte en el sótano)\r\n(tú recordarás lo que olvidó tu padre)\r\n\r\nTeniendo en cuenta el texto anterior. ¿Cómo se siente Jack?''':'Eufórico', \r\n#50\r\n'''—No... no deberías hablarle de esa forma a tu padre —la voz era ronca,\r\nel mazo tembló y descendió lentamente—. Sólo haces empeorar las cosas para\r\nti. El... el castigo. Peor.\r\nTambaleándose como si estuviera ebrio, aquello lo miraba con una llorosa\r\nconmiseración que empezaba a convertirse en odio. El mazo empezó a\r\nlevantarse nuevamente.\r\n\r\nTeniendo en cuenta el texto anterior. ¿cómo es la actitud de Jack?''':'Desquiciada', \r\n}\r\n#Fabricar todo\r\ndef Pregunta ():\r\n for TodaslasPreguntas in range(10): #Se realizarán 10 archivos:\r\n Respuestas = open('respuestas%s.txt' % (TodaslasPreguntas + 1),'w+') #Respuestas\r\n PreguntaconRespuesta = open('preguntacompleta%s.txt' % (TodaslasPreguntas +1),'w+')#La pregunta completa\r\n \r\n RespuestasdePreguntas= list(RelacionPreguntas.keys()) #Aleatorizar las preguntas.\r\n random.shuffle(RespuestasdePreguntas)\r\n \r\n for TodaslasRespuestas in range(1):\r\n \r\n RespuestaCorrecta = RelacionPreguntas[RespuestasdePreguntas[TodaslasRespuestas]] #Indicar cuál es la respuesta correcta.\r\n RespuestaIncorrecta = list(RelacionPreguntas.values()) #Mostrar otras respuestas incorrectas.\r\n del RespuestaIncorrecta[RespuestaIncorrecta.index(RespuestaCorrecta)] #Eliminar de la lista de respuestas incorrectas la correcta\r\n RespuestaIncorrecta = random.sample(RespuestaIncorrecta, 3) #A respuesta incorrecta se le concatenan 3 valores al azar de la lista\r\n Opciones = RespuestaIncorrecta + [RespuestaCorrecta] #Las otras respuestas\r\n random.shuffle(Opciones) #Aleatorizar las otras respuestas\r\n \r\n PreguntaconRespuesta.write('%s. %s\\n\\n' % (TodaslasPreguntas + 1,RespuestasdePreguntas[TodaslasRespuestas])) #Escribir la pregunta en un archivo\r\n \r\n del RelacionPreguntas[RespuestasdePreguntas[TodaslasRespuestas]] #Evitar que se repitan las preguntas eliminandolas del diccionario\r\n \r\n for i in range(4): #Escribir debajo de la pregunta las respuestas\r\n PreguntaconRespuesta.write(' %s. %s\\n' % ('ABCD'[i], Opciones[i]))\r\n PreguntaconRespuesta.write('\\n')\r\n \r\n Respuestas.write('%s' % 'ABCD'[Opciones.index(RespuestaCorrecta)]) #Escribir en otro arhivo la respuesta de la pregunta\r\n \r\n PreguntaconRespuesta = open('preguntacompleta%s.txt' % (TodaslasPreguntas +1)) \r\n \r\n PreguntaFinal=PreguntaconRespuesta.read()\r\n \r\n Respuestas.close()\r\n PreguntaconRespuesta.close() \r\n return(PreguntaFinal) #Enviar todo lo obtenido al programa main\r\n\r\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\r\nPregunta() #Llamar a la función de arriba\r\n\r\nprint('Saludos, ingresa tu nombre') #Introducción\r\nname=str(input()) #Usuario\r\nif name.isalpha():\r\n name=name\r\nelse:\r\n while name.isalpha()==False:\r\n print('El nombre no puede llevar números ni caracteres especiales')\r\n print('Ingresa tu nombre')\r\n name=str(input())\r\nprint(name,''', un dia encaras un libro bastante extraño, su contenido cambia y hace preguntas. Parece que solo queda leerlo.\r\n\r\nPresiona enter para comenzar.\r\nEscribe \"Help\" y presiona enter para leer las instrucciones.''')\r\nstart=str(input())\r\nif start != '' or start != 'help' or start != 'Help': #Instrucciones si se escribe 'Help'\r\n if start == 'help' or start == 'Help':\r\n print('''El juego funciona de la siguiente manera:\r\n-Deberás de leer con cuidado y antención los textos para responder correctamente.\r\n-La respuesta que quieras dar deberá de ser escrita solo ingresando la letra de la misma, en mayuscula y después presionar enter.\r\n-Si respondes erroneamente una pregunta, perderás vida.\r\n-Si tu vida llega a 0, perderás y tendrás que empezar desde el principio.\r\n-Los puntos que se obtienen son al azar.\r\n-Perderás puntos su contestas mal a una respuesta (Puedes tener puntuación negativa).\r\n-Obten la máxima puntuación.\r\n\r\nPresiona enter para comenzar.\r\n''')\r\n help1=str(input()) #Salir de instrucciones\r\n while help1 != '':\r\n print('Solo se acepta presionar la tecla \\\"enter\\\".')\r\n help1=str(input())\r\n\r\nprint('''Comienzas a leerlo y al parecer si contestas correctamente a sus cuestionamientos te recompenzará.\r\nFragmentos de texto sacados de los siguientes libros:\r\n-\\\"It\\\", de Stephen King.\r\n-\\\"El resplandor\\\", de Stephen King. \\n''') #Comienzo del juego\r\n\r\ndef abrirpregunta (a): #Abrir cada pregunta y mostrarla en pantalla, después cerrarlas para evitar arruinar todo.\r\n a1=open('preguntacompleta%s.txt' % (a),'r')\r\n print(a1.read())\r\n a1.close()\r\n \r\n a2=open('respuestas%s.txt' % (a),'r')\r\n return (a2)\r\n \r\n\r\nfor e in range(10): #Juego en si\r\n a2=(abrirpregunta(e+1)) #Llamar a la función que mostrará las preguntas\r\n respuesta_real=str(input()) #Confirmar que la respuesta sea correcta\r\n \r\n while respuesta_real != 'A' and respuesta_real != 'B' and respuesta_real != 'C' and respuesta_real != 'D':\r\n print('Solo se aceptan los valores de las respuestas en mayusculas: A, B, C o D.')\r\n respuesta_real=str(input()) #Todo este segmento limita las respuestas.\r\n \r\n if (respuesta_real in a2)==True: #En caso de serlo:\r\n print('Excelente')\r\n hp=hp+5 #Sistema de vida que no logré hacer funcionar en una función\r\n print('''+5 hp\r\nTus puntos de vida son: ''',hp,'\\n')\r\n azar=(random.randint(5,20)) #Sistema de puntos recibidos de forma al azar, minimo 5 y máximo 20\r\n puntosganados=azar\r\n puntos=puntos+puntosganados\r\n print('Has ganado, ',puntosganados,' puntos, tus puntos totales son: ',puntos)\r\n \r\n else: #En caso de no serlo:\r\n print('Respuesta incorrecta, asegurate de leer palabras clave y de comprender lo que estás leyendo.')\r\n hp=hp-20 #Sistema de vida que no logré hacer funcionar en una función\r\n print('''-20 hp\r\nTus puntos de vida son: ''',hp,'\\n')\r\n azar=(random.randint(5,20)) #Sistema de puntos recibidos de forma al azar, minimo 5 y máximo 20\r\n puntosperdidos=azar\r\n puntos=puntos-puntosperdidos\r\n print('Has perdido, ',puntosperdidos,' puntos, tus puntos totales son: ',puntos)\r\n \r\n print('Presiona enter para continuar.') #Pausa para leer información desplegada\r\n \r\n if hp <= 0: #Game over si vida llega a 0\r\n print('Oh no!, tu vida ha llegado a su fin, concentrate más la próxima vez y asegurate de comprender lo que lees.')\r\n proseguirfinal=input()\r\n if proseguirfinal=='':\r\n print('Saliendo')\r\n else:\r\n while proseguirfinal != '':\r\n print('Solo se acepta la entrada \\\"Enter\\\"')\r\n print('Presiona enter para continuar.')\r\n proseguirfinal=input()\r\n break\r\n \r\n proseguir=input() #Prosigue\r\n if proseguir=='':\r\n continue\r\n else:\r\n while proseguir != '':\r\n print('Solo se acepta la entrada \\\"Enter\\\"')\r\n print('Presiona enter para continuar.')\r\n proseguir=input()\r\n \r\n \r\nif puntos>=150: #Gamification\r\n print('''¡Felicidades!, tu conocimiento y el azar estuvieron de tu lado, no puedo recompensarte con nada mejor\r\nque una felicitación pero lo has hecho muy bien, ¡vuelve y mejora aún más tu record!''')\r\nelse:\r\n if puntos <150 and puntos>100:\r\n print('¡Muy bien!, pero se puede obtener un mejor puntaje, ¡Vuelve a intentarlo!')\r\n else:\r\n if puntos<100 and puntos>=50:\r\n print('¿Eso no ha salido perfecto cierto?, ¡vuelve y mejora tu record!')\r\n else:\r\n if puntos<50 and puntos>0:\r\n print('Pudo haber sido peor, ¡esfuerzate más y lo lograrás!')\r\n else:\r\n if puntos<=0:\r\n print('Tranquilo, la práctica hace al maestro, concentrate y lograrás mejorar ese puntaje.')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n " } ]
1
piotradamczyk7/test2
https://github.com/piotradamczyk7/test2
2ef602bc20c57dd21e3baafc2059f0c6b4d4e92d
8ec3aa12aa4f73b3cd2ffe1d0a79a71942aab38f
0ef39230872c5d4c8f8f48f6718ac3de3942a388
refs/heads/master
2020-06-17T01:54:51.478013
2019-07-08T07:54:46
2019-07-08T07:54:46
195,760,817
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43866172432899475, "alphanum_fraction": 0.4553903341293335, "avg_line_length": 24.66666603088379, "blob_id": "2da63df18538ff7c2e46036a2730cb597fc5229f", "content_id": "dca52b77149153b105fd57343e3d479d35d73728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 538, "license_type": "no_license", "max_line_length": 55, "num_lines": 21, "path": "/loteria.py", "repo_name": "piotradamczyk7/test2", "src_encoding": "UTF-8", "text": "money=100\nimport random\ndef flipping_coin(bit, y):\n if bit>money:\n print (\"You haven't got enought money!\")\n else:\n x=random.randint(1,2)\n if x == 1:\n z = \"Heads\"\n print (\"It's a Heads\")\n else:\n z = \"Tails\"\n print (\"It's a Tails\")\n if z == y:\n print (\"You have won \"+str(bit)+\" money.\")\n return bit\n else:\n print (\"You have lost \"+str(bit)+\" money.\")\n return bit*(-1)\n \nflipping_coin(10,\"Tails\")" } ]
1
johannes87/tgrep
https://github.com/johannes87/tgrep
bca22c70546241fde5b2ba60588e61e9844a02fd
8513060214c731b0322cb302d86c060a5dcf09e4
6331c310235bea0d43eadf0f7547173b11eedc57
refs/heads/master
2021-01-19T06:10:40.720369
2011-04-10T18:00:27
2011-04-10T18:00:27
1,412,433
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.772946834564209, "alphanum_fraction": 0.772946834564209, "avg_line_length": 28.571428298950195, "blob_id": "c98bb2847f395504f54d9424498be3bf493ae155", "content_id": "2a27f9ff50cbd7b2cf16e01122a22dfa39989174", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 207, "license_type": "no_license", "max_line_length": 70, "num_lines": 7, "path": "/README.md", "repo_name": "johannes87/tgrep", "src_encoding": "UTF-8", "text": "tgrep\n=====\n\ntgrep is a log-file grepping utility which makes use of binary search.\nIt assumes a log-file with its timestamps ordered by date, ascending.\n\nIt also assumes the timestamps have a fixed length.\n" }, { "alpha_fraction": 0.532474935054779, "alphanum_fraction": 0.5427753925323486, "avg_line_length": 33.264705657958984, "blob_id": "9e473aaf9e03f45cce792f58504b88dce13dae17", "content_id": "a83e0b762bb4f0f249e712821fe04ca8d5c30948", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3495, "license_type": "no_license", "max_line_length": 99, "num_lines": 102, "path": "/tgrep.py", "repo_name": "johannes87/tgrep", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport os\nimport time\n\nclass BinaryLogSearch(object):\n def __init__(self, log_path, timestamp_format, timestamp_length, search_timestamp):\n self.log_size = os.path.getsize(log_path)\n self.log_fd = os.open(log_path, os.O_RDONLY)\n self.search_time_tuple = time.strptime(search_timestamp, timestamp_format)\n self.timestamp_format = timestamp_format\n self.timestamp_length = timestamp_length\n \n def start_search(self):\n self.__found_pos = None\n self.__search(0, self.log_size - 1)\n\n def show_found(self, lines_before=0, lines_after=0, line_delimiter=\"\\n\"):\n if self.__found_pos == None:\n print \"nothing found\"\n return\n\n cur_pos = self.__found_pos - 1\n found_lines_before = 0\n while cur_pos >= 0 and found_lines_before <= lines_before:\n os.lseek(self.log_fd, cur_pos, os.SEEK_SET)\n found = os.read(self.log_fd, len(line_delimiter))\n if found == line_delimiter:\n found_lines_before += 1\n cur_pos -= 1\n \n output_start = cur_pos + 1 + len(line_delimiter)\n \n cur_pos = self.__found_pos + 1\n found_lines_after = 0\n while cur_pos < self.log_size and found_lines_after <= lines_after:\n os.lseek(self.log_fd, cur_pos, os.SEEK_SET)\n found = os.read(self.log_fd, len(line_delimiter))\n if found == line_delimiter:\n found_lines_after += 1\n cur_pos += 1\n \n output_length = cur_pos - 1 + len(line_delimiter) - output_start\n os.lseek(self.log_fd, output_start, os.SEEK_SET)\n output = os.read(self.log_fd, output_length)\n \n print output,\n\n def close(self):\n os.close(self.log_fd)\n \n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.close()\n\n def __get_next_time_tuple(self, search_pos):\n cur_pos = search_pos\n\n while cur_pos < self.log_size:\n os.lseek(self.log_fd, cur_pos, os.SEEK_SET)\n str = os.read(self.log_fd, self.timestamp_length)\n try:\n time_tuple = time.strptime(str, self.timestamp_format)\n return (time_tuple, cur_pos + self.timestamp_length)\n except:\n cur_pos += 1\n\n return (None, None)\n\n def __search(self, start_pos, end_pos):\n center_pos = start_pos + (end_pos - start_pos) / 2 \n (found_time_tuple, last_read_pos) = self.__get_next_time_tuple(center_pos)\n \n\n if found_time_tuple == None:\n return\n \n if last_read_pos > end_pos:\n if center_pos <= start_pos:\n # found next timestamp\n self.__found_pos = last_read_pos\n return\n else:\n self.__search(start_pos, center_pos - 1)\n\n else:\n if found_time_tuple == self.search_time_tuple:\n # found exact timestamp\n self.__found_pos = last_read_pos\n elif self.search_time_tuple > found_time_tuple:\n self.__search(last_read_pos + 1, end_pos)\n else:\n self.__search(start_pos, center_pos - 1)\n\ndef main():\n with BinaryLogSearch(\"log.txt\", \"%d/%b/%Y:%H:%M:%S\", 20, \"21/Jan/1975:18:56:41\") as log_search:\n log_search.start_search()\n log_search.show_found(3, 3)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5540069937705994, "alphanum_fraction": 0.6445993185043335, "avg_line_length": 25.090909957885742, "blob_id": "090ad793a99b5878c461741ce57b77bb51854322", "content_id": "a1affd928793f7728f5926dcd13ffe7fbaff20ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "no_license", "max_line_length": 97, "num_lines": 11, "path": "/genlog.py", "repo_name": "johannes87/tgrep", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nfrom time import strftime, gmtime\nimport random\n\ntemplate='127.0.0.1 - frank [%d/%b/%Y:%H:%M:%S -0700] \"GET {0} /apache_pb.gif HTTP/1.0\" 200 2326'\n\nt_secs = 0\nwhile True:\n print strftime(template, gmtime(t_secs)).format(random.randint(0,30) * ' ')\n t_secs += 10\n" } ]
3
YasuhiroOsajima/workflow_runner
https://github.com/YasuhiroOsajima/workflow_runner
1c344b7f92e183408bdb7f543d7a7de023635a36
1587bfc9802801bd88b12e24e98a1d132486b3bf
d8086f5774fdb5212d96370e8e484db9ee2364a4
refs/heads/master
2022-12-11T22:35:32.305821
2019-10-31T16:58:55
2019-10-31T16:58:55
189,456,802
0
0
null
2019-05-30T17:40:28
2019-10-31T16:58:57
2022-12-08T05:12:11
Python
[ { "alpha_fraction": 0.555311381816864, "alphanum_fraction": 0.5633699893951416, "avg_line_length": 26.85714340209961, "blob_id": "a6aab3fd2a30e0b825f5f191f84a007b5a322d29", "content_id": "ad942788db85e8d61e51745e179ad731a50a82e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 66, "num_lines": 49, "path": "/tests/internal/workflow/test_parser.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Unit test for workflow parser \"\"\"\n\nimport unittest\n\nimport yaml\n\nfrom internal.workflow import tree\n\n\nclass TestWorkFlowParser(unittest.TestCase):\n \"\"\" Unit test for workflow parser \"\"\"\n\n def test_generate_workflow_dict(self):\n \"\"\" Test case for YAML file convert to dict \"\"\"\n\n workflow_yml = \"\"\"\n---\n- job_template: sample_job1\n success:\n - job_template: sample_job2\n always:\n - job_template: sample_job3\"\"\"\n\n result = yaml.load(workflow_yml, Loader=yaml.SafeLoader)\n\n correct = [{'job_template': 'sample_job1',\n 'success': [{'job_template': 'sample_job2'}],\n 'always': [{'job_template': 'sample_job3'}]}]\n\n self.assertEqual(result, correct)\n\n def test_workflow_parse(self):\n \"\"\" Test case dict convert to workflow Node obj \"\"\"\n\n workflow = [{'job_template': 'sample_job1',\n 'success': [{'job_template': 'sample_job2'}],\n 'always': [{'job_template': 'sample_job3'}]}]\n dry_run = True\n extra_vars_arg = {'sample_vars': 'sample'}\n\n top_node = tree.generate_workflow_tree(workflow, dry_run,\n extra_vars_arg)\n correct = 1\n self.assertEqual(top_node.node_id, correct)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.4833886921405792, "alphanum_fraction": 0.7009966969490051, "avg_line_length": 15.722222328186035, "blob_id": "45e1065f9f4d57cf7b9af92f6daa1d7a538d922a", "content_id": "0c309c8b9850cd0ad25715a7df51d8a722b8c2fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 602, "license_type": "no_license", "max_line_length": 25, "num_lines": 36, "path": "/requirements.txt", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "ansible==2.7.12\nappdirs==1.4.3\nasn1crypto==0.24.0\nbcrypt==3.1.6\ncertifi==2019.3.9\ncffi==1.12.3\nchardet==3.0.4\ncryptography==2.6.1\ndecorator==4.4.0\ndogpile.cache==0.7.1\nidna==2.8\niso8601==0.1.12\nJinja2==2.10.1\njmespath==0.9.4\njsonpatch==1.23\njsonpointer==2.0\nkeystoneauth1==3.14.0\nMarkupSafe==1.1.1\nmunch==2.3.2\nnetifaces==0.10.9\nopenstacksdk==0.28.0\nos-client-config==1.32.0\nos-service-types==1.7.0\nparamiko==2.4.2\npbr==5.2.0\npyasn1==0.4.5\npycparser==2.19\nPyNaCl==1.3.0\nPyYAML==5.1\nrequests==2.22.0\nrequestsexceptions==1.4.0\nshade==1.31.0\nsix==1.12.0\nstevedore==1.30.1\ntexttable==1.6.1\nurllib3==1.25.2\n" }, { "alpha_fraction": 0.5565569996833801, "alphanum_fraction": 0.559260904788971, "avg_line_length": 31.632352828979492, "blob_id": "e6d5a958854297c74fc258532dd90ebf3ac1d8e4", "content_id": "632fbd51f8f9bce6790445b59ea62bfe2f91aca7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4438, "license_type": "no_license", "max_line_length": 78, "num_lines": 136, "path": "/internal/workflow/tree.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nTree structure generator for workflow parser.\n\"\"\"\n\nimport glob\nimport pathlib\n\nfrom internal.workflow import node\n\n# resource file path from project top directory.\nJOB_TEMPLATE_DIR = 'resource_files/job_template'\n\n\nclass ParseFailed(Exception):\n \"\"\"\n Parsing workflow structure failed.\n \"\"\"\n\n def __init__(self, message):\n super(ParseFailed, self).__init__()\n self.message = message\n\n def __str__(self):\n return repr(self.message)\n\n\ndef generate_workflow_tree(workflow: list, dry_run: bool,\n extra_vars_arg: dict) -> node.Node:\n \"\"\"\n arg 'workflow' ->\n [\n {\n \"job_template\": \"sample_job1\",\n \"success\": [\n {\n \"job_template\": \"sample_job2\",\n \"success\": [\n {\n \"job_template\": \"sample_job3\"\n }\n ]\n }\n ]\n }\n ]\n \"\"\"\n\n stack = []\n node_id = 0\n initial_job_template: dict = workflow[0]\n\n top_node: node.Node = parse_job_dict(initial_job_template, stack, node_id,\n child_type=None, dry_run=dry_run,\n extra_vars_arg=extra_vars_arg)\n if not top_node:\n raise ParseFailed('Top level job_template not found '\n 'in target workflow file.')\n\n return top_node\n\n\ndef _get_playbook_file_path(job_template_name: str) -> str:\n top_dir: pathlib.PosixPath = \\\n pathlib.Path(__file__).resolve().parent.parent.parent\n job_template_dir_path = \\\n str(top_dir / \"{}/**/{}.y*\".format(JOB_TEMPLATE_DIR,\n job_template_name))\n match: list = glob.glob(job_template_dir_path, recursive=True)\n if not match:\n raise ParseFailed(\"Job_template file not found \"\n \"by resource files directory. \"\n \"job_template: `{}`\".format(job_template_name))\n\n playbook_path: str = match[0]\n return playbook_path\n\n\ndef parse_job_dict(job_dict: dict, stack: list, node_id: int,\n child_type: str = None, dry_run: bool = False,\n extra_vars_arg: dict = None):\n \"\"\" Create each job's Node and chain to it's parent Node.\"\"\"\n\n top_node = None\n node_id += 1\n\n # Get this job stage's executable keyword. Maybe `job_template`.\n # nested workflow yaml is an future issue.\n # execute_available = {'job_template', 'workflow'}\n execute_available = {'job_template'}\n\n executable_keywords = execute_available & set(job_dict.keys())\n if len(executable_keywords) != 1:\n raise ParseFailed(\"Invalid executable_keywords: `{}`\"\n .format(executable_keywords))\n\n keyword: str = list(executable_keywords)[0]\n\n # Get this stage's job_template name.\n # Currently, nested workflow is not supported.\n job_template_name: str = \\\n job_dict[keyword] # Target job's `job_template` playbook name.\n playbook_path: str = _get_playbook_file_path(job_template_name)\n\n # Parse and prepare job_template.\n # And go to next stage by Depth first search.\n _node = node.Node(node_id, job_template_name, playbook_path)\n if node_id == 1:\n top_node = _node\n _node.prepare_job_node(dry_run, extra_vars_arg=extra_vars_arg)\n else:\n parent_node: node.Node = stack[-1]\n _node.prepare_job_node(dry_run, parent_node=parent_node,\n case_type=child_type)\n\n if node.SwitchJobResult.is_success(child_type):\n _node.add_parent_success(parent_node)\n elif node.SwitchJobResult.is_failed(child_type):\n _node.add_parent_failed(parent_node)\n elif node.SwitchJobResult.is_always(child_type):\n _node.add_parent_always(parent_node)\n else:\n raise ParseFailed(\"Invalid keyword specified: `{}`\"\n .format(child_type))\n\n # Move forward to each result next job stage.\n stack.append(_node)\n for state, child_list in job_dict.items():\n if node.SwitchJobResult.is_result_keyword(state):\n for child_dict in child_list:\n parse_job_dict(child_dict, stack, node_id, child_type=state,\n dry_run=dry_run)\n\n stack.pop()\n\n return top_node\n" }, { "alpha_fraction": 0.6567164063453674, "alphanum_fraction": 0.6580732464790344, "avg_line_length": 23.566667556762695, "blob_id": "e9d5a51a9b785d82d85c260b037aad5369035c3d", "content_id": "47277b3ba9c73f828cb8db1b6308fedebdf5046c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 737, "license_type": "no_license", "max_line_length": 70, "num_lines": 30, "path": "/internal/playbook/runner.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nRunner method to start running playbook.\n\"\"\"\n\nimport shutil\n\nfrom ansible.cli import playbook\nimport ansible.constants as conf_param\n\n\ndef run_playbook(playbook_path: str, inventory_path: str,\n auth_extra_vars: str, extra_vars_json: str = None):\n \"\"\" Execute ansible-playbook. \"\"\"\n\n ansible_path: str = shutil.which('ansible-playbook')\n args = [ansible_path, '-i', inventory_path, '-e', auth_extra_vars]\n\n if extra_vars_json:\n args.append('-e')\n args.append(extra_vars_json)\n\n args.append(playbook_path)\n\n cli = playbook.PlaybookCLI(args)\n cli.parse()\n exit_code: int = cli.run()\n\n shutil.rmtree(conf_param.DEFAULT_LOCAL_TMP, True)\n return exit_code\n" }, { "alpha_fraction": 0.5559830665588379, "alphanum_fraction": 0.5577145218849182, "avg_line_length": 32.108280181884766, "blob_id": "a0dcdf4fa7c8548eeb109ebed3e23081908b7d6a", "content_id": "03869209bb8cd1e1e150742d9a25096624071af5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5198, "license_type": "no_license", "max_line_length": 77, "num_lines": 157, "path": "/internal/workflow/runner.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nRunner for workflow.\n\"\"\"\n\nimport copy\nfrom datetime import datetime, timezone\n\nfrom internal.workflow import parser as w_parser\n\n\nclass JobRecord:\n \"\"\" Data class for recording job result. \"\"\"\n\n def __init__(self, job_id: int, job_template_name: str):\n self._start: datetime = datetime.now(timezone.utc)\n self._end: str = ''\n\n self._job_id: int = job_id\n self._job_template_name: str = job_template_name\n self._type: str = 'job_template' # workflow_job is no supported yet.\n self._status: str = ''\n\n def set_result_successful(self):\n \"\"\" record job result \"\"\"\n self._status = 'successful'\n\n def set_result_failed(self):\n \"\"\" record job result \"\"\"\n self._status = 'failed'\n\n def set_end_time(self):\n \"\"\" record job finished time \"\"\"\n self._end = datetime.now(timezone.utc)\n\n def get_created_time(self) -> str:\n \"\"\" get `created_time` for printing \"\"\"\n return self._start.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n\n def get_elapsed(self) -> str:\n \"\"\" get `elapsed` for printing \"\"\"\n return str(self._end - self._start).split(':')[-1]\n\n @property\n def job_id(self) -> int:\n \"\"\" getter for job_template_name \"\"\"\n return self._job_id\n\n @property\n def job_template_name(self) -> str:\n \"\"\" getter for job_template_name \"\"\"\n return self._job_template_name\n\n @property\n def type(self) -> str:\n \"\"\" getter for job type \"\"\"\n return self._type\n\n @property\n def status(self) -> str:\n \"\"\" getter for job result \"\"\"\n return self._status\n\n\nclass WorkflowRunner:\n \"\"\" Workflow runner. \"\"\"\n\n def __init__(self, inventory_file: str):\n self.inventory_file_path = inventory_file\n\n # record results of running job_templates.\n self.executed = []\n\n def dry_run(self, workflow_node: w_parser.WorkflowNode):\n \"\"\"\n Check each Ansible playbook's all of variables\n in each node's `before_extra_vars`.\n \"\"\"\n\n workflow_node.dry_run()\n\n if workflow_node.current_node.success:\n for node in workflow_node.current_node.success:\n child_workflow_node: w_parser.WorkflowNode = \\\n copy.deepcopy(workflow_node)\n child_workflow_node.go_next_child(node)\n self.dry_run(child_workflow_node)\n\n if workflow_node.current_node.failed:\n for node in workflow_node.current_node.failed:\n child_workflow_node: w_parser.WorkflowNode = \\\n copy.deepcopy(workflow_node)\n child_workflow_node.go_next_child(node)\n self.dry_run(child_workflow_node)\n\n if workflow_node.current_node.always:\n for node in workflow_node.current_node.always:\n child_workflow_node: w_parser.WorkflowNode = \\\n copy.deepcopy(workflow_node)\n child_workflow_node.go_next_child(node)\n self.dry_run(child_workflow_node)\n\n def run(self, workflow_node: w_parser.WorkflowNode, auth_extra_vars: str,\n work_dir: str, job_id: int = 1) -> list:\n \"\"\" Execute each Ansible playbook. \"\"\"\n\n job_template_name: str = workflow_node.current_node.node_name\n\n print()\n print('-----')\n print(\"<< Execute job: '{}' >>\".format(job_template_name))\n\n record = JobRecord(job_id, job_template_name)\n\n r_code = workflow_node.run(self.inventory_file_path,\n auth_extra_vars,\n work_dir)\n record.set_end_time()\n\n if r_code == 0:\n record.set_result_successful()\n else:\n record.set_result_failed()\n\n self.executed.append(record)\n\n # Go next job\n if r_code == 0 and workflow_node.current_node.success:\n for node in workflow_node.current_node.success:\n job_id += 1\n child_workflow_node: w_parser.WorkflowNode = \\\n copy.deepcopy(workflow_node)\n child_workflow_node.go_next_child(node)\n self.run(child_workflow_node, auth_extra_vars, work_dir,\n job_id=job_id)\n\n elif r_code != 0 and workflow_node.current_node.failed:\n for node in workflow_node.current_node.failed:\n job_id += 1\n child_workflow_node: w_parser.WorkflowNode = \\\n copy.deepcopy(workflow_node)\n child_workflow_node.go_next_child(node)\n self.run(child_workflow_node, auth_extra_vars, work_dir,\n job_id=job_id)\n else:\n pass\n\n if workflow_node.current_node.always:\n for node in workflow_node.current_node.always:\n job_id += 1\n child_workflow_node: w_parser.WorkflowNode = \\\n copy.deepcopy(workflow_node)\n child_workflow_node.go_next_child(node)\n self.run(child_workflow_node, auth_extra_vars, work_dir,\n job_id=job_id)\n\n return self.executed\n" }, { "alpha_fraction": 0.5643516778945923, "alphanum_fraction": 0.5645110011100769, "avg_line_length": 34.87428665161133, "blob_id": "0bab1cb307488e09c14298675d92b19b18935f22", "content_id": "6ac3e923345ab156006abfa69c81b26f12191a10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6278, "license_type": "no_license", "max_line_length": 79, "num_lines": 175, "path": "/internal/workflow/node.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nNode object for job_template information..\n\"\"\"\n\nfrom internal.playbook import parser\n\n\nclass SwitchJobResult:\n \"\"\" Check methods state keyword.\"\"\"\n\n success_keyword = {'success'}\n failed_keyword = {'failure'}\n always_keyword = {'always'}\n\n @classmethod\n def is_success(cls, state: str):\n \"\"\" `state` is success \"\"\"\n return state in cls.success_keyword\n\n @classmethod\n def is_failed(cls, state: str):\n \"\"\" `state` is failed \"\"\"\n return state in cls.failed_keyword\n\n @classmethod\n def is_always(cls, state: str):\n \"\"\" `state` is always \"\"\"\n return state in cls.always_keyword\n\n @classmethod\n def is_result_keyword(cls, state):\n \"\"\" `state` is in result keyword \"\"\"\n result_keywords: set = (cls.success_keyword |\n cls.failed_keyword |\n cls.always_keyword)\n return state in result_keywords\n\n\nclass Node:\n \"\"\"\n workflow job_template node in workflow tree.\n \"\"\"\n\n def __init__(self, node_id: int, node_name: str, playbook_path: str):\n self.node_id = node_id\n self.node_name = node_name\n self.playbook_path = playbook_path\n\n # child job_template list.\n self.success = []\n self.failed = []\n self.always = []\n\n # extra_vars at this job_template stage.\n self.before_extra_vars = {}\n self.define_stats = {}\n self.define_fact = {}\n self.define_vars_header = set()\n self.after_extra_vars = {}\n self.after_extra_vars_failed = {}\n\n def _set_job_extra_vars_run(self, parent=None,\n extra_vars_arg: dict = None):\n extra_vars_dict = {}\n\n if parent:\n extra_vars_dict.update(parent.after_extra_vars)\n else:\n # Top level node case.\n if extra_vars_arg:\n # If `extra_vars` are given by command line args.\n extra_vars_dict.update(extra_vars_arg)\n\n # `extra_vars` at start of job_template executing.\n self.before_extra_vars = extra_vars_dict\n\n def _set_job_extra_vars_dry_run(self, parent=None,\n extra_vars_arg: dict = None,\n case_type: str = None):\n extra_vars_dict = {}\n\n if parent:\n if SwitchJobResult.is_success(case_type):\n extra_vars_dict.update(parent.after_extra_vars)\n else:\n # `failed` and `always` situation\n # doesn't include `set_stats` vars.\n extra_vars_dict.update(parent.after_extra_vars_failed)\n else:\n # Top level node case.\n if extra_vars_arg:\n # If `extra_vars` are given by command line args.\n extra_vars_dict.update(extra_vars_arg)\n\n # `extra_vars` at start of job_template executing.\n self.before_extra_vars = extra_vars_dict\n\n def _set_define_vars(self):\n defined: dict = parser.get_defined_variable_keys(self.playbook_path)\n stats: list = defined['set_stats']\n fact: dict = defined['set_fact']\n self.define_vars_header: set = defined['vars']\n # `fact` is dictionary to contain defined variables.\n # These dict's keys mean defined task timing in the playbook.\n # And the values mean defined variables name.\n\n if stats:\n self.define_stats = {key: None for key in stats}\n\n if [v_key for v_key in fact.values() if v_key]:\n self.define_fact = fact\n\n def _set_dry_run_after_extra_vars(self):\n self.after_extra_vars.update(self.before_extra_vars)\n self.after_extra_vars_failed.update(self.before_extra_vars)\n\n self.after_extra_vars.update(self.define_stats)\n\n def prepare_job_node_run(self, parent_node=None,\n extra_vars_arg: dict = None):\n \"\"\" This method is always called for top job_template \"\"\"\n\n self._set_job_extra_vars_run(parent=parent_node,\n extra_vars_arg=extra_vars_arg)\n self._set_define_vars()\n # Non top job_template node's `self.before_extra_vars`\n # will be replaced to parent's after extra_vars\n # in ahead of job running process.\n # And `self.after_extra_vars` will be set at after job running process.\n\n def prepare_job_node_dry_run(self, parent_node=None,\n extra_vars_arg: dict = None,\n case_type: str = None):\n \"\"\"\n Set job_template node's all of data for dry run.\n This method takes `extra_vars_arg` or `parent_node`.\n \"\"\"\n\n self._set_job_extra_vars_dry_run(parent=parent_node,\n extra_vars_arg=extra_vars_arg,\n case_type=case_type)\n self._set_define_vars()\n self._set_dry_run_after_extra_vars()\n\n def prepare_job_node(self, dry_run: bool, parent_node=None,\n extra_vars_arg: dict = None, case_type: str = None):\n \"\"\" This method is always called for top job_template \"\"\"\n\n if dry_run:\n self.prepare_job_node_dry_run(parent_node, extra_vars_arg,\n case_type)\n else:\n self.prepare_job_node_run(parent_node, extra_vars_arg)\n\n def set_before_extra_vars(self, parent_node):\n \"\"\" setter for Node's `before_extra_vars` \"\"\"\n parent_after_extra_vars: dict = parent_node.after_extra_vars\n self.before_extra_vars = parent_after_extra_vars\n\n def set_after_extra_vars(self, after_extra_vars: dict):\n \"\"\" setter for Node's `after_extra_vars` \"\"\"\n self.after_extra_vars = after_extra_vars\n\n def add_parent_success(self, parent):\n \"\"\" Add target Node to parent Node's `success` child list. \"\"\"\n parent.success.append(self)\n\n def add_parent_failed(self, parent):\n \"\"\" Add target Node to parent Node's `failed` child list. \"\"\"\n parent.failed.append(self)\n\n def add_parent_always(self, parent):\n \"\"\" Add target Node to parent Node's `always` child list. \"\"\"\n parent.always.append(self)\n" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.6459330320358276, "avg_line_length": 16.41666603088379, "blob_id": "5fb6db4403f8ed41ef4807a4236324427a21c434", "content_id": "224e81e8921f3c6d9ddf6faede64c01272a3ca25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 209, "license_type": "no_license", "max_line_length": 46, "num_lines": 12, "path": "/setup.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "\"\"\"\n$ pip install -e .\n\"\"\"\n\nfrom setuptools import setup, find_packages\n\nsetup(\n name=\"workflow_runner\",\n version='0.1.1',\n packages=find_packages(exclude=['tests']),\n include_package_data=True,\n)\n" }, { "alpha_fraction": 0.5060364007949829, "alphanum_fraction": 0.507673442363739, "avg_line_length": 32.24489974975586, "blob_id": "2b1349e9d126a63a9c3c2e3080e0bf10b8bde24a", "content_id": "b1a7412c91f712d581d6db6be9dc61168a99c55e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4887, "license_type": "no_license", "max_line_length": 80, "num_lines": 147, "path": "/cmd/workflow_runner.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\n$ python3 workflow_runner.py 'workflow file path'\n\"\"\"\n\nimport argparse\nimport json\nimport sys\n\nimport yaml\n\nfrom internal import auth_info as aui\nfrom internal import subcommand as com\n\n\ndef _parse_extra_vars(extra_vars: str) -> dict:\n def _is_json(text: str) -> bool:\n try:\n json.loads(text)\n except json.JSONDecodeError:\n return False\n except ValueError:\n return False\n\n return True\n\n if not extra_vars:\n extra_vars_arg: dict = {}\n\n elif extra_vars.startswith('@'):\n with open(extra_vars[1:], 'r') as evf:\n extra_vars_arg: dict = yaml.load(stream=evf, Loader=yaml.SafeLoader)\n\n elif _is_json(extra_vars):\n extra_vars_arg: dict = json.loads(extra_vars)\n\n else:\n extra_vars_arg: dict = yaml.load(extra_vars, Loader=yaml.SafeLoader)\n if not isinstance(extra_vars_arg, dict):\n print()\n print('<< Invalid argument. >>')\n print('Specified `extra_vars` format is invalid.')\n sys.exit(2)\n\n return extra_vars_arg\n\n\ndef _arg_parse() -> dict:\n usage = (\"\"\"\n Ansible workflow runner on local command line.\n\n Please use this command as follows:\n $ python3 %(prog)s `workflow file path`\\\n -i `inventory file path`\\\n (--ask-pass or --private-key `file path`)\\\n [-e '@extra-vars_file_path']\n\n If you want to check settings correctness, you can use `dry_run` mode.\n $ python3 %(prog)s `workflow file path`\\\n -i `inventory file path`\\\n --dry_run\\\n [-e '@extra-vars_file_path']\n \n\"\"\")\n\n parser = argparse.ArgumentParser(usage=usage, add_help=True)\n\n parser.add_argument('workflow_file',\n type=str,\n help='Target workflow file path.')\n parser.add_argument('-i', '--inventory_file',\n type=str,\n help='Target inventory file path.')\n\n parser.add_argument('-u', '--user',\n type=str,\n help=\"Ansible's `ansible_ssh_user` option. \"\n \"Default is current user.\")\n parser.add_argument('--port',\n type=int,\n help=\"Ansible's `ansible_port` option. \"\n \"Default is `22`.\")\n parser.add_argument('--become-user',\n type=str,\n help=\"Ansible's `ansible_become_user` option. \"\n \"Default is `root`.\")\n parser.add_argument('-K', '--ask-become-pass',\n action='store_true',\n help=\"Ansible's `ansible_become_pass` option.\")\n parser.add_argument('-e', '--extra-vars',\n type=str,\n help=\"Ansible's extra_vars option. \"\n \"Default is `None`.\")\n\n auth_method = parser.add_mutually_exclusive_group(required=True)\n auth_method.add_argument('-k', '--ask-pass',\n action='store_true',\n help='Password auth enable '\n 'for ansible remote login. '\n 'Please specify this or `--private-key`.')\n auth_method.add_argument('--private-key',\n type=str,\n help='Private key file path '\n 'for ansible remote login. '\n 'Please specify this or `--ask-pass`.')\n auth_method.add_argument('--dry_run',\n action='store_true',\n help='Run with `dry_run` mode.')\n\n args = parser.parse_args()\n\n auth_info: aui.AuthInfo = aui.AuthInfo(args.ask_pass,\n args.private_key,\n args.user,\n args.port,\n args.become_user,\n args.ask_become_pass)\n auth_extra_vars: str = auth_info.generate_auth_extra_vars()\n\n extra_vars: str = args.extra_vars\n extra_vars_dict: dict = _parse_extra_vars(extra_vars)\n\n return {'dry_run': args.dry_run,\n 'workflow_file': args.workflow_file,\n 'inventory_file': args.inventory_file,\n 'extra_vars': extra_vars_dict,\n 'auth_extra_vars': auth_extra_vars}\n\n\ndef main():\n \"\"\"\n Run workflow.\n \"\"\"\n\n args: dict = _arg_parse()\n dry_run: bool = args['dry_run']\n workflow_file: str = args['workflow_file']\n inventory_file: str = args['inventory_file']\n extra_vars: dict = args['extra_vars']\n auth_extra_vars: str = args['auth_extra_vars']\n\n com.execute(dry_run, workflow_file, inventory_file, auth_extra_vars,\n extra_vars)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.543067455291748, "alphanum_fraction": 0.5442944765090942, "avg_line_length": 29.185184478759766, "blob_id": "af76f5b0b20f2684e3fbd80498bd5ca4232f2514", "content_id": "8e93e251c427df1c17c5ee3dc872ba44f5acaead", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4075, "license_type": "no_license", "max_line_length": 78, "num_lines": 135, "path": "/internal/subcommand.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nrouting sub command process.\n\"\"\"\n\nfrom datetime import datetime, timezone\nimport os\nimport pathlib\nimport re\n\nimport texttable as ttb\n\nfrom internal.workflow import parser as w_parser\nfrom internal.workflow import runner as w_run\n\nDEFAULT_DIR = '/tmp/workflow_runner'\n\n\ndef _prepare_work_directory(dir_path='') -> str:\n if not dir_path:\n dir_path = DEFAULT_DIR\n\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n\n return dir_path\n\n\ndef _get_tty_width():\n tty_size = os.popen('stty size 2> /dev/null', 'r').read().split()\n if len(tty_size) != 2:\n return 0\n _, width = tty_size\n return int(width)\n\n\ndef _print_job_results(results: [w_run.JobRecord]):\n table = ttb.Texttable(max_width=_get_tty_width())\n\n table.set_deco(ttb.Texttable.HEADER |\n ttb.Texttable.VLINES |\n ttb.Texttable.BORDER)\n table.set_chars(['=', # horizontal\n ' ', # vertical\n ' ', # corner\n '=']) # header\n\n headers = [\"id\", \"name\", \"type\", \"status\", \"created\", \"elapsed\"]\n table.header(headers)\n table.set_cols_dtype(['t' for _ in headers])\n table.set_cols_align(['l' for _ in headers])\n\n for res in results:\n record = [res.job_id,\n res.job_template_name,\n res.type,\n res.status,\n res.get_created_time(),\n res.get_elapsed()]\n table.add_row(record)\n\n print()\n print('------ Job results ------')\n job_results: str = \\\n re.sub('^ ', '',\n table.draw().replace('\\n ', '\\n').replace('\\r ', '\\r'))\n print(job_results)\n print()\n\n\ndef _print_workflow_result(workflow_file: str, workflow_start: str,\n workflow_status: str):\n table = ttb.Texttable(max_width=_get_tty_width())\n\n table.set_deco(ttb.Texttable.HEADER |\n ttb.Texttable.VLINES |\n ttb.Texttable.BORDER)\n table.set_chars(['=', # horizontal\n ' ', # vertical\n ' ', # corner\n '=']) # header\n\n headers = [\"workflow_job_template\", \"created\", \"status\"]\n table.header(headers)\n table.set_cols_dtype(['t' for _ in headers])\n table.set_cols_align(['l' for _ in headers])\n\n workflow_name: str = pathlib.Path(workflow_file).name\n table.add_row([workflow_name, workflow_start, workflow_status])\n\n print('------ Workflow process ended ------')\n workflow_results: str = \\\n re.sub('^ ', '',\n table.draw().replace('\\n ', '\\n').replace('\\r ', '\\r'))\n print(workflow_results)\n print()\n\n\ndef _print_result(workflow_file: str, workflow_start: str,\n workflow_status: str, job_results: [w_run.JobRecord]):\n _print_job_results(job_results)\n _print_workflow_result(workflow_file, workflow_start, workflow_status)\n\n\ndef execute(dry_run: bool, workflow_file: str, inventory_file: str,\n auth_extra_vars: str, extra_vars: dict):\n \"\"\"\n Run sub command with switching 'dry_run' option.\n \"\"\"\n\n work_dir: str = _prepare_work_directory()\n\n workflow_node: w_parser.WorkflowNode = w_parser.parse(workflow_file,\n dry_run, extra_vars)\n workflow = w_run.WorkflowRunner(inventory_file)\n\n if dry_run:\n print()\n print('Check all variables are defined at running each job_template.')\n print('------')\n\n workflow.dry_run(workflow_node)\n\n print(\"Dry run complete.\")\n else:\n workflow_start: str = \\\n datetime.now(timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n\n job_result: [w_run.JobRecord] = workflow.run(workflow_node,\n auth_extra_vars,\n work_dir)\n\n workflow_status: str = job_result[-1].status\n _print_result(workflow_file, workflow_start, workflow_status,\n job_result)\n" }, { "alpha_fraction": 0.5534290075302124, "alphanum_fraction": 0.5799441933631897, "avg_line_length": 43, "blob_id": "f0144daee33baf0f3890c8ff14481f2865b06522", "content_id": "fed4c09a089470734825c57ce26c1b4c772febee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5016, "license_type": "no_license", "max_line_length": 181, "num_lines": 114, "path": "/README.md", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "# Ansible Tower(AWX) workflow runner\n\n## What is this.\nAnsible workflow runner on local command line. \nThis tool is to run workflow template without Ansible AWX server. \nAnd this can also check `extra_vars` dependency in each jobs in workflow by `dry_run` mode. \n\nPlease use this command as follows: \n```\n$ python3 workflow_runner.py `workflow file path` -i `inventory file path` (--ask-pass or --private-key `file path`) [-e '@extra-vars_file_path']\n```\n\nIf you want to check `extra_vars` dependency correctness, you can use `dry_run` mode. \n```\n$ python3 workflow_runner.py `workflow file path` -i `inventory file path` --dry_run [-e '@extra-vars_file_path']\n```\n\n**positional arguments:**\n```\nworkflow_file target workflow file path.\n```\n\n**optional arguments:**\n```\n-h, --help show this help message and exit\n-i INVENTORY_FILE, --inventory_file INVENTORY_FILE Target inventory file path.\n-u USER, --user USER Ansible's `ansible_ssh_user` option. Default is current user.\n--port PORT Ansible's `ansible_port` option. Default is `22`.\n--become-user BECOME_USER Ansible's `ansible_become_user` option. Default is `root`.\n-K, --ask-become-pass Ansible's `ansible_become_pass` option.\n-e EXTRA_VARS, --extra-vars EXTRA_VARS Ansible's extra_vars option. Default is `None`.\n-k, --ask-pass Password auth enable for ansible remote login.\n Please specify this or `--private-key`.\n--private-key PRIVATE_KEY Private key file path for ansible remote login.\n Please specify this or `--ask-pass`.\n--dry_run Run with `dry_run` mode.\n```\n\n## Setup\n```\n$ pip3 install requirements.txt\n$ pip3 install -e .\n```\nAnd if you use ssh login, you have to install sshpass by Ansible's dependency. \n\nDry run sample workflow.\n```\n# python cmd/workflow_runner.py resource_files/workflow/sample_workflow.yml -i resource_files/inventory/sample_inventory.txt -e \"@resource_files/extra_vars/extra-vars.yml\" --dry_run\n\nCheck all variables are defined at running each job_template.\n------\n- OK. Variables in playbook '/vagrant/data/workflow_runner/resource_files/job_template/sample_job_template/sample_job1.yml' are available at running.\n\n- OK. Variables in playbook '/vagrant/data/workflow_runner/resource_files/job_template/sample_job_template/sample_job2.yml' are available at running.\n\n- OK. Variables in playbook '/vagrant/data/workflow_runner/resource_files/job_template/sample_job_template/sample_job3.yml' are available at running.\n\nDry run complete.\n```\n\nRun sample workflow.\n```\n# python cmd/workflow_runner.py resource_files/workflow/sample_workflow.yml -i resource_files/inventory/sample_inventory.txt -e \"@resource_files/extra_vars/extra-vars.yml\" -k\nSSH password:\n......................\n\n------ Job results ------\n==== ============= ============== ============ ============================ ===========\n id name type status created elapsed\n==== ============= ============== ============ ============================ ===========\n 1 sample_job1 job_template successful 2019-06-02T08:49:43.738865 06.343523\n 2 sample_job2 job_template successful 2019-06-02T08:49:50.082515 01.832642\n 3 sample_job3 job_template successful 2019-06-02T08:49:51.915217 01.879878\n==== ============= ============== ============ ============================ ===========\n\n------ Workflow process ended ------\n======================= ============================ ============\n workflow_job_template created status\n======================= ============================ ============\n sample_workflow.yml 2019-06-02T08:49:43.738723 successful\n======================= ============================ ============\n```\n\n## Attention\n- job_template names in workflow YAML file have to be same as job_template YAML file name which without '.yml'.\n- YAML structure of workflow file have to be following Ansible AWX style:\n ```\n - job_template: sample_job1\n success:\n - job_template: sample_job2\n success:\n - job_template: sample_job4\n failure:\n - job_template: sample_job3\n ```\n \n You can not use other type style with `success_nodes`, `always_nodes`,`failure_nodes`,`inventory_source`,`project`. \n ```\n - failure_nodes:\n - inventory_source: 42\n job_template: 45\n success_nodes:\n - always_nodes:\n - job_template: 55\n success_nodes:\n - job_template: 44\n project: 40\n ```\n \n## Issue\n- all style workflow support.\n- not supported workflow in workflow yet.\n- not supported cover roles in job_template yet.\n- simultaneous multi job execution if parallel case wrote in workflow.\n" }, { "alpha_fraction": 0.5326101779937744, "alphanum_fraction": 0.534000813961029, "avg_line_length": 36.64921569824219, "blob_id": "104e90c6ca3168647b71bee74177c00d85ef38bd", "content_id": "3bb462f07667ea104f40677308c09c3d82e2cd7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7191, "license_type": "no_license", "max_line_length": 79, "num_lines": 191, "path": "/internal/workflow/parser.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nParse workflow structure.\n\"\"\"\n\nfrom datetime import datetime\nimport json\n\nimport yaml\n\nfrom internal.workflow import tree, node\nfrom internal.playbook import runner, parser\n\n\nclass DryRunFailed(Exception):\n \"\"\"\n Dry run failed by defined variables not enough.\n \"\"\"\n\n def __init__(self, message):\n super(DryRunFailed, self).__init__()\n self.message = message\n\n def __str__(self):\n return repr(self.message)\n\n\nclass WorkflowNode:\n \"\"\"\n workflow tree object.\n \"\"\"\n\n def __init__(self, top_node: node.Node):\n self.current_node: node.Node = top_node\n self.parent_node: node.Node = node.Node(0, 'None', '')\n\n def check_var_defined(self, var_name: str):\n \"\"\" Check target extra_vars already defined. \"\"\"\n\n return var_name in self.parent_node.before_extra_vars\n\n def go_next_child(self, next_node: node.Node):\n \"\"\" Move forward current job_template node. \"\"\"\n self.parent_node = self.current_node\n self.current_node = next_node\n\n def go_back(self, top_on_parent_node: node.Node):\n \"\"\" Move back current job_template node. \"\"\"\n self.current_node = self.parent_node\n self.parent_node = top_on_parent_node\n\n def _prepare_playbook(self, work_dir: str) -> (str, list):\n \"\"\" Generate copy playbook file with dump `set_stats` value. \"\"\"\n\n set_stats_file_list = []\n\n if self.current_node.define_stats:\n # Create copy playbook and replace playbook to use.\n\n node_id: str = str(self.current_node.node_id)\n p_time_stamp: str = datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n copy_playbook_path: str = \"{}/tmp_playbook_{}_{}.yml\".format(\n work_dir, node_id, p_time_stamp)\n\n with open(self.current_node.playbook_path, 'r') as pbf:\n playbook: dict = yaml.load(stream=pbf, Loader=yaml.SafeLoader)\n tasks = playbook[0]['tasks']\n\n skip_num: int = 1\n for idx, task in enumerate(tasks):\n if 'set_stats' in task:\n for v_name, v_val in task['set_stats']['data'].items():\n\n # Prepare tmp file path.\n time_stamp: str = \\\n datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n stats_var_path: str = \"{}/{}-{}-{}.txt\".format(\n work_dir, node_id, v_name, time_stamp)\n set_stats_file_list.append(stats_var_path)\n\n # Insert task to register after var tmp file.\n echo_com = \\\n \"echo {} >> {}\".format(v_val, stats_var_path)\n copy_task = {'name': 'Register after extra_vars '\n 'temporarily file',\n 'shell': echo_com}\n if 'item' in v_val:\n # This task has `with_items`.\n copy_task['with_items'] = task['with_items']\n if 'when' in task:\n copy_task['when'] = task['when']\n\n tasks = (tasks[:idx + skip_num] + [copy_task]\n + tasks[idx + skip_num:])\n skip_num += 1\n\n playbook[0]['tasks'] = tasks\n with open(copy_playbook_path, 'w') as tpf:\n tpf.write(yaml.dump(playbook))\n\n playbook_path = copy_playbook_path\n else:\n playbook_path = self.current_node.playbook_path\n\n return playbook_path, set_stats_file_list\n\n def _set_after_extra_vars(self, set_stats_files: [str]):\n after_extra_vars = {}\n after_extra_vars.update(self.current_node.before_extra_vars)\n\n if set_stats_files:\n for stats_file in set_stats_files:\n try:\n with open(stats_file, \"r\") as stf:\n stats_value: str = stf.read().rstrip('\\n').rstrip('\\r')\n stats_key: str = stats_file.split('-')[1]\n after_extra_vars.update({stats_key: stats_value})\n except FileNotFoundError:\n pass\n\n self.current_node.set_after_extra_vars(after_extra_vars)\n\n def run(self, inventory_file: str, auth_extra_vars: str,\n work_dir: str) -> int:\n \"\"\" Execute each playbook. \"\"\"\n\n playbook, set_stats_list = self._prepare_playbook(work_dir)\n\n if self.parent_node.node_id != 0:\n self.current_node.set_before_extra_vars(self.parent_node)\n\n extra_vars_json: str = json.dumps(self.current_node.before_extra_vars)\n\n r_code = runner.run_playbook(playbook, inventory_file,\n auth_extra_vars, extra_vars_json)\n\n self._set_after_extra_vars(set_stats_list)\n return r_code\n\n @staticmethod\n def _check_vars_covered(necessary: set, defined: set, playbook_path: str):\n if not necessary <= defined:\n undefined: set = necessary - defined\n message = \"Necessary variables not defined. \"\"\" \\\n \"playbook: '{}', variable: {}\".format(playbook_path,\n undefined)\n raise DryRunFailed(message)\n\n def dry_run(self):\n \"\"\" Exec dry run check each playbook. \"\"\"\n\n playbook_path: str = self.current_node.playbook_path\n result: tuple = parser.get_necessary_variable_keys(playbook_path)\n necessary_at_started: set = result[0]\n necessary_in_tasks: dict = result[1]\n\n defined_at_started: set = \\\n set(self.current_node.before_extra_vars.keys())\n set_fact_in_tasks: dict = self.current_node.define_fact\n defined_on_vars_header: set = self.current_node.define_vars_header\n\n # Check variables defined for playbook header.\n self._check_vars_covered(necessary_at_started, defined_at_started,\n playbook_path)\n\n # Check variables defined for playbook tasks.\n defined: set = defined_at_started | defined_on_vars_header\n for task_idx, necessary_key in necessary_in_tasks.items():\n if set_fact_in_tasks:\n defined = defined | set_fact_in_tasks[task_idx]\n\n self._check_vars_covered(necessary_key, defined, playbook_path)\n\n print(\"- OK. Variables in playbook '{}' are available at running.\"\n .format(playbook_path))\n print()\n\n\ndef parse(workflow_file_path: str, dry_run: bool,\n extra_vars_arg: dict) -> WorkflowNode:\n \"\"\"\n parse workflow file and return tree object.\n \"\"\"\n\n with open(workflow_file_path, \"r\") as wfp:\n workflow_dict = yaml.load(stream=wfp, Loader=yaml.SafeLoader)\n\n top_node: node.Node = tree.generate_workflow_tree(workflow_dict, dry_run,\n extra_vars_arg)\n workflow = WorkflowNode(top_node)\n return workflow\n" }, { "alpha_fraction": 0.5582442283630371, "alphanum_fraction": 0.5599324703216553, "avg_line_length": 28.86554527282715, "blob_id": "74c20cbff2b5aebd7f851e120b7320811e9cc7d2", "content_id": "e27c72f1d25591dd717eb5bc05a77965c540c184", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3554, "license_type": "no_license", "max_line_length": 77, "num_lines": 119, "path": "/internal/playbook/parser.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nParse playbook structure and extract local variables.\n\"\"\"\n\nimport yaml\n\nANSIBLE_RESERVED_WORDS = {'inventory_dir', 'inventory_hostname'}\n\n\ndef get_defined_variable_keys(playbook_path: str) -> dict:\n \"\"\" Extract local defined variables in target playbook. \"\"\"\n\n set_stats = []\n set_fact = {}\n\n with open(playbook_path, 'r') as pbf:\n playbook: dict = yaml.load(stream=pbf, Loader=yaml.SafeLoader)[0]\n\n if 'vars' in playbook:\n defined_on_vars_header: set = set(playbook['vars'].keys())\n else:\n defined_on_vars_header = set()\n\n tasks: list = playbook['tasks']\n for idx, task in enumerate(tasks):\n if 'set_stats' in task:\n for stats_name in task['set_stats']['data'].keys():\n set_stats.append(stats_name)\n\n defined_fact = set()\n if 'set_fact' in task:\n for fact_name in task['set_fact'].keys():\n defined_fact.add(fact_name)\n\n set_fact[idx]: set = defined_fact\n\n return {'set_stats': set_stats, 'set_fact': set_fact,\n 'vars': defined_on_vars_header}\n\n\ndef _is_variable(value) -> bool:\n \"\"\" argument is `str` type or `bool` type. \"\"\"\n value_str: str = str(value)\n\n vars_exists = False\n for sp_word in value_str.split('{{ '):\n inner_word: str = sp_word.split(' }}')[0]\n if ' }}' in sp_word and '.' not in inner_word:\n if inner_word in ANSIBLE_RESERVED_WORDS:\n continue\n\n vars_exists = True\n\n return vars_exists\n\n\ndef _get_variable_name(value) -> set:\n value_str: str = str(value)\n\n necessary = set()\n for sp_word in value_str.split('{{ '):\n inner_word: str = sp_word.split(' }}')[0]\n\n if ' }}' in sp_word and '.' not in inner_word:\n if '[' in inner_word:\n inner_word = inner_word.split('[')[0]\n\n if \"% set {}\".format(inner_word) in value:\n continue\n\n if inner_word in ANSIBLE_RESERVED_WORDS:\n continue\n\n necessary.add(inner_word)\n\n return necessary\n\n\ndef _parse_task_dick(task_dict: dict, necessary: set) -> set:\n for val in task_dict.values():\n if isinstance(val, dict):\n necessary = necessary | _parse_task_dick(val, necessary)\n elif isinstance(val, str):\n if _is_variable(val):\n necessary = necessary | _get_variable_name(val)\n else:\n pass\n\n return necessary\n\n\ndef get_necessary_variable_keys(playbook_path: str) -> tuple:\n \"\"\"\n Search and collect necessary variable keys in playbook.\n \"\"\"\n\n with open(playbook_path, 'r') as pbp:\n playbook: dict = yaml.load(stream=pbp, Loader=yaml.SafeLoader)\n\n necessary_keys_at_started = set()\n necessary_keys_in_tasks = {}\n playbook_dict: dict = playbook[0]\n for key, sub_dict in playbook_dict.items():\n if key in ('vars', 'environment'):\n for value in sub_dict.values():\n if _is_variable(value):\n necessary_keys_at_started = \\\n necessary_keys_at_started | _get_variable_name(value)\n\n if 'tasks' in key:\n # `tasks` is list of task dictionary.\n\n for idx, task_dict in enumerate(sub_dict):\n necessary_in_task = set()\n necessary_keys_in_tasks[idx] = \\\n _parse_task_dick(task_dict, necessary_in_task)\n\n return necessary_keys_at_started, necessary_keys_in_tasks\n" }, { "alpha_fraction": 0.5726714134216309, "alphanum_fraction": 0.5736950039863586, "avg_line_length": 27.31884002685547, "blob_id": "6bc9528cdd094b00f25b931bc955e1bc7074282a", "content_id": "abae29bbd11de08479e7235ec3d889a5fa129204", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1954, "license_type": "no_license", "max_line_length": 78, "num_lines": 69, "path": "/internal/auth_info.py", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nAnsible auth env variables for remote login.\n\"\"\"\n\nimport getpass\nimport json\nimport os\nimport sys\n\n\nclass AuthInfo:\n \"\"\"\n Data class for Ansible auth env variables.\n \"\"\"\n\n def __init__(self, ask_pass: bool, private_key: str, user: str, port: int,\n become_user: str, ask_become_pass: bool):\n self._check_private_key(private_key)\n\n self._ask_pass: bool = ask_pass\n self._private_key: str = private_key\n self._user: str = user\n self._port: int = port\n self._become_user: str = become_user\n self._ask_become_pass: bool = ask_become_pass\n\n @staticmethod\n def _check_private_key(private_key: str):\n if private_key and not os.path.isfile(private_key):\n print()\n print('<< Invalid argument. >>')\n print('Specified private key not found.')\n sys.exit(2)\n\n def generate_auth_extra_vars(self) -> str:\n \"\"\"\n Generate Ansible extra_vars json for remote login auth.\n \"\"\"\n\n auth_extra_vars = {}\n\n # necessary auth vars\n if self._ask_pass:\n ask_pass: str = getpass.getpass('SSH password: ')\n\n auth_extra_vars['ansible_ssh_pass']: str = ask_pass\n else:\n auth_extra_vars['ansible_ssh_private_key_file']: str = \\\n self._private_key\n\n # other options\n if self._user:\n auth_extra_vars['ansible_ssh_user']: str = self._user\n\n if self._port:\n auth_extra_vars['ansible_port']: str = self._port\n\n if self._become_user:\n auth_extra_vars['ansible_become_user']: str = self._become_user\n\n if self._ask_become_pass:\n become_pass: str = getpass.getpass('SUDO password: ')\n\n auth_extra_vars['ansible_become_user']: str = become_pass\n\n auth_extra_vars_json: str = json.dumps(auth_extra_vars)\n\n return auth_extra_vars_json\n" }, { "alpha_fraction": 0.640949547290802, "alphanum_fraction": 0.6483679413795471, "avg_line_length": 18.823530197143555, "blob_id": "61ac4dc4c641cb03b1702b653bf05e531b3d3bae", "content_id": "48846d8890111adaa07cbd0e53a67ac8d0b9875d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 674, "license_type": "no_license", "max_line_length": 69, "num_lines": 34, "path": "/install.sh", "repo_name": "YasuhiroOsajima/workflow_runner", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Use like this:\n#\n# $ git clone https://github.com/YasuhiroOsajima/workflow_runner.git\n# $ cd workflow_runner\n# $ python3 -m vevn venv\n# $ source venv/bin/activate\n# $ pip install -r requirements.txt\n# $ bash install.sh\n\n\nPYTHON_PATH=`which python`\nRUNNER_PATH=`pwd`/cmd/workflow_runner.py\nLOCAL_BIN=\"${HOME}/.local/bin\"\n\nLOCAL_BIN_WC=`echo ${PATH} | grep ${LOCAL_BIN} | wc -l`\nif [ ${LOCAL_BIN_WC} = 1 ]; then\n BIN_PATH=${LOCAL_BIN}\nelse\n BIN_PATH='/usr/local/bin/'\nfi\n\nRUNNER_FILE=\"${BIN_PATH}/workflow_runner\"\n\n\n# create runner file\ncat <<__EOT__ > ${RUNNER_FILE}\n#!/bin/bash\n\n${PYTHON_PATH} ${RUNNER_PATH} \\$@\n__EOT__\n\nchmod 755 ${RUNNER_FILE}\n" } ]
14
gobgob/MouseToLyre
https://github.com/gobgob/MouseToLyre
d988fde106bfa35b162b0ed5d5b1b81882880e7c
44246c8b54a41873ebc8309129f7e6a30e41c81d
b048cae49e59d03b85a3abc841e295ca01af2b7f
refs/heads/master
2021-01-01T17:56:25.136048
2013-11-07T16:02:13
2013-11-07T16:02:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6174127459526062, "alphanum_fraction": 0.6399848461151123, "avg_line_length": 30.75301170349121, "blob_id": "3b23768e4f984889a13e4baa5193b7b0625e619e", "content_id": "bed38512883ebd6859af0c2a501fc6e3af59923f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5272, "license_type": "no_license", "max_line_length": 87, "num_lines": 166, "path": "/soft-pc/lyre.py", "repo_name": "gobgob/MouseToLyre", "src_encoding": "UTF-8", "text": " #! /usr/bin/env python\n \nimport pygame\nimport pygame.mixer\nimport serial\nimport os\nimport sys\nfrom time import *\nimport ConfigParser\n\nfrom LyreDevice import LyreDevice\n\n\nPROGRAMM_PATH=os.path.dirname(os.path.realpath(__file__))\nCONFIG_PATH=PROGRAMM_PATH+\"/config.ini\"\n\nrunning = 1\n\nlyre = LyreDevice(CONFIG_PATH)\nlyre.GoboSwitch(5)\n\npygame.font.init()\npygame.init()\npygame.mixer.init\n\nif (len(sys.argv)>1):\n SCREEN_WIDTH=480\n SCREEN_HEIGHT=234\n screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT),pygame.FULLSCREEN)\nelse:\n SCREEN_WIDTH=1280\n SCREEN_HEIGHT=1024\n screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n\nsound = pygame.mixer.Sound(PROGRAMM_PATH+\"/criticalstop_short.wav\")\nfont = pygame.font.Font(None,30)\npygame.mouse.set_visible(False)\n\nsound.play()\n\ndef redraw():\n global lyre\n bgcolor = 0, 0, 0\n linecolor = 255, 255, 255\n screen.fill(bgcolor)\n scr_y=(lyre.pan*SCREEN_WIDTH)/lyre.MAX_PAN\n scr_x=(lyre.tilt*SCREEN_HEIGHT)/lyre.MAX_TILT\n pygame.draw.line(screen, linecolor, (scr_x, 0), (scr_x, SCREEN_HEIGHT))\n pygame.draw.line(screen, linecolor, (0, scr_y), (SCREEN_WIDTH, scr_y))\n text=font.render(\"pan =\"+str(lyre.pan)+\" tilt =\"+str(lyre.tilt), 1,(255,255,255))\n screen.blit(text, (0, 100))\n text=font.render(\" x =\"+str(scr_x)+\" y =\"+str(scr_y), 1,(255,255,255))\n screen.blit(text, (0, 0))\n pygame.display.flip()\n\ndef move(x,y):\n global lyre\n lyre.IncrementTilt(-x*lyre.TILT_RATIO)\n lyre.IncrementPan(-y*lyre.PAN_RATIO)\n\ndef click():\n sound.play()\n if (lyre.DETECT_CLICK):\n lyre.GoboSwitch(6)\n lyre.GoboRotate(40)\n sleep(2)\n lyre.GoboRotate(0)\n lyre.GoboSwitch(5)\n\nclass menus:\n MENU_NORMAL=\"MENU_NORMAL\"\n MENU_LUMINOSITY=\"MENU_LUMINOSITY\"\n MENU_MAX_PAN=\"MENU_MAX_PAN\"\n MENU_MIN_PAN=\"MENU_MIN_PAN\"\n MENU_MAX_TILT=\"MENU_MAX_TILT\"\n MENU_MIN_TILT=\"MENU_MIN_TILT\"\n MENU_PAN_RATIO=\"MENU_PAN_RATIO\"\n MENU_TILT_RATIO=\"MENU_TILT_RATIO\"\n MENU_FOCUS=\"MENU_FOCUS\"\n DETECT_CLICK=\"DETECT_CLICK\"\n\ncurrentMenu = menus.MENU_NORMAL\n\ndef menu(key):\n global currentMenu, lyre\n if(key==pygame.K_KP0) : currentMenu = menus.MENU_NORMAL\n if(key==pygame.K_KP1) : currentMenu = menus.MENU_LUMINOSITY\n if(key==pygame.K_KP2) : currentMenu = menus.MENU_MAX_PAN\n if(key==pygame.K_KP3) : currentMenu = menus.MENU_MIN_PAN\n if(key==pygame.K_KP4) : currentMenu = menus.MENU_MAX_TILT\n if(key==pygame.K_KP5) : currentMenu = menus.MENU_MIN_TILT\n if(key==pygame.K_KP6) : currentMenu = menus.MENU_PAN_RATIO\n if(key==pygame.K_KP7) : currentMenu = menus.MENU_TILT_RATIO\n if(key==pygame.K_KP8) : currentMenu = menus.MENU_FOCUS\n if(key==pygame.K_KP9) : currentMenu = menus.DETECT_CLICK\n print currentMenu\n\n if(currentMenu==menus.MENU_LUMINOSITY):\n if(key==pygame.K_KP_PLUS) : lyre.IncrementIntensity(10)\n if(key==pygame.K_KP_MINUS) : lyre.IncrementIntensity(-10)\n\n if(currentMenu==menus.MENU_MAX_PAN):\n if(key==pygame.K_KP_PLUS) : lyre.IncrementMaxPan(100)\n if(key==pygame.K_KP_MINUS) : lyre.IncrementMaxPan(-100)\n lyre.SetPan(lyre.MAX_PAN)\n\n if(currentMenu==menus.MENU_MIN_PAN):\n if(key==pygame.K_KP_PLUS) : lyre.IncrementMinPan(100)\n if(key==pygame.K_KP_MINUS) : lyre.IncrementMinPan(-100)\n lyre.SetPan(lyre.MIN_PAN)\n\n if(currentMenu==menus.MENU_MAX_TILT):\n if(key==pygame.K_KP_PLUS) : lyre.IncrementMaxTilt(100)\n if(key==pygame.K_KP_MINUS) : lyre.IncrementMaxTilt(-100)\n lyre.SetTilt(lyre.MAX_TILT)\n\n if(currentMenu==menus.MENU_MIN_TILT):\n if(key==pygame.K_KP_PLUS) : lyre.IncrementMinTilt(100)\n if(key==pygame.K_KP_MINUS) : lyre.IncrementMinTilt(-100)\n lyre.SetTilt(lyre.MIN_TILT)\n\n if(currentMenu==menus.MENU_PAN_RATIO):\n if(key==pygame.K_KP_PLUS) : lyre.PAN_RATIO+=1\n if(key==pygame.K_KP_MINUS) : lyre.PAN_RATIO-=1\n\n if(currentMenu==menus.MENU_TILT_RATIO):\n if(key==pygame.K_KP_PLUS) : lyre.TILT_RATIO+=1\n if(key==pygame.K_KP_MINUS) : lyre.TILT_RATIO-=1\n\n if(currentMenu==menus.MENU_FOCUS):\n if(key==pygame.K_KP_PLUS) : lyre.IncrementFocus(1)\n if(key==pygame.K_KP_MINUS) : lyre.IncrementFocus(-1)\n\n if(currentMenu==menus.DETECT_CLICK):\n if(key==pygame.K_KP_PLUS) : lyre.DETECT_CLICK=True\n if(key==pygame.K_KP_MINUS) : lyre.DETECT_CLICK=False\n\n lyre.SaveConfig()\n\nwhile running:\n while True:\n event = pygame.event.poll()\n if (not event):\n break\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n running = False\n else:\n menu(event.key)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if (event.button==1):\n click()\n\n if (currentMenu in [menus.MENU_NORMAL,menus.MENU_TILT_RATIO,menus.MENU_PAN_RATIO]):\n x, y = pygame.mouse.get_rel()\n\n # in thoses menues we limit the movement to 1 axe at the time\n if(currentMenu==menus.MENU_TILT_RATIO):y=0\n if(currentMenu==menus.MENU_PAN_RATIO):x=0\n\n if (x!=0 or y!=0):\n move(x,y)\n sleep(0.025)\n redraw()\n" }, { "alpha_fraction": 0.7241379022598267, "alphanum_fraction": 0.7241379022598267, "avg_line_length": 16.600000381469727, "blob_id": "3c83aa7bec285547e1da0758c9ed940b79e652d2", "content_id": "10dc586958abadee9e8241fca934896051d6c631", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 87, "license_type": "no_license", "max_line_length": 59, "num_lines": 5, "path": "/soft-pc/lauch.sh", "repo_name": "gobgob/MouseToLyre", "src_encoding": "UTF-8", "text": "#!/bin/bash\nwhile :\ndo\n\t/usr/bin/python ~/MouseToLyre/soft-pc/lyre.py --fullscreen\ndone" }, { "alpha_fraction": 0.4765625, "alphanum_fraction": 0.671875, "avg_line_length": 13.11111068725586, "blob_id": "7426baecaf23fb81feb8ebfeb96618f756c59a3b", "content_id": "4216635cee99334fa408f3425d7b021796f2d761", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 128, "license_type": "no_license", "max_line_length": 16, "num_lines": 9, "path": "/soft-pc/config.ini", "repo_name": "gobgob/MouseToLyre", "src_encoding": "UTF-8", "text": "[LYRE]\nmax_tilt = 22900\nmax_pan = 32400\nmin_tilt = 0\nmin_pan = 6100\nintensity = 255\nfocus = 100\npan_ratio = 21\ntilt_ratio = 20\n\n" }, { "alpha_fraction": 0.556463897228241, "alphanum_fraction": 0.5800380110740662, "avg_line_length": 29.21839141845703, "blob_id": "52d94f2e529a4139dba74abe12de3a7a499d7f96", "content_id": "5b80c4a7429d2bf2de3b8c515b2407c7b08dec36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5260, "license_type": "no_license", "max_line_length": 78, "num_lines": 174, "path": "/soft-pc/LyreDevice.py", "repo_name": "gobgob/MouseToLyre", "src_encoding": "UTF-8", "text": "\nimport serial\nfrom serial.tools import list_ports\nfrom time import *\nimport ConfigParser\n\nclass LyreDevice:\n\n ser = None\n config = None\n configPath = \"\"\n\n#working values\n pan=0\n tilt=0\n\n# setup values\n MAX_TILT=32000\n MAX_PAN=32000\n MIN_TILT=0\n MIN_PAN=0\n\n INTENSITY=255\n FOCUS=100\n\n #mouse related, nothing to do there but easier\n PAN_RATIO=20\n TILT_RATIO=20\n DETECT_CLICK=True\n\n DMX_TILT_1 = 1\n DMX_TILT_2 = 13\n DMX_PAN_1 = 2\n DMX_PAN_2 = 14\n DMX_INTENSITY = 11\n DMX_ROTATING_GOBO_WHEEL = 5\n DMX_ROTATING_GOBO_ROT = 6\n DMX_FOCUS = 8\n\n\n#static values\n GOBOS_INDEX=[0,19,38,57,76,95,114,128,192]\n\n def __init__(self,configPath):\n self.configPath=configPath\n self.LoadConfig()\n\n def LoadConfig(self):\n self.config = ConfigParser.ConfigParser()\n self.config.read(self.configPath)\n try:\n self.MAX_TILT=int(self.config.get('LYRE', \"MAX_TILT\"))\n self.MAX_PAN=int(self.config.get('LYRE', \"MAX_PAN\"))\n self.MIN_TILT=int(self.config.get('LYRE', \"MIN_TILT\"))\n self.MIN_PAN=int(self.config.get('LYRE', \"MIN_PAN\"))\n self.INTENSITY=int(self.config.get('LYRE', \"INTENSITY\"))\n self.FOCUS=int(self.config.get('LYRE', \"FOCUS\"))\n self.PAN_RATIO=int(self.config.get('LYRE', \"PAN_RATIO\"))\n self.TILT_RATIO=int(self.config.get('LYRE', \"TILT_RATIO\"))\n self.DETECT_CLICK=(self.config.get('LYRE',\"DETECT_CLICK\")==\"True\")\n self.SetIntensity(self.INTENSITY)\n self.SetFocus(self.FOCUS)\n except Exception, e:\n self.SaveConfig()\n self.LoadConfig()\n\n\n def SaveConfig(self):\n cfgfile = open(self.configPath,'w')\n if (not self.config.has_section(\"LYRE\")):\n self.config.add_section(\"LYRE\")\n self.config.set('LYRE', \"MAX_TILT\", self.MAX_TILT)\n self.config.set('LYRE', \"MAX_PAN\", self.MAX_PAN)\n self.config.set('LYRE', \"MIN_TILT\", self.MIN_TILT)\n self.config.set('LYRE', \"MIN_PAN\", self.MIN_PAN)\n self.config.set('LYRE', \"INTENSITY\", self.INTENSITY)\n self.config.set('LYRE', \"FOCUS\", self.FOCUS)\n self.config.set('LYRE', \"PAN_RATIO\", self.PAN_RATIO)\n self.config.set('LYRE', \"TILT_RATIO\", self.TILT_RATIO)\n self.config.set('LYRE', \"DETECT_CLICK\", self.DETECT_CLICK)\n self.config.write(cfgfile)\n cfgfile.close()\n\n def Open(self):\n ports = [port[0] for port in list_ports.comports()]\n while True:\n for port in ports:\n print \"Trying port:\" + port\n try:\n self.ser = serial.Serial(port, 9600, timeout=0.5)\n except Exception, e:\n print \"nope !\"\n else:\n sleep(2)\n self.ser.write('?')\n if (self.ser.read(12) == \"I am the One\"):\n print \"Lyre found on \"+port\n return port\n else:\n self.ser.close()\n sleep(0.5)\n\n def Send(self,channel,value):\n if (not self.ser):\n self.Open()\n self.ser.write(str(channel)+\"c\"+str(int(value))+\"w\")\n self.ser.flushInput()\n\n ### MOVEMENT ###\n\n def SetTilt(self,value):\n self.tilt=min(max(value,self.MIN_TILT),self.MAX_TILT)\n tilt_highbits = (int(self.tilt)&0xff00)>>8\n tilt_lowbits = (int(self.tilt)&0x00ff)\n self.Send(self.DMX_TILT_1,tilt_highbits)\n self.Send(self.DMX_TILT_2,tilt_lowbits)\n\n def IncrementTilt(self,value):\n self.SetTilt(self.tilt+value)\n \n def SetPan(self,value):\n self.pan=min(max(value,self.MIN_PAN),self.MAX_PAN)\n pan_highbits = (int(self.pan)&0xff00)>>8\n pan_lowbits = (int(self.pan)&0x00ff)\n self.Send(self.DMX_PAN_1,pan_highbits)\n self.Send(self.DMX_PAN_2,pan_lowbits)\n\n def IncrementPan(self,value):\n self.SetPan(self.pan+value)\n\n ### GOBOS ###\n\n def GoboSwitch(self,index):\n self.Send(self.DMX_ROTATING_GOBO_WHEEL,self.GOBOS_INDEX[index])\n\n def GoboRotate(self,speed):\n self.Send(self.DMX_ROTATING_GOBO_ROT,118-speed)\n\n ### SETUP ###\n\n def SetIntensity(self,value):\n self.INTENSITY=min(max(value,0),255)\n self.Send(self.DMX_INTENSITY,self.INTENSITY)\n print \"INTENSITY=\"+str(self.INTENSITY)\n\n def IncrementIntensity(self,value):\n self.SetIntensity(self.INTENSITY+value)\n\n def IncrementMaxPan(self,value):\n self.MAX_PAN=min(max(self.MAX_PAN+value,0),65535)\n\n def IncrementMaxTilt(self,value):\n self.MAX_TILT=min(max(self.MAX_TILT+value,0),65535)\n\n def IncrementMinPan(self,value):\n self.MIN_PAN=min(max(self.MIN_PAN+value,0),65535)\n\n def IncrementMinTilt(self,value):\n self.MIN_TILT=min(max(self.MIN_TILT+value,0),65535)\n\n def SetFocus(self,value):\n self.FOCUS=min(max(value,0),255)\n self.Send(self.DMX_FOCUS,self.FOCUS)\n print \"FOCUS=\"+str(self.FOCUS)\n\n def IncrementFocus(self,value):\n self.SetFocus(self.FOCUS+value)\n\n ###TODO ###\n \n def ColorSwitch(self,index):\n pass\n\n def Reset(self,value):\n pass\n\n" } ]
4
lishuo02/python_sale
https://github.com/lishuo02/python_sale
bcd8f8ec8ede11c53e1ae8723d4010cee0d6f088
a11f3a4a3a9bbb899f6c61082b14aee2db5aa476
39270ebae390176573db9fb2343c82271a707c7f
refs/heads/master
2020-05-09T12:24:26.448017
2019-04-13T03:02:22
2019-04-13T03:02:22
181,111,473
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5318725109100342, "alphanum_fraction": 0.5786852836608887, "avg_line_length": 22.16867446899414, "blob_id": "7998e7a6d972303bf05e15ded1634657d95ef7ed", "content_id": "57994ec1af1870102a8d816aaf3c41eff44f9196", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2114, "license_type": "no_license", "max_line_length": 114, "num_lines": 83, "path": "/LI.py", "repo_name": "lishuo02/python_sale", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\r\n# -*- coding: UTF-8 -*-\r\n\r\nimport pymysql as MySQLdb\r\nimport pandas as pd\r\n\r\nimport matplotlib.pyplot as plt\r\nimport datetime\r\n\r\nhost = \r\nuser = \r\npasswd = \r\nport = 3306\r\ndb = \"trade_stats\"\r\n\r\n\r\ndef connect_sql():\r\n conn = MySQLdb.connect(host=host,port=port,user=user,passwd=passwd,db=db, charset='utf8')\r\n cur = conn.cursor()\r\n return conn,cur\r\n\r\ndef close_connect(conn,cur):\r\n conn.commit()\r\n cur.close()\r\n conn.close()\r\n\r\ndef select_sql(cur,sql):\r\n try:\r\n cur.execute(sql)\r\n alldata = cur.fetchall()\r\n frame = pd.DataFrame(list(alldata))\r\n except:\r\n frame = pd.DataFrame()\r\n return frame\r\n\r\n#将日期转换为星期\r\ndef data_to_week(arrLike):\r\n create_time = arrLike[\"count_day\"]\r\n create_time = str(create_time)\r\n create_time = pd.to_datetime(create_time)\r\n # #获取第几周\r\n # week = str(create_time.strftime(\"%W\"))\r\n #获取周几\r\n week_day = str(create_time.strftime(\"%w\"))\r\n return week_day\r\n\r\n\r\nif __name__ == \"__main__\":\r\n #打开连接\r\n conn,cur = connect_sql()\r\n result = pd.DataFrame()\r\n months = [\"201801\", \"201802\", \"201803\", \"201804\", \"201805\", \"201806\", \"201807\", \"201808\", \"201809\", \"2018010\",\r\n \"201811\", \"201812\"]\r\n for month in months:\r\n sql = \"SELECT goods_name,sale_amount,count_day FROM `svm_goods_stats_\" + month + \"` where svm_id=23833;\"\r\n # print(sql)\r\n result1 = select_sql(cur,sql)\r\n # print(result1)\r\n result = result.append(result1)\r\n\r\n #关闭连接\r\n close_connect(conn,cur)\r\n\r\n #修改列名\r\n result.columns = [\"goods_name\",\"sale_amount\",\"count_day\"]\r\n\r\n # 添加周几\r\n result[\"week_day\"] = result.apply(data_to_week, axis=1)\r\n\r\n print(result)\r\n #雀巢罐装(180ml/罐)\r\n quechao=result[result[\"goods_name\"].isin([\"卫龙大面筋(106g袋)\"])]\r\n print(quechao)\r\n\r\n week = quechao[\"week_day\"]\r\n sale = quechao[\"sale_amount\"]\r\n plt.bar(week,sale)\r\n\r\n plt.title(\"雀巢每周销量散点图\")\r\n plt.xlabel(\"week\")\r\n plt.ylabel(\"sale\")\r\n\r\n # plt.show()\r\n\r\n" }, { "alpha_fraction": 0.7543859481811523, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 20.375, "blob_id": "f0ffec56febd7a3a3e35c1c5812fe72ce05afc79", "content_id": "6f105f0e8d6b2161ca857ed268773a4b37ea5b99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 425, "license_type": "no_license", "max_line_length": 40, "num_lines": 8, "path": "/README.md", "repo_name": "lishuo02/python_sale", "src_encoding": "UTF-8", "text": "# python_sale\n**单品周期销售数据散点图**\n***\n为了反应商品销售规律,按照一周为周期,反应每周的销售情况,获得单品每周销售规律。\n- 1.配置线上数据库链接地址\n- 2.设置链接开始和关闭方法,查询完成后方便关闭链接\n- 3.将日期格式转换为星期,每周作为一个周期\n- 4.主函数输入参数,商品名称,绘制以周为周期散点图\n" } ]
2
FThompson/DominionRandomizer
https://github.com/FThompson/DominionRandomizer
af3bb71a066495dbb68dc986090dbf9c8fd7aaf5
176c3550a6b097a432288e64bd849dc7e18dd08c
2bdc1ca51313a0f35c11ea45eb6f3cceed3a1ac1
refs/heads/master
2022-12-09T03:04:13.583942
2018-12-30T09:56:46
2018-12-30T09:56:46
159,743,833
0
0
null
2018-11-30T00:07:22
2018-12-30T09:57:00
2021-06-01T22:59:42
Python
[ { "alpha_fraction": 0.5993217825889587, "alphanum_fraction": 0.6014086604118347, "avg_line_length": 39.24671936035156, "blob_id": "9df870f146cc7aad72d147fabce8200c9fb8a2d4", "content_id": "b33a718b75eabc80d5e24a20f10ac0eaf097a36c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15334, "license_type": "no_license", "max_line_length": 117, "num_lines": 381, "path": "/randomizer.py", "repo_name": "FThompson/DominionRandomizer", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module contains Randomizer, used to generate random Dominion kingdoms with various randomization options.\n\n\"\"\"\n\nimport json\nimport random\nfrom collections import defaultdict\nfrom dtypes import Card, GameSet, SpecialTypeCard, SplitPileCard\n\n\nclass Randomizer():\n \"\"\"\n Randomizes Dominion cards from given sets and provides customization options including the number of cards, set\n weights or counts, included and excluded cards, filtered card types, and drawing events or landmarks.\n \n \"\"\"\n\n def __init__(self, data_path, sets, number=10, weights=[], counts=[], include=[], exclude=[], filter_types=[],\n n_events=0, n_landmarks=0):\n \"\"\"\n Creates a randomizer with given arguments.\n \n :param data_path: The cards.json file path.\n :type data_path: str\n :param sets: The names of the sets to randomize, optionally in argument form (i.e. base2e).\n :type sets: List[str]\n :param number: The total number of cards to pick, defaults to 10.\n :type number: int, optional\n :param weights: The weights to be applied to each set when randomly picking cards, defaults to an empty list.\n :type weights: List[int], optional\n :param counts: The counts of cards to pick from each set, defaults to an empty list.\n :type counts: List[int], optional\n :param include: The cards to include, optionally in argument form, defaults to an empty list.\n :type include: List[str], optional\n :param exclude: The cards to exclude, optionally in argument form, defaults to an empty list.\n :type exclude: List[str], optional\n :param filter_types: The card types to filter out before randomly picking cards, defaults to an empty list.\n :type filter_types: List[str], optional\n :param n_events: The number of events to pick, defaults to 0.\n :type n_events: int, optional\n :param n_landmarks: The number of landmarks to pick, defaults to 0.\n :type n_landmarks: int, optional\n \"\"\"\n\n self.data_path = data_path\n self.sets = GameSet.complete_sets() if 'all' in sets else [GameSet.for_arg(set_arg) for set_arg in sets]\n self.number = int(number)\n self.weights = weights\n self.counts = counts\n self.include = include\n self.exclude = exclude\n self.filter_types = [t.lower() for t in filter_types]\n self.n_events = int(n_events)\n self.n_landmarks = int(n_landmarks)\n self.count = self.number - len(self.include)\n self.mode = 'weighted' if self.weights else 'counted' if self.counts else 'normal'\n self.cards = {}\n self.possible_cards = {}\n self.included_cards = []\n self.events = []\n self.landmarks = []\n self.possible_events = []\n self.possible_landmarks = []\n self.load_cards()\n self.validate_configuration()\n if self.counts:\n self.adjust_counts()\n\n def print_cards(self):\n \"\"\"\n Prints the randomizeds cards, listed by set name.\n \n \"\"\"\n\n cards = defaultdict(list)\n for game_set, set_cards in self.cards.items():\n cards[game_set.set_name].extend(set_cards)\n for game_set in sorted(cards.keys()):\n print(game_set)\n cards[game_set].sort(key=lambda c: c.name)\n for card in cards[game_set]:\n print('- %s (%s), %s' % (card.name, ', '.join(card.types), card.cost))\n self.print_non_cards(self.events, 'Events', True)\n self.print_non_cards(self.landmarks, 'Landmarks', False)\n\n def print_non_cards(self, card_list, label, print_cost):\n \"\"\"\n Prints the given list of non-card cards (i.e. Events, Landmarks) with the given label.\n \n :param card_list: The cards to print.\n :type card_list: List[Card]\n :param label: The header to print the cards under.\n :type label: str\n :param print_cost: True to print the card cost, otherwise False\n :type print_cost: bool\n \"\"\"\n\n if len(card_list) > 0:\n print(label)\n for card in card_list:\n if print_cost:\n print('- %s, %s, %s' % (card.name, card.game_set, card.cost))\n else:\n print('- %s, %s' % (card.name, card.game_set))\n\n def randomize(self):\n \"\"\"\n Picks random cards based on the randomizer's parameters.\n \n \"\"\"\n\n\n if self.mode == 'counted':\n counts = {self.sets[i]: self.counts[i] for i in range(len(self.sets))}\n else:\n if self.mode == 'normal':\n # weight set picks based on how many cards in each set\n weights = [len(set_cards) for game_set, set_cards in self.possible_cards.items()]\n set_picks = random.choices(self.sets, weights=weights, k=self.count)\n elif self.mode == 'weighted':\n set_picks = random.choices(self.sets, weights=self.weights, k=self.count)\n counts = defaultdict(int)\n for set_pick in set_picks:\n counts[set_pick] += 1\n cards = {game_set: self.randomize_set(game_set, count) for game_set, count in counts.items()}\n self.cards = defaultdict(list, cards)\n for card in self.included_cards:\n self.cards[card.game_set].append(card)\n self.events = random.sample(self.possible_events, self.n_events)\n self.landmarks = random.sample(self.possible_landmarks, self.n_landmarks)\n\n def randomize_set(self, game_set, count):\n \"\"\"\n Picks the given count of cards from the given game set.\n \n :param game_set: The game set to pick cards from in the possible card list.\n :type game_set: GameSet\n :param count: The count of cards to pick.\n :type count: int\n :return: The list of random cards picked from the set.\n :rtype: List[Card]\n \"\"\" \n\n return random.sample(self.possible_cards[game_set], k=count)\n\n def load_cards(self):\n \"\"\"\n Loads cards from the data path and populates possible card lists.\n \n \"\"\"\n\n with open(self.data_path) as f:\n data = json.load(f)\n self.all_cards = [Card.from_json(**d) for d in data]\n for game_set in self.sets:\n # less efficient than building by card.game_set but done to handle editioned sets\n self.possible_cards[game_set] = [c for c in self.all_cards\n if game_set.contains(c) and self.is_possible_card(c)]\n self.add_special_type_cards()\n self.remove_split_pile_cards()\n self.possible_events = self.get_non_cards('Event', self.n_events)\n self.possible_landmarks = self.get_non_cards('Landmark', self.n_landmarks)\n self.add_inclusions()\n self.add_exclusions()\n\n def get_non_cards(self, category, count):\n \"\"\"\n Gets all possible cards of the given category, throwing an error if fewer than the given number exist.\n \n :param category: The card category to get.\n :type category: str\n :param count: The desired count of cards. Used to throw an error if not possible to get this amount.\n :type count: int\n :raises ValueError: Throws an argparse error if fewer than the requested number of cards exist.\n :return: The list of possible cards of the given category.\n :rtype: List[Card]\n \"\"\"\n\n card_list = [c for c in self.all_cards if c.category == category and self.any_set_contains(c)]\n if count > len(card_list):\n raise ValueError('too few %ss available in given sets: requested %d' % (category, count))\n return card_list\n\n def any_set_contains(self, card):\n \"\"\"\n Checks if any set in the randomizer contains the given card.\n \n :param card: The card to check for.\n :type card: Card\n :return: True if the card is contained by this randomizer's sets, otherwise False.\n :rtype: bool\n \"\"\"\n\n return any(game_set.contains(card) for game_set in self.sets)\n\n def add_special_type_cards(self):\n \"\"\"\n Adds special randomizer cards into the list of possible cards to pick.\n \n \"\"\"\n\n for card in SpecialTypeCard:\n if card.value.game_set in self.sets:\n self.possible_cards[card.value.game_set].append(card.value)\n\n def remove_split_pile_cards(self):\n \"\"\"\n Replaces the split pile cards with their corresponding split randomizer cards.\n \n \"\"\"\n\n for split_card in SplitPileCard:\n if split_card.value.game_set in self.sets:\n card_splits = split_card.value.name.split('/')\n set_cards = self.possible_cards[split_card.value.game_set]\n set_cards[:] = [card for card in set_cards if card.name not in card_splits]\n\n def add_inclusions(self):\n \"\"\"\n Adds the included cards and removes them from the possible card pool and adjusts pick counts if necessary.\n \n \"\"\"\n\n for card in self.get_name_filtered_cards(self.include, '-i/--include'):\n self.included_cards.append(card)\n self.remove_card_from_pool(card)\n\n def adjust_counts(self):\n \"\"\"\n Decrements each set's pick count based on included cards' sets.\n \n \"\"\"\n\n for card in self.included_cards:\n for i in range(len(self.sets)):\n if self.sets[i].contains(card):\n self.counts[i] -= 1\n\n def add_exclusions(self):\n \"\"\"\n Removes the excluded cards from the possible card pool.\n \n :raises ValueError\n \"\"\"\n\n for card in self.get_name_filtered_cards(self.exclude, '-x/--exclude'):\n print(card.name)\n if card in self.included_cards:\n raise ValueError('must not have \"%s\" specified for both inclusion and exclusion' % card.name)\n self.remove_card_from_pool(card)\n\n def remove_card_from_pool(self, card):\n \"\"\"\n Removes the given card from the possible card pool.\n \n :param card: The card to remove from the pool.\n :type card: Card\n \"\"\"\n\n for game_set in self.possible_cards:\n if game_set.contains(card):\n self.possible_cards[game_set].remove(card)\n break # cards are unique, may exit function once found\n\n def get_name_filtered_cards(self, card_args, arg_hint):\n \"\"\"\n Parses the given card arguments or throws an argparse error with the given hint if unable to find a card.\n \n :param card_args: The card arguments to parse.\n :type card_args: List[str]\n :param arg_hint: The argument hint to include in the error if necessary.\n :type arg_hint: str\n :raises ValueError: Throws an error if the requested card could not be found.\n :return: The list of cards matching the card arguments.\n :rtype: List[Card]\n \"\"\"\n\n cards = []\n for card_arg in card_args:\n found = False\n card_arg = Randomizer.standardize_input(card_arg)\n for card in self.all_cards:\n if card_arg == Randomizer.standardize_input(card.name):\n cards.append(card)\n found = True\n if not found:\n raise ValueError('unable to find card specified via %s: %s' % (arg_hint, card_arg))\n return cards\n\n def is_possible_card(self, card):\n \"\"\"\n Checks if the given card can be picked and is not type filtered.\n \n :param card: The card to check.\n :type card: Card\n :return: True if the card is a possible card for this randomizer, otherwise False.\n :rtype: bool\n \"\"\"\n\n return card.can_pick and not Randomizer.in_type_filter(card, self.filter_types)\n\n def validate_configuration(self):\n \"\"\"\n Checks that this randomizer has a valid configuration and raises a ValueError if not.\n This function checks for the following conditions:\n * Conflicting editioned sets (i.e. Base 1E and Base 2E)\n * Conflicting counts of sets and distributions (weights/counts)\n * Requested set counts not adding up to the requested number of cards\n * Too many included cards.\n \n :raises ValueError: If any of the previous invalidating condition are met.\n \"\"\"\n\n self.validate_editioned_sets(GameSet.BASE_1E, GameSet.BASE_2E)\n self.validate_editioned_sets(GameSet.INTRIGUE_1E, GameSet.INTRIGUE_2E)\n self.validate_distribution_lengths(self.weights, 'weights')\n self.validate_distribution_lengths(self.counts, 'counts')\n if self.counts and sum(self.counts) != self.number:\n raise ValueError('counts must add up to %d' % self.number)\n if len(self.include) > self.number:\n raise ValueError('must not have more cards included (%d) than requested (%d)' %\n (len(self.include), self.number))\n\n def validate_editioned_sets(self, set1, set2):\n \"\"\"\n Checks if both of the given game sets exist in this randomizer.\n Used to avoid conflicting editioned sets (Base1E/Base2E, Intrigue1E/Intrigue2E)\n \n :param set1: The first set to check for.\n :type set1: GameSet\n :param set2: The second set to check for.\n :type set2: GameSet\n :raises ValueError: If both sets exist in this randomizer.\n \"\"\"\n\n if set1 in self.sets and set2 in self.sets:\n raise ValueError('must choose only one of %s, %s' % (set1.full_set_name, set2.full_set_name))\n\n def validate_distribution_lengths(self, distribution, error_hint):\n \"\"\"\n Checks if the given distribution list matches this randomizer's game set count.\n \n :param distribution: The distribution to check.\n :type distribution: List[int]\n :param error_hint: The hint to include in the error message.\n :type error_hint: str\n :raises ValueError: If the quantities do not match.\n \"\"\"\n\n if distribution and len(self.sets) != len(distribution):\n raise ValueError('must have equal quantities of sets (%d) and %s (%d)' %\n (len(self.sets), error_hint, len(distribution)))\n\n @staticmethod\n def in_type_filter(card, types):\n \"\"\"\n Checks if the given card has any of the given types.\n \n :param card: The card to check.\n :type card: Card\n :param types: The list of types to check for.\n :type types: List[str]\n :return: True if the card has any of the given types.\n :rtype: bool\n \"\"\"\n\n return any(t.lower() in types for t in card.types) if types else False\n\n @staticmethod\n def standardize_input(string):\n \"\"\"\n Standardizes argument input by lowercasing and removing apostrophes and spaces.\n \n :param string: The string to standardize.\n :type string: str\n :return: The standardized string.\n :rtype: str\n \"\"\"\n\n return string.replace(\"'\", '').replace(' ', '').lower()\n" }, { "alpha_fraction": 0.6171428561210632, "alphanum_fraction": 0.6228571534156799, "avg_line_length": 27.040000915527344, "blob_id": "c8d5c33078d119d80cf70a1d5f604eabf60875cf", "content_id": "82ef579ab264c4cc01e35c463af634fe7a3863e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 700, "license_type": "no_license", "max_line_length": 112, "num_lines": 25, "path": "/json_util.py", "repo_name": "FThompson/DominionRandomizer", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module contains a custom JSON encoder that looks for __json__ functions.\n\n\"\"\"\n\nimport json\n\n\nclass JSONUnderscoreEncoder(json.JSONEncoder):\n \"\"\"\n A custom JSON Encoder which uses objects' __json__ functions if present, otherwise uses the default encoder.\n \n \"\"\"\n\n def default(self, obj): # pylint: disable=E0202\n \"\"\"\n Overrides the standard JSONEncoder's default encoder to check for the callable __json__ attribute.\n \n :return: The JSON encoded object.\n :rtype: str\n \"\"\"\n\n if hasattr(obj, '__json__') and callable(getattr(obj, '__json__')):\n return obj.__json__()\n return json.JSONEncoder.default(self, obj)" }, { "alpha_fraction": 0.6791523098945618, "alphanum_fraction": 0.6899950504302979, "avg_line_length": 23.445783615112305, "blob_id": "fa89eb01f9ee998719c69c895db68f7a4400bf51", "content_id": "80f56223a9660c01d04027d9847d6ec6858d4831", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2029, "license_type": "no_license", "max_line_length": 263, "num_lines": 83, "path": "/README.md", "repo_name": "FThompson/DominionRandomizer", "src_encoding": "UTF-8", "text": "# Dominion Randomizer #\n\nThis program automates the card randomizer process by picking 10 cards from the given sets, as this process can be cumbersome to do manually when shuffling randomizers from many game sets. Run with the desired game sets, or `all`, as parameters to `randomize.py`.\n\n## Example ##\n\n python randomize.py base1e intrigue2e seaside prosperity\n\n## Output ##\n\n Base\n - Laboratory (Action), Cost(5C)\n - Market (Action), Cost(5C)\n Intrigue\n - Minion (Action, Attack), Cost(5C)\n - Patrol (Action), Cost(5C)\n - Swindler (Action, Attack), Cost(3C)\n Prosperity\n - King's Court (Action), Cost(7C)\n - Vault (Action), Cost(5C)\n Seaside\n - Island (Action, Victory), Cost(4C)\n - Native Village (Action), Cost(2C)\n - Wharf (Action, Duration), Cost(5C)\n\n## Configuration ##\n\n`python randomize.py [SETS ...]`\n\nRequired. Specify the Dominion sets to randomize from. Possible options:\n\n- `base1e`\n- `base2e`\n- `intrigue1e`\n- `intrigue2e`\n- `seaside`\n- `alchemy`\n- `prosperity`\n- `cornucopia`\n- `hinterlands`\n- `darkages`\n- `guilds`\n- `adventures`\n- `empires`\n- `nocturne`\n- `renaissance`\n- `all`\n\nIf `all` is selected, cards from all game sets are included.\n\n#### Optional Arguments ####\n\n`-n/--number NUMBER`\n\nNumber of cards to pick, default 10.\n\n`-w/--weights [WEIGHTS ...]`\n\nSpecify weights to apply to each given set for randomization. The weights can be floats and are applied relative to each other.\n\n`-c/--counts [COUNTS ...]`\n\nSpecify counts of cards to randomly draw from each given set. The sum of the counts must match the total number of cards being drawn randomly.\n\n`-i/--include [INCLUDE ...]`\n\nSpecify cards to include in the output.\n\n`-x/--exclude [EXCLUDE ...]`\n\nSpecify cards to exclude from the list of possible cards.\n\n`-f/--filter-types [TYPES ...]`\n\nFilter out cards with specific types from the list of possible cards.\n\n`-e/--events EVENTS`\n\nNumber of Event cards to pick, default 0.\n\n`-l/--landmarks LANDMARKS`\n\nNumber of Landmark cards to pick, default 0.\n" }, { "alpha_fraction": 0.5908694863319397, "alphanum_fraction": 0.5940059423446655, "avg_line_length": 32.561405181884766, "blob_id": "b820b75f4fa77741373952c543c4d2136d099e44", "content_id": "5c0a585bb20f700c88656c5f22bb2d9d47044c92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5739, "license_type": "no_license", "max_line_length": 115, "num_lines": 171, "path": "/fetch_cards.py", "repo_name": "FThompson/DominionRandomizer", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module contains CardFetcher, which can be called via command line to fetch cards, and card images if the\n-i/--images argument is present. Card data is saved into res/cards.json and card images are saved into res/cards/.\n\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport re\nimport shutil\nimport urllib.request\nfrom argparse import ArgumentParser\nfrom pathlib import Path\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom json_util import JSONUnderscoreEncoder\nfrom dtypes import Card, Cost, GameSet, SpecialTypeCard, SplitPileCard\n\n\nclass CardFetcher:\n \"\"\"\n Fetches Dominion card data and images from the Dominion Wiki.\n \n \"\"\"\n\n def fetch_cards(self):\n \"\"\"\n Fetches and parses all cards from the Dominion Wiki.\n Uses http://wiki.dominionstrategy.com/index.php/List_of_cards?action=raw.\n \n \"\"\"\n\n cards = []\n response = requests.get('http://wiki.dominionstrategy.com/index.php/List_of_cards?action=raw')\n raw_cards = response.content.decode('utf-8').split('\\n|-\\n')\n for raw_card in raw_cards[1:]: # skip data header line\n card = self.parse_card_data(raw_card)\n cards.append(card)\n self.cards = cards\n self.add_special_cards()\n\n def fetch_card_image(self, card):\n \"\"\"\n Fetches a given card's image at maximum available resolution and saves it to res/cards/{name}.jpg.\n If the image already exists at that path, this function returns without doing anything.\n \n :param card: The card to fetch the image of.\n :type card: Card\n \"\"\"\n\n filepath = Path('res') / 'cards' / (card.encoded_name + '.jpg')\n if not filepath.exists():\n response = requests.get('http://wiki.dominionstrategy.com/index.php/File:%s.jpg' % card.encoded_name)\n soup = BeautifulSoup(response.content, 'html.parser')\n image_url = 'http://wiki.dominionstrategy.com/' + soup.select_one('#file a').get('href')\n temp_path, headers = urllib.request.urlretrieve(image_url)\n if not filepath.parent.exists():\n filepath.parent.mkdir()\n shutil.move(temp_path, filepath)\n\n def parse_card_data(self, raw_card):\n \"\"\"\n Parses a Card object from the given raw card data entry pulled from the Dominion Wiki.\n Card text is left in Wiki format and should not be rendered directly.\n \n :param raw_card: The raw card data entry.\n :type raw_card: str\n :return: The Card parsed from the data.\n :rtype: Card\n \"\"\"\n\n raw = re.split(r'\\D\\|\\|\\D', raw_card)\n name, category = self.get_name_and_category(raw[0])\n game_set = self.get_game_set(raw[1])\n types = self.get_types(raw[2])\n cost = self.get_cost(raw[3])\n text = raw[4].strip()\n return Card(name, category, types, game_set, cost, text)\n\n def get_name_and_category(self, raw):\n \"\"\"\n Parses the name and category from the given raw string.\n \n :param raw: The raw data part, like \"|{{Card|Cellar}}\".\n :type raw: str\n :return: The card's name and category as a tuple.\n :rtype: Tuple[str]\n \"\"\"\n\n m = re.match(r'\\|\\{\\{(.*?)\\|(.*?)\\}\\}', raw)\n name = m.group(2)\n category = m.group(1)\n return name, category\n\n def get_game_set(self, raw):\n \"\"\"\n Parses the game set and edition from the given raw string.\n \n :param raw: The raw data part, like \"[[Base]], <abbr title=\"Only in First Edition\">1E</abbr>\".\n :type raw: str\n :return: The card's game set.\n :rtype: GameSet\n \"\"\"\n\n m = re.match(r'\\[\\[(.*?)\\]\\](, <abbr.+>([12]E)<)?', raw)\n game_set = m.group(1)\n edition = m.group(3)\n name = game_set + (' ' + edition if edition else '')\n return GameSet.for_name(name)\n\n def get_types(self, raw):\n \"\"\"\n Parses the card's types.\n \n :param raw: The raw data part, like \"Action - Reaction\".\n :type raw: str\n :return: The card's types as a list.\n :rtype: List[str]\n \"\"\"\n\n return [x.strip() for x in raw.split('-')]\n\n def get_cost(self, raw):\n \"\"\"\n Parses the card's cost, including coins, potions, and debt.\n \n :param raw: The raw data part, like \"{{Cost|2}}\".\n :type raw: str\n :return: The card's cost as a Cost object.\n :rtype: Cost\n \"\"\"\n\n raw_cost = raw.split('|', 1)[1].strip()\n return Cost.from_raw(raw_cost)\n\n def add_special_cards(self):\n \"\"\"\n Adds special randomizer cards and split pile randomizer cards to the card fetcher.\n These card objects are absent from the Dominion Wiki list of cards due to their special status.\n \n \"\"\"\n\n self.cards.extend([c.value for c in SpecialTypeCard])\n self.cards.extend([c.value for c in SplitPileCard])\n\n\ndef main():\n \"\"\"\n Runs the card fetcher and saves cards to res/cards.json.\n If the -i/--images argument is specified, the fetcher will also retrieve card images, saved to res/cards/*.jpg.\n \n \"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--images', action='store_true', help='Fetch card images')\n args = parser.parse_args()\n fetcher = CardFetcher()\n fetcher.fetch_cards()\n for card in fetcher.cards:\n if args.images:\n fetcher.fetch_card_image(card)\n print(card)\n json_path = os.path.join(os.path.dirname(__file__), 'res/cards.json')\n with open(json_path, 'w') as f:\n json.dump(fetcher.cards, f, cls=JSONUnderscoreEncoder)\n \nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5511729717254639, "alphanum_fraction": 0.5596023797988892, "avg_line_length": 29.301204681396484, "blob_id": "6513f95496e91ce0649a4382e270ecfd9150b42d", "content_id": "3089332fefc586acf0e5d45057b69c28b79c8cb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12575, "license_type": "no_license", "max_line_length": 117, "num_lines": 415, "path": "/dtypes.py", "repo_name": "FThompson/DominionRandomizer", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module contains various common Dominion types and enums.\n\n\"\"\"\n\nimport re\nfrom enum import Enum\n\n\nclass Card:\n \"\"\"\n Represents a Dominion card, including non-card cards like Events.\n \n \"\"\"\n\n def __init__(self, name, category, types, game_set, cost, text, special_can_pick=False):\n \"\"\"\n Creates a card instance.\n \n :param name: The card's name.\n :type name: str\n :param category: The card's category (Card, Event, etc.).\n :type category: str\n :param types: The card's types (Attack, Duration, etc.).\n :type types: List[str]\n :param game_set: The card's game set.\n :type game_set: GameSet\n :param cost: The card's cost, including coins, potions, and debt.\n :type cost: Cost\n :param text: The card's text.\n :type text: str\n :param special_can_pick: True if this card has a special randomizer, otherwise False. Defaults to False.\n :param special_can_pick: bool, optional\n \"\"\"\n\n self.name = name\n self.category = category\n self.types = types\n self.game_set = game_set\n self.cost = cost\n self.text = text\n self.in_supply = (self.category == 'Card' and 'This is not in the Supply' not in self.text and\n all(CardType.is_in_supply(t) for t in self.types))\n self.is_basic = self.name.lower() in [c.name.lower() for c in BasicCard]\n self.can_pick = special_can_pick or (self.in_supply and not self.is_basic)\n self.encoded_name = self.name.replace(' ', '_').replace('/', '_').replace(\"'\", '%27')\n\n @classmethod\n def from_json(cls, **json):\n \"\"\"\n Parses a Card from the given json dictionary.\n \n :return: The card instance stored in the given json data.\n :rtype: Card\n \"\"\"\n\n props = dict(json)\n props['game_set'] = GameSet.for_name(props['game_set'])\n props['cost'] = Cost(**props['cost'])\n return cls(**props)\n\n def __str__(self):\n \"\"\"\n Formats this card like \"Cellar (Card), Base, (Action), Cost(2C, 0P, 0D)\"\n \n :return: The card's formatted data.\n :rtype: str\n \"\"\"\n\n return '%s (%s), %s, (%s), %s' % (self.name, self.category, self.game_set, ', '.join(self.types), self.cost)\n\n def __json__(self):\n \"\"\"\n Creates a dict of this card's data to be stored in a json file.\n \n :return: This card's data as a dict.\n :rtype: Dict[str, T]\n \"\"\"\n\n return {'name': self.name, 'category': self.category, 'types': self.types, 'game_set': self.game_set,\n 'cost': self.cost, 'text': self.text}\n\n\nclass Cost:\n \"\"\"\n Represents a cost, consisting of coins, potions, and/or debt.\n \n \"\"\"\n\n def __init__(self, coins=0, potions=0, debt=0, has_exception=False):\n \"\"\"\n Creates a Cost instance.\n \n :param coins: The cost's coins component, defaults to 0\n :param coins: int, optional\n :param potions: The cost's potions component, defaults to 0\n :param potions: int, optional\n :param debt: The cost's debt component, defaults to 0\n :param debt: int, optional\n :param has_exception: True if the card's cost has an asterisk, defaults to False\n :param has_exception: bool, optional\n \"\"\"\n\n self.coins = int(coins)\n self.potions = int(potions)\n self.debt = int(debt)\n self.has_exception = bool(has_exception)\n\n @classmethod\n def from_raw(cls, raw_cost):\n \"\"\"\n Parses a cost from the given raw data string, as formatted in the Dominion Wiki.\n Possible formats:\n * {{Cost|2}}\n * {{Cost|4P}}\n * {{Cost|8||8}}\n * {{Cost| | |5}}\n \n :param raw_cost: The raw cost, in one of the above forms.\n :type raw_cost: str\n :return: The Cost object.\n :rtype: Cost\n \"\"\"\n\n m = re.match(r'\\{\\{Cost\\|(\\d+)(\\*?)(P?)\\}\\}', raw_cost) # e.g. {{Cost|5}} or {{Cost|5P}}\n if m:\n return cls(coins=m.group(1), potions=1 if m.group(3) else 0, has_exception=m.group(2))\n m = re.match(r'\\{\\{Cost\\|(\\d+)\\|\\|(\\d+)\\}\\}', raw_cost) # e.g. {{Cost|4||3}}\n if m:\n return cls(coins=m.group(1), debt=m.group(2))\n m = re.match(r'\\{\\{Cost\\| \\| \\|(\\d+)\\}\\}', raw_cost) # e.g. {{Cost| | |8}}\n if m:\n return cls(debt=m.group(1))\n return cls() # zero expense Cost\n\n def __str__(self):\n \"\"\"\n Formats this cost like Cost(8C, 8D).\n \n :return: The formatted cost string.\n :rtype: str\n \"\"\"\n\n if all(x is 0 for x in [self.coins, self.potions, self.debt]):\n return 'Cost(0)'\n parts = []\n if self.coins > 0 or self.has_exception:\n parts.append(str(self.coins) + 'C' + ('*' if self.has_exception else ''))\n if self.potions > 0:\n parts.append(str(self.potions) + 'P')\n if self.debt > 0:\n parts.append(str(self.debt) + 'D')\n return 'Cost(%s)' % ', '.join(parts)\n\n def __json__(self):\n \"\"\"\n This cost's json encoded form.\n \n :return: The cost's attribute dictionary.\n :rtype: Dict[str, T]\n \"\"\"\n\n return self.__dict__\n\n\nclass GameSet(Enum):\n \"\"\"\n An enumeration of all Dominion game sets.\n Game sets with multiple editions have entries for each edition as well as the non-editioned name.\n \"\"\"\n\n BASE = 'Base', None, False\n BASE_1E = 'Base', 1\n BASE_2E = 'Base', 2\n INTRIGUE = 'Intrigue', None, False\n INTRIGUE_1E = 'Intrigue', 1\n INTRIGUE_2E = 'Intrigue', 2\n SEASIDE = 'Seaside'\n ALCHEMY = 'Alchemy'\n PROSPERITY = 'Prosperity'\n CORNUCOPIA = 'Cornucopia'\n HINTERLANDS = 'Hinterlands'\n DARK_AGES = 'Dark Ages'\n GUILDS = 'Guilds'\n ADVENTURES = 'Adventures'\n EMPIRES = 'Empires'\n NOCTURNE = 'Nocturne'\n RENAISSANCE = 'Renaissance'\n PROMO = 'Promo', None, False\n\n def __init__(self, set_name, edition=None, complete=True):\n \"\"\"\n Creates a game set with given name, edition, and completedness.\n \n :param set_name: The game set's name.\n :type set_name: str\n :param edition: The game set's edition, defaults to None\n :param edition: int, optional\n :param complete: True if the game set is a complete set, otherwise False, defaults to True\n :param complete: bool, optional\n \"\"\"\n\n self.set_name = set_name\n self.full_set_name = set_name + ((' %dE' % edition) if edition else '')\n self.complete = complete\n\n def contains(self, card):\n \"\"\"\n Checks if this game set contains the given card.\n \n :param card: The card to check for.\n :type card: Card\n :return: True if the card is in this set, otherwise False.\n :rtype: bool\n \"\"\"\n\n # uses startswith to handle editioned sets properly\n return self.full_set_name.startswith(card.game_set.full_set_name)\n\n def as_arg(self):\n \"\"\"\n Converts this set's name into argument form (no spaces, lowercase).\n \n :return: The set's name, in lowercase, without any spaces.\n :rtype: str\n \"\"\"\n\n return self.full_set_name.lower().replace(' ', '')\n\n def __str__(self):\n \"\"\"\n Returns this set's name without edition.\n \n :return: This set's name.\n :rtype: str\n \"\"\"\n\n return self.set_name\n\n def __json__(self):\n \"\"\"\n Returns this set's json form.\n \n :return: The game set's name including edition.\n :rtype: str\n \"\"\"\n\n return self.full_set_name\n\n @classmethod\n def for_arg(cls, arg):\n \"\"\"\n Gets the game set with the given argument form.\n \n :param arg: The arg to check for.\n :type arg: str\n :return: The game set if found, otherwise None.\n :rtype: GameSet\n \"\"\"\n\n arg = arg.lower().replace(' ', '')\n for game_set in cls:\n if game_set.as_arg() == arg:\n return game_set\n return None\n\n @classmethod\n def for_name(cls, name):\n \"\"\"\n Gets the game set with the given name.\n \n :param name: The name to check for.\n :type name: str\n :return: The game set if found, otherwise None.\n :rtype: GameSet\n \"\"\"\n\n for game_set in cls:\n if game_set.full_set_name == name:\n return game_set\n return None\n\n @classmethod\n def complete_sets(cls):\n \"\"\"\n Gets all complete sets.\n \n :return: A list of all complete game sets.\n :rtype: List[GameSet]\n \"\"\"\n\n return [g for g in GameSet if g.complete]\n\n\nclass CardCategory(Enum):\n \"\"\"\n An enumeration of card categories (Card, Event, etc.).\n \n \"\"\"\n\n CARD = 0\n EVENT = 1\n LANDMARK = 2\n BOON = 3\n HEX = 4\n STATE = 5\n ARTIFACT = 6\n PROJECT = 7\n\n\nclass BasicCard(Enum):\n \"\"\"\n An enumeration of basic cards that are used in all or most games.\n \n \"\"\"\n\n COPPER = 0\n SILVER = 1\n GOLD = 2\n ESTATE = 3\n DUCHY = 4\n PROVINCE = 5\n CURSE = 6\n PLATINUM = 7\n COLONY = 8\n POTION = 9\n\n\nclass CardType(Enum):\n \"\"\"\n An enumeration of card types (Attack, Duration, etc.) and whether or not cards with each type are in the supply.\n \n \"\"\"\n\n ACTION = 0, True\n TREASURE = 1, True\n VICTORY = 2, True\n CURSE = 3, True\n ATTACK = 4, True\n DURATION = 5, True\n REACTION = 6, True\n CASTLE = 7, False\n DOOM = 8, True\n FATE = 9, True\n GATHERING = 10, True\n HEIRLOOM = 11, False\n KNIGHT = 12, False\n LOOTER = 13, True\n NIGHT = 14, True\n PRIZE = 15, False\n RESERVE = 16, True\n RUINS = 17, False\n SHELTER = 18, False\n SPIRIT = 19, False\n TRAVELLER = 20, True\n ZOMBIE = 21, False\n\n def __init__(self, value, in_supply):\n \"\"\"\n Creates a card type.\n \n :param value: The enum index, used only for creating unique objects.\n :type value: int\n :param in_supply: True if cards of this type are in the supply, otherwise False.\n If a card has any type where in_supply is False, then that card is not in the supply.\n :type in_supply: bool\n \"\"\"\n\n self.in_supply = in_supply\n\n def get_name(self):\n return str(self.name)[0] + str(self.name)[1:].lower()\n\n @classmethod\n def is_in_supply(cls, card_type):\n \"\"\"\n Checks if the given card type is in the supply.\n \n :param card_type: The card type to check.\n :type card_type: str\n :return: True if the card type is in the supply, otherwise False.\n :rtype: bool\n \"\"\"\n\n for t in CardType:\n if t.name.lower() == card_type.lower():\n return t.in_supply\n return False\n\n\nclass SpecialTypeCard(Enum):\n \"\"\"\n An enumeration of special randomizer cards, which replace several unique cards of the same type (Knight, Castle).\n Drawing the randomizer for the entire type means the game should include the stack of unique cards of that type.\n \"\"\"\n\n KNIGHTS = Card('Knights', 'Card', ['Action', 'Attack', 'Knight'], GameSet.DARK_AGES, Cost(5), '', True)\n CASTLES = Card('Castles', 'Card', ['Victory', 'Castle'], GameSet.EMPIRES, Cost(3), '', True)\n\n\nclass SplitPileCard(Enum):\n \"\"\"\n An enumeration of special randomizer cards, which replace pairs of cards that exist only in split piles.\n Drawing the randomizer for the pair means the game should include both cards in a split pile stack.\n\n The types of each pair card listed below represent only the types from the top (first) card in the split pile.\n \"\"\"\n\n ENCAMPMENT_PLUNDER = Card('Encampment/Plunder', 'Card', ['Action'], GameSet.EMPIRES, Cost(2), '', True)\n PATRICIAN_EMPORIUM = Card('Patrician/Emporium', 'Card', ['Action'], GameSet.EMPIRES, Cost(2), '', True)\n SETTLERS_BUSTLING_VILLAGE = Card('Settlers/Bustling Village', 'Card', ['Action'], GameSet.EMPIRES, Cost(2), '',\n True)\n CATAPULT_ROCKS = Card('Catapult/Rocks', 'Card', ['Action', 'Attack'], GameSet.EMPIRES, Cost(3), '', True)\n GLADIATOR_FORTUNE = Card('Gladiator/Fortune', 'Card', ['Action'], GameSet.EMPIRES, Cost(3), '', True)\n SAUNA_AVANTO = Card('Sauna/Avanto', 'Card', ['Action'], GameSet.PROMO, Cost(4), '', True)\n" }, { "alpha_fraction": 0.43233081698417664, "alphanum_fraction": 0.6729323267936707, "avg_line_length": 14.647058486938477, "blob_id": "e4c9e4d70180180390d417e3d43fca39e0c3bd80", "content_id": "a8fdfd94c35ae9b2231ab2922c695d6031ecd5ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 266, "license_type": "no_license", "max_line_length": 24, "num_lines": 17, "path": "/requirements.txt", "repo_name": "FThompson/DominionRandomizer", "src_encoding": "UTF-8", "text": "astroid==2.1.0\nbeautifulsoup4==4.6.3\ncertifi==2018.10.15\nchardet==3.0.4\ncolorama==0.4.1\nidna==2.7\nisort==4.3.4\nlazy-object-proxy==1.3.1\nmccabe==0.6.1\npep8==1.7.1\npylint==2.2.2\nrequests==2.20.1\nrope==0.11.0\nsix==1.11.0\ntyped-ast==1.1.0\nurllib3==1.24.1\nwrapt==1.10.11\n" }, { "alpha_fraction": 0.5878539085388184, "alphanum_fraction": 0.5904473662376404, "avg_line_length": 46.224491119384766, "blob_id": "00d6f8adb1ebb3268cf76930287e1b5ad0e73b69", "content_id": "d5fbb0a62569d685f1ee4d0c238f0e1d8ce4759d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4627, "license_type": "no_license", "max_line_length": 116, "num_lines": 98, "path": "/randomize.py", "repo_name": "FThompson/DominionRandomizer", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module contains the command-line interface for the Dominion randomizer.\n\n\"\"\"\n\n\nimport argparse\nimport os\nfrom dtypes import CardType, GameSet\nfrom randomizer import Randomizer\n\n\nclass RandomizerParser():\n \"\"\"\n An argument parser that parses the following arguments and converts them into a Randomizer instance.\n\n positional arguments:\n {base1e,base2e,intrigue1e,intrigue2e,seaside,alchemy,prosperity,cornucopia,hinterlands,darkages,guilds,\n adventures,empires,nocturne,renaissance,all}\n Game sets to choose from, or all\n\n optional arguments:\n -h, --help show this help message and exit\n -n NUMBER, --number NUMBER\n Number of cards to pick, default 10\n -w WEIGHTS [WEIGHTS ...], --weights WEIGHTS [WEIGHTS ...]\n Weights to be applied to each set when randomly\n picking cards\n -c COUNTS [COUNTS ...], --counts COUNTS [COUNTS ...]\n Counts of cards to pick from each set\n -i INCLUDE [INCLUDE ...], --include INCLUDE [INCLUDE ...]\n Specific cards to include\n -x EXCLUDE [EXCLUDE ...], --exclude EXCLUDE [EXCLUDE ...]\n Specific cards to exclude\n -f {action,treasure,victory,attack,duration,reaction,doom,fate,gathering,looter,night,reserve,traveller}\n [{TYPES} ...], --filter-types {TYPES} [{TYPES} ...]\n Specific cards types to filter out before randomly\n picking cards\n -e EVENTS, --events EVENTS\n Number of events to pick\n -l LANDMARKS, --landmarks LANDMARKS\n Number of landmarks to pick\n \"\"\"\n\n def get_randomizer(self, data_path):\n \"\"\"\n Construct a Randomizer instance from the parsed arguments and the given data path.\n \n :param data_path: The cards.json data path.\n :type data_path: str\n :return: A randomizer instance.\n :rtype: Randomizer\n \"\"\"\n\n return Randomizer(data_path, self.args.sets, self.args.number, self.args.weights, self.args.counts,\n self.args.include, self.args.exclude, self.args.filter_types, self.args.events,\n self.args.landmarks)\n\n def parse_args(self):\n \"\"\"\n Creates the argparse.ArgumentParser and parses and checks args.\n \"\"\"\n\n self.parser = argparse.ArgumentParser()\n game_choices = [g.as_arg() for g in GameSet.complete_sets()]\n game_choices.append('all')\n self.parser.add_argument('sets', nargs='+', choices=game_choices, help='Game sets to choose from, or all')\n self.parser.add_argument('-n', '--number', type=int, default=10, help='Number of cards to pick, default 10')\n distribution_group = self.parser.add_mutually_exclusive_group()\n distribution_group.add_argument('-w', '--weights', nargs='+', type=float, default=[],\n help='Weights to be applied to each set when randomly picking cards')\n distribution_group.add_argument('-c', '--counts', nargs='+', type=int, default=[],\n help='Counts of cards to pick from each set')\n self.parser.add_argument('-i', '--include', nargs='+', default=[], help='Specific cards to include')\n self.parser.add_argument('-x', '--exclude', nargs='+', default=[], help='Specific cards to exclude')\n type_choices = [t.name.lower() for t in CardType if t.in_supply]\n type_choices.remove('curse') # curse type only present on basic curse card\n self.parser.add_argument('-f', '--filter-types', nargs='+', choices=type_choices, default=[],\n help='Specific cards types to filter out before randomly picking cards')\n self.parser.add_argument('-e', '--events', type=int, default=0, help='Number of events to pick')\n self.parser.add_argument('-l', '--landmarks', type=int, default=0, help='Number of landmarks to pick')\n self.args = self.parser.parse_args()\n\n\ndef main():\n \"\"\"\n Parses randomizer args, creates a randomizer, and randomizes and prints cards.\n \"\"\"\n\n json_path = os.path.join(os.path.dirname(__file__), 'res/cards.json')\n parser = RandomizerParser()\n parser.parse_args()\n randomizer = parser.get_randomizer(json_path)\n randomizer.randomize()\n randomizer.print_cards()\n\nif __name__ == '__main__':\n main()" } ]
7
jiang16/auto-commit
https://github.com/jiang16/auto-commit
c1fce075eaeae6a05f9767021bae1fe6a59f461a
bb7ef2343fb799afc7227ec8e41f1f50a292790a
01bb8d20b70aee18e3042f58acaa2af9c6808c08
refs/heads/master
2021-08-14T09:47:54.517544
2017-11-15T08:30:11
2017-11-15T08:30:11
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5587056875228882, "alphanum_fraction": 0.5781201720237732, "avg_line_length": 35.875, "blob_id": "96533cd9b9bdf8a5407462d247193a95a1914191", "content_id": "718f460e54f669926bc490a011348e662a53cc35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3331, "license_type": "no_license", "max_line_length": 139, "num_lines": 88, "path": "/submit.py", "repo_name": "jiang16/auto-commit", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python \n#-*-coding:utf-8-*- \n \nimport sys, os, shutil\nimport urllib, urllib2 \nimport cookielib \nimport getpass \nfrom bs4 import BeautifulSoup \n \n#处理编码问题\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nhome_url = 'http://acm.sdut.edu.cn/onlinejudge2/index.php/Home' \nlogin_url = 'http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Login/login' \nheaders = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'} \n \ndef Login(): \n cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar()) \n opener = urllib2.build_opener(cookie_support) \n urllib2.install_opener(opener) \n home_temp = urllib2.urlopen(home_url) \n uername = raw_input('请输入用户名:') \n key = getpass.getpass('请输入登录密码:') \n values = {'user_name': uername, 'password': key} \n post = urllib.urlencode(values) \n request = urllib2.Request(login_url, post, headers) \n response = urllib2.urlopen(request) \n soup = BeautifulSoup(response.read()) \n if soup.find(text = 'Logout') != None: \n print '登录成功:)'\n else: \n print '登录失败:('\n sys.exit(0)\n\ndef Logout():\n urllib2.urlopen('http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Login/logout')\n print '退出登录'\n\ndef Contest(cid, do):\n url = 'http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/problemlist/cid/' + cid\n soup = BeautifulSoup(urllib2.urlopen(url))\n problem = soup.find_all('tr')\n for tr in problem:\n try:\n td = tr.find_all('td')\n pid = td[0].a['href'][-4:]\n if do == True:\n DownloadCode(cid, pid)\n else:\n Submit(cid, pid)\n print td[0].text + '提交成功'\n except:\n pass\n\ndef DownloadCode(cid, pid):\n url = 'http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Solution/status/pid/' + pid + '/result/1.html'\n sub = BeautifulSoup(urllib2.urlopen(url)) \n table = sub.find_all('tr') \n for tr in table: \n try: \n td = tr.find_all('td') \n if td[3].text == 'Accepted' and td[2].a['href'][-9:-5] == pid and (td[6].text == 'g++' or td[6].text == 'gcc'): \n code_url = 'http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Viewcode/view/sid/' + td[0].text \n code = BeautifulSoup(urllib2.urlopen(code_url)).find(class_ = 'brush:cpp;').text\n with open('/home/lenovo/Code/' + pid + '.cpp', 'w') as f:\n f.write(code)\n return\n except: \n pass \n\ndef Submit(cid, pid):\n url = 'http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestsubmit/cid/' + cid + '/pid/' + pid + '.html'\n with open('/home/lenovo/Code/' + pid + '.cpp', 'r') as f:\n code = f.read()\n value = {'cid': cid, 'pid': pid, 'lang': 'g++', 'code': code}\n request = urllib2.Request(url, urllib.urlencode(value), headers) \n response = urllib2.urlopen(request)\n \nif __name__ == '__main__':\n os.mkdir('/home/lenovo/Code')\n Login()\n cid = raw_input('请输入比赛的id:')\n Contest(cid, True)\n Logout()\n Login()\n Contest(cid, False)\n shutil.rmtree('/home/lenovo/Code')\n" } ]
1
tilakbabu/test
https://github.com/tilakbabu/test
d2a6930b219fd02896b9bdadaf28b260e7188eb7
a7956e416153683475ed28746c24290738b43eb0
a17ea542edbc7ff6d2b5a59526fec36452e82b0e
refs/heads/master
2020-03-26T23:11:43.388994
2018-08-21T06:47:25
2018-08-21T06:47:25
145,519,091
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5141327977180481, "alphanum_fraction": 0.5240120887756348, "avg_line_length": 47.10560989379883, "blob_id": "bf9ca05b37bdeb0ad1b5e8dc8a9e31b1064d33a8", "content_id": "faa6a3566584f7c1054e7eb4262beda6a574a13f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14576, "license_type": "no_license", "max_line_length": 228, "num_lines": 303, "path": "/HTML/cgi-bin/fread.py", "repo_name": "tilakbabu/test", "src_encoding": "UTF-8", "text": "import cgi,cgitb\ncgitb.enable()\nimport sqlite3\nform=cgi.FieldStorage()\nname=form.getvalue('name')\nconn=sqlite3.connect('e-articles.db')\nd1=conn.execute(\"select Aname,Description,Aid,Area,Fname from Articles A,Faculty F where A.F_email=F.F_email and F.Fname=?\",(name,))\nd3=conn.execute(\"select F_email from Faculty where Fname=?\",(name,))\ndata3=d3.fetchall()\nd2=conn.execute(\"select count(*) from Articles where F_email=?\",(data3[0][0],))\ndata2=d2.fetchall()\ndata1=d1.fetchall()\nprint(\"Content-type:text/html\")\nprint()\nprint(\"\"\"<!DOCTYPE html>\n<!-- ==============================\n\tProject: Metronic \"Asentus\" Frontend Freebie - Responsive HTML Template Based On Twitter Bootstrap 3.3.4\n\tVersion: 1.0\n\tAuthor: KeenThemes\n\tPrimary use: Corporate, Business Themes.\n\tEmail: [email protected]\n\tFollow: http://www.twitter.com/keenthemes\n\tLike: http://www.facebook.com/keenthemes\n\tWebsite: http://www.keenthemes.com\n\tPremium: Premium Metronic Admin Theme: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes\n================================== -->\n<html lang=\"en\" class=\"no-js\">\n\t<!-- BEGIN HEAD -->\n\t<head>\n\t\t<meta charset=\"utf-8\"/>\n\t\t<title>E-ARTICLES</title>\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta content=\"width=device-width, initial-scale=1\" name=\"viewport\"/>\n\t\t<meta content=\"\" name=\"description\"/>\n\t\t<meta content=\"\" name=\"author\"/>\n\n\t\t<!-- GLOBAL MANDATORY STYLES -->\n\t\t<link href=\"http://fonts.googleapis.com/css?family=Hind:300,400,500,600,700\" rel=\"stylesheet\" type=\"text/css\">\n\t\t<link href=\"/vendor/simple-line-icons/simple-line-icons.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\t\t<link href=\"/vendor/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\n\t\t<!-- PAGE LEVEL PLUGIN STYLES -->\n\t\t<link href=\"/css/animate.css\" rel=\"stylesheet\">\n\t\t<link href=\"/vendor/swiper/css/swiper.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\n\t\t<!-- THEME STYLES -->\n\t\t<link href=\"/css/layout.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\n\t\t<!-- Favicon -->\n\t\t<link rel=\"shortcut icon\" href=\"favicon.ico\"/>\n\t</head>\n\t<!-- END HEAD -->\n\n\t<!-- BODY -->\n\t<body>\n\n\t\t<!--========== HEADER ==========-->\n\t\t<header class=\"header navbar-fixed-top\">\n\t\t\t<!-- Navbar -->\n\t\t\t<nav class=\"navbar\" role=\"navigation\">\n\t\t\t\t<div class=\"container\">\n\t\t\t\t\t<!-- Brand and toggle get grouped for better mobile display -->\n\t\t\t\t\t<div class=\"menu-container\">\n\t\t\t\t\t\t<button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".nav-collapse\">\n\t\t\t\t\t\t\t<span class=\"sr-only\">Toggle navigation</span>\n\t\t\t\t\t\t\t<span class=\"toggle-icon\"></span>\n\t\t\t\t\t\t</button>\n\n\t\t\t\t\t\t<!-- Logo -->\n\t\t\t\t\t\t<div class=\"logo\">\n\t\t\t\t\t\t\t<a class=\"logo-wrap\" href=\"fhome.py\">\n\t\t\t\t\t\t\t\t<img class=\"logo-img logo-img-main\" src=\"/img/logo.png\" alt=\"Asentus Logo\">\n\t\t\t\t\t\t\t\t<img class=\"logo-img logo-img-active\" src=\"/img/logo-dark.png\" alt=\"Asentus Logo\">\n\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<!-- End Logo -->\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<!-- Collect the nav links, forms, and other content for toggling -->\n\t\t\t\t\t<div class=\"collapse navbar-collapse nav-collapse\">\n\t\t\t\t\t\t<div class=\"menu-container\">\n\t\t\t\t\t\t\t<ul class=\"navbar-nav navbar-nav-right\">\n\t\t\t\t\t\t\t\t<li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover active\" href=\"fhome.py\">Read Articles</a></li>\n\t\t\t\t\t\t\t\t<li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"fssearch.py\">Read Students Articles</a></li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover \" href=\"fpublish.py\">Publish an Article</a></li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"fprofile.py\">Profile</a></li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"fverify.py\">Verify Articles</a></li>\n\t\t\t\t\t\t\t\t<li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"/index.html\">Sign Out</a></li>\n\t\t\t\t\t\t\t\t<!--<li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"contact.html\">Contact</a></li>-->\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<!-- End Navbar Collapse -->\n\t\t\t\t</div>\n\t\t\t</nav>\n\t\t\t<!-- Navbar -->\n\t\t</header>\n\t\t<!--========== END HEADER ==========-->\n\n\t\t<!--========== PARALLAX ==========-->\n\t\t<div class=\"parallax-window\" data-parallax=\"scroll\" data-image-src=\"/img/1920x1080/01.jpg\">\n\t\t\t<div class=\"parallax-content container\">\n\t\t\t\t<h1 class=\"carousel-title\">READ ARTICLES</h1>\n\t\t\t\t<p>HERE YOU CAN FIND<br/> THE ARTICLES PUBLISHED AND YOU CAN READ THEM</p>\n\t\t\t</div>\n\t\t</div>\n\t\t<!--========== PARALLAX ==========-->\n\n\t\t<!--========== PAGE LAYOUT ==========-->\n\t\t<!-- Pricing -->\n\t\t<div class=\"bg-color-sky-light\">\n\t\t\t<div class=\"content-lg container\">\"\"\")\nfor i in range(1):\n print(\"\"\"<div class=\"row row-space-1\">\"\"\")\n for j in range(0,data2[0][0]):\n print(\"\"\"<div class=\"col-sm-4 sm-margin-b-2\">\n <div class=\"wow fadeInLeft\" data-wow-duration=\".3\" data-wow-delay=\".1s\">\n <!-- Pricing -->\n <div class=\"pricing\">\n <div class=\"margin-b-30\">\n <!--<i class=\"pricing-icon icon-chemistry\"></i>-->\n <h3>\"\"\",data1[j][0],\"\"\"<!--<span> - $</span> 49--></h3>\n <p>\"\"\",data1[j][1],\"\"\"</p>\n </div>\n <ul class=\"list-unstyled pricing-list margin-b-50\">\n <li class=\"pricing-list-item\">Article ID:\"\"\",data1[j][2],\"\"\"</li>\n <li class=\"pricing-list-item\">Published on:24/09/2017</li>\n <li class=\"pricing-list-item\">Published by:\"\"\",data1[j][4],\"\"\"</li>\n <li class=\"pricing-list-item\">Genre:\"\"\",data1[j][3],\"\"\"</li>\n </ul>\n <!--<a href=\"pricing.html\" class=\"btn-theme btn-theme-sm btn-default-bg text-uppercase\">Read</a>-->\n </div>\n <!-- End Pricing -->\n </div>\n </div>\"\"\")\n print(\"\"\"</div><!--// end row -->\"\"\")\nprint(\"\"\"</div>\n\t\t</div>\n\t\t<!-- End Pricing -->\n\n\t\t<!-- Testimonials -->\n\t <!-- <div class=\"content-lg container\">\n\t\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-sm-9\">\n\t\t\t\t\t<h2>Why Customers Are Choosing Asentus?</h2>\n\n\t\t\t\t\t<!-- Swiper Testimonials -->\n\t\t\t\t<!-- <div class=\"swiper-slider swiper-testimonials\">\n\t\t\t\t\t\t<!-- Swiper Wrapper -->\n\t\t\t\t <!-- <div class=\"swiper-wrapper\">\n\t\t\t\t\t\t\t<div class=\"swiper-slide\">\n\t\t\t\t\t\t\t\t<blockquote class=\"blockquote\">\n\t\t\t\t\t\t\t\t\t<div class=\"margin-b-20\">\n\t\t\t\t\t\t\t\t\t\tLorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incididunt ut laboret dolore magna aliqua. Ut enim minim veniam exercitation laboris ut siad consequat siad minim enum esqudiat dolore.\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"margin-b-20\">\n\t\t\t\t\t\t\t\t\t\tLorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incididunt ut laboret tempor incididunt dolore magna consequat siad minim aliqua.\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<p><span class=\"fweight-700 color-link\">Joh Milner</span>, Metronic Customer</p>\n\t\t\t\t\t\t\t\t</blockquote>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"swiper-slide\">\n\t\t\t\t\t\t\t\t<blockquote class=\"blockquote\">\n\t\t\t\t\t\t\t\t\t<div class=\"margin-b-20\">\n\t\t\t\t\t\t\t\t\t\tDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"margin-b-20\">\n\t\t\t\t\t\t\t\t\t\tUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<p><span class=\"fweight-700 color-link\">Alex Clarson</span>, Metronic Customer</p>\n\t\t\t\t\t\t\t\t</blockquote>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<!-- End Swiper Wrapper -->\n\n\t\t\t\t\t\t<!-- Pagination -->\n<!--<div class=\"swiper-testimonials-pagination\"></div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<!-- End Swiper Testimonials -->\n\t\t\t <!-- </div>\n\t\t\t</div>\n\t\t\t<!--// end row -->\n\t <!-- </div>-->\n\t\t<!-- End Testimonials -->\n\n\t\t<!-- Clients -->\n\t\t<!--<div class=\"bg-color-sky-light\">\n\t\t\t<div class=\"content-lg container\">\n\t\t\t\t<!-- Swiper Clients -->\n\t\t\t <!-- <div class=\"swiper-slider swiper-clients\">\n\t\t\t\t\t<!-- Swiper Wrapper -->\n\t\t\t\t <!-- <div class=\"swiper-wrapper\">\n\t\t\t\t\t\t<div class=\"swiper-slide\">\n\t\t\t\t\t\t\t<img class=\"swiper-clients-img\" src=\"/img/clients/01.png\" alt=\"Clients Logo\">\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"swiper-slide\">\n\t\t\t\t\t\t\t<img class=\"swiper-clients-img\" src=\"/img/clients/02.png\" alt=\"Clients Logo\">\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"swiper-slide\">\n\t\t\t\t\t\t\t<img class=\"swiper-clients-img\" src=\"/img/clients/03.png\" alt=\"Clients Logo\">\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"swiper-slide\">\n\t\t\t\t\t\t\t<img class=\"swiper-clients-img\" src=\"/img/clients/04.png\" alt=\"Clients Logo\">\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"swiper-slide\">\n\t\t\t\t\t\t\t<img class=\"swiper-clients-img\" src=\"/img/clients/05.png\" alt=\"Clients Logo\">\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"swiper-slide\">\n\t\t\t\t\t\t\t<img class=\"swiper-clients-img\" src=\"/img/clients/06.png\" alt=\"Clients Logo\">\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<!-- End Swiper Wrapper -->\n\t\t\t <!-- </div>\n\t\t\t\t<!-- End Swiper Clients -->\n\t\t <!-- </div>\n\t\t</div>\n\t\t<!-- End Clients -->\n\t\t<!--========== END PAGE LAYOUT ==========-->\n\n\t\t<!--========== FOOTER ==========-->\n\t <footer class=\"footer\">\n\t\t\t<!-- Links -->\n\t\t\t<div class=\"footer-seperator\">\n\t\t\t\t<div class=\"content-lg container\">\n\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t<div class=\"col-sm-2 sm-margin-b-50\">\n\t\t\t\t\t\t\t<!-- List -->\n\t\t\t\t\t <!-- <ul class=\"list-unstyled footer-list\">\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Home</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">About</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Products</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Pricing</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Clients</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Careers</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Contact</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Terms</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t\t<!-- End List -->\n\t\t\t\t\t <!-- </div>\n\t\t\t\t\t\t<div class=\"col-sm-4 sm-margin-b-30\">\n\t\t\t\t\t\t\t<!-- List -->\n\t\t\t\t\t\t <!-- <ul class=\"list-unstyled footer-list\">\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Twitter</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Facebook</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Instagram</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">YouTube</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t\t<!-- End List -->\n\t\t\t\t\t\t</div>\n\t\t\t\t\t <div class=\"col-sm-5 sm-margin-b-30\">\n\t\t\t\t\t\t <form action=\"articles2.py\" method=\"post\">\n <h2 class=\"color-white\">ENTER ARTICLE ID TO READ IT</h2>\n <input type=\"numeric\" class=\"form-control footer-input margin-b-20\" placeholder=\"*ARTICLE ID\" required name=\"id\">\n <button type=\"submit\" target=\"_blank\" class=\"btn-theme btn-theme-sm btn-base-bg text-uppercase\">READ</button>\n </div>\n\t\t\t\t\t\t\n\t\t\t\t\t</div>\n\t\t\t\t\t<!--// end row -->\n\t\t\t<!-- </div>\n\t\t\t</div> -->\n\t\t\t<!-- End Links -->\n\n\t\t\t<!-- Copyright -->\n\t\t\t<!--<div class=\"content container\">\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<div class=\"col-xs-6\">\n\t\t\t\t\t\t<img class=\"footer-logo\" src=\"/img/logo.png\" alt=\"Asentus Logo\">\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"col-xs-6 text-right\">\n\t\t\t\t\t\t<p class=\"margin-b-0\"><a class=\"color-base fweight-700\" href=\"http://keenthemes.com/preview/asentus/\">Asentus</a> Theme Powered by: <a class=\"color-base fweight-700\" href=\"http://www.keenthemes.com/\">KeenThemes.com</a></p>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<!--// end row -->\n\t\t\t</div>\n\t\t\t<!-- End Copyright -->\n\t\t</footer>\n\t\t<!--========== END FOOTER ==========-->\n\n\t\t<!-- Back To Top -->\n\t\t<a href=\"javascript:void(0);\" class=\"js-back-to-top back-to-top\">Top</a>\n\n\t\t<!-- JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->\n\t\t<!-- CORE PLUGINS -->\n\t\t<script src=\"/vendor/jquery.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery-migrate.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/bootstrap/js/bootstrap.min.js\" type=\"text/javascript\"></script>\n\n\t\t<!-- PAGE LEVEL PLUGINS -->\n\t\t<script src=\"/vendor/jquery.easing.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery.back-to-top.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery.smooth-scroll.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery.wow.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery.parallax.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/swiper/js/swiper.jquery.min.js\" type=\"text/javascript\"></script>\n\n\t\t<!-- PAGE LEVEL SCRIPTS -->\n\t\t<script src=\"/js/layout.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/js/components/wow.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/js/components/swiper.min.js\" type=\"text/javascript\"></script>\n\n\t</body>\n\t<!-- END BODY -->\n</html>\"\"\")\n" }, { "alpha_fraction": 0.6674233675003052, "alphanum_fraction": 0.7014756202697754, "avg_line_length": 38.8636360168457, "blob_id": "a39a4cc79e72b3db20b420e7ae504125b2172184", "content_id": "e29a84b2216e986b24955e955ed2cdd3813a02bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 223, "num_lines": 22, "path": "/HTML/cgi-bin/verifying.py", "repo_name": "tilakbabu/test", "src_encoding": "UTF-8", "text": "import cgi,cgitb,os,sqlite3\ncgitb.enable()\nform=cgi.FieldStorage()\nid1=form.getvalue('id')\nconn=sqlite3.connect('e-articles.db')\nc=conn.execute(\"select Area from SArticles where Aid=?\",(id1,))\nc1=c.fetchall()\nd=conn.execute(\"select count(Farea) from Faculty where Farea=?\",(c1[0][0],))\nd1=d.fetchall()\nn=d1[0][0]\nd2=conn.execute(\"select count1 from SArticles where Aid=?\",(id1,))\nd3=d2.fetchall()\nm=d3[0][0]\nif m==(int)(n/2):\n conn.execute(\"update SArticles set status='accepted' where Aid=?\",(id1,))\nelse:\n conn.execute(\"update SArticles set count1=count1+1 where Aid=?\",(id1,))\nconn.commit()\nconn.close()\nprint(\"Content-type:text/html\")\nprint()\nprint(\"\"\"<html><h1>The Article has been accepted by you<br>will be available for all the users if atleast half of the faculty from the same genre accepted it</h1><br><a href=\"fhome.py\"><h2>Return to Home</h2></a></html>\"\"\")\n\n\n\n\n" }, { "alpha_fraction": 0.681098222732544, "alphanum_fraction": 0.6927138566970825, "avg_line_length": 34.074073791503906, "blob_id": "9ffbc67d3275bede668a7acac0b57e683bd72e3c", "content_id": "81bd8cf75824145218caaa8a8bd8d921baabd9bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 947, "license_type": "no_license", "max_line_length": 217, "num_lines": 27, "path": "/HTML/cgi-bin/spublishing.py", "repo_name": "tilakbabu/test", "src_encoding": "UTF-8", "text": "import cgi,cgitb,os,sqlite3\ncgitb.enable()\nform=cgi.FieldStorage()\naname=form.getvalue('aname')\ngenre=form.getvalue('aos')\ndesc=form.getvalue('desc')\ncontent=form.getvalue('file')\nemail=\"\"\nstatus=\"request pending\"\ncount1=0\naid=form.getvalue('aid')\nhandler = {}\nif 'HTTP_COOKIE' in os.environ:\n cookies = os.environ['HTTP_COOKIE']\n cookies = cookies.split('; ')\n for cookie in cookies:\n cookie = cookie.split('=')\n handler[cookie[0]] = cookie[1]\nfor k in handler:\n email=handler[k]\nconn=sqlite3.connect('e-articles.db')\nconn.execute(\"insert into SArticles values(?,?,?,?,?,?,?,?)\",(aid,aname,genre,content,desc,email,status,count1))\nprint(\"Content-type:text/html\")\nprint()\nprint(\"\"\"<html><h1>Your article has been sent to Renowned professors.<br>You have to wait until it is accepted by corresponding professor of your genre</h1><br><a href=\"shome.py\"><h1>Return to Home</h2></a></html>\"\"\")\nconn.commit()\nconn.close()\n" }, { "alpha_fraction": 0.5417868494987488, "alphanum_fraction": 0.553591787815094, "avg_line_length": 45.8100471496582, "blob_id": "9276222ba0ee4f03ceb7f0b166393a7ad4bfc278", "content_id": "162e5b9b04eb665e0694feb6f06ca48135cc1b9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29818, "license_type": "no_license", "max_line_length": 310, "num_lines": 637, "path": "/HTML/cgi-bin/registration.py", "repo_name": "tilakbabu/test", "src_encoding": "UTF-8", "text": "import cgi,cgitb,os\ncgitb.enable()\nform=cgi.FieldStorage()\nSid=form.getvalue('id')\nSname=form.getvalue('name')\nSbranch=form.getvalue('dept')\nSarea=form.getvalue('aos')\nSpassword=form.getvalue('password')\nSphoneno=form.getvalue('phno')\nS_email=form.getvalue('email')\na=form.getvalue('actype')\nimport sqlite3 \nconn=sqlite3.connect(\"e-articles.db\")\nif a=='f':\n\td=conn.execute(\"select F_email from Faculty where F_email=?\",(S_email,))\n\tdata=d.fetchall()\n\tif len(data)==0:\n\t\tconn.execute(\"insert into Faculty values(?,?,?,?,?,?,?)\",(Sid,Sname,Sbranch,Sarea,Spassword,Sphoneno,S_email))\n\t\t\"\"\"import smtplib\n\t\tfrom email.mime.multipart import MIMEMultipart\n\t\tfrom email.mime.base import MIMEBase\n\t\tfrom email.mime.text import MIMEText\n\t\tfrom email.utils import COMMASPACE, formatdate\n\t\tfrom email import encoders\n\t\timport datetime\n\t\tsmtpUser = '[email protected]'\n\t\tsmtpPass = 'bdy@12345'\n\t\tCOMMASPACE = ', '\n\n\t\tdef sendMail(to, subject, text, files=[]):\n\t\t\tassert type(to)==list\n\t\t\tassert type(files)==list\n\n\t\t\tmsg = MIMEMultipart()\n\t\t\tmsg['From'] = smtpUser\n\t\t\tmsg['To'] = COMMASPACE.join(to)\n\t\t\tmsg['Date'] = formatdate(localtime=True)\n\t\t\tmsg['Subject'] = 'Mail sending Test'\n\n\t\t\tmsg.attach( MIMEText(text) )\n\n\t\t\tfor file in files:\n\t\t\t\tpart = MIMEBase('application', \"octet-stream\")\n\t\t\t\tpart.set_payload( open(file,\"rb\").read() )\n\t\t\t\tencoders.encode_base64(part)\n\t\t\t\tpart.add_header('Content-Disposition', 'attachment; filename=\"%s\"'\n\t\t\t\t\t\t\t % os.path.basename(file))\n\t\t\t\tmsg.attach(part)\n\n\t\t\tserver = smtplib.SMTP('smtp.gmail.com:587')\n\t\t\tserver.ehlo_or_helo_if_needed()\n\t\t\tserver.starttls()\n\t\t\tserver.ehlo_or_helo_if_needed()\n\t\t\tserver.login(smtpUser,smtpPass)\n\t\t\tserver.sendmail(smtpUser, to, msg.as_string())\n\t\t\tprint ('Done')\n\t\t\tserver.quit()\n\n\t\tsendMail( [S_email],'Hi Friend', 'Hello', [])\"\"\"\n\t\tprint(\"Content-type:text/html\")\n\t\tprint()\n\t\tprint(\"\"\"<!DOCTYPE html>\n<!-- ==============================\n Project: Metronic \"Asentus\" Frontend Freebie - Responsive HTML Template Based On Twitter Bootstrap 3.3.4\n Version: 1.0\n Author: KeenThemes\n Primary use: Corporate, Business Themes.\n Email: [email protected]\n Follow: http://www.twitter.com/keenthemes\n Like: http://www.facebook.com/keenthemes\n Website: http://www.keenthemes.com\n Premium: Premium Metronic Admin Theme: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes\n================================== -->\n<html lang=\"en\" class=\"no-js\">\n <!-- BEGIN HEAD -->\n <head>\n <meta charset=\"utf-8\"/>\n <title>E-ARTICLES</title>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta content=\"width=device-width, initial-scale=1\" name=\"viewport\"/>\n <meta content=\"\" name=\"description\"/>\n <meta content=\"\" name=\"author\"/>\n\n <!-- GLOBAL MANDATORY STYLES -->\n <link href=\"http://fonts.googleapis.com/css?family=Hind:300,400,500,600,700\" rel=\"stylesheet\" type=\"text/css\">\n <link href=\"/vendor/simple-line-icons/simple-line-icons.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"/vendor/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\n <!-- PAGE LEVEL PLUGIN STYLES -->\n <link href=\"/css/animate.css\" rel=\"stylesheet\">\n\n <!-- THEME STYLES -->\n <link href=\"/css/layout.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\n <!-- Favicon -->\n <link rel=\"shortcut icon\" href=\"favicon.ico\"/>\n </head>\n <!-- END HEAD -->\n\n <!-- BODY -->\n <body>\n\n <!--========== HEADER ==========-->\n <header class=\"header navbar-fixed-top\">\n <!-- Navbar -->\n <nav class=\"navbar\" role=\"navigation\">\n <div class=\"container\">\n <!-- Brand and toggle get grouped for better mobile display -->\n <div class=\"menu-container\">\n <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".nav-collapse\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"toggle-icon\"></span>\n </button>\n\n <!-- Logo -->\n <div class=\"logo\">\n <a class=\"logo-wrap\" href=\"/index.html\">\n <img class=\"logo-img logo-img-main\" src=\"/img/logo.png\" alt=\"Asentus Logo\">\n <img class=\"logo-img logo-img-active\" src=\"/img/logo-dark.png\" alt=\"Asentus Logo\">\n </a>\n </div>\n <!-- End Logo -->\n </div>\n\n <!-- Collect the nav links, forms, and other content for toggling -->\n <div class=\"collapse navbar-collapse nav-collapse\">\n <div class=\"menu-container\">\n <ul class=\"navbar-nav navbar-nav-right\">\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"/index.html\">Home</a></li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"#\">Login</a></li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"/registration.html\">Register</a></li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"/contact.html\">contact</a></li>\n \n </ul>\n </div>\n </div>\n <!-- End Navbar Collapse -->\n </div>\n </nav>\n <!-- Navbar -->\n </header>\n <!--========== END HEADER ==========-->\n\n <!--========== PARALLAX ==========-->\n <div class=\"parallax-window\" data-parallax=\"scroll\" data-image-src=\"/img/1920x1080/01.jpg\">\n <div class=\"parallax-content container\">\n <h1 class=\"carousel-title\">Sign In here</h1>\n <p>To share your valuable information to entire world through our website</p>\n </div>\n </div>\n <!--========== PARALLAX ==========-->\n\n <!--========== PAGE LAYOUT ==========-->\n <!-- Contact List -->\n <!-- <div class=\"section-seperator\">\n <div class=\"content-lg container\">\n <div class=\"row\">\n <!-- Contact List -->\n <!-- <div class=\"col-sm-4 sm-margin-b-50\">\n <div class=\"wow fadeInLeft\" data-wow-duration=\".3\" data-wow-delay=\".3s\">\n <h3><a href=\"#\">New York</a> <span class=\"text-uppercase margin-l-20\">Head Office</span></h3>\n <p>Lorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incdidunt ut laboret dolor magna ut consequat siad esqudiat dolor</p>\n <ul class=\"list-unstyled contact-list\">\n <li><i class=\"margin-r-10 color-base icon-call-out\"></i> 1 012 3456 7890</li>\n <li><i class=\"margin-r-10 color-base icon-envelope\"></i> [email protected]</li>\n </ul>\n </div>\n </div>\n <!-- End Contact List -->\n\n <!-- Contact List -->\n <!-- <div class=\"col-sm-4 sm-margin-b-50\">\n <div class=\"wow fadeInLeft\" data-wow-duration=\".3\" data-wow-delay=\".3s\">\n <h3><a href=\"#\">London</a> <span class=\"text-uppercase margin-l-20\">Operation</span></h3>\n <p>Lorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incdidunt ut laboret dolor magna ut consequat siad esqudiat dolor</p>\n <ul class=\"list-unstyled contact-list\">\n <li><i class=\"margin-r-10 color-base icon-call-out\"></i> 44 77 3456 7890</li>\n <li><i class=\"margin-r-10 color-base icon-envelope\"></i> [email protected]</li>\n </ul>\n </div>\n </div>\n <!-- End Contact List -->\n\n <!-- Contact List -->\n <!-- <div class=\"col-sm-4 sm-margin-b-50\">\n <div class=\"wow fadeInLeft\" data-wow-duration=\".3\" data-wow-delay=\".3s\">\n <h3><a href=\"#\">Singapore</a> <span class=\"text-uppercase margin-l-20\">Finance</span></h3>\n <p>Lorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incdidunt ut laboret dolor magna ut consequat siad esqudiat dolor</p>\n <ul class=\"list-unstyled contact-list\">\n <li><i class=\"margin-r-10 color-base icon-call-out\"></i> 50 012 456 7890</li>\n <li><i class=\"margin-r-10 color-base icon-envelope\"></i> [email protected]</li>\n </ul>\n </div>\n </div>\n <!-- End Contact List -->\n </div>\n <!--// end row -->\n </div>\n </div>\n <!-- End Contact List -->\n\n <!-- Google Map -->\n <!-- <div id=\"map\" class=\"map height-400\"></div>-->\n\n <!-- Promo Section -->\n <!-- <div class=\"promo-section overflow-h\">\n <div class=\"container\">\n <div class=\"clearfix\">\n <div class=\"ver-center\">\n <div class=\"ver-center-aligned\">\n <div class=\"promo-section-col\">\n <h2>Our Clients</h2>\n <p>Lorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incididunt ut laboret dolore magna aliqua enim minim veniam exercitation ipsum dolor sit amet consectetur adipiscing elit sed tempor incididunt ut laboret dolore magna aliqua enim minim veniam exercitation</p>\n <p>Ipsum dolor sit amet consectetur adipiscing elit sed tempor incididut ut sead laboret dolore magna aliqua enim minim veniam exercitation ipsum dolor sit amet consectetur adipiscing</p>\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class=\"promo-section-img-right\">\n <img class=\"img-responsive\" src=\"/img/970x970/01.jpg\" alt=\"Content Image\">\n </div>\n </div>-->\n <!-- End Promo Section -->\n <!--========== END PAGE LAYOUT ==========-->\n\n <!--========== FOOTER ==========-->\n <footer class=\"footer\">\n <!-- Links -->\n <div class=\"footer-seperator\">\n <div class=\"content-lg container\">\n <div class=\"row\">\n <!-- <div class=\"col-sm-2 sm-margin-b-50\">\n <!-- List -->\n <!-- <ul class=\"list-unstyled footer-list\">\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Home</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">About</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Products</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Pricing</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Clients</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Careers</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Contact</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Terms</a></li>\n </ul>\n <!-- End List -->\n <!-- </div>\n <div class=\"col-sm-4 sm-margin-b-30\">\n <!-- List -->\n <!-- <ul class=\"list-unstyled footer-list\">\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Twitter</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Facebook</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Instagram</a></li>\n <li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">YouTube</a></li>\n </ul>\n <!-- End List -->\n </div>\n <div class=\"col-sm-5 sm-margin-b-30\" align=\"center\">\n\t\t\t\t\t\t\t<form action=\"loginvali.py\" method=\"post\">\n\t\t\t\t\t\t\t\t<h2 class=\"color-white\">Sign in</h2>\n\t\t\t\t\t\t\t\t<!--<input type=\"text\" class=\"form-control footer-input margin-b-20\" placeholder=\"Name\" required>-->\n\t\t\t\t\t\t\t\t<select name=\"actype\" class=\"form-control footer-input margin-b-20\">\n\t\t\t\t\t\t\t\t <option selected>Select Account Type</option>\n\t\t\t\t\t\t\t\t\t<option value=\"f\" >Faculty</option>\n\t\t\t\t\t\t\t\t\t<option value=\"s\" >Student</option>\n\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t<input type=\"email\" class=\"form-control footer-input margin-b-20\" placeholder=\"* Email\" required name=\"email\">\n\t\t\t\t\t\t\t\t<input type=\"password\" class=\"form-control footer-input margin-b-20\" placeholder=\"* Password\" required name=\"password\">\n\t\t\t\t\t\t\t <!-- <textarea class=\"form-control footer-input margin-b-30\" rows=\"6\" placeholder=\"Message\" required></textarea>-->\n\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"btn-theme btn-theme-sm btn-base-bg text-uppercase\">Sign in</button><br><br>\n\t\t\t\t\t\t\t\t<a href=\"/registration.html\">New user,Register here</a>\n\t\t\t\t\t\t\t</form>\n </div>\n </div>\n <!--// end row -->\n </div>\n </div>\n <!-- End Links -->\n\n <!-- Copyright -->\n <div class=\"content container\">\n <div class=\"row\">\n <div class=\"col-xs-6\">\n <img class=\"footer-logo\" src=\"/img/logo.png\" alt=\"Asentus Logo\">\n </div>\n <div class=\"col-xs-6 text-right\">\n <!--<p class=\"margin-b-0\"><a class=\"color-base fweight-700\" href=\"http://keenthemes.com/preview/asentus/\">Asentus</a> Theme Powered by: <a class=\"color-base fweight-700\" href=\"http://www.keenthemes.com/\">KeenThemes.com</a></p>-->\n </div>\n </div>\n <!--// end row -->\n </div>\n <!-- End Copyright -->\n </footer>\n <!--========== END FOOTER ==========-->\n\n <!-- Back To Top -->\n <a href=\"javascript:void(0);\" class=\"js-back-to-top back-to-top\">Top</a>\n\n <!-- JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->\n <!-- CORE PLUGINS -->\n <script src=\"/vendor/jquery.min.js\" type=\"text/javascript\"></script>\n <script src=\"/vendor/jquery-migrate.min.js\" type=\"text/javascript\"></script>\n <script src=\"/vendor/bootstrap/js/bootstrap.min.js\" type=\"text/javascript\"></script>\n\n <!-- PAGE LEVEL PLUGINS -->\n <script src=\"/vendor/jquery.easing.js\" type=\"text/javascript\"></script>\n <script src=\"/vendor/jquery.back-to-top.js\" type=\"text/javascript\"></script>\n <script src=\"/vendor/jquery.smooth-scroll.js\" type=\"text/javascript\"></script>\n <script src=\"/vendor/jquery.wow.min.js\" type=\"text/javascript\"></script>\n <script src=\"/vendor/jquery.parallax.min.js\" type=\"text/javascript\"></script>\n\n <!-- PAGE LEVEL SCRIPTS -->\n <script src=\"/js/layout.min.js\" type=\"text/javascript\"></script>\n <script src=\"/js/components/wow.min.js\" type=\"text/javascript\"></script>\n <script src=\"/js/components/gmap.min.js\" type=\"text/javascript\"></script>\n <script src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyBsXUGTFS09pLVdsYEE9YrO2y4IAncAO2U&amp;callback=initMap\" async defer></script>\n\n </body>\n <!-- END BODY -->\n</html>\n\t\t\"\"\")\n\telse:\n\t\tprint(\"Content-type:text/html\")\n\t\tprint()\n\t\tprint(\"\"\"<h1><a href=\"/registration.html\">Registration Failed Username already exists</a><h1>\"\"\")\n\t\nelif a==\"s\":\n\td=conn.execute(\"select S_email from Students where S_email=?\",(S_email,))\n\tdata=d.fetchall()\n\tif len(data)==0:\n\t\t\"\"\"import smtplib\n\t\tfrom email.mime.multipart import MIMEMultipart\n\t\tfrom email.mime.base import MIMEBase\n\t\tfrom email.mime.text import MIMEText\n\t\tfrom email.utils import COMMASPACE, formatdate\n\t\tfrom email import encoders\n\t\timport datetime\n\t\tsmtpUser = '[email protected]'\n\t\tsmtpPass = 'bdy@12345'\n\t\tCOMMASPACE = ', '\n\n\t\tdef sendMail(to, subject, text, files=[]):\n\t\t\tassert type(to)==list\n\t\t\tassert type(files)==list\n\n\t\t\tmsg = MIMEMultipart()\n\t\t\tmsg['From'] = smtpUser\n\t\t\tmsg['To'] = COMMASPACE.join(to)\n\t\t\tmsg['Date'] = formatdate(localtime=True)\n\t\t\tmsg['Subject'] = 'Mail sending Test'\n\n\t\t\tmsg.attach( MIMEText(text) )\n\n\t\t\tfor file in files:\n\t\t\t\tpart = MIMEBase('application', \"octet-stream\")\n\t\t\t\tpart.set_payload( open(file,\"rb\").read() )\n\t\t\t\tencoders.encode_base64(part)\n\t\t\t\tpart.add_header('Content-Disposition', 'attachment; filename=\"%s\"'\n\t\t\t\t\t\t\t % os.path.basename(file))\n\t\t\t\tmsg.attach(part)\n\n\t\t\tserver = smtplib.SMTP('smtp.gmail.com:587')\n\t\t\tserver.ehlo_or_helo_if_needed()\n\t\t\tserver.starttls()\n\t\t\tserver.ehlo_or_helo_if_needed()\n\t\t\tserver.login(smtpUser,smtpPass)\n\t\t\tserver.sendmail(smtpUser, to, msg.as_string())\n\t\t\tprint ('Done')\n\t\t\tserver.quit()\n\n\t\tsendMail( [S_email],'Hi Friend', 'Hello', [])\"\"\"\n\t\tconn.execute(\"insert into Students values(?,?,?,?,?,?,?)\",(Sid,Sname,Sbranch,Sarea,Spassword,Sphoneno,S_email))\n\t\tprint(\"Content-type:text/html\")\n\t\tprint()\n\t\tprint(\"\"\"<!DOCTYPE html>\n<!-- ==============================\n\tProject: Metronic \"Asentus\" Frontend Freebie - Responsive HTML Template Based On Twitter Bootstrap 3.3.4\n\tVersion: 1.0\n\tAuthor: KeenThemes\n\tPrimary use: Corporate, Business Themes.\n\tEmail: [email protected]\n\tFollow: http://www.twitter.com/keenthemes\n\tLike: http://www.facebook.com/keenthemes\n\tWebsite: http://www.keenthemes.com\n\tPremium: Premium Metronic Admin Theme: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes\n================================== -->\n<html lang=\"en\" class=\"no-js\">\n\t<!-- BEGIN HEAD -->\n\t<head>\n\t\t<meta charset=\"utf-8\"/>\n\t\t<title>E-ARTICLES</title>\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta content=\"width=device-width, initial-scale=1\" name=\"viewport\"/>\n\t\t<meta content=\"\" name=\"description\"/>\n\t\t<meta content=\"\" name=\"author\"/>\n\n\t\t<!-- GLOBAL MANDATORY STYLES -->\n\t\t<link href=\"http://fonts.googleapis.com/css?family=Hind:300,400,500,600,700\" rel=\"stylesheet\" type=\"text/css\">\n\t\t<link href=\"/vendor/simple-line-icons/simple-line-icons.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\t\t<link href=\"/vendor/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\n\t\t<!-- PAGE LEVEL PLUGIN STYLES -->\n\t\t<link href=\"/css/animate.css\" rel=\"stylesheet\">\n\n\t\t<!-- THEME STYLES -->\n\t\t<link href=\"/css/layout.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n\n\t\t<!-- Favicon -->\n\t\t<link rel=\"shortcut icon\" href=\"favicon.ico\"/>\n\t</head>\n\t<!-- END HEAD -->\n\n\t<!-- BODY -->\n\t<body>\n\n\t\t<!--========== HEADER ==========-->\n\t\t<header class=\"header navbar-fixed-top\">\n\t\t\t<!-- Navbar -->\n\t\t\t<nav class=\"navbar\" role=\"navigation\">\n\t\t\t\t<div class=\"container\">\n\t\t\t\t\t<!-- Brand and toggle get grouped for better mobile display -->\n\t\t\t\t\t<div class=\"menu-container\">\n\t\t\t\t\t\t<button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".nav-collapse\">\n\t\t\t\t\t\t\t<span class=\"sr-only\">Toggle navigation</span>\n\t\t\t\t\t\t\t<span class=\"toggle-icon\"></span>\n\t\t\t\t\t\t</button>\n\n\t\t\t\t\t\t<!-- Logo -->\n\t\t\t\t\t\t<div class=\"logo\">\n\t\t\t\t\t\t\t<a class=\"logo-wrap\" href=\"index.html\">\n\t\t\t\t\t\t\t\t<img class=\"logo-img logo-img-main\" src=\"/img/logo.png\" alt=\"Asentus Logo\">\n\t\t\t\t\t\t\t\t<img class=\"logo-img logo-img-active\" src=\"/img/logo-dark.png\" alt=\"Asentus Logo\">\n\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<!-- End Logo -->\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<!-- Collect the nav links, forms, and other content for toggling -->\n\t\t\t\t\t<div class=\"collapse navbar-collapse nav-collapse\">\n\t\t\t\t\t\t<div class=\"menu-container\">\n\t\t\t\t\t\t\t<ul class=\"navbar-nav navbar-nav-right\">\n\t\t\t\t\t\t\t\t<li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"index.html\">Home</a></li>\n\t\t\t\t\t\t\t\t<li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"#\">Login</a></li>\n\t\t\t\t\t\t\t\t<li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"/registration.html\">Register</a></li>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover active\" href=\"/contact.html\">Contact</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<!-- End Navbar Collapse -->\n\t\t\t\t</div>\n\t\t\t</nav>\n\t\t\t<!-- Navbar -->\n\t\t</header>\n\t\t<!--========== END HEADER ==========-->\n\n\t\t<!--========== PARALLAX ==========-->\n\t <div class=\"parallax-window\" data-parallax=\"scroll\" data-image-src=\"/img/1920x1080/01.jpg\">\n\t\t\t<div class=\"parallax-content container\">\n\t\t\t\t<h1 class=\"carousel-title\">Sign In here</h1>\n\t\t\t\t<p>To share your valuable information to entire world through our website</p>\n\t\t\t</div>\n\t\t</div>\n\t\t<!--========== PARALLAX ==========-->\n\n\t\t<!--========== PAGE LAYOUT ==========-->\n\t\t<!-- Contact List -->\n\t <!-- <div class=\"section-seperator\">\n\t\t\t<div class=\"content-lg container\">\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<!-- Contact List -->\n\t\t\t <!-- <div class=\"col-sm-4 sm-margin-b-50\">\n\t\t\t\t\t\t<div class=\"wow fadeInLeft\" data-wow-duration=\".3\" data-wow-delay=\".3s\">\n\t\t\t\t\t\t\t<h3><a href=\"#\">New York</a> <span class=\"text-uppercase margin-l-20\">Head Office</span></h3>\n\t\t\t\t\t\t\t<p>Lorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incdidunt ut laboret dolor magna ut consequat siad esqudiat dolor</p>\n\t\t\t\t\t\t\t<ul class=\"list-unstyled contact-list\">\n\t\t\t\t\t\t\t\t<li><i class=\"margin-r-10 color-base icon-call-out\"></i> 1 012 3456 7890</li>\n\t\t\t\t\t\t\t\t<li><i class=\"margin-r-10 color-base icon-envelope\"></i> [email protected]</li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<!-- End Contact List -->\n\n\t\t\t\t\t<!-- Contact List -->\n\t\t\t <!-- <div class=\"col-sm-4 sm-margin-b-50\">\n\t\t\t\t\t\t<div class=\"wow fadeInLeft\" data-wow-duration=\".3\" data-wow-delay=\".3s\">\n\t\t\t\t\t\t\t<h3><a href=\"#\">London</a> <span class=\"text-uppercase margin-l-20\">Operation</span></h3>\n\t\t\t\t\t\t\t<p>Lorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incdidunt ut laboret dolor magna ut consequat siad esqudiat dolor</p>\n\t\t\t\t\t\t\t<ul class=\"list-unstyled contact-list\">\n\t\t\t\t\t\t\t\t<li><i class=\"margin-r-10 color-base icon-call-out\"></i> 44 77 3456 7890</li>\n\t\t\t\t\t\t\t\t<li><i class=\"margin-r-10 color-base icon-envelope\"></i> [email protected]</li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<!-- End Contact List -->\n\n\t\t\t\t\t<!-- Contact List -->\n\t\t\t <!-- <div class=\"col-sm-4 sm-margin-b-50\">\n\t\t\t\t\t\t<div class=\"wow fadeInLeft\" data-wow-duration=\".3\" data-wow-delay=\".3s\">\n\t\t\t\t\t\t\t<h3><a href=\"#\">Singapore</a> <span class=\"text-uppercase margin-l-20\">Finance</span></h3>\n\t\t\t\t\t\t\t<p>Lorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incdidunt ut laboret dolor magna ut consequat siad esqudiat dolor</p>\n\t\t\t\t\t\t\t<ul class=\"list-unstyled contact-list\">\n\t\t\t\t\t\t\t\t<li><i class=\"margin-r-10 color-base icon-call-out\"></i> 50 012 456 7890</li>\n\t\t\t\t\t\t\t\t<li><i class=\"margin-r-10 color-base icon-envelope\"></i> [email protected]</li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<!-- End Contact List -->\n\t\t\t\t</div>\n\t\t\t\t<!--// end row -->\n\t\t\t</div>\n\t\t</div>\n\t\t<!-- End Contact List -->\n\n\t\t<!-- Google Map -->\n\t <!-- <div id=\"map\" class=\"map height-400\"></div>-->\n\n\t\t<!-- Promo Section -->\n\t <!-- <div class=\"promo-section overflow-h\">\n\t\t\t<div class=\"container\">\n\t\t\t\t<div class=\"clearfix\">\n\t\t\t\t\t<div class=\"ver-center\">\n\t\t\t\t\t\t<div class=\"ver-center-aligned\">\n\t\t\t\t\t\t\t<div class=\"promo-section-col\">\n\t\t\t\t\t\t\t\t<h2>Our Clients</h2>\n\t\t\t\t\t\t\t\t<p>Lorem ipsum dolor sit amet consectetur adipiscing elit sed tempor incididunt ut laboret dolore magna aliqua enim minim veniam exercitation ipsum dolor sit amet consectetur adipiscing elit sed tempor incididunt ut laboret dolore magna aliqua enim minim veniam exercitation</p>\n\t\t\t\t\t\t\t\t<p>Ipsum dolor sit amet consectetur adipiscing elit sed tempor incididut ut sead laboret dolore magna aliqua enim minim veniam exercitation ipsum dolor sit amet consectetur adipiscing</p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class=\"promo-section-img-right\">\n\t\t\t\t<img class=\"img-responsive\" src=\"/img/970x970/01.jpg\" alt=\"Content Image\">\n\t\t\t</div>\n\t\t</div>-->\n\t\t<!-- End Promo Section -->\n\t\t<!--========== END PAGE LAYOUT ==========-->\n\n\t\t<!--========== FOOTER ==========-->\n\t\t<footer class=\"footer\">\n\t\t\t<!-- Links -->\n\t\t\t<div class=\"footer-seperator\">\n\t\t\t\t<div class=\"content-lg container\">\n\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t <!-- <div class=\"col-sm-2 sm-margin-b-50\">\n\t\t\t\t\t\t\t<!-- List -->\n\t\t\t\t\t\t <!-- <ul class=\"list-unstyled footer-list\">\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Home</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">About</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Products</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Pricing</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Clients</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Careers</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Contact</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Terms</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t\t<!-- End List -->\n\t\t\t\t\t <!-- </div>\n\t\t\t\t\t\t<div class=\"col-sm-4 sm-margin-b-30\">\n\t\t\t\t\t\t\t<!-- List -->\n\t\t\t\t\t\t <!-- <ul class=\"list-unstyled footer-list\">\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Twitter</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Facebook</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">Instagram</a></li>\n\t\t\t\t\t\t\t\t<li class=\"footer-list-item\"><a class=\"footer-list-link\" href=\"#\">YouTube</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t\t<!-- End List -->\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"col-sm-5 sm-margin-b-30\" align=\"center\">\n\t\t\t\t\t\t\t<form action=\"loginvali.py\" method=\"post\">\n\t\t\t\t\t\t\t\t<h2 class=\"color-white\">Sign in</h2>\n\t\t\t\t\t\t\t\t<!--<input type=\"text\" class=\"form-control footer-input margin-b-20\" placeholder=\"Name\" required>-->\n\t\t\t\t\t\t\t\t<select name=\"actype\" class=\"form-control footer-input margin-b-20\">\n\t\t\t\t\t\t\t\t\t<option selected>Select Account Type</option>\n\t\t\t\t\t\t\t\t\t<option value=\"f\" >Faculty</option>\n\t\t\t\t\t\t\t\t\t<option value=\"s\" >Student</option>\n\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t<input type=\"email\" class=\"form-control footer-input margin-b-20\" placeholder=\"* Email\" required name=\"email\">\n\t\t\t\t\t\t\t\t<input type=\"password\" class=\"form-control footer-input margin-b-20\" placeholder=\"* Password\" required name=\"password\">\n\t\t\t\t\t\t\t\t<!-- <textarea class=\"form-control footer-input margin-b-30\" rows=\"6\" placeholder=\"Message\" required></textarea>-->\n\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"btn-theme btn-theme-sm btn-base-bg text-uppercase\">Sign in</button><br><br>\n\t\t\t\t\t\t\t\t<a href=\"/registration.html\">New user,Register here</a>\n\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<!--// end row -->\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<!-- End Links -->\n\n\t\t\t<!-- Copyright -->\n\t\t\t<div class=\"content container\">\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<div class=\"col-xs-6\">\n\t\t\t\t\t\t<img class=\"footer-logo\" src=\"/img/logo.png\" alt=\"Asentus Logo\">\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"col-xs-6 text-right\">\n\t\t\t\t\t\t<p class=\"margin-b-0\"><a class=\"color-base fweight-700\" href=\"http://keenthemes.com/preview/asentus/\">Asentus</a> Theme Powered by: <a class=\"color-base fweight-700\" href=\"http://www.keenthemes.com/\">KeenThemes.com</a></p>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<!--// end row -->\n\t\t\t</div>\n\t\t\t<!-- End Copyright -->\n\t\t</footer>\n\t\t<!--========== END FOOTER ==========-->\n\n\t\t<!-- Back To Top -->\n\t\t<a href=\"javascript:void(0);\" class=\"js-back-to-top back-to-top\">Top</a>\n\n\t\t<!-- JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->\n\t\t<!-- CORE PLUGINS -->\n\t\t<script src=\"/vendor/jquery.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery-migrate.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/bootstrap/js/bootstrap.min.js\" type=\"text/javascript\"></script>\n\n\t\t<!-- PAGE LEVEL PLUGINS -->\n\t\t<script src=\"/vendor/jquery.easing.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery.back-to-top.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery.smooth-scroll.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery.wow.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/vendor/jquery.parallax.min.js\" type=\"text/javascript\"></script>\n\n\t\t<!-- PAGE LEVEL SCRIPTS -->\n\t\t<script src=\"/js/layout.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/js/components/wow.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"/js/components/gmap.min.js\" type=\"text/javascript\"></script>\n\t\t<script src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyBsXUGTFS09pLVdsYEE9YrO2y4IAncAO2U&amp;callback=initMap\" async defer></script>\n\n\t\t </body>\n\t\t<!-- END BODY -->\n\t\t</html>\"\"\")\n\telse:\n\t\tprint(\"Content-type:text/html\")\n\t\tprint()\n\t\tprint(\"\"\"<h1><a href=\"/registration.html\">Registration Failed Username already exists</a><h1>\"\"\")\nconn.commit()\nconn.close()\n" }, { "alpha_fraction": 0.6620046496391296, "alphanum_fraction": 0.6736596822738647, "avg_line_length": 32, "blob_id": "178019e14ec40e91f8b4e4d212fe7a9a00de9d9d", "content_id": "31a0e4f5ae311635cba9ffc306313ddc19b21b60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 858, "license_type": "no_license", "max_line_length": 116, "num_lines": 26, "path": "/HTML/cgi-bin/fpublishing.py", "repo_name": "tilakbabu/test", "src_encoding": "UTF-8", "text": "import cgi,cgitb,os,sqlite3\ncgitb.enable()\nform=cgi.FieldStorage()\naname=form.getvalue('aname')\ndesc=form.getvalue('desc')\ncontent=form.getvalue('file')\nemail=\"\"\naid=form.getvalue('aid')\nhandler = {}\nif 'HTTP_COOKIE' in os.environ:\n cookies = os.environ['HTTP_COOKIE']\n cookies = cookies.split('; ')\n for cookie in cookies:\n cookie = cookie.split('=')\n handler[cookie[0]] = cookie[1]\nfor k in handler:\n email=handler[k]\nconn=sqlite3.connect('e-articles.db')\nd=conn.execute(\"select Farea from Faculty where F_email=?\",(email,))\ndata=d.fetchall()\nconn.execute(\"insert into Articles values(?,?,?,?,?,?)\",(aid,aname,data[0][0],content,desc,email))\nprint(\"Content-type:text/html\")\nprint()\nprint(\"\"\"<html><h1>Your article has been published</h1><br><a href=\"fhome.py\"><h1>Return to Home</h2></a></html>\"\"\")\nconn.commit()\nconn.close()\n" }, { "alpha_fraction": 0.6677215099334717, "alphanum_fraction": 0.699367105960846, "avg_line_length": 30.600000381469727, "blob_id": "0bed967472d9480310c8efea7b708edf7c9e4b02", "content_id": "e7a5aa4bf486deb7e7a2c10287bbfa874c46f8de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 67, "num_lines": 10, "path": "/HTML/cgi-bin/starticles.py", "repo_name": "tilakbabu/test", "src_encoding": "UTF-8", "text": "import cgi,cgitb,os,sqlite3\ncgitb.enable()\nconn=sqlite3.connect('e-articles.db')\nform=cgi.FieldStorage()\nid1=form.getvalue('id')\nd1=conn.execute(\"select Content from SArticles where Aid=?\",(id1,))\ndata1=d1.fetchall()\nprint(\"Content-type:text/html\")\nprint()\nprint(\"\"\"<html><body>\"\"\",data1[0][0],\"\"\"</body></html>\"\"\")\n" } ]
6
dswanderley/fms
https://github.com/dswanderley/fms
defb289e549300a701754ae106b4d8940dfd8196
73dbfaa4e54497e3ee73b7fe6462228878eb2f12
d9bb8002e94082369199da6db2f7c018c859b119
refs/heads/master
2023-01-02T20:26:06.375858
2020-10-26T21:16:29
2020-10-26T21:16:29
276,942,584
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7875000238418579, "alphanum_fraction": 0.8374999761581421, "avg_line_length": 25.66666603088379, "blob_id": "d62260b65c976026fa3d3251940cd6997433aa08", "content_id": "fd969d8256395cca97906be33e806ba4ad9f316a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 160, "license_type": "no_license", "max_line_length": 105, "num_lines": 6, "path": "/README.md", "repo_name": "dswanderley/fms", "src_encoding": "UTF-8", "text": "# fms\nFish Monitoring System\n\nVISUM Competition 2002\n\nhttps://github.com/visum-summerschool/visum-competition2020/blob/master/leaderboards/final_leaderboard.md\n" }, { "alpha_fraction": 0.5098793506622314, "alphanum_fraction": 0.5294631719589233, "avg_line_length": 33.0476188659668, "blob_id": "1a2cfc642d7186bca7281b6f1585a9bd7d9db0cd", "content_id": "614b1efe604374f18fbb892642ed5156a6696dfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5719, "license_type": "no_license", "max_line_length": 95, "num_lines": 168, "path": "/transforms.py", "repo_name": "dswanderley/fms", "src_encoding": "UTF-8", "text": "import random\nimport torch\nimport kornia\nimport numpy as np\nfrom torchvision.transforms import functional as F\nimport torchvision\nfrom torchvision.transforms import transforms as T\n\ndef _flip_coco_person_keypoints(kps, width):\n flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]\n flipped_data = kps[:, flip_inds]\n flipped_data[..., 0] = width - flipped_data[..., 0]\n # Maintain COCO convention that if visibility == 0, then x, y = 0\n inds = flipped_data[..., 2] == 0\n flipped_data[inds] = 0\n return flipped_data\n\n\nclass Compose(object):\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, image, target):\n for t in self.transforms:\n image, target = t(image, target)\n return image, target\n\nclass RandomHorizontalFlip(object):\n def __init__(self, prob):\n self.prob = prob\n\n def __call__(self, image, target):\n if random.random() < self.prob:\n height, width = image.shape[-2:]\n image = image.flip(-1)\n bbox = target[\"boxes\"]\n bbox[:, [0, 2]] = width - bbox[:, [2, 0]]\n target[\"boxes\"] = bbox\n if \"masks\" in target:\n target[\"masks\"] = target[\"masks\"].flip(-1)\n if \"keypoints\" in target:\n keypoints = target[\"keypoints\"]\n keypoints = _flip_coco_person_keypoints(keypoints, width)\n target[\"keypoints\"] = keypoints\n return image, target\n\nclass RandomBlur(object):\n def __init__(self, prob):\n self.prob = prob\n\n def __call__(self, image, target):\n\n if random.random() < self.prob:\n # add B dimension to image: (C, H, W) to (B, C, H, W)\n blur_image = torch.unsqueeze(image.float(), dim=0) \n # blur the image\n blur = kornia.filters.GaussianBlur2d((11, 11), (10.5, 10.5))\n blur_image = blur(blur_image)\n\n # Debug\n '''\n from matplotlib import pyplot as plt\n plt.figure()\n plt.imshow(image.numpy().transpose(1, 2, 0))\n plt.show()\n plt.figure()\n plt.imshow(blur_image[0].numpy().transpose(1, 2, 0))\n plt.show()\n '''\n image = blur_image[0]\n\n return image, target\n\nclass RandomContrastLuminance(object):\n def __init__(self, prob):\n self.prob = prob\n\n def __call__(self, image, target):\n if random.random() < self.prob:\n\n # Debug\n # from matplotlib import pyplot as plt\n # plt.figure()\n # plt.imshow(image.numpy().transpose(1, 2, 0))\n # plt.show()\n\n # transform to PIL image\n if (image.shape==3):\n image = F.to_pil_image(image)\n # apply brightness to the image\n contrast = T.ColorJitter(brightness=1.0, contrast=0.5, saturation=0.0, hue=0.0)\n image = contrast(image)\n image = F.to_tensor(image)\n\n # Debug\n # plt.figure()\n # plt.imshow(image.numpy().transpose(1, 2, 0))\n # plt.show()\n \n return image, target\n\nclass RandomVerticalFlip(object):\n def __init__(self, prob):\n self.prob = prob\n\n def __call__(self, image, target):\n if random.random() < self.prob:\n height, width = image.shape[-2:]\n image = image.flip(1) # flip img vertically\n bbox = target[\"boxes\"]\n bbox[:, [1, 3]] = height - bbox[:, [3, 1]] # flip bbox upside down\n target[\"boxes\"] = bbox\n\n # Debug\n \"\"\"\n import matplotlib.pyplot as plt\n import matplotlib.patches as pat\n \n if bbox.shape[0] != 0:\n img = image\n fig, ax = plt.subplots(1)\n plt.imshow( img.permute(1, 2, 0) )\n rect = pat.Rectangle([int(bbox[0, 0]), int(bbox[0, 1])], # x, y\n int(bbox[0, 2] - bbox[0, 0]), # w\n int(bbox[0, 3] - bbox[0, 1]), # h\n edgecolor='r', linewidth=3, fill=False)\n ax.add_patch(rect)\n plt.show()\n a = 1\n \"\"\"\n if \"masks\" in target:\n target[\"masks\"] = target[\"masks\"].flip(1) # flip masks upside down\n\n # TODO: check this code\n \"\"\"\n if \"keypoints\" in target:\n keypoints = target[\"keypoints\"]\n keypoints = _flip_coco_person_keypoints(keypoints, height)\n target[\"keypoints\"] = keypoints\n \"\"\"\n return image, target\n\nclass ToTensor(object):\n def __call__(self, image, target):\n image = F.to_tensor(image)\n return image, target\n\n# Data augmentation\ndef get_transform(train):\n transforms = []\n # converts the image, a PIL image, into a PyTorch Tensor\n transforms.append(ToTensor())\n if train:\n # during training, randomly flip the training images\n # and ground-truth for data augmentation\n transforms.append(RandomHorizontalFlip(0.5))\n transforms.append(RandomVerticalFlip(0.5))\n transforms.append(RandomBlur(0.15))\n transforms.append(RandomContrastLuminance(0.15))\n #transforms.append(RandomRotation(1))\n #transforms.append(RandomScale(1))\n \n return Compose(transforms)\n\n# transform for images only (no labels)\ndef get_test_transform():\n # in case you want to insert some transformation in here\n return torchvision.transforms.Compose([torchvision.transforms.ToTensor()])" }, { "alpha_fraction": 0.6373986005783081, "alphanum_fraction": 0.6492102146148682, "avg_line_length": 38.4775276184082, "blob_id": "4d4709fc5dff595e906627cee2ba3ff75244b03e", "content_id": "0d43128f75bdbdc3dfe2a1d17ab0d6efb1dd37d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7027, "license_type": "no_license", "max_line_length": 139, "num_lines": 178, "path": "/train.py", "repo_name": "dswanderley/fms", "src_encoding": "UTF-8", "text": "import os\nimport argparse\nimport torch\nimport torch.utils.data\nimport torchvision\nfrom torchvision.models.detection import FasterRCNN, fasterrcnn_resnet50_fpn\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection.rpn import AnchorGenerator\nfrom torchvision.models.detection.backbone_utils import resnet_fpn_backbone\nfrom engine import train_one_epoch, evaluate\nimport utils\nfrom dataset import Dataset\nfrom transforms import get_transform\nfrom models.backbones import get_backbone, get_model\nfrom models.fpn import GroupedPyramidFeatures\nfrom models.deeplab import DeepLabv3Plus\n\n\n\"\"\" Training parameters \"\"\"\n# Save condition\nval_mAP = 0\n\n\n\"\"\" Training script \"\"\"\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n # Training parameters\n parser.add_argument(\"--backbone\", type=str, default=\"resnext50\", help=\"backbone name\")\n parser.add_argument(\"--neck\", type=str, default=\"fpn\", help=\"network neck name\")\n parser.add_argument(\"--num_epochs\", type=int, default=40, help=\"size of each image batch\")\n parser.add_argument(\"--batch_size\", type=int, default=18, help=\"number of workers\")\n parser.add_argument(\"--num_workers\", type=int, default=4, help=\"number of workers\")\n parser.add_argument(\"--data_dir\", type=str, default=\"vm\", help=\"dataset dir\")\n parser.add_argument(\"--load_weights\", type=int, default=0, help=\"to load weights\")\n parser.add_argument(\"--min_size\", type=int, default=600, help=\"image minimum size\")\n parser.add_argument(\"--max_size\", type=int, default=600, help=\"maximum size\")\n\n opt = parser.parse_args()\n print(opt)\n\n # Dataset path\n if opt.data_dir == 'vm':\n DATA_DIR = '/home/master/dataset/train/' # VISUM VM path\n else:\n DATA_DIR = '../dataset/train/' # Your PC path, don't forget the backslash in the end\n\n # Get sequence list\n sequences = [ int(folder.replace('seq','')) for _, dirnames, filenames in os.walk(DATA_DIR) for folder in dirnames if 'seq' in folder ]\n val_len = int(len(sequences) / 5)\n \n # Device\n device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n print(device)\n\n # Backbone name\n backbone_name = opt.backbone\n # Neck name\n neck_name = opt.neck\n # Weights definitions\n load_weigths = True if opt.load_weights == 1 else False\n SAVE_MODEL = ('fasterRCNN_' + str(backbone_name) + '_' + str(neck_name) )\n\n # number of processes \n num_workers = opt.num_workers # 4 for VISUM VM and 1 for our Windows machines\n\n # Training epochs\n num_epochs = opt.num_epochs\n\n # Number of images in a batch\n batch_size = opt.batch_size\n\n # Image size\n max_size = opt.max_size\n min_size = opt.min_size\n \n # Initial model \n model = fasterrcnn_resnet50_fpn(pretrained=True, min_size=min_size, max_size=max_size)\n in_features = model.roi_heads.box_predictor.cls_score.in_features\n model.roi_heads.box_predictor = FastRCNNPredictor(in_features, 2)\n\n # load a pre-trained model for classification and return\n # only the features\n if neck_name == 'fpn':\n out_channels = 256\n backbone = resnet_fpn_backbone(backbone_name, pretrained=True)\n backbone.out_channels = out_channels\n model.backbone = backbone\n elif neck_name == 'gfpn':\n out_channels = 256\n backbone = GroupedPyramidFeatures(backbone_name=backbone_name, out_features=out_channels, pretrained=True) \n backbone.out_channels = out_channels \n model.backbone = backbone\n elif neck_name == 'deeplab':\n out_channels = 256\n backbone = DeepLabv3Plus(n_classes=out_channels, backbone_name=backbone_name, pretrained=True)\n backbone.out_channels = out_channels\n model.backbone = backbone\n else:\n backbone, out_channels = get_backbone(backbone_name, pretrained=True)\n backbone.out_channels = out_channels\n\n # Anchors\n anchor_generator = AnchorGenerator(\n sizes=((32, 64, 128, 256),), aspect_ratios=((0.5, 1.0, 2.0),)\n )\n\n # let's define what are the feature maps that we will\n # use to perform the region of interest cropping, as well as\n # the size of the crop after rescaling.\n # if your backbone returns a Tensor, featmap_names is expected to\n # be [0]. More generally, the backbone should return an\n # OrderedDict[Tensor], and in featmap_names you can choose which\n # feature maps to use\n roi_pooler = torchvision.ops.MultiScaleRoIAlign(\n featmap_names=[\"0\"], output_size=7, sampling_ratio=2\n )\n\n # put the pieces together inside a FasterRCNN model\n # one class for fish, other for the backgroud\n model = FasterRCNN(\n backbone,\n num_classes=2,\n rpn_anchor_generator=anchor_generator,\n box_roi_pool=roi_pooler,\n min_size=min_size, max_size=max_size\n )\n\n # See the model architecture\n print(model)\n\n if load_weigths:\n model = torch.load(SAVE_MODEL)\n model.to(device)\n\n # define an optimizer\n params = [p for p in model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)\n\n # and a learning rate scheduler which decreases the learning rate\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=15, gamma=0.1)\n\n for k in [0,1]:\n\n if k == 0:\n seq_train = sequences[:-val_len]\n seq_val = sequences[-val_len:]\n else:\n seq_train = sequences[val_len:]\n seq_val = sequences[:val_len]\n\n # use our dataset and defined transformations\n dataset_train = Dataset(DATA_DIR, transforms=get_transform(train=True), sequences=seq_train)\n dataset_val = Dataset(DATA_DIR, transforms=get_transform(train=False), sequences=seq_val)\n \n # define training and validation data loaders\n data_loader = torch.utils.data.DataLoader(\n dataset_train, batch_size=batch_size, shuffle=True, num_workers=num_workers, collate_fn=utils.collate_fn\n )\n\n data_loader_val = torch.utils.data.DataLoader(\n dataset_val, batch_size=batch_size, shuffle=False, num_workers=num_workers, collate_fn=utils.collate_fn\n )\n\n # Training\n for epoch in range(int(num_epochs/2)):\n # train for one epoch, printing every 10 iterations\n epoch_loss = train_one_epoch(model, optimizer, data_loader,\n device, epoch, print_freq=10)\n # update the learning rate\n lr_scheduler.step()\n # evaluate on the validation dataset\n evaluator = evaluate(model, data_loader_val, dataset_val, device)\n\n if val_mAP < evaluator[0]:\n val_mAP = evaluator[0]\n torch.save(model, SAVE_MODEL)\n print('Model Saved. mAP = %1.6f' % val_mAP)\n" }, { "alpha_fraction": 0.5941786766052246, "alphanum_fraction": 0.6175978779792786, "avg_line_length": 35.91358184814453, "blob_id": "e9eef72adba4cacb0a97db0f1f3c6762a091f2e5", "content_id": "39bd23b835cc9e9c8990b1273539d442783d75b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2989, "license_type": "no_license", "max_line_length": 132, "num_lines": 81, "path": "/clusters.py", "repo_name": "dswanderley/fms", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\n#from utils.datasets import OvaryDataset\nfrom torch.utils.data import DataLoader\nimport utils\nimport torch\nfrom dataset import Dataset\nfrom transforms import get_transform\n\nDATA_DIR = '../dataset/train/' # Your PC path, don't forget the backslash in the end\n\nclass Clusters():\n def __init__(self):\n self.N_CLUSTERS = 6 # CHANGE THIS WHEN THIS CHANGE!!!\n self.batch_size = 12 # CHANGE THIS WHEN THIS CHANGE!!!\n self.num_workers = 1 # CHANGE THIS WHEN THIS CHANGE!!!\n\n self.colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']\n self.widths = []\n self.heights = []\n\nif __name__ == '__main__':\n\n # init cluster vars\n clusters = Clusters()\n\n # use our dataset and defined transformations\n dataset = Dataset(DATA_DIR, transforms=get_transform(train=True))\n\n # create data loader\n data_loader = torch.utils.data.DataLoader(\n dataset, batch_size=clusters.batch_size, shuffle=True, num_workers=clusters.num_workers, collate_fn=utils.collate_fn\n )\n\n # iterate through the labels\n for images, targets, _ in data_loader:\n # read each image in batch\n for target in targets:\n for bbox in target['boxes']:\n w = int(bbox[2].item() - bbox[0].item()) # width\n h = int(bbox[3].item() - bbox[1].item()) # hight\n clusters.widths.append(w)\n clusters.heights.append(h)\n\n # compute clusters\n data = np.array( [clusters.widths, clusters.heights] )\n kmeans = KMeans(n_clusters=clusters.N_CLUSTERS, random_state=0).fit(data.transpose())\n\n # print width vs hight graph: (x, y) of each detection\n for xy, cl in zip(data.transpose(), kmeans.labels_):\n x = xy[0]\n y = xy[1]\n c = clusters.colors[cl]\n plt.scatter(x, y, c=c, marker=\".\")\n\n # print width vs hight graph: clusters \n centers = [ [c[0], c[1], c[0]*c[1]] for c in kmeans.cluster_centers_]\n centers = np.array(centers)\n centers = np.sort(centers.view('i8,i8,i8'), order=['f1'], axis=0).view(np.float)\n\n for w, h, area in centers:\n print('width: ' + str( round(w) ) , 'height: ' + str( round(h) ), 'area: ' + str( round(area) ))\n plt.scatter(w, h, c='k', marker=\"*\")\n\n # show width vs hight graph:\n plt.axis([ 0, max(clusters.widths)+5, 0, max(clusters.heights)+5 ])\n plt.show()\n\n aspect_ratios = []\n # print aspect ratio graph: (width/hight) of each detection\n for bbox in data.transpose():\n aspect_ratios.append(bbox[0]/bbox[1])\n\n # show graph\n plt.hist(aspect_ratios, bins=100)\n min, max = plt.ylim()\n plt.vlines(np.quantile(aspect_ratios, 0.25),ymin=min, ymax=max)\n plt.vlines(np.quantile(aspect_ratios, 0.5),ymin=min, ymax=max)\n plt.vlines(np.quantile(aspect_ratios, 0.75),ymin=min, ymax=max)\n plt.show()" }, { "alpha_fraction": 0.5585852265357971, "alphanum_fraction": 0.6000311374664307, "avg_line_length": 36.98225021362305, "blob_id": "030df71c8cb807e95e4dc3c359bcf9a03d3afbb0", "content_id": "3a6c4cc0336fffcfc0f7161ccd0d9c49fdd415b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6418, "license_type": "no_license", "max_line_length": 120, "num_lines": 169, "path": "/models/deeplab.py", "repo_name": "dswanderley/fms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 06 15:10:50 2020\n@author: Diego Wanderley, Filipa Rocha, Henrique Carvalho\n@python: 3.6\n@description: Proposed DeepLabv3 Network and auxiliary classes.\n\"\"\"\n\nimport math\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torch.nn.functional as F\nfrom torchvision.models.segmentation.deeplabv3 import DeepLabHead, ASPP #, DeepLabV3\n\n\ndef get_backbone(name, pretrained=True):\n \"\"\" Loading backbone, defining names for skip-connections and encoder output. \"\"\"\n\n # TODO: More backbones\n\n # loading backbone model\n if name == 'resnet18':\n backbone = models.resnet18(pretrained=pretrained)\n elif name == 'resnet34':\n backbone = models.resnet34(pretrained=pretrained)\n elif name == 'resnet50':\n backbone = models.resnet50(pretrained=pretrained)\n elif name == 'resnet101':\n backbone = models.resnet101(pretrained=pretrained)\n elif name == 'resnext50':\n backbone = models.resnext50_32x4d(pretrained=pretrained)\n elif name == 'resnext101':\n backbone = models.resnext101_32x8d(pretrained=pretrained)\n else:\n raise NotImplemented('{} backbone model is not implemented so far.'.format(name))\n\n # specifying skip feature and output names\n if name.startswith('resnet18') or name.startswith('resnet34'):\n feature_sizes = [ backbone.conv1.out_channels,\n backbone.layer1[-1].conv2.out_channels,\n backbone.layer2[-1].conv2.out_channels,\n backbone.layer3[-1].conv2.out_channels,\n backbone.layer4[-1].conv2.out_channels ]\n feature_names = ['relu', 'layer1', 'layer2', 'layer3', 'layer4']\n elif name.startswith('resnet') or name.startswith('resnext'):\n feature_sizes = [ backbone.conv1.out_channels,\n backbone.layer1[-1].conv3.out_channels,\n backbone.layer2[-1].conv3.out_channels,\n backbone.layer3[-1].conv3.out_channels,\n backbone.layer4[-1].conv3.out_channels ]\n feature_names = ['relu', 'layer1', 'layer2', 'layer3', 'layer4']\n else:\n raise NotImplemented('{} backbone model is not implemented so far.'.format(name))\n\n return backbone, feature_sizes, feature_names\n\n\nclass ResNetBackbone(nn.Module):\n '''\n ResNet backbone for Feature Pyramid Net.\n '''\n def __init__(self, backbone_model='resnet50', pretrained=True):\n super(ResNetBackbone, self).__init__()\n # load backbone\n backbone, features, _ = get_backbone(backbone_model, pretrained=pretrained)\n # backbone input conv\n self.conv1 = backbone.conv1\n self.bn1 = backbone.bn1\n self.relu = nn.ReLU(inplace=True)\n #self.relu = self.backbone.relu\n self.maxpool = backbone.maxpool\n # Sequence 1\n self.layer1 = backbone.layer1\n # Sequence 2\n self.layer2 = backbone.layer2\n # Sequence 3\n self.layer3 = backbone.layer3\n # Sequence 4\n self.layer4 = backbone.layer4\n # Output features\n self.features = features\n # Load weigths\n if pretrained:\n self.conv1.load_state_dict(backbone.conv1.state_dict())\n self.bn1.load_state_dict(backbone.bn1.state_dict())\n self.layer1.load_state_dict(backbone.layer1.state_dict())\n self.layer2.load_state_dict(backbone.layer2.state_dict())\n self.layer3.load_state_dict(backbone.layer3.state_dict())\n self.layer4.load_state_dict(backbone.layer4.state_dict())\n\n def forward(self, x):\n # backbone input conv\n x0 = self.conv1(x)\n x0 = self.bn1(x0)\n x0 = self.relu(x0)\n x0 = self.maxpool(x0)\n # Bottleneck sequence\n x1 = self.layer1(x0)\n x2 = self.layer2(x1)\n x3 = self.layer3(x2)\n x4 = self.layer4(x3)\n # output features\n return x1, x2, x3, x4\n\n\nclass DeepLabv3Plus(nn.Module):\n def __init__(self, n_classes=256, layer_base=1, backbone_name='resnet50', pretrained=False):\n super(DeepLabv3Plus, self).__init__()\n\n # Parameters\n self.layer_base = layer_base\n # Backbone\n self.backbone = ResNetBackbone(backbone_model=backbone_name, pretrained=pretrained)\n featues = self.backbone.features\n self.low_features = featues[layer_base]\n self.high_features = featues[-1]\n # Neck\n self.aspp = ASPP(self.high_features, [12, 24, 36])\n # adopt [1x1, 48] for channel reduction.\n self.conv1 = nn.Sequential()\n self.conv1.add_module('0', nn.Conv2d(self.low_features, 48, 1, bias=False) ) #nn.Conv2d(256, 48, 1, bias=False))\n self.conv1.add_module('1', nn.BatchNorm2d(48))\n self.conv1.add_module('2', nn.ReLU())\n self.conv1.add_module('3', nn.Dropout(0.5))\n # Final conv block\n self.conv2 = nn.Sequential()\n self.conv2.add_module('0', nn.Conv2d(304, 256, kernel_size=3, stride=1, padding=1, bias=False))\n self.conv2.add_module('1', nn.BatchNorm2d(256))\n self.conv2.add_module('2', nn.ReLU())\n self.conv2.add_module('3', nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=False))\n self.conv2.add_module('4', nn.BatchNorm2d(256))\n self.conv2.add_module('5', nn.ReLU())\n self.conv2.add_module('6', nn.Conv2d(256, n_classes, kernel_size=1, stride=1))\n # Dropout\n self.dropout = nn.Dropout(0.5)\n\n def forward(self, x):\n # Backbone\n features = self.backbone(x)\n x_low = features[self.layer_base-1]\n x_high = features[-1]\n size = ( x_low.shape[-2], x_low.shape[-1] )\n # ASPP\n x1 = self.aspp(x_high)\n # Upsampling\n x2 = F.interpolate( x1, mode='bilinear', align_corners=True, size=size )\n # Low Level\n y = self.conv1(x_low)\n # Combination\n z = torch.cat((x2, y), dim=1)\n z = self.conv2(z)\n # z = F.interpolate(z, size=x.shape[2:], mode='bilinear', align_corners=True)\n z = self.dropout(z)\n\n out = {\n '0': z,\n '1': x1\n }\n return out\n\n\nif __name__ == \"__main__\":\n\n image = torch.randn(4, 3, 512, 512)\n model = DeepLabv3Plus(backbone_name='resnet50', pretrained=True)\n\n output = model(image)\n print(output.shape)" }, { "alpha_fraction": 0.5650741457939148, "alphanum_fraction": 0.6276770830154419, "avg_line_length": 32.730159759521484, "blob_id": "24b451f833f04f23bed2999952b50535f60bc1fb", "content_id": "d3c9b9025bf76c24aad3965c6543cda26df45b3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4249, "license_type": "no_license", "max_line_length": 90, "num_lines": 126, "path": "/models/backbones.py", "repo_name": "dswanderley/fms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 05 16:25:01 2020\n@author: Diego Wanderley\n@python: 3.7\n@description: Load backbones from torchvision models.\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nfrom torchvision.models._utils import IntermediateLayerGetter\n\n\ndef get_backbone(name, pretrained=True):\n \"\"\" \n Returns the backone of a CNN and its number of output channels.\n\n Parameters:\n name (string): CNN name\n pretrained (bool): Pretrained weights condition\n\n Returns:\n backbone (Sequential): The CNN backone warped as a torch.nn.Sequential object\n out_channels (int): The depth of the last layer\n \"\"\"\n \n # Mobilenet\n if name == 'mobilenet':\n backbone = models.mobilenet_v2(pretrained=pretrained).features\n out_channels = 1280\n # ResNet\n elif name == 'resnet18':\n resnet = models.resnet18(pretrained=pretrained)\n modules = list(resnet.children())[:-2]\n backbone = nn.Sequential(*modules)\n out_channels = 512\n elif name == 'resnet34':\n resnet = models.resnet34(pretrained=pretrained)\n modules = list(resnet.children())[:-2]\n backbone = nn.Sequential(*modules)\n out_channels = 512\n elif name == 'resnet50':\n resnet = models.resnet50(pretrained=pretrained)\n modules = list(resnet.children())[:-2]\n backbone = nn.Sequential(*modules)\n out_channels = 2048\n elif name == 'resnet101':\n resnet = models.resnet101(pretrained=pretrained)\n modules = list(resnet.children())[:-2]\n backbone = nn.Sequential(*modules)\n out_channels = 2048\n # ResNeXt\n elif name == 'resnext50':\n resnext = models.resnext50_32x4d(pretrained=pretrained)\n modules = list(resnext.children())[:-2]\n backbone = nn.Sequential(*modules)\n out_channels = 2048\n elif name == 'resnext101':\n resnext = models.resnext101_32x8d(pretrained=pretrained)\n modules = list(resnext.children())[:-2]\n backbone = nn.Sequential(*modules)\n out_channels = 2048\n elif name == 'wide_resnet50':\n w_resnet = models.wide_resnet50_2(pretrained=pretrained)\n modules = list(w_resnet.children())[:-2]\n backbone = nn.Sequential(*modules)\n out_channels = 2048\n elif name == 'wide_resnet101':\n w_resnet = models.wide_resnet101_2(pretrained=pretrained)\n modules = list(w_resnet.children())[:-2]\n backbone = nn.Sequential(*modules)\n out_channels = 2048\n # Error\n else:\n raise NotImplemented('{} backbone model is not implemented so far.'.format(name))\n\n return backbone, out_channels\n\n\ndef get_model(name, pretrained=True):\n\n if name == 'resnet18':\n model = models.resnet18(pretrained=pretrained)\n out_channels = [64, 128, 256, 512]\n elif name == 'resnet34':\n model = models.resnet34(pretrained=pretrained)\n out_channels = [64, 128, 256, 512]\n elif name == 'resnet50':\n model = models.resnet50(pretrained=pretrained)\n out_channels = [256, 512, 1024, 2048]\n elif name == 'resnet101':\n model = models.resnet101(pretrained=pretrained)\n out_channels = [256, 512, 1024, 2048]\n # ResNeXt\n elif name == 'resnext50':\n model = models.resnext50_32x4d(pretrained=pretrained)\n out_channels = [256, 512, 1024, 2048]\n elif name == 'resnext101':\n model = models.resnext101_32x8d(pretrained=pretrained)\n out_channels = [256, 512, 1024, 2048]\n elif name == 'wide_resnet50':\n model = models.wide_resnet50_2(pretrained=pretrained)\n out_channels = [256, 512, 1024, 2048]\n elif name == 'wide_resnet101':\n model = models.wide_resnet101_2(pretrained=pretrained)\n out_channels = [256, 512, 1024, 2048]\n # Error\n else:\n raise NotImplemented('{} backbone model is not implemented so far.'.format(name))\n \n return model, out_channels\n\n\n\nif __name__ == \"__main__\":\n from torch.autograd import Variable\n\n image = Variable( torch.randn(2,3,840,600) ) \n\n my_backbone, channels = get_model('resnet18', pretrained=True)\n\n print(my_backbone)\n\n x = my_backbone(image)\n print('end')" } ]
6
project-sunbird/sunbird-devops
https://github.com/project-sunbird/sunbird-devops
e31db7970f815f2c427cbc21e9777317037f23f0
b5797a4039a45c8f2c813ef343529b8a4212a009
b50249f2132d456acfef5bcdacc5cf376b9f2791
refs/heads/master
2023-08-17T03:00:17.706252
2023-04-26T06:49:27
2023-04-26T06:49:27
96,124,296
60
679
MIT
2017-07-03T15:17:48
2023-08-03T21:57:09
2023-09-14T07:17:46
Jinja
[ { "alpha_fraction": 0.7236467003822327, "alphanum_fraction": 0.7483381032943726, "avg_line_length": 49.095237731933594, "blob_id": "857da6638b0cd31df0fcbf121a950d334964ab21", "content_id": "ac2511f6a99c6e06985be8d56b4dc83dd1d49cc5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1053, "license_type": "permissive", "max_line_length": 152, "num_lines": 21, "path": "/deploy/sunbird_upgrade.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nimplementation_name=$(awk '/implementation_name: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\nenv_name=$(awk '/env: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\nansible_variable_path=\"${implementation_name}\"-devops/ansible/inventories/\"$env_name\"\nansible-playbook -i $ansible_variable_path/hosts ../ansible/system-init-upgrade.yml --extra-vars @config.yml\n\nexport sunbird_cassandra_host=`ip route get 8.8.8.8 | awk '{print $NF; exit}'`\nexport sunbird_cassandra_port=9042\n\ncd /tmp\n\n#Check cassandra migration jar file present or not inside /tmp\nif [ -f cassandra-migration-0.0.1-SNAPSHOT-jar-with-dependencies.jar ] \nthen\n rm -rf cassandra-migration-0.0.1-SNAPSHOT-jar-with-dependencies.jar\nfi\n\nwget https://github.com/project-sunbird/sunbird-utils/releases/download/R1.5/cassandra-migration-0.0.1-SNAPSHOT-jar-with-dependencies.jar\n\n# Start the java process to apply cassandra migration \nnohup java -cp \"cassandra-migration-0.0.1-SNAPSHOT-jar-with-dependencies.jar\" com.contrastsecurity.cassandra.migration.utils.MigrationScriptEntryPoint &\n\n" }, { "alpha_fraction": 0.625952422618866, "alphanum_fraction": 0.6887555122375488, "avg_line_length": 42.310001373291016, "blob_id": "f481fb7c1323cc0fd487af3dde7e8d3c40c4252f", "content_id": "37f298818460ac1dc8949a24fbb34ded7941cf62", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4331, "license_type": "permissive", "max_line_length": 523, "num_lines": 100, "path": "/ansible/roles/ansible-postgres_patroni/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "Role Name\n=========\n```\npostgresql-cluster-ansible\n```\nRequirements\n------------\n```\n1. comment or uncomment the properties in templates of the roles available as per the requirement.\n2. provide the variables where ever required.\n```\nRole Variables\n--------------\n```\nIn hosts files:\n1. etcd_ip : <etcdip is to be provided for postgresql group and etcd group>\n2. postgresql_origin: <same as server ip>\n3. postgresql_1: <master postgres server Ip>\n4. postgresql_2: <postgres replica 1 server IP>\n5. postgresql_3: <postgres replica 2 server IP>\n\n\netcd Role variables:\npostgres_patroni_etcd_name: \"postgres-etcd\" # cluster name\npostgres_patroni_etcd_initial_cluster: \"{{ etcd_name }}=http://{{ etcd_ip }}:2380\" # initial cluster\npostgres_patroni_etcd_initial_cluster_state: \"postgres\" # initial cluster state\npostgres_patroni_etcd_initial_cluster_token: \"etcd-cluster-postgres\" # initial cluster token\npostgres_patroni_etcd_initial_advertise_peer_urls: \"http://{{ etcd_ip }}:2380\" # initial advertise peer urls\npostgres_patroni_etcd_listen_peer_urls: \"http://{{ etcd_ip }}:2380\" # listen peer urls\npostgres_patroni_etcd_listen_client_urls: \"http://{{ etcd_ip }}:2379,http://127.0.0.1:2379\" # listen client urls\npostgres_patroni_etcd_advertise_client_urls: \"http://{{ etcd_ip }}:2379\" # advertise client urls\n\nAnsible-postgres_patroni role Variables:\n#patroni .yaml config\nPostgres_cluster_name: postgresql-prod # Cluster name\n\n# users admin password\npostgres_patroni_admin_password: admin # Admin Password\n\n#Authentication\n# Replication\npostgres_patroni_replication_username: replicator # Replication Username\npostgres_patroni_replication_password: password # Replication password\n\n#SuperUser\npostgres_patroni_superuser_username: postgres # Superuser username\npostgres_patroni_superuser_password: password # Superuser Password\n```\nArchitecture\n------------\n![Untitled Diagram (1)](https://user-images.githubusercontent.com/63706239/203470986-f8ec3d56-a6d2-4678-b594-dc20a29ec972.jpg)\n\n```\nDescription:\nAnsible postgres cluter role is used to setup a postgres cluster with 1 Primary and 2 replicas where we are using the patroni as HA solution for postgres cluster.Patroni can be configured to handle tasks like replication, backups and restorations.We are also using HAProxy load Balancer to route the traffic and Etcd is a fault-tolerant, distributed key-value store that is used to store the state of the Postgres cluster. Via Patroni, all of the Postgres nodes make use of etcd to keep the Postgres cluster up and running.\n\nUsers and applications can access the postgres server using Haproxy IP and Port defined in the haproxy configuration rules. \n```\n\nInventory hosts file as shown Below\n-----------------------------------\n```\n[etcd]\n192.168.245.129 etcd_ip=192.168.245.129 ansible_ssh_user=ubuntu\n\n[postgresql]\n192.168.245.129 postgresql_origin=192.168.245.129 postgresql_1=192.168.245.129 postgresql_2=192.168.245.130 postgresql_3=192.168.245.131 etcd_ip=192.168.245.129 ansible_ssh_user=ubuntu\n<postgres_server_2> postgresql_origin=<server_ip1> postgresql_1=<server_ip2> postgresql_2=<server_ip3> postgresql_3=<server_ip4> etcd_ip=192.168.245.129 ansible_ssh_user=ubuntu\n<postgres_server_3> postgresql_origin=<server_ip1> postgresql_1=<server_ip2> postgresql_2=<server_ip3> postgresql_3=<server_ip4> etcd_ip=192.168.245.129 ansible_ssh_user=ubuntu\n\n[haproxy]\n192.168.245.129 postgresql_1=192.168.245.129 postgresql_2=192.168.245.130 postgresql_3=192.168.245.131 ansible_ssh_user=ubuntu\n```\n\nLicense\n-------\n```\nBSD\n```\nAuthor Information\n------------------\n```\nNikhil Varma\n\nSenior DevOps Engineer\n```\n\npostgres cluster setup using ansible\n-----------------------------------\n\n```\n# Command to run Ansibe-postgresql role\n\n$ ansible-playbook -i inventory/hosts main.yaml -K --ask-pass\n\n# Commands to run postgresql roles by using the tags and skipping the tags\n\n$ ansible-playbook -i inventory/hosts main.yaml -K --ask-pass --tags=\"<tag>\"\n$ ansible-playbook -i inventory/hosts main.yaml -K --ask-pass --skip-tags=\"<tag>\"\n```\n" }, { "alpha_fraction": 0.616221010684967, "alphanum_fraction": 0.6176902651786804, "avg_line_length": 37.65909194946289, "blob_id": "24c0effce0696c1117f6cecfe23adb3dde413754", "content_id": "4705499cb4ad173ffb3defd238602d4f9c00cee9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3403, "license_type": "permissive", "max_line_length": 122, "num_lines": 88, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/keycloak_main.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "import json\n\nfrom keycloak import KeycloakOpenID\nfrom keycloak import KeycloakAdmin\nimport urllib2, argparse, json\n\n# Import realm\ndef keycloak_import_realm(keycloak_realm_file):\n data = json.load(open(keycloak_realm_file))\n realm_import = keycloak_admin.import_realm(data)\n\n# Add user and set password\ndef keycloak_create_user(email, username, firstName, lastName, password):\n new_user = keycloak_admin.create_user({\"email\": email,\n \"username\": username,\n \"emailVerified\": True,\n \"enabled\": True,\n \"firstName\": firstName,\n \"lastName\": lastName,\n \"credentials\": [{\"value\": \"12345\",\"type\": password}],\n \"realmRoles\": [\"user_default\"]})\n\n# Create the user and assign the role to access the user management API\ndef update_user_roles(config):\n realm_json = json.load(open(config['keycloak_realm_json_file_path']))\n\n # Get the id of realm-management\n for client in realm_json['clients']:\n if config['clientId'] == client['clientId']:\n client_id = client[\"id\"]\n break\n\n user = keycloak_admin.get_users({\"username\":config['keycloak_api_management_username']})\n user_id = user[0]['id']\n\n # Read the role from file\n with open(config['keycloak_user_manager_roles_json_file_path'], 'r') as data_file:\n json_data = data_file.read()\n\n roles = json.loads(json_data)\n\n # Get only client roles\n clientRoles = roles[config['clientId']]\n\n keycloak_admin.assign_client_role(user_id, client_id, clientRoles)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Configure keycloak user apis')\n parser.add_argument('keycloak_bootstrap_config', help='configuration json file that is needed for keycloak bootstrap')\n args = parser.parse_args()\n\n with open(args.keycloak_bootstrap_config) as keycloak_bootstrap_config:\n config = json.load(keycloak_bootstrap_config)\n\n try:\n # Get access token\n keycloak_admin = KeycloakAdmin(server_url=config['keycloak_auth_server_url'],\n username=config['keycloak_management_user'],\n password=config['keycloak_management_password'],\n realm_name=\"master\",\n client_id='admin-cli',\n verify=False)\n # Import realm\n keycloak_import_realm(config['keycloak_realm_json_file_path'])\n\n # Set realm name to sunbird\n keycloak_admin.realm_name = config['keycloak_realm']\n\n # Add user for user api\n keycloak_create_user(email=config['keycloak_api_management_user_email'],\n username=config['keycloak_api_management_username'],\n firstName=config['keycloak_api_management_user_first_name'],\n lastName=config['keycloak_api_management_user_last_name'],\n password=config['keycloak_api_management_user_password'])\n\n # Update user roles for access user management API's\n config['clientId'] = \"realm-management\"\n update_user_roles(config)\n\n # Update user roles for SSO\n config['clientId'] = \"admin-cli\"\n update_user_roles(config)\n # If keycloak is returning the error realm does exists\n except Exception as e:\n if \"409\" in str(e):\n print \"Skipping error: \" + str(e)\n else:\n raise\n\n" }, { "alpha_fraction": 0.6386554837226868, "alphanum_fraction": 0.6554622054100037, "avg_line_length": 38.33333206176758, "blob_id": "968e15d9ad6f0e290601e8e52000e8654f0992e8", "content_id": "d2b6da98048fbed4562e81a054ec99096750ffe5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 119, "license_type": "permissive", "max_line_length": 90, "num_lines": 3, "path": "/images/docker-registry/metadata.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# return version\necho '{\"name\":\"registry_image\",\"version\":\"2.0\",\"org\":\"sunbird\",\"hubuser\":\"purplesunbird\"}'\n\n" }, { "alpha_fraction": 0.6661618947982788, "alphanum_fraction": 0.6819933652877808, "avg_line_length": 31.42410659790039, "blob_id": "7de3a679f99e088dff1fc7f9503448837f5ce384", "content_id": "003ffe6c9bfd60af8f4a67da0aa1cdab58aacb97", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7264, "license_type": "permissive", "max_line_length": 122, "num_lines": 224, "path": "/ansible/roles/elasticsearch/test/integration/helpers/serverspec/multi_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'spec_helper'\n\nshared_examples 'multi::init' do |es_version,plugins|\n\n describe user('elasticsearch') do\n it { should exist }\n end\n\n describe service('node1_elasticsearch') do\n it { should be_running }\n end\n\n describe service('master_elasticsearch') do\n it { should be_running }\n end\n\n describe package('elasticsearch') do\n it { should be_installed }\n end\n\n #test configuration parameters have been set - test all appropriately set in config file\n describe file('/etc/elasticsearch/node1/elasticsearch.yml') do\n it { should be_file }\n it { should contain 'http.port: 9201' }\n it { should contain 'transport.tcp.port: 9301' }\n it { should contain 'node.data: true' }\n it { should contain 'node.master: false' }\n it { should contain 'node.name: localhost-node1' }\n it { should_not contain 'bootstrap.memory_lock: true' }\n it { should contain 'path.conf: /etc/elasticsearch/node1' }\n it { should contain 'path.data: /opt/elasticsearch/data-1/localhost-node1,/opt/elasticsearch/data-2/localhost-node1' }\n it { should contain 'path.logs: /var/log/elasticsearch/localhost-node1' }\n end\n\n\n #test configuration parameters have been set for master - test all appropriately set in config file\n describe file('/etc/elasticsearch/master/elasticsearch.yml') do\n it { should be_file }\n it { should contain 'http.port: 9200' }\n it { should contain 'transport.tcp.port: 9300' }\n it { should contain 'node.data: false' }\n it { should contain 'node.master: true' }\n it { should contain 'node.name: localhost-master' }\n it { should contain 'bootstrap.memory_lock: true' }\n it { should contain 'path.conf: /etc/elasticsearch/master' }\n it { should contain 'path.data: /opt/elasticsearch/master/localhost-master' }\n it { should contain 'path.logs: /var/log/elasticsearch/localhost-master' }\n end\n\n describe 'Master listening' do\n it 'listening in port 9200' do\n expect(port 9200).to be_listening\n end\n end\n\n describe 'Node listening' do\n it 'node should be listening in port 9201' do\n expect(port 9201).to be_listening\n end\n end\n\n #test we started on the correct port was used for master\n describe 'master started' do\n it 'master node should be running', :retry => 3, :retry_wait => 10 do\n command = command('curl \"localhost:9200\" | grep name')\n #expect(command.stdout).should match '/*master_localhost*/'\n expect(command.exit_status).to eq(0)\n end\n end\n\n #test we started on the correct port was used for node 1\n describe 'node1 started' do\n it 'node should be running', :retry => 3, :retry_wait => 10 do\n command = command('curl \"localhost:9201\" | grep name')\n #expect(command.stdout).should match '/*node1_localhost*/'\n expect(command.exit_status).to eq(0)\n end\n end\n\n describe file('/etc/elasticsearch/templates') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/templates/basic.json') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe 'Template Installed' do\n it 'should be reported as being installed', :retry => 3, :retry_wait => 10 do\n command = command('curl localhost:9200/_template/basic')\n expect(command.stdout).to match(/basic/)\n expect(command.exit_status).to eq(0)\n end\n end\n\n describe 'Template Installed' do\n it 'should be reported as being installed', :retry => 3, :retry_wait => 10 do\n command = command('curl localhost:9201/_template/basic')\n expect(command.stdout).to match(/basic/)\n expect(command.exit_status).to eq(0)\n end\n end\n\n #Confirm scripts are on both nodes\n describe file('/etc/elasticsearch/node1/scripts') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/node1/scripts/calculate-score.groovy') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/master/scripts') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/master/scripts/calculate-score.groovy') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n #Confirm that the data directory has only been set for the first node\n describe file('/opt/elasticsearch/master/localhost-master') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/opt/elasticsearch/data-1/localhost-node1') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n\n describe file('/opt/elasticsearch/data-2/localhost-node1') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n #test to make sure mlock was applied\n describe command('curl -s \"localhost:9200/_nodes/localhost-master/process?pretty=true\" | grep mlockall') do\n its(:stdout) { should match /true/ }\n its(:exit_status) { should eq 0 }\n end\n\n #test to make sure mlock was not applied\n describe command('curl -s \"localhost:9201/_nodes/localhost-node1/process?pretty=true\" | grep mlockall') do\n its(:stdout) { should match /false/ }\n its(:exit_status) { should eq 0 }\n end\n\n describe 'version check on master' do\n it 'should be reported as version '+es_version do\n command = command('curl -s localhost:9200 | grep number')\n expect(command.stdout).to match(es_version)\n expect(command.exit_status).to eq(0)\n end\n end\n\n describe 'version check on data' do\n it 'should be reported as version '+es_version do\n command = command('curl -s localhost:9201 | grep number')\n expect(command.stdout).to match(es_version)\n expect(command.exit_status).to eq(0)\n end\n end\n\n for plugin in plugins\n\n describe command('curl -s localhost:9200/_nodes/plugins?pretty=true | grep '+plugin) do\n its(:exit_status) { should eq 0 }\n end\n\n describe command('curl -s localhost:9201/_nodes/plugins?pretty=true | grep '+plugin) do\n its(:exit_status) { should eq 0 }\n end\n\n describe file('/usr/share/elasticsearch/plugins/'+plugin) do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n end\n\n describe file('/etc/init.d/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/default/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/sysconfig/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/usr/lib/systemd/system/elasticsearch.service') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/elasticsearch.yml') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/logging.yml') do\n it { should_not exist }\n end\n\n\n #Test server spec file has been created and modified - currently not possible as not copied for debian 8\n #describe file('/usr/lib/systemd/system/master_elasticsearch.service') do\n # it { should be_file }\n # it { should contain 'LimitMEMLOCK=infinity' }\n #end\n\n #describe file('/usr/lib/systemd/system/node1_elasticsearch.service') do\n # it { should be_file }\n # it { should_not contain 'LimitMEMLOCK=infinity' }\n #end\n\nend\n\n" }, { "alpha_fraction": 0.7450076937675476, "alphanum_fraction": 0.777265727519989, "avg_line_length": 58.181819915771484, "blob_id": "e04b629f5a9f544d3552afa419cd31b04f87c874", "content_id": "e0ca3db716a12e34984d39f1d30f1111aa60620a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 651, "license_type": "permissive", "max_line_length": 299, "num_lines": 11, "path": "/exporters/Go/tcp-logger/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "## Usage\n\nThis application will help to debug network communication via TCP by proxying the connection while printing the data to terminal console. For example, if ApplicationA -> ApplicationB and there is some issue in the data recieved by ApplicationB, you can run ApplicationA -> tcp_proxy -> ApplicationB.\n\nApplicationB listens to 8080\n\nWe'll start tcp_proxy as `./tcp_proxy -l 0.0.0.0:9999 -r localhost:8080` in ApplicationB Machine. Then we'll remap, ApplicationA to point to `APplicationB machine ip address:8080`, which will proxy to applicationB while printing the data to terminal.\n\n## Build\n\n`CGO_ENABLED=0 go build -o tcp_proxy ./main.go`\n" }, { "alpha_fraction": 0.6545893549919128, "alphanum_fraction": 0.6585748791694641, "avg_line_length": 40.6030158996582, "blob_id": "012c6217c6b2a3f436e5111bc409df2705a6a4c2", "content_id": "05ac0c46cc9ae7d64c16f8bbac2a4680a8bebc93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8280, "license_type": "permissive", "max_line_length": 263, "num_lines": 199, "path": "/deploy/cassandra_backup.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "\n#!/usr/bin/env python3\n\n# Author: Rajesh Rajendran <[email protected]>\n\n'''\nCreate cassandra snapshot with specified name,\nand create tar ball in targetdirectory name\n\nBy default\n\nCassandra data directory : /var/lib/cassandra/data\nSnapshot name : cassandra_backup-YYYY-MM-DD\nBackup name : cassandra_backup-YYYY-MM-DD.tar.gz\n\nusage: script snapshot_name\n\neg: ./cassandra_backup.py\n\nfor help ./cassandra_backup.py -h\n'''\n\nfrom argparse import ArgumentParser\nimport concurrent.futures\nfrom os import cpu_count, getcwd, link, makedirs, makedirs, sep, system, walk, path\nfrom re import compile, match\nfrom shutil import copytree, ignore_patterns, rmtree\nimport socket\nfrom subprocess import check_output\nfrom sys import exit\nfrom time import strftime\n\n\n'''\nReturns the ip address of current host machine\n'''\ndef get_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n # doesn't even have to be reachable\n s.connect(('10.255.255.255', 1))\n IP = s.getsockname()[0]\n except Exception:\n print(\"Couldn't get the correct, please pass the current node's cassandra ip address using flag '--host <ip address>'\")\n raise\n finally:\n s.close()\n return str(IP)\n\n# Create temporary directory to copy data\ndefault_snapshot_name = \"cassandra_backup\" + strftime(\"%Y-%m-%d-%H%M%S\")\ntmpdir = getcwd()+sep+default_snapshot_name\n\nparser = ArgumentParser(description=\"Create a snapshot and create tar ball inside tardirectory\")\nparser.add_argument(\"-d\", \"--datadirectory\", metavar=\"datadir\", default='/var/lib/cassandra/data',\n help=\"Path to cassadandra keyspaces. Default /var/lib/cassadra/data\")\nparser.add_argument(\"-s\", \"--snapshotdirectory\", metavar=\"snapdir\", default=tmpdir,\n help=\"Path to take cassandra snapshot. Default {}\".format(tmpdir))\nparser.add_argument(\"-n\", \"--snapshotname\", metavar=\"snapshotname\",\n default=\"cassandra_backup-\"+strftime(\"%Y-%m-%d\"),\n help=\"Name with which snapshot to be taken. Default {}\".format(default_snapshot_name))\nparser.add_argument(\"-t\", \"--tardirectory\", metavar=\"tardir\",\n default='', help=\"Path to create the tarball. Disabled by Default\")\nparser.add_argument(\"-w\", \"--workers\", metavar=\"workers\",\n default=cpu_count(), help=\"Number of workers to use. Default same as cpu cores {}\".format(cpu_count()))\nparser.add_argument(\"--disablesnapshot\", action=\"store_true\",\n help=\"disable taking snapshot, snapshot name can be given via -s flag\")\nparser.add_argument(\"--host\", default=get_ip(), metavar=\"< Default: \"+get_ip()+\" >\", help=\"ip address of cassandra instance. Used to take the token ring info. If the ip address is not correct, Please update the ip address, else your token ring won't be correct.\")\nargs = parser.parse_args()\n\ntmpdir = args.snapshotdirectory\n# Trying to create the directory if not exists\ntry:\n makedirs(tmpdir+sep+\"cassandra_backup\")\nexcept OSError as e:\n raise\n\ndef customCopy(root, root_target_dir):\n print(\"copying {} to {}\".format(root, root_target_dir))\n copytree(src=root, dst=root_target_dir, copy_function=link, ignore=ignore_patterns('.*'))\n\n# Names of the keyspaces to take schema backup\nignore_keyspace_names = []\n\ndef copy():\n '''\n Copying the data sanpshots to the target directory\n '''\n root_levels = args.datadirectory.rstrip('/').count(sep)\n # List of system keyspaces, which we don't need.\n # We need system_schema keyspace, as it has all the keyspace,trigger,types information.\n ignore_keyspaces = [\"system\", \"system_auth\", \"system_traces\", \"system_distributed\", \"lock_db\"]\n # ignore_list = compile('^'+tmpdir+sep+\"cassandra_backup\"+sep+'(system|system_auth|system_traces|system_distributed|lock_db)/.*$')\n ignore_list = compile('^'+tmpdir+sep+\"cassandra_backup\"+sep+\"(\"+\"|\".join(ignore_keyspaces)+')/.*$')\n # List of the threds running in background\n futures = []\n try:\n with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor:\n for root, _, _ in walk(args.datadirectory):\n keyspace = sep+sep.join(root.split(sep)[root_levels+1:-2])\n # We don't need tables and other inner directories for keyspace.\n if len(keyspace.split('/')) != 3:\n continue\n root_target_dir = tmpdir+sep+\"cassandra_backup\"+keyspace\n if match(ignore_list, root_target_dir):\n continue\n if root.split(sep)[-1] == args.snapshotname:\n # Keeping copy operation in background with threads\n tmp_arr = [root, root_target_dir]\n futures.append( executor.submit( lambda p: customCopy(*p), tmp_arr))\n except Exception as e:\n print(e)\n # Checking status of the copy operation\n for future in concurrent.futures.as_completed(futures):\n try:\n print(\"Task completed. Result: {}\".format(future.result()))\n except Exception as e:\n print(e)\n\nkeyspaces_schema_dict = {}\ndef create_schema(schema_file):\n cmd = \"cqlsh -e 'SELECT * from system_schema.keyspaces;' | tail -n +4 | head -n -2\"\n output = check_output('{}'.format(cmd), shell=True).decode().strip()\n for line in output.split('\\n'):\n tmpline = line.split(\"|\")\n keyspaces_schema_dict[tmpline[0].strip()] = {\"durable_writes\": tmpline[1].strip(),\"replication\": tmpline[2].strip()}\n\n # Creating table schema\n for root, _, files in walk(tmpdir):\n for file in files:\n if file.endswith(\".cql\"):\n with open(path.join(root, file),'r') as f:\n with open(schema_file,'a') as w:\n w.write(f.read())\n w.write('\\n')\n\n# Creating complete schema\n# For `ALTER DROP COLUMN`,\n# This schema will have issues.\n# So you'll have to create and drop the column.\n# For details about that table/column, look at snapshot_table_schema.sql\ncommand = \"cqlsh -e 'DESC SCHEMA' > {}/cassandra_backup/complete_db_schema.cql\".format(tmpdir)\nrc = system(command)\nif rc != 0:\n print(\"Couldn't backup schema, exiting...\")\n exit(1)\nprint(\"Schema backup completed. saved in {}/cassandra_backup/complete_db_schema.sql\".format(tmpdir))\n\n# Backing up tokenring\ncommand = \"\"\" nodetool ring | grep ^\"\"\" + get_ip() + \"\"\" | awk '{print $NF \",\"}' | xargs | tee -a \"\"\" + tmpdir + \"\"\"/cassandra_backup/tokenring.txt \"\"\" #.format(args.host, tmpdir)\nprint(command)\nrc = system(command)\nif rc != 0:\n print(\"Couldn't backup tokenring, exiting...\")\n exit(1)\nprint(\"Token ring backup completed. saved in {}/cassandra_backup/tokenring.txt\".format(tmpdir))\n\n# Creating snapshots\nif not args.disablesnapshot:\n # Cleaning all old snapshots\n command = \"nodetool clearsnapshot\"\n system(command)\n # Taking new snapshot\n command = \"nodetool snapshot -t {}\".format(args.snapshotname)\n rc = system(command)\n if rc != 0:\n print(\"Backup failed\")\n exit(1)\n print(\"Snapshot taken.\")\n\n# Copying the snapshot to proper folder structure, this is not a copy but a hard link.\ncopy()\n\n# Dropping unwanted keyspace schema\n# Including system schemas\n## deduplicating Ignore Keyspace list\nignore_keyspace_names = list(dict.fromkeys(ignore_keyspace_names))\n# Creating schema for keyspaces.\ncreate_schema(\"{}/cassandra_backup/snapshot_table_schema.cql\".format(tmpdir))\n\n# Clearing the snapshot.\n# We've the data now available in the copied directory.\ncommand = \"nodetool clearsnapshot -t {}\".format(args.snapshotname)\nprint(\"Clearing snapshot {} ...\".format(args.snapshotname))\nrc = system(command)\nif rc != 0:\n print(\"Clearing snapshot {} failed\".format(args.snapshotname))\n exit(1)\n\n# Creating tarball\nif args.tardirectory:\n print(\"Making a tarball: {}.tar.gz\".format(args.snapshotname))\n command = \"cd {} && tar --remove-files -czvf {}/{}.tar.gz *\".format(tmpdir, args.tardirectory, args.snapshotname)\n rc = system(command)\n if rc != 0:\n print(\"Creation of tar failed\")\n exit(1)\n # Cleaning up backup directory\n rmtree(tmpdir)\n print(\"Cassandra backup completed and stored in {}/{}.tar.gz\".format(args.tardirectory, args.snapshotname))\n" }, { "alpha_fraction": 0.6529449224472046, "alphanum_fraction": 0.661177933216095, "avg_line_length": 24.467741012573242, "blob_id": "98203aaeb824a875f622f7024ccae39a8538c4a8", "content_id": "1a20cc99f9304dc1f12350a36334e493a74ad84c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1579, "license_type": "permissive", "max_line_length": 80, "num_lines": 62, "path": "/exporters/Go/tcp-logger/main.go", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "// vim: set nofoldenable:\n// Author: rjshrjdnrn <[email protected]>\n\n// This application will proxy tcp connecion while printing the logs to console.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n)\n\nvar localAddr *string = flag.String(\"l\", \"localhost:9999\", \"local address\")\nvar remoteAddr *string = flag.String(\"r\", \"localhost:8888\", \"remote address\")\n\nfunc main() {\n\tflag.Parse()\n\tfmt.Printf(\"Listening: %v\\nProxying: %v\\n\\n\", *localAddr, *remoteAddr)\n\n\tlistener, err := net.Listen(\"tcp\", *localAddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor {\n\t\t// Creating a listener\n\t\tconn, err := listener.Accept()\n\t\tlog.Println(\"New connection\", conn.RemoteAddr())\n\t\tif err != nil {\n\t\t\tlog.Println(\"error accepting connection\", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo func() {\n\t\t\t// Closing the listener\n\t\t\tdefer conn.Close()\n\t\t\t// Creating connection to remote server, proxy connection.\n\t\t\tconn2, err := net.Dial(\"tcp\", *remoteAddr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"error dialing remote addr\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Closing proxy connection\n\t\t\tdefer conn2.Close()\n\t\t\t// Creating channel to copy the data\n\t\t\tcloser := make(chan struct{}, 2)\n\t\t\t// Copy local data to remotet server\n\t\t\tgo copy(closer, conn2, conn)\n\t\t\t// Copy proxy data to local listener\n\t\t\tgo copy(closer, conn, conn2)\n\t\t\t// Waiting for the data to be written\n\t\t\t<-closer\n\t\t\tlog.Println(\"Connection complete\", conn.RemoteAddr())\n\t\t}()\n\t}\n}\n\nfunc copy(closer chan struct{}, dst io.Writer, src io.Reader) {\n\tio.Copy(os.Stdout, io.TeeReader(src, dst))\n\tcloser <- struct{}{} // connection is closed, send signal to stop proxy\n}\n" }, { "alpha_fraction": 0.6874391436576843, "alphanum_fraction": 0.7221681475639343, "avg_line_length": 54.01785659790039, "blob_id": "bdab3c1967b1af32bd7879edd85fc6be4b8ad9af", "content_id": "cb339215be2b58e20f8dd6fb5a5a217ae55dba01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3081, "license_type": "permissive", "max_line_length": 168, "num_lines": 56, "path": "/deploy/migrate-to-keycloak7.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -eu -o pipefail\n\necho \"Get the standalone-ha.xml template file and module.xml\"\ncurl -sS https://raw.githubusercontent.com/project-sunbird/sunbird-devops/keycloak7/ansible/roles/keycloak-deploy/templates/standalone-ha.xml --output standalone-ha.xml\ncurl -sS https://raw.githubusercontent.com/project-sunbird/sunbird-devops/keycloak7/ansible/roles/keycloak-deploy/templates/module.xml.j2 --output module.xml\n\necho \"Get the current VM IP\"\nip=\"$(ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)\"\n\necho \"Replace ansible variables with postgres details\"\nsed -i \"s/{{keycloak_postgres_host}}/$PG_HOST/g\" standalone-ha.xml\nsed -i \"s/{{keycloak_postgres_database}}/${PG_DB}7/g\" standalone-ha.xml\nsed -i \"s/{{keycloak_postgres_user}}/$PG_USER/g\" standalone-ha.xml\nsed -i \"s/{{keycloak_postgres_password}}/$PGPASSWORD/g\" standalone-ha.xml\nsed -i \"s/{{ansible_default_ipv4.address}}/$ip/g\" standalone-ha.xml\nsed -i \"s/8080/8081/g\" standalone-ha.xml\nsed -i \"s/\\\"900\\\"/\\\"3600\\\"/g\" standalone-ha.xml\n\necho \"Get vanilla keycloak package\"\nwget -q https://downloads.jboss.org/keycloak/7.0.1/keycloak-7.0.1.tar.gz\n\necho \"Extract keycloak package\"\ntar -xf keycloak-7.0.1.tar.gz\n\necho \"Get the postgres jar\"\nwget -q https://jdbc.postgresql.org/download/postgresql-9.4.1212.jar\n\necho \"Copy standalone-ha.xml, postgres jar and module.xml file to keycloak package\"\ncp standalone-ha.xml keycloak-7.0.1/standalone/configuration\nmkdir -p keycloak-7.0.1/modules/system/layers/keycloak/org/postgresql/main\ncp postgresql-9.4.1212.jar keycloak-7.0.1/modules/system/layers/keycloak/org/postgresql/main\ncp module.xml keycloak-7.0.1/modules/system/layers/keycloak/org/postgresql/main\n\necho \"Backup the existing keycloak db\"\npg_dump -Fd -j 4 -h $PG_HOST -U $PG_USER -d $PG_DB -f ${PG_DB}\n\necho \"Create a new db for keycloak 7\"\npsql -h $PG_HOST -U $PG_USER -p 5432 -d postgres -c \"CREATE DATABASE ${PG_DB}7\"\n\necho \"Restore the existing keycloak 3 db to the new database\"\npg_restore -O -j 4 -h $PG_HOST -U $PG_USER -d ${PG_DB}7 ${PG_DB}\n\necho \"Clear the DB of duplicate values\"\npsql -h $PG_HOST -U $PG_USER -p 5432 -d ${PG_DB}7 -c \"delete from public.COMPOSITE_ROLE a using public.COMPOSITE_ROLE b where a=b and a.ctid < b.ctid\"\npsql -h $PG_HOST -U $PG_USER -p 5432 -d ${PG_DB}7 -c \"delete from public.REALM_EVENTS_LISTENERS a using public.REALM_EVENTS_LISTENERS b where a=b and a.ctid < b.ctid\"\npsql -h $PG_HOST -U $PG_USER -p 5432 -d ${PG_DB}7 -c \"delete from public.REDIRECT_URIS a using public.REDIRECT_URIS b where a=b and a.ctid < b.ctid\"\npsql -h $PG_HOST -U $PG_USER -p 5432 -d ${PG_DB}7 -c \"delete from public.WEB_ORIGINS a using public.WEB_ORIGINS b where a=b and a.ctid < b.ctid\"\npsql -h $PG_HOST -U $PG_USER -p 5432 -d ${PG_DB}7 -c \"truncate offline_user_session\"\npsql -h $PG_HOST -U $PG_USER -p 5432 -d ${PG_DB}7 -c \"truncate offline_client_session\"\npsql -h $PG_HOST -U $PG_USER -p 5432 -d ${PG_DB}7 -c \"truncate jgroupsping\" || true\n\necho \"Migrate the DB to keycloak 7\"\ncd keycloak-7.0.1\nbin/standalone.sh -b=$ip -bprivate=$ip --server-config standalone-ha.xml\n" }, { "alpha_fraction": 0.6128456592559814, "alphanum_fraction": 0.628902792930603, "avg_line_length": 37.655174255371094, "blob_id": "9d5ea5456e68250f163fc9257c219bd52eabff3b", "content_id": "ded56118f63ec06083fa369ba7d3d1919e4855d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1121, "license_type": "permissive", "max_line_length": 125, "num_lines": 29, "path": "/kubernetes/ansible/static-files/elasticsearch_mapping.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#### Cloning and Changing the directory:\nrm -rf sunbird-utils\ngit clone https://github.com/project-sunbird/sunbird-utils.git -b $1\nrm sunbird-utils/sunbird-es-utils/src/main/resources/indices/cbatchstats.json\nrm sunbird-utils/sunbird-es-utils/src/main/resources/mappings/cbatchstats-mapping.json \ncd sunbird-utils/sunbird-es-utils/src/main/resources/indices\n\n#### Creating the new indices:\n\nindices_files=$(ls -l | awk 'NR>1{print $9}' | awk -F\".\" '{print $1}' | tr \"\\n\" \" \")\nfor file in ${indices_files[@]}\ndo\n curl -X PUT http://localhost:9200/${file} -H 'Content-Type: application/json' -d @${file}.json\ndone\n\n#### Updating the mapping for newly created indices:\n\necho \"#################################################\"\n\ncd ../mappings\n#mapping_files=$(ls -l | awk 'NR>1{print $9}' | awk -F\"-\" '{print $1}' | tr \"\\n\" \" \")\nmapping_files=$(ls -l | awk 'NR>1{print $9}' | awk -F\".\" '{print $1}' | tr \"\\n\" \" \" | sed 's/-mapping//g')\n\nfor file in ${mapping_files[@]}\ndo\n curl -X PUT http://localhost:9200/${file}/_mapping/_doc -H 'Content-Type: application/json' -d @${file}-mapping.json\ndone\n" }, { "alpha_fraction": 0.6752368211746216, "alphanum_fraction": 0.7198917269706726, "avg_line_length": 42.47058868408203, "blob_id": "388e215f9743b2b0c726f715314bbd3b8e74ce6a", "content_id": "12bdfdeceb63c66948e4391707bfb9192bc1e539", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 739, "license_type": "permissive", "max_line_length": 143, "num_lines": 17, "path": "/kubernetes/utils/cluster_creation.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# vim: set ts=4 sw=4 tw=0 et :\n\n#!/bin/bash\ncluster_name=$1\nservice_principal=$2\nclient_secret=$3\nssh_public_key_location=$4\nsubscription_id=$5\n\naz aks create --resource-group test --name ${cluster_name} \\\n --node-count 1 --admin-username deployer --kubernetes-version 1.14.7 \\\n --service-cidr 172.16.0.0/16 --service-principal ${service_principal} \\\n --node-vm-size Standard_D4s_v3 --client-secret ${client_secret} \\\n --network-plugin kubenet --dns-service-ip 172.16.10.10 \\\n --ssh-key-value @${ssh_public_key_location} -l centralindia \\\n --vm-set-type VirtualMachineScaleSets \\\n --vnet-subnet-id /subscriptions/${subscription_id}/resourceGroups/Test/providers/Microsoft.Network/virtualNetworks/Test-vnet/subnets/default\n" }, { "alpha_fraction": 0.6708074808120728, "alphanum_fraction": 0.6770186424255371, "avg_line_length": 28.272727966308594, "blob_id": "327aa8aa77b70214d8eeaf29cc21f1a3395c6b46", "content_id": "879ef039ecf446b260967cc464efcb5d66189c99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 322, "license_type": "permissive", "max_line_length": 56, "num_lines": 11, "path": "/ansible/roles/firebase_deploy/templates/deployToFirebase.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Upload build to Firebase\n# Usage: upload.sh <file>\n\n#!/bin/bashset -e\necho \"Build to upload \"${1}\nfirebase appdistribution:distribute ${1} \\\n --token {{mobile_firebse_app_distribution_token}} \\\n --app {{mobile_firebse_app_distribution_id}} \\\n --groups {{mobile_firebse_app_distribution_group}}\n" }, { "alpha_fraction": 0.7025948166847229, "alphanum_fraction": 0.7045907974243164, "avg_line_length": 54.77777862548828, "blob_id": "e82b3e5a4a9742d5e31ac84812a9cc2663f3984b", "content_id": "bc9305f51f217201bfe46a67cb7ad9b8c3118107", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 501, "license_type": "permissive", "max_line_length": 220, "num_lines": 9, "path": "/ansible/roles/swarm-agent-docker-prune/files/swarm-agent-docker-prune.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\nmaster_node_ip=$1\nagent_nodes=$(ssh -o StrictHostKeyChecking=no -i /run/secrets/ops-private-key ops@$master_node_ip \"docker node ls -f role=worker --format {{.Hostname}}\")\nfor agent_node in $agent_nodes; do\n echo \"\"\n echo \"Cleaning node: $agent_node\"\n eval `ssh-agent -s` && ssh-add /run/secrets/ops-private-key && ssh -A -o StrictHostKeyChecking=no ops@$master_node_ip \"ssh -o StrictHostKeyChecking=no $agent_node 'docker container prune -f && docker image prune -f'\"\ndone;" }, { "alpha_fraction": 0.6685606241226196, "alphanum_fraction": 0.6780303120613098, "avg_line_length": 30.058822631835938, "blob_id": "569fe43ceb0b42838d63733d1ded95d024062bbc", "content_id": "8a91a5a750c28fe2a39f8a6b571929461924f598", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 528, "license_type": "permissive", "max_line_length": 151, "num_lines": 17, "path": "/deploy/system-init.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory-path>\"\n exit 1\nfi\n\nINVENTORY_PATH=$1\n\n[ -f ~/jwt_token_player.txt ] || echo \"JWT token (~/jwt_token_player.txt) not found\" || exit 1\nsunbird_api_auth_token=$(cat ~/jwt_token_player.txt|sed 's/ //g')\n\n# System Initialisation\necho \"System Initialisation\"\nansible-playbook -i $INVENTORY_PATH ../ansible/system-init.yml [email protected] --extra-vars \"sunbird_api_auth_token=${sunbird_api_auth_token}\"\n" }, { "alpha_fraction": 0.7786885499954224, "alphanum_fraction": 0.7786885499954224, "avg_line_length": 120, "blob_id": "889fe6798d37e43758479d562318fbfbb4e5b730", "content_id": "192cfc2a1a0a5a372c9679b82e5ad83aa75d57dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 122, "license_type": "permissive", "max_line_length": 120, "num_lines": 1, "path": "/Installation.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "### Installation wiki moved to [here.](http://docs.sunbird.org/latest/developer-docs/server-installation/prerequisites/) \n" }, { "alpha_fraction": 0.769565224647522, "alphanum_fraction": 0.769565224647522, "avg_line_length": 16.769229888916016, "blob_id": "a93135d8d501ba71b5bd1400cd35fa74dbe5def0", "content_id": "c34b0f2bb0b4006029ef5b9f9b81f88ed9d2152b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 230, "license_type": "permissive", "max_line_length": 50, "num_lines": 13, "path": "/ansible/roles/grafana-dashboards-import/templates/import-dashboards-from-git-repo.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nset -e\n\nGIT_REPO_URL={{ grafana_dashboards_git_repo_url }}\n\nrm -rf grafana-dashboards\ngit clone $GIT_REPO_URL grafana-dashboards\n\nrm -rf dashboards\ncp -r grafana-dashboards/dashboards dashboards\n\nwizzy export dashboards" }, { "alpha_fraction": 0.5139442086219788, "alphanum_fraction": 0.5298804640769958, "avg_line_length": 37.61538314819336, "blob_id": "e7d61f7ba4b3ff705737eb9606c54c38a1e147ee", "content_id": "b46e18d1c4580a3a5f9404b220fde165b7eddaa9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 502, "license_type": "permissive", "max_line_length": 108, "num_lines": 13, "path": "/deploy/utilities/kill_samza_app.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Author S M Y <[email protected]>\n# Kill All the Samza Jobs\n\nfor id in $(/usr/local/hadoop/bin/yarn application --list | column -t | awk 'NR>2{print $1}' | tr \"\\n\" \" \");\ndo\n\techo \"ID is $id\"\n\t/usr/local/hadoop/bin/yarn application -kill $id\n\tsleep 1\ndone\necho -e \"\\n--------------------------------------------------------------------------\\n\"\necho \"The Overall status of yarn is as follows:\"\n/usr/local/hadoop/bin/yarn application --list | awk '{print $1 \" \" $2 \" \" $6 \" \" $7 \" \" $9}' | column -t\n" }, { "alpha_fraction": 0.7824030518531799, "alphanum_fraction": 0.7833490967750549, "avg_line_length": 59.400001525878906, "blob_id": "589d72d68dda544ee5854d7052e6648a011aa76d", "content_id": "ddb61d3802c3531779919c4ce5561c1d7d5efd25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 2114, "license_type": "permissive", "max_line_length": 136, "num_lines": 35, "path": "/ansible/generic_templates/keycloak_301_rollback.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "ALTER TABLE REALM_SUPPORTED_LOCALES ADD COLUMN id SERIAL;\nselect count(*) from public.REALM_SUPPORTED_LOCALES;\nDELETE FROM REALM_SUPPORTED_LOCALES a USING REALM_SUPPORTED_LOCALES b WHERE a.id < b.id AND a.value = b.value;\nselect count(*) from public.REALM_SUPPORTED_LOCALES;\nALTER TABLE REALM_SUPPORTED_LOCALES DROP COLUMN id;\nALTER TABLE composite_role ADD COLUMN id SERIAL;\nselect count(*) from public.composite_role;\nDELETE FROM composite_role a USING composite_role b WHERE a.id < b.id AND a.composite = b.composite AND a.child_role = b.child_role;\nselect count(*) from public.composite_role;\nALTER TABLE composite_role DROP COLUMN id;\nALTER TABLE realm_events_listeners ADD COLUMN id SERIAL;\nselect count(*) from public.realm_events_listeners;\nDELETE FROM realm_events_listeners a USING realm_events_listeners b WHERE a.id < b.id AND a.realm_id = b.realm_id AND a.value = b.value;\nselect count(*) from public.realm_events_listeners;\nALTER TABLE realm_events_listeners DROP COLUMN id;\nALTER TABLE redirect_uris ADD COLUMN id SERIAL;\nselect count(*) from public.redirect_uris;\nDELETE FROM redirect_uris a USING redirect_uris b WHERE a.id < b.id AND a.client_id = b.client_id AND a.value = b.value;\nselect count(*) from public.redirect_uris;\nALTER TABLE redirect_uris DROP COLUMN id;\nALTER TABLE web_origins ADD COLUMN id SERIAL;\nselect count(*) from public.web_origins;\nDELETE FROM web_origins a USING web_origins b WHERE a.id < b.id AND a.client_id = b.client_id AND a.value = b.value;\nselect count(*) from public.web_origins;\nALTER TABLE web_origins DROP COLUMN id;\nALTER TABLE databasechangelog ADD COLUMN serid SERIAL;\nselect count(*) from public.databasechangelog;\nDELETE FROM databasechangelog a USING databasechangelog b WHERE a.serid < b.serid AND a.author = b.author AND a.md5sum = b.md5sum;\nselect count(*) from public.databasechangelog;\nALTER TABLE databasechangelog DROP COLUMN serid;\nALTER TABLE public.USER_ENTITY DROP COLUMN NOT_BEFORE;\nselect count(*) from offline_client_session;\nselect count(*) from offline_user_session;\ndelete from offline_user_session;\ndelete from offline_client_session;\n" }, { "alpha_fraction": 0.47507330775260925, "alphanum_fraction": 0.48973608016967773, "avg_line_length": 20.375, "blob_id": "28e2c197222110d204c620bf37d52d1a4b65546e", "content_id": "b6da2af07fbd7c6f79403920a2ad130d1389141f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 341, "license_type": "permissive", "max_line_length": 72, "num_lines": 16, "path": "/ansible/roles/reset-docker/templates/reset_docker.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor host in `docker node ls | awk '{if (NR>1 && NF==4) print $2}'`\ndo\n\tssh -n $host sudo service docker restart\n \twhile true;\n \tdo\n var=`docker node ls | grep $host | awk '{ print $NF }'`\n echo $var\n if [ $var == \"Active\" ];\n \t\tthen\n \t\t\tbreak\n \t\tfi\n \t\tsleep 10\n\tdone\ndone" }, { "alpha_fraction": 0.8520709872245789, "alphanum_fraction": 0.8520709872245789, "avg_line_length": 41.25, "blob_id": "5b8302507934da9906b1ad969c6ae399a6ef7ae9", "content_id": "2bac215b8ea6ebbe7a8a2de8a83f2beadd76f094", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 169, "license_type": "permissive", "max_line_length": 53, "num_lines": 4, "path": "/images/cassandra_jmx_exporter/logging.properties", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "handlers=java.util.logging.ConsoleHandler\njava.util.logging.ConsoleHandler.level=INFO\nio.prometheus.jmx.level=INFO\nio.prometheus.jmx.shaded.io.prometheus.jmx.level=INFO\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6723356246948242, "avg_line_length": 43.099998474121094, "blob_id": "142d93ad36a835d2bcdfff6f05099f1d463bf74d", "content_id": "6306ae920e9c0cb245acf26022c7eaec5174f201", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 882, "license_type": "permissive", "max_line_length": 107, "num_lines": 20, "path": "/ansible/static-files/kong-api-scripts/kong_apis_report.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "import urllib2, argparse, json, csv\n\nfrom common import get_apis, json_request\n\ndef create_api_report_csv(kong_admin_api_url, report_file_path):\n saved_apis = get_apis(kong_admin_api_url)\n with open(report_file_path, 'w') as csvfile:\n fieldnames = ['Name', 'Path']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for api in saved_apis:\n writer.writerow({'Name': api['name'], 'Path': api['request_path']})\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Generate report for APIs on-boarded')\n parser.add_argument('report_file_path', help='Report file path')\n parser.add_argument('--kong-admin-api-url', help='Admin url for kong', default='http://localhost:8001')\n args = parser.parse_args()\n\n create_api_report_csv(args.kong_admin_api_url, args.report_file_path)\n" }, { "alpha_fraction": 0.5011342763900757, "alphanum_fraction": 0.5122609734535217, "avg_line_length": 38.0590705871582, "blob_id": "1c22e870974c758f52cb1ee68a6084250cae3c66", "content_id": "afbf255eb0cb9e20eebe8a7ebfa55f89872b47e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 9257, "license_type": "permissive", "max_line_length": 252, "num_lines": 237, "path": "/deploy/sunbird_install.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# vim: set ts=4 et:\n\n#--------------------------------------------------------------------------------------------------------#\n# This script installs and configures sunbird according to the confugurations specified in config file\n#\n# Usage \n# ./sunbird_install.sh ==> Install and configure sunbird from scratch\n# ./sunbird_install.sh -h ==> Help\n# ./sunbird_install.sh -s <service name> ==> Install the specific service\n#\n# Original Author: Rajesh Rajendran <[email protected]>\n# Maintainers: Manoj <[email protected]>\n#---------------------------------------------------------------------------------------------------------#\n\nset -eu -o pipefail\n\nusage() { echo \"Usage: $0 [ -s {validateconfig|sanity|config|dbs|apis|proxy|keycloak|badger|core|configservice|logger|monitor|posttest|systeminit} ]\" ; exit 0; }\n\n# Checking for valid argument\nif [[ ! -z ${1:-} ]] && [[ ${1} != -* ]]; then\n usage\n exit 1\nfi\n\n# Sourcing versions of images\nsource version.env\n\n# Reading environment and implementation name\nimplementation_name=$(awk '/implementation_name: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\nenv_name=$(awk '/env: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\napp_host=$(awk '/application_host: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\ndb_host=$(awk '/database_host: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\nssh_ansible_user=$(awk '/ssh_ansible_user: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\nansible_private_key_path=$(awk '/ansible_private_key_path: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\nansible_variable_path=\"${implementation_name}\"-devops/ansible/inventories/\"$env_name\"\nprotocol=$(awk '/proto: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\ndomainname=$(awk '/dns_name: /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\nENV=sample\nORG=sunbird\n#TO skip the host key verification\nexport ANSIBLE_HOST_KEY_CHECKING=False\n#Enable force color\nexport ANSIBLE_FORCE_COLOR=true\n\n# Creating logging directory\nif [ ! -d logs ];then mkdir logs &> /dev/null;fi\n# Creating temporary directory\nif [ ! -d .sunbird/ignore ];then mkdir -p .sunbird/ignore &> /dev/null;fi\n\n# Validate config file\nvalidateconfig(){\nif [[ $# -eq 0 ]]; then\n ./validateConfig.sh\nelse\n ./validateConfig.sh $1\nfi \n}\n\n# Generating configs\nconfig() { \n sudo ./install-deps.sh\n time ./generate-config.sh $implementation_name $env_name core;\n # Creating inventory\n sed -i s#\\\"{{database_host}}\\\"#$db_host#g $ansible_variable_path/hosts\n sed -i s#\\\"{{application_host}}\\\"#$app_host#g $ansible_variable_path/hosts\n sed -i s#\\\"{{ansible_private_key_path}}\\\"#$ansible_private_key_path#g $ansible_variable_path/hosts\n ansible-playbook -i \"localhost,\" -c local ../ansible/generate-hosts.yml --extra-vars @config.yml --extra-vars \"host_path=$ansible_variable_path\"\n .sunbird/generate_host.sh > $ansible_variable_path/hosts 2>&1 /dev/null\n}\n\n# Sanity check\nsanity() {\n ./sanity.sh $ssh_ansible_user $ansible_private_key_path\n}\n\nconfigservice() {\n\techo \"Deploy Config service\"\n\tansible-playbook -i $ansible_variable_path ../ansible/deploy.yml --tags \"stack-sunbird\" --extra-vars \"hub_org=${ORG} image_name=config-service image_tag=${CONFIG_SERVICE_VERSION} service_name=config-service deploy_config=True\" --extra-vars @config.yml\n}\n\n# Installing dependencies\ndeps() { \nansible-playbook -i $ansible_variable_path/hosts ../ansible/sunbird_prerequisites.yml --extra-vars @config.yml \nansible-playbook -i $ansible_variable_path/hosts ../ansible/setup-dockerswarm.yml --extra-vars @config.yml\n}\n\n\n# Installing and initializing dbs\ndbs() { ./install-dbs.sh $ansible_variable_path; ./init-dbs.sh $ansible_variable_path; }\n\n# Apis\napis() { ./deploy-apis.sh $ansible_variable_path; }\n\n# Proxy\nproxy() { ./deploy-proxy.sh $ansible_variable_path; }\n\n# Keycloak\nkeycloak() { \n ./provision-keycloak.sh $ansible_variable_path\n ./deploy-keycloak-vm.sh $ansible_variable_path \n sleep 15\n ./bootstrap-keycloak.sh $ansible_variable_path\n}\n\n# badger\nbadger() { ./deploy-badger.sh $ansible_variable_path; }\n\n# Core\ncore() { ./deploy-core.sh $ansible_variable_path; }\n\n# System Initialisation\nsysteminit() { ./system-init.sh $ansible_variable_path; }\n\n# Logger\nlogger() { ./deploy-logger.sh $ansible_variable_path; }\n\n# Monitor\nmonitor() { ./deploy-monitor.sh $ansible_variable_path; }\n\n#Post Installation Testing\nposttest() { ./postInstallation.sh $ansible_private_key_path $ssh_ansible_user $protocol $domainname; }\n\nwhile getopts \"s:h\" o;do\n case \"${o}\" in\n s)\n s=${OPTARG}\n case \"${s}\" in\n validateconfig)\n echo -e \"\\n$(date)\\n\">>logs/validateconfig.log;\n validateconfig 2>&1 | tee -a logs/validateconfig.log\n exit 0\n ;;\n config)\n echo -e \"\\n$(date)\\n\">>logs/config.log;\n config 2>&1 | tee -a logs/config.log\n exit 0\n ;;\n sanity)\n echo -e \"\\n$(date)\\n\">>logs/sanity.log;\n config 2>&1 | tee -a logs/sanity.log\n sanity 2>&1 | tee -a logs/sanity.log\n exit 0\n ;;\n deps)\n echo -e \"\\n$(date)\\n\">>logs/deps.log;\n sudo ./install-deps.sh 2>&1 | tee -a logs/deps.log\n deps 2>&1 | tee -a logs/deps.log\n exit 0\n ;;\n dbs)\n echo -e \"\\n$(date)\\n\">>logs/dbs.log; dbs 2>&1 | tee -a logs/dbs.log\n exit 0\n ;;\n apis)\n echo -e \"\\n$(date)\\n\">>logs/apis.log; apis 2>&1 | tee -a logs/apis.log\n exit 0\n ;;\n proxy)\n echo -e \"\\n$(date)\\n\">>logs/proxy.log; proxy 2>&1 | tee -a logs/proxy.log\n exit 0\n ;;\n keycloak)\n echo -e \"\\n$(date)\\n\">>logs/keycloak.log; keycloak 2>&1 | tee -a logs/keycloak.log\n exit 0\n ;;\n badger)\n echo -e \"\\n$(date)\\n\">>logs/badger.log; badger 2>&1 | tee -a logs/badger.log\n exit 0\n ;;\n core)\n echo -e \"\\n$(date)\\n\">>logs/validateconfig.log; validateconfig \"${s}\" 2>&1 | tee -a logs/validateconfig.log\n echo -e \"\\n$(date)\\n\">>logs/core.log; core 2>&1 | tee -a logs/core.log\n exit 0\n ;;\n\t\tconfigservice)\n echo -e \"\\n$(date)\\n\">>logs/configservice.log; configservice 2>&1 | tee -a logs/configservice.log\n exit 0\n ;;\n systeminit)\n echo -e \"\\n$(date)\\n\">>logs/systeminit.log; systeminit 2>&1 | tee -a logs/systeminit.log\n exit 0\n ;;\n logger)\n echo -e \"\\n$(date)\\n\">>logs/logger.log; logger 2>&1 | tee -a logs/logger.log\n exit 0\n ;;\n monitor)\n\t\t echo -e \"\\n$(date)\\n\">>logs/proxy.log; proxy 2>&1 | tee -a logs/proxy.log\n echo -e \"\\n$(date)\\n\">>logs/monitor.log; monitor 2>&1 | tee -a logs/monitor.log\n exit 0 \n ;;\n posttest)\n echo -e \"\\n$(date)\\n\">>logs/postInstallationLogs.log;\n config 2>&1 | tee -a logs/postInstallationLogs.log\n posttest 2>&1 | tee -a logs/postInstallationLogs.log\n exit 0\n ;;\n *)\n usage\n exit 0\n ;;\n esac\n ;;\n *)\n usage\n exit 0\n ;;\n esac\ndone\n\n# Default action: install and configure from scratch\necho \"\"\"\n\n ###### ## ## ## ## ######## #### ######## ######## \n## ## ## ## ### ## ## ## ## ## ## ## ## \n## ## ## #### ## ## ## ## ## ## ## ## \n ###### ## ## ## ## ## ######## ## ######## ## ## \n ## ## ## ## #### ## ## ## ## ## ## ## \n## ## ## ## ## ### ## ## ## ## ## ## ## \n ###### ####### ## ## ######## #### ## ## ######## $(git rev-parse --abbrev-ref HEAD)\n\n\"\"\"\n\n## Installing and configuring prerequisites\necho -e \\n$(date)\\n >> logs/validateconfig.log; validateconfig 2>&1 | tee -a logs/validateconfig.log\necho -e \\n$(date)\\n >> logs/config.log; config 2>&1 | tee -a logs/config.log\n## checking for prerequisites\necho -e \\n$(date)\\n >> logs/sanity.log; sanity 2>&1 | tee -a logs/sanity.log\necho -e \\n$(date)\\n >> logs/deps.log; deps 2>&1 | tee -a logs/deps.log\n\n## Installing services and dbs\necho -e \\n$(date)\\n >> logs/dbs.log; dbs 2>&1 | tee -a logs/dbs.log\necho -e \\n$(date)\\n >> logs/apis.log; apis 2>&1 | tee -a logs/apis.log\necho -e \\n$(date)\\n >> logs/proxies.log; proxy 2>&1 | tee -a logs/proxies.log\necho -e \\n$(date)\\n >> logs/keycloak.log; keycloak 2>&1 | tee -a logs/keycloak.log\necho -e \\n$(date)\\n >> logs/badger.log; badger 2>&1 | tee -a logs/badger.log\n" }, { "alpha_fraction": 0.6008968353271484, "alphanum_fraction": 0.6233183741569519, "avg_line_length": 34.68000030517578, "blob_id": "ffb3302cdac29775cc672b575f7f1a68d83094c0", "content_id": "7f8e077f9a72384fedc823eb6225d2a0b558e25a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 892, "license_type": "permissive", "max_line_length": 93, "num_lines": 25, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/setup.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom setuptools import setup\n\nsetup(\n name='python-keycloak',\n version='0.12.0',\n url='https://bitbucket.org/agriness/python-keycloak',\n license='GNU General Public License - V3',\n author='Marcos Pereira',\n author_email='[email protected]',\n keywords='keycloak openid',\n description=u'python-keycloak is a Python package providing access to the Keycloak API.',\n packages=['keycloak', 'keycloak.authorization', 'keycloak.tests'],\n install_requires=['requests==2.20.0', 'httmock==1.2.5', 'python-jose==1.4.0'],\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Development Status :: 3 - Alpha',\n 'Operating System :: MacOS',\n 'Operating System :: Unix',\n 'Operating System :: Microsoft :: Windows',\n 'Topic :: Utilities'\n ]\n)\n" }, { "alpha_fraction": 0.661784291267395, "alphanum_fraction": 0.6997336745262146, "avg_line_length": 70.57142639160156, "blob_id": "f4dda94af0fdff93c73977c20cbe55a44d7c6d51", "content_id": "e0514c6dd6504c07ba2998f4693c89359e2047d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1502, "license_type": "permissive", "max_line_length": 204, "num_lines": 21, "path": "/private_repo/ansible/inventory/dev/key-generate.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -euo pipefail\nread -s -p 'Enter the ansible vault password (redacted): ' vault_pass\necho\nread -s -p 'Re-enter the ansible vault password (redacted): ' confirm_vault_pass\necho\nif [[ $vault_pass == $confirm_vault_pass ]]\nthen\n echo \"$vault_pass\" > temp_vault_pass\n mkdir -p Core/keys && cd Core/keys\n for i in {1..10}; do openssl genrsa -out mobile_devicev2_c$i 2048 && openssl pkcs8 -topk8 -inform PEM -in mobile_devicev2_c$i -out mobile_devicev2_key$i -nocrypt && rm -rf mobile_devicev2_c$i ; done\n for i in {1..10}; do openssl genrsa -out accessv1_c$i 2048 && openssl pkcs8 -topk8 -inform PEM -in accessv1_c$i -out accessv1_key$i -nocrypt && rm -rf accessv1_c$i ; done\n for i in {1..10}; do openssl genrsa -out desktop_devicev2_c$i 2048 && openssl pkcs8 -topk8 -inform PEM -in desktop_devicev2_c$i -out desktop_devicev2_key$i -nocrypt && rm -rf desktop_devicev2_c$i ; done\n for i in {1..10}; do openssl genrsa -out portal_anonymous_c$i 2048 && openssl pkcs8 -topk8 -inform PEM -in portal_anonymous_c$i -out portal_anonymous_key$i -nocrypt && rm -rf portal_anonymous_c$i ; done\n for i in {1..10}; do openssl genrsa -out portal_loggedin_c$i 2048 && openssl pkcs8 -topk8 -inform PEM -in portal_loggedin_c$i -out portal_loggedin_key$i -nocrypt && rm -rf portal_loggedin_c$i ; done\n while read -r line; do ansible-vault encrypt $line --vault-password-file ../../temp_vault_pass; done <<< $(ls)\n cd ../.. && rm temp_vault_pass\n echo \"OK\"\nelse\n echo \"Vault passwords dont match\"\nfi" }, { "alpha_fraction": 0.7456828951835632, "alphanum_fraction": 0.7472527623176575, "avg_line_length": 24.479999542236328, "blob_id": "85b08d3bb89c0b5496d4c79be22e56a3c87b0497", "content_id": "e0ff0ae49283ef47c695881197fd01f6821562d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 637, "license_type": "permissive", "max_line_length": 88, "num_lines": 25, "path": "/kubernetes/opa-plugins/cmd/main.go", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/open-policy-agent/opa-envoy-plugin/plugin\"\n\t\"github.com/open-policy-agent/opa/cmd\"\n\t\"github.com/open-policy-agent/opa/runtime\"\n\t\"github.com/project-sunbird/sunbird-devops/kubernetes/opa-plugins/plugins/decisionlogs\"\n)\n\nfunc main() {\n\t// opa-envoy-plugin register\n\truntime.RegisterPlugin(\"envoy.ext_authz.grpc\", plugin.Factory{})\n\truntime.RegisterPlugin(plugin.PluginName, plugin.Factory{})\n\n\t// decision-logs-plugin register\n\truntime.RegisterPlugin(decisionlogs.PluginName, decisionlogs.Factory{})\n\n\tif err := cmd.RootCommand.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n" }, { "alpha_fraction": 0.6784141063690186, "alphanum_fraction": 0.7048457860946655, "avg_line_length": 36.83333206176758, "blob_id": "b23a7040a33bee0b69b3c929735eb7264395ca01", "content_id": "24a97a676ef8d2ea9c28c686bfc53d33d365e04e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 454, "license_type": "permissive", "max_line_length": 99, "num_lines": 12, "path": "/images/api-manager-jenkins-swarm-agent/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM vfarcic/jenkins-swarm-agent:17.10.07-4\n\nUSER root\nRUN apk --update add sudo && \\\n apk --update add python py-pip openssl ca-certificates && \\\n apk --update add --virtual build-dependencies python-dev libffi-dev openssl-dev build-base && \\\n pip install --upgrade pip cffi && \\\n pip install \"ansible==2.1.3\"\nRUN pip install PyJWT\nRUN apk add --virtual build-deps gcc python-dev musl-dev && \\\n apk add py2-psycopg2\nRUN pip install retry\n" }, { "alpha_fraction": 0.7085533142089844, "alphanum_fraction": 0.7444561719894409, "avg_line_length": 44.0476188659668, "blob_id": "9ca4ce5c90c8abe351a472b266fea94c40174ea6", "content_id": "b2b66e0acb7be999de6ba3185427fa30f81db24b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 947, "license_type": "permissive", "max_line_length": 113, "num_lines": 21, "path": "/images/kong/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM kong:0.14.1-centos\n\nENV KONG_VERSION 0.14.1\n\nCOPY docker-entrypoint.sh /docker-entrypoint.sh\nENTRYPOINT [\"/docker-entrypoint.sh\"]\n\nCOPY plugins/$KONG_VERSION/jwt/* /usr/local/share/lua/5.1/kong/plugins/jwt/\n#COPY plugins/$KONG_VERSION/prometheus/* /usr/local/share/lua/5.1/kong/plugins/prometheus/\nCOPY plugins/$KONG_VERSION/rate-limiting/policies/* /usr/local/share/lua/5.1/kong/plugins/rate-limiting/policies/\nCOPY templates/$KONG_VERSION/nginx_kong.lua /usr/local/share/lua/5.1/kong/templates/\nCOPY templates/$KONG_VERSION/kong_defaults.lua /usr/local/share/lua/5.1/kong/templates/\n\n# ensure Kong logs go to the log pipe from our entrypoint and so to docker logging\nRUN mkdir -p /usr/local/kong/logs \\\n && ln -sf /tmp/logpipe /usr/local/kong/logs/access.log \\\n && ln -sf /tmp/logpipe /usr/local/kong/logs/error.log \\\n && ln -sf /tmp/logpipe /usr/local/kong/logs/admin_access.log\n\nEXPOSE 8000 8443 8001 7946\nCMD [\"kong\", \"start\"]\n\n" }, { "alpha_fraction": 0.665648877620697, "alphanum_fraction": 0.6671755909919739, "avg_line_length": 30.975608825683594, "blob_id": "a65b02b07ad6869f04864d357fcde3550db114b7", "content_id": "d0bf228439e2b53aee4ecda78911cc730a56e71d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1310, "license_type": "permissive", "max_line_length": 81, "num_lines": 41, "path": "/deploy/deploy-azure.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# Provision servers\nset -eu -o pipefail\nset -x\n\nsource deployments/deployment/app/env.sh\nAZURE_APP_DEPLOYMENT_NAME=\"$AZURE_DEPLOYMENT_NAME-app\"\nAZURE_DB_DEPLOYMENT_NAME=\"$AZURE_DEPLOYMENT_NAME-db\"\naz login\naz account set --subscription \"${AZURE_SUBSCRIPTION}\"\naz group create \\\n --name $AZURE_RG_NAME \\\n --location $AZURE_RG_LOCATION\naz group deployment create \\\n --name $AZURE_APP_DEPLOYMENT_NAME \\\n --mode \"Incremental\" \\\n --resource-group $AZURE_RG_NAME \\\n --template-file \"./deployments/deployment/app/azuredeploy.json\" \\\n --parameters \"@./deployments/deployment/app/azuredeploy.parameters.json\" \\\n --verbose \nif [ -e ./deployments/deployment/db/azuredeploy.parameters.json ]; then\n az group deployment create \\\n --name $AZURE_DB_DEPLOYMENT_NAME \\\n --mode \"Incremental\" \\\n --resource-group $AZURE_RG_NAME \\\n --template-file \"./deployments/deployment/db/azuredeploy.json\" \\\n --parameters \"@./deployments/deployment/db/azuredeploy.parameters.json\" \\\n --verbose \nelse\n echo -e \"DB Setup skipped\"\nfi\n# az vm create \\\n# --resource-group $AZURE_RG_NAME \\\n# --name DB-1 \\\n# --image UbuntuLTS \\\n# --public-ip-address \"\"\n# --ssh-key-value \n# --vnet-name MyVnet \n# --subnet subnet1\naz logout\nexit" }, { "alpha_fraction": 0.6301887035369873, "alphanum_fraction": 0.6415094137191772, "avg_line_length": 32.125, "blob_id": "3a5af962a356c26cb7dcac69f5f1c473b873909d", "content_id": "4e98719cd5a3af2537996d908eeab335d1b3dd10", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 265, "license_type": "permissive", "max_line_length": 137, "num_lines": 8, "path": "/images/azure-ambari-prometheus-exporter/build.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nbuild_tag=$1\nnode=$2\norg=$3\n\ndocker build -f Dockerfile -t ${org}/azure-ambari-prometheus-exporter:${build_tag} .\necho {\\\"image_name\\\" : \\\"azure-ambari-prometheus-exporter\\\", \\\"image_tag\\\" : \\\"${build_tag}\\\", \\\"node_name\\\" : \\\"$node\\\"} > metadata.json\n" }, { "alpha_fraction": 0.6505133509635925, "alphanum_fraction": 0.6751540303230286, "avg_line_length": 32.342464447021484, "blob_id": "869a1dd78f782210fa309cbc73e85383f7e4d327", "content_id": "a740a0ababcd6f718b6ab57d8676ccbb266ca49c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2435, "license_type": "permissive", "max_line_length": 79, "num_lines": 73, "path": "/deploy/system-check.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# System Health check\n# set -o errexit\nexport TERM=xterm-color\nexport GREP_OPTIONS='--color=auto' GREP_COLOR='1;32'\nexport CLICOLOR=1\nexport LSCOLORS=ExFxCxDxBxegedabagacad\n\nexport COLOR_NC='\\e[0m' # No Color\nexport COLOR_WHITE='\\e[1;37m'\nexport COLOR_BLACK='\\e[0;30m'\nexport COLOR_BLUE='\\e[0;34m'\nexport COLOR_LIGHT_BLUE='\\e[1;34m'\nexport COLOR_GREEN='\\e[0;32m'\nexport COLOR_LIGHT_GREEN='\\e[1;32m'\nexport COLOR_CYAN='\\e[0;36m'\nexport COLOR_LIGHT_CYAN='\\e[1;36m'\nexport COLOR_RED='\\e[0;31m'\nexport COLOR_LIGHT_RED='\\e[1;31m'\nexport COLOR_PURPLE='\\e[0;35m'\nexport COLOR_LIGHT_PURPLE='\\e[1;35m'\nexport COLOR_BROWN='\\e[0;33m'\nexport COLOR_YELLOW='\\e[1;33m'\nexport COLOR_GRAY='\\e[0;30m'\nexport COLOR_LIGHT_GRAY='\\e[0;37m'\n\nexport L=\"\\n*******************************\\n\"\n\nclear\necho -e $COLOR_WHITE$L\"VM CHECKS\"$L\necho -e $COLOR_GREEN\"Date: \" $COLOR_NC$(date +%c)\necho -e $COLOR_GREEN\"OS: \" $COLOR_NC$(uname -srm)\necho -e $COLOR_GREEN\"Uptime:\" $COLOR_NC$(/usr/bin/uptime)\necho -e $COLOR_GREEN\"RAM:\" $COLOR_NC\n/usr/bin/free -m\necho -e $COLOR_GREEN\"Testing internet connectivity:\" $COLOR_NC\ncurl -sSf https://github.com/project-sunbird/sunbird-devops > /dev/null\necho -e $COLOR_GREEN\"Checked\" $COLOR_NC\necho -e $COLOR_GREEN\"Disk Usage:\" $COLOR_NC\n/bin/df -h\necho -e $COLOR_GREEN\"CPU Usage:\" $COLOR_NC\nmpstat\necho -e $COLOR_GREEN\"Zombie processes:\" $COLOR_NC\nps -eo stat,pid|grep -w Z|awk '{print $2}'\necho -e $COLOR_GREEN\"RAM Usage:\" $COLOR_NC\nfree -m\necho -e $COLOR_GREEN\"TOP Memory hoggers:\" $COLOR_NC\nps -eo pmem,pcpu,pid,ppid,user,stat,args | sort -k 1 -r | head -6|sed 's/$/\\n/'\necho -e $COLOR_GREEN\"TOP CPU hoggers:\" $COLOR_NC\nps -eo pcpu,pmem,pid,ppid,user,stat,args | sort -k 1 -r | head -6|sed 's/$/\\n/'\n\nif command -v docker 2>/dev/null; then\n echo -e $COLOR_WHITE$L\"DOCKER CHECKS\"$L\n echo -e $COLOR_GREEN\"Version: \" $COLOR_NC$(docker -v)\nelse\n echo -e $COLOR_RED$L\"Skipping DOCKER CHECKS\"$L $COLOR_NC\nfi\n\nif command -v docker swarm 2>/dev/null; then\n echo -e $COLOR_WHITE$L\"SWARM CHECKS\"$L\n echo -e $COLOR_GREEN\"Nodes: \" $COLOR_NC\n docker node ls\n echo -e $COLOR_GREEN\"Services: \" $COLOR_NC\n docker service ls\n echo -e $COLOR_GREEN\"Networks: \" $COLOR_NC\n docker network ls\n echo -e $COLOR_GREEN\"Configs: \" $COLOR_NC\n docker config ls\n echo -e $COLOR_GREEN\"Stats: \" $COLOR_NC\n docker stats --no-stream\nelse\n echo -e $COLOR_RED$L\"Skipping SWARM CHECKS\"$L $COLOR_NC\nfi\n\n" }, { "alpha_fraction": 0.6293375492095947, "alphanum_fraction": 0.6892744302749634, "avg_line_length": 29.190475463867188, "blob_id": "8eb17487fe849633b78136ce6becb81d0ce14fe0", "content_id": "7171e26e8a1879166bbc43d1eeffcedfe2fb0bd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 634, "license_type": "permissive", "max_line_length": 155, "num_lines": 21, "path": "/deploy/restore_elasticsearch.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nbackup_path=/etc/elasticsearch/backup\nes_ip=$(hostname -i)\n#es_ip=$(ip route get 8.8.8.8 | awk '{print $NF; exit}')\n\n#Removing exiting indexes \ncurl http://\"$es_ip\":9200/_cat/indices?v | awk '{print $3}' | awk 'NR>1' > ~/index.txt \n\nwhile read line;\ndo\n\tcurl -XDELETE http://\"$es_ip\":9200/$line\ndone < ~/index.txt\n\nrm -rf ~/index.txt\n\n#Provide snapshot id for restore of elasticsearch ex: ./restore.sh snapshot_09_04_2018105317, snapshot ID can be found in /etc/elasticsearch/backup/index-0\nsnapshot_id=$1\n\ncurl -XPOST http://\"$es_ip\":9200/_snapshot/my_backup/$snapshot_id/_restore\n\ncurl http://\"$es_ip\":9200/_cat/indices?v\n" }, { "alpha_fraction": 0.6304079294204712, "alphanum_fraction": 0.7101359963417053, "avg_line_length": 33.446807861328125, "blob_id": "418a0f1da42da3bd44ab2f94fb75d6571ce6e572", "content_id": "38e8369bba360043d45c06c79679498bddb0c0fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1618, "license_type": "permissive", "max_line_length": 89, "num_lines": 47, "path": "/deploy/jenkins/jenkins-mobile-slave-setup.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nbold=$(tput bold)\nnormal=$(tput sgr0)\n\necho -e \"\\n\\e[0;32m${bold}Updating the apt repo${normal}\\n\"\napt update\n\necho -e \"\\n\\e[0;32m${bold}Installating JDK11${normal}\\n\"\napt install -y openjdk-11-jdk\n\necho -e \"\\n\\e[0;32m${bold}Installating Git ${normal}\"\napt install -y git\n\necho -e \"\\n\\e[0;32m${bold}Installating zip unzip${normal}\"\napt install -y unzip zip\n\necho -e \"\\n\\e[0;32m${bold}Installating JQ${normal}\"\napt install -y jq\n\necho -e \"\\n\\e[0;32m${bold}Installating Gradle-6.5.1${normal}\"\nwget -O gradle-6.5.1.zip https://services.gradle.org/distributions/gradle-6.5.1-all.zip\nunzip -q gradle-6.5.1.zip\nmkdir -p /usr/lib/gradle\nmv gradle-6.5.1 6.5.1\nsudo mv 6.5.1 /usr/lib/gradle/\n\necho -e \"\\n\\e[0;32m${bold}Installating Gradle-7.4.1${normal}\"\nwget -O gradle-7.4.1.zip 'https://services.gradle.org/distributions/gradle-7.4.1-all.zip'\nunzip -q gradle-7.4.1.zip\nmkdir -p /opt/gradle\nmv gradle-7.4.1 /opt/gradle/\n\necho -e \"\\n\\e[0;32m${bold}Installating node\"\nwget https://nodejs.org/download/release/v12.20.0/node-v12.20.0-linux-x64.tar.gz\ntar -xvf node-v12.20.0-linux-x64.tar.gz\nmv node-v12.20.0-linux-x64 /usr/local/lib/\nln -s /usr/local/lib/node-v12.20.0-linux-x64/bin/node /usr/bin/node\nln -s /usr/local/lib/node-v12.20.0-linux-x64/bin/npm /usr/bin/npm\n\necho -e \"\\n\\e[0;32m${bold}Installating node modules\"\nnpm install -g ionic\nnpm install -g [email protected]\nnpm install -g cordova-res\nln -s /usr/local/lib/node-v12.20.0-linux-x64/bin/ionic /usr/bin/ionic\nln -s /usr/local/lib/node-v12.20.0-linux-x64/bin/cordova /usr/bin/cordova\n\necho -e \"\\n\\e[0;32m${bold}Jenkins slave installation complete..${normal}\"" }, { "alpha_fraction": 0.7685950398445129, "alphanum_fraction": 0.7823691368103027, "avg_line_length": 17.149999618530273, "blob_id": "d231631b2d47a1f37c2994026cc77c542468a46c", "content_id": "beba479d4f915240bcd71a0a0c70f3a1c301a0d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 726, "license_type": "permissive", "max_line_length": 117, "num_lines": 40, "path": "/ansible/roles/cassandra-db-update/templates/alter_user_feed_table.cql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "copy sunbird.user_feed(\nid,\ncategory,\ncreatedby,\ncreatedon,\ndata,\nexpireon,\npriority,\nstatus,\nupdatedby,\nupdatedon,\nuserid) to 'user_feed_{{timestamp}}.csv' with header=true and numprocesses=8 and maxattempts=10;\n\nDROP TABLE IF EXISTS sunbird.user_feed;\n\nCREATE TABLE sunbird.user_feed(\nid text,\ncategory text,\ncreatedby text,\ncreatedon timestamp,\ndata text,\nexpireon timestamp,\npriority int,\nstatus text,\nupdatedby text,\nupdatedon timestamp,\nuserid text,\nPRIMARY KEY(userId, category, id));\n\ncopy sunbird.user_feed(id,\ncategory,\ncreatedby,\ncreatedon,\ndata,\nexpireon,\npriority,\nstatus,\nupdatedby,\nupdatedon,\nuserid) from 'user_feed_{{timestamp}}.csv' with header=true and chunksize=2000 and numprocesses=8 and maxattempts=10;\n" }, { "alpha_fraction": 0.6037735939025879, "alphanum_fraction": 0.650943398475647, "avg_line_length": 20.200000762939453, "blob_id": "6f0c0b8647e71e725168f2419e3b459a5bb3d86d", "content_id": "acc98d5f3a7c36eae50fec5ee92cf7d0a002cb10", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 106, "license_type": "permissive", "max_line_length": 33, "num_lines": 5, "path": "/images/kong/installDeps.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Build script\n# set -o errexit\napk -v --update --no-cache add jq\napk -v add ansible=2.3.0.0-r1\n" }, { "alpha_fraction": 0.694656491279602, "alphanum_fraction": 0.7175572514533997, "avg_line_length": 42.66666793823242, "blob_id": "084e5197d3b07a4e89b603214c8b3f6dd5d555c6", "content_id": "cb2d297ec07552e8dd312693b027621a3ebacc60", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 131, "license_type": "permissive", "max_line_length": 111, "num_lines": 3, "path": "/images/logstash_5.6/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM logstash:5.6\n\nENTRYPOINT [\"/usr/share/logstash/bin/logstash\",\"--pipeline.batch.size\",\"1\",\"-f\",\"/etc/telemetry-logstash.conf\"]\n" }, { "alpha_fraction": 0.5497651100158691, "alphanum_fraction": 0.5538541674613953, "avg_line_length": 38.225257873535156, "blob_id": "b733630b8599e86172c9d0d67c0c7d727b7dc0f4", "content_id": "3abf3396c1339f5d5c69ece82bc441436da9ec81", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11494, "license_type": "permissive", "max_line_length": 295, "num_lines": 293, "path": "/images/azure-ambari-prometheus-exporter/collector.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport yaml\nimport re\nimport time\nimport logging\nimport datetime\nfrom pytz import timezone\nfrom datetime import timedelta,date\nfrom prometheus_client import start_http_server\nfrom prometheus_client.core import GaugeMetricFamily, REGISTRY\nfrom expiringdict import ExpiringDict\nimport requests\n\nLOGLEVEL = os.getenv('LOGLEVEL', 'INFO').upper()\nlogging.basicConfig(\n format='%(asctime)s - %(levelname)s - %(message)s'\n , datefmt='%m/%d/%Y %I:%M:%S %p'\n , level=LOGLEVEL\n)\n\nBATCH_DELAY = os.getenv('BATCH_DELAY', 60)\nCONF_FILE = os.getenv('CONF_FILE', 'conf/components.yaml')\n\n\n\nclass AmbariMetricCollector(object):\n def __init__(self, conf_file):\n self.cache = ExpiringDict(max_len=10000, max_age_seconds=86400)\n self.prom_metrics = {}\n self.host = {}\t\n self.ambari_info = {\n 'AMBARI_USER': os.getenv('AMBARI_USER')\n , 'AMBARI_PASS': os.getenv('AMBARI_PASS')\n }\n\n with open(conf_file, \"r\") as read_conf_file:\n conf = yaml.load(read_conf_file)\n\n self.conf_nn, self.conf_rm, self.conf_alert, self.conf_apphistory = self._parse_conf(conf)\n\n def _parse_conf(self, conf):\n conf_nn = conf.get('namenode', None)\n conf_rm = conf.get('resourcemanager', None)\n conf_alert = conf.get('ambari_alert', None)\n conf_apphistory= conf.get('ambari_apphistory', None)\n\n return conf_nn, conf_rm, conf_alert, conf_apphistory\n\n def _parse_metrics(self, data, prefix, metrics): \t\t\n for k, v in data.items():\n if type(v) is dict:\n prefix.append(k)\n self._parse_metrics(v, prefix, metrics)\n if len(prefix) > 0:\n prefix.pop(len(prefix) - 1)\n else:\t\n metric_name = '{}_{}'.format('_'.join(prefix), k)\n\n if type(v) is int or type(v) is float:\n metrics[metric_name] = v\n\n def _parse_cluster_metrics(self, data, prefix, metrics, host): \n for k, v in data.items():\n if k in ('HostRoles'):\n host['component_name'] = str(v['component_name'])\n host['host_name']= v['host_name'].replace(\".\", \"_\").replace(\"-\", \"_\")\n elif type(v) is dict:\n prefix.append(k)\n self._parse_cluster_metrics(v, prefix, metrics, host)\n if len(prefix) > 0:\n prefix.pop(len(prefix) - 1)\n else:\n metric_name = '{}_{}'.format('_'.join(prefix), k)\n if type(v) is int or type(v) is float:\n if bool(host) :\n prom_metric = GaugeMetricFamily(metric_name, metric_name, labels=['component_name','host_name'])\n prom_metric.add_metric([host['component_name'],host['host_name']],v)\n metric_name +=(host['host_name'])\n metrics[metric_name] = prom_metric\n\n def _parse_with_filter(self, data, prefix, metrics, conf):\n new_metrics = {}\n self._parse_metrics(data, prefix, new_metrics)\n\n if conf.get('white_list', None):\n self._filter_metric_in_white_list(new_metrics, conf.get('white_list', None))\n elif conf.get('black_list', None):\n self._filter_metric_in_black_list(new_metrics, conf.get('black_list', None))\n\n metrics.update(new_metrics)\n\n def _parse_with_clusterfilter(self, data, prefix, metrics, conf):\n new_metrics = {}\n host = {}\n self._parse_cluster_metrics(data, prefix, new_metrics, host)\n\n if conf.get('white_list', None):\n self._filter_metric_in_white_list(new_metrics, conf.get('white_list', None))\n elif conf.get('black_list', None):\n self._filter_metric_in_black_list(new_metrics, conf.get('black_list', None))\n\n self.prom_metrics.update(new_metrics)\n metrics.update(new_metrics)\n\n def _parse_apphistory_metrics(self, data, prefix, app_id, metrics,group_metric):\n for k, v in data.items():\n if type(v) is dict:\n prefix.append(k)\n self._parse_metrics(v, prefix, metrics)\n if len(prefix) > 0:\n prefix.pop(len(prefix) - 1)\n else:\n if len(prefix) > 0:\n metric_name = '{}_{}'.format('_'.join(prefix), k)\n else:\n metric_name = k\n\n if type(v) is int or type(v) is float:\n prom_metric = GaugeMetricFamily(metric_name, metric_name, labels=list(group_metric.keys()))\n prom_metric.add_metric(list(group_metric.values()),v)\n metric_name += app_id\n metric_name += str(group_metric['stageId'])\n metrics[metric_name] = prom_metric\n\n def _parse_apphistory_with_filter(self, data, prefix, app_id, group_metric, metrics, conf):\n new_metrics = {}\n host = {}\n self._parse_apphistory_metrics(data, prefix, app_id, new_metrics, group_metric)\n\n if conf.get('white_list', None):\n self._filter_metric_in_white_list(new_metrics, conf.get('white_list', None))\n elif conf.get('black_list', None):\n self._filter_metric_in_black_list(new_metrics, conf.get('black_list', None))\n for k,v in new_metrics.items():\n if(len(self.cache) == 0 or k not in self.cache.keys()):\n self.cache[k] = v\n self.prom_metrics[k] = v\n metrics[k] = v\n else:\n #self.prom_metrics.pop(k,'No Key found')\n metrics.pop(k,'No Key found')\n \n def _filter_by_rule(self, metrics, rules, is_wl=True):\n if rules is None:\n return\n\n remove_metrics = []\n for k, v in metrics.items():\n if is_wl:\n remove = True\n for bl in rules:\n if re.search(bl, k):\n remove = False\n break\n\n if remove:\n remove_metrics.append(k)\n else:\n for bl in rules:\n if re.search(bl, k):\n remove_metrics.append(k)\n break\n\n for rm in remove_metrics:\n if rm in metrics:\n del metrics[rm]\n\n def _filter_metric_in_black_list(self, metrics, metrics_bl=None):\n self._filter_by_rule(metrics, metrics_bl, is_wl=False)\n\n def _filter_metric_in_white_list(self, metrics, metrics_wl=None):\n self._filter_by_rule(metrics, metrics_wl, is_wl=True)\n\n def _collect_ambari_alerts(self, metrics):\n try:\n ambari_alert_url = os.getenv('AMBARI_ALERT_URL', '')\t\n data = self._call_ambari_api(ambari_alert_url)\n except Exception as e:\n logging.error('Call Ambari API error.\\n {}'.format(e))\n\n return\n\n self._parse_with_filter(data['alerts_summary'], ['ambari_alert'], metrics, self.conf_alert)\n\n def _collect_namenode_metrics(self, metrics):\n try:\n ambari_metrics_url = os.getenv('AMBARI_METRICS_URL', '')\n data = self._call_json_api(ambari_metrics_url)\n except Exception as e:\n logging.error('Call Namenode JMX error.\\n {}'.format(e))\n\n return\n\n for item in data['items']:\n self._parse_with_clusterfilter(item, ['cluster'], metrics, self.conf_nn)\n\n def _collect_resourcemanager_metrics(self, metrics):\n try:\n data = self._call_json_api(os.getenv('AMBARI_RM_URL', ''), headers={'Accept': 'application/json'})\n except Exception as e:\n logging.error('Call Resource Manager metrics error.\\n {}'.format(e))\n return\n\n if not data.get('clusterMetrics'):\n return\n\n self._parse_with_filter(data['clusterMetrics'], ['resourcemanager'], metrics, self.conf_rm)\n\n def _collect_apphistory_metrics(self, metrics):\n group_metric={}\n date_today = (int(date.today().strftime('%s')) * 1000)\n try:\n url = self.conf_apphistory['url']+'?minDate='+(datetime.datetime.now(timezone('GMT'))-datetime.timedelta(minutes = 10)).strftime('%Y-%m-%dT%H:%M:%S.000GMT')+'&maxDate='+(datetime.datetime.now(timezone('GMT'))+datetime.timedelta(minutes = 10)).strftime('%Y-%m-%dT%H:%M:%S.000GMT')\n data = self._call_json_api(url)\n except Exception as e:\n logging.error('Call Namenode JMX error.\\n {}'.format(e))\n return\n for item in data:\n latest_attempt = len(item['attempts'])\n if item['attempts'][latest_attempt-1]['endTimeEpoch'] >= date_today:\n app_data= self._call_json_api(os.getenv('AMBARI_APPHISTORY_URL', '')+r\"/\"+item['id']+r\"/\"+str(latest_attempt)+r\"/\"+\"stages\")\n group_metric['appname'] = item['name'].replace(\" \", \"\")\n for data_item in app_data :\n data_item['reportDate'] = item['attempts'][latest_attempt-1]['lastUpdated']\n data_item['timeTaken']= item['attempts'][latest_attempt-1]['duration']\n for label in self.conf_apphistory['labels']:\n group_metric[label]= str(data_item[label])\n self._parse_apphistory_with_filter(data_item,[] ,item['id'], group_metric , metrics, self.conf_apphistory) \n\n def _collect(self):\n metrics = {}\n labels = {}\n host = {}\n self._collect_resourcemanager_metrics(metrics)\n self._collect_ambari_alerts(metrics)\n self._collect_namenode_metrics(metrics)\n self._collect_apphistory_metrics(metrics)\n\n for k, v in metrics.items():\n prom_metric = self.prom_metrics.get(k, None)\n if not prom_metric:\n prom_metric = GaugeMetricFamily(k, k, labels=['cluster_name', 'component_name', 'host_name'])\n self.prom_metrics[k] = prom_metric\n prom_metric.add_metric(list(labels.values()), v)\n\n def collect(self):\n logging.info('Start fetching metrics')\n self._collect()\n logging.info('Finish fetching metrics')\n for m in list(self.prom_metrics.values()):\n yield m\n\n def _call_ambari_api(self, url):\n \"\"\"\n Call Ambari's API to return json data\n Sample curl\n curl -k \\\n -u username:password \\\n -H 'X-Requested-By: ambari' \\\n -X GET \\\n \"https://localhost:8080/api/v1/clusters/trustingsocial/host_components?fields=metrics/*\"\n \"\"\"\n\n ambari_info = self.ambari_info\n\n response = requests.get(\n url\n , auth=(ambari_info['AMBARI_USER'], ambari_info['AMBARI_PASS'])\n , headers={'X-Requested-By': 'ambari'}\n , verify=False\n )\n\n if response.status_code != requests.codes.ok:\n return {}\n return response.json()\n\n def _call_json_api(self, url, headers={}):\n ambari_info = self.ambari_info\n response = requests.get(url, auth=(ambari_info['AMBARI_USER'], ambari_info['AMBARI_PASS']), headers=headers)\n \t\n if response.status_code != requests.codes.ok:\n return {}\n return response.json()\n\n\nif __name__ == \"__main__\":\n collector = AmbariMetricCollector(CONF_FILE)\n\n REGISTRY.register(collector)\n start_http_server(9999)\n while True:\n time.sleep(1)\n\n" }, { "alpha_fraction": 0.661497175693512, "alphanum_fraction": 0.6787950992584229, "avg_line_length": 31.55339813232422, "blob_id": "4afa90484ddb0809d4edfd66b98e07990990b15e", "content_id": "ce22a25494cfa6a07d5ce524bfd1d4073b5c176e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3353, "license_type": "permissive", "max_line_length": 590, "num_lines": 103, "path": "/ansible/static-files/api_count_query.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n###-----------------------------------------------------###\n# Author:: Kaliraja\n# Description:: This script is to query the api calls data \n# from log-es and send as a report to email and uploading\n# the same to azure storage.\n###-----------------------------------------------------###\n\n\n#date variables\nprev_day=`date \"+%s\" -d \"yesterday 03:30:00\"`\ntoday=`date \"+%s\" -d \"today 03:30:00\"`\ndate=`date +\"%m-%d-%Y\"`\n\n#prev_day=`date \"+%s\" -d \"yesterday -7 day 03:30:00\"`\n#today=`date \"+%s\" -d \"yesterday -6 day 03:30:00\"`\n#date=`date +%m-%d-%y --date=\"yesterday -6 day\" | sed 's/19/2019/'`\n\n#api variable\ncontentsearch=\"/api/composite/v1/search\"\ncontentread=\"/api/content/v1/read/\"\ntelemetry=\"/api/data/v1/telemetry\"\nregistermobile=\"/api/api-manager/v1/consumer/mobile_device/credential/register\"\n\n#filename variable\ncontentsearch_filename=contentsearch-$date.txt\ncontentread_filename=contentread-$date.txt\ntelemetry_filename=telemetry-$date.txt\nmobiledevice_registerfilename=registermobile-$date.txt\n\n#sedngrid variable\nsguser=\"$1\"\nsgpass=\"$2\"\ncontainer_name=\"$3\"\naccount_name=\"$4\"\nstorage_key=\"$5\"\n\n\nquery(){\n curl -H 'Content-Type:application/json' -s -XPOST 'localhost:9200/logstash-*/_search?pretty' -d '{\"query\":{\"bool\":{\"must\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"\\\"'$1'\\\"\"}},\"filter\":{\"bool\":{\"must\":[{\"range\":{\"@timestamp\":{\"gte\":\"'\"$prev_day\"'\",\"lte\":\"'\"$today\"'\",\"format\":\"epoch_second\"}}}],\"must_not\":[]}}}},\"size\":0,\"aggs\":{\"2\":{\"date_histogram\":{\"field\":\"@timestamp\",\"interval\":\"15m\",\"time_zone\":\"Asia/Kolkata\",\"min_doc_count\":1,\"extended_bounds\":{\"min\": 0,\"max\": 500}}}}}' | jq -r '.aggregations.\"2\".buckets[]|.key_as_string+\" \"+ (.doc_count|tostring)' | column -t > $2\n}\n\n#Executing content search query\n\nquery $contentsearch $contentsearch_filename\n\n#Execurting the contentread query\n\nquery $contentread $contentread_filename\n\n#Executing the telemetry query\n\nquery $telemetry $telemetry_filename\n\n#Executing the registermobiledevice query\n\nquery $registermobile $mobiledevice_registerfilename\n\n#sending an email with an attachment\n\ncurl https://api.sendgrid.com/api/mail.send.json \\\n {{ api_report_mailing_list }} -F subject=\"Data for Diksha api calls\" \\\n -F text=\"Data\" --form-string html=\"<strong>Hi Team, PFA.</strong>\" \\\n -F [email protected] -F api_user=\"$sguser\" -F api_key=\"$sgpass\" \\\n -F files\\[contentsearch.txt\\]=@contentsearch-$date.txt -F files\\[contentread.txt\\]=@contentread-$date.txt -F files\\[telemetry.txt]=@telemetry-$date.txt -F files\\[registermobile.txt]=@registermobile-$date.txt\n\n\n# uploading the reports to storage\n\naz storage blob upload \\\n--container-name $container_name \\\n--file contentsearch-$date.txt \\\n--name contentsearch-$date.txt \\\n--account-name $account_name \\\n--account-key $storage_key\n\naz storage blob upload \\\n--container-name $container_name \\\n--file contentread-$date.txt \\\n--name contentread-$date.txt \\\n--account-name $account_name \\\n--account-key $storage_key\n\n\naz storage blob upload \\\n--container-name $container_name \\\n--file telemetry-$date.txt \\\n--name telemetry-$date.txt \\\n--account-name $account_name \\\n--account-key $storage_key\n\naz storage blob upload \\\n--container-name $container_name \\\n--file registermobile-$date.txt \\\n--name registermobile-$date.txt \\\n--account-name $account_name \\\n--account-key $storage_key\n\n\n# deleting files\n\nrm *-$date.txt\n" }, { "alpha_fraction": 0.7458333373069763, "alphanum_fraction": 0.7770833373069763, "avg_line_length": 29.0625, "blob_id": "62a98bbc722ca595f1818f6956f5c43fb801bbf3", "content_id": "ee2f8d478d88ca566508ebbf7fe84e7c158ae4e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 480, "license_type": "permissive", "max_line_length": 110, "num_lines": 16, "path": "/deploy/restore_postgres.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n## Temporary backup directory\npostgresql_backup_dir=/tmp/postgresql-backup\n\n#Provide backup filename as ex: sudo bash restore_postgres.sh postgresql_backup_UTC-2018-04-08-21-16-05.sql.gz\nbackupfile=$1\n\nsqlfile=\"${backupfile//.gz}\"\n\ngunzip $postgresql_backup_dir/$backupfile -d $postgresql_backup_dir/$sqlfile \n\npostgresql_backup_gzip_file_path=$postgresql_backup_dir/$sqlfile\n\n# restore process\nsudo su postgres -c \"psql -f $postgresql_backup_gzip_file_path postgres\"" }, { "alpha_fraction": 0.6943995952606201, "alphanum_fraction": 0.6973613500595093, "avg_line_length": 26.917293548583984, "blob_id": "80adec78a25a647e6d8718a2f5193a8cfcdca3d9", "content_id": "356f5ec6e7ebfb9b4f9859e50ef920fa8b99ce67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3714, "license_type": "permissive", "max_line_length": 122, "num_lines": 133, "path": "/ansible/roles/update_hosts/templates/generate_host.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# This script will create dynamic host file for multinodal installation\n# Ansible will overwrite all variables, and creates a bash script\n# Executing that will generate formatted host entries for ansible\n#\n# Authors: <[email protected]> <[email protected]>\n\nelasticsearch_ips=\"{{elasticsearch_host if elasticsearch_host else database_host}}\"\ncassandra_ips=\"{{cassandra_host if cassandra_host else database_host}}\"\npostgres_master_ips=\"{{postgres_master_host if postgres_master_host else database_host}}\"\npostgres_slave_ips=\"{{postgres_slave_host if postgres_slave_host else database_host}}\"\nswarm_manager_ips=\"{{swarm_manager_host if swarm_manager_host else application_host}}\"\nswarm_node_ips=\"{{swarm_node_host if swarm_node_host else application_host}}\"\nkeycloak_ips=\"{{keycloak_host if keycloak_host else application_host}}\"\nlog_es_ips=\"{{log_es_host if log_es_host else application_host}}\"\nswarm_agent_for_prometheus_ips=\"{{prometheus_host if prometheus_host else application_host}}\"\nswarm_agent_for_grafana_ips=\"{{grafana_host if grafana_host else application_host}}\"\nswarm_agent_for_alertmanager_ips=\"{{alertmanager_host if alertmanager_host else application_host}}\"\n\n# Creating an array from comma seperated ips\nips(){\n IFS=',' read -ra arr <<<$1\n}\n\n# Generating service specific variables\nservice_vars(){\n case $1 in\n es)\n echo -n es_instance_name=\"es-$count\" es_etc_node_master=true es_etc_node_data=true \n group_name=es\n ;;\n\tlog-es)\n echo -n es_instance_name=\"es-$count\" es_etc_node_master=true es_etc_node_data=true node_name=dev-log-es-$count\n group_name=log-es\n ;;\n swarm-manager|swarm-worker)\n echo -n \"swarm_master=true\"\n ;;\n *)\n ;;\n esac\n}\n\nget_host_entries()\n{\n if [ $# -ne 2 ];then \n echo \"Usage: get_host_entries <comma seperated ips> <service name>\"\n exit 1\n fi\n\n # Generating ip array of the service\n ips $2\n \n count=1\n for ip in ${arr[@]}\n do\n # Creating group/host name for ansible\n echo -e \"\\n[$1-$count] \"\n echo -n $ip ansible_ssh_user=\"{{ssh_ansible_user}}\" ansible_ssh_private_key_file=\"{{ansible_private_key_path}}\" \\\n ansible_sudo_pass=\"{{sudo_passwd}} \"\n service_vars $1\n ((count++))\n done\n echo -e \"\\n\"\n\n # Creating groups\n count=1\n echo \"[$1:children]\"\n for ip in ${arr[@]}\n do\n echo \"$1-$count\"\n ((count++))\n done\n\n unset arr\n unset count\n}\n\nget_host_entries es $elasticsearch_ips\nget_host_entries cassandra $cassandra_ips\nget_host_entries postgresql-master $postgres_master_ips\nget_host_entries postgresql-slave $postgres_slave_ips\nget_host_entries swarm-manager $swarm_manager_ips\nget_host_entries swarm-worker $swarm_node_ips\nget_host_entries keycloak $keycloak_ips\nget_host_entries log-es $log_es_ips\nget_host_entries swarm-agent-for-prometheus $swarm_agent_for_prometheus_ips\nget_host_entries swarm-agent-for-grafana $swarm_agent_for_prometheus_ips\nget_host_entries swarm-agent-for-alertmanager $swarm_agent_for_prometheus_ips\n\n# Static Groups\n\necho \"\n[kong-api]\nlocalhost ansible_connection=local\n\n[swarm-bootstrap-manager:children]\nswarm-manager\n\n[non-swarm-nodes:children]\npostgresql-master\npostgresql-slave\nes\ncassandra\nkong-api\nkeycloak\nlog-es\n\n[swarm-nodes:children]\nswarm-manager\nswarm-bootstrap-manager\nswarm-agent-for-prometheus\nswarm-agent-for-grafana\nswarm-agent-for-alertmanager\n\n[node-exporter:children]\nnon-swarm-nodes\nswarm-manager\n\n[process-exporter:children]\nnon-swarm-nodes\nswarm-manager\n\n[log-forwarder:children]\nnon-swarm-nodes\nswarm-manager\n\n[{{env}}:children]\nnon-swarm-nodes\nswarm-nodes\nswarm-manager\n\"\n\n" }, { "alpha_fraction": 0.5785440802574158, "alphanum_fraction": 0.5900382995605469, "avg_line_length": 28, "blob_id": "1664336194afab5903f8aa1943f62eefe2049c7f", "content_id": "1fd03f95122ea331b8fa44f7c8fcfe71b691d4e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 261, "license_type": "permissive", "max_line_length": 112, "num_lines": 9, "path": "/images/kong/build.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Build script\n# set -o errexit\nbuild_tag=$1\nnode=$2\nhub_org=$3\nname=kong\ndocker build -f Dockerfile -t ${hub_org}/${name}:${build_tag} .\necho {\\\"image_name\\\" : \\\"${name}\\\", \\\"image_tag\\\" : \\\"${build_tag}\\\", \\\"node_name\\\" : \\\"$node\\\"} > metadata.json\n" }, { "alpha_fraction": 0.5037593841552734, "alphanum_fraction": 0.5413534045219421, "avg_line_length": 17.85714340209961, "blob_id": "f695b17271beb41833c643247b60001ea173daa8", "content_id": "fc12cd451edc058c8999972a814c9dde0bbca89b", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 133, "license_type": "permissive", "max_line_length": 37, "num_lines": 7, "path": "/ansible/roles/graylog/templates/mongodb_replication_params.js", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "{% for server in groups['graylog'] %}\n- {\n host_name: {{server}},\n host_port: 27017,\n host_type: replica,\n }\n{% endfor %}\n\n" }, { "alpha_fraction": 0.8363636136054993, "alphanum_fraction": 0.8363636136054993, "avg_line_length": 54, "blob_id": "0c6ca3fc5bb358c290b764ff1aa9459960945112", "content_id": "cf8adcad503ced84dff24cf5f45a4986bc2f9dc3", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 55, "license_type": "permissive", "max_line_length": 54, "num_lines": 1, "path": "/ansible/roles/postgres-migration/files/sunbird_programs/V4.4.2.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "ALTER TYPE programTargetType ADD VALUE 'questionSets';\n" }, { "alpha_fraction": 0.6008230447769165, "alphanum_fraction": 0.6242284178733826, "avg_line_length": 37.117645263671875, "blob_id": "11baccb490ec880acd4d94b09fcc8ba140bb57c2", "content_id": "af73589a9aa6c99832d84d7395e00ca7a6c9a941", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3888, "license_type": "permissive", "max_line_length": 244, "num_lines": 102, "path": "/deploy/azure_vm/azure_create_vm.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Author: Harsha <[email protected]>\n\n# update the VM details in create_vm file\n\n# checking for argumnent\nif [[ $# == '0' ]]; then\n echo \"Please provide the Input file path\"\n echo \"Usage: $0 <input_file_path>\"\n exit 1\nfi\n\n# reading input file values\nIFS=\",\"\ngrep -v -e \"^#\" -e \"^$\" $1 | while read -ra LINE\ndo\n rg=\"${LINE[0]}\"\n location=\"${LINE[1]}\"\n vnet=\"${LINE[2]}\"\n sn=\"${LINE[3]}\"\n ap=\"${LINE[4]}\"\n sp=\"${LINE[5]}\"\n nsg=\"${LINE[6]}\"\n aset=\"${LINE[7]}\"\n vname=\"${LINE[8]}\"\n size=\"${LINE[9]}\"\n baseos=\"${LINE[10]}\"\n uname=\"${LINE[11]}\"\n pubip=\"${LINE[12]}\"\n pubkey=\"${LINE[13]}\"\n\necho -e \"\\e[1;32mVM DETAILS\\e[0m\"\necho -e \"RESOURCE_GROUP=$rg\\nLOCATION=$location\\nVNET_NAME=$vnet\\nSUBNET_NAME=$sn\\nADDRESS_PREFIX=$ap\\nSUBNET_PREFIX=$sp\\nNSG=$nsg\\nAVAIL_SET=$aset\\nVM_NAME=$vname\\nSIZE=$size\\nOS=$baseos\\nUSER=$uname\\nPUBLIC_IP=$pubip\\nPATH_TO_PUB_KEY=$pubkey\"\n\n\n# valdating resource group and create if not exists\nerg=$(az group list -o table | awk -F \" \" '{print $1}' | awk 'NR>2' | grep -E \"^$rg$\")\n\nif [[ $? == \"0\" ]]; then\n echo -e \"Resource group with this name \\e[1;31m$rg\\e[0m already exists\"\nelse\n echo -e \"Creating the Resource group \\e[1;32m$rg..\\e[0m\"\n az group create --name $rg --location $location\nfi\n\n# valdating virtual network and create if not exists\nevnet=$(az network vnet list -o table | awk -F \" \" '{print $4}' | awk 'NR>2' | grep -E \"^$vnet$\")\n\nif [[ $? == \"0\" ]]; then\n echo -e \"Vnet with this name \\e[1;31m$vnet\\e[0m already exists\"\nelse\n echo -e \"Creating the Vnet \\e[1;32m$vnet..\\e[0m\"\n az network vnet create --resource-group $rg --name $vnet --address-prefix $ap --subnet-name $sn --subnet-prefix $sp\nfi\n\n\n# valdating network security group and create if not exists\nensg=$(az network nsg list -g $rg -o table | awk -F \" \" '{print $2}' | awk 'NR>2' | grep -E \"^$nsg$\")\n\nif [[ $? == \"0\" ]]; then\n echo -e \"Security group with this name \\e[1;31m$nsg\\e[0m already exists\"\nelse\n echo -e \"Creating the Security group \\e[1;32m$nsg..\\e[0m\"\n az network nsg create --name $nsg --resource-group $rg\n az network nsg rule create --resource-group $rg --nsg-name $nsg --name ssh --protocol tcp --priority 1000 --destination-port-range 22 --access allow\nfi\n\n# valdating availability set and create if not exists\neaset=$(az vm availability-set list -g $aset -o table | awk -F \" \" '{print $2}' | awk 'NR>2' | grep -E \"^$aset$\")\n\nif [[ $? == \"0\" ]]; then\n echo -e \"Availability set with this name \\e[1;31m$aset\\e[0m already exists\"\nelse\n echo -e \"Creating the Avaiablity set \\e[1;32m$aset..\\e[0m\"\n az vm availability-set create --resource-group $rg --name $aset\nfi\n\n# attaching public ip\nif [[ \"$pubip\" = \"Yes\" || \"$pubip\" = \"yes\" ]]; then\n echo \"Public IP will be assigned to the instance\"\nelif [[ \"$pubip\" = \"No\" || \"$pubip\" = \"no\" ]]; then\n echo \"Public IP will not be assigned\"\nelse\n echo \"Wrong input! please enter 'Yes' for Yes or 'No' for No\"\nfi\n\n\n# valdating vm and create if not exists\nevname=$(az vm list -g $rg -o table | awk -F \" \" '{print $2}' | awk 'NR>2' | grep -E \"^$vname$\")\n\nif [[ $? == \"0\" ]]; then\n echo -e \"Virtual Machine with this name \\e[1;31m$vname\\e[0m already exists\"\nelif [[ \"$pubip\" == \"Yes\" || \"$pubip\" == \"yes\" ]]; then\n echo -e \"Creating Your Virtual Machine \\e[1;32m$vname\\e[0m hold on..\"\n az vm create --resource-group $rg --name $vname --location $location --availability-set $aset --image $baseos --admin-username $uname --vnet-name $vnet --subnet $sn --nsg $nsg --size $size --ssh-key-value $pubkey \nelse\n echo -e \"Creating Your Virtual Machine \\e[1;32m$vname\\e[0m hold on..\"\n az vm create --resource-group $rg --name $vname --location $location --availability-set $aset --image $baseos --admin-username $uname --vnet-name $vnet --subnet $sn --nsg $nsg --size $size --public-ip-address \"\" --ssh-key-value $pubkey\nfi\n\ndone\n" }, { "alpha_fraction": 0.717391312122345, "alphanum_fraction": 0.717391312122345, "avg_line_length": 46, "blob_id": "840be7d8f0baa21a5ba7bc80d83dfe77a1d75987", "content_id": "6b2b6e8fac09da2e0ca67439e7628502d1b8344c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 46, "license_type": "permissive", "max_line_length": 46, "num_lines": 1, "path": "/ansible/artifacts/sunbird/email/theme.properties", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "locales=ca,de,en,es,fr,it,ja,lt,no,pt-BR,ru,sv" }, { "alpha_fraction": 0.6635679602622986, "alphanum_fraction": 0.6662240028381348, "avg_line_length": 51.546512603759766, "blob_id": "226988c793a89794d425b297307c49c331364c60", "content_id": "9936160f97db893eb8fd7edef7e0eefb0511163b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4518, "license_type": "permissive", "max_line_length": 145, "num_lines": 86, "path": "/ansible/static-files/kong-api-scripts/kong_apis.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "import urllib2, argparse, json\n\nfrom common import get_apis, json_request, get_api_plugins\n\ndef save_apis(kong_admin_api_url, input_apis):\n apis_url = \"{}/apis\".format(kong_admin_api_url)\n saved_apis = get_apis(kong_admin_api_url)\n\n print(\"Number of input APIs : {}\".format(len(input_apis)))\n print(\"Number of existing APIs : {}\".format(len(saved_apis)))\n\n input_api_names = [api[\"name\"] for api in input_apis]\n saved_api_names = [api[\"name\"] for api in saved_apis]\n\n print(\"Input APIs : {}\".format(input_api_names))\n print(\"Existing APIs : {}\".format(saved_api_names))\n\n input_apis_to_be_created = [input_api for input_api in input_apis if input_api[\"name\"] not in saved_api_names]\n input_apis_to_be_updated = [input_api for input_api in input_apis if input_api[\"name\"] in saved_api_names]\n saved_api_to_be_deleted = [saved_api for saved_api in saved_apis if saved_api[\"name\"] not in input_api_names]\n\n for input_api in input_apis_to_be_created:\n print(\"Adding API {}\".format(input_api[\"name\"]))\n json_request(\"POST\", apis_url, _sanitized_api_data(input_api))\n\n for input_api in input_apis_to_be_updated:\n print(\"Updating API {}\".format(input_api[\"name\"]))\n saved_api_id = [saved_api[\"id\"] for saved_api in saved_apis if saved_api[\"name\"] == input_api[\"name\"]][0]\n input_api[\"id\"] = saved_api_id\n json_request(\"PATCH\", apis_url + \"/\" + saved_api_id, _sanitized_api_data(input_api))\n\n for saved_api in saved_api_to_be_deleted:\n print(\"Deleting API {}\".format(saved_api[\"name\"]));\n json_request(\"DELETE\", apis_url + \"/\" + saved_api[\"id\"], \"\")\n\n for input_api in input_apis:\n _save_plugins_for_api(kong_admin_api_url, input_api)\n\ndef _save_plugins_for_api(kong_admin_api_url, input_api_details):\n get_plugins_max_page_size = 2000\n api_name = input_api_details[\"name\"]\n input_plugins = input_api_details[\"plugins\"]\n api_pugins_url = \"{}/apis/{}/plugins\".format(kong_admin_api_url, api_name)\n saved_plugins_including_consumer_overrides = get_api_plugins(kong_admin_api_url, api_name)\n saved_plugins_without_consumer_overrides = [plugin for plugin in saved_plugins_including_consumer_overrides if not plugin.get('consumer_id')]\n\n saved_plugins = saved_plugins_without_consumer_overrides\n input_plugin_names = [input_plugin[\"name\"] for input_plugin in input_plugins]\n saved_plugin_names = [saved_plugin[\"name\"] for saved_plugin in saved_plugins]\n\n input_plugins_to_be_created = [input_plugin for input_plugin in input_plugins if input_plugin[\"name\"] not in saved_plugin_names]\n input_plugins_to_be_updated = [input_plugin for input_plugin in input_plugins if input_plugin[\"name\"] in saved_plugin_names]\n saved_plugins_to_be_deleted = [saved_plugin for saved_plugin in saved_plugins if saved_plugin[\"name\"] not in input_plugin_names]\n\n for input_plugin in input_plugins_to_be_created:\n print(\"Adding plugin {} for API {}\".format(input_plugin[\"name\"], api_name));\n json_request(\"POST\", api_pugins_url, input_plugin)\n\n for input_plugin in input_plugins_to_be_updated:\n print(\"Updating plugin {} for API {}\".format(input_plugin[\"name\"], api_name));\n saved_plugin_id = [saved_plugin[\"id\"] for saved_plugin in saved_plugins if saved_plugin[\"name\"] == input_plugin[\"name\"]][0]\n input_plugin[\"id\"] = saved_plugin_id\n json_request(\"PATCH\", api_pugins_url + \"/\" + saved_plugin[\"id\"], input_plugin)\n\n for saved_plugin in saved_plugins_to_be_deleted:\n print(\"Deleting plugin {} for API {}\".format(saved_plugin[\"name\"], api_name));\n json_request(\"DELETE\", api_pugins_url + \"/\" + saved_plugin[\"id\"], \"\")\n\ndef _sanitized_api_data(input_api):\n keys_to_ignore = ['plugins']\n sanitized_api_data = dict((key, input_api[key]) for key in input_api if key not in keys_to_ignore)\n return sanitized_api_data\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Configure kong apis')\n parser.add_argument('apis_file_path', help='Path of the json file containing apis data')\n parser.add_argument('--kong-admin-api-url', help='Admin url for kong', default='http://localhost:8001')\n args = parser.parse_args()\n with open(args.apis_file_path) as apis_file:\n input_apis = json.load(apis_file)\n try:\n save_apis(args.kong_admin_api_url, input_apis)\n except urllib2.HTTPError as e:\n error_message = e.read()\n print(error_message)\n raise" }, { "alpha_fraction": 0.686703085899353, "alphanum_fraction": 0.755464494228363, "avg_line_length": 26.450000762939453, "blob_id": "6942e57ee78a3eeb59aee3ff4ec23d06892b3442", "content_id": "0e9dd060de4ed755ea1dd53cb0a3f193fc9313a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 2196, "license_type": "permissive", "max_line_length": 287, "num_lines": 80, "path": "/images/kong/templates/0.14.1/kong_defaults.lua", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "return [[\nprefix = /usr/local/kong/\nlog_level = notice\nproxy_access_log = logs/access.log\nproxy_error_log = logs/error.log\nadmin_access_log = logs/admin_access.log\nadmin_error_log = logs/error.log\nplugins = bundled\ncustom_plugins = NONE\nanonymous_reports = on\n\nproxy_listen = 0.0.0.0:8000, 0.0.0.0:8443 ssl\nadmin_listen = 127.0.0.1:8001, 127.0.0.1:8444 ssl\nnginx_user = nobody nobody\nnginx_worker_processes = auto\nnginx_optimizations = on\nnginx_daemon = on\nmem_cache_size = 128m\nratelimit_cache_size = 12m\nssl_cert = NONE\nssl_cert_key = NONE\nclient_ssl = off\nclient_ssl_cert = NONE\nclient_ssl_cert_key = NONE\nssl_cipher_suite = modern\nssl_ciphers = ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256\nadmin_ssl_cert = NONE\nadmin_ssl_cert_key = NONE\nupstream_keepalive = 60\nheaders = server_tokens, latency_tokens\ntrusted_ips = NONE\nreal_ip_header = X-Real-IP\nreal_ip_recursive = off\nclient_max_body_size = 0\nclient_body_buffer_size = 8k\nerror_default_type = text/plain\n\ndatabase = postgres\npg_host = 127.0.0.1\npg_port = 5432\npg_database = kong\npg_user = kong\npg_password = NONE\npg_ssl = off\npg_ssl_verify = off\ncassandra_contact_points = 127.0.0.1\ncassandra_port = 9042\ncassandra_keyspace = kong\ncassandra_timeout = 5000\ncassandra_ssl = off\ncassandra_ssl_verify = off\ncassandra_username = kong\ncassandra_password = NONE\ncassandra_consistency = ONE\ncassandra_lb_policy = RoundRobin\ncassandra_local_datacenter = NONE\ncassandra_repl_strategy = SimpleStrategy\ncassandra_repl_factor = 1\ncassandra_data_centers = dc1:2,dc2:3\ncassandra_schema_consensus_timeout = 10000\n\ndb_update_frequency = 5\ndb_update_propagation = 0\ndb_cache_ttl = 0\ndb_resurrect_ttl = 30\n\ndns_resolver = NONE\ndns_hostsfile = /etc/hosts\ndns_order = LAST,SRV,A,CNAME\ndns_stale_ttl = 4\ndns_not_found_ttl = 30\ndns_error_ttl = 1\ndns_no_sync = off\n\nlua_socket_pool_size = 30\nlua_ssl_trusted_certificate = NONE\nlua_ssl_verify_depth = 1\nlua_package_path = ./?.lua;./?/init.lua;\nlua_package_cpath = NONE\n]]\n" }, { "alpha_fraction": 0.6560356616973877, "alphanum_fraction": 0.6704389452934265, "avg_line_length": 25.990739822387695, "blob_id": "b4c2239f93062104894349f8ec545044ec116691", "content_id": "ac68bc28c9fcbd67d3d4953940fc6fafa46a7590", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2916, "license_type": "permissive", "max_line_length": 122, "num_lines": 108, "path": "/ansible/roles/elasticsearch/test/integration/helpers/serverspec/package_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'spec_helper'\n\nshared_examples 'package::init' do |es_version,plugins|\n\n describe user('elasticsearch') do\n it { should exist }\n end\n\n describe service('node1_elasticsearch') do\n it { should be_running }\n end\n\n describe package('elasticsearch') do\n it { should be_installed }\n end\n\n describe file('/etc/elasticsearch/node1/elasticsearch.yml') do\n it { should be_file }\n it { should contain 'http.port: 9200' }\n it { should contain 'transport.tcp.port: 9300' }\n it { should contain 'discovery.zen.ping.unicast.hosts: localhost:9300' }\n end\n\n describe file('/etc/elasticsearch/node1/scripts') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/node1/scripts/calculate-score.groovy') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe 'Node listening' do\n it 'listening in port 9200' do\n expect(port 9200).to be_listening\n end\n end\n\n describe file('/etc/elasticsearch/templates') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/templates/basic.json') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe 'Template Installed' do\n it 'should be reported as being installed', :retry => 3, :retry_wait => 10 do\n command = command('curl -s \"localhost:9200/_template/basic\"')\n expect(command.stdout).to match(/basic/)\n expect(command.exit_status).to eq(0)\n end\n end\n\n describe 'version check' do\n it 'should be reported as version '+es_version do\n command = command('curl -s localhost:9200 | grep number')\n expect(command.stdout).to match(es_version)\n expect(command.exit_status).to eq(0)\n end\n end\n\n describe file('/usr/share/elasticsearch/plugins') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n\n for plugin in plugins\n describe file('/usr/share/elasticsearch/plugins/'+plugin) do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n #confirm plugins are installed and the correct version\n describe command('curl -s localhost:9200/_nodes/plugins | grep \\'\"name\":\"'+plugin+'\",\"version\":\"'+es_version+'\"\\'') do\n its(:exit_status) { should eq 0 }\n end\n end\n\n\n describe file('/etc/init.d/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/default/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/sysconfig/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/usr/lib/systemd/system/elasticsearch.service') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/elasticsearch.yml') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/logging.yml') do\n it { should_not exist }\n end\n\nend\n\n" }, { "alpha_fraction": 0.6995614171028137, "alphanum_fraction": 0.7072368264198303, "avg_line_length": 22.384614944458008, "blob_id": "adfa3b362f37549b46b19be24a7352d7a7688185", "content_id": "fac9c2e53a165eda3adf4988729d87f576527005", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1824, "license_type": "permissive", "max_line_length": 122, "num_lines": 78, "path": "/ansible/roles/cassandra-restore/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "Role Name\n=========\n\nAn [Ansible] role to install [Cassandra]\n\nRequirements\n------------\n\n- Oracle Java 8\n\nInstall [Ansible] requirements `ansible-galaxy install -r requirements.yml`\n\nRole Variables\n--------------\n\n```\n---\n# defaults file for ansible-cassandra\ncassandra_cluster_group: 'cassandra-cluster-nodes'\ncassandra_cluster_name: 'Test Cluster'\ncassandra_cluster_setup: false\ncassandra_commitlog_directory: '/var/lib/cassandra/commitlog'\ncassandra_config: false\ncassandra_debian_repo_info:\n repo: 'deb http://www.apache.org/dist/cassandra/debian 36x main'\n repo_key: 'https://www.apache.org/dist/cassandra/KEYS'\ncassandra_data_file_directories:\n - '/var/lib/cassandra/data'\ncassandra_hints_directory: '/var/lib/cassandra/hints'\ncassandra_listen_address: \"{{ hostvars[inventory_hostname]['ansible_' + cassandra_listen_interface]['ipv4']['address'] }}\"\ncassandra_listen_interface: 'eth1'\ncassandra_log_dir: '/var/log/cassandra'\ncassandra_root_dir: '/etc/cassandra'\ncassandra_saved_caches_directory: '/var/lib/cassandra/saved_caches'\ncassandra_seeds: '127.0.0.1' # Only used if not setting up a cluster\ncassandra_version: '3.6'\n```\n\nDependencies\n------------\n\nReference requirements\n\nExample Playbook\n----------------\n\n```\n---\n- hosts: cassandra-cluster-nodes\n become: true\n vars:\n cassandra_cluster_setup: true\n cassandra_config: true\n pri_domain_name: 'test.vagrant.local'\n roles:\n - role: ansible-oracle-java8\n - role: ansible-cassandra\n tasks:\n```\n\nLicense\n-------\n\nBSD\n\nAuthor Information\n------------------\n\n\nLarry Smith Jr.\n- [@mrlesmithjr]\n- [EveryThingShouldBeVirtual]\n- mrlesmithjr [at] gmail.com\n\n[@mrlesmithjr]: <https://twitter.com/mrlesmithjr>\n[EveryThingShouldBeVirtual]: <http://everythingshouldbevirtual.com>\n[Ansible]: <https://www.ansible.com>\n[Cassandra]: <http://cassandra.apache.org/>\n" }, { "alpha_fraction": 0.7534246444702148, "alphanum_fraction": 0.7648401856422424, "avg_line_length": 17.25, "blob_id": "88760436ef5f5b22c7e14229fbe530ce7b448c7d", "content_id": "0489eed81e018d151b8222a8e8d98b2ca0c3186b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 438, "license_type": "permissive", "max_line_length": 69, "num_lines": 24, "path": "/images/kong/plugins/0.14.1/prometheus/handler.lua", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "local prometheus = require \"kong.plugins.prometheus.exporter\"\nlocal basic_serializer = require \"kong.plugins.log-serializers.basic\"\n\n\nprometheus.init()\n\n\nlocal PrometheusHandler = {\n PRIORITY = 13,\n VERSION = \"0.9.0\",\n}\n\nfunction PrometheusHandler.init_worker()\n prometheus.init_worker()\nend\n\n\nfunction PrometheusHandler.log()\n local message = basic_serializer.serialize(ngx)\n prometheus.log(message)\nend\n\n\nreturn PrometheusHandler\n" }, { "alpha_fraction": 0.7404625415802002, "alphanum_fraction": 0.7450088858604431, "avg_line_length": 47.644229888916016, "blob_id": "f2f46a73cb0b066af7392b209951b2d6ff0264f6", "content_id": "f919cbb670951f2ac9cad5222f73fca827b2da87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5059, "license_type": "permissive", "max_line_length": 416, "num_lines": 104, "path": "/ansible/roles/jenkins/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# Ansible Role: Jenkins CI\n\n[![Build Status](https://travis-ci.org/geerlingguy/ansible-role-jenkins.svg?branch=master)](https://travis-ci.org/geerlingguy/ansible-role-jenkins)\n\nInstalls Jenkins CI on RHEL/CentOS and Debian/Ubuntu servers.\n\n## Requirements\n\nRequires `curl` to be installed on the server. Also, newer versions of Jenkins require Java 8+ (see the test playbooks inside the `tests/` directory for an example of how to use newer versions of Java for your OS).\n\n## Role Variables\n\nAvailable variables are listed below, along with default values (see `defaults/main.yml`):\n\n jenkins_hostname: localhost\n\nThe system hostname; usually `localhost` works fine. This will be used during setup to communicate with the running Jenkins instance via HTTP requests.\n\n jenkins_home: /var/lib/jenkins\n\nThe Jenkins home directory which, amongst others, is being used for storing artifacts, workspaces and plugins. This variable allows you to override the default `/var/lib/jenkins` location.\n\n jenkins_http_port: 8080\n\nThe HTTP port for Jenkins' web interface.\n\n jenkins_admin_username: admin\n jenkins_admin_password: admin\n\nDefault admin account credentials which will be created the first time Jenkins is installed.\n\n jenkins_admin_password_file: \"\"\n\nDefault admin password file which will be created the first time Jenkins is installed as /var/lib/jenkins/secrets/initialAdminPassword\n\n jenkins_jar_location: /opt/jenkins-cli.jar\n\nThe location at which the `jenkins-cli.jar` jarfile will be kept. This is used for communicating with Jenkins via the CLI.\n\n jenkins_plugins: []\n\nJenkins plugins to be installed automatically during provisioning. (_Note_: This feature is currently undergoing some changes due to the `jenkins-cli` authentication changes in Jenkins 2.0, and may not work as expected.)\n\n jenkins_version: \"1.644\"\n jenkins_pkg_url: \"http://www.example.com\"\n\n(Optional) Then Jenkins version can be pinned to any version available on `http://pkg.jenkins-ci.org/debian/` (Debian/Ubuntu) or `http://pkg.jenkins-ci.org/redhat/` (RHEL/CentOS). If the Jenkins version you need is not available in the default package URLs, you can override the URL with your own; set `jenkins_pkg_url` (_Note_: the role depends on the same naming convention that `http://pkg.jenkins-ci.org/` uses).\n\n jenkins_url_prefix: \"\"\n\nUsed for setting a URL prefix for your Jenkins installation. The option is added as `--prefix={{ jenkins_url_prefix }}` to the Jenkins initialization `java` invocation, so you can access the installation at a path like `http://www.example.com{{ jenkins_url_prefix }}`. Make sure you start the prefix with a `/` (e.g. `/jenkins`).\n\n jenkins_connection_delay: 5\n jenkins_connection_retries: 60\n\nAmount of time and number of times to wait when connecting to Jenkins after initial startup, to verify that Jenkins is running. Total time to wait = `delay` * `retries`, so by default this role will wait up to 300 seconds before timing out.\n\n # For RedHat/CentOS (role default):\n jenkins_repo_url: http://pkg.jenkins-ci.org/redhat/jenkins.repo\n jenkins_repo_key_url: http://pkg.jenkins-ci.org/redhat/jenkins-ci.org.key\n # For Debian (role default):\n jenkins_repo_url: deb http://pkg.jenkins-ci.org/debian binary/\n jenkins_repo_key_url: http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key\n\nThis role will install the latest version of Jenkins by default (using the official repositories as listed above). You can override these variables (use the correct set for your platform) to install the current LTS version instead:\n\n # For RedHat/CentOS LTS:\n jenkins_repo_url: http://pkg.jenkins-ci.org/redhat-stable/jenkins.repo\n jenkins_repo_key_url: http://pkg.jenkins-ci.org/redhat-stable/jenkins-ci.org.key\n # For Debian/Ubuntu LTS:\n jenkins_repo_url: deb http://pkg.jenkins-ci.org/debian-stable binary/\n jenkins_repo_key_url: http://pkg.jenkins-ci.org/debian-stable/jenkins-ci.org.key\n\n jenkins_java_options: \"-Djenkins.install.runSetupWizard=false\"\n\nExtra Java options for the Jenkins launch command configured in the init file can be set with the var `jenkins_java_options`. By default the option to disable the Jenkins 2.0 setup wizard is added.\n\n jenkins_init_changes:\n - option: \"JENKINS_ARGS\"\n value: \"--prefix={{ jenkins_url_prefix }}\"\n - option: \"JENKINS_JAVA_OPTIONS\"\n value: \"{{ jenkins_java_options }}\"\n\nChanges made to the Jenkins init script; the default set of changes set the configured URL prefix and add in configured Java options for Jenkins' startup. You can add other option/value pairs if you need to set other options for the Jenkins init file.\n\n## Dependencies\n\n - geerlingguy.java\n\n## Example Playbook\n\n - hosts: ci-server\n vars:\n jenkins_hostname: jenkins.example.com\n roles:\n - geerlingguy.jenkins\n\n## License\n\nMIT (Expat) / BSD\n\n## Author Information\n\nThis role was created in 2014 by [Jeff Geerling](https://www.jeffgeerling.com/), author of [Ansible for DevOps](https://www.ansiblefordevops.com/).\n" }, { "alpha_fraction": 0.5965517163276672, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 21.384614944458008, "blob_id": "9a3045647a1a66ae3c93608b2fb2df6e8d385ee0", "content_id": "e9e89d27a5d25163c2201e3d0e3ee2e376cb0f92", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 290, "license_type": "permissive", "max_line_length": 49, "num_lines": 13, "path": "/ansible/roles/cassandra-restore/templates/nodetool.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nsnapshot={{snapshot}}\nfor keyspace in sunbird\ndo\n echo $keyspace\n cd {{user_home}}/snapshot-$snapshot/$keyspace\n for table in *\n do\n echo $table\n table_name=`echo $table | cut -d \"-\" -f1`\n nodetool refresh -- $keyspace $table_name\n done \ndone" }, { "alpha_fraction": 0.6592082381248474, "alphanum_fraction": 0.7710843086242676, "avg_line_length": 35.3125, "blob_id": "0b0a1a970260104ceed5e8802c53f6d9857b6d2a", "content_id": "66ca1a1531abea8ed55b00f99c07c060d2927f84", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go Module", "length_bytes": 581, "license_type": "permissive", "max_line_length": 71, "num_lines": 16, "path": "/kubernetes/opa-plugins/go.mod", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "module github.com/project-sunbird/sunbird-devops/kubernetes/opa-plugins\n\ngo 1.16\n\nrequire (\n\tgithub.com/bytecodealliance/wasmtime-go v0.33.1 // indirect\n\tgithub.com/golang-jwt/jwt v3.2.2+incompatible\n\tgithub.com/open-policy-agent/opa v0.34.2\n\tgithub.com/open-policy-agent/opa-envoy-plugin v0.34.2-envoy\n\tgithub.com/prometheus/client_golang v1.12.0 // indirect\n\tgithub.com/spf13/cobra v1.3.0 // indirect\n\tgithub.com/tidwall/gjson v1.12.1\n\tgithub.com/tidwall/sjson v1.2.4\n\tgolang.org/x/net v0.0.0-20211111083644-e5c967477495 // indirect\n\tgoogle.golang.org/grpc v1.44.0 // indirect\n)\n" }, { "alpha_fraction": 0.7575757503509521, "alphanum_fraction": 0.7597402334213257, "avg_line_length": 45.20000076293945, "blob_id": "147250c64ad7d21e58cf4a095cd7de056bbe37f0", "content_id": "65e8cdf33dcb97c528e60ae565895a68edbc944c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 462, "license_type": "permissive", "max_line_length": 107, "num_lines": 10, "path": "/deploy/gitOPS/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# Using scripts:\n\n- All the scripts are using the github api's.\n- All the scripts will take github.csv file as input and read each line to get the values of all variables\n- First udpate github.csv file row wise and run the scripts\n- In github.csv there are 4 variables with comma seperated \n\n REPO_NAME,BRANCH_NAME,MERGE_ACCESS_USERS(;),CHECKS\n \n MERGE_ACCESS_USERS and CHECKS: These variables are required only by disableBranchProtection.sh script.\n" }, { "alpha_fraction": 0.6515527963638306, "alphanum_fraction": 0.6534161567687988, "avg_line_length": 29.09345817565918, "blob_id": "52bf0ec20b6a8fcf8c71bf535c87e599c70d0724", "content_id": "66512bac3a5a0a7efe77f7118f09910535992335", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3220, "license_type": "permissive", "max_line_length": 106, "num_lines": 107, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/authorization/policy.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Marcos Pereira <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nfrom ..exceptions import KeycloakAuthorizationConfigError\n\n\nclass Policy:\n \"\"\"\n A policy defines the conditions that must be satisfied to grant access to an object.\n Unlike permissions, you do not specify the object being protected but rather the conditions\n that must be satisfied for access to a given object (for example, resource, scope, or both).\n Policies are strongly related to the different access control mechanisms (ACMs) that you can use to\n protect your resources. With policies, you can implement strategies for attribute-based access control\n (ABAC), role-based access control (RBAC), context-based access control, or any combination of these.\n\n https://keycloak.gitbooks.io/documentation/authorization_services/topics/policy/overview.html\n\n \"\"\"\n\n def __init__(self, name, type, logic, decision_strategy):\n self._name = name\n self._type = type\n self._logic = logic\n self._decision_strategy = decision_strategy\n self._roles = []\n self._permissions = []\n\n def __repr__(self):\n return \"<Policy: %s (%s)>\" % (self.name, self.type)\n\n def __str__(self):\n return \"Policy: %s (%s)\" % (self.name, self.type)\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n\n @property\n def type(self):\n return self._type\n\n @type.setter\n def type(self, value):\n self._type = value\n\n @property\n def logic(self):\n return self._logic\n\n @logic.setter\n def logic(self, value):\n self._logic = value\n\n @property\n def decision_strategy(self):\n return self._decision_strategy\n\n @decision_strategy.setter\n def decision_strategy(self, value):\n self._decision_strategy = value\n\n @property\n def roles(self):\n return self._roles\n\n @property\n def permissions(self):\n return self._permissions\n\n def add_role(self, role):\n \"\"\"\n Add keycloak role in policy.\n\n :param role: keycloak role.\n :return:\n \"\"\"\n if self.type != 'role':\n raise KeycloakAuthorizationConfigError(\n \"Can't add role. Policy type is different of role\")\n self._roles.append(role)\n\n def add_permission(self, permission):\n \"\"\"\n Add keycloak permission in policy.\n\n :param permission: keycloak permission.\n :return:\n \"\"\"\n self._permissions.append(permission)\n" }, { "alpha_fraction": 0.84375, "alphanum_fraction": 0.84375, "avg_line_length": 15.5, "blob_id": "a0fedae0cb693dcce03845f158db39f89055403e", "content_id": "467e2c24a775a8e752d46cac571ea12391f3e51d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 32, "license_type": "permissive", "max_line_length": 24, "num_lines": 2, "path": "/ansible/roles/postgresql-data-update/templates/uci_odk_postgres.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "CREATE SCHEMA aggregate;\ncommit;" }, { "alpha_fraction": 0.6734693646430969, "alphanum_fraction": 0.7006802558898926, "avg_line_length": 28.200000762939453, "blob_id": "d2cf82dc4f6388d9f7da2be49d67a406f96195b5", "content_id": "785614bf1b12a01d82bc376d146a0c51b48f9e0b", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 147, "license_type": "permissive", "max_line_length": 85, "num_lines": 5, "path": "/ansible/roles/elasticsearch/test/integration/config-5x/serverspec/default_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'config_spec'\n\ndescribe 'Config Tests v 5.x' do\n include_examples 'config::init', \"5.2.2\", [\"ingest-attachment\",\"ingest-user-agent\"]\nend\n\n" }, { "alpha_fraction": 0.6669320464134216, "alphanum_fraction": 0.7176221013069153, "avg_line_length": 34.38028335571289, "blob_id": "12a286e33eb4bdeaac7f5874dc3f7c6c5199c9a3", "content_id": "d96e3b4228597bed0e9794084a77867150b8cea3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 7536, "license_type": "permissive", "max_line_length": 134, "num_lines": 213, "path": "/deploy/jenkins/jenkins-server-setup.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nbold=$(tput bold)\nnormal=$(tput sgr0)\n\necho -e \"\\n\\e[0;32m${bold}Clean up${normal}\"\nrm -rf /etc/apt/sources.list.d/azure-cli.list /etc/apt/sources.list.d/packages_microsoft_com_repos_azure_cli.list*\n\necho -e \"\\n\\e[0;32m${bold}Updating the apt repo${normal}\\n\"\napt-get update\n\necho -e \"\\n\\e[0;32m${bold}Installating JDK8${normal}\\n\"\napt-get install -y openjdk-8-jdk\n\necho -e \"\\n\\e[0;32m${bold}Installating Jenkins${normal}\"\nwget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | apt-key add -\napt-add-repository \"deb https://pkg.jenkins.io/debian-stable binary/\"\napt-get update\napt-get install -y jenkins=2.319.3\n\necho -e \"\\n\\e[0;32m${bold}Installating PIP${normal}\"\napt-get install -y python-pip\napt-get install -y python3-pip\n\necho -e \"\\n\\e[0;32m${bold}Installating Maven${normal}\"\napt-get install -y maven\n\necho -e \"\\n\\e[0;32m${bold}Installating Git ${normal}\"\napt-get install -y git\n\necho -e \"\\n\\e[0;32m${bold}Installating zip unzip${normal}\"\napt-get install -y unzip zip\n\necho -e \"\\n\\e[0;32m${bold}Installating JQ${normal}\"\napt-get install -y jq\n\necho -e \"\\n\\e[0;32m${bold}Installating Simplejson${normal}\"\napt-get install -y python-simplejson\n\necho -e \"\\n\\e[0;32m${bold}Installating tree${normal}\"\napt install tree -y\n\necho -e \"\\n\\e[0;32m${bold}Installating Docker${normal}\"\napt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\nadd-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\napt-get update\napt-get install -y docker-ce docker-ce-cli containerd.io\n\necho -e \"\\n\\e[0;32m${bold}Installating node and npm modules\"\nwget https://nodejs.org/download/release/v6.17.1/node-v6.17.1-linux-x64.tar.gz\ntar -xf node-v6.17.1-linux-x64.tar.gz\nrm -rf /usr/local/lib/node-v6.17.1-linux-x64\nrm -rf /usr/bin/node\nrm -rf /usr/bin/npm\nrm -rf /usr/bin/grunt\nrm -rf /usr/bin/bower\nrm -rf /usr/bin/gulp\nmv node-v6.17.1-linux-x64 /usr/local/lib/\nln -s /usr/local/lib/node-v6.17.1-linux-x64/bin/node /usr/bin/node\nln -s /usr/local/lib/node-v6.17.1-linux-x64/bin/npm /usr/bin/npm\nnpm install -g [email protected]\nln -s /usr/local/lib/node-v6.17.1-linux-x64/bin/grunt /usr/bin/grunt\nnpm install -g [email protected]\nln -s /usr/local/lib/node-v6.17.1-linux-x64/bin/bower /usr/bin/bower\nnpm install -g @alexlafroscia/yaml-merge\nln -s /var/lib/jenkins/.nvm/versions/node/v12.16.1/bin/yaml-merge /usr/bin/yaml-merge\nnpm install -g [email protected]\nln -s /usr/local/lib/node-v6.17.1-linux-x64/bin/gulp /usr/bin/gulp\nrm -rf node-v6.17.1-linux-x64*\n\necho -e \"\\n\\e[0;32m${bold}Installating Ansible${normal}\"\npip uninstall -y ansible\npip3 install ansible==2.8.19\n\necho -e \"\\n\\e[0;32m${bold}Installating azure cli${normal}\"\napt-get install ca-certificates curl apt-transport-https lsb-release gnupg\ncurl -sL https://packages.microsoft.com/keys/microsoft.asc |\n gpg --dearmor |\n sudo tee /etc/apt/trusted.gpg.d/microsoft.asc.gpg > /dev/null\nAZ_REPO=$(lsb_release -cs)\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main\" |\n sudo tee /etc/apt/sources.list.d/azure-cli.list\nsudo apt-get update\nsudo apt-get install azure-cli\n\n# Install azcopy\necho -e \"\\n\\e[0;32m${bold}Installating AzCopy${normal}\"\napt update\nwget https://aka.ms/downloadazcopy-v10-linux\ntar -xf downloadazcopy-v10-linux\ncp ./azcopy_linux_amd64_*/azcopy /usr/bin/\nchmod +x /usr/bin/azcopy\nrm -rf downloadazcopy-v10-linux* azcopy_linux_amd*\n###\n\necho -e \"\\n\\e[0;32m${bold}Installating pip docker${normal}\"\npip install docker\npip3 install docker\n\necho -e \"\\n\\e[0;32m${bold}Installating colordiff${normal}\"\napt-get install -y colordiff\n\necho -e \"\\n\\e[0;32m${bold}Adding jenkins user to docker group${normal}\"\nusermod -aG docker jenkins\n\necho -e \"\\n\\e[0;32m${bold}Creating bashrc for jenkins user ${normal}\"\ncp /etc/skel/.bashrc /var/lib/jenkins\nchown jenkins:jenkins /var/lib/jenkins/.bashrc\n\necho -e \"\\n\\e[0;32m${bold}Setting timezone to IST ${normal}\"\ntimedatectl set-timezone Asia/Kolkata\n\necho -e \"\\n\\e[0;32m${bold}Installing nvm${normal}\"\nsu jenkins bash -c \"curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash\"\n\necho -e \"\\n\\e[0;32m${bold}Installing jmespath${normal}\"\nsudo apt install -y python3-jmespath\n\n#### Kubernetes Tools ####\n\n# Install Helm version 3.0.2\necho -e \"\\n\\e[0;32m${bold}Installating Helm${normal}\"\nwget https://get.helm.sh/helm-v3.0.2-linux-386.tar.gz\ntar -xzvf helm-v3.0.2-linux-386.tar.gz\nrm -rf /usr/local/bin/helm\ncp linux-386/helm /usr/local/bin/helm\nrm -rf helm-v* linux-amd*\n\n# Install kubectl v1.22.0\necho -e \"\\n\\e[0;32m${bold}Installating kubectl${normal}\"\ncurl -LO https://dl.k8s.io/release/v1.22.0/bin/linux/amd64/kubectl\nchmod +x kubectl\nmv kubectl /usr/local/bin\n\n#Install yarn\necho -e \"\\n\\e[0;32m${bold}Installating yarn${normal}\"\ncurl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -\necho \"deb https://dl.yarnpkg.com/debian/ stable main\" | sudo tee /etc/apt/sources.list.d/yarn.list\napt update && apt install -y yarn\n\n#Install openjdk\necho -e \"\\n\\e[0;32m${bold}Installating openjdk 11${normal}\"\nwget https://download.java.net/openjdk/jdk11/ri/openjdk-11+28_linux-x64_bin.tar.gz\ntar -xf openjdk-11+28_linux-x64_bin.tar.gz\nmv jdk-11 java-11-openjdk-amd64\ncp -r java-11-openjdk-amd64 /usr/lib/jvm/\nrm -rf java-11-openjdk-amd64 openjdk-11+28_linux-x64_bin.tar.gz\n\n#Install openjdk-11.0.2 # needed for DP jobs\necho -e \"\\n\\e[0;32m${bold}Installating openjdk 11.0.2${normal}\"\nwget https://download.java.net/java/GA/jdk11/9/GPL/openjdk-11.0.2_linux-x64_bin.tar.gz\ntar -xf openjdk-11.0.2_linux-x64_bin.tar.gz\nmv jdk-11.0.2 /usr/lib/jvm/\nrm openjdk-11.0.2_linux-x64_bin.tar.gz\n\n#Install maven 3.6.3\necho -e \"\\n\\e[0;32m${bold}Installating maven 3.6.3${normal}\"\nwget https://downloads.apache.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz\ntar -xf apache-maven-3.6.3-bin.tar.gz\nmv apache-maven-3.6.3 /opt/\nmv /opt/apache-maven-3.6.3/bin/mvn /opt/apache-maven-3.6.3/bin/mvn3.6\nrm -rf apache-maven-3.6.3-bin.tar.gz\n\n#Install python-psycopg2\necho -e \"\\n\\e[0;32m${bold}Installating python-psycopg2${normal}\"\napt install -y python-psycopg2\n\n#Install libpng-dev - Ubuntu 18 and above fix for plugin builds\necho -e \"\\n\\e[0;32m${bold}Installating libpng-dev${normal}\"\napt install -y libpng-dev\n\necho -e \"\\n\\e[0;32m${bold}Installating OPA${normal}\"\ncurl -k -L -o opa https://openpolicyagent.org/downloads/v0.34.2/opa_linux_amd64_static\nchmod 755 ./opa\nmv opa /usr/local/bin/\n\necho -e \"\\n\\e[0;32m${bold}Installing mongo tools${normal}\"\napt install -y mongo-tools\n\necho -e \"\\n\\e[0;32m${bold}Installing required python2 pacakges if distro is ubuntu 18 and above${normal}\"\n# For kong api and consumer onboarding\nosrelease=$(cat /etc/lsb-release | grep DISTRIB_RELEASE | awk -F '=' '{print $2}')\nif [[ $osrelease > 18 ]]\nthen\n wget https://bootstrap.pypa.io/pip/2.7/get-pip.py\n which pip\n rc=$?\n if [[ $rc == 0 ]]\n then\n cp /usr/local/bin/pip /usr/local/bin/pip3\n fi\n which python2.7\n rc=$?\n if [[ $rc == 0 ]]\n then\n python2.7 get-pip.py\n pip install retry\n pip install PyJWT\n apt reinstall -y python3-pip\n else\n apt reinstall -y python2\n python2.7 get-pip.py\n python2.7 get-pip.py\n pip install PyJWT\n apt reinstall -y python3-pip\n fi\nfi\nrm -rf get-pip.py\n\necho -e \"\\n\\e[0;32m${bold}Clean up${normal}\"\nsudo apt -y autoremove\n\necho -e \"\\n\\e[0;32m${bold}Installation complete. Please go to your jenkins URL and continue setup if this is the first run..${normal}\"\n" }, { "alpha_fraction": 0.6159247159957886, "alphanum_fraction": 0.6184642910957336, "avg_line_length": 33.32820510864258, "blob_id": "44301fad37072d008e5427f1d5a8b5e2b2e80017", "content_id": "f1dcde44e32b46848ed5dcc0a1de8a4220e24854", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13388, "license_type": "permissive", "max_line_length": 105, "num_lines": 390, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/keycloak_openid.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Marcos Pereira <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nfrom .authorization import Authorization\nfrom .exceptions import raise_error_from_response, KeycloakGetError, \\\n KeycloakRPTNotFound, KeycloakAuthorizationConfigError, KeycloakInvalidTokenError\nfrom .urls_patterns import (\n URL_TOKEN,\n URL_USERINFO,\n URL_WELL_KNOWN,\n URL_LOGOUT,\n URL_CERTS,\n URL_ENTITLEMENT,\n URL_INTROSPECT\n)\nfrom .connection import ConnectionManager\nfrom jose import jwt\nimport json\n\n\nclass KeycloakOpenID:\n\n def __init__(self, server_url, realm_name, client_id, client_secret_key=None, verify=True):\n \"\"\"\n\n :param server_url: Keycloak server url\n :param client_id: client id\n :param realm_name: realm name\n :param client_secret_key: client secret key\n :param verify: True if want check connection SSL\n \"\"\"\n self._client_id = client_id\n self._client_secret_key = client_secret_key\n self._realm_name = realm_name\n self._connection = ConnectionManager(base_url=server_url,\n headers={},\n timeout=60,\n verify=verify)\n\n self._authorization = Authorization()\n\n @property\n def client_id(self):\n return self._client_id\n\n @client_id.setter\n def client_id(self, value):\n self._client_id = value\n\n @property\n def client_secret_key(self):\n return self._client_secret_key\n\n @client_secret_key.setter\n def client_secret_key(self, value):\n self._client_secret_key = value\n\n @property\n def realm_name(self):\n return self._realm_name\n\n @realm_name.setter\n def realm_name(self, value):\n self._realm_name = value\n\n @property\n def connection(self):\n return self._connection\n\n @connection.setter\n def connection(self, value):\n self._connection = value\n\n @property\n def authorization(self):\n return self._authorization\n\n @authorization.setter\n def authorization(self, value):\n self._authorization = value\n\n def _add_secret_key(self, payload):\n \"\"\"\n Add secret key if exist.\n\n :param payload:\n :return:\n \"\"\"\n if self.client_secret_key:\n payload.update({\"client_secret\": self.client_secret_key})\n\n return payload\n\n def _build_name_role(self, role):\n \"\"\"\n\n :param role:\n :return:\n \"\"\"\n return self.client_id + \"/\" + role\n\n def _token_info(self, token, method_token_info, **kwargs):\n \"\"\"\n\n :param token:\n :param method_token_info:\n :param kwargs:\n :return:\n \"\"\"\n if method_token_info == 'introspect':\n token_info = self.introspect(token)\n else:\n token_info = self.decode_token(token, **kwargs)\n\n return token_info\n\n def well_know(self):\n \"\"\" The most important endpoint to understand is the well-known configuration\n endpoint. It lists endpoints and other configuration options relevant to\n the OpenID Connect implementation in Keycloak.\n\n :return It lists endpoints and other configuration options relevant.\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))\n\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def auth_url(self, redirect_uri):\n \"\"\"\n\n http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint\n\n :return:\n \"\"\"\n return NotImplemented\n\n def token(self, username, password, grant_type=[\"password\"]):\n \"\"\"\n The token endpoint is used to obtain tokens. Tokens can either be obtained by\n exchanging an authorization code or by supplying credentials directly depending on\n what flow is used. The token endpoint is also used to obtain new access tokens\n when they expire.\n\n http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint\n\n :param username:\n :param password:\n :param grant_type:\n :return:\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n payload = {\"username\": username, \"password\": password,\n \"client_id\": self.client_id, \"grant_type\": grant_type}\n\n payload = self._add_secret_key(payload)\n data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path),\n data=payload)\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def refresh_token(self, refresh_token, grant_type=[\"refresh_token\"]):\n \"\"\"\n The token endpoint is used to obtain tokens. Tokens can either be obtained by\n exchanging an authorization code or by supplying credentials directly depending on\n what flow is used. The token endpoint is also used to obtain new access tokens\n when they expire.\n\n http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint\n\n :param refresh_token:\n :param grant_type:\n :return:\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n payload = {\"client_id\": self.client_id, \"grant_type\": grant_type, \"refresh_token\": refresh_token}\n payload = self._add_secret_key(payload)\n data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path),\n data=payload)\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def userinfo(self, token):\n \"\"\"\n The userinfo endpoint returns standard claims about the authenticated user,\n and is protected by a bearer token.\n\n http://openid.net/specs/openid-connect-core-1_0.html#UserInfo\n\n :param token:\n :return:\n \"\"\"\n\n self.connection.add_param_headers(\"Authorization\", \"Bearer \" + token)\n params_path = {\"realm-name\": self.realm_name}\n\n data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))\n\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def logout(self, refresh_token):\n \"\"\"\n The logout endpoint logs out the authenticated user.\n :param refresh_token:\n :return:\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n payload = {\"client_id\": self.client_id, \"refresh_token\": refresh_token}\n\n payload = self._add_secret_key(payload)\n data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path),\n data=payload)\n\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def certs(self):\n \"\"\"\n The certificate endpoint returns the public keys enabled by the realm, encoded as a\n JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled\n for verifying tokens.\n\n https://tools.ietf.org/html/rfc7517\n\n :return:\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def entitlement(self, token, resource_server_id):\n \"\"\"\n Client applications can use a specific endpoint to obtain a special security token\n called a requesting party token (RPT). This token consists of all the entitlements\n (or permissions) for a user as a result of the evaluation of the permissions and authorization\n policies associated with the resources being requested. With an RPT, client applications can\n gain access to protected resources at the resource server.\n\n :return:\n \"\"\"\n self.connection.add_param_headers(\"Authorization\", \"Bearer \" + token)\n params_path = {\"realm-name\": self.realm_name, \"resource-server-id\": resource_server_id}\n data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))\n\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def introspect(self, token, rpt=None, token_type_hint=None):\n \"\"\"\n The introspection endpoint is used to retrieve the active state of a token. It is can only be\n invoked by confidential clients.\n\n https://tools.ietf.org/html/rfc7662\n\n :param token:\n :param rpt:\n :param token_type_hint:\n\n :return:\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n\n payload = {\"client_id\": self.client_id, \"token\": token}\n\n if token_type_hint == 'requesting_party_token':\n if rpt:\n payload.update({\"token\": rpt, \"token_type_hint\": token_type_hint})\n self.connection.add_param_headers(\"Authorization\", \"Bearer \" + token)\n else:\n raise KeycloakRPTNotFound(\"Can't found RPT.\")\n\n payload = self._add_secret_key(payload)\n\n data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path),\n data=payload)\n\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def decode_token(self, token, key, algorithms=['RS256'], **kwargs):\n \"\"\"\n A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data\n structure that represents a cryptographic key. This specification\n also defines a JWK Set JSON data structure that represents a set of\n JWKs. Cryptographic algorithms and identifiers for use with this\n specification are described in the separate JSON Web Algorithms (JWA)\n specification and IANA registries established by that specification.\n\n https://tools.ietf.org/html/rfc7517\n\n :param token:\n :param key:\n :param algorithms:\n :return:\n \"\"\"\n\n return jwt.decode(token, key, algorithms=algorithms,\n audience=self.client_id, **kwargs)\n\n def load_authorization_config(self, path):\n \"\"\"\n Load Keycloak settings (authorization)\n\n :param path: settings file (json)\n :return:\n \"\"\"\n authorization_file = open(path, 'r')\n authorization_json = json.loads(authorization_file.read())\n self.authorization.load_config(authorization_json)\n authorization_file.close()\n\n def get_policies(self, token, method_token_info='introspect', **kwargs):\n \"\"\"\n Get policies by user token\n\n :param token: user token\n :return: policies list\n \"\"\"\n\n if not self.authorization.policies:\n raise KeycloakAuthorizationConfigError(\n \"Keycloak settings not found. Load Authorization Keycloak settings.\"\n )\n\n token_info = self._token_info(token, method_token_info, **kwargs)\n\n if method_token_info == 'introspect' and not token_info['active']:\n raise KeycloakInvalidTokenError(\n \"Token expired or invalid.\"\n )\n\n user_resources = token_info['resource_access'].get(self.client_id)\n\n if not user_resources:\n return None\n\n policies = []\n\n for policy_name, policy in self.authorization.policies.items():\n for role in user_resources['roles']:\n if self._build_name_role(role) in policy.roles:\n policies.append(policy)\n\n return list(set(policies))\n\n def get_permissions(self, token, method_token_info='introspect', **kwargs):\n \"\"\"\n Get permission by user token\n\n :param token: user token\n :param method_token_info: Decode token method\n :param kwargs: parameters for decode\n :return: permissions list\n \"\"\"\n\n if not self.authorization.policies:\n raise KeycloakAuthorizationConfigError(\n \"Keycloak settings not found. Load Authorization Keycloak settings.\"\n )\n\n token_info = self._token_info(token, method_token_info, **kwargs)\n\n if method_token_info == 'introspect' and not token_info['active']:\n raise KeycloakInvalidTokenError(\n \"Token expired or invalid.\"\n )\n\n user_resources = token_info['resource_access'].get(self.client_id)\n\n if not user_resources:\n return None\n\n permissions = []\n\n for policy_name, policy in self.authorization.policies.items():\n for role in user_resources['roles']:\n if self._build_name_role(role) in policy.roles:\n permissions += policy.permissions\n\n return list(set(permissions))\n" }, { "alpha_fraction": 0.7342857122421265, "alphanum_fraction": 0.7628571391105652, "avg_line_length": 30.81818199157715, "blob_id": "0377bd4d792f7bce59c92b0e98ca8e261e80205c", "content_id": "ca21bff48e51a879d5c89c5b0fdd397eec6dde0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 350, "license_type": "permissive", "max_line_length": 86, "num_lines": 11, "path": "/images/kafka-topic-exporter/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM golang:1.13.10 AS builder\nWORKDIR /work\nCOPY main.go /work\nRUN go get github.com/segmentio/kafka-go ; go get github.com/segmentio/kafka-go/snappy\nRUN CGO_ENABLED=0 go build -o kafka-topic-exporter main.go\n\nFROM scratch\nLABEL maintainer=\"Rajesh Rajendran<[email protected]>\"\nCOPY --from=builder /work/kafka-topic-exporter /\nEXPOSE 8000\nCMD [\"/kafka-topic-exporter\"]\n" }, { "alpha_fraction": 0.6477272510528564, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 24.285715103149414, "blob_id": "8689a31a663f4273f59e14e921313b28f57c9e7e", "content_id": "0d43006cb8e710f552e0f0b262b64e878e431757", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 176, "license_type": "permissive", "max_line_length": 56, "num_lines": 7, "path": "/ansible/roles/provision-kafka/files/truncate_logs.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# Truncate zookeeper logs\nZOOKEEPER_VERSION_2=/var/log/zookeeper/version-2/log.*\n\nfor f in $ZOOKEEPER_VERSION_2\ndo\n\ttail -n 100 $f > $f.tmp && cat $f.tmp > $f && rm $f.tmp\ndone" }, { "alpha_fraction": 0.6280992031097412, "alphanum_fraction": 0.6611570119857788, "avg_line_length": 18.83333396911621, "blob_id": "4353a593ef47d7eb56e100488e467820b739c688", "content_id": "7020270cddc3f0784ee2361dcb02208983c387d4", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 121, "license_type": "permissive", "max_line_length": 59, "num_lines": 6, "path": "/ansible/roles/elasticsearch/test/integration/multi-5x/serverspec/default_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'multi_spec'\n\n\ndescribe 'Multi Tests v 5.x' do\n include_examples 'multi::init', \"5.2.2\", [\"ingest-geoip\"]\nend\n\n\n" }, { "alpha_fraction": 0.6836292147636414, "alphanum_fraction": 0.6895463466644287, "avg_line_length": 26.25806427001953, "blob_id": "aec59804adf7e6efe0fd95a483cc17e2c9aea568", "content_id": "27d8b14c156086b3de650a4248c4bf09c5cc27c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2535, "license_type": "permissive", "max_line_length": 77, "num_lines": 93, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/exceptions.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Marcos Pereira <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nimport requests\n\n\nclass KeycloakError(Exception):\n def __init__(self, error_message=\"\", response_code=None,\n response_body=None):\n\n Exception.__init__(self, error_message)\n\n self.response_code = response_code\n self.response_body = response_body\n self.error_message = error_message\n\n def __str__(self):\n if self.response_code is not None:\n return \"{0}: {1}\".format(self.response_code, self.error_message)\n else:\n return \"{0}\".format(self.error_message)\n\n\nclass KeycloakAuthenticationError(KeycloakError):\n pass\n\n\nclass KeycloakConnectionError(KeycloakError):\n pass\n\n\nclass KeycloakOperationError(KeycloakError):\n pass\n\n\nclass KeycloakGetError(KeycloakOperationError):\n pass\n\n\nclass KeycloakSecretNotFound(KeycloakOperationError):\n pass\n\n\nclass KeycloakRPTNotFound(KeycloakOperationError):\n pass\n\n\nclass KeycloakAuthorizationConfigError(KeycloakOperationError):\n pass\n\n\nclass KeycloakInvalidTokenError(KeycloakOperationError):\n pass\n\n\ndef raise_error_from_response(response, error, expected_code=200):\n\n if expected_code == response.status_code:\n if expected_code == requests.codes.no_content:\n return {}\n try:\n return response.json()\n except ValueError:\n return response.content\n\n try:\n message = response.json()['message']\n except (KeyError, ValueError):\n message = response.content\n\n if isinstance(error, dict):\n error = error.get(response.status_code, KeycloakOperationError)\n else:\n if response.status_code == 401:\n error = KeycloakAuthenticationError\n\n raise error(error_message=message,\n response_code=response.status_code,\n response_body=response.content)\n" }, { "alpha_fraction": 0.47028422355651855, "alphanum_fraction": 0.5038759708404541, "avg_line_length": 42, "blob_id": "4dc32638d9f8e224476b8051385f770d230ce304", "content_id": "509400d7d6d763f0b20cec9c9054b3d9213591d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 387, "license_type": "permissive", "max_line_length": 88, "num_lines": 9, "path": "/deploy/gitOPS/getRepos.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nread -p \"Enter Github Username: \" user\nread -sp \"Enter Github Password: \" pass\necho \" \"\nread -p \"Enter Github Account Name: \" acc_name\necho \"---------------------------------------------\"\necho -e '\\033[0;32m'$acc_name'\\033[0m'\necho \"---------------------------------------------\"\ncurl -s -N https://api.github.com/users/$acc_name/repos\\?per_page=100 | jq '.[].name' -r\n" }, { "alpha_fraction": 0.7846027612686157, "alphanum_fraction": 0.7846027612686157, "avg_line_length": 72.26000213623047, "blob_id": "7ce5451093ecd0d8b491acd01ac132abdca1919d", "content_id": "7bc00285731f1a42436b8c6ac298ef654eab0e35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3663, "license_type": "permissive", "max_line_length": 517, "num_lines": 50, "path": "/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# sunbird-devops\n\nThis repository contains the information and references needed to run [Sunbird](http://open-sunbird.org/) in a Production environment. The deployment design and software choices taken have been motivated with a need to run Sunbird in a highly available, reliable and scaleable setup. Higher levels of automation have been favored. The stack is meant to be extensible and parts of it are swappable to suit your deployment environments. Pull Requests are invited to add capability and variety to the deployment choices.\n\n## Table of content\n\n- [Prerequisites](#prerequisites)\n- [Installation](#installation)\n - [Developer](#developer)\n - [Production](#production)\n- [Deployment architecture](#deployment-architecture)\n- [License](#license)\n\n## Prerequisites\nThis section should expand as open source contributions to support multiple run times increase over time. Presently, the software and reference steps consider the following tech stack:\n\nRequired:\n\n- Linux, preferably Ubuntu\n- [Docker Swarm Mode](https://docs.docker.com/engine/swarm/)\n- [Ansible](https://www.ansible.com/)\n\nOptional:\n\n- A CI server, e.x. [Jenkins](https://jenkins.io/), to build extensions and take future upgrades\n- a source control mechanism, e.x. [Git](https://github.com/)\n\n## Installation\n### Developer\nHead over to specific Frontend or Backend service repos in [Project Sunbird](https://github.com/project-sunbird/) to understand how to run the parts of the stack locally, perhaps on your laptop.\n\n### Production\n\nPlease refer to https://github.com/project-sunbird/sunbird-devops/blob/master/Installation.md\n\n## Deployment Architecture\n### Infrastructure\nSunbird can be run on VMs on various Cloud providers or bare metal. Cloud Infrastructure automation is work in progress.\n### Stable Builds Registry\nSunbird builds are available at a [Image Registry](https://hub.docker.com/u/sunbird/dashboard/). These builds are in the form of a [Dockerfile](https://docs.docker.com/engine/reference/builder/). Stable releases are tagged as ```gold```. Deployment scripts pull the ```gold``` images for production deployment. The ```gold``` images are also versioned to allow for release management and upgrade paths.\n### Software Runtime\nMost runtimes in Sunbird are containerized as [Docker containers](https://www.docker.com/what-container) for portability, process isolation and standardization. For container orchestration, this repo contains scripts to run Sunbird on [Docker Swarm](https://docs.docker.com/engine/swarm/). Cloud providers provide container services. In this repo, we are using [ACS-Engine](https://github.com/Azure/acs-engine).\n### Logging, Monitoring and Operational dashboards\nSunbird comes with log aggregation and metrics reporting out of the box. For log aggregation, Sunbird is using a combination of [cAdvisor](https://github.com/google/cadvisor), [ELK stack](https://www.elastic.co/webinars/introduction-elk-stack), [Prometheus](https://prometheus.io/) and their plugin ecosystem.\nOps dashboards are built using [Grafana](https://grafana.com/) with some [reference](https://github.com/project-sunbird/sunbird-devops/tree/master/cloud/monitoring/grafana) dashboards.\n### Custom builds\nSunbird is extendible. Sunbird can be taken as a base image with custom implementation of public interfaces and rebuilt for deployment. Scripts are available for ramping up of complex deployments with support to run local build promotions and deployments.\n\n## License\nThe code in this repository is licensed under MIT unless otherwise noted. Please see the [LICENSE](https://github.com/project-sunbird/sunbird-devops/blob/master/LICENSE) file for details.\n" }, { "alpha_fraction": 0.5984848737716675, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 38.70000076293945, "blob_id": "65527af6bd3f31d6d0266ed3252431d5084bb989", "content_id": "375c95a3f7c9c94addbe433aa96a4e40aeb37692", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 396, "license_type": "permissive", "max_line_length": 144, "num_lines": 10, "path": "/images/reporter-jenkins-swarm-agent/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM vfarcic/jenkins-swarm-agent:17.10.07-4\nENV CQLSH_VERSION=5.0.3\n\nRUN apk --update add tar curl && \\\n pip install cassandra-driver\n\nRUN mkdir -p /usr/var/cqlsh && \\\n curl -SL https://pypi.python.org/packages/12/a7/13aff4ad358ff4abef6823d872154d0955ff6796739fcaaa2c80a6940aa6/cqlsh-${CQLSH_VERSION}.tar.gz \\\n | tar xzvC /usr/var && \\\n /usr/var/cqlsh-${CQLSH_VERSION}/cqlsh --version" }, { "alpha_fraction": 0.7355614304542542, "alphanum_fraction": 0.7369295358657837, "avg_line_length": 63.358489990234375, "blob_id": "2f24250f020402ceae3f80b12906d7c7c621cd35", "content_id": "e90b960dd386ef7ada9a1eddf705cfd824527b85", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 10233, "license_type": "permissive", "max_line_length": 509, "num_lines": 159, "path": "/ansible/roles/postgres-migration/files/sunbird_programs/V3.8.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "CREATE TYPE status AS ENUM ('Draft', 'Live', 'Unlisted', 'Retired');\nCREATE TYPE programtype AS ENUM ('public', 'private');\nCREATE TYPE nominationstatus AS ENUM ('Pending', 'Approved', 'Rejected', 'Initiated');\nCREATE SEQUENCE nomination_id_seq;\nCREATE SEQUENCE IF NOT EXISTS contentid_seq;\nCREATE TABLE program\n(\n program_id character varying COLLATE pg_catalog.\"default\" NOT NULL,\n name character varying COLLATE pg_catalog.\"default\",\n description text COLLATE pg_catalog.\"default\",\n content_types text[] COLLATE pg_catalog.\"default\",\n collection_ids text[] COLLATE pg_catalog.\"default\",\n type programtype,\n startdate timestamp without time zone DEFAULT timezone('utc'::text, (CURRENT_DATE)::timestamp with time zone),\n enddate timestamp without time zone,\n nomination_enddate timestamp without time zone,\n shortlisting_enddate timestamp without time zone,\n content_submission_enddate timestamp without time zone,\n image character varying COLLATE pg_catalog.\"default\",\n status status,\n slug character varying COLLATE pg_catalog.\"default\",\n config jsonb,\n channel character varying COLLATE pg_catalog.\"default\" DEFAULT 'DIKSHA'::character varying,\n template_id character varying COLLATE pg_catalog.\"default\" DEFAULT 'template1'::character varying,\n rootorg_id character varying COLLATE pg_catalog.\"default\",\n sourcing_org_name character varying COLLATE pg_catalog.\"default\",\n createdby character varying COLLATE pg_catalog.\"default\",\n createdon timestamp with time zone DEFAULT timezone('utc'::text, now()),\n updatedby character varying COLLATE pg_catalog.\"default\",\n updatedon timestamp with time zone DEFAULT timezone('utc'::text, now()),\n guidelines_url text COLLATE pg_catalog.\"default\",\n rolemapping json,\n targetprimarycategories jsonb,\n CONSTRAINT pk_program_id PRIMARY KEY (program_id)\n);\n\nCREATE TABLE nomination\n(\n id integer NOT NULL DEFAULT nextval('nomination_id_seq'::regclass),\n program_id character varying COLLATE pg_catalog.\"default\" NOT NULL,\n user_id character varying COLLATE pg_catalog.\"default\" NOT NULL,\n organisation_id character varying COLLATE pg_catalog.\"default\",\n status nominationstatus,\n content_types text[] COLLATE pg_catalog.\"default\",\n collection_ids text[] COLLATE pg_catalog.\"default\",\n feedback text COLLATE pg_catalog.\"default\",\n rolemapping json,\n createdby character varying COLLATE pg_catalog.\"default\",\n createdon timestamp with time zone DEFAULT timezone('utc'::text, now()),\n updatedby character varying COLLATE pg_catalog.\"default\",\n updatedon timestamp with time zone,\n targetprimarycategories jsonb,\n CONSTRAINT pk_id PRIMARY KEY (id)\n);\n\nCREATE TYPE contenttypesenum AS ENUM ('TeachingMethod', 'PedagogyFlow', 'FocusSpot', 'LearningOutcomeDefinition', 'PracticeQuestionSet', 'CuriosityQuestionSet', 'MarkingSchemeRubric', 'ExplanationResource', 'ExperientialResource', 'ConceptMap', 'SelfAssess', 'ExplanationVideo', 'ClassroomTeachingVideo', 'ExplanationReadingMaterial', 'LearningActivity', 'PreviousBoardExamPapers', 'LessonPlanResource');\n\nCREATE TABLE contenttypes (\n id int4 NOT NULL DEFAULT nextval('contentid_seq'::regclass),\n name varchar NOT NULL,\n value contenttypesenum NOT NULL,\n createdon timestamp with time zone DEFAULT timezone('utc'::text, now()),\n updatedon timestamp with time zone DEFAULT timezone('utc'::text, now()),\n PRIMARY KEY (\"id\")\n);\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Teaching Method', 'TeachingMethod');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Pedagogy Flow', 'PedagogyFlow');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Focus Spot', 'FocusSpot');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Learning Outcome Definition', 'LearningOutcomeDefinition');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Practice Question Set', 'PracticeQuestionSet');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Curiosity Question Set', 'CuriosityQuestionSet');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Marking Scheme Rubric', 'MarkingSchemeRubric');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Explanation Resource', 'ExplanationResource');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Experiential Resource', 'ExperientialResource');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Concept Map', 'ConceptMap');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Self Assess', 'SelfAssess');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Explanation Video', 'ExplanationVideo');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Classroom Teaching Video', 'ClassroomTeachingVideo');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Explanation Reading Material', 'ExplanationReadingMaterial');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Activity for Learning', 'LearningActivity');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Previous Board Exam Papers', 'PreviousBoardExamPapers');\nINSERT INTO \"public\".\"contenttypes\" (\"name\", \"value\") VALUES ('Lesson Plan', 'LessonPlanResource');\n\n\nCREATE SEQUENCE IF NOT EXISTS configurationid_seq;\nCREATE TYPE configurationstatus AS ENUM ('active', 'inactive');\nCREATE TABLE configuration (\n\tid int4 NOT NULL DEFAULT nextval('configurationid_seq'::regclass),\n\tkey varchar NOT NULL,\n\tvalue VARCHAR NOT NULL,\n status configurationstatus,\n createdby character varying COLLATE pg_catalog.\"default\",\n createdon timestamp with time zone DEFAULT timezone('utc'::text, now()),\n updatedby character varying COLLATE pg_catalog.\"default\",\n updatedon timestamp with time zone DEFAULT timezone('utc'::text, now()),\n\tPRIMARY KEY (\"id\")\n);\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('smsNominationAccept', 'VidyaDaan: Your nomination for $projectName is accepted. Please login to $url to start contributing content.', 'active');\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('smsNominationReject', 'VidyaDaan: Your nomination for $projectName has not been accepted. Thank you for your interest. Please login to $url for details.', 'active');\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('smsContentRequestedChanges', 'VidyaDaan: Your Content $contentName has not been accepted by your organization upon review. Please login to $url for details.', 'active');\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('smsContentReject', 'VidyaDaan: Your Content $contentName has not been approved by the project owner. Please login to $url for details.', 'active');\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('smsContentAccept', 'VidyaDaan: Your Content $contentName for the project $projectName has been approved by the project owner.', 'active');\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('contentVideoSize', 15360, 'active');\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('projectFeedDays', 3, 'active');\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('smsContentAcceptWithChanges', 'VidyaDaan: Your Content $contentName for the project $projectName has been approved by the project owner with few changes.', 'active');\nINSERT INTO \"public\".\"configuration\" (\"key\", \"value\", \"status\") VALUES ('overrideMetaData', '[{\"code\":\"name\",\"dataType\":\"text\",\"editable\":true},{\"code\":\"learningOutcome\",\"dataType\":\"list\",\"editable\":true},{\"code\":\"attributions\",\"dataType\":\"list\",\"editable\":false},{\"code\":\"copyright\",\"dataType\":\"text\",\"editable\":false},{\"code\":\"creator\",\"dataType\":\"text\",\"editable\":false},{\"code\":\"license\",\"dataType\":\"list\",\"editable\":false},{\"code\":\"contentPolicyCheck\",\"dataType\":\"boolean\",\"editable\":false}]', 'active');\n\nCREATE SEQUENCE user_program_preference_id_seq;\nCREATE TABLE public.user_program_preference\n(\n id integer NOT NULL DEFAULT nextval('user_program_preference_id_seq'::regclass),\n user_id character varying COLLATE pg_catalog.\"default\" NOT NULL,\n program_id character varying COLLATE pg_catalog.\"default\" NOT NULL,\n contributor_preference json,\n sourcing_preference json,\n createdby text COLLATE pg_catalog.\"default\",\n updatedby text COLLATE pg_catalog.\"default\",\n createdon timestamp without time zone DEFAULT timezone('utc'::text, now()),\n updatedon timestamp without time zone DEFAULT timezone('utc'::text, now()),\n CONSTRAINT user_program_preference_pkey PRIMARY KEY (user_id, program_id)\n);\n\n\n-- Sprint 12\nCREATE INDEX \"idx_program_rootorgid_status\" ON \"public\".\"program\" USING BTREE (\"rootorg_id\", \"status\");\nCREATE INDEX \"pk_program_status_type\" ON \"public\".\"program\" USING BTREE (\"status\", \"type\");\nCREATE INDEX \"pk_program_updatedon\" ON \"public\".\"program\" USING BTREE (updatedon DESC);\nCREATE INDEX \"idx_nomination_updatedon\" ON \"public\".\"nomination\" USING BTREE (updatedon DESC);\nCREATE INDEX \"idx_nomination_userid\" ON \"public\".\"nomination\" (user_id);\nCREATE INDEX \"idx_nomination_programid\" ON \"public\".\"nomination\" USING BTREE (program_id);\n\n-- Sprint 14\n\n-- Sequence and defined type\nCREATE SEQUENCE IF NOT EXISTS bulk_job_id_seq;\nCREATE TYPE bulk_job_status AS ENUM ('processing', 'completed', 'failed');\nCREATE TYPE bulk_job_type AS ENUM ('bulk_upload', 'bulk_approval');\n-- Table Definition\nCREATE TABLE bulk_job_request (\n id int4 NOT NULL DEFAULT nextval('bulk_job_id_seq'::regclass),\n process_id varchar NOT NULL UNIQUE,\n program_id varchar NOT NULL,\n collection_id varchar,\n org_id varchar,\n status bulk_job_status,\n type bulk_job_type,\n overall_stats jsonb,\n data jsonb,\n err_message text,\n createdby varchar,\n updatedby varchar,\n createdon timestamptz DEFAULT timezone('utc'::text, now()),\n updatedon timestamptz NOT NULL DEFAULT timezone('utc'::text, now()),\n completedon timestamp,\n expiration timestamp,\n PRIMARY KEY (id, process_id)\n);\n-- Indices\nCREATE INDEX \"pk_bulk_job_request_createdon\" ON \"public\".\"bulk_job_request\" USING BTREE (createdon DESC);\n" }, { "alpha_fraction": 0.765625, "alphanum_fraction": 0.7673611044883728, "avg_line_length": 25.18181800842285, "blob_id": "a22d99c3ab37826665e719082a5d33c453e8d20f", "content_id": "752bbfa57bd34d20b21aeaed8a3a9dcdb2930f43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 576, "license_type": "permissive", "max_line_length": 90, "num_lines": 22, "path": "/ansible/roles/grafana-dashboards-export/templates/export-dashboards-to-git-repo.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nset -e\n\nGIT_REPO_URL={{ grafana_dashboards_git_repo_url_with_credentails }}\nrm -rf grafana-dashboards\ngit clone $GIT_REPO_URL grafana-dashboards\n\n# Remove old dashboards\nrm -rf dashboards\nrm -rf grafana-dashboards/dashboards/*\n\n# Import and copy dashboards\nwizzy import dashboards\ncp dashboards/* grafana-dashboards/dashboards/\n\ncd grafana-dashboards\ngit config user.email \"[email protected]\"\ngit config user.name \"grafana-dashboards-exporter\"\ngit add -A\ngit diff-index --quiet HEAD || git commit -m \"Issue #1 chore: Automated dashboards update\"\ngit push $GIT_REPO_URL --all\n" }, { "alpha_fraction": 0.672290027141571, "alphanum_fraction": 0.6838956475257874, "avg_line_length": 29.727941513061523, "blob_id": "7dcce32f325292617b94b596a60ce01da56fb523", "content_id": "1f0ad3f283284d3cda4243dcccee3c71149e493d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 8358, "license_type": "permissive", "max_line_length": 127, "num_lines": 272, "path": "/exporters/Go/kafka-topic-exporter/main.go", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "// Author : Kaliraja Ramasami <[email protected]>\n// Author : Rajesh Rajendran <[email protected]>\npackage main\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tkafka \"github.com/segmentio/kafka-go\"\n\t_ \"github.com/segmentio/kafka-go/snappy\"\n)\n\nvar kafkaReaders []*kafka.Reader\n\n// Channel to keep metrics till prometheus scrape that\nvar promMetricsChannel = make(chan metric)\n\n// Metrics structure\ntype Metrics struct {\n\tSystem string `json:\"system\"`\n\tSubSystem string `json:\"subsystem\"`\n\tMetricTS json.Number `json:\"metricTs\"`\n\tMetrics []struct {\n\t\tID string `json:\"id\"`\n\t\tValue float64 `json:\"value\"`\n\t} `json:\"metrics\"`\n\t// Labels to be added for the metric\n\tLables []struct {\n\t\tID string `json:\"id\"`\n\t\t// Even nimbers will be read as string\n\t\tValue json.Number `json:\"value\"`\n\t} `json:\"dimensions\"`\n}\n\n// This is to get the last message served to prom endpoint.\ntype lastReadMessage struct {\n\tmu sync.RWMutex\n\t// \t map[partition]message\n\tlast map[int]kafka.Message\n\t// slice pointer of kafkaReaders\n\tclusterId int\n}\n\n// Adding message\n// Only the latest\nfunc (lrm *lastReadMessage) Store(message kafka.Message, clusterId int) error {\n\tlrm.mu.Lock()\n\tdefer lrm.mu.Unlock()\n\t// Initializing map if nil\n\tif lrm.last == nil {\n\t\tlrm.last = make(map[int]kafka.Message)\n\t}\n\tif _, ok := lrm.last[message.Partition]; ok {\n\t\t// Updating only if the offset is greater\n\t\tif lrm.last[message.Partition].Offset < message.Offset {\n\t\t\tlrm.last[message.Partition] = message\n\t\t\tlrm.clusterId = clusterId\n\t\t}\n\t\treturn fmt.Errorf(\"lower offset(%d) than the latest(%d)\", message.Offset, lrm.last[message.Partition].Offset)\n\t} else {\n\t\tlrm.last[message.Partition] = message\n\t\tlrm.clusterId = clusterId\n\t}\n\treturn nil\n}\n\n// Return the last message read\nfunc (lrm *lastReadMessage) Get() (map[int]kafka.Message, int) {\n\tlrm.mu.RLock()\n\tdefer lrm.mu.RUnlock()\n\treturn lrm.last, lrm.clusterId\n}\n\n// Validating metrics name\n// Input a list of string, and concatinate with _ after\n// Removing all - in the provided names\n// Convert mix cases to lowercases\nfunc metricsNameValidator(names ...string) string {\n\tretName := \"\"\n\tfor _, name := range names {\n\t\tretName += strings.ReplaceAll(name, \"-\", \"_\") + \"_\"\n\t}\n\treturn strings.ToLower(strings.TrimRight(retName, \"_\"))\n}\n\n// Message format\ntype metric struct {\n\tmessage string\n\tid kafka.Message\n\tclusterId int\n}\n\n// This function will take the metrics input and create prometheus metrics\n// output and send it to metrics channel\n// So that http endpoint can serve the data\nfunc (metrics *Metrics) pushMetrics(clusterId int, ctx context.Context, metricData *kafka.Message) (err error) {\n\tlabel := fmt.Sprintf(\"system=%q,subsystem=%q,\", metrics.System, metrics.SubSystem)\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t\t// Creating dictionary of labels\n\t\tfor _, labels := range metrics.Lables {\n\t\t\t// Lables can't have '-' in it\n\t\t\tlabel += fmt.Sprintf(\"%v=%q,\", metricsNameValidator(labels.ID), labels.Value)\n\t\t}\n\t\t// Generating metrics\n\t\tfor _, m := range metrics.Metrics {\n\t\t\tmetricStruct := metric{}\n\t\t\t// Adding optional timestamp\n\t\t\tswitch metrics.MetricTS {\n\t\t\tcase \"\":\n\t\t\t\tmetricStruct.message = fmt.Sprintf(\"%s{%s} %.2f\",\n\t\t\t\t\tmetricsNameValidator(metrics.System, metrics.SubSystem, m.ID),\n\t\t\t\t\tstrings.TrimRight(label, \",\"), m.Value)\n\t\t\tdefault:\n\t\t\t\tmetricStruct.message = fmt.Sprintf(\"%s{%s} %.1f %s\",\n\t\t\t\t\tmetricsNameValidator(metrics.System, metrics.SubSystem, m.ID),\n\t\t\t\t\tstrings.TrimRight(label, \",\"), m.Value, metrics.MetricTS)\n\t\t\t}\n\t\t\tmetricStruct.id = *metricData\n\t\t\tmetricStruct.clusterId = clusterId\n\t\t\tpromMetricsChannel <- metricStruct\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc metricsCreation(clusterId int, ctx context.Context, m kafka.Message) error {\n\tmetrics := Metrics{}\n\tdata := m.Value\n\t// Creating metrics struct\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t\tif err := json.Unmarshal(data, &metrics); err != nil {\n\t\t\tfmt.Printf(\"Unmarshal error: %q data: %q\\n\", err, string(data))\n\t\t\treturn err\n\t\t}\n\t\tmetrics.pushMetrics(clusterId, ctx, &m)\n\t\treturn nil\n\t}\n}\n\nfunc commitMessage(lastReadMessages *[]*lastReadMessage) error {\n\tfmt.Println(\"number of clusters: \", len(*lastReadMessages))\n\tfor _, lrm := range *lastReadMessages {\n\t\tmessages, clusterId := lrm.Get()\n\t\tfmt.Println(\"cluster: \", clusterId)\n\t\tfor k, message := range messages {\n\t\t\tif message.Offset <= 0 {\n\t\t\t\tfmt.Println(\"Not committing anything\", clusterId)\n\t\t\t\treturn errors.New(\"offset is not > 0 for cluster \" + string(clusterId))\n\t\t\t}\n\t\t\tfmt.Printf(\"Commiting message partition %d offset %d cluster %d\\n\", k, message.Offset, clusterId)\n\t\t\tif err := kafkaReaders[clusterId].CommitMessages(context.Background(), message); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc health(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write([]byte(\"{\\\"Healthy\\\": true}\"))\n}\nfunc serve(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Serving Request\")\n\tctx := r.Context()\n\tvar lastReadMessages []*lastReadMessage\n\t// Reading topic\n\tfor k, v := range kafkaReaders {\n\t\tlastReadMessage := lastReadMessage{}\n\t\tlastReadMessages = append(lastReadMessages, &lastReadMessage)\n\t\tgo func(clusterId int, ctx context.Context, r *kafka.Reader) {\n\t\t\tfor {\n\t\t\t\t// Only fetching the message, not commiting them\n\t\t\t\t// It'll be commited once the transmission closes\n\t\t\t\tm, err := r.FetchMessage(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"err reading message: %v\\n\", err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"topic: %q partition: %v offset: %v\\n\", m.Topic, m.Partition, m.Offset)\n\t\t\t\tgo func(clusterId int, ctx context.Context, m kafka.Message) {\n\t\t\t\t\tif err := metricsCreation(clusterId, ctx, m); err != nil {\n\t\t\t\t\t\tfmt.Printf(\"errored out metrics creation; err: %s\\n\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}(clusterId, ctx, m)\n\t\t\t}\n\t\t}(k, ctx, v)\n\t}\n\tfor {\n\t\tselect {\n\t\tcase message := <-promMetricsChannel:\n\t\t\tfmt.Fprintf(w, \"%s\\n\", message.message)\n\t\t\tlastReadMessages[message.clusterId].Store(message.id, message.clusterId)\n\t\tcase <-ctx.Done():\n\t\t\tcommitMessage(&lastReadMessages)\n\t\t\treturn\n\t\tcase <-time.After(1 * time.Second):\n\t\t\tcommitMessage(&lastReadMessages)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc main() {\n\t// Getting kafka_ip and topic\n\tkafkaHosts := strings.Split(os.Getenv(\"kafka_host\"), \";\")\n\tkafkaTopic := strings.Split(os.Getenv(\"kafka_topic\"), \";\")\n\tkafkaConsumerGroupName := os.Getenv(\"kafka_consumer_group_name\")\n\tif kafkaConsumerGroupName == \"\" {\n\t\tkafkaConsumerGroupName = \"prometheus-metrics-consumer\"\n\t}\n\tif kafkaTopic[0] == \"\" || kafkaHosts[0] == \"\" {\n\t\tlog.Fatalf(`\"kafka_topic or kafka_host environment variables not set.\"\nFor example,\n\t# export kafka_host=cluster1ip1:9092,cluster1ip2:9092;cluster2ip1:9092,cluster2ip2:9092\n\t# export kafka_topic=cluster1topic;cluster2topic\n\t# ',' seperated multiple kafka nodes in the cluster and \n\t# ';' seperated multiple kafka clusters\n\texport kafka_host=10.0.0.9:9092,10.0.0.10:9092;20.0.0.9:9092,20.0.0.10:9092\n\texport kafka_topic=sunbird.metrics.topic;myapp.metrics.topic`)\n\t}\n\tfmt.Printf(\"kafka_host: %s\\nkafka_topic: %s\\nkafka_consumer_group_name: %s\\n\", kafkaHosts, kafkaTopic, kafkaConsumerGroupName)\n\t// Checking kafka topics are given for all kafka clusters\n\tif len(kafkaHosts) != len(kafkaTopic) {\n\t\tlog.Fatal(\"You should give same number of kafka_topics as kafka_clusters\")\n\t}\n\t// Checking kafka port and ip are accessible\n\tfmt.Println(\"Checking connection to kafka\")\n\tfor _, hosts := range kafkaHosts {\n\t\tfor _, host := range strings.Split(hosts, \",\") {\n\t\t\tconn, err := net.DialTimeout(\"tcp\", host, 10*time.Second)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Connection error: %s\", err)\n\t\t\t}\n\t\t\tfmt.Println(\"connection succeeded\", host)\n\t\t\tconn.Close()\n\t\t}\n\t}\n\tfmt.Println(\"kafka is accessible\")\n\t// Initializing kafka\n\tfor k, v := range kafkaHosts {\n\t\tkafkaReaders = append(kafkaReaders, kafka.NewReader(kafka.ReaderConfig{\n\t\t\tBrokers: strings.Split(v, \",\"),\n\t\t\tGroupID: kafkaConsumerGroupName, // Consumer group ID\n\t\t\tTopic: kafkaTopic[k],\n\t\t\tMinBytes: 1e3, // 1KB\n\t\t\tMaxBytes: 10e6, // 10MB\n\t\t\tMaxWait: 200 * time.Millisecond,\n\t\t\tRebalanceTimeout: time.Second * 5,\n\t\t}))\n\t\tdefer kafkaReaders[k].Close()\n\t}\n\thttp.HandleFunc(\"/metrics\", serve)\n\thttp.HandleFunc(\"/health\", health)\n\tlog.Fatal(http.ListenAndServe(\":8000\", nil))\n}\n" }, { "alpha_fraction": 0.6837416291236877, "alphanum_fraction": 0.6971046924591064, "avg_line_length": 22.6842098236084, "blob_id": "3ad43d5c096fa8afe8863a2ab166e91af1270456", "content_id": "b09f9631d58b94532545526eca639a66b43aaf87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 449, "license_type": "permissive", "max_line_length": 83, "num_lines": 19, "path": "/ansible-syntax-check.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nSCRIPT_BASE_DIR=$(dirname $0)\nSUNBIRD_DEVOPS_FOLDER=$SCRIPT_BASE_DIR\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory>\"\n echo \"Example: $0 $SUNBIRD_DEVOPS_FOLDER/ansible/inventories/sample\"\n exit 1\nfi\n\nset -e\n\nINVENTORY_DIR=$1\n\nfor playbook_yaml in $SUNBIRD_DEVOPS_FOLDER/ansible/*.yml; do\n ansible-playbook -i $INVENTORY_DIR $playbook_yaml --syntax-check -e \"hosts=dummy\"\ndone" }, { "alpha_fraction": 0.7109267115592957, "alphanum_fraction": 0.7164592146873474, "avg_line_length": 30.434782028198242, "blob_id": "0fdde2d1ea523d9b2ff41682b91069a3b17b247a", "content_id": "2cc6e8bef29a62ffdb5b60989f60cce851bc13a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 723, "license_type": "permissive", "max_line_length": 111, "num_lines": 23, "path": "/deploy/install-dbs.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory-path>\"\n exit 1\nfi\n\nINVENTORY_PATH=$1\nignore_folder=.sunbird/ignore\n\n#Elasticsearch installation\necho \"@@@@@@@@@ Elasticsearch installation\"\nansible-playbook -i $INVENTORY_PATH ../ansible/provision.yml --tags es [email protected]\n\n# Cassandra installation\necho \"@@@@@@@@@ Cassandra installation\"\nansible-playbook -i $INVENTORY_PATH ../ansible/provision.yml --tags cassandra [email protected] \n\n# Postgresql-master installation\necho \"@@@@@@@@@ Postgresql-master installation\"\nansible-playbook -i $INVENTORY_PATH ../ansible/provision.yml --tags postgresql-master [email protected]\n" }, { "alpha_fraction": 0.8399999737739563, "alphanum_fraction": 0.8399999737739563, "avg_line_length": 57.33333206176758, "blob_id": "de3ff4c375ecc77733a728532e8ea183c15a30b3", "content_id": "555f6bef6f3242df5eb2ffd5c740f27352e7d013", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 175, "license_type": "permissive", "max_line_length": 62, "num_lines": 3, "path": "/ansible/roles/postgres-migration/files/sunbird_programs/V4.4.0.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "ALTER TABLE program ADD COLUMN acceptedContents text[];\nALTER TABLE program ADD COLUMN rejectedContents text[];\nALTER TABLE program ADD COLUMN sourcingRejectedComments jsonb;\n" }, { "alpha_fraction": 0.6377952694892883, "alphanum_fraction": 0.6614173054695129, "avg_line_length": 41, "blob_id": "873ac6b701f207022fce582e495db72c4e412f96", "content_id": "4c9273a7f4b98f020b69acccac67e44c9ca530a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 127, "license_type": "permissive", "max_line_length": 98, "num_lines": 3, "path": "/images/keycloak/metadata.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# return version\necho '{\"name\":\"keycloak_image\",\"version\":\"3.2.1.Final\",\"org\":\"sunbird\",\"hubuser\":\"purplesunbird\"}'\n\n" }, { "alpha_fraction": 0.7149321436882019, "alphanum_fraction": 0.7194570302963257, "avg_line_length": 33, "blob_id": "b43ae1c5066d99f75fdaee6ff548de87fc6c17be", "content_id": "7cf1a47f493226d9ec45c6bcf964d134d8764c16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1326, "license_type": "permissive", "max_line_length": 145, "num_lines": 39, "path": "/deploy/cassandra_restore.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n# Author: Rajesh Rajendran <[email protected]>.\n\n\"\"\"\n\nThis script will restore complete backup from the backup data folder.\n\nTo restore the cassandra database snapshot\n\n1. If it's an old cassandra instance, do the following else continue to step 2\n a. stop cassandra\n b. delete the data (usually sudo rm -rf /var/lib/cassandra/*)\n c. start cassandra\n\n2. Restore the schema\n cqlsh -e \"source 'backup_dir/db_schema.cql';\"\n\n3. Restore the data\n usage: python cassandra_restore.py\n\n\"\"\"\n\nfrom os import walk, sep\nfrom subprocess import STDOUT, call\nfrom argparse import ArgumentParser\nimport socket\nparser = ArgumentParser(description=\"Restore cassandra snapshot\")\nparser.add_argument(\"--host\", default=socket.getfqdn(), metavar=\"< Default: \"+socket.getfqdn()+\" >\", help=\"ip address of cassandra instance\")\nparser.add_argument(\"--snapshotdir\", default=\"cassandra_backup\", metavar=\"< Default: cassandra_backup >\", help=\"snapshot directory name or path\")\nargs = parser.parse_args()\n\n# Unix autocompletion for directory will append '/', which will break restore process\nsnap_dir = args.snapshotdir.rstrip('/')\nroot_levels = snap_dir.count(sep)\nfor root, dirs, files in walk(snap_dir):\n if root.count(sep) == root_levels + 2:\n print(root)\n call([\"sstableloader\", \"-v\", \"-d\", args.host, root], stderr=STDOUT)\n" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 12.25, "blob_id": "5f6b22ce216c9f686bad16d98cda0367a39a5f17", "content_id": "c700ef2114813b98f015ed83f23799dfa6e461c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 105, "license_type": "permissive", "max_line_length": 20, "num_lines": 8, "path": "/kubernetes/opa-plugins/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "ARG BASE\nFROM ${BASE}\nARG USER=0\nUSER ${USER}\nWORKDIR /app\nCOPY opa /app\nENTRYPOINT [\"./opa\"]\nCMD [\"run\"]" }, { "alpha_fraction": 0.6705882549285889, "alphanum_fraction": 0.6866310238838196, "avg_line_length": 21.780487060546875, "blob_id": "f852d4dc204d4d60962dac3f736f4a0f6c88b17e", "content_id": "cf871dc9030bca79a09d4f439ce1eafc064c9f45", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 935, "license_type": "permissive", "max_line_length": 96, "num_lines": 41, "path": "/deploy/backup_elasticsearch.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nbackup_path=/etc/elasticsearch/backup\nes_ip=$(hostname -i)\n#es_ip=$(ip route get 8.8.8.8 | awk '{print $NF; exit}')\n\n#Creating backup folder\nif [ -d $backup_path ];\nthen\n echo \"directory exists\"\nelse\n mkdir -p $backup_path\nfi\n\n#Adding backup path repo to elasticsearch config\ntemp=$(grep \"path.repo:\" /etc/elasticsearch/es-1/elasticsearch.yml)\n\nif [ $? -ne 0 ]; then\n\n cat >> /etc/elasticsearch/es-1/elasticsearch.yml << EOF\npath.repo: [\"$backup_path\"]\nEOF\n\nfi\n\n#Changing permissions to backup path\nchown -R elasticsearch:elasticsearch $backup_path\n\n#Creating Indexes name for backup\ncurl -XPUT http://\"$es_ip\":9200/_snapshot/my_backup -d '{\n \"type\": \"fs\",\n \"settings\": {\n \"location\": \"'$backup_path'\",\n \"compress\": true\n }\n}'\n\n\n#Taking Snapshot of elasticsearch with timestamp\ntimestamp=`date '+%d_%m_%Y%H%M%S'`\n\ncurl -XPUT http://\"$es_ip\":9200/_snapshot/my_backup/snapshot_$timestamp?wait_for_completion=true\n\n" }, { "alpha_fraction": 0.652168869972229, "alphanum_fraction": 0.6548223495483398, "avg_line_length": 52.177913665771484, "blob_id": "24720a032d13d01cb59a21c593a37d95d1e2b2a2", "content_id": "3b396ce07d56eb3e1f088b96d5ea5759d1373c86", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8668, "license_type": "permissive", "max_line_length": 165, "num_lines": 163, "path": "/ansible/static-files/kong-api-scripts/kong_consumers.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "import urllib2, argparse, json\nimport jwt\n\nfrom common import json_request, get_api_plugins, retrying_urlopen\n\ndef _consumer_exists(kong_admin_api_url, username):\n consumers_url = \"{}/consumers\".format(kong_admin_api_url)\n try:\n retrying_urlopen(consumers_url + \"/\" + username)\n return True\n except urllib2.HTTPError as e:\n if(e.code == 404):\n return False\n else:\n raise\n\ndef _get_consumer(kong_admin_api_url, username):\n consumers_url = \"{}/consumers\".format(kong_admin_api_url)\n try:\n response = retrying_urlopen(consumers_url + \"/\" + username)\n consumer = json.loads(response.read())\n return consumer\n except urllib2.HTTPError as e:\n if(e.code == 404):\n return None\n else:\n raise\n\ndef _dict_without_keys(a_dict, keys):\n return dict((key, a_dict[key]) for key in a_dict if key not in keys)\n\ndef _ensure_consumer_exists(kong_admin_api_url, consumer):\n username = consumer['username']\n consumers_url = \"{}/consumers\".format(kong_admin_api_url)\n if(not _consumer_exists(kong_admin_api_url, username)):\n print(\"Adding consumer {}\".format(username));\n json_request(\"POST\", consumers_url, {'username': username})\n\n\ndef save_consumers(kong_admin_api_url, consumers):\n consumers_url = \"{}/consumers\".format(kong_admin_api_url)\n consumers_to_be_present = [consumer for consumer in consumers if consumer['state'] == 'present']\n consumers_to_be_absent = [consumer for consumer in consumers if consumer['state'] == 'absent']\n\n for consumer in consumers_to_be_absent:\n username = consumer['username']\n if(_consumer_exists(kong_admin_api_url, username)):\n print(\"Deleting consumer {}\".format(username));\n json_request(\"DELETE\", consumers_url + \"/\" + username, \"\")\n\n for consumer in consumers_to_be_present:\n username = consumer['username']\n _ensure_consumer_exists(kong_admin_api_url, consumer)\n _save_groups_for_consumer(kong_admin_api_url, consumer)\n jwt_credential = _get_first_or_create_jwt_credential(kong_admin_api_url, consumer)\n credential_algorithm = jwt_credential['algorithm']\n if credential_algorithm == 'HS256':\n jwt_token = jwt.encode({'iss': jwt_credential['key']}, jwt_credential['secret'], algorithm=credential_algorithm)\n print(\"JWT token for {} is : {}\".format(username, jwt_token))\n if 'print_credentials' in consumer:\n print(\"Credentials for consumer {}, key: {}, secret: {}\".format(username, jwt_credential['key'], jwt_credential['secret']))\n\n saved_consumer = _get_consumer(kong_admin_api_url, username)\n rate_limits = consumer.get('rate_limits')\n if(rate_limits is not None):\n _save_rate_limits(kong_admin_api_url, saved_consumer, rate_limits)\n\ndef _save_rate_limits(kong_admin_api_url, saved_consumer, rate_limits):\n plugin_name = 'rate-limiting'\n consumer_id = saved_consumer['id']\n consumer_username = saved_consumer['username']\n for rate_limit in rate_limits:\n api_name = rate_limit[\"api\"]\n saved_plugins = get_api_plugins(kong_admin_api_url, api_name)\n rate_limit_plugins = [saved_plugin for saved_plugin in saved_plugins if saved_plugin['name'] == plugin_name]\n rate_limit_plugins_for_this_consumer = [rate_limit_plugin for rate_limit_plugin in rate_limit_plugins if rate_limit_plugin.get('consumer_id') == consumer_id]\n rate_limit_plugin_for_this_consumer = rate_limit_plugins_for_this_consumer[0] if rate_limit_plugins_for_this_consumer else None\n\n rate_limit_state = rate_limit.get('state', 'present')\n api_pugins_url = kong_admin_api_url + \"/apis/\" + api_name + \"/plugins\"\n if rate_limit_state == 'present':\n rate_limit_plugin_data = _dict_without_keys(rate_limit, ['api', 'state'])\n rate_limit_plugin_data['name'] = plugin_name\n rate_limit_plugin_data['consumer_id'] = consumer_id\n if not rate_limit_plugin_for_this_consumer:\n print(\"Adding rate_limit for consumer {} for API {}\".format(consumer_username, api_name));\n print(\"rate_limit_plugin_data: {}\".format(rate_limit_plugin_data))\n json_request(\"POST\", api_pugins_url, rate_limit_plugin_data)\n\n if rate_limit_plugin_for_this_consumer:\n print(\"Updating rate_limit for consumer {} for API {}\".format(consumer_username, api_name));\n json_request(\"PATCH\", api_pugins_url + \"/\" + rate_limit_plugin_for_this_consumer[\"id\"], rate_limit_plugin_data)\n\n elif rate_limit_state == 'absent':\n if rate_limit_plugin_for_this_consumer:\n print(\"Deleting rate_limit for consumer {} for API {}\".format(consumer_username, api_name));\n json_request(\"DELETE\", api_pugins_url + \"/\" + saved_plugin[\"id\"], \"\")\n\n\ndef _get_first_or_create_jwt_credential(kong_admin_api_url, consumer):\n username = consumer[\"username\"]\n credential_algorithm = consumer.get('credential_algorithm', 'HS256')\n consumer_jwt_credentials_url = kong_admin_api_url + \"/consumers/\" + username + \"/jwt\"\n saved_credentials_details = json.loads(retrying_urlopen(consumer_jwt_credentials_url).read())\n saved_credentials = saved_credentials_details[\"data\"]\n saved_credentials_for_algorithm = [saved_credential for saved_credential in saved_credentials if saved_credential['algorithm'] == credential_algorithm]\n if(len(saved_credentials_for_algorithm) > 0):\n print(\"Updating credentials for consumer {} for algorithm {}\".format(username, credential_algorithm));\n this_credential = saved_credentials_for_algorithm[0]\n credential_data = {\n \"rsa_public_key\": consumer.get('credential_rsa_public_key', this_credential.get(\"rsa_public_key\", '')),\n \"key\": consumer.get('credential_iss', this_credential['key'])\n }\n this_credential_url = \"{}/{}\".format(consumer_jwt_credentials_url, this_credential[\"id\"])\n response = json_request(\"PATCH\", this_credential_url, credential_data)\n jwt_credential = json.loads(response.read())\n return jwt_credential\n else:\n print(\"Creating jwt credentials for consumer {}\".format(username));\n credential_data = {\n \"algorithm\": credential_algorithm,\n }\n if 'credential_rsa_public_key' in consumer:\n credential_data[\"rsa_public_key\"] = consumer['credential_rsa_public_key']\n if 'credential_iss' in consumer:\n credential_data[\"key\"] = consumer['credential_iss']\n response = json_request(\"POST\", consumer_jwt_credentials_url, credential_data)\n jwt_credential = json.loads(response.read())\n return jwt_credential\n\ndef _save_groups_for_consumer(kong_admin_api_url, consumer):\n username = consumer[\"username\"]\n input_groups = consumer[\"groups\"]\n consumer_acls_url = kong_admin_api_url + \"/consumers/\" + username + \"/acls\"\n saved_acls_details = json.loads(retrying_urlopen(consumer_acls_url).read())\n saved_acls = saved_acls_details[\"data\"]\n saved_groups = [acl[\"group\"] for acl in saved_acls]\n print(\"Existing groups for consumer {} : {}\".format(username, saved_groups))\n print(\"Required groups for consumer {} : {}\".format(username, input_groups))\n input_groups_to_be_created = [input_group for input_group in input_groups if input_group not in saved_groups]\n saved_groups_to_be_deleted = [saved_group for saved_group in saved_groups if saved_group not in input_groups]\n\n for input_group in input_groups_to_be_created:\n print(\"Adding group {} for consumer {}\".format(input_group, username));\n json_request(\"POST\", consumer_acls_url, {'group': input_group})\n\n for saved_group in saved_groups_to_be_deleted:\n print(\"Deleting group {} for consumer {}\".format(saved_group, username));\n json_request(\"DELETE\", consumer_acls_url + \"/\" + saved_group, \"\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Configure kong consumers')\n parser.add_argument('consumers_file_path', help='Path of the json file containing consumer data')\n parser.add_argument('--kong-admin-api-url', help='Admin url for kong', default='http://localhost:8001')\n args = parser.parse_args()\n with open(args.consumers_file_path) as consumers_file:\n input_consumers = json.load(consumers_file)\n try:\n save_consumers(args.kong_admin_api_url, input_consumers)\n except urllib2.HTTPError as e:\n error_message = e.read()\n print(error_message)\n raise\n" }, { "alpha_fraction": 0.6059971451759338, "alphanum_fraction": 0.616366982460022, "avg_line_length": 37.918487548828125, "blob_id": "adbd9804eb77a46a175298279c70eb52d07d90ba", "content_id": "6dfecdd8120fbb3c2b15930316028620ceb95438", "detected_licenses": [ "GPL-2.0-only", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19576, "license_type": "permissive", "max_line_length": 166, "num_lines": 503, "path": "/ansible/roles/mongodb-cluster/library/mongodb_replication.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n# (c) 2015-2021, Sergei Antipov\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nDOCUMENTATION = '''\n---\nmodule: mongodb_replication\nshort_description: Adds or removes a node from a MongoDB Replica Set.\ndescription:\n - Adds or removes host from a MongoDB replica set. Initialize replica set if it needed.\nversion_added: \"2.4\"\noptions:\n login_user:\n description:\n - The username used to authenticate with\n required: false\n default: null\n login_password:\n description:\n - The password used to authenticate with\n required: false\n default: null\n login_host:\n description:\n - The host running the database\n required: false\n default: localhost\n login_port:\n description:\n - The port to connect to\n required: false\n default: 27017\n login_database:\n description:\n - The database where login credentials are stored\n required: false\n default: admin\n replica_set:\n description:\n - Replica set to connect to (automatically connects to primary for writes)\n required: false\n default: null\n host_name:\n description:\n - The name of the host to add/remove from replica set\n required: true\n host_port:\n description:\n - The port of the host, which should be added/deleted from RS\n required: true\n default: null\n host_type:\n description:\n - The type of the host in replica set\n required: false\n default: replica\n choices: [ \"replica\", \"arbiter\" ]\n ssl:\n description:\n - Whether to use an SSL connection when connecting to the database\n default: False\n ssl_cert_reqs:\n description:\n - Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided.\n required: false\n default: \"CERT_REQUIRED\"\n choices: [\"CERT_REQUIRED\", \"CERT_OPTIONAL\", \"CERT_NONE\"]\n build_indexes:\n description:\n - Determines whether the mongod builds indexes on this member.\n required: false\n default: true\n hidden:\n description:\n - When this value is true, the replica set hides this instance,\n and does not include the member in the output of db.isMaster()\n or isMaster\n required: false\n default: false\n priority:\n description:\n - A number that indicates the relative eligibility of a member\n to become a primary\n required: false\n default: 1.0\n slave_delay:\n description:\n - The number of seconds behind the primary that this replica set\n member should lag\n required: false\n default: 0\n votes:\n description:\n - The number of votes a server will cast in a replica set election\n default: 1\n state:\n state:\n description:\n - The replica set member state\n required: false\n default: present\n choices: [ \"present\", \"absent\" ]\nnotes:\n - Requires the pymongo Python package on the remote host, version 3.2+. It\n can be installed using pip or the OS package manager. @see http://api.mongodb.org/python/current/installation.html\nrequirements: [ \"pymongo\" ]\nauthor: \"Sergei Antipov @UnderGreen\"\n'''\n\nEXAMPLES = '''\n# Add 'mongo1.dev:27017' host into replica set as replica (Replica will be initiated if it not exists)\n- mongodb_replication: replica_set=replSet host_name=mongo1.dev host_port=27017 state=present\n\n# Add 'mongo2.dev:30000' host into replica set as arbiter\n- mongodb_replication: replica_set=replSet host_name=mongo2.dev host_port=30000 host_type=arbiter state=present\n\n# Add 'mongo3.dev:27017' host into replica set as replica and authorization params\n- mongodb_replication: replica_set=replSet login_host=mongo1.dev login_user=siteRootAdmin login_password=123456 host_name=mongo3.dev host_port=27017 state=present\n\n# Add 'mongo4.dev:27017' host into replica set as replica via SSL\n- mongodb_replication: replica_set=replSet host_name=mongo4.dev host_port=27017 ssl=True state=present\n\n# Remove 'mongo4.dev:27017' host from the replica set\n- mongodb_replication: replica_set=replSet host_name=mongo4.dev host_port=27017 state=absent\n'''\n\nRETURN = '''\nhost_name:\n description: The name of the host to add/remove from replica set\n returned: success\n type: string\n sample: \"mongo3.dev\"\nhost_port:\n description: The port of the host, which should be added/deleted from RS\n returned: success\n type: int\n sample: 27017\nhost_type:\n description: The type of the host in replica set\n returned: success\n type: string\n sample: \"replica\"\n'''\n\nimport os\nimport ssl as ssl_lib\nimport time\nimport traceback\nfrom datetime import datetime as dtdatetime\nfrom distutils.version import LooseVersion\n\ntry:\n from pymongo.errors import ConnectionFailure, OperationFailure, AutoReconnect, ServerSelectionTimeoutError\n from pymongo import version as PyMongoVersion\n from pymongo import MongoClient\nexcept ImportError:\n try: # for older PyMongo 2.2\n from pymongo import Connection as MongoClient\n except ImportError:\n pymongo_found = False\n else:\n pymongo_found = True\nelse:\n pymongo_found = True\n\nfrom ansible.module_utils.basic import AnsibleModule, missing_required_lib\nfrom ansible.module_utils.six.moves import configparser\nfrom ansible.module_utils._text import to_native\n\n# =========================================\n# MongoDB module specific support methods.\n#\n\n\ndef check_compatibility(module, client):\n \"\"\"Check the compatibility between the driver and the database.\n See: https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#python-driver-compatibility\n Args:\n module: Ansible module.\n client (cursor): Mongodb cursor on admin database.\n \"\"\"\n loose_srv_version = LooseVersion(client.server_info()['version'])\n loose_driver_version = LooseVersion(PyMongoVersion)\n\n if loose_srv_version >= LooseVersion('4.0') and loose_driver_version < LooseVersion('3.7'):\n module.fail_json(msg=' (Note: you must use pymongo 3.7+ with MongoDB >= 4.0)')\n\n elif loose_srv_version >= LooseVersion('3.6') and loose_driver_version < LooseVersion('3.6'):\n module.fail_json(msg=' (Note: you must use pymongo 3.6+ with MongoDB >= 3.6)')\n\n elif loose_srv_version >= LooseVersion('3.2') and loose_driver_version < LooseVersion('3.2'):\n module.fail_json(msg=' (Note: you must use pymongo 3.2+ with MongoDB >= 3.2)')\n\n elif loose_srv_version >= LooseVersion('3.0') and loose_driver_version <= LooseVersion('2.8'):\n module.fail_json(msg=' (Note: you must use pymongo 2.8+ with MongoDB 3.0)')\n\n elif loose_srv_version >= LooseVersion('2.6') and loose_driver_version <= LooseVersion('2.7'):\n module.fail_json(msg=' (Note: you must use pymongo 2.7+ with MongoDB 2.6)')\n\n elif LooseVersion(PyMongoVersion) <= LooseVersion('2.5'):\n module.fail_json(msg=' (Note: you must be on mongodb 2.4+ and pymongo 2.5+ to use the roles param)')\n\n\ndef check_members(state, module, client, host_name, host_port, host_type):\n local_db = client['local']\n\n if local_db.system.replset.count() > 1:\n module.fail_json(msg='local.system.replset has unexpected contents')\n\n cfg = local_db.system.replset.find_one()\n if not cfg:\n module.fail_json(msg='no config object retrievable from local.system.replset')\n\n for member in cfg['members']:\n if state == 'present':\n if host_type == 'replica':\n if \"{0}:{1}\".format(host_name, host_port) in member['host']:\n module.exit_json(changed=False, host_name=host_name, host_port=host_port, host_type=host_type)\n else:\n if \"{0}:{1}\".format(host_name, host_port) in member['host'] and member['arbiterOnly']:\n module.exit_json(changed=False, host_name=host_name, host_port=host_port, host_type=host_type)\n else:\n if host_type == 'replica':\n if \"{0}:{1}\".format(host_name, host_port) not in member['host']:\n module.exit_json(changed=False, host_name=host_name, host_port=host_port, host_type=host_type)\n else:\n if \"{0}:{1}\".format(host_name, host_port) not in member['host'] and member['arbiterOnly']:\n module.exit_json(changed=False, host_name=host_name, host_port=host_port, host_type=host_type)\n\n\ndef add_host(module, client, host_name, host_port, host_type, timeout=180, **kwargs):\n start_time = dtdatetime.now()\n while True:\n try:\n admin_db = client['admin']\n local_db = client['local']\n\n if local_db.system.replset.count() > 1:\n module.fail_json(msg='local.system.replset has unexpected contents')\n\n cfg = local_db.system.replset.find_one()\n if not cfg:\n module.fail_json(msg='no config object retrievable from local.system.replset')\n\n cfg['version'] += 1\n max_id = max(cfg['members'], key=lambda x: x['_id'])\n new_host = {'_id': max_id['_id'] + 1, 'host': \"{0}:{1}\".format(host_name, host_port)}\n if host_type == 'arbiter':\n new_host['arbiterOnly'] = True\n\n if not kwargs['build_indexes']:\n new_host['buildIndexes'] = False\n\n if kwargs['hidden']:\n new_host['hidden'] = True\n\n if kwargs['priority'] != 1.0:\n new_host['priority'] = kwargs['priority']\n\n if kwargs['slave_delay'] != 0:\n new_host['slaveDelay'] = kwargs['slave_delay']\n\n if kwargs['votes'] != 1:\n new_host['votes'] = kwargs['votes']\n\n cfg['members'].append(new_host)\n admin_db.command('replSetReconfig', cfg)\n return\n except (OperationFailure, AutoReconnect) as e:\n if (dtdatetime.now() - start_time).seconds > timeout:\n module.fail_json(msg='reached timeout while waiting for rs.reconfig(): %s' % to_native(e), exception=traceback.format_exc())\n time.sleep(5)\n\n\ndef remove_host(module, client, host_name, timeout=180):\n start_time = dtdatetime.now()\n while True:\n try:\n local_db = client['local']\n\n if local_db.system.replset.count() > 1:\n module.fail_json(msg='local.system.replset has unexpected contents')\n\n cfg = local_db.system.replset.find_one()\n if not cfg:\n module.fail_json(msg='no config object retrievable from local.system.replset')\n\n cfg['version'] += 1\n\n if len(cfg['members']) == 1:\n module.fail_json(msg=\"You can't delete last member of replica set\")\n for member in cfg['members']:\n if host_name in member['host']:\n cfg['members'].remove(member)\n else:\n fail_msg = \"couldn't find member with hostname: {0} in replica set members list\".format(host_name)\n module.fail_json(msg=fail_msg)\n except (OperationFailure, AutoReconnect) as e:\n if (dtdatetime.now() - start_time).seconds > timeout:\n module.fail_json(msg='reached timeout while waiting for rs.reconfig(): %s' % to_native(e), exception=traceback.format_exc())\n time.sleep(5)\n\n\ndef load_mongocnf():\n config = configparser.RawConfigParser()\n mongocnf = os.path.expanduser('~/.mongodb.cnf')\n\n try:\n config.readfp(open(mongocnf))\n creds = dict(\n user=config.get('client', 'user'),\n password=config.get('client', 'pass')\n )\n except (configparser.NoOptionError, IOError):\n return False\n\n return creds\n\n\ndef wait_for_ok_and_master(module, connection_params, timeout=180):\n start_time = dtdatetime.now()\n while True:\n try:\n client = MongoClient(**connection_params)\n authenticate(module, client, connection_params[\"username\"], connection_params[\"password\"])\n\n status = client.admin.command('replSetGetStatus', check=False)\n if status['ok'] == 1 and status['myState'] == 1:\n return\n\n except ServerSelectionTimeoutError:\n pass\n\n client.close()\n\n if (dtdatetime.now() - start_time).seconds > timeout:\n module.fail_json(msg='reached timeout while waiting for rs.status() to become ok=1')\n\n time.sleep(1)\n\n\ndef authenticate(module, client, login_user, login_password):\n if login_user is None and login_password is None:\n mongocnf_creds = load_mongocnf()\n if mongocnf_creds is not False:\n login_user = mongocnf_creds['user']\n login_password = mongocnf_creds['password']\n elif login_password is None and login_user is not None:\n module.fail_json(msg='when supplying login arguments, both login_user and login_password must be provided')\n\n if login_user is not None and login_password is not None:\n client.admin.authenticate(login_user, login_password)\n\n# =========================================\n# Module execution.\n#\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n login_user=dict(default=None),\n login_password=dict(default=None, no_log=True),\n login_host=dict(default='localhost'),\n login_port=dict(default='27017'),\n login_database=dict(default=\"admin\"),\n replica_set=dict(default=None),\n host_name=dict(default='localhost'),\n host_port=dict(default='27017'),\n host_type=dict(default='replica', choices=['replica', 'arbiter']),\n ssl=dict(default=False, type='bool'),\n ssl_cert_reqs=dict(default='CERT_REQUIRED', choices=['CERT_NONE', 'CERT_OPTIONAL', 'CERT_REQUIRED']),\n build_indexes=dict(type='bool', default='yes'),\n hidden=dict(type='bool', default='no'),\n priority=dict(default='1.0'),\n slave_delay=dict(type='int', default='0'),\n votes=dict(type='int', default='1'),\n state=dict(default='present', choices=['absent', 'present']),\n )\n )\n\n if not pymongo_found:\n module.fail_json(msg=missing_required_lib('pymongo'))\n\n login_user = module.params['login_user']\n login_password = module.params['login_password']\n login_host = module.params['login_host']\n login_port = module.params['login_port']\n login_database = module.params['login_database']\n replica_set = module.params['replica_set']\n host_name = module.params['host_name']\n host_port = module.params['host_port']\n host_type = module.params['host_type']\n ssl = module.params['ssl']\n state = module.params['state']\n priority = float(module.params['priority'])\n\n replica_set_created = False\n\n try:\n if replica_set is None:\n module.fail_json(msg='replica_set parameter is required')\n else:\n connection_params = {\n \"host\": login_host,\n \"port\": int(login_port),\n \"username\": login_user,\n \"password\": login_password,\n \"authsource\": login_database,\n \"serverselectiontimeoutms\": 5000,\n \"replicaset\": replica_set,\n }\n\n if ssl:\n connection_params[\"ssl\"] = ssl\n connection_params[\"ssl_cert_reqs\"] = getattr(ssl_lib, module.params['ssl_cert_reqs'])\n\n client = MongoClient(**connection_params)\n authenticate(module, client, login_user, login_password)\n client['admin'].command('replSetGetStatus')\n\n except ServerSelectionTimeoutError:\n try:\n connection_params = {\n \"host\": login_host,\n \"port\": int(login_port),\n \"username\": login_user,\n \"password\": login_password,\n \"authsource\": login_database,\n \"serverselectiontimeoutms\": 10000,\n }\n\n if ssl:\n connection_params[\"ssl\"] = ssl\n connection_params[\"ssl_cert_reqs\"] = getattr(ssl_lib, module.params['ssl_cert_reqs'])\n\n client = MongoClient(**connection_params)\n authenticate(module, client, login_user, login_password)\n if state == 'present':\n new_host = {'_id': 0, 'host': \"{0}:{1}\".format(host_name, host_port)}\n if priority != 1.0:\n new_host['priority'] = priority\n config = {'_id': \"{0}\".format(replica_set), 'members': [new_host]}\n client['admin'].command('replSetInitiate', config)\n client.close()\n wait_for_ok_and_master(module, connection_params)\n replica_set_created = True\n module.exit_json(changed=True, host_name=host_name, host_port=host_port, host_type=host_type)\n except OperationFailure as e:\n module.fail_json(msg='Unable to initiate replica set: %s' % to_native(e), exception=traceback.format_exc())\n except ConnectionFailure as e:\n module.fail_json(msg='unable to connect to database: %s' % to_native(e), exception=traceback.format_exc())\n\n # reconnect again\n client = MongoClient(**connection_params)\n authenticate(module, client, login_user, login_password)\n check_compatibility(module, client)\n check_members(state, module, client, host_name, host_port, host_type)\n\n if state == 'present':\n if host_name is None and not replica_set_created:\n module.fail_json(msg='host_name parameter required when adding new host into replica set')\n\n try:\n if not replica_set_created:\n add_host(module, client, host_name, host_port, host_type,\n build_indexes=module.params['build_indexes'],\n hidden=module.params['hidden'],\n priority=float(module.params['priority']),\n slave_delay=module.params['slave_delay'],\n votes=module.params['votes'])\n except OperationFailure as e:\n module.fail_json(msg='Unable to add new member to replica set: %s' % to_native(e), exception=traceback.format_exc())\n\n elif state == 'absent':\n try:\n remove_host(module, client, host_name)\n except OperationFailure as e:\n module.fail_json(msg='Unable to remove member of replica set: %s' % to_native(e), exception=traceback.format_exc())\n\n module.exit_json(changed=True, host_name=host_name, host_port=host_port, host_type=host_type)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6653908491134644, "alphanum_fraction": 0.6895333528518677, "avg_line_length": 32.62376403808594, "blob_id": "eb8d5b132fea306a716471accf9d416db0a9b389", "content_id": "08a7cac535336cd2a8b2f11688b7795ef9479842", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6793, "license_type": "permissive", "max_line_length": 148, "num_lines": 202, "path": "/ansible/roles/elasticsearch/test/integration/helpers/serverspec/xpack_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'spec_helper'\n\nshared_examples 'xpack::init' do |es_version,plugins|\n\n describe user('elasticsearch') do\n it { should exist }\n end\n\n describe service('security_node_elasticsearch') do\n it { should be_running }\n end\n\n describe package('elasticsearch') do\n it { should be_installed }\n end\n\n describe file('/etc/elasticsearch/security_node/elasticsearch.yml') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/security_node/log4j2.properties') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/security_node/elasticsearch.yml') do\n it { should contain 'node.name: localhost-security_node' }\n it { should contain 'cluster.name: elasticsearch' }\n it { should contain 'path.conf: /etc/elasticsearch/security_node' }\n it { should contain 'path.data: /var/lib/elasticsearch/localhost-security_node' }\n it { should contain 'path.logs: /var/log/elasticsearch/localhost-security_node' }\n end\n\n describe 'Node listening' do\n it 'listening in port 9200' do\n expect(port 9200).to be_listening\n end\n end\n\n describe 'version check' do\n it 'should be reported as version '+es_version do\n command = command('curl -s localhost:9200 -u es_admin:changeMeAgain | grep number')\n expect(command.stdout).to match(es_version)\n expect(command.exit_status).to eq(0)\n end\n end\n\n describe file('/etc/init.d/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/default/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/sysconfig/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/usr/lib/systemd/system/elasticsearch.service') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/elasticsearch.yml') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/logging.yml') do\n it { should_not exist }\n end\n\n #Xpack specific tests\n describe file('/usr/share/elasticsearch/plugins') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n #Test if x-pack is activated\n describe 'x-pack activation' do\n it 'should be activated and valid' do\n command = command('curl -s localhost:9200/_license?pretty=true -u es_admin:changeMeAgain')\n expect(command.stdout).to match('\"status\" : \"active\"')\n expect(command.exit_status).to eq(0)\n end\n end\n\n describe file('/usr/share/elasticsearch/plugins/x-pack') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe command('curl -s localhost:9200/_nodes/plugins?pretty=true -u es_admin:changeMeAgain | grep x-pack') do\n its(:exit_status) { should eq 0 }\n end\n\n describe file('/etc/elasticsearch/security_node/x-pack') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/usr/share/elasticsearch/plugins/x-pack') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n for plugin in plugins\n describe file('/usr/share/elasticsearch/plugins/'+plugin) do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe command('curl -s localhost:9200/_nodes/plugins -u es_admin:changeMeAgain | grep \\'\"name\":\"'+plugin+'\",\"version\":\"'+es_version+'\"\\'') do\n its(:exit_status) { should eq 0 }\n end\n end\n\n #Test users file, users_roles and roles.yml\n describe file('/etc/elasticsearch/security_node/x-pack/users_roles') do\n it { should be_owned_by 'elasticsearch' }\n it { should contain 'admin:es_admin' }\n it { should contain 'power_user:testUser' }\n end\n\n describe file('/etc/elasticsearch/security_node/x-pack/users') do\n it { should be_owned_by 'elasticsearch' }\n it { should contain 'testUser:' }\n it { should contain 'es_admin:' }\n end\n\n\n describe file('/etc/elasticsearch/security_node/x-pack/roles.yml') do\n it { should be_owned_by 'elasticsearch' }\n #Test contents as expected\n its(:md5sum) { should eq '7800182547287abd480c8b095bf26e9e' }\n end\n\n\n #Test native roles and users are loaded\n describe command('curl -s localhost:9200/_xpack/security/user -u es_admin:changeMeAgain | md5sum | grep 74bcc9f9534b253c1204e264df21496c') do\n its(:exit_status) { should eq 0 }\n end\n\n describe command('curl -s localhost:9200/_xpack/security/role -u es_admin:changeMeAgain | md5sum | grep 2bf3ffbb9cabf26bb25de6334c4da323') do\n its(:exit_status) { should eq 0 }\n end\n\n describe file('/etc/elasticsearch/templates') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/templates/basic.json') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe 'Template Installed' do\n it 'should be reported as being installed', :retry => 3, :retry_wait => 10 do\n command = command('curl -s \"localhost:9200/_template/basic\" -u es_admin:changeMeAgain')\n expect(command.stdout).to match(/basic/)\n expect(command.exit_status).to eq(0)\n end\n end\n\n #This is possibly subject to format changes in the response across versions so may fail in the future\n describe 'Template Contents Correct' do\n it 'should be reported as being installed', :retry => 3, :retry_wait => 10 do\n command = command('curl -s \"localhost:9200/_template/basic\" -u es_admin:changeMeAgain | md5sum')\n expect(command.stdout).to match(/153b1a45daf48ccee80395b85c61e332/)\n end\n end\n\n #Test contents of Elasticsearch.yml file\n describe file('/etc/elasticsearch/security_node/elasticsearch.yml') do\n it { should contain 'security.authc.realms.file1.order: 0' }\n it { should contain 'security.authc.realms.file1.type: file' }\n it { should contain 'security.authc.realms.native1.order: 1' }\n it { should contain 'security.authc.realms.native1.type: native' }\n end\n\n #Test contents of role_mapping.yml\n describe file('/etc/elasticsearch/security_node/x-pack/role_mapping.yml') do\n it { should be_owned_by 'elasticsearch' }\n it { should contain 'power_user:' }\n it { should contain '- cn=admins,dc=example,dc=com' }\n it { should contain 'user:' }\n it { should contain '- cn=admins,dc=example,dc=com' }\n end\n\n\n describe file('/etc/elasticsearch/security_node/x-pack/system_key') do\n it { should be_owned_by 'elasticsearch' }\n it { should be_writable.by('owner') }\n it { should be_writable.by_user('elasticsearch') }\n it { should be_readable.by('owner') }\n it { should be_readable.by_user('elasticsearch') }\n it { should_not be_executable }\n #Test contents as expected\n its(:md5sum) { should eq '6ff0e6c4380a6ac0f6e04d871c0ca5e8' }\n end\nend\n\n" }, { "alpha_fraction": 0.6333333253860474, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 14, "blob_id": "a8dfb4e3e4bfdd4bd4a15833ef52c7c0acd0250f", "content_id": "8e42060285daba94e1276ad9c03879748ff8f361", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 120, "license_type": "permissive", "max_line_length": 27, "num_lines": 8, "path": "/images/echo-server/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM python:2.7.13-alpine\n\nCOPY server.py server.py\n\nENV ECHO_SERVER_PORT 9595\nEXPOSE 9595\n\nCMD [\"python\", \"server.py\"]\n" }, { "alpha_fraction": 0.6972222328186035, "alphanum_fraction": 0.6977777481079102, "avg_line_length": 28.508195877075195, "blob_id": "d607b7f39ddc08e0a414267cd62e2c537f753043", "content_id": "b6f8f80fc2051fbf08670f0d320ad7c3b5e67f27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3600, "license_type": "permissive", "max_line_length": 105, "num_lines": 122, "path": "/kubernetes/opa-plugins/plugins/decisionlogs/decisionlogs.go", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "package decisionlogs\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/open-policy-agent/opa/plugins\"\n\t\"github.com/open-policy-agent/opa/plugins/logs\"\n\n\t\"github.com/golang-jwt/jwt\"\n\t\"github.com/open-policy-agent/opa/util\"\n\t\"github.com/tidwall/gjson\"\n\t\"github.com/tidwall/sjson\"\n)\n\nconst PluginName = \"print_decision_logs_on_failure\"\n\ntype Factory struct{}\n\nfunc (Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error) {\n\tcfg := Config{}\n\n\tif err := util.Unmarshal(config, &cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, util.Unmarshal(config, &cfg)\n}\n\nfunc (Factory) New(m *plugins.Manager, config interface{}) plugins.Plugin {\n\n\tm.UpdatePluginStatus(PluginName, &plugins.Status{State: plugins.StateNotReady})\n\n\treturn &PrintlnLogger{\n\t\tmanager: m,\n\t\tconfig: config.(Config),\n\t}\n}\n\ntype Config struct {\n\t// true => failed decision logs printed, false => failed decision logs are not printed\n\tStdout bool `json:\"stdout\"`\n}\n\ntype PrintlnLogger struct {\n\tmanager *plugins.Manager\n\tmtx sync.Mutex\n\tconfig Config\n}\n\nfunc (p *PrintlnLogger) Start(ctx context.Context) error {\n\tp.manager.UpdatePluginStatus(PluginName, &plugins.Status{State: plugins.StateOK})\n\treturn nil\n}\n\nfunc (p *PrintlnLogger) Stop(ctx context.Context) {\n\tp.manager.UpdatePluginStatus(PluginName, &plugins.Status{State: plugins.StateNotReady})\n}\n\nfunc (p *PrintlnLogger) Reconfigure(ctx context.Context, config interface{}) {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tp.config = config.(Config)\n}\n\nfunc (p *PrintlnLogger) Log(ctx context.Context, event logs.EventV1) error {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tw := os.Stdout\n\tif !p.config.Stdout {\n\t\tw = os.Stderr\n\t}\n\tbs, err := json.Marshal(event)\n\tif err != nil {\n\t\tp.manager.UpdatePluginStatus(PluginName, &plugins.Status{State: plugins.StateErr})\n\t\treturn nil\n\t}\n\tjson_log := string(bs)\n\tresult := gjson.Get(json_log, \"result.allowed\")\n\tbearer_token := gjson.Get(json_log, \"input.attributes.request.http.headers.authorization\")\n\tx_auth_token := gjson.Get(json_log, \"input.attributes.request.http.headers.x-authenticated-user-token\")\n\n\tjson_log, _ = sjson.Delete(json_log, \"input.attributes.request.http.headers.authorization\")\n\tjson_log, _ = sjson.Delete(json_log, \"input.attributes.request.http.headers.x-authenticated-user-token\")\n\tjson_log, _ = sjson.Delete(json_log, \"input.attributes.request.http.headers.x-auth-token\")\n\tjson_log, _ = sjson.Delete(json_log, \"input.attributes.request.http.headers.cookie\")\n\n\t// Print the decision logs only when result.allowed == false && Config.Stdout == true\n\tif !result.Bool() && p.config.Stdout {\n\t\tif bearer_token.Exists() {\n\t\t\ttoken := strings.Split(bearer_token.String(), \" \")[1]\n\t\t\tb_token, _ := jwt.Parse(token, nil)\n\t\t\tif b_token != nil {\n\t\t\t\tb_claims, _ := json.Marshal(b_token.Claims)\n\t\t\t\tb_header, _ := json.Marshal(b_token.Header)\n\t\t\t\tjson_log, _ = sjson.SetRaw(json_log, \"input.bearer_token_claims\", string(b_claims))\n\t\t\t\tjson_log, _ = sjson.SetRaw(json_log, \"input.bearer_token_header\", string(b_header))\n\t\t\t}\n\t\t}\n\n\t\tif x_auth_token.Exists() {\n\t\t\tx_token, _ := jwt.Parse(x_auth_token.String(), nil)\n\t\t\tif x_token != nil {\n\t\t\t\tx_claims, _ := json.Marshal(x_token.Claims)\n\t\t\t\tx_header, _ := json.Marshal(x_token.Header)\n\t\t\t\tjson_log, _ = sjson.SetRaw(json_log, \"input.x_auth_token_claims\", string(x_claims))\n\t\t\t\tjson_log, _ = sjson.SetRaw(json_log, \"input.x_auth_token_header\", string(x_header))\n\t\t\t}\n\t\t}\n\n\t\t_, err = fmt.Fprintln(w, json_log)\n\t}\n\n\tif err != nil {\n\t\tp.manager.UpdatePluginStatus(PluginName, &plugins.Status{State: plugins.StateErr})\n\t}\n\treturn nil\n}\n" }, { "alpha_fraction": 0.4891846776008606, "alphanum_fraction": 0.5069329142570496, "avg_line_length": 23.364864349365234, "blob_id": "976bc0cfbd0c266c1f93a299b38c996ba998a3c2", "content_id": "d597d4a881e64a506ec569d310f3e83e441405a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1803, "license_type": "permissive", "max_line_length": 148, "num_lines": 74, "path": "/exporters/Go/kafka-topic-exporter/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "## Design\n\nThis program is designed to be eventually consistent, metrics exporter.\n\n## What it does\n\nScrape a kafka topic for metrics of specific json format, and expose one endpoint for prometheus\n\n## How to run\n\n`docker run -e kafaka_host=11.1.1.11:9092 -e kafka_topic=metrics.topic.dev rjshrjndrn/kafka-topic-exporter:v1`\n\n## Json format\n\n```\n{\n\t\"system\": \"<category of the metrics, for example: samza>\",\n\t\"subsystem\": \"<producer of the metrics, for example: pipeline-metrics>\",\n\t\"metricts\": \"< timestamp of the merics, which should be passed to prometheus. This should be in epoch milliseconds>\", // This is an optional field\n\t\"metrics\": [\n\t\t{\n\t\t\t\"id\": \"<name of the metric>\", // It can contain alphabets and '-' and '_'. Should should start with alphabet\n\t\t\t\"value\": \"< value of the metric>\" // Should be of int or float64\n\t\t}\n\t\t{\n\t\t\t...\n\t\t\t...\n\t\t\t...\n\t\t}\n\t],\n\t\"dimensions\": [ // Labels which will get injectd to each of the above metrics\n\t\t{\n\t\t\t\"id\": \"< name of the label>\", // It can contain alphabets and '-' and '_'. Should should start with alphabet\n\t\t\t\"value\": < value of the label>\"\n\t\t}\n\t\t{\n\t\t\t...\n\t\t\t...\n\t\t\t...\n\t\t}\n\t]\n}\n```\n \nExample:\n```\n{\n \"system\": \"samza\",\n \"subsystem\": \"pipeline-metrics\",\n \"metricts\" : 1582521646464,\n \"metrics\": [\n {\n \"id\": \"success-message-count\",\n \"value\": 1\n },\n {\n \"id\": \"skipped-message-count\",\n \"value\": 1\n },\n {\n }\n ],\n \"dimensions\": [\n {\n \"id\": \"job-name\",\n \"value\": \"test-job\"\n },\n {\n \"id\": \"partition\",\n \"value\": 0\n }\n ]\n}\n```\n" }, { "alpha_fraction": 0.4787667393684387, "alphanum_fraction": 0.4898196756839752, "avg_line_length": 26.725807189941406, "blob_id": "97675fecbac40ae043903819a66e639ab81f3902", "content_id": "1eda8d728bc3b657258d7c63a1ca342fe08c0d2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1719, "license_type": "permissive", "max_line_length": 97, "num_lines": 62, "path": "/deploy/gitOPS/enableBranchProtection.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash -xv\nread -p \"Enter the github username: \" user\nread -sp \"Enter the password: \" pass\necho \" \"\nstatusChecks=0\nIFS=','\n#read input from a file\ngrep -v -e '#' -e \"^$\" github.csv | while read -ra LINE\ndo\n repo_name=\"${LINE[0]}\"\n branch_name=\"${LINE[1]}\"\n users=\"${LINE[2]}\"\n check=\"${LINE[3]}\"\nunset IFS\nUsers=\\\"$users\\\"\ngithubUsers=$(echo $Users | sed 's/;/\\\",\\\"/g')\necho \"------------------------------------------------------------------\"\necho -e '\\033[0;32m'$repo_name $branch_name $githubUsers $check'\\033[0m'\necho \"------------------------------------------------------------------\"\nIFS=','\nif [[ $check == \"1\" ]]; then\n statusChecks='\"Codacy/PR Quality Review\"'\nelif [[ $check == \"2\" ]]; then\n statusChecks='\"ci/circleci: build\"'\nelif [[ $check == \"3\" ]]; then\n statusChecks='\"Codacy/PR Quality Review\",\n \"ci/circleci: build\"'\nelse\n echo \"Provide correct value!\"\nfi\n\ncurl -u $user:$pass -XPUT \\\n -H 'Accept: application/vnd.github.luke-cage-preview+json' \\\n -d '{\n \"protection\": {\n \"enabled\": true\n },\n\n \"enforce_admins\": true,\n \"required_pull_request_reviews\": {\n \"dismiss_stale_reviews\": true,\n \"require_code_owner_reviews\": false,\n \"required_approving_review_count\": 1\n },\n\n \"required_status_checks\": {\n \"strict\": true,\n \"contexts\": [\n '\"$statusChecks\"'\n ]\n },\n \n \"restrictions\": {\n \"users\": [\n '\"$githubUsers\"'\n ],\n \"teams\": [\n \"null\"\n ]\n }\n }' \"https://api.github.com/repos/project-sunbird/$repo_name/branches/$branch_name/protection\"\ndone\n" }, { "alpha_fraction": 0.6294784545898438, "alphanum_fraction": 0.6355555653572083, "avg_line_length": 31.14285659790039, "blob_id": "dae5a95b3c63034a0599b4381a8e1a2dfeed4e72", "content_id": "9dc70a7b5e9b20130bd701d21623044840aec855", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 11025, "license_type": "permissive", "max_line_length": 192, "num_lines": 343, "path": "/ansible/roles/firebase_deploy/templates/uploadToGdrive.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Upload a file to Google Drive\n# Usage: upload.sh <file> <folder_name>\n\n#!/bin/bashset -e\nfunction usage(){\n\n\techo -e \"\\nThe script can be used to upload file/directory to google drive.\"\n\techo -e \"\\nUsage:\\n $0 [options..] <filename> <foldername> \\n\"\n\techo -e \"Foldername argument is optional. If not provided, the file will be uploaded to preconfigured google drive. \\n\"\n\techo -e \"File name argument is optional if create directory option is used. \\n\"\n\techo -e \"Options:\\n\"\n\techo -e \"-C | --create-dir <foldername> - option to create directory. Will provide folder id.\"\n\techo -e \"-r | --root-dir <google_folderid> - google folder id to which the file/directory to upload.\"\n\techo -e \"-v | --verbose - Display detailed message.\"\n\techo -e \"-z | --config - Override default config file with custom config file.\"\n\techo -e \"-h | --help - Display usage instructions.\\n\"\n\texit 0;\n}\n\nfile=${3}\n#Configuration variables\nROOT_FOLDER=\"\"\nCLIENT_ID={{mobile_gdrive_client_id}}\nCLIENT_SECRET={{mobile_gdrive_client_secret}}\nAPI_REFRESH_TOKEN={{mobile_gdrive_refresh_token}}\nFOLDER_ID={{mobile_release_gdrive_folder_id}}\nFILE_NAME=${3}\nSCOPE=${SCOPE:-\"https://docs.google.com/feeds\"}\n\necho \"FILE\"${3}\n#Internal variable\nACCESS_TOKEN=\"\"\nFILE=\"\"\nFOLDERNAME=\"\"\ncurl_args=\"\"\n\nDIR=\"$( cd \"$( dirname \"$( readlink \"${BASH_SOURCE[0]}\" )\" )\" && pwd )\"\n\nif [ -e $HOME/.googledrive.conf ]\nthen\n . $HOME/.googledrive.conf\nfi\n\nPROGNAME=${0##*/}\nSHORTOPTS=\"vhr:C:z:\"\nLONGOPTS=\"verbose,help,create-dir:,root-dir:,config:\"\n\nset -o errexit -o noclobber -o pipefail #-o nounset\nOPTS=$(getopt -s bash --options $SHORTOPTS --longoptions $LONGOPTS --name $PROGNAME -- \"$@\" )\n\n# script to parse the input arguments\n#if [ $? != 0 ] ; then echo \"Failed parsing options.\" >&2 ; exit 1 ; fi\n\neval set -- \"$OPTS\"\n\nVERBOSE=false\nHELP=false\nCONFIG=\"\"\nROOTDIR=\"\"\n\nwhile true; do\n case \"$1\" in\n -v | --verbose ) VERBOSE=true;curl_args=\"--progress\"; shift ;;\n -h | --help ) usage; shift ;;\n -C | --create-dir ) FOLDERNAME=\"$2\"; shift 2 ;;\n -r | --root-dir ) ROOTDIR=\"$2\";ROOT_FOLDER=\"$2\"; shift 2 ;;\n -z | --config ) CONFIG=\"$2\"; shift 2 ;;\n -- ) shift; break ;;\n * ) break ;;\n esac\ndone\n\nif [ ! -z \"$CONFIG\" ]\n\tthen\n\tif [ -e \"$CONFIG\" ]\n\tthen\n \t. $CONFIG\n\tfi\n\tif [ ! -z \"$ROOTDIR\" ]\n\t\tthen\n\t\tROOT_FOLDER=\"$ROOTDIR\"\n\tfi\n\nfi\n\nif [ ! -z \"$1\" ]\nthen\n\tFILE=$1\nfi\n\nif [ ! -z \"$2\" ] && [ -z \"$FOLDERNAME\" ]\nthen\n\tFOLDERNAME=$2\nfi\n\n\nfunction log() {\n\n\tif [ \"$VERBOSE\" = true ]; then\n\t\techo -e \"${1}\"\n\n\tfi\n}\n\n# Method to extract data from json response\nfunction jsonValue() {\nKEY=$1\nnum=$2\nawk -F\"[,:}][^://]\" '{for(i=1;i<=NF;i++){if($i~/\\042'$KEY'\\042/){print $(i+1)}}}' | tr -d '\"' | sed -n ${num}p | sed -e 's/[}]*$//' -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/[,]*$//'\n}\n# Method to upload files to google drive. Requires 3 arguments file path, google folder id and access token.\nfunction uploadFile(){\n\tFILE=\"$1\"\n\tFOLDER_ID=\"$2\"\n\tACCESS_TOKEN=\"$3\"\n\tSLUG=`basename \"$FILE\"`\n\tFILENAME=\"${SLUG%.*}\"\n\tEXTENSION=\"${SLUG##*.}\"\n\tif [ \"$FILENAME\" == \"$EXTENSION\" -o ! \"$(command -v mimetype)\" ]\n \tthen\n \t\tMIME_TYPE=`file --brief --mime-type \"$FILE\"`\n \telse\n MIME_TYPE=`mimetype --output-format %m \"$FILE\"`\n\n\tfi\n\n\n\tFILESIZE=$(stat -c%s \"$FILE\")\n\n\t# JSON post data to specify the file name and folder under while the file to be created\n\tpostData=\"{\\\"mimeType\\\": \\\"$MIME_TYPE\\\",\\\"title\\\": \\\"$SLUG\\\",\\\"parents\\\": [{\\\"id\\\": \\\"${FOLDER_ID}\\\"}]}\"\n\tpostDataSize=$(echo $postData | wc -c)\n\t# Curl command to initiate resumable upload session and grab the location URL\n\tlog \"Generating upload link for file $FILE ...\"\n\tuploadlink=`/usr/bin/curl \\\n\t\t\t\t--silent \\\n\t\t\t\t-X POST \\\n\t\t\t\t-H \"Host: www.googleapis.com\" \\\n\t\t\t\t-H \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n\t\t\t\t-H \"Content-Type: application/json; charset=UTF-8\" \\\n\t\t\t\t-H \"X-Upload-Content-Type: $MIME_TYPE\" \\\n\t\t\t\t-H \"X-Upload-Content-Length: $FILESIZE\" \\\n\t\t\t\t-d \"$postData\" \\\n\t\t\t\t\"https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&supportsAllDrives=true&supportsTeamDrives=true\" \\\n\t\t\t\t--dump-header - | sed -ne s/\"Location: \"//pi | tr -d '\\r\\n'`\n\n\t# Curl command to push the file to google drive.\n\t# If the file size is large then the content can be split to chunks and uploaded.\n\t# In that case content range needs to be specified.\n\tlog \"Uploading file $FILE to google drive...\"\n\tcurl \\\n\t--silent \\\n\t-X PUT \\\n\t-H \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n\t-H \"Content-Type: $MIME_TYPE\" \\\n\t-H \"Content-Length: $FILESIZE\" \\\n\t-H \"Slug: $SLUG\" \\\n\t--upload-file \"$FILE\" \\\n\t--output /dev/null \\\n\t\"$uploadlink\" \\\n\t$curl_args\n}\nif [ \"$#\" = \"0\" ] && [ -z \"$FOLDERNAME\" ]\n\tthen\n\t\techo \"CLIENT_ID\"${CLIENT_ID}\n\t\techo \"CLIENT_SECRET\"${CLIENT_SECRET}\n\t\techo \"API_REFRESH_TOKEN\"${API_REFRESH_TOKEN}\n\t\techo \"FILE\"${FILE_NAME}\n\t\tRESPONSE=`curl --silent \"https://accounts.google.com/o/oauth2/token\" --data \"client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&refresh_token=$API_REFRESH_TOKEN&grant_type=refresh_token\"`\n\t\tACCESS_TOKEN=`echo $RESPONSE | jsonValue access_token`\n\t\techo \"ACCESS_TOKEN\"${ACCESS_TOKEN}\n\t\tuploadFile \"${FILE_NAME}\" \"$FOLDER_ID\" \"$ACCESS_TOKEN\"\n\t\t# usage\nfi\n\n\n# Method to create directory in google drive. Requires 3 arguments foldername,root directory id and access token.\nfunction createDirectory(){\n\tDIRNAME=\"$1\"\n\tROOTDIR=\"$2\"\n\tACCESS_TOKEN=\"$3\"\n\tFOLDER_ID=\"\"\n QUERY=\"mimeType='application/vnd.google-apps.folder' and title='$DIRNAME'\"\n QUERY=$(echo $QUERY | sed -f ${DIR}/url_escape.sed)\n\n\tSEARCH_RESPONSE=`/usr/bin/curl \\\n\t\t\t\t\t--silent \\\n\t\t\t\t\t-XGET \\\n\t\t\t\t\t-H \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n\t\t\t\t\t \"https://www.googleapis.com/drive/v2/files/${ROOTDIR}/children?orderBy=title&q=${QUERY}&fields=items%2Fid\"`\n\n\tFOLDER_ID=`echo $SEARCH_RESPONSE | jsonValue id`\n\n\n\tif [ -z \"$FOLDER_ID\" ]\n\tthen\n\t\tCREATE_FOLDER_POST_DATA=\"{\\\"mimeType\\\": \\\"application/vnd.google-apps.folder\\\",\\\"title\\\": \\\"$DIRNAME\\\",\\\"parents\\\": [{\\\"id\\\": \\\"$ROOTDIR\\\"}]}\"\n\t\tCREATE_FOLDER_RESPONSE=`/usr/bin/curl \\\n\t\t\t\t\t\t\t\t--silent \\\n\t\t\t\t\t\t\t\t-X POST \\\n\t\t\t\t\t\t\t\t-H \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n\t\t\t\t\t\t\t\t-H \"Content-Type: application/json; charset=UTF-8\" \\\n\t\t\t\t\t\t\t\t-d \"$CREATE_FOLDER_POST_DATA\" \\\n\t\t\t\t\t\t\t\t\"https://www.googleapis.com/drive/v2/files?fields=id\"`\n\t\tFOLDER_ID=`echo $CREATE_FOLDER_RESPONSE | jsonValue id`\n\n\tfi\n}\n\n# Method to upload files to google drive. Requires 3 arguments file path, google folder id and access token.\n# function uploadFile(){\n# \tFILE=\"$1\"\n# \tFOLDER_ID=\"$2\"\n# \tACCESS_TOKEN=\"$3\"\n# \tSLUG=`basename \"$FILE\"`\n# \tFILENAME=\"${SLUG%.*}\"\n# \tEXTENSION=\"${SLUG##*.}\"\n# \tif [ \"$FILENAME\" == \"$EXTENSION\" -o ! \"$(command -v mimetype)\" ]\n# \tthen\n# \t\tMIME_TYPE=`file --brief --mime-type \"$FILE\"`\n# \telse\n# MIME_TYPE=`mimetype --output-format %m \"$FILE\"`\n#\n# \tfi\n#\n#\n# \tFILESIZE=$(stat -c%s \"$FILE\")\n#\n# \t# JSON post data to specify the file name and folder under while the file to be created\n# \tpostData=\"{\\\"mimeType\\\": \\\"$MIME_TYPE\\\",\\\"title\\\": \\\"$SLUG\\\",\\\"parents\\\": [{\\\"id\\\": \\\"${FOLDER_ID}\\\"}]}\"\n# \tpostDataSize=$(echo $postData | wc -c)\n# \t# Curl command to initiate resumable upload session and grab the location URL\n# \tlog \"Generating upload link for file $FILE ...\"\n# \tuploadlink=`/usr/bin/curl \\\n# \t\t\t\t--silent \\\n# \t\t\t\t-X POST \\\n# \t\t\t\t-H \"Host: www.googleapis.com\" \\\n# \t\t\t\t-H \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n# \t\t\t\t-H \"Content-Type: application/json; charset=UTF-8\" \\\n# \t\t\t\t-H \"X-Upload-Content-Type: $MIME_TYPE\" \\\n# \t\t\t\t-H \"X-Upload-Content-Length: $FILESIZE\" \\\n# \t\t\t\t-d \"$postData\" \\\n# \t\t\t\t\"https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&supportsAllDrives=true&supportsTeamDrives=true\" \\\n# \t\t\t\t--dump-header - | sed -ne s/\"Location: \"//pi | tr -d '\\r\\n'`\n#\n# \t# Curl command to push the file to google drive.\n# \t# If the file size is large then the content can be split to chunks and uploaded.\n# \t# In that case content range needs to be specified.\n# \tlog \"Uploading file $FILE to google drive...\"\n# \tcurl \\\n# \t--silent \\\n# \t-X PUT \\\n# \t-H \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n# \t-H \"Content-Type: $MIME_TYPE\" \\\n# \t-H \"Content-Length: $FILESIZE\" \\\n# \t-H \"Slug: $SLUG\" \\\n# \t--upload-file \"$FILE\" \\\n# \t--output /dev/null \\\n# \t\"$uploadlink\" \\\n# \t$curl_args\n# }\n\nold_umask=`umask`\numask 0077\n\nif [ -z \"$ROOT_FOLDER\" ]\nthen\n read -p \"Root Folder ID (Default: root): \" ROOT_FOLDER\n if [ -z \"$ROOT_FOLDER\" ] || [ `echo $ROOT_FOLDER | tr [:upper:] [:lower:]` = `echo \"root\" | tr [:upper:] [:lower:]` ]\n \tthen\n \t\tROOT_FOLDER=\"root\"\n \t\techo \"ROOT_FOLDER=$ROOT_FOLDER\" >> $HOME/.googledrive.conf\n \telse\n\t\t if expr \"$ROOT_FOLDER\" : '^[A-Za-z0-9_-]\\{28\\}$' > /dev/null\n\t\t then\n\t\t\t\techo \"ROOT_FOLDER=$ROOT_FOLDER\" >> $HOME/.googledrive.conf\n\t\t\telse\n\t\t\t\techo \"Invalid root folder id\"\n\t\t\t\texit -1\n\t\t\tfi\n\t\tfi\nfi\n\nif [ -z \"$CLIENT_ID\" ]\nthen\n read -p \"Client ID: \" CLIENT_ID\n echo \"CLIENT_ID=$CLIENT_ID\" >> $HOME/.googledrive.conf\nfi\n\nif [ -z \"$CLIENT_SECRET\" ]\nthen\n read -p \"Client Secret: \" CLIENT_SECRET\n echo \"CLIENT_SECRET=$CLIENT_SECRET\" >> $HOME/.googledrive.conf\nfi\n\nif [ -z \"$REFRESH_TOKEN\" ]\nthen\n RESPONSE=`curl --silent \"https://accounts.google.com/o/oauth2/device/code\" --data \"client_id=$CLIENT_ID&scope=$SCOPE\"`\n\tDEVICE_CODE=`echo \"$RESPONSE\" | jsonValue \"device_code\"`\n\tUSER_CODE=`echo \"$RESPONSE\" | jsonValue \"user_code\"`\n\tURL=`echo \"$RESPONSE\" | jsonValue \"verification_url\"`\n\n\tRESPONSE=`curl --silent \"https://accounts.google.com/o/oauth2/token\" --data \"client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&refresh_token=$API_REFRESH_TOKEN&grant_type=refresh_token\"`\n\tACCESS_TOKEN=`echo \"$RESPONSE\" | jsonValue access_token`\nfi\n\nif [ -z \"$ACCESS_TOKEN\" ]\n\tthen\n\t# Access token generation\n\tRESPONSE=`curl --silent \"https://accounts.google.com/o/oauth2/token\" --data \"client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&refresh_token=$REFRESH_TOKEN&grant_type=refresh_token\"`\n\tACCESS_TOKEN=`echo $RESPONSE | jsonValue access_token`\nfi\n\n# Check to find whether the folder exists in google drive. If not then the folder is created in google drive under the configured root folder\nif [ -z \"$FOLDERNAME\" ] || [[ `echo \"$FOLDERNAME\" | tr [:upper:] [:lower:]` = `echo \"root\" | tr [:upper:] [:lower:]` ]]\n\tthen\n\tif [[ `echo \"$FOLDERNAME\" | tr [:upper:] [:lower:]` = `echo \"root\" | tr [:upper:] [:lower:]` ]]\n\tthen\n\t\tROOT_FOLDER=\"root\"\n\tfi\n FOLDER_ID=$ROOT_FOLDER\nelse\n\tFOLDER_ID=`createDirectory \"$FOLDERNAME\" \"$ROOT_FOLDER\" \"$ACCESS_TOKEN\"`\n\nfi\n\tlog \"Folder ID for folder name $FOLDERNAME : $FOLDER_ID\"\n\n# Check whether the given file argument is valid and check whether the argument is file or directory.\n# based on the type, if the argument is directory do a recursive upload.\nif [ ! -z \"$FILE\" ]; then\n\tif [ -f \"$FILE\" ];then\n\t\tuploadFile \"$FILE\" \"$FOLDER_ID\" \"$ACCESS_TOKEN\"\n\telif [ -d \"$FILE\" ];then\n\t\t\tFOLDERNAME=$(basename $FILE)\n\t\t\tFOLDER_ID=`createDirectory \"$FOLDERNAME\" \"$ROOT_FOLDER\" \"$ACCESS_TOKEN\"`\n\t\t\tfor file in $(find \"$FILE\" -type f);\n\t\t\tdo\n\t\t\t\tuploadFile \"$file\" \"$FOLDER_ID\" \"$ACCESS_TOKEN\"\n\t\t\tdone\n\tfi\nfi\n" }, { "alpha_fraction": 0.6796116232872009, "alphanum_fraction": 0.6873786449432373, "avg_line_length": 23.5238094329834, "blob_id": "df90a92659f6a3e4758a0b2aaf009e0ac2951a5f", "content_id": "fc3a70f0a30acd4ccab7f6bf4261db2547b46a1f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 515, "license_type": "permissive", "max_line_length": 78, "num_lines": 21, "path": "/ansible/roles/cassandra-cql-update/templates/content_service.cql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "{% if (cassandra_cluster_size | int) > 1 %}\nCREATE KEYSPACE portal\nWITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 2 };\nUSE portal;\nCREATE TABLE IF NOT EXISTS sessions (\n sid text,\n session text,\n expires timestamp,\n PRIMARY KEY(sid)\n);\n{% else %}\nCREATE KEYSPACE portal\nWITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};\nUSE portal;\nCREATE TABLE IF NOT EXISTS sessions (\n sid text,\n session text,\n expires timestamp,\n PRIMARY KEY(sid)\n);\n{% endif %}\n" }, { "alpha_fraction": 0.5206929445266724, "alphanum_fraction": 0.5283926725387573, "avg_line_length": 34.82758712768555, "blob_id": "09e6b290ac3aeccebc09430076990315d6d7433c", "content_id": "487689d7679d1445344a09a0edb772dd4d8f6456", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1039, "license_type": "permissive", "max_line_length": 100, "num_lines": 29, "path": "/deploy/utilities/cassandra_row_counter.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n \nimport os\nfrom subprocess import check_output, STDOUT\nfrom re import match, DOTALL, compile\n \nroot_dir = '/var/lib/cassandra/data'\nlog_file = os.path.expanduser(\"~\")+'/cassandra_row_count.txt'\nos.chdir(root_dir)\nignore_list = compile(r'(system|system|systemtauth|system_traces|system_schema|system_distributed)')\n \nwith open(log_file,'a') as cf:\n for i in os.listdir(root_dir):\n if match(ignore_list, i):\n continue\n try:\n for j in os.listdir(i):\n ks = i+'.'+str(j.split('-')[0])\n val = 'cqlsh --request-timeout=36000 -e \"select count(*) from {};\"'.format(ks)\n try:\n out = check_output([\"/bin/bash\",\"-c\",val], stderr=STDOUT)\n except Exception as e:\n print(e)\n pass\n tmp = ks+' : '+match(r'.+\\s(\\d+).+', str(out), DOTALL).group(1)\n cf.write(tmp+'\\n')\n print(tmp)\n except Exception as e:\n print(e)\n" }, { "alpha_fraction": 0.7542768120765686, "alphanum_fraction": 0.7542768120765686, "avg_line_length": 36.82352828979492, "blob_id": "ddbfcac022ff2688463cb08dbf7f75f3fd602130", "content_id": "4701439fb4b42b6182a42ff5fb1266a8bf74093d", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 643, "license_type": "permissive", "max_line_length": 116, "num_lines": 17, "path": "/ansible/roles/postgres-migration/files/sunbird_programs/V4.6.0.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "CREATE TYPE formstatus AS ENUM ('Active', 'Inactive');\nCREATE TABLE public.formdata (\n id character varying NOT NULL,\n channel character varying,\n objecttype character varying,\n primarycategory character varying,\n context character varying,\n context_type character varying,\n operation character varying,\n data jsonb,\n status public.formstatus,\n createdon timestamp without time zone,\n updatedon timestamp without time zone,\n createdby character varying,\n updatedby character varying,\n CONSTRAINT unique_form_data PRIMARY KEY (channel, objecttype, primarycategory, context, context_type, operation)\n);\n" }, { "alpha_fraction": 0.6474452614784241, "alphanum_fraction": 0.7021898031234741, "avg_line_length": 32.414634704589844, "blob_id": "1567a612cd4ab5fd93665eea3edfa8117b1fc482", "content_id": "2cd473ac7a30f4df6e520bde6de9c6ffae7d4d10", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1370, "license_type": "permissive", "max_line_length": 76, "num_lines": 41, "path": "/deploy/jenkins/jenkins-slave-setup.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nbold=$(tput bold)\nnormal=$(tput sgr0)\n\necho -e \"\\n\\e[0;32m${bold}Updating the apt repo${normal}\\n\"\napt-get update\n\necho -e \"\\n\\e[0;32m${bold}Installating JDK8${normal}\\n\"\napt-get install -y openjdk-8-jdk\n\necho -e \"\\n\\e[0;32m${bold}Installating PIP${normal}\"\napt-get install -y python-pip\n\necho -e \"\\n\\e[0;32m${bold}Installating Git ${normal}\"\napt-get install -y git\n\necho -e \"\\n\\e[0;32m${bold}Installating zip unzip${normal}\"\napt-get install -y unzip zip\n\necho -e \"\\n\\e[0;32m${bold}Installating JQ${normal}\"\napt-get install -y jq\n\necho -e \"\\n\\e[0;32m${bold}Installating node and npm modules\"\nwget https://nodejs.org/download/release/v6.1.0/node-v6.1.0-linux-x64.tar.gz\ntar -xvf node-v6.1.0-linux-x64.tar.gz\nmv node-v6.1.0-linux-x64 /usr/local/lib/\nln -s /usr/local/lib/node-v6.1.0-linux-x64/bin/node /usr/bin/node\nln -s /usr/local/lib/node-v6.1.0-linux-x64/bin/npm /usr/bin/npm\nnpm install -g [email protected]\nln -s /usr/local/lib/node-v6.1.0-linux-x64/bin/gulp /usr/bin/gulp\n\necho -e \"\\n\\e[0;32m${bold}Installating Ansible${normal}\"\npip install ansible==2.5.0\n\necho -e \"\\n\\e[0;32m${bold}Installating Docker-py${normal}\"\npip install docker-py\n\necho -e \"\\n\\e[0;32m${bold}Adding jenkins user to docker group${normal}\"\nuseradd -m -d /var/lib/jenkins -s /bin/bash -c \"Jenkins user\" -U jenkins\n\necho -e \"\\n\\e[0;32m${bold}Jenkins slave installation complete..${normal}\"\n" }, { "alpha_fraction": 0.7384615540504456, "alphanum_fraction": 0.7589743733406067, "avg_line_length": 47.75, "blob_id": "32457fe0ba70517c122bfb79addd0c0cf908025e", "content_id": "cdb71433defb2bc5cc26c691ed47cf62ea1f4eae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 195, "license_type": "permissive", "max_line_length": 142, "num_lines": 4, "path": "/ansible/roles/ml-analytics-service/files/faust.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nexport LANG=C.UTF-8\nexport LC_ALL=C.UTF-8\n/opt/sparkjobs/spark_venv/bin/python /opt/sparkjobs/ml-analytics-service/$1.py --workdir /opt/sparkjobs/ml-analytics-service/$2 worker -l info\n" }, { "alpha_fraction": 0.6750348806381226, "alphanum_fraction": 0.6899116635322571, "avg_line_length": 37.41071319580078, "blob_id": "2b22c86594d9b294b1588eaaabb0b5685ab2ea4f", "content_id": "06418c0315b2fe98bf177ce3a2c0aa297a0b291e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2151, "license_type": "permissive", "max_line_length": 248, "num_lines": 56, "path": "/deploy/deploy-apis.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory-path>\"\n exit 1\nfi\n\nINVENTORY_PATH=$1\n# Importing variables\nsource version.env\n\nORG=sunbird\nECHO_SERVER_VERSION=0.0.2-silver\nADMIN_UTILS_VERSION=0.0.1-SNAPSHOT-gold\n\n\n# Bootstrap swarm\necho \"@@@@@@@@@ Bootstrap swarm\"\nansible-playbook -i $INVENTORY_PATH ../ansible/bootstrap.yml --extra-vars \"hosts=swarm-manager\" --tags bootstrap_swarm [email protected]\n\n# Deploy API Manager\necho \"@@@@@@@@@ Deploy API Manager\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy.yml --tags \"stack-api-manager\" --extra-vars \"hub_org=${ORG} echo_server_image_name=echo-server echo_server_image_tag=${ECHO_SERVER_VERSION} kong_version=${KONG_VERSION}\" [email protected]\n\nsleep 20\n\n# Deploy Admin Utils API\necho \"@@@@@@@@@ Deploy Admin Utils API\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy.yml --tags \"stack-adminutil\" --extra-vars \"hub_org=${ORG} image_name=adminutil image_tag=${ADMIN_UTILS_VERSION}\" [email protected]\n\nsleep 10\n\n# Saving kong api url\nkong_admin_api_url=$(sudo docker service ps api-manager_kong | grep Runn | head -n1 | awk '{print $4}')\necho $kong_admin_api_url\nretry_count=5\nwhile [[ $kong_admin_api_url = '' && retry_count -ge 0 ]]; do\n kong_admin_api_url=$(sudo docker service ps api-manager_kong | grep Runn | head -n1 | awk '{print $4}')\n echo \"api-manager kong container is not running, waiting for 5 more seconds, retying $retry_count\"\n sleep 5\n ((retry_count--))\n if [[ $kong_admin_api_url = '' ]] && [[ retry_count -eq 0 ]];then \n echo \"api manger kong is not running, exiting script\"\n exit 1\n fi\ndone\n\n# Onboard APIs\necho \"@@@@@@@@@ Onboard APIs\"\nansible-playbook -i $INVENTORY_PATH ../ansible/api-manager.yml --tags kong-api --extra-vars kong_admin_api_url=http://$kong_admin_api_url:8001 [email protected]\n\n# Onboard Consumers\necho \"@@@@@@@@@ Onboard Consumers\"\nansible-playbook -v -i $INVENTORY_PATH ../ansible/api-manager.yml --tags kong-consumer --extra-vars kong_admin_api_url=http://$kong_admin_api_url:8001 [email protected]\n" }, { "alpha_fraction": 0.7084870934486389, "alphanum_fraction": 0.723247230052948, "avg_line_length": 44.16666793823242, "blob_id": "fd99466c0d0a98d45b8e21ca47acae9b234bc0a2", "content_id": "f3d6c24e7a943ea66fd4877b34cdf850b5d6d802", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 271, "license_type": "permissive", "max_line_length": 93, "num_lines": 6, "path": "/images/kafka-topic-exporter/build.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# vim: set ts=4 sw=4 tw=0 et :\n#!/bin/bash\n\n# Have to copy this file because In docker container we can't pass directories other than PWD\ncp ../../exporters/Go/kafka-topic-exporter/{main.go,go.mod,go.sum} .\ndocker build -f Dockerfile -t sunbird/kafka-topic-exporter:v3 .\n" }, { "alpha_fraction": 0.5558324456214905, "alphanum_fraction": 0.5714063048362732, "avg_line_length": 33.15425491333008, "blob_id": "e1030d825565b876f417c0ae5b19cc74375c9389", "content_id": "009bb75c1f89202c65ecb6c5dd2e63ed29140888", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 6421, "license_type": "permissive", "max_line_length": 160, "num_lines": 188, "path": "/deploy/postInstallation.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# AUTHOR: S M Y ALTAMASH <[email protected]>\n \nssh_key=$1\nssh_user=$2\nprotocol=$3\nserverIP=$4\nServiceLogsFolder=logs/service_logs/\nconfig_dir=.sunbird\necho \"---------------------------------------------------------------------------------\"\necho \"Checking Databases:-\"\necho \"\"\n\n# Sourcing the variables\nsource $config_dir/generate_host.sh &> /dev/null\n\nif [ ! -z $ssh_key ];then\n # Refreshing ssh-agent\n eval $(ssh-agent) &> /dev/null\n # Adding key to ssh-agent\n ssh-add $ssh_key &> /dev/null\nfi\n\nif [ -d .sunbird/ignore ]; then mkdir -p .sunbird/ignore; fi\nrm -rf .sunbird/ignore/*\n\nnssh() {\n ssh -o \"UserKnownHostsFile /dev/null\" -o \"StrictHostKeyChecking false\" -o \"LogLevel ERROR\" $@\n return $?\n}\n\ncheck_es() {\n ips $1\n ip=${arr[0]}\n\tlocal outpt=$(nssh $ssh_user@$ip \"sudo netstat -ntpl | grep 9200 | awk 'NR==1{print $4}' | cut -d \\\":\\\" -f2\" )\n\tlocal outpt1=$(curl -XGET -s \"$ip:9200/_cluster/health\" | jq \".status\")\n\tlocal outpt2=$(curl -XGET -s \"$ip:9200\" | jq \".version.number\")\n\tif [ \"$outpt1\" == \"\\\"green\\\"\" ] || [ \"$outpt1\" == \"\\\"yellow\\\"\" ] && [ \"$outpt\" -eq 9200 ];then\n \techo \"ELASTICSEARCH cluster is healthy\"\n\t\techo -e \"The Version of Elasticsearch being used is \\\"$outpt2\\\"\\n\"\n\telse\n\t\techo -e \"ELASTICSEARCH cluster is unhealthy\\n\"\n fi\n}\n\n\ncheck_postgres() {\n ips $1\n for ip in ${arr[@]}; do\n local outpt2=$(nssh $ssh_user@$ip \"ps -ef | grep postgres | wc -l\" )\n\tlocal outpt4=$(nssh $ssh_user@$ip \"/usr/lib/postgresql/9.5/bin/postgres --version\")\n local outpt3=$(nc -z $ip 5432; echo $? ) \n\tif [ \"$outpt2\" -gt 1 ] && [ \"$outpt3\" -eq 0 ];then\n echo \"POSTGRES is working in $ip\"\n else\n echo \"POSTGRES is Not Working in $ip\"\n fi\n echo \"The Postgres version which is being used is \\\"$outpt4\\\"\"\n done\n echo -e \"\\n\"\n}\n\ncheck_cassandra() {\n ips $1\n for ip in ${arr[@]}; do\n local outpt4=$(nssh $ssh_user@$ip \"ps -ef | grep cassandra | wc -l\" )\n local outpt5=$(nc -z $ip 9042; echo $? )\n local outpt6=$(nssh $ssh_user@$ip \"cqlsh --version\")\n\tif [ \"$outpt4\" -gt 1 ] && [ \"$outpt5\" -eq 0 ];then\n echo \"CASSANDRA is working in $ip\"\n else\n echo \"CASSANDRA is Not Working in $ip\"\n fi\n done\n echo -e \"The Cassandra version being used is \\\"$outpt6\\\" \\n\"\n}\n\ncheck_es_indices() {\n echo \"-----------------------------------------\"\n echo -e \"Checking The Ealstic Search Indices:-\\n\"\n ips $1\n flag=0\n ip=${arr[0]}\n local outpt1=$(curl -XGET -s \"$ip:9200/_cat/indices\" | awk '{print $3}')\n if [ \"$outpt1\" == \"searchindex\" ];then\n echo \"OK: ELASTICSEARCH indices exists\"\n else\n echo \"WARNING: ELASTICSEARCH indices does NOT EXISTS\"\n fi\n echo \"-----------------------------------------\"\n}\n\ncheck_postgres_databases() {\n ips $1\n\techo \"-----------------------------------------\"\n echo -e \"Checking Postgres Databases:-\\n\"\n ip=${arr[0]}\n\tlocal outpt2=$(nssh $ssh_user@$ip 'sudo su postgres bash -c \"psql -c \\\"SELECT datname FROM pg_database;\\\"\"' | awk 'NR>2' | head -n -2 | tr \"\\n\" \" \")\n\tdbNames=(\"api_manager\" \"keycloak\" \"quartz\" \"badger\")\n flag=0\n for db in ${dbNames[@]}; do\n echo $outpt2 | grep $db &>/dev/null\n if [ $? -eq 1 ]; then\n echo \"$db Database doesn't exist in Postgres\"\n flag=1\n fi\n done\n\n if [ $flag -eq 0 ]; then\n echo \"All the Databases Exists which are necessary for sunbird\"\n fi\n\techo \"-----------------------------------------\"\n}\n\ncheck_cassandra_keyspaces() {\n ips $1\n echo \"-----------------------------------------\"\n echo -e \"Checking Cassandra Keyspaces:-\\n\"\n ip=${arr[0]}\n local outpt=$(nssh $ssh_user@$ip '/usr/bin/cqlsh -e \"DESCRIBE KEYSPACES\"' | awk 'NR>1' | tr \"\\n\" \" \" | sed 's/ */ /g')\n existingKeyspaces=(\"dialcodes\" \"system_auth\" \"sunbirdplugin\" \"sunbird portal\")\n flag=0\n for db in ${existingKeyspaces[@]}; do\n\techo $outpt | grep $db &>/dev/null\n\tif [ $? -eq 1 ]; then\n\t\techo \"$db Keyspace doesn't exist in Cassandra\"\n\t\tflag=1\n\tfi\n done\n if [ $flag -eq 0 ]; then\n\t\techo \"All the Keyspaces Exists which are necessary for sunbird\"\n\tfi\n echo \"-----------------------------------------\"\n}\n\ncheck_version() {\n\tlist=(actor-service player_player learner-service content-service proxy_proxy api-manager_kong)\n\tversionReq=$(git branch | grep \\* | cut -d '-' -f2)\n\techo -e \"The Sunbird Version being used is $versionReq \\n\"\n\tif [ $(git branch | grep \\* | cut -d '-' -f2 | grep -Ewo '.' | wc -l) -ne 3 ]; then\n\t\tversionReq=\"${versionReq}.0\"\n\tfi\n for service in ${list[@]}; do\n\t versionGot=$( sudo docker service ls | grep $service | awk '{ print $5 }' | cut -d ':' -f2 | cut -d '-' -f1)\n if [ \"$versionReq\" == \"$versionGot\" ]; then\n\t\techo \"OK: $service Version is as per the Latest Release\"\n\t else\n\t echo \"WARNING: $service Version is NOT as per the latest release,the version obtained is $versionGot\"\n\t fi\n\tdone\n\n}\n\nget_logs() {\n\tmkdir -p $ServiceLogsFolder\n\techo \"Storing logs of core services in $ServiceLogsFolder\"\n\techo \"-----------------------------------------\"\n\tserviceNames=(player_player learner-service content-service proxy_proxy api-manager_kong)\n\tfor service in ${serviceNames[@]}; do\n\t\techo -e \"\\nexporting $service logs to $ServiceLogsFolder\"\n\t\tsudo docker service logs $service --tail 10000 > $ServiceLogsFolder/$service\n\tdone\n}\n\ncheck_service_health() {\n\techo \"-----------------------------------------\"\n echo \"Checking Service Health:-\"\n echo \"\"\n proxyServerID=$(getent hosts $(sudo docker service ps proxy_proxy | grep Running | awk '{print $4}') | awk '{print $1}')\n echo \"Proxy server IP is $proxyServerID\"\n ansible-playbook -i \"$proxyServerID,\" ../ansible/servicehealth.yml --extra-vars \"ansible_ssh_private_key_file=$ssh_key ansible_ssh_username=$ssh_user\" \n}\n\ncheck_es $elasticsearch_ips\npostgres_ips=$postgres_master_ips,$postgres_slave_ips\ncheck_postgres $postgres_ips\ncheck_cassandra $cassandra_ips\npython3 statusChecks.py $protocol $serverIP\ncheck_version\ncheck_es_indices $elasticsearch_ips\ncheck_postgres_databases $postgres_master_ips\ncheck_cassandra_keyspaces $cassandra_ips\nget_logs\ncheck_service_health\n\n#Zipping Logs to send it via email\nsudo apt-get install zip -y\nzip -r logs logs/*\n" }, { "alpha_fraction": 0.6548672318458557, "alphanum_fraction": 0.6902654767036438, "avg_line_length": 17.33333396911621, "blob_id": "0f2bd532a175fd3ea14621a914973286dd2b64d9", "content_id": "22b0976224e1bdee993c51e7c7d424a61c248944", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 113, "license_type": "permissive", "max_line_length": 44, "num_lines": 6, "path": "/ansible/roles/elasticsearch/test/integration/standard-5x/serverspec/default_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'standard_spec'\n\n\ndescribe 'Standard Tests v 5.x' do\n include_examples 'standard::init', \"5.2.2\"\nend\n\n\n\n" }, { "alpha_fraction": 0.4520833194255829, "alphanum_fraction": 0.4749999940395355, "avg_line_length": 35.92307662963867, "blob_id": "43ee319f2155c07ceafa1807432825c0744368d4", "content_id": "caffb6a1a4482ef1beecff588ff46c7d5729360f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 480, "license_type": "permissive", "max_line_length": 112, "num_lines": 13, "path": "/deploy/gitOPS/getBranches.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nread -p \"Enter Github Username: \" user\nread -sp \"Enter Github Password: \" pass\necho \" \"\nIFS=','\ngrep -v -e '#' -e \"^$\" github.csv | while read -ra LINE\ndo\n repo_name=\"${LINE[0]}\"\n echo \"----------------------------------------------------\"\n echo -e '\\033[0;32m'$repo_name'\\033[0m'\n echo \"----------------------------------------------------\"\n curl -u $user:$pass -s -N https://api.github.com/repos/project-sunbird/$repo_name/branches | jq '.[].name' -r\ndone\n" }, { "alpha_fraction": 0.6436781883239746, "alphanum_fraction": 0.6590038537979126, "avg_line_length": 19.076923370361328, "blob_id": "c14029cc2caea80399c5622d808e3cc6271bef26", "content_id": "3c59fddfc36e314953e858af600b7183c5d2b476", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 261, "license_type": "permissive", "max_line_length": 83, "num_lines": 13, "path": "/deploy/deploy-logger.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory-path>\"\n exit 1\nfi\n\nINVENTORY_PATH=$1\n\n#Deploy logger \nansible-playbook -i $INVENTORY_PATH ../ansible/logging.yml --extra-vars @config.yml\n" }, { "alpha_fraction": 0.6553129553794861, "alphanum_fraction": 0.6577875018119812, "avg_line_length": 31.714284896850586, "blob_id": "76c316ee58379d2f38dceb0c20da4f1e37b62785", "content_id": "c6b0940b0800fa091d58eaf2ac1b1103ae460878", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6870, "license_type": "permissive", "max_line_length": 160, "num_lines": 210, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "[![Documentation Status](https://readthedocs.org/projects/python-keycloak/badge/?version=latest)](http://python-keycloak.readthedocs.io/en/latest/?badge=latest)\n\nPython Keycloak\n====================\n\nFor review- see https://bitbucket.org/agriness/python-keycloak\n\n**python-keycloak** is a Python package providing access to the Keycloak API.\n\n## Installation\n\n### Via Pypi Package:\n\n``` $ pip install python-keycloak ```\n\n### Manually\n\n``` $ python setup.py install ```\n\n## Dependencies\n\npython-keycloak depends on:\n\n* Python 3\n* [requests](http://docs.python-requests.org/en/master/)\n* [python-jose](http://python-jose.readthedocs.io/en/latest/)\n\n### Tests Dependencies\n\n* unittest\n* [httmock](https://github.com/patrys/httmock)\n\n## Bug reports\n\nPlease report bugs and feature requests at\nhttps://bitbucket.org/agriness/python-keycloak/issues\n\n## Documentation\n\nThe documentation for python-keycloak is available on [readthedocs](http://python-keycloak.readthedocs.io).\n\n## Contributors\n\n* [Agriness Team](http://www.agriness.com/pt/)\n* [Marcos Pereira]([email protected])\n* [Martin Devlin]([email protected]) \n* [Shon T. Urbas]([email protected]>)\n\n## Usage\n\n```python\nfrom keycloak import KeycloakOpenID\n\n# Configure client\nkeycloak_openid = KeycloakOpenID(server_url=\"http://localhost:8080/auth/\",\n client_id=\"example_client\",\n realm_name=\"example_realm\",\n client_secret_key=\"secret\")\n\n# Get WellKnow\nconfig_well_know = keycloak_openid.well_know()\n\n# Get Token\ntoken = keycloak_openid.token(\"user\", \"password\")\n\n# Get Userinfo\nuserinfo = keycloak_openid.userinfo(token['access_token'])\n\n# Refresh token\ntoken = keycloak_openid.refresh_token(token['refresh_token'])\n\n# Logout\nkeycloak_openid.logout(token['refresh_token'])\n\n# Get Certs\ncerts = keycloak_openid.certs()\n\n# Get RPT (Entitlement)\ntoken = keycloak_openid.token(\"user\", \"password\")\nrpt = keycloak_openid.entitlement(token['access_token'], \"resource_id\")\n\n# Instropect RPT\ntoken_rpt_info = keycloak_openid.introspect(keycloak_openid.introspect(token['access_token'], rpt=rpt['rpt'],\n token_type_hint=\"requesting_party_token\"))\n\n# Introspect Token\ntoken_info = keycloak_openid.introspect(token['access_token']))\n\n# Decode Token\nKEYCLOAK_PUBLIC_KEY = \"secret\"\noptions = {\"verify_signature\": True, \"verify_aud\": True, \"exp\": True}\ntoken_info = keycloak_openid.decode_token(token['access_token'], key=KEYCLOAK_PUBLIC_KEY, options=options)\n\n# Get permissions by token\ntoken = keycloak_openid.token(\"user\", \"password\")\nkeycloak_openid.load_authorization_config(\"example-authz-config.json\")\npolicies = keycloak_openid.get_policies(token['access_token'], method_token_info='decode', key=KEYCLOAK_PUBLIC_KEY)\npermissions = keycloak_openid.get_permissions(token['access_token'], method_token_info='introspect')\n\n# KEYCLOAK ADMIN\n\nfrom keycloak import KeycloakAdmin\n\nkeycloak_admin = KeycloakAdmin(server_url=\"http://localhost:8080/auth/\",\n username='example-admin',\n password='secret',\n realm_name=\"example_realm\",\n verify=True)\n \n# Add user \nnew_user = keycloak_admin.create_user({\"email\": \"[email protected]\",\n \"username\": \"[email protected]\",\n \"enabled\": True,\n \"firstName\": \"Example\",\n \"lastName\": \"Example\",\n \"realmRoles\": [\"user_default\", ],\n \"attributes\": {\"example\": \"1,2,3,3,\"}}) \n \n \n# Add user and set password\nnew_user = keycloak_admin.create_user({\"email\": \"[email protected]\",\n \"username\": \"[email protected]\",\n \"enabled\": True,\n \"firstName\": \"Example\",\n \"lastName\": \"Example\",\n \"credentials\": [{\"value\": \"secret\",\"type\": \"password\",}],\n \"realmRoles\": [\"user_default\", ],\n \"attributes\": {\"example\": \"1,2,3,3,\"}}) \n\n# User counter\ncount_users = keycloak_admin.users_count()\n\n# Get users Returns a list of users, filtered according to query parameters\nusers = keycloak_admin.get_users({})\n\n# Get user ID from name\nuser-id-keycloak = keycloak_admin.get_user_id(\"[email protected]\")\n\n# Get User\nuser = keycloak_admin.get_user(\"user-id-keycloak\")\n\n# Update User\nresponse = keycloak_admin.update_user(user_id=\"user-id-keycloak\", \n payload={'firstName': 'Example Update'})\n\n# Update User Password\nresponse = set_user_password(user_id=\"user-id-keycloak\", password=\"secret\", temporary=True)\n \n# Delete User\nresponse = keycloak_admin.delete_user(user_id=\"user-id-keycloak\")\n\n# Get consents granted by the user\nconsents = keycloak_admin.consents_user(user_id=\"user-id-keycloak\")\n\n# Send User Action\nresponse = keycloak_admin.send_update_account(user_id=\"user-id-keycloak\", \n payload=json.dumps(['UPDATE_PASSWORD']))\n\n# Send Verify Email\nresponse = keycloak_admin.send_verify_email(user_id=\"user-id-keycloak\")\n\n# Get sessions associated with the user\nsessions = keycloak_admin.get_sessions(user_id=\"user-id-keycloak\")\n\n# Get themes, social providers, auth providers, and event listeners available on this server\nserver_info = keycloak_admin.get_server_info()\n\n# Get clients belonging to the realm Returns a list of clients belonging to the realm\nclients = keycloak_admin.get_clients()\n\n# Get client - id (not client-id) from client by name\nclient_id=keycloak_admin.get_client_id(\"my-client\")\n\n# Get representation of the client - id of client (not client-id)\nclient = keycloak_admin.get_client(client_id=\"client_id\")\n\n# Get all roles for the realm or client\nrealm_roles = keycloak_admin.get_realm_roles()\n\n# Get all roles for the client\nclient_roles = keycloak_admin.get_client_roles(client_id=\"client_id\")\n\n# Get client role\nrole = keycloak_admin.get_client_role(client_id=\"client_id\", role_name=\"role_name\")\n\n# Warning: Deprecated\n# Get client role id from name\nrole_id = keycloak_admin.get_client_role_id(client_id=\"client_id\", role_name=\"test\")\n\n# Create client role\nkeycloak_admin.create_client_role(client_id, \"test\")\n\n# Assign client role to user. Note that BOTH role_name and role_id appear to be required.\nkeycloak_admin.assign_client_role(client_id=\"client_id\", user_id=\"user_id\", role_id=\"role_id\", role_name=\"test\")\n\n# Create new group\ngroup = keycloak_admin.create_group(name=\"Example Group\")\n\n# Get all groups\ngroups = keycloak_admin.get_groups()\n\n# Get group \ngroup = keycloak_admin.get_group(group_id='group_id')\n\n# Get group by name\ngroup = keycloak_admin.get_group_by_name(name_or_path='group_id', search_in_subgroups=True)\n\n# Function to trigger user sync from provider\nsync_users(storage_id=\"storage_di\", action=\"action\")\n```\n" }, { "alpha_fraction": 0.6813504695892334, "alphanum_fraction": 0.6836012601852417, "avg_line_length": 36.02381134033203, "blob_id": "7062ae219ba80400e6d711f0de9d69ef24ee1476", "content_id": "2978d1f2d4104a2e7dbd281bf33937aead64e417", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3110, "license_type": "permissive", "max_line_length": 137, "num_lines": 84, "path": "/ansible/roles/cassandra-backup/templates/cassandra_backup.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Author: Rajesh Rajendran <[email protected]>\n\n'''\nCreate cassandra snapshot with specified name,\nand create tar ball in targetdirectory name\n\nBy default\n\nCassandra data directory : /var/lib/cassandra/data\nSnapshot name : cassandra_backup-YYYY-MM-DD\nBackup name : cassandra_backup-YYYY-MM-DD.tar.gz\n\nusage: script snapshot_name\n\neg: ./cassandra_backup.py\n\nfor help ./cassandra_backup.py -h\n'''\n\nfrom os import walk, sep, system, getcwd, makedirs\nfrom argparse import ArgumentParser\nfrom shutil import rmtree, ignore_patterns, copytree\nfrom re import match, compile\nfrom sys import exit\nfrom tempfile import mkdtemp\nfrom time import strftime\n\nparser = ArgumentParser(description=\"Create a snapshot and create tar ball inside tardirectory\")\nparser.add_argument(\"-d\", \"--datadirectory\", metavar=\"datadir\", default='/var/lib/cassandra/data',\n help=\"Path to cassadandra keyspaces. Default /var/lib/cassadra/data\")\nparser.add_argument(\"-s\", \"--snapshotname\", metavar=\"snapshotname\",\n default=\"cassandra_backup-\"+strftime(\"%Y-%m-%d\"),\n help=\"Name with which snapshot to be taken. Default {}\".format(\"cassandra_backup-\"+strftime(\"%Y-%m-%d\")))\nparser.add_argument(\"-t\", \"--tardirectory\", metavar=\"tardir\",\n default=getcwd(), help=\"Path to create the tarball. Default {}\".format(getcwd()))\nargs = parser.parse_args()\n\n# Create temporary directory to copy data\ntmpdir = mkdtemp()\nmakedirs(tmpdir+sep+\"cassandra_backup\")\n\n\ndef copy():\n '''\n Copying the data sanpshots to the target directory\n '''\n root_levels = args.datadirectory.count(sep)\n ignore_list = compile(tmpdir+sep+\"cassandra_backup\"+sep+'(system|system|systemtauth|system_traces|system_schema|system_distributed)')\n\n try:\n for root, dirs, files in walk(args.datadirectory):\n root_target_dir = tmpdir+sep+\"cassandra_backup\"+sep+sep.join(root.split(sep)[root_levels+1:-2])\n if match(ignore_list, root_target_dir):\n continue\n if root.split(sep)[-1] == args.snapshotname:\n copytree(src=root, dst=root_target_dir, ignore=ignore_patterns('.*'))\n except Exception as e:\n print(e)\n\n\n# Creating schema\ncommand = \"cqlsh -e 'DESC SCHEMA' > {}/cassandra_backup/db_schema.cql\".format(tmpdir)\nrc = system(command)\nif rc != 0:\n print(\"Couldn't backup schema, exiting...\")\n exit(1)\nprint(\"Schema backup completed. saved in {}/cassandra_backup/db_schema.sql\".format(tmpdir))\n# Cleaning all old snapshots\ncommand = \"nodetool clearsnapshot\"\nsystem(command)\n# Creating snapshots\ncommand = \"nodetool snapshot -t {}\".format(args.snapshotname)\nrc = system(command)\nif rc == 0:\n print(\"Snapshot taken.\")\n copy()\n print(\"Making a tarball: {}.tar.gz\".format(args.snapshotname))\n command = \"cd {} && tar -czvf {}/{}.tar.gz *\".format(tmpdir, args.tardirectory, args.snapshotname)\n system(command)\n # Cleaning up backup directory\n rmtree(tmpdir)\n print(\"Cassandra backup completed and stored in {}/{}.tar.gz\".format(args.tardirectory, args.snapshotname))\n" }, { "alpha_fraction": 0.6126126050949097, "alphanum_fraction": 0.6396396160125732, "avg_line_length": 36, "blob_id": "991ddb562b560aa74470fe5665299fad61154ec6", "content_id": "5c744fc32268836fa9d5f9d2dad21a94f6047606", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 111, "license_type": "permissive", "max_line_length": 83, "num_lines": 3, "path": "/images/proxy/metadata.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# return version\necho '{\"name\":\"proxy\",\"version\":\"1.5.0\",\"org\":\"sunbird\",\"hubuser\":\"purplesunbird\"}'\n" }, { "alpha_fraction": 0.41727179288864136, "alphanum_fraction": 0.5315093398094177, "avg_line_length": 27.661710739135742, "blob_id": "51eb70a781105618c9d2e32a17a32506fe9358b3", "content_id": "9f84a0b5f34761277682fd48ca97095bbd389c5b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 7712, "license_type": "permissive", "max_line_length": 98, "num_lines": 269, "path": "/ansible/roles/curl_command/templates/curl_commands.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\n\n#Create User Partner\ncurl -X POST \\\n https://{{curl_host}}/api//user/v1/create \\\n -H 'authorization: Bearer {{kong__test_jwt}}' \\\n -H 'cache-control: no-cache' \\\n -H 'content-type: application/json' \\\n -H 'ts: 2017-05-25 10:18:56:578+0530' \\\n -H 'x-authenticated-userid: e9280b815c0e41972bf754e9409b66d778b8e11bb91844892869a1e828d7d2f2a' \\\n -H 'x-consumer-id: X-Consumer-ID' \\\n -H 'x-device-id: X-Device-ID' \\\n -H 'x-msgid: 8e27cbf5-e299-43b0-bca7-8347f7e5abcf' \\\n -d '\n{\n \"params\": { },\n \"request\":{\n \"firstName\": \"apiuser868\",\n \"lastName\": \"Kumar\",\n \"password\": \"password\",\n \"provider\":\"NTP\",\n \"emailVerified\": true,\n \"phoneVerified\": true,\n \"email\": \"[email protected]\",\n \"userName\":\"apiuser200\",\n \"phone\": \"99000321212\",\n \"gender\": \"male\",\n\n \"avatar\": null,\n \"dob\": \"1992-10-12\",\n \"language\":[\"English\",\"Hindi\"],\n \"subject\":[\"Physics\",\"Math\",\"English\"],\n \"address\": [\n {\n \"addType\": \"permanent\",\n \"addressLine1\": \"212 winding hill dr\",\n \"addressLine2\": \"Frazer town\",\n \"city\": \"Bangalore\",\n \"state\": \"Karnataka\",\n \"zipCode\": \"560103\"\n } ,\n {\n \"addType\": \"permanent\",\n \"addressLine1\": \"2121 winding hill dr\",\n \"addressLine2\": \"Frazer town1\",\n \"city\": \"Bangalore1\",\n \"state\": \"Karnataka1\",\n \"zipCode\": \"560135\"\n }\n ],\n \"education\": [\n {\n \"degree\": \"Bachelor of Science\",\n \"yearOfPassing\": 2012,\n \"percentage\": 72.5,\n \"grade\": \"B\",\n \"name\": \"MG College\",\n \"boardOrUniversity\": \"Anna University\",\n \"address\":{\n \"addressLine1\": \"2121 winding hill dr\",\n \"addressLine2\": \"Frazer town1\",\n \"city\": \"Bangalore1\",\n \"state\": \"Karnataka1\",\n \"zipCode\": \"560135\"\n }\n },\n {\n \"degree\": \"Plus 2\",\n \"yearOfPassing\": 2009,\n\n \"name\": \"Delhi Public School\",\n \"boardOrUniversity\": \"CBSE\",\n \"address\":{\n \"addressLine1\": \"2121 winding hill dr\",\n \"addressLine2\": \"Frazer town1\",\n \"city\": \"Bangalore1\",\n \"state\": \"Karnataka1\",\n \"zipCode\": \"560135\"\n }\n }\n ],\n \"jobProfile\":[\n {\n \"jobName\":\"jobName\",\n \"role\":\"teacher\",\n \"joiningDate\":\"1992-10-12\",\n \"endDate\":\"1992-10-12\",\n\n \"orgName\":\"AP ORG\",\n \"subject\":[\"Physics\",\"Chemistry\"],\n\n \"address\":{\n \"addressLine1\": \"2121 winding hill dr\",\n \"addressLine2\": \"Frazer town1\",\n \"city\": \"Bangalore1\",\n \"state\": \"Karnataka1\",\n \"zipCode\": \"560135\"\n }\n },\n {\n \"jobName\":\"jobName1\",\n \"role\":\"teacher\",\n \"joiningDate\":\"1992-10-12\",\n \"endDate\":\"1992-10-12\",\n\n \"orgName\":\"AP ORG\",\n \"subject\":[\"Physics\",\"Chemistry\"],\n\n \"address\":{\n \"addressLine1\": \"2121 winding hill dr\",\n \"addressLine2\": \"Frazer town1\",\n \"city\": \"Bangalore1\",\n \"state\": \"Karnataka1\",\n \"zipCode\": \"560135\"\n }\n }\n ]\n }\n}'\n\n\n#GET User By Login ID\ncurl -X PATCH \\\n https://{{curl_host}}/api//user/v1/update \\\n -H 'accept: application/json' \\\n -H 'authorization: Bearer {{kong__test_jwt}}' \\\n -H 'cache-control: no-cache' \\\n -H 'content-type: application/json' \\\n -H 'ts: 2017-05-25 10:18:56:578+0530' \\\n -H 'x-authenticated-userid: 7d086e8c-68ac-4aaa-8b91-d75ff922bae5' \\\n -H 'x-consumer-id: 7c03ca2e78326957afbb098044a3f60783388d5cc731a37821a20d95ad497ca8' \\\n -H 'x-device-id: X-Device-ID' \\\n -H 'x-msgid: 8e27cbf5-e299-43b0-bca7-8347f7e5abcf' \\\n -d '{\n\"id\":\"unique API ID\",\n\"ts\":\"2013/10/15 16:16:39\",\n \"params\": {\n\n },\n\"request\":{\n\"lastName\":\"test100\",\n\"gender\":\"female\",\n\"phoneVerified\":true,\n\"emailVerified\":true,\n\"userName\":\"apiuser301\",\n\"provider\": \"Sunbird\",\n\"userId\":\"b882c5a2-96f2-43be-8ec3-d424ab7e62fb\",\n\"firstName\": \"apiuser862\",\n\"phone\": \"99000321212\",\n\"dob\": \"1992-10-12\"\n}\n}'\n\n#Create Organization\ncurl -X POST \\\n https://{{curl_host}}/api//api/org/v1/create \\\n -H 'accept: application/json' \\\n -H 'authorization: Bearer {{kong__test_jwt}}' \\\n -H 'cache-control: no-cache' \\\n -H 'content-type: application/json' \\\n -H 'ts: 2017-05-25 10:18:56:578+0530' \\\n -H 'x-authenticated-userid: e9280b815c0e41972bf754e9409b66d778b8e11bb91844892869a1e828d7d2f2a' \\\n -H 'x-consumer-id: X-Consumer-ID' \\\n -H 'x-device-id: X-Device-ID' \\\n -H 'x-msgid: 8e27cbf5-e299-43b0-bca7-8347f7e5abcf' \\\n -d '\n{\n \"params\": { },\n \"request\":{\n \"orgName\": \"Genie Ltd\",\n \"description\":\"Genie Ltd1\",\n \"orgType\":\"Training\",\n \"preferredLanguage\":\"English\",\n \"orgCode\":\"ABCL\",\n \"isRootOrg\":false,\n \"address\":{\n \"city\":\"abc\",\n \"state\":\"TN\",\n \"country\":\"India\",\n \"zipCode\":\"45678\"\n\n\n\n\n }\n }\n}'\n\n\n#GET Organization\ncurl -X POST \\\n https://{{curl_host}}/api//api/org/v1/read \\\n -H 'accept: application/json' \\\n -H 'authorization: Bearer {{kong__test_jwt}}' \\\n -H 'cache-control: no-cache' \\\n -H 'content-type: application/json' \\\n -H 'ts: 2017-05-25 10:18:56:578+0530' \\\n -H 'x-authenticated-userid: e9280b815c0e41972bf754e9409b66d778b8e11bb91844892869a1e828d7d2f2a' \\\n -H 'x-consumer-id: X-Consumer-ID' \\\n -H 'x-device-id: X-Device-ID' \\\n -H 'x-msgid: 8e27cbf5-e299-43b0-bca7-8347f7e5abcf' \\\n -d '{\n \"params\": { },\n \"request\":{\n \"organisationId\": \"012327352153448448232\"\n\n\n }\n}'\n\n#Update User Info\ncurl -X PATCH \\\n https://{{curl_host}}/user/v1/update \\\n -H 'accept: application/json' \\\n -H 'authorization: Bearer {{kong__test_jwt}}' \\\n -H 'cache-control: no-cache' \\\n -H 'content-type: application/json' \\\n -H 'ts: 2017-05-25 10:18:56:578+0530' \\\n -H 'x-authenticated-userid: 7d086e8c-68ac-4aaa-8b91-d75ff922bae5' \\\n -H 'x-consumer-id: 7c03ca2e78326957afbb098044a3f60783388d5cc731a37821a20d95ad497ca8' \\\n -H 'x-device-id: X-Device-ID' \\\n -H 'x-msgid: 8e27cbf5-e299-43b0-bca7-8347f7e5abcf' \\\n -d '{\n\"id\":\"unique API ID\",\n\"ts\":\"2013/10/15 16:16:39\",\n \"params\": {\n\n },\n\"request\":{\n\"lastName\":\"test100\",\n\"gender\":\"female\",\n\"phoneVerified\":true,\n\"emailVerified\":true,\n\"userName\":\"apiuser301\",\n\"provider\": \"Sunbird\",\n\"userId\":\"b882c5a2-96f2-43be-8ec3-d424ab7e62fb\",\n\"firstName\": \"apiuser862\",\n\"phone\": \"99000321212\",\n\"dob\": \"1992-10-12\"\n}\n}'\n\n#Add Member to Org\ncurl -X POST \\\n https://{{curl_host}}/api/org/v1/member/add \\\n -H 'accept: application/json' \\\n -H 'authorization: Bearer {{kong__test_jwt}}' \\\n -H 'cache-control: no-cache' \\\n -H 'content-type: application/json' \\\n -H 'ts: 2017-05-25 10:18:56:578+0530' \\\n -H 'x-authenticated-userid: e9280b815c0e41972bf754e9409b66d778b8e11bb91844892869a1e828d7d2f2a' \\\n -H 'x-consumer-id: X-Consumer-ID' \\\n -H 'x-device-id: X-Device-ID' \\\n -H 'x-msgid: 8e27cbf5-e299-43b0-bca7-8347f7e5abcf' \\\n -d ' {\n\"id\":\"unique API ID\",\n\"ts\":\"2013/10/15 16:16:39\",\n \"params\": {\n\n },\n \"request\":{\n \"userName\":\"ntp_prod_9806\",\n \"provider\":\"NTP\",\n \"organisationId\":\"01231499296775372835\",\n \"roles\": [\"CONTENT_CREATOR\", \"CONTENT_REVIEWER\"]\n\n }\n}'\n\n\n" }, { "alpha_fraction": 0.7331730723381042, "alphanum_fraction": 0.7359775900840759, "avg_line_length": 54.44444274902344, "blob_id": "fa3699a7fa57032d2c68a55edad019e9f5982d2d", "content_id": "f5c9fc1a7fe8dde2e5309f9d5c8231c10d7bbf8f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2496, "license_type": "permissive", "max_line_length": 349, "num_lines": 45, "path": "/deploy/deploy-core.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory-path>\"\n exit 1\nfi\n\nINVENTORY_PATH=$1\n\nENV=sample\nORG=sunbird\n# Getting image versions\nsource version.env\n[ -f ~/jwt_token_player.txt ] || echo \"JWT token (~/jwt_token_player.txt) not found\" || exit 1\nsunbird_api_auth_token=$(cat ~/jwt_token_player.txt|sed 's/ //g')\n\n# Bootstrap swarm\necho \"@@@@@@@@@ Bootstrap swarm\"\nansible-playbook -i $INVENTORY_PATH ../ansible/bootstrap.yml --extra-vars \"hosts=swarm-manager\" --tags bootstrap_swarm --extra-vars @config.yml\n\n# Re-deploying badger service\necho \"Redeploy Badger service\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy-badger.yml [email protected] --extra-vars \"hub_org=${ORG} image_name=badger image_tag=${BADGER_SERVICE_VERSION}\"\n\n[ -f ~/badger_token.txt ] || echo \"badger auth token (~/badger_token.txt) not found\" || exit 1\nbadger_token=$(cat ~/badger_token.txt | cut -d '\"' -f 4)\n\n\n# Re-deploy Player service\necho \"@@@@@@@@@ Redeploy player service\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy.yml --tags \"stack-sunbird\" --extra-vars \"hub_org=${ORG} image_name=player image_tag=${PLAYER_VERSION} service_name=player deploy_stack=True sunbird_api_auth_token=${sunbird_api_auth_token} vault_badging_authorization_key=${badger_token}\" --extra-vars @config.yml\n\n# Re-deploy Learner service\necho \"Redeploy learner service\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy.yml --tags \"stack-sunbird\" --extra-vars \"hub_org=${ORG} image_name=learner_service image_tag=${LEARNER_SERVICE_VERSION} service_name=learner-service deploy_learner=True sunbird_api_auth_token=${sunbird_api_auth_token} vault_badging_authorization_key=${badger_token}\" --extra-vars @config.yml -v\n\n# Re-deploy Content service\necho \"Redeploy content service\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy.yml --tags \"stack-sunbird\" --extra-vars \"hub_org=${ORG} image_name=content-service image_tag=${CONTENT_SERVICE_VERSION} service_name=content-service deploy_content=True sunbird_api_auth_token=${sunbird_api_auth_token} vault_badging_authorization_key=${badger_token}\" --extra-vars @config.yml\n\n#Telemetry-Service\necho \"Redeploy Telemetry service\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy.yml --tags \"stack-sunbird\" --extra-vars \"hub_org=${ORG} image_name=telemetry-service image_tag=${TELEMETRY_SERVICE_VERSION} service_name=telemetry-service deploy_telemetry=True\" --extra-vars @config.yml\n\n" }, { "alpha_fraction": 0.758865237236023, "alphanum_fraction": 0.758865237236023, "avg_line_length": 24.727272033691406, "blob_id": "8f690d09df783e87ff8bff57f09925ccbe2e3ab5", "content_id": "1a1bfb522f92c9cb4021d3915a922d1ee61bebeb", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 282, "license_type": "permissive", "max_line_length": 72, "num_lines": 11, "path": "/ansible/roles/elasticsearch/test/integration/helpers/serverspec/spec_helper.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'serverspec'\nset :backend, :exec\n\nrequire 'rspec/retry'\n\nRSpec.configure do |config|\n # show retry status in spec process\n config.verbose_retry = true\n # show exception that triggers a retry if verbose_retry is set to true\n config.display_try_failure_messages = true\nend" }, { "alpha_fraction": 0.6961630582809448, "alphanum_fraction": 0.7152278423309326, "avg_line_length": 35.419212341308594, "blob_id": "6a2521c9ef98d678a750a88b1dbe9d9c0547e2f6", "content_id": "ee0313fe06cc56bcdfb2be464812231a4262a91e", "detected_licenses": [ "GPL-2.0-only", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8340, "license_type": "permissive", "max_line_length": 417, "num_lines": 229, "path": "/ansible/roles/mongodb-cluster/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# Ansible role for MongoDB\n![Centos](https://github.com/UnderGreen/ansible-role-mongodb/actions/workflows/centos.yml/badge.svg) ![Debian](https://github.com/UnderGreen/ansible-role-mongodb/actions/workflows/debian.yml/badge.svg) ![Ubuntu](https://github.com/UnderGreen/ansible-role-mongodb/actions/workflows/ubuntu.yml/badge.svg) ![Amazon Linux 2](https://github.com/UnderGreen/ansible-role-mongodb/actions/workflows/amazonlinux2.yml/badge.svg)\n\nAnsible role to install and manage [MongoDB](http://www.mongodb.org/).\n\n- Install and configure the MongoDB\n- Configure mongodb users\n- Configure authentication\n- Configure replication\n- Setup MMS automation agent;\n\nMongoDB support matrix:\n\n| Distribution | < MongoDB 3.4 | MongoDB 3.6 | MongoDB 4.0 | MongoDB 4.2 | MongoDB 4.4 |\n| -------------- | :-----------: | :----------------: | :----------------: | :----------------: | :----------------: |\n| Ubuntu 16.04 | :no_entry: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: |\n| Ubuntu 18.04 | :no_entry: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: |\n| Ubuntu 20.04 | :no_entry: | :x: | :x: | :x: | :white_check_mark: |\n| Debian 9.x | :no_entry: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |\n| Debian 10.x | :no_entry: | :x: | :x: | :white_check_mark: | :white_check_mark: |\n| RHEL 7.x | :no_entry: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |\n| RHEL 8.x | :no_entry: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |\n| Amazon Linux 2 | :no_entry: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |\n\n- :white_check_mark: - fully tested\n- :x: - don't have official support\n- :no_entry: - MongoDB has reached EOL\n\n#### Variables\n\n```yaml\n# This variable is used to set source of MongoDB installation.\n# 'mongodb' - version provided by Debian-based distributions from their official package repositories.\n# 'mongodb-org' - version provided by MongoDB package repository.\n# 'mongodb' is not included in th role test matrix and working of it is not guarantied.\nmongodb_package: mongodb-org\n\n# `mongodb_version` variable sets version of MongoDB.\n# Should be '3.6', '4.0', '4.2' or '4.4'. This role doesn't support MongoDB < 3.6.\n# I would recommend you to use the latest version of MongoDB.\nmongodb_version: \"4.4\"\n\nmongodb_pymongo_from_pip: true # Install latest PyMongo via PIP or package manager\nmongodb_pymongo_pip_version: 3.6.1 # Choose PyMong version to install from pip. If not set use latest\nmongodb_user_update_password: \"on_create\" # MongoDB user password update default policy\nmongodb_manage_service: true\nmongodb_manage_systemd_unit: true\n\n# Disable transparent hugepages on systemd debian based installations\nmongodb_disable_transparent_hugepages: false\n\n# You can enable or disable NUMA support\nmongodb_use_numa: true\n\nmongodb_user: \"{{ 'mongod' if ('RedHat' == ansible_os_family) else 'mongodb' }}\"\nmongodb_uid:\nmongodb_gid:\nmongodb_daemon_name: \"{{ 'mongod' if ('mongodb-org' in mongodb_package) else 'mongodb' }}\"\n## net Options\nmongodb_net_bindip: 127.0.0.1 # Comma separated list of ip addresses to listen on\nmongodb_net_http_enabled: false # Enable http interface\nmongodb_net_ipv6: false # Enable IPv6 support (disabled by default)\nmongodb_net_maxconns: 65536 # Max number of simultaneous connections\nmongodb_net_port: 27017 # Specify port number\n\n## processManagement Options\nmongodb_processmanagement_fork: false # Fork server process\n\n## security Options\n# Disable or enable security. Possible values: 'disabled', 'enabled'\nmongodb_security_authorization: \"disabled\"\nmongodb_security_keyfile: /etc/mongodb-keyfile # Specify path to keyfile with password for inter-process authentication\n\n## storage Options\nmongodb_storage_dbpath: /data/db # Directory for datafiles\nmongodb_storage_dirperdb: false # Use one directory per DB\n\n# The storage engine for the mongod database\nmongodb_storage_engine: \"wiredTiger\"\n# mmapv1 specific options\nmongodb_storage_quota_enforced: false # Limits each database to a certain number of files\nmongodb_storage_quota_maxfiles: 8 # Number of quota files per DB\nmongodb_storage_smallfiles: false # Very useful for non-data nodes\n\nmongodb_storage_journal_enabled: true # Enable journaling\nmongodb_storage_prealloc: true # Disable data file preallocation\n\n# WiredTiger Options\nmongodb_wiredtiger_cache_size: 1 # Cache size for wiredTiger in GB\n\n## systemLog Options\n## The destination to which MongoDB sends all log output. Specify either 'file' or 'syslog'.\n## If you specify 'file', you must also specify mongodb_systemlog_path.\nmongodb_systemlog_destination: \"file\"\nmongodb_systemlog_logappend: true # Append to logpath instead of over-writing\nmongodb_systemlog_path: /var/log/mongodb/{{ mongodb_daemon_name }}.log # Log file to send write to instead of stdout\n\n## replication Options\nmongodb_replication_replset: # Enable replication <setname>[/<optionalseedhostlist>]\nmongodb_replication_replindexprefetch: \"all\" # specify index prefetching behavior (if secondary) [none|_id_only|all]\nmongodb_replication_oplogsize: 1024 # specifies a maximum size in megabytes for the replication operation log\n\n## setParameter options\n# Configure setParameter option.\n# Example :\nmongodb_set_parameters:\n {\n \"enableLocalhostAuthBypass\": \"true\",\n \"authenticationMechanisms\": \"SCRAM-SHA-1,MONGODB-CR\",\n }\n\n## Extend config with arbitrary values\n# Example :\nmongodb_config:\n replication:\n - \"enableMajorityReadConcern: false\"\n\n# MMS Agent\nmongodb_mms_agent_pkg: https://cloud.mongodb.com/download/agent/monitoring/mongodb-mms-monitoring-agent_7.2.0.488-1_amd64.ubuntu1604.deb\nmongodb_mms_group_id: \"\"\nmongodb_mms_api_key: \"\"\nmongodb_mms_base_url: https://mms.mongodb.com\n\n# Log rotation\nmongodb_logrotate: true # Rotate mongodb logs.\nmongodb_logrotate_options:\n - compress\n - copytruncate\n - daily\n - dateext\n - rotate 7\n - size 10M\n\n# password for inter-process authentication\n# please regenerate this file on production environment with command 'openssl rand -base64 741'\nmongodb_keyfile_content: |\n 8pYcxvCqoe89kcp33KuTtKVf5MoHGEFjTnudrq5BosvWRoIxLowmdjrmUpVfAivh\n CHjqM6w0zVBytAxH1lW+7teMYe6eDn2S/O/1YlRRiW57bWU3zjliW3VdguJar5i9\n Z+1a8lI+0S9pWynbv9+Ao0aXFjSJYVxAm/w7DJbVRGcPhsPmExiSBDw8szfQ8PAU\n 2hwRl7nqPZZMMR+uQThg/zV9rOzHJmkqZtsO4UJSilG9euLCYrzW2hdoPuCrEDhu\n Vsi5+nwAgYR9dP2oWkmGN1dwRe0ixSIM2UzFgpaXZaMOG6VztmFrlVXh8oFDRGM0\n cGrFHcnGF7oUGfWnI2Cekngk64dHA2qD7WxXPbQ/svn9EfTY5aPw5lXzKA87Ds8p\n KHVFUYvmA6wVsxb/riGLwc+XZlb6M9gqHn1XSpsnYRjF6UzfRcRR2WyCxLZELaqu\n iKxLKB5FYqMBH7Sqg3qBCtE53vZ7T1nefq5RFzmykviYP63Uhu/A2EQatrMnaFPl\n TTG5CaPjob45CBSyMrheYRWKqxdWN93BTgiTW7p0U6RB0/OCUbsVX6IG3I9N8Uqt\n l8Kc+7aOmtUqFkwo8w30prIOjStMrokxNsuK9KTUiPu2cj7gwYQ574vV3hQvQPAr\n hhb9ohKr0zoPQt31iTj0FDkJzPepeuzqeq8F51HB56RZKpXdRTfY8G6OaOT68cV5\n vP1O6T/okFKrl41FQ3CyYN5eRHyRTK99zTytrjoP2EbtIZ18z+bg/angRHYNzbgk\n lc3jpiGzs1ZWHD0nxOmHCMhU4usEcFbV6FlOxzlwrsEhHkeiununlCsNHatiDgzp\n ZWLnP/mXKV992/Jhu0Z577DHlh+3JIYx0PceB9yzACJ8MNARHF7QpBkhtuGMGZpF\n T+c73exupZFxItXs1Bnhe3djgE3MKKyYvxNUIbcTJoe7nhVMrwO/7lBSpVLvC4p3\n wR700U0LDaGGQpslGtiE56SemgoP\n\n# names and passwords for administrative users\nmongodb_user_admin_name: siteUserAdmin\nmongodb_user_admin_password: passw0rd\n\nmongodb_root_admin_name: siteRootAdmin\nmongodb_root_admin_password: passw0rd\n\nmongodb_root_backup_name: backupuser\nmongodb_root_backup_password: passw0rd\n```\n\n#### Usage\n\nAdd `undergreen.mongodb` to your roles and set vars in your playbook file.\n\nExample vars for authorization:\n\n```yaml\nmongodb_security_authorization: \"enabled\"\nmongodb_users:\n - {\n name: testUser,\n password: passw0rd,\n roles: readWrite,\n database: app_development\n}\n```\n\nExample vars for oplog user:\n\n```yaml\nmongodb_oplog_users:\n - {\n user: oplog,\n password: passw0rd\n}\n```\n\nRequired vars to change on production:\n\n```yaml\nmongodb_user_admin_password\nmongodb_root_admin_password\nmongodb_root_backup_password\n\n# if you use replication and authorization\nmongodb_security_keyfile\n```\n\nExample vars for replication:\n\n```yaml\n# It's a 'master' node\nmongodb_login_host: 192.168.56.2\n\n# mongodb_replication_params should be configured on each replica set node\nmongodb_replication_params:\n - {\n host_name: 192.168.56.2,\n host_port: \"{{ mongodb_net_port }}\",\n host_type: replica,\n }\n # host_type can be replica(default) and arbiter\n```\n\nAnd inventory file for replica set:\n\n```ini\n[mongo_master]\n192.158.56.2 mongodb_master=True # it is't a really master of MongoDB replica set,\n # use this variable for replica set init only\n\t\t\t\t\t\t\t\t # or when master is moved from initial master node\n\n[mongo_replicas]\n192.168.56.3\n192.168.56.4\n\n[mongo:children]\nmongo_master\nmongo_replicas\n```\n\nLicensed under the GPLv2 License. See the [LICENSE.md](LICENSE.md) file for details.\n\n#### Feedback, bug-reports, requests, ...\n\nAre [welcome](https://github.com/UnderGreen/ansible-role-mongodb/issues)!\n" }, { "alpha_fraction": 0.5833732485771179, "alphanum_fraction": 0.6007659435272217, "avg_line_length": 25.78205108642578, "blob_id": "29b9c6cb276f8f3889d9824cc8e7376e98f0f06b", "content_id": "0fb2d2fbedba48379d7efdbd846f1815893519e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 6267, "license_type": "permissive", "max_line_length": 73, "num_lines": 234, "path": "/images/kong/templates/0.14.1/nginx_kong.lua", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "return [[\ncharset UTF-8;\n\n> if anonymous_reports then\n${{SYSLOG_REPORTS}}\n> end\n\nerror_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}};\n\n> if nginx_optimizations then\n>-- send_timeout 60s; # default value\n>-- keepalive_timeout 75s; # default value\n>-- client_body_timeout 60s; # default value\n>-- client_header_timeout 60s; # default value\n>-- tcp_nopush on; # disabled until benchmarked\n>-- proxy_buffer_size 128k; # disabled until benchmarked\n>-- proxy_buffers 4 256k; # disabled until benchmarked\n>-- proxy_busy_buffers_size 256k; # disabled until benchmarked\n>-- reset_timedout_connection on; # disabled until benchmarked\n> end\n\nclient_max_body_size ${{CLIENT_MAX_BODY_SIZE}};\nproxy_ssl_server_name on;\nunderscores_in_headers on;\n\nlua_package_path '${{LUA_PACKAGE_PATH}};;';\nlua_package_cpath '${{LUA_PACKAGE_CPATH}};;';\nlua_socket_pool_size ${{LUA_SOCKET_POOL_SIZE}};\nlua_max_running_timers 4096;\nlua_max_pending_timers 16384;\nlua_shared_dict kong 5m;\nlua_shared_dict kong_db_cache ${{MEM_CACHE_SIZE}};\nlua_shared_dict kong_db_cache_miss 12m;\nlua_shared_dict kong_locks 8m;\nlua_shared_dict kong_process_events 5m;\nlua_shared_dict kong_cluster_events 5m;\nlua_shared_dict kong_healthchecks 5m;\nlua_shared_dict kong_rate_limiting_counters ${{RATELIMIT_CACHE_SIZE}};\n> if database == \"cassandra\" then\nlua_shared_dict kong_cassandra 5m;\n> end\nlua_socket_log_errors off;\n> if lua_ssl_trusted_certificate then\nlua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}';\nlua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}};\n> end\n\n# injected nginx_http_* directives\n> for _, el in ipairs(nginx_http_directives) do\n$(el.name) $(el.value);\n> end\n\ninit_by_lua_block {\n Kong = require 'kong'\n Kong.init()\n}\n\ninit_worker_by_lua_block {\n Kong.init_worker()\n}\n\n\n> if #proxy_listeners > 0 then\nupstream kong_upstream {\n server 0.0.0.1;\n balancer_by_lua_block {\n Kong.balancer()\n }\n keepalive ${{UPSTREAM_KEEPALIVE}};\n}\n\nserver {\n server_name kong;\n> for i = 1, #proxy_listeners do\n listen $(proxy_listeners[i].listener);\n> end\n error_page 400 404 408 411 412 413 414 417 494 /kong_error_handler;\n error_page 500 502 503 504 /kong_error_handler;\n\n access_log ${{PROXY_ACCESS_LOG}};\n error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}};\n\n client_body_buffer_size ${{CLIENT_BODY_BUFFER_SIZE}};\n\n> if proxy_ssl_enabled then\n ssl_certificate ${{SSL_CERT}};\n ssl_certificate_key ${{SSL_CERT_KEY}};\n ssl_protocols TLSv1.1 TLSv1.2;\n ssl_certificate_by_lua_block {\n Kong.ssl_certificate()\n }\n\n ssl_session_cache shared:SSL:10m;\n ssl_session_timeout 10m;\n ssl_prefer_server_ciphers on;\n ssl_ciphers ${{SSL_CIPHERS}};\n> end\n\n> if client_ssl then\n proxy_ssl_certificate ${{CLIENT_SSL_CERT}};\n proxy_ssl_certificate_key ${{CLIENT_SSL_CERT_KEY}};\n> end\n\n real_ip_header ${{REAL_IP_HEADER}};\n real_ip_recursive ${{REAL_IP_RECURSIVE}};\n> for i = 1, #trusted_ips do\n set_real_ip_from $(trusted_ips[i]);\n> end\n\n # injected nginx_proxy_* directives\n> for _, el in ipairs(nginx_proxy_directives) do\n $(el.name) $(el.value);\n> end\n\n location / {\n default_type '';\n\n set $ctx_ref '';\n set $upstream_host '';\n set $upstream_upgrade '';\n set $upstream_connection '';\n set $upstream_scheme '';\n set $upstream_uri '';\n set $upstream_x_forwarded_for '';\n set $upstream_x_forwarded_proto '';\n set $upstream_x_forwarded_host '';\n set $upstream_x_forwarded_port '';\n\n rewrite_by_lua_block {\n Kong.rewrite()\n }\n\n access_by_lua_block {\n Kong.access()\n }\n\n proxy_http_version 1.1;\n proxy_set_header Host $upstream_host;\n proxy_set_header Upgrade $upstream_upgrade;\n proxy_set_header Connection $upstream_connection;\n proxy_set_header X-Forwarded-For $upstream_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;\n proxy_set_header X-Forwarded-Host $upstream_x_forwarded_host;\n proxy_set_header X-Forwarded-Port $upstream_x_forwarded_port;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_pass_header Server;\n proxy_pass_header Date;\n proxy_ssl_name $upstream_host;\n proxy_pass $upstream_scheme://kong_upstream$upstream_uri;\n\n header_filter_by_lua_block {\n Kong.header_filter()\n }\n\n body_filter_by_lua_block {\n Kong.body_filter()\n }\n\n log_by_lua_block {\n Kong.log()\n }\n }\n\n location = /kong_error_handler {\n internal;\n uninitialized_variable_warn off;\n\n content_by_lua_block {\n Kong.handle_error()\n }\n\n header_filter_by_lua_block {\n Kong.header_filter()\n }\n\n body_filter_by_lua_block {\n Kong.body_filter()\n }\n\n log_by_lua_block {\n Kong.log()\n }\n }\n}\n> end\n\n> if #admin_listeners > 0 then\nserver {\n server_name kong_admin;\n> for i = 1, #admin_listeners do\n listen $(admin_listeners[i].listener);\n> end\n\n access_log ${{ADMIN_ACCESS_LOG}};\n error_log ${{ADMIN_ERROR_LOG}} ${{LOG_LEVEL}};\n\n client_max_body_size 10m;\n client_body_buffer_size 10m;\n\n> if admin_ssl_enabled then\n ssl_certificate ${{ADMIN_SSL_CERT}};\n ssl_certificate_key ${{ADMIN_SSL_CERT_KEY}};\n ssl_protocols TLSv1.1 TLSv1.2;\n\n ssl_session_cache shared:SSL:10m;\n ssl_session_timeout 10m;\n ssl_prefer_server_ciphers on;\n ssl_ciphers ${{SSL_CIPHERS}};\n> end\n\n # injected nginx_admin_* directives\n> for _, el in ipairs(nginx_admin_directives) do\n $(el.name) $(el.value);\n> end\n\n location / {\n default_type application/json;\n content_by_lua_block {\n Kong.serve_admin_api()\n }\n }\n\n location /nginx_status {\n internal;\n access_log off;\n stub_status;\n }\n\n location /robots.txt {\n return 200 'User-agent: *\\nDisallow: /';\n }\n}\n> end\n]]\n" }, { "alpha_fraction": 0.48098859190940857, "alphanum_fraction": 0.5038022994995117, "avg_line_length": 36.57143020629883, "blob_id": "8bfaa6f21862c65c41383325e5896e08b314cc2b", "content_id": "b635d0388683ab2beb19f3ae64ac8b4acc013518", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 526, "license_type": "permissive", "max_line_length": 115, "num_lines": 14, "path": "/deploy/gitOPS/deleteBranches.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nread -p \"Enter Github Username: \" user\nread -sp \"Enter Github Password: \" pass\necho \" \"\nIFS=','\ngrep -v -e '#' -e \"^$\" github.csv | while read -ra LINE\ndo\n repo_name=\"${LINE[0]}\"\n branch_name=\"${LINE[1]}\"\n echo \"----------------------------------------------------\"\n echo -e '\\033[0;32m'$repo_name' '$branch_name'\\033[0m'\n echo \"----------------------------------------------------\"\n curl -u $user:$pass -XDELETE https://api.github.com/repos/project-sunbird/$repo_name/git/refs/heads/$branch_name\ndone\n" }, { "alpha_fraction": 0.6940639019012451, "alphanum_fraction": 0.7534246444702148, "avg_line_length": 35.66666793823242, "blob_id": "675092eb65f1e17f08570b9775f9c317c71a194b", "content_id": "d43ff1053a2d65188fb1adc10ec3bfd4edd377a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 219, "license_type": "permissive", "max_line_length": 81, "num_lines": 6, "path": "/deploy/build-keycloak.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nwget https://downloads.jboss.org/keycloak/3.2.0.Final/keycloak-3.2.0.Final.tar.gz\ntar -xvf keycloak-3.2.0.Final.tar.gz\nmv keycloak-3.2.0.Final keycloak\ntar -czvf keycloak.tar.gz keycloak\nmv keycloak.tar.gz $1" }, { "alpha_fraction": 0.5684803128242493, "alphanum_fraction": 0.6051996946334839, "avg_line_length": 35.8190803527832, "blob_id": "40d14b9b08120dc5f6833452fbadf163aa90fccd", "content_id": "dfe8bd63b174728bad685d0b5265c4681f6127d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 11193, "license_type": "permissive", "max_line_length": 187, "num_lines": 304, "path": "/deploy/validateConfig.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#/bin/bash\n\n# Trampoline secret length validation\ncheck_tram_secret(){\nkey=$1\nvalue=$2\nlength=$(echo $value | awk '{print length}')\nif [[ $length -lt 8 ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Invalid value for $key. Value must be at least 8 characters in length\"\n fail=1\nfi\n}\n\n\n# Basic phone number validation\ncheck_phone(){\nkey=$1\nvalue=$2\nlength=$(echo $value | awk '{print length}')\nif [[ $length -lt 8 || $value =~ [a-zA-Z] ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Invalid value for $key. Phone number cannot include alphabets and should contain 8 digits minimum${normal}\"\n fail=1\nfi\n}\n\n\n# Basic email validation\ncheck_email(){\nkey=$1\nvalue=$2\nif ! [[ $value =~ ^([a-zA-Z0-9]).*@([a-zA-Z0-9]).*\\.([a-zA-Z0-9]).*$ ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Invalid value for $key. Email must be of the format [email protected]${normal}\"\n fail=1\nfi\n}\n\n\n# Check if the CIDR value specified in app_address_space is valid\ncheck_cidr(){\nkey=$1\nvalue=$2\ncidr_result=\"OK\"\nIFS=\"./\" read -r ip1 ip2 ip3 ip4 N <<< $value\nip=$(($ip1 * 256 ** 3 + $ip2 * 256 ** 2 + $ip3 * 256 + $ip4))\nif ! [[ $(($ip % 2**(32-$N))) = 0 ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Invalid CIDR value for $key. Please enter a valid value. CIDR is of the format 172.10.0.0/24\"\n fail=1\n cidr_result=\"fail\"\nfi\n}\n\n\n# Check if the IP address belongs to the CIDR block specified in app_address_space\ncheck_ip(){\nkey=$1\nvalue=$2\nif [[ ${vals[app_address_space]} != \"\" && $cidr_result != \"fail\" ]]; then\n\n IFS=\".\" read -r hip1 hip2 hip3 hip4 <<< $value\n host_ip=$(($hip1 * 256 ** 3 + $hip2 * 256 ** 2 + $hip3 * 256 + $hip4))\n\n # Obtain the netmask\n IFS=\"./\" read -r cip1 cip2 cip3 cip4 N <<< ${vals[app_address_space]}\n set -- $(( 5 - ($N / 8))) 255 255 255 255 $(((255 << (8 - ($N % 8))) & 255 )) 0 0 0\n [ $1 -gt 1 ] && shift $1 || shift\n mask=${1-0}.${2-0}.${3-0}.${4-0}\n IFS=\".\" read -r mip1 mip2 mip3 mip4 <<< $mask\n\n # Network address - Formula to calculate is cidr ip bitwise AND with mask ip\n # Ex: 172.30.0.0 & 255.255.0.0 = 172.30.0.0 (First address)\n nip1=$((cip1&mip1))\n nip2=$((cip2&mip2))\n nip3=$((cip3&mip3))\n nip4=$((cip4&mip4))\n net_ip=$(($nip1 * 256 ** 3 + $nip2 * 256 ** 2 + $nip3 * 256 + $nip4))\n\n # Broadcast address - Formula to calculate is cidr ip bitwise AND with mask ip then XOR with 255 - mask IP\n # Ex: 172.30.0.0 & 255.255.0.0 ^ 0.0.255.255 = 172.30.255.255 (Last address)\n bip1=$((cip1&mip1^(255-$mip1)))\n bip2=$((cip2&mip2^(255-$mip2)))\n bip3=$((cip3&mip3^(255-$mip3)))\n bip4=$((cip4&mip4^(255-$mip4)))\n broad_ip=$(($bip1 * 256 ** 3 + $bip2 * 256 ** 2 + $bip3 * 256 + $bip4))\n\n # Bitwise AND host ip with mask ip to obtain CIDR block.\n # Example: 172.30.30.55 & 255.255.0.0 = 172.30.0.0 (CIDR)\n hipm1=$((hip1&mip1))\n hipm2=$((hip2&mip2))\n hipm3=$((hip3&mip3))\n hipm4=$((hip4&mip4))\n\n cidr_trim=$cip1.$cip2.$cip3.$cip4\n ip_mask=$hipm1.$hipm2.$hipm3.$hipm4\n\n range_start=$nip1.$nip2.$nip3.$((nip4 + 1))\n range_end=$bip1.$bip2.$bip3.$((bip4 - 1))\n\n\n if ! [[ $ip_mask == $cidr_trim && $host_ip -gt $net_ip && $host_ip -lt $broad_ip ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Invalid value for $key. IP address does not belong to the CIDR group. Valid range for given app_address_space is $range_start to $range_end${normal}\"\n fail=1\n fi\nfi\n}\n\n\n# Check if login succeeds to the app, db, es, cass and pg master server using username and private key if values are not null\ncheck_login(){\nkey=$1\nvalue=$2\nusername=${vals[ssh_ansible_user]}\n\nfor j in ${!arr_hosts[@]}\ndo\n if [[ ${arr_hosts[$j]} != \"\" ]]; then\n login_user=$(ssh -i $value -o StrictHostKeyChecking=no -o ConnectTimeout=1 $username@${arr_hosts[$j]} whoami 2> /dev/null)\n\n if [[ $login_user != $username ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Login to ${index_keys[$j]} failed. Please check ${index_keys[$j]}, ssh_ansible_user, ansible_private_key_path${normal}\"\n fail=1\n fi\n fi\ndone\n}\n\n\n# Validate ssh_ansible_user can run sudo commands using the sudo password\ncheck_sudo(){\nkey=$1\nvalue=$2\nusername=${vals[ssh_ansible_user]}\nprivate_key=${vals[ansible_private_key_path]}\n\nfor j in ${!arr_hosts[@]}\ndo\n if [[ ${arr_hosts[$j]} != \"\" ]]; then\n result=$(ssh -i $private_key -o StrictHostKeyChecking=no -o ConnectTimeout=1 $username@${arr_hosts[$j]} \"echo $value | sudo -S apt-get check\" 2> /dev/null)\n\n if ! [[ $result =~ (Reading|Building) ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Sudo check failed. Please check the value provided in ssh_ansible_user, $key, ansible_private_key_path, ${index_keys[$j]}${normal}\"\n fail=1\n fi\nfi\ndone\n}\n\n\n# Function to retrieve values of mandatory fields and store it as key value pair\nget_config_values(){\nkey=$1\nvals[$key]=$(awk ''/^$key:' /{ if ($2 !~ /#.*/) {print $2}}' config.yml)\n}\n\n# Script start. core_install will receive value as \"core\" from calling script when -s core option is triggered.\nbold=$(tput bold)\nnormal=$(tput sgr0)\nfail=0\nif ! [[ $# -eq 0 ]]; then\n core_install=$1\nelse\n core_install=\"NA\"\nfi\n\necho -e \"\\e[0;33m${bold}Validating the config file...${normal}\"\n\n\n# An array of mandatory values\ndeclare -a arr=(\"env\" \"implementation_name\" \"ssh_ansible_user\" \"dns_name\" \"proto\" \"cert_path\" \"key_path\" \"keycloak_admin_password\" \\\n \"sso_password\" \"trampoline_secret\" \"backup_storage_key\" \"badger_admin_password\" \"badger_admin_email\" \"ekstep_api_base_url\" \\\n \"ekstep_proxy_base_url\" \"ekstep_api_key\" \"sunbird_image_storage_url\" \"sunbird_azure_storage_key\" \"sunbird_azure_storage_account\" \\\n \"sunbird_custodian_tenant_name\" \"sunbird_custodian_tenant_description\" \"sunbird_custodian_tenant_channel\" \"sunbird_root_user_firstname\" \\\n \"sunbird_root_user_lastname\" \"sunbird_root_user_username\" \"sunbird_root_user_password\" \"sunbird_root_user_email\" \"sunbird_root_user_phone\" \\\n \"sunbird_sso_publickey\" \"app_address_space\" \"application_host\" \"database_host\" \"sudo_passwd\" \\\n \"ansible_private_key_path\" \"elasticsearch_host\" \"cassandra_host\" \"postgres_master_host\" \"database_password\" \"postgres_keycloak_password\" \\\n \"postgres_app_password\" \"postgres_kong_password\" \"postgres_badger_password\" \"cassandra_password\")\n\n# Create and empty array which will store the key and value pair from config file\ndeclare -A vals\n\n# Iterate the array and retrieve values for mandatory fields from config file\nfor i in ${arr[@]}\ndo\nget_config_values $i\ndone\n\n# An array of all the IP addresses which we will use to test login and sudo privilege\ndeclare -a arr_hosts=(\"${vals[application_host]}\" \"${vals[database_host]}\" \"${vals[elasticsearch_host]}\" \"${vals[cassandra_host]}\" \"${vals[postgres_master_host]}\")\ndeclare -a index_keys=(\"application_host\" \"database_host\" \"elasticsearch_host\" \"cassandra_host\" \"postgres_master_host\")\n\n# Iterate the array of key values and based on key check the validation\nfor i in ${arr[@]}\ndo\nkey=$i\nvalue=${vals[$key]}\ncase $key in\n proto)\n if [[ ! \"$value\" =~ ^(http|https)$ ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Valid values are http / https${normal}\"; fail=1\n fi\n ;;\n cert_path|key_path)\n if [[ \"$value\" == \"\" && \"${vals[proto]}\" == \"https\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Protocal https specified but $key is blank. Please fill this value${normal}\"; fail=1\n fi\n ;;\n ekstep_api_base_url)\n if [[ ! \"$value\" =~ ^(https://api-qa.ekstep.in|https://api.ekstep.in)$ ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Valid values for $key are https://api.ekstep.in or https://api-qa.ekstep.in${normal}\"; fail=1\n fi\n ;;\n ekstep_proxy_base_url)\n if [[ ! \"$value\" =~ ^(https://community.ekstep.in|https://qa.ekstep.in)$ ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Valid values for $key are https://community.ekstep.in or https://qa.ekstep.in${normal}\"; fail=1\n fi\n ;;\n trampoline_secret)\n if [[ $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value with a minimum of 8 characters${normal}\"; fail=1\n else\n check_tram_secret $key $value\n fi\n ;;\n sunbird_root_user_phone)\n if [[ $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value with a minimum of 8 digits${normal}\"; fail=1\n else\n check_phone $key $value\n fi\n ;;\n badger_admin_email|sunbird_root_user_email)\n if [[ $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value${normal}\"; fail=1\n else\n check_email $key $value\n fi\n ;;\n app_address_space)\n if [[ $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value${normal}\"; fail=1\n else\n check_cidr $key $value\n fi\n ;;\n application_host)\n if [[ $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value${normal}\"; fail=1\n else\n check_ip $key $value\n fi\n ;;\n ansible_private_key_path)\n if [[ $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value${normal}\"; fail=1\n else\n check_login $key $value\n fi\n ;;\n sudo_passwd)\n if [[ $value != \"\" ]]; then\n check_sudo $key $value\n fi\n ;;\n sunbird_sso_publickey)\n if [[ $core_install == \"core\" && $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value before running core${normal}\"; fail=1\n fi\n ;;\n database_host)\n if [[ $value != \"\" ]]; then\n check_ip $key $value\n fi\n ;;\n elasticsearch_host|cassandra_host|postgres_master_host)\n if [[ $value != \"\" ]]; then\n check_ip $key $value\n elif [[ $value == \"\" && ${vals[database_host]} == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value OR provide value for database_host which will be default DB${normal}\"; fail=1\n fi\n ;;\n database_password)\n continue\n ;;\n postgres_keycloak_password|postgres_app_password|postgres_kong_password|postgres_badger_password|cassandra_password)\n if [[ ${vals[database_password]} == \"\" && $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key is empty. Please provide fill this value OR provide value for database_password which will be default password${normal}\"; fail=1\n fi\n ;;\n\n *)\n if [[ $value == \"\" ]]; then\n echo -e \"\\e[0;31m${bold}ERROR - Value for $key cannot be empty. Please fill this value${normal}\"; fail=1\n fi\n ;;\nesac\ndone\n\n\n# Check if any of the validation failed and exit\nif [[ $fail -eq 1 ]]; then\n echo -e \"\\e[0;34m${bold}Config file has errors. Please rectify the issues and rerun${normal}\"\n exit 1\nelse\n echo -e \"\\e[0;32m${bold}Config file successfully validated${normal}\"\nfi\n" }, { "alpha_fraction": 0.7515451312065125, "alphanum_fraction": 0.7985166907310486, "avg_line_length": 41.578948974609375, "blob_id": "4556726f68712605326d14601d9e2f64be15bf8c", "content_id": "6d7e474059c825cc80dfbb29d0d51c967a45b440", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 809, "license_type": "permissive", "max_line_length": 241, "num_lines": 19, "path": "/images/cassandra_jmx_exporter/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM openjdk:8-jre-alpine\n\nENV APP_HOME=/opt/app\nRUN mkdir -p $APP_HOME\nWORKDIR $APP_HOME\n\nCOPY /images/cassandra_jmx_exporter/jmx_prometheus_httpserver-0.11.jar jmx_prometheus_httpserver-0.11.jar\nCOPY /images/cassandra_jmx_exporter/logging.properties logging.properties\n\nEXPOSE 5556\n\nENTRYPOINT /usr/bin/java ${JAVA_OPTS} -jar jmx_prometheus_httpserver-0.11.jar 5556 $APP_HOME/jmx_httpserver.yml\n\n#!/usr/bin/env bash\n# Script to run a java application for testing jmx4prometheus.\n\n# Note: You can use localhost:5556 instead of 5556 for configuring socket hostname.\n\n#java -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=5555 -jar /usr/share/cassandra/lib/jmx_prometheus_httpserver-0.11.jar 5556 /etc/cassandra/jmx_httpserver.yml\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.7293233275413513, "avg_line_length": 32.25, "blob_id": "79bedb06514bb655a12ed57c485d81c3119a4724", "content_id": "171143c3778068e5cc101c49c42701a26af6b878", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 133, "license_type": "permissive", "max_line_length": 77, "num_lines": 4, "path": "/images/documentation-jenkins-swarm-agent/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM vfarcic/jenkins-swarm-agent:17.10.07-4\n\nUSER root\nRUN apk -v --update add ruby=2.4.1-r3 nodejs=6.10.3-r1 ruby-bundler=1.15.0-r0\n" }, { "alpha_fraction": 0.6715328693389893, "alphanum_fraction": 0.6751824617385864, "avg_line_length": 30.653846740722656, "blob_id": "1a8339c239fa605842d90981643afa2555216330", "content_id": "995b88b082128950984b7cd709ead3eeed0d8feb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 822, "license_type": "permissive", "max_line_length": 112, "num_lines": 26, "path": "/images/echo-server/server.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport os, sys\nfrom BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer\n\nPORT_NUMBER = int(os.environ['ECHO_SERVER_PORT'])\n\nclass EchoRequestHandler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/plain\")\n self.end_headers()\n self.wfile.write(self.path)\n return\n\n def log_message(self, format, *args):\n sys.stdout.write(\"%s - - [%s] %s\\n\" % (self.address_string(), self.log_date_time_string(), format%args))\n sys.stdout.flush()\n\ntry:\n server = HTTPServer(('', PORT_NUMBER), EchoRequestHandler)\n print 'Started httpserver on port ' , PORT_NUMBER\n server.serve_forever()\nexcept KeyboardInterrupt:\n print '^C received, shutting down the web server'\n server.socket.close()" }, { "alpha_fraction": 0.7219436168670654, "alphanum_fraction": 0.7334063649177551, "avg_line_length": 45.07572937011719, "blob_id": "42e51a976df22770db2925d7728af317dc6df3b9", "content_id": "d7c922b359138798f5afb14d4b52d7f64b1341ad", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23729, "license_type": "permissive", "max_line_length": 419, "num_lines": 515, "path": "/ansible/roles/es7/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# ansible-elasticsearch\n[![Build Status](https://img.shields.io/jenkins/s/https/devops-ci.elastic.co/job/elastic+ansible-elasticsearch+master.svg)](https://devops-ci.elastic.co/job/elastic+ansible-elasticsearch+master/)\n[![Ansible Galaxy](https://img.shields.io/badge/ansible--galaxy-elastic.elasticsearch-blue.svg)](https://galaxy.ansible.com/elastic/elasticsearch/)\n\n**THIS ROLE IS FOR 7.x & 6.x**\n\nAnsible role for 7.x/6.x Elasticsearch. Currently this works on Debian and RedHat based linux systems. Tested platforms are:\n\n* Ubuntu 14.04\n* Ubuntu 16.04\n* Ubuntu 18.04\n* Debian 8\n* Debian 9\n* Debian 10\n* CentOS 7\n* CentOS 8\n* Amazon Linux 2\n\nThe latest Elasticsearch versions of 7.x & 6.x are actively tested.\n\n## BREAKING CHANGES\n\n### Notice about multi-instance support\n\n* If you use only one instance but want to upgrade from an older ansible-elasticsearch version, follow [upgrade procedure](https://github.com/elastic/ansible-elasticsearch/blob/master/docs/multi-instance.md#upgrade-procedure)\n* If you install more than one instance of Elasticsearch on the same host (with different ports, directory and config files), **do not update to ansible-elasticsearch >= 7.1.1**, please follow this [workaround](https://github.com/elastic/ansible-elasticsearch/blob/master/docs/multi-instance.md#workaround) instead.\n* For multi-instances use cases, we are now recommending Docker containers using our official images (https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html).\n\n### Removing the MAX_THREAD settings\n\nAnsible-elasticsearch 7.5.2 is removing the option to customize the maximum number of threads the process can start in [#637](https://github.com/elastic/ansible-elasticsearch/pull/637/files#diff-04c6e90faac2675aa89e2176d2eec7d8L408).\nWe discovered that this option wasn't working anymore since multi-instance support removal in ansible-elasticsearch 7.1.1.\nThis option will be added back in a following release if it's still relevant regarding latest Elasticsearch evolutions.\n\n### Changes about configuration files\n\nAnsible-elasticsearch 7.5.2 is updating the configuration files provided by this role in [#637](https://github.com/elastic/ansible-elasticsearch/pull/637) which contained some options deprecated in 6.x and 7.x:\n- `/etc/default/elasticsearch`|`/etc/sysconfig/elasticsearch`: the new template reflect the configuration file provided by Elasticsearch >= 6.x, the parameters we removed were already not used in 6.x and 7.x\n- `/etc/elasticsearch/jvm.options`: the new template reflect the configuration files provided by Elasticsearch >= 6.x\n- `/etc/elasticsearch/log4j2.properties`:\n - We removed `log4j2.properties.j2` template from this Ansible role as it was a static file not bringing any customization specific to some ansible variable.\n - Deployment of this Ansible role on new servers will get the default `log4j2.properties` provided by Elasticsearch without any override.\n - **WARNING**: For upgrade scenarios where this file was already managed by previous versions of ansible-elasticsearch, this file will become unmanaged and won't be updated by default. If you wish to update it to 7.5 version, you can retrieve it [here](https://github.com/elastic/elasticsearch/blob/7.5/distribution/src/config/log4j2.properties) and use this file with `es_config_log4j2` Ansible variable (see below).\n\n### Removing OSS distribution for versions >= 7.11.0\n\nStarting from Elasticsearch 7.11.0, OSS distributions will no more provided following Elasticsearch\nrecent license change.\n\nThis Ansible role will fail if `oss_version` is set to `true` and `es_version` is greater than \n`7.11.0`.\n\nSee [Doubling down on open, Part II](https://www.elastic.co/blog/licensing-change for more details)\nblog post for more details.\n\n#### How to override configuration files provided by ansible-elasticsearch?\n\nYou can now override the configuration files with your own versions by using the following Ansible variables:\n- `es_config_default: \"elasticsearch.j2\"`: replace `elasticsearch.j2` by your own template to use a custom `/etc/default/elasticsearch`|`/etc/sysconfig/elasticsearch` configuration file\n- `es_config_jvm: \"jvm.options.j2\"`: replace `jvm.options.j2` by your own template to use a custom `/etc/elasticsearch/jvm.options` configuration file\n- `es_config_log4j2: \"\"`: set this variable to the path of your own template to use a custom `/etc/elasticsearch/log4j2.properties` configuration file\n\n## Dependency\n\nThis role uses the json_query filter which [requires jmespath](https://github.com/ansible/ansible/issues/24319) on the local machine.\n\n## Usage\n\nCreate your Ansible playbook with your own tasks, and include the role elasticsearch. You will have to have this repository accessible within the context of playbook.\n\n```sh\nansible-galaxy install elastic.elasticsearch,v7.11.1\n```\n\nThen create your playbook yaml adding the role elasticsearch.\nThe application of the elasticsearch role results in the installation of a node on a host.\n\nThe simplest configuration therefore consists of:\n\n```yaml\n- name: Simple Example\n hosts: localhost\n roles:\n - role: elasticsearch7\n vars:\n es_version: 7.11.1\n```\n\nThe above installs Elasticsearch 7.11.1 in a single node 'node1' on the hosts 'localhost'.\n\n\nThis role also uses [Ansible tags](http://docs.ansible.com/ansible/playbooks_tags.html). Run your playbook with the `--list-tasks` flag for more information.\n\n## Testing\n\nThis playbook uses [Kitchen](https://kitchen.ci/) for CI and local testing.\n\n### Requirements\n\n* Ruby\n* Bundler\n* Docker\n* Make\n\n### Running the tests\n\n* Ensure you have checked out this repository to `elasticsearch`, not `ansible-elasticsearch`.\n* If you don't have a Gold or Platinum license to test with you can run the trial versions of the `xpack-upgrade` suites by appending `-trial` to the `PATTERN` variable.\n* You may need to explicitly specify `VERSION=7.x` if some suites are failing.\n\nInstall the ruby dependencies with bundler\n\n```sh\nmake setup\n```\n\nIf you want to test X-Pack features with a license you will first need to export the `ES_XPACK_LICENSE_FILE` variable.\n```sh\nexport ES_XPACK_LICENSE_FILE=\"$(pwd)/license.json\"\n```\n\nTo converge an Ubuntu 16.04 host running X-Pack\n```sh\n$ make converge\n```\n\nTo run the tests\n```sh\n$ make verify\n```\n\nTo list all of the different test suits\n```sh\n$ make list\n```\n\nThe default test suite is Ubuntu 16.04 with X-Pack. If you want to test another suite you can override this with the `PATTERN` variable\n```sh\n$ make converge PATTERN=security-centos-7\n```\n\nThe `PATTERN` is a kitchen pattern which can match multiple suites. To run all tests for CentOS\n```sh\n$ make converge PATTERN=centos-7\n```\n\nThe default version is 7.x. If you want to test 6.x you can override it with the `VERSION` variable, for example:\n```sh\n$ make converge VERSION=6.x PATTERN=security-centos-7\n```\n\nWhen you are finished testing you can clean up everything with\n```sh\n$ make destroy-all\n```\n\n### Basic Elasticsearch Configuration\n\nAll Elasticsearch configuration parameters are supported. This is achieved using a configuration map parameter 'es_config' which is serialized into the elasticsearch.yml file.\nThe use of a map ensures the Ansible playbook does not need to be updated to reflect new/deprecated/plugin configuration parameters.\n\nIn addition to the es_config map, several other parameters are supported for additional functions e.g. script installation. These can be found in the role's defaults/main.yml file.\n\nThe following illustrates applying configuration parameters to an Elasticsearch instance.\n\n```yaml\n- name: Elasticsearch with custom configuration\n hosts: localhost\n roles:\n - role: elasticsearch7\n vars:\n es_data_dirs:\n - \"/opt/elasticsearch/data\"\n es_log_dir: \"/opt/elasticsearch/logs\"\n es_config:\n node.name: \"node1\"\n cluster.name: \"custom-cluster\"\n discovery.seed_hosts: \"localhost:9301\"\n http.port: 9201\n transport.port: 9301\n node.data: false\n node.master: true\n bootstrap.memory_lock: true\n es_heap_size: 1g\n es_api_port: 9201\n```\n\nWhilst the role installs Elasticsearch with the default configuration parameters, the following should be configured to ensure a cluster successfully forms:\n\n* ```es_config['http.port']``` - the http port for the node\n* ```es_config['transport.port']``` - the transport port for the node\n* ```es_config['discovery.seed_hosts']``` - the unicast discovery list, in the comma separated format ```\"<host>:<port>,<host>:<port>\"``` (typically the clusters dedicated masters)\n* ```es_config['cluster.initial_master_nodes']``` - for 7.x and above the list of master-eligible nodes to boostrap the cluster, in the comma separated format ```\"<node.name>:<port>,<node.name>:<port>\"``` (typically the node names of the clusters dedicated masters)\n* ```es_config['network.host']``` - sets both network.bind_host and network.publish_host to the same host value. The network.bind_host setting allows to control the host different network components will bind on.\n\nThe `network.publish_host` setting allows to control the host the node will publish itself within the cluster so other nodes will be able to connect to it.\n\nSee https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-network.html for further details on default binding behavior and available options.\nThe role makes no attempt to enforce the setting of these are requires users to specify them appropriately. It is recommended master nodes are listed and thus deployed first where possible.\n\nA more complex example:\n\n```yaml\n- name: Elasticsearch with custom configuration\n hosts: localhost\n roles:\n - role: elasticsearch7\n vars:\n es_data_dirs:\n - \"/opt/elasticsearch/data\"\n es_log_dir: \"/opt/elasticsearch/logs\"\n es_config:\n node.name: \"node1\"\n cluster.name: \"custom-cluster\"\n discovery.seed_hosts: \"localhost:9301\"\n http.port: 9201\n transport.port: 9301\n node.data: false\n node.master: true\n bootstrap.memory_lock: true\n es_heap_size: 1g\n es_start_service: false\n es_api_port: 9201\n es_plugins:\n - plugin: ingest-attachment\n```\n\n#### Important Notes\n\n**The role uses es_api_host and es_api_port to communicate with the node for actions only achievable via http e.g. to install templates and to check the NODE IS ACTIVE. These default to \"localhost\" and 9200 respectively.\nIf the node is deployed to bind on either a different host or port, these must be changed.**\n\n**Only use es_data_dirs and es_log_dir for customizing the data and log dirs respectively. When using together with `es_config['path.data']` and `es_config['path.logs']` it would result in generating duplicate data- and logs-keys in `elasticsearch.yml` and thus let fail to start elasticsearch.**\n\n### Multi Node Server Installations\n\nThe application of the elasticsearch role results in the installation of a node on a host. Specifying the role multiple times for a host therefore results in the installation of multiple nodes for the host.\n\nAn example of a three server deployment is shown below. The first server holds the master and is thus declared first. Whilst not mandatory, this is recommended in any multi node cluster configuration. The two others servers hosts data nodes.\n\n**Note that we do not support anymore installation of more than one node in the same host**\n\n```yaml\n- hosts: master_node\n roles:\n - role: elasticsearch7\n vars:\n es_heap_size: \"1g\"\n es_config:\n cluster.name: \"test-cluster\"\n cluster.initial_master_nodes: \"elastic02\"\n discovery.seed_hosts: \"elastic02:9300\"\n http.port: 9200\n node.data: false\n node.master: true\n bootstrap.memory_lock: false\n es_plugins:\n - plugin: ingest-attachment\n\n- hosts: data_node_1\n roles:\n - role: elasticsearch7\n vars:\n es_data_dirs:\n - \"/opt/elasticsearch\"\n es_config:\n cluster.name: \"test-cluster\"\n cluster.initial_master_nodes: \"elastic02\"\n discovery.seed_hosts: \"elastic02:9300\"\n http.port: 9200\n node.data: true\n node.master: false\n bootstrap.memory_lock: false\n es_plugins:\n - plugin: ingest-attachment\n\n- hosts: data_node_2\n roles:\n - role: elasticsearch7\n vars:\n es_config:\n cluster.name: \"test-cluster\"\n discovery.seed_hosts: \"elastic02:9300\"\n http.port: 9200\n node.data: true\n node.master: false\n bootstrap.memory_lock: false\n es_plugins:\n - plugin: ingest-attachment\n```\n\nParameters can additionally be assigned to hosts using the inventory file if desired.\n\nMake sure your hosts are defined in your ```inventory``` file with the appropriate ```ansible_ssh_host```, ```ansible_ssh_user``` and ```ansible_ssh_private_key_file``` values.\n\nThen run it:\n\n```sh\nansible-playbook -i hosts ./your-playbook.yml\n```\n\n### Installing X-Pack Features\n\n* ```es_role_mapping``` Role mappings file declared as yml as described [here](https://www.elastic.co/guide/en/x-pack/current/mapping-roles.html)\n\n\n```yaml\nes_role_mapping:\n power_user:\n - \"cn=admins,dc=example,dc=com\"\n user:\n - \"cn=users,dc=example,dc=com\"\n - \"cn=admins,dc=example,dc=com\"\n```\n\n* ```es_users``` - Users can be declared here as yml. Two sub keys 'native' and 'file' determine the realm under which the user is created. Beneath each of these keys users should be declared as yml entries. e.g.\n\n```yaml\nes_users:\n native:\n kibana4_server:\n password: changeMe\n roles:\n - kibana4_server\n file:\n es_admin:\n password: changeMe\n roles:\n - admin\n testUser:\n password: changeMeAlso!\n roles:\n - power_user\n - user\n```\n\n\n* ```es_roles``` - Elasticsearch roles can be declared here as yml. Two sub keys 'native' and 'file' determine how the role is created i.e. either through a file or http(native) call. Beneath each key list the roles with appropriate permissions, using the file based format described [here](https://www.elastic.co/guide/en/x-pack/current/file-realm.html) e.g.\n\n```yaml\nes_roles:\n file:\n admin:\n cluster:\n - all\n indices:\n - names: '*'\n privileges:\n - all\n power_user:\n cluster:\n - monitor\n indices:\n - names: '*'\n privileges:\n - all\n user:\n indices:\n - names: '*'\n privileges:\n - read\n kibana4_server:\n cluster:\n - monitor\n indices:\n - names: '.kibana'\n privileges:\n - all\n native:\n logstash:\n cluster:\n - manage_index_templates\n indices:\n - names: 'logstash-*'\n privileges:\n - write\n - delete\n - create_index\n```\n\n* ```es_xpack_license``` - X-Pack license. The license is a json blob. Set the variable directly (possibly protected by Ansible vault) or from a file in the Ansible project on the control machine via a lookup:\n\n```yaml\nes_xpack_license: \"{{ lookup('file', playbook_dir + '/files/' + es_cluster_name + '/license.json') }}\"\n```\n\nIf you don't have a license you can enable the 30-day trial by setting `es_xpack_trial` to `true`.\n\nX-Pack configuration parameters can be added to the elasticsearch.yml file using the normal `es_config` parameter.\n\nFor a full example see [here](https://github.com/elastic/ansible-elasticsearch/blob/master/test/integration/xpack-upgrade.yml)\n\n#### Important Note for Native Realm Configuration\n\nIn order for native users and roles to be configured, the role calls the Elasticsearch API. Given security is installed this requires definition of two parameters:\n\n* ```es_api_basic_auth_username``` - admin username\n* ```es_api_basic_auth_password``` - admin password\n\nThese can either be set to a user declared in the file based realm, with admin permissions, or the default \"elastic\" superuser (default password is changeme).\n\n#### X-Pack Security SSL/TLS\n\n* To configure your cluster with SSL/TLS for HTTP and/or transport communications follow the [SSL/TLS setup procedure](https://github.com/elastic/ansible-elasticsearch/blob/master/docs/ssl-tls-setup.md)\n\n\n### Additional Configuration\n\nIn addition to es_config, the following parameters allow the customization of the Java and Elasticsearch versions as well as the role behavior. Options include:\n\n* ```oss_version``` Default `false`. Setting this to `true` will install the oss release of Elasticsearch (for version <7.11.0 only).\n* `es_xpack_trial` Default `false`. Setting this to `true` will start the 30-day trail once the cluster starts.\n* ```es_version``` (e.g. \"7.11.1\").\n* ```es_api_host``` The host name used for actions requiring HTTP e.g. installing templates. Defaults to \"localhost\".\n* ```es_api_port``` The port used for actions requiring HTTP e.g. installing templates. Defaults to 9200. **CHANGE IF THE HTTP PORT IS NOT 9200**\n* ```es_api_basic_auth_username``` The Elasticsearch username for making admin changing actions. Used if Security is enabled. Ensure this user is admin.\n* ```es_api_basic_auth_password``` The password associated with the user declared in `es_api_basic_auth_username`\n* `es_delete_unmanaged_file` Default `true`. Set to false to keep file realm users that have been added outside of ansible.\n* `es_delete_unmanaged_native` Default `true`. Set to false to keep native realm users that have been added outside of ansible.\n* ```es_start_service``` (true (default) or false)\n* ```es_plugins_reinstall``` (true or false (default) )\n* ```es_plugins``` an array of plugin definitions e.g.:\n\n ```yaml\n es_plugins:\n - plugin: ingest-attachment\n ```\n\n* ```es_path_repo``` Sets the whitelist for allowing local back-up repositories\n* ```es_action_auto_create_index``` Sets the value for auto index creation, use the syntax below for specifying indexes (else true/false):\n es_action_auto_create_index: '[\".watches\", \".triggered_watches\", \".watcher-history-*\"]'\n* ```es_allow_downgrades``` For development purposes only. (true or false (default) )\n* ```es_java_install``` If set to true, Java will be installed. (false (default for 7.x) or true (default for 6.x))\n* ```update_java``` Updates Java to the latest version. (true or false (default))\n* ```es_max_map_count``` maximum number of VMA (Virtual Memory Areas) a process can own. Defaults to 262144.\n* ```es_max_open_files``` the maximum file descriptor number that can be opened by this process. Defaults to 65536.\n* ```es_debian_startup_timeout``` how long Debian-family SysV init scripts wait for the service to start, in seconds. Defaults to 10 seconds.\n* ```es_use_repository``` Setting this to `false` will stop Ansible from using the official Elastic package from any repository configured on the system.\n* ```es_add_repository``` Setting this to `false` will stop Ansible to add the official Elastic package repositories (if es_use_repository is true) if you want to use a repo already present.\n* ```es_custom_package_url``` the URL to the rpm or deb package for Ansible to install. When using this you will also need to set `es_use_repository: false` and make sure that the `es_version` matches the version being installed from your custom URL. E.g. `es_custom_package_url: https://downloads.example.com/elasticsearch.rpm`\n\nEarlier examples illustrate the installation of plugins using `es_plugins`. For officially supported plugins no version or source delimiter is required. The plugin script will determine the appropriate plugin version based on the target Elasticsearch version. For community based plugins include the full url. This approach should NOT be used for the X-Pack plugin. See X-Pack below for details here.\n\nIf installing Monitoring or Alerting, ensure the license plugin is also specified. Security configuration currently has limited support, but more support is planned for later versions.\n\nTo configure X-pack to send mail, the following configuration can be added to the role. When require_auth is true, you will also need to provide the user and password. If not these can be removed:\n\n```yaml\n es_mail_config:\n account: <functional name>\n profile: standard\n from: <from address>\n require_auth: <true or false>\n host: <mail domain>\n port: <port number>\n user: <e-mail address> --optional\n pass: <password> --optional\n```\n\n* ```es_user``` - defaults to elasticsearch.\n* ```es_group``` - defaults to elasticsearch.\n* ```es_user_id``` - default is undefined.\n* ```es_group_id``` - default is undefined.\n\nBoth ```es_user_id``` and ```es_group_id``` must be set for the user and group ids to be set.\n\n* ```es_restart_on_change``` - defaults to true. If false, changes will not result in Elasticsearch being restarted.\n* ```es_plugins_reinstall``` - defaults to false. If true, all currently installed plugins will be removed from a node. Listed plugins will then be re-installed.\n\nTo add, update or remove elasticsearch.keystore entries, use the following variable:\n\n```yaml\n# state is optional and defaults to present\nes_keystore_entries:\n- key: someKeyToAdd\n value: someValue\n state: present\n\n- key: someKeyToUpdate\n value: newValue\n # state: present\n force: Yes\n\n- key: someKeyToDelete\n state: absent\n```\n\n\n\nThis role ships with sample templates located in the [test/integration/files/templates-7.x](https://github.com/elastic/ansible-elasticsearch/tree/master/test/integration/files/templates-7.x) directory. `es_templates_fileglob` variable is used with the Ansible [with_fileglob](http://docs.ansible.com/ansible/playbooks_loops.html#id4) loop. When setting the globs, be sure to use an absolute path.\n\n### Proxy\n\nTo define proxy globally, set the following variables:\n\n* ```es_proxy_host``` - global proxy host\n* ```es_proxy_port``` - global proxy port\n\n## Notes\n\n* The role assumes the user/group exists on the server. The elasticsearch packages create the default elasticsearch user. If this needs to be changed, ensure the user exists.\n* The playbook relies on the inventory_name of each host to ensure its directories are unique\n* KitchenCI has been used for testing. This is used to confirm images reach the correct state after a play is first applied. We currently test the latest version of 7.x and 6.x on all supported platforms.\n* The role aims to be idempotent. Running the role multiple times, with no changes, should result in no state change on the server. If the configuration is changed, these will be applied and Elasticsearch restarted where required.\n* In order to run x-pack tests a license file with security enabled is required. Set the environment variable `ES_XPACK_LICENSE_FILE` to the full path of the license file prior to running tests. A trial license is appropriate and can be used by setting `es_xpack_trial` to `true`\n\n## IMPORTANT NOTES RE PLUGIN MANAGEMENT\n\n* If the ES version is changed, all plugins will be removed. Those listed in the playbook will be re-installed. This is behavior is required in ES 6.x.\n* If no plugins are listed in the playbook for a node, all currently installed plugins will be removed.\n* The role supports automatic detection of differences between installed and listed plugins - installing those listed but not installed, and removing those installed but not listed. Should users wish to re-install plugins they should set es_plugins_reinstall to true. This will cause all currently installed plugins to be removed and those listed to be installed.\n\n## Questions on Usage\n\nWe welcome questions on how to use the role. However, in order to keep the GitHub issues list focused on \"issues\" we ask the community to raise questions at https://discuss.elastic.co/c/elasticsearch. This is monitored by the maintainers.\n" }, { "alpha_fraction": 0.7493796348571777, "alphanum_fraction": 0.7543424367904663, "avg_line_length": 39.29999923706055, "blob_id": "4332c55c32103b3171783459083b349677efb618", "content_id": "993f6bcddf19d3239619d95ed31de54b39939411", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 806, "license_type": "permissive", "max_line_length": 151, "num_lines": 20, "path": "/ansible/roles/provision-kafka/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#Kafka\nInstalls [kafka](https://kafka.apache.org/)\n\n##Requirements\n- kafka_hosts - comma separated list of host:port pairs in the cluster, defaults to 'ansible_fqdn:9092' for a single node \n- zookeeper_hosts - comma separated list of host:port pairs.\n\n##Optional\n- kafka_listen_address - defines a specifc address for kafka to listen on, by defaults listens on all interfaces\n- kafka_id - Id to be used if one can't or shouldn't be derived from kafka_hosts. This will happen if kafka_hosts doesn't contain the fqdn but an alias\n- monasca_log_level - Log level to be used for Kafka logs. Defaults to WARN\n- run_mode - One of Deploy, Stop, Install, Start, or Use. The default is Deploy which will do Install, Configure, then Start. \n\n##License\nApache\n\n##Author Information\nTim Kuhlman\n\nMonasca Team email [email protected]\n" }, { "alpha_fraction": 0.5966029763221741, "alphanum_fraction": 0.6220806837081909, "avg_line_length": 20.409090042114258, "blob_id": "09f806438998ebc977d222bb6d96dabf8a1855e2", "content_id": "f569c990e27234dc91c348041db7e14f45cc4dda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 471, "license_type": "permissive", "max_line_length": 56, "num_lines": 22, "path": "/ansible/roles/desktop-deploy/templates/setupOfflineInstaller.sh.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd /project/app_dist\n\nif [ \"{{offline_installer_type}}\" != \"windows32bit\" ];\nthen\n #Build the offline installer\n yarn install\n node scripts/metadata.js\n rm -rf scripts\nfi\n\nif [ \"{{offline_installer_type}}\" == \"windows32bit\" ];\nthen\n npm run dist-win32\nelif [ \"{{offline_installer_type}}\" == \"windows64bit\" ];\nthen\n npm run dist-win64\nelif [ \"{{offline_installer_type}}\" == \"linux64bit\" ];\nthen\n npm run dist-linux\nfi\n" }, { "alpha_fraction": 0.6574185490608215, "alphanum_fraction": 0.6996381282806396, "avg_line_length": 33.54166793823242, "blob_id": "3e2b48cc65c49199d66a4aa58fe9299c6682cd1b", "content_id": "738938f805b68e235a83a2f5d3b50db12d4da7c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 829, "license_type": "permissive", "max_line_length": 112, "num_lines": 24, "path": "/images/proxy/build.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Build script\nset -eo pipefail\n\n# Downloading deps\nwget https://codeload.github.com/simplresty/ngx_devel_kit/tar.gz/v0.3.0 -O ngx_devel_kit_0_3_0.tar.gz\nwget https://codeload.github.com/openresty/luajit2/tar.gz/v2.1-20190626 -O luajit_2_1.tar.gz\nwget https://codeload.github.com/openresty/lua-nginx-module/tar.gz/v0.10.15 -O ngx_lua.tar.gz\n\n# Creating deps directory\nmkdir -p nginx_devel_kit luajit nginx_lua\ntar --strip-components=1 -xf ngx_devel_kit_0_3_0.tar.gz -C nginx_devel_kit\ntar --strip-components=1 -xf luajit_2_1.tar.gz -C luajit\ntar --strip-components=1 -xf ngx_lua.tar.gz -C nginx_lua\n\n# Creating nginx\nbuild_tag=$1\nname=proxy\nnode=$2\norg=$3\n\ndocker build -t ${org}/${name}:${build_tag} .\necho {\\\"image_name\\\" : \\\"${name}\\\", \\\"image_tag\\\" : \\\"${build_tag}\\\", \\\"node_name\\\" : \\\"$node\\\"} > metadata.json\n" }, { "alpha_fraction": 0.704407274723053, "alphanum_fraction": 0.738601803779602, "avg_line_length": 37.70588302612305, "blob_id": "5b7b20a4aad1738c89d01655f5106c0b3966e1a2", "content_id": "c4256b3620432a14cab2342f39adec9ac42effce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1316, "license_type": "permissive", "max_line_length": 162, "num_lines": 34, "path": "/deploy/jenkins/jenkins-plugins-setup.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nbold=$(tput bold)\nnormal=$(tput sgr0)\n\nif [[ ! -d /var/lib/jenkins/.m2 ]]; then\necho -e \"\\n\\e[0;32m${bold}Downloading and copying m2 directory to Jenkins ${normal}\"\nwget https://sunbirdpublic.blob.core.windows.net/installation/m2-slim.tar\ntar -xf m2-slim.tar\nmv .m2 /var/lib/jenkins\nchown -R jenkins:jenkins /var/lib/jenkins/.m2\nelse\nwget https://sunbirdpublic.blob.core.windows.net/installation/m2-slim.tar\ntar -xf m2-slim.tar\ncp -rf .m2/* /var/lib/jenkins/.m2/\nchown -R jenkins:jenkins /var/lib/jenkins/.m2\nfi\n\necho -e \"\\n\\e[0;32m${bold}Downloading and copying jenkins plugin directory to Jenkins ${normal}\"\nif [[ ! -d /var/lib/jenkins/plugins ]]; then\nwget https://sunbirdpublic.blob.core.windows.net/installation/plugins-2-319-3.tar\ntar -xf plugins-2-319-3.tar\nmv plugins /var/lib/jenkins/\nchown -R jenkins:jenkins /var/lib/jenkins/plugins\nelse\nwget https://sunbirdpublic.blob.core.windows.net/installation/plugins-2-319-3.tar\ntar -xf plugins-2-319-3.tar\ncp -rf plugins/* /var/lib/jenkins/plugins/\nchown -R jenkins:jenkins /var/lib/jenkins/plugins\nfi\n\necho -e \"\\n\\e[0;32m${bold}Clean up${normal}\"\nrm -rf plugins.tar plugins m2-slim.tar\n\necho -e \"\\n\\e[0;32m${bold}Go to manage jenkins -> Plugin manager -> Update center -> Check status of installation OR Check the list of installed plugins${normal}\"\n" }, { "alpha_fraction": 0.5967402458190918, "alphanum_fraction": 0.6009463667869568, "avg_line_length": 34.22222137451172, "blob_id": "9be2235a94e1f5fab3d36972eb4c746661dcb7e4", "content_id": "8c0e811f6f862c9f42f680b3c3252363bfd71f48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1902, "license_type": "permissive", "max_line_length": 122, "num_lines": 54, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/keycloak_patch.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "import json\n\nfrom keycloak import KeycloakOpenID\nfrom keycloak import KeycloakAdmin\nimport urllib2, argparse, json\n\n# Create client\ndef keycloak_create_client(config):\n data = json.load(open(config['keycloak_clients']))\n \n # Get the existing clients\n keycloak_admin.realm_name = config['keycloak_realm'] \n clients = keycloak_admin.get_clients()\n \n # 1. Read the clients to be added from json\n # 2. Check if client already exists in keycloak\n # 3. Add the client if not exist\n for rec in data['clients']:\n client_exist_falg = 0\n for client in clients:\n if rec['clientId'] == client['clientId']:\n client_exist_falg = 1\n break\n if (client_exist_falg == 0):\n keycloak_admin.create_client(rec)\n print rec['clientId'] + \" client created\"\n else :\n print rec['clientId'] + \" client already exist\"\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Configure keycloak user apis')\n parser.add_argument('keycloak_bootstrap_config', help='configuration json file that is needed for keycloak bootstrap')\n args = parser.parse_args()\n\n with open(args.keycloak_bootstrap_config) as keycloak_bootstrap_config:\n config = json.load(keycloak_bootstrap_config)\n\n try:\n # Get access token\n keycloak_admin = KeycloakAdmin(server_url=config['keycloak_auth_server_url'],\n username=config['keycloak_management_user'],\n password=config['keycloak_management_password'],\n realm_name=\"master\",\n client_id='admin-cli',\n verify=False)\n \n\n # Create clients\n keycloak_create_client(config)\n\n except urllib2.HTTPError as e:\n error_message = e.read()\n print(error_message)\n raise\n" }, { "alpha_fraction": 0.6670135259628296, "alphanum_fraction": 0.8033298850059509, "avg_line_length": 33.32143020629883, "blob_id": "b8e8dfdd6351366a7893da13c91ded79b4472cf6", "content_id": "188d2c86609b94acf7b7a8033a463fef084a298a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 961, "license_type": "permissive", "max_line_length": 122, "num_lines": 28, "path": "/pipelines/build/nodebb/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM node:lts\nRUN mkdir -p /usr/src/app\nWORKDIR /usr/src/app\n\nARG NODE_ENV\nENV NODE_ENV $NODE_ENV\n\nCOPY NodeBB/install/package.json /usr/src/app/package.json\nCOPY NodeBB/ /usr/src/app\nRUN npm install --only=prod && \\\n npm cache clean --force\n\n\nRUN npm install https://github.com/Sunbird-Ed/nodebb-plugin-sunbird-oidc.git#7482a20a2c2670d4409ef936df35fd260293bcce\nRUN npm install https://github.com/Sunbird-Ed/nodebb-plugin-sunbird-api.git#105d83c0accf095115eced997aa7a756d9923a62\nRUN npm install https://github.com/Sunbird-Ed/nodebb-plugin-sunbird-telemetry.git#f6ae10182c881b6d05b1d29208ac2d328d920f11\nRUN npm install https://github.com/Sunbird-Ed/nodebb-plugin-azure-storage.git#3469f7a2169ab08bdc1c7b9b756b1405d387e9c6\nRUN npm install https://github.com/NodeBB/nodebb-plugin-write-api.git#cc795803a1c61042fc6eebeaabc89e4d8c233362\n\n\n\nENV NODE_ENV=production \\\n daemon=false \\\n silent=false\n\nEXPOSE 4567\n\nCMD node ./nodebb build ; node ./nodebb start\n" }, { "alpha_fraction": 0.6669968962669373, "alphanum_fraction": 0.6744976043701172, "avg_line_length": 29.5887451171875, "blob_id": "709915111e0345cc93affdaa4575a3ef807f8127", "content_id": "81fbdade923a2d80a17a1f4bc388aa27e5b8b5fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 7066, "license_type": "permissive", "max_line_length": 133, "num_lines": 231, "path": "/images/kong/plugins/0.12.3/jwt/handler.lua", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "local singletons = require \"kong.singletons\"\nlocal BasePlugin = require \"kong.plugins.base_plugin\"\nlocal responses = require \"kong.tools.responses\"\nlocal constants = require \"kong.constants\"\nlocal jwt_decoder = require \"kong.plugins.jwt.jwt_parser\"\n\nlocal ipairs = ipairs\nlocal string_format = string.format\nlocal ngx_re_gmatch = ngx.re.gmatch\nlocal ngx_set_header = ngx.req.set_header\nlocal get_method = ngx.req.get_method\n\nlocal JwtHandler = BasePlugin:extend()\n\nJwtHandler.PRIORITY = 1005\nJwtHandler.VERSION = \"0.1.0\"\n\n--- Retrieve a JWT in a request.\n-- Checks for the JWT in URI parameters, then in cookies, and finally\n-- in the `Authorization` header.\n-- @param request ngx request object\n-- @param conf Plugin configuration\n-- @return token JWT token contained in request (can be a table) or nil\n-- @return err\nlocal function retrieve_token(request, conf)\n local uri_parameters = request.get_uri_args()\n\n for _, v in ipairs(conf.uri_param_names) do\n if uri_parameters[v] then\n return uri_parameters[v]\n end\n end\n\n local ngx_var = ngx.var\n for _, v in ipairs(conf.cookie_names) do\n local jwt_cookie = ngx_var[\"cookie_\" .. v]\n if jwt_cookie and jwt_cookie ~= \"\" then\n return jwt_cookie\n end\n end\n\n local authorization_header = request.get_headers()[\"authorization\"]\n if authorization_header then\n local iterator, iter_err = ngx_re_gmatch(authorization_header, \"\\\\s*[Bb]earer\\\\s+(.+)\")\n if not iterator then\n return nil, iter_err\n end\n\n local m, err = iterator()\n if err then\n return nil, err\n end\n\n if m and #m > 0 then\n return m[1]\n end\n end\nend\n\nfunction JwtHandler:new()\n JwtHandler.super.new(self, \"jwt\")\nend\n\nlocal function load_credential(jwt_secret_key)\n local rows, err = singletons.dao.jwt_secrets:find_all {key = jwt_secret_key}\n if err then\n return nil, err\n end\n return rows[1]\nend\n\nlocal function load_consumer(consumer_id, anonymous)\n local result, err = singletons.dao.consumers:find { id = consumer_id }\n if not result then\n if anonymous and not err then\n err = 'anonymous consumer \"' .. consumer_id .. '\" not found'\n end\n return nil, err\n end\n return result\nend\n\nlocal function set_consumer(consumer, jwt_secret)\n ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id)\n ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)\n ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)\n ngx.ctx.authenticated_consumer = consumer\n\n if jwt_secret then\n ngx.ctx.authenticated_credential = jwt_secret\n ngx_set_header(constants.HEADERS.ANONYMOUS, nil) -- in case of auth plugins concatenation\n else\n ngx_set_header(constants.HEADERS.ANONYMOUS, true)\n end\n\nend\n\nlocal function do_authentication(conf)\n local token, err = retrieve_token(ngx.req, conf)\n if err then\n return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)\n end\n\n local ttype = type(token)\n if ttype ~= \"string\" then\n if ttype == \"nil\" then\n return false, {status = 401}\n elseif ttype == \"table\" then\n return false, {status = 401, message = \"Multiple tokens provided\"}\n else\n return false, {status = 401, message = \"Unrecognizable token\"}\n end\n end\n -- Decode token to find out who the consumer is\n local jwt, err = jwt_decoder:new(token)\n if err then\n -- Don't sent Bad Token for null / empty Bearer tokens\n return false, {status = 401}\n end\n\n local claims = jwt.claims\n\n local jwt_secret_key = claims[conf.key_claim_name]\n if not jwt_secret_key then\n return false, {status = 401, message = \"No mandatory '\" .. conf.key_claim_name .. \"' in claims\"}\n end\n\n -- If the bearer key contains a kid, change the secret key\n if jwt.header.kid then\n jwt_secret_key = jwt.header.kid\n end\n\n -- Retrieve the secret\n local jwt_secret_cache_key = singletons.dao.jwt_secrets:cache_key(jwt_secret_key)\n local jwt_secret, err = singletons.cache:get(jwt_secret_cache_key, nil,\n load_credential, jwt_secret_key)\n if err then\n return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)\n end\n\n if not jwt_secret then\n return false, {status = 403, message = \"No credentials found for given '\" .. conf.key_claim_name .. \"'\"}\n end\n\n local algorithm = jwt_secret.algorithm or \"HS256\"\n\n -- Verify \"alg\"\n if jwt.header.alg ~= algorithm then\n return false, {status = 403, message = \"Invalid algorithm\"}\n end\n\n local jwt_secret_value = algorithm == \"HS256\" and jwt_secret.secret or jwt_secret.rsa_public_key\n if conf.secret_is_base64 then\n jwt_secret_value = jwt:b64_decode(jwt_secret_value)\n end\n\n if not jwt_secret_value then\n return false, {status = 403, message = \"Invalid key/secret\"}\n end\n\n -- Now verify the JWT signature\n if not jwt:verify_signature(jwt_secret_value) then\n return false, {status = 403, message = \"Invalid signature\"}\n end\n\n -- Verify the JWT registered claims\n local ok_claims, errors = jwt:verify_registered_claims(conf.claims_to_verify)\n if not ok_claims then\n return false, {status = 401, message = errors}\n end\n\n -- Retrieve the consumer\n local consumer_cache_key = singletons.dao.consumers:cache_key(jwt_secret.consumer_id)\n local consumer, err = singletons.cache:get(consumer_cache_key, nil,\n load_consumer,\n jwt_secret.consumer_id, true)\n if err then\n return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)\n end\n\n -- However this should not happen\n if not consumer then\n return false, {status = 403, message = string_format(\"Could not find consumer for '%s=%s'\", conf.key_claim_name, jwt_secret_key)}\n end\n\n-- Restore the orignal key and update the id post operation\n if jwt.header.kid then\n jwt_secret.id = jwt.claims[\"iss\"]\n jwt_secret.key = jwt.claims[\"iss\"]\n end\n\n set_consumer(consumer, jwt_secret)\n\n return true\nend\n\n\nfunction JwtHandler:access(conf)\n JwtHandler.super.access(self)\n\n -- check if preflight request and whether it should be authenticated\n if not conf.run_on_preflight and get_method() == \"OPTIONS\" then\n return\n end\n\n if ngx.ctx.authenticated_credential and conf.anonymous ~= \"\" then\n -- we're already authenticated, and we're configured for using anonymous,\n -- hence we're in a logical OR between auth methods and we're already done.\n return\n end\n\n local ok, err = do_authentication(conf)\n if not ok then\n if conf.anonymous ~= \"\" then\n -- get anonymous user\n local consumer_cache_key = singletons.dao.consumers:cache_key(conf.anonymous)\n local consumer, err = singletons.cache:get(consumer_cache_key, nil,\n load_consumer,\n conf.anonymous, true)\n if err then\n return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)\n end\n set_consumer(consumer, nil)\n else\n return responses.send(err.status, err.message)\n end\n end\nend\n\n\nreturn JwtHandler\n" }, { "alpha_fraction": 0.7237237095832825, "alphanum_fraction": 0.7289789915084839, "avg_line_length": 32.29999923706055, "blob_id": "1bb78a13fce0396e1056ddb73375789aaf48d41a", "content_id": "e1b9eba69cf6939e71ed32fd12e186014a3c5cb4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1332, "license_type": "permissive", "max_line_length": 143, "num_lines": 40, "path": "/deploy/certbot.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -e\n\n# This script won't work for aws, as it's black listed\n\necho -e \"This script won't work for aws, as it's black listed in letsencrypt\\nso if youre running on aws please press ctrl+c with in 5 seconds\"\n\nsleep 5\n\necho please enter your dns name : \nread dns_name\nssh_ansible_user=$(whoami)\ncertbot_home=/etc/letsencrypt/archive/$dns_name\n\n\n#Check certbot installed or not\nif [ $(which certbot) ]; then\n echo \"certbot is already installed\"\nelse\n sudo apt-get update\n sudo apt-get install -y software-properties-common\n sudo add-apt-repository ppa:certbot/certbot\n sudo apt-get update\n sudo apt-get install -y certbot\nfi\n\nsudo certbot certonly --standalone -d $dns_name\n\nsudo cp $certbot_home/privkey1.pem /home/$ssh_ansible_user/site.key\nsudo cp $certbot_home/fullchain1.pem /home/$ssh_ansible_user/site.crt\nsudo chown -R $ssh_ansible_user:$ssh_ansible_user /home/$ssh_ansible_user/site.key /home/$ssh_ansible_user/site.crt\nsudo chmod 775 /home/$ssh_ansible_user/site.crt /home/$ssh_ansible_user/site.key\n\n\necho -e \"Please take a note of these, and fill it up in config file: \\\n \\n\\n dns_name: $dns_name \\n\n cert_path: /home/$ssh_ansible_user/site.crt \\n\n key_path: /home/$ssh_ansible_user/site.key\\n\n!!! please remove certs after the installation process. or keep it in a safe place.\"\n" }, { "alpha_fraction": 0.6365747451782227, "alphanum_fraction": 0.6481857895851135, "avg_line_length": 54.119998931884766, "blob_id": "ff807c826d6b3079b1e5138638bd9694a79e44fb", "content_id": "41f009f3f96ba840837140b2a45415db9816a620", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 6890, "license_type": "permissive", "max_line_length": 854, "num_lines": 125, "path": "/deploy/jenkins/jenkins-jobs-setup.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nbold=$(tput bold)\nnormal=$(tput sgr0)\ntoday=$(date +%Y-%m-%d-%H-%M-%S)\nJENKINS_TMP=/tmp/$today\nenvOrder=\"/dev/null\"\n\nsetupJobs(){\n declare -A arr\n while IFS=\"\" read -r line; do\n key=$(echo $line | awk -F \"=\" '{print $1}')\n value=$(echo $line | awk -F \"=\" '{print $2}')\n arr[$value]=$key\n done < $envOrder\n mkdir $JENKINS_TMP\n rsync -r jobs/* $JENKINS_TMP\n if [[ ${arr[0]} != \"dev\" ]]; then\n mv $JENKINS_TMP/ArtifactUpload/jobs/dev $JENKINS_TMP/ArtifactUpload/jobs/${arr[0]}\n mv $JENKINS_TMP/Deploy/jobs/dev $JENKINS_TMP/Deploy/jobs/${arr[0]}\n mv $JENKINS_TMP/OpsAdministration/jobs/dev $JENKINS_TMP/OpsAdministration/jobs/${arr[0]}\n mv $JENKINS_TMP/Provision/jobs/dev $JENKINS_TMP/Provision/jobs/${arr[0]}\n find $JENKINS_TMP/Deploy/jobs/${arr[0]} -type f -name config.xml -exec sed -i \"s#ArtifactUpload/dev/#ArtifactUpload/${arr[0]}/#g\" {} \\;\n find $JENKINS_TMP/Deploy/jobs/${arr[0]} -type f -name config.xml -exec sed -i \"s#Deploy/dev/#Deploy/${arr[0]}/#g\" {} \\;\n fi\n find $JENKINS_TMP/Deploy/jobs/${arr[0]} -type d -path \"*Summary*\" -prune -o -name config.xml -exec sed -i 's#<upstreamProjects>.*##g' {} \\;\n find $JENKINS_TMP/Build/jobs -type f -name config.xml -exec sed -i 's#refs/heads/${public_repo_branch}##g' {} \\;\n find $JENKINS_TMP/Build/jobs -type f -name config.xml -exec sed -i 's#use refs/tags/github_tag#specify the github tag#g' {} \\;\n find $JENKINS_TMP/Build/jobs -type f -name config.xml -exec sed -i 's#use refs/heads/github_branch#specify the github branch#g' {} \\;\n find $JENKINS_TMP/Build/jobs -type f -name config.xml -exec sed -i '/The default value of/d' {} \\;\n find $JENKINS_TMP/Build/jobs -type f -name config.xml -exec sed -i '/To build from a differnt branch/d' {} \\;\n\n echo -e \"\\e[0;33m${bold}Jobs created for ${arr[0]}${normal}\"\n\n for key in \"${!arr[@]}\"; do\n if [[ $key -eq 0 ]]; then\n continue\n fi\n cp -r $JENKINS_TMP/Provision/jobs/${arr[0]} $JENKINS_TMP/Provision/jobs/${arr[$key]}\n cp -r $JENKINS_TMP/OpsAdministration/jobs/${arr[0]} $JENKINS_TMP/OpsAdministration/jobs/${arr[$key]}\n cp -r $JENKINS_TMP/Deploy/jobs/${arr[0]} $JENKINS_TMP/Deploy/jobs/${arr[$key]}\n find $JENKINS_TMP/Deploy/jobs/${arr[$key]} -type f -name config.xml -exec bash -c 'configPath=$0; jobPath=$(dirname $configPath); jobName=$(basename $jobPath); modulePath=${jobPath%/*/*}; moduleName=$(basename $modulePath); sed -i \"s#ArtifactUpload/$1/$moduleName/.*<#Deploy/$2/$moduleName/$jobName<#g\" $0' {} ${arr[0]} ${arr[$(($key - 1))]} \\;\n find $JENKINS_TMP/Deploy/jobs/${arr[$key]} -type d -path \"*Summary*\" -prune -o -name config.xml -exec sed -i 's#<upstreamProjects>.*##g' {} \\;\n find $JENKINS_TMP/Deploy/jobs/${arr[$key]}/jobs/Summary/jobs/DeployedVersions -type f -name config.xml -exec sed -i \"s#Deploy/${arr[0]}/#Deploy/${arr[$key]}/#g\" {} \\;\n echo -e \"\\e[0;33m${bold}Jobs created for ${arr[$key]}${normal}\"\n done\n echo -e \"\\e[0;36m${bold}Do you want to disable auto trigger of build jobs based on new commits?${normal}\"\n read -p 'y/n: ' choice\n if [[ $choice == \"y\" ]]; then\n find $JENKINS_TMP/Build -type f -name config.xml -exec sed -i 's#<spec>.*</spec>#<spec></spec>#g' {} \\;\n find $JENKINS_TMP/Deploy -type f -name config.xml -exec sed -i 's#<spec>.*</spec>#<spec></spec>#g' {} \\;\n fi\n echo -e \"\\e[0;36m${bold}Do you want to disable daily backup jobs (Ex: DB backups)?${normal}\"\n read -p 'y/n: ' choice\n if [[ $choice == \"y\" ]]; then\n find $JENKINS_TMP/OpsAdministration -type f -name config.xml -exec sed -i 's#<spec>.*</spec>#<spec></spec>#g' {} \\;\n fi\n find $JENKINS_TMP/Build -type f -name config.xml -exec sed -i 's#<upstreamProjects>.*##g' {} \\;\n find $JENKINS_TMP -type f -name config.xml -exec sed -i 's#<sandbox>false</sandbox>#<sandbox>true</sandbox>#g' {} \\;\n diffs=$(colordiff -r --suppress-common-lines --no-dereference -x 'nextBuildNumber' -x 'builds' -x 'last*' /var/lib/jenkins/jobs $JENKINS_TMP | wc -l)\n if [[ $diffs -eq 0 ]]; then\n echo -e \"\\e[0;33m${bold}No changes detected. Exiting...${normal}\"\n exit\n fi\n colordiff -r --suppress-common-lines --no-dereference -x 'nextBuildNumber' -x 'builds' -x 'last*' --suppress-blank-empty --ignore-tab-expansion --ignore-trailing-space --ignore-space-change --ignore-matching-lines='<com.cloudbees' --ignore-matching-lines='<org.jenkinsci' --ignore-matching-lines='<registry plugin' --ignore-matching-lines='<flow-definition' --ignore-matching-lines='<com.sonyericsson' --ignore-matching-lines='<org.biouno' --ignore-matching-lines='<secureScript' --ignore-matching-lines='<secureFallbackScript' --ignore-matching-lines='<hudson.plugins' --ignore-matching-lines='<definition class' --ignore-matching-lines='<scm class' --ignore-matching-lines='</flow' --ignore-matching-lines='<configVersion>' --ignore-matching-lines='<visibleItemCount>' --ignore-matching-lines='<parameters class' /var/lib/jenkins/jobs $JENKINS_TMP\n echo -e \"\\e[0;33m${bold}Please review the changes shown. Proceed with overwriting the changes?${normal}\"\n}\n\nsyncJobs(){\nread -p 'YES/NO: ' changes\necho -e \"\\e[0;33m${bold}This might take a while... Do not kill the process!${normal}\"\n if [[ $changes == \"YES\" ]]; then\n rsync -r $JENKINS_TMP/* /var/lib/jenkins/jobs\n chown -R jenkins:jenkins /var/lib/jenkins/jobs\n echo -e \"\\e[0;32m${bold}Setup complete!${normal}\"\n else\n echo -e \"\\e[0;31m${bold}Aborted!${normal}\"\n fi\n}\n\n\nfirstRun(){\nchoice=\"n\"\nenvOrder=envOrder.txt\ncat $envOrder\necho -e \"\\e[0;36m${bold}Is this the correct order? Jobs will be created and configured based on this order.${normal}\"\nread -p 'y/n: ' choice\nif [[ $choice == \"y\" ]]; then\n setupJobs\n syncJobs\n cp $envOrder /var/lib/jenkins\n chown -R jenkins:jenkins /var/lib/jenkins/$envOrder\nelse\n echo -e \"\\e[0;31m${bold}Please update the envOrder.txt and re-run..${normal}\"\nfi\n}\n\nupdateRun(){\nchoice=\"n\"\nenvOrder=/var/lib/jenkins/envOrder.txt \ncat $envOrder\necho -e \"\\e[0;36m${bold}Is this the current order? Choose n if you want to add a new environment.${normal}\"\nread -p 'y/n: ' choice\nif [[ $choice == \"n\" ]]; then\n rm -rf $envOrder\n echo -e \"\\e[0;31m${bold}Please update the envOrder.txt and re-run from sunbird-devops/deploy/jenkins directory.\"\nelif [[ $choice == \"y\" ]]; then\n setupJobs\n syncJobs\nelse\n echo -e \"\\e[0;31m${bold}Aborted!${normal}\" \nfi\n}\n\necho -e \"\\e[0;33m${bold}**** Welcome to Jenkins config setup! ****${normal}\"\nif [[ ! -f /var/lib/jenkins/envOrder.txt ]]; then\n if [[ ! -f ./envOrder.txt ]]; then\n echo -e \"\\e[0;31m${bold}Please create a file named envOrder.txt with your environment order. Refer envOrder.txt.sample for reference\"\n else\n echo -e \"\\e[0;33m${bold}Starting setup...${normal}\"\n firstRun\n fi\nelse\n echo -e \"\\e[0;33m${bold}Checking for updates...${normal}\"\n updateRun\nfi\n" }, { "alpha_fraction": 0.7621951103210449, "alphanum_fraction": 0.7662601470947266, "avg_line_length": 43.6363639831543, "blob_id": "f3c7fd2640e73e32b30ee47c51251a227992f3fa", "content_id": "eeea05d0e4a55df16f7f5e47493aa887868258be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 492, "license_type": "permissive", "max_line_length": 134, "num_lines": 11, "path": "/images/certbot-updater/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "\nFROM alpine:latest\nLABEL maintainer=\"[email protected]\"\nRUN apk update\n\nRUN apk add --no-cache curl certbot\n#Oneliner due to the use of release as variable for wget which is previously curled\nRUN export release=$(curl https://storage.googleapis.com/kubernetes-release/release/stable.txt); \\\n curl https://storage.googleapis.com/kubernetes-release/release/$release/bin/linux/amd64/kubectl --output /usr/local/bin/kubectl; \\\n chmod +x /usr/local/bin/kubectl\n\nENTRYPOINT [\"/usr/local/bin/kubectl\"]\n" }, { "alpha_fraction": 0.43760624527931213, "alphanum_fraction": 0.4440666437149048, "avg_line_length": 44.24615478515625, "blob_id": "d113f9026afe3e76f8c583608e07a2acf7fa76de", "content_id": "2ada0b3ae8ba9c6832a7afa78460f8908627a621", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2941, "license_type": "permissive", "max_line_length": 185, "num_lines": 65, "path": "/deploy/statusChecks.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# Author S M Y ALTAMASH <[email protected]>\nimport sys\nimport subprocess\nimport multiprocessing\nfrom urllib.request import Request, urlopen\nfrom urllib.error import URLError, HTTPError\nimport csv\n\nprotocol=sys.argv[1]\nserverIP=sys.argv[2]\n\ndef checkStatus(req,name):\n try:\n response = urlopen(req)\n print(str(name) + ' ' + str(\" is working\"))\n #print(\"HTTP Header:\\n\" .join(str(response.headers).split(\"\\n\")[:-1]))\n print(\"HTTP Header:\")\n print(str(response.headers).rsplit(\"\\n\", 2)[0])\n print(\"HTTP Response Status code: \"+str(response.status))\n # print(response.info())\n except HTTPError as e:\n print('The server couldn\\'t fulfill the request.')\n print('Error code: ', e.code)\n except URLError as e:\n print('We failed to reach a server.')\n print('Reason: ', e.reason)\n\ndef checkAvailibility():\n with open(\"ServiceDetails.csv\",\"r\") as k:\n reading=csv.reader(k)\n for data in reading:\n try:\n ServiceName,Port,AdditionalURL=data\n if ServiceName == \"ServiceName\" and Port == \"Port\" and AdditionalURL == \"AdditionalURL\":\n continue\n name=ServiceName\n print(\"\\n\\nService name: \" +str(name))\n if Port == \"\":\n req=\"{}://{}{}\".format(protocol,serverIP,AdditionalURL)\n else:\n req=\"{}://{}:{}{}\".format(protocol,serverIP,Port,AdditionalURL)\n\n p = multiprocessing.Process(target=checkStatus(req,name))\n p.start()\n p.join(5)\n if p.is_alive():\n print(str(k) + ' ' + str(' is not Working'))\n p.terminate()\n p.join(5) \n except Exception as e:\n continue\n\ndef checkContainerReplication():\n print(\"Checking Container Replication:-\\n\")\n reslt=(subprocess.check_output(\"sudo docker service ls | awk 'NR>1{print $2,$4 }' | sed 's/\\// /g'| awk '($2!=$3) || (($2==0) && ($3==0)){ print $1}'\", shell=True)).splitlines()\n for val in reslt:\n print(\"Container \"+str(val,\"utf-8\")+\" Failed to replicate\")\n\nprint(\"\\n-----------------------------------------\\n\")\ncheckContainerReplication()\nprint(\"\\n-----------------------------------------\\n\")\nprint(\"Checking The service status:-\\n\")\ncheckAvailibility()\nprint(\"\\n-----------------------------------------\\n\")\n" }, { "alpha_fraction": 0.6871165633201599, "alphanum_fraction": 0.7177914381027222, "avg_line_length": 31.600000381469727, "blob_id": "9f5917e3553b630180ba41c557f0180775f0bd21", "content_id": "f4fbcb0a09b57a42880166ecd4ec05fc29803b9b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 163, "license_type": "permissive", "max_line_length": 63, "num_lines": 5, "path": "/exporters/Go/kafka-topic-exporter/build.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# vim: set ts=4 sw=4 tw=0 et :\n#!/bin/bash\n\nCGO_ENABLED=0 go build -o kafka-topic-exporter main.go\ndocker build -f Dockerfile -t sunbird/kafka-topic-exporter:v1 .\n" }, { "alpha_fraction": 0.7722222208976746, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 35, "blob_id": "78d679403241f40d9a98a6a03f230019db7b149b", "content_id": "9dca12f86d7dc8e3e37e53cc9c3b6477175ea18e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 180, "license_type": "permissive", "max_line_length": 50, "num_lines": 5, "path": "/images/docker-registry/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM registry:2\nCOPY images/docker-registry/docker-entrypoint.sh .\nRUN chmod a+x docker-entrypoint.sh\nENTRYPOINT [\"./docker-entrypoint.sh\"]\nCMD [\"/etc/docker/registry/config.yml\"]\n" }, { "alpha_fraction": 0.7094339728355408, "alphanum_fraction": 0.7150943279266357, "avg_line_length": 23.090909957885742, "blob_id": "a74a28e60cdf9f32afa79a1f1f253462475d6e1a", "content_id": "8290530523118d8f3e0300ee3617b710140a6cb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 530, "license_type": "permissive", "max_line_length": 58, "num_lines": 22, "path": "/pipelines/deploy/player/build-cdn.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Build script\n# set -o errexit\nset -x\n\nsed -i '/jessie-updates/d' /etc/apt/sources.list\napt update && apt install git python make g++ jq zip -y\nsu jenkins\ncd src/app\nversion=$(jq '.version' package.json | sed 's/\\\"//g')\ncdnUrl=$1\nbuild_hash=$2\nartifact_version=$3\nnpm install\n./node_modules/.bin/gulp download:editors\ncd client\nnpm install\nnpm run build-cdn -- --deployUrl $cdnUrl\ncd ..\n# Gzipping of assets\n./node_modules/.bin/gulp gzip:editors client:gzip\nmv dist/index.html dist/index.${version}.${build_hash}.ejs\n" }, { "alpha_fraction": 0.6376811861991882, "alphanum_fraction": 0.695652186870575, "avg_line_length": 12.866666793823242, "blob_id": "dce3526cf528e3bd2bdc66505a2092445327c91d", "content_id": "cb308bfa0553bee26510557d308b088f9eb4b7dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 207, "license_type": "permissive", "max_line_length": 71, "num_lines": 15, "path": "/images/echo-server/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# Echo server\n\nA simple echo server using python alpine image to echo the request path\n\n### How to run\n\n```\ndocker run -p 9595:9595 sunbird/echo-server:latest\n```\n\n### Test\n\n```\ncurl localhost:9595/hello\n```" }, { "alpha_fraction": 0.622710645198822, "alphanum_fraction": 0.6299145221710205, "avg_line_length": 59.66666793823242, "blob_id": "f01e0a56dd54a0bcb5ea72508e208abd2d7a5f0d", "content_id": "4d299c8eccbadc9b84c60ce3191e858412641e57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8190, "license_type": "permissive", "max_line_length": 547, "num_lines": 135, "path": "/kubernetes/helm_charts/monitoring/prometheus-redis-exporter/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# prometheus-redis-exporter\n\n[redis_exporter](https://github.com/oliver006/redis_exporter) is a Prometheus exporter for Redis metrics.\n\n## TL;DR;\n\n```bash\n$ helm install stable/prometheus-redis-exporter\n```\n\n## Introduction\n\nThis chart bootstraps a [redis_exporter](https://github.com/oliver006/redis_exporter) deployment on a [Kubernetes](http://kubernetes.io) cluster using the [Helm](https://helm.sh) package manager.\n\n## Prerequisites\n\n- Kubernetes 1.10+ with Beta APIs enabled\n\n## Installing the Chart\n\nTo install the chart with the release name `my-release`:\n\n```bash\n$ helm install --name my-release stable/prometheus-redis-exporter\n```\n\nThe command deploys prometheus-redis-exporter on the Kubernetes cluster in the default configuration.\n\n## Uninstalling the Chart\n\nTo uninstall/delete the `my-release` deployment:\n\n```bash\n$ helm delete my-release\n```\n\nThe command removes all the Kubernetes components associated with the chart and deletes the release.\n\n## Configuration\n\nThe following table lists the configurable parameters and their default values.\n\n| Parameter | Description | Default |\n| ---------------------- | --------------------------------------------------- | ------------------------- |\n| `replicaCount` | desired number of prometheus-redis-exporter pods | `1` |\n| `image.repository` | prometheus-redis-exporter image repository | `oliver006/redis_exporter`|\n| `image.tag` | prometheus-redis-exporter image tag | `v1.3.4` |\n| `image.pullPolicy` | image pull policy | `IfNotPresent` |\n| `image.pullSecrets` | image pull secrets | {} |\n| `extraArgs` | extra arguments for the binary; possible values [here](https://github.com/oliver006/redis_exporter#flags)| {}\n| `env` | additional environment variables in YAML format. Can be used to pass credentials as env variables (via secret) as per the image readme [here](https://github.com/oliver006/redis_exporter#environment-variables) | {} |\n| `resources` | cpu/memory resource requests/limits | {} |\n| `tolerations` | toleration labels for pod assignment | {} |\n| `affinity` | affinity settings for pod assignment | {} |\n| `service.type` | desired service type | `ClusterIP` |\n| `service.port` | service external port | `9121` |\n| `service.annotations` | Custom annotations for service | `{}` |\n| `service.labels` | Additional custom labels for the service | `{}` |\n| `redisAddress` | Address of the Redis instance to scrape. Use `rediss://` for SSL. | `redis://myredis:6379` |\n| `annotations` | pod annotations for easier discovery | {} |\n| `rbac.create` | Specifies whether RBAC resources should be created.| `true` |\n| `rbac.pspEnabled` | Specifies whether a PodSecurityPolicy should be created.| `true` |\n| `serviceAccount.create` | Specifies whether a service account should be created.| `true` |\n| `serviceAccount.name` | Name of the service account.| |\n| `serviceMonitor.enabled` | Use servicemonitor from prometheus operator | `false` |\n| `serviceMonitor.namespace` | Namespace this servicemonitor is installed in | |\n| `serviceMonitor.interval` | How frequently Prometheus should scrape | |\n| `serviceMonitor.telemetryPath` | Path to redis-exporter telemtery-path | |\n| `serviceMonitor.labels` | Labels for the servicemonitor passed to Prometheus Operator | `{}` |\n| `serviceMonitor.timeout` | Timeout after which the scrape is ended | |\n| `serviceMonitor.targetLabels` | Set of labels to transfer on the Kubernetes Service onto the target. | |\n| `prometheusRule.enabled` | Set this to true to create prometheusRules for Prometheus operator | `false` |\n| `prometheusRule.additionalLabels` | Additional labels that can be used so prometheusRules will be discovered by Prometheus | `{}` |\n| `prometheusRule.namespace` | namespace where prometheusRules resource should be created | |\n| `prometheusRule.rules` | [rules](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) to be created, check values for an example. | `[]` |\n| `script.configmap` | Let you run a custom lua script from a configmap. The corresponding environment variable `REDIS_EXPORTER_SCRIPT` will be set automatically ||\n| `script.keyname` | Name of the key inside configmap which contains your script ||\n| `auth.enabled` | Specifies whether redis uses authentication | `false` |\n| `auth.secret.name` | Name of existing redis secret (ignores redisPassword) ||\n| `auth.secret.key` | Name of key containing password to be retrieved from the existing secret ||\n| `auth.redisPassword` | Redis password (when not stored in a secret) ||\n\nFor more information please refer to the [redis_exporter](https://github.com/oliver006/redis_exporter) documentation.\n\nSpecify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example,\n\n```bash\n$ helm install --name my-release \\\n --set \"redisAddress=redis://myredis:6379\" \\\n stable/prometheus-redis-exporter\n```\n\nAlternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example,\n\n```bash\n$ helm install --name my-release -f values.yaml stable/prometheus-redis-exporter\n```\n### Using a custom LUA-Script\nFirst, you need to deploy the script with a configmap. This is an example script from mentioned in the [redis_exporter-image repository](https://github.com/oliver006/redis_exporter/blob/master/contrib/sample_collect_script.lua)\n```yaml\napiVersion: v1\nkind: ConfigMap\nmetadata:\n name: prometheus-redis-exporter-script\ndata:\n script: |-\n -- Example collect script for -script option\n -- This returns a Lua table with alternating keys and values.\n -- Both keys and values must be strings, similar to a HGETALL result.\n -- More info about Redis Lua scripting: https://redis.io/commands/eval\n\n local result = {}\n\n -- Add all keys and values from some hash in db 5\n redis.call(\"SELECT\", 5)\n local r = redis.call(\"HGETALL\", \"some-hash-with-stats\")\n if r ~= nil then\n for _,v in ipairs(r) do\n table.insert(result, v) -- alternating keys and values\n end\n end\n\n -- Set foo to 42\n table.insert(result, \"foo\")\n table.insert(result, \"42\") -- note the string, use tostring() if needed\n\n return result\n```\nIf you want to use this script for collecting metrics, you could do this by just set `script.configmap` to the name of the configmap (e.g. `prometheus-redis-exporter-script`) and `script.keyname` to the configmap-key holding the script (eg. `script`). The required variables inside the container will be set automatically.\n\n## Upgrading\n\n### To 3.0.1\n\n The default tag for the exporter image is now `v1.x.x`. This major release includes changes to the names of various metrics and no longer directly supports the configuration (and scraping) of multiple redis instances; that is now the Prometheus server's responsibility. You'll want to use [this dashboard](https://github.com/oliver006/redis_exporter/blob/master/contrib/grafana_prometheus_redis_dashboard.json) now. Please see the [redis_exporter github page](https://github.com/oliver006/redis_exporter#upgrading-from-0x-to-1x) for more details.\n" }, { "alpha_fraction": 0.8085106611251831, "alphanum_fraction": 0.8085106611251831, "avg_line_length": 46, "blob_id": "d1af7b3a0aaeeb091fe0dec79401919fec46da43", "content_id": "ae5d8b22d4d2639b2fab8fa312d400c1691a6ba1", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 47, "license_type": "permissive", "max_line_length": 46, "num_lines": 1, "path": "/ansible/roles/postgres-migration/files/sunbird_programs/V4.2.0.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "ALTER TYPE programtype ADD VALUE 'restricted';\n" }, { "alpha_fraction": 0.7469879388809204, "alphanum_fraction": 0.7469879388809204, "avg_line_length": 33.66666793823242, "blob_id": "73699edbbfb0ec95371e9f9c6f26a68af5ae2bcb", "content_id": "e7173bd2455a67b531ca3da5f72ec24635aa3ac2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 419, "license_type": "permissive", "max_line_length": 89, "num_lines": 12, "path": "/deploy/backup_postgres.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\npostgresql_backup_dir=/tmp/postgresql-backup\nif [ -f $postgresql_backup_dir ]\nthen\n echo “directory already exists”\nelse\n mkdir $postgresql_backup_dir\nfi\n\npostgresql_backup_gzip_file_name=\"postgresql_backup_`date +%Z-%Y-%m-%d-%H-%M-%S`.txt\"\npostgresql_backup_gzip_file_path=$postgresql_backup_dir/$postgresql_backup_gzip_file_name\nsudo su postgres -c 'pg_dumpall' > $postgresql_backup_gzip_file_path" }, { "alpha_fraction": 0.6819728016853333, "alphanum_fraction": 0.7176870703697205, "avg_line_length": 33.588233947753906, "blob_id": "36da35de0b6f295ddde7e2d8c21d3758031f82fb", "content_id": "abb3612f631cbca3b6659e70cde61b75c2b42157", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 588, "license_type": "permissive", "max_line_length": 283, "num_lines": 17, "path": "/kubernetes/opa-plugins/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# opa-plugins\n\n> OPA version - 0.34.2\n#### Build opa binary\n```\nexport today=$(date --iso-8601=seconds)\ngo mod tidy\ngo mod vendor\ngo build -o opa -ldflags \"-X 'github.com/open-policy-agent/opa/version.Version=0.34.2' -X 'github.com/open-policy-agent/opa/version.Vcs=9f11f21' -X 'github.com/open-policy-agent/opa/version.Timestamp=$today' -X 'github.com/open-policy-agent/opa/version.Hostname=sunbird'\" cmd/main.go\n```\n\n\n#### Build Docker Image\n- To build the docker image run\n```\ndocker build -t docker_user_name/opa:0.34.2-envoy --build-arg BASE=gcr.io/distroless/cc -f Dockerfile .\n```\n" }, { "alpha_fraction": 0.6163636445999146, "alphanum_fraction": 0.6369696855545044, "avg_line_length": 34.869564056396484, "blob_id": "f274b9c34776739cd8122812edb5210f3e2f7cce", "content_id": "0c3beafb35a00d25d9eb6f1085af444a3c1497dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1650, "license_type": "permissive", "max_line_length": 221, "num_lines": 46, "path": "/deploy/gitOPS/prinfo.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#reading date arguments and github username from command line and converting into string \nd1=$(date -d \"$1 00:00:00\" +%s) \nd2=$(date -d \"$2 23:59:59\" +%s)\ngitUser=$6\nusername=$3\npassword=$4\n#reading reponame from jenkins\nrepo=$(echo $repositories | tr ',' '\\n') \n\necho \"$repo\" | while read repo_line\n do\n\techo $repo_line\n\t#getting pull request id list\n\tprlist=$(curl -s -u $username:$password https://api.github.com/repos/$5/$repo_line/pulls\\?state\\=all\\&page=1\\&per_page=10 | jq -r '.[].number')\n\techo \"REPO_NAME,PR_ID,RAISED_BY,CREATED_AT,STATE,MERGED_BY,MERGED_AT,NO.OF_COMMITS,NO.FILES_CHANGED\" > prinfo.csv\n\n\necho \"$prlist\" | while read LINE\n\tdo\n\t\t#passing pull request id to get full info\n\t\tpr_info=$(curl -s -u $username:$password https://api.github.com/repos/$5/$repo_line/pulls/$LINE | jq -r '.base.repo.name,.user.login,.created_at,.state,.merged_by.login,.merged_at,.commits,.changed_files' | tr '\\n' ' ')\n\t\techo $LINE $pr_info | tr ' ' ',' >> tmpFile\n\t\t\n\tdone\n\n#reading file and list PR based on start and end date\ncat tmpFile | while read pr_line\n do\n \tdate=$(echo $pr_line | awk -F, '{sub(/T.*/,\"\",$3);print}' OFS=, | awk -F ',' '{print $4}')\n\tdate=$(date -d \"$date\" +%s)\n\t\tif [[ $date -ge $d1 && $date -le $d2 ]]\n\t\tthen\n\t\t\techo $pr_line | awk -F, ' { t = $1; $1 = $2; $2 = t; print; }' OFS=, >> prinfo.csv\n\t\tfi\n done\n\necho \"REPO_NAME,PR_ID,RAISED_BY,CREATED_AT,STATE,MERGED_BY,MERGED_AT,NO.OF_COMMITS,NO.FILES_CHANGED\" > $gitUser.csv\n#grouping PR's by username\nif [[ $gitUser == \"\" ]]; then\n\tcontinue;\nelse\n\tcat prinfo.csv | awk -v var=\"$gitUser\" -F, '{ if ($3==var) print $0}' >> $gitUser.csv\nfi\ncp *.csv ../../\ndone\n" }, { "alpha_fraction": 0.6159574389457703, "alphanum_fraction": 0.6436170339584351, "avg_line_length": 20.363636016845703, "blob_id": "49d72329e7c104188bb2891b6a471c11e2c006ff", "content_id": "575fd669e270382be9f1da100e8e44960244567d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 940, "license_type": "permissive", "max_line_length": 87, "num_lines": 44, "path": "/kubernetes/ansible/static-files/health.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n#apk update curl\n#apk add curl\n#apk update jq\n#apk add jq\noutpt1=$(curl -s content-service:5000/health | jq '.result.healthy')\noutpt2=$(curl -s player_player:3000/health| jq '.result.healthy')\noutpt3=$(curl -s learner-service:9000/health | jq '.result.response.checks[0].healthy')\noutpt4=$(curl -s lms-service:9005/health | jq '.result.response.checks[0].healthy')\necho \"\"\necho \"\"\nif [ \"$outpt1\" == \"true\" ];then\n echo \"content service is Healthy\"\nelse\n echo \"content service is unhealthy\"\nfi\n\necho \"\"\necho \"\"\n\nif [ \"$outpt2\" == \"true\" ];then\n echo \"Player Service is Healthy\"\nelse\n echo \"Player Service is unhealthy\"\nfi\n\necho \"\"\necho \"\"\n\nif [ \"$outpt3\" == \"true\" ];then\n echo \"Learner Service is Healthy\"\nelse\n echo \"Learner Service is unhealthy\"\nfi\n\necho \"\"\necho \"\"\n\nif [ \"$outpt4\" == \"true\" ];then\n echo \"Lms Service is Healthy\"\nelse\n echo \"Lms Service is unhealthy\"\nfi\n" }, { "alpha_fraction": 0.5849056839942932, "alphanum_fraction": 0.5896226167678833, "avg_line_length": 22.5, "blob_id": "cb3c165916ee91a8e9f857c24eb2ee278e8e5ba0", "content_id": "fb3f9091480dc8d6025d7c3eb9e05986a835cf47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 424, "license_type": "permissive", "max_line_length": 60, "num_lines": 18, "path": "/images/keycloak/dockerPushToRepo.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Build script\n# set -o errexit\nset -e\ne () {\n echo $( echo ${1} | jq \".${2}\" | sed 's/\\\"//g')\n}\nm=$(./images/keycloak/metadata.sh)\n\norg=$(e \"${m}\" \"org\")\nhubuser=$(e \"${m}\" \"hubuser\")\nname=$(e \"${m}\" \"name\")\nversion=$(e \"${m}\" \"version\")\nartifactLabel=${ARTIFACT_LABEL:-bronze}\n\ndocker login -u \"purplesunbird\" -p`cat /home/ops/vault_pass`\ndocker push ${org}/${name}:${version}-${artifactLabel}\ndocker logout\n\n" }, { "alpha_fraction": 0.7046413421630859, "alphanum_fraction": 0.7046413421630859, "avg_line_length": 29.913043975830078, "blob_id": "a3b86db5c9ecad8f0fde376176b7eaf4bcd8c6c3", "content_id": "73fd307099cd0aa4a3863a5f14e2e7bc90f82600", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1422, "license_type": "permissive", "max_line_length": 100, "num_lines": 46, "path": "/deploy/provision-servers.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# Provision servers\nset -eu -o pipefail\nset -x\n\necho \"${APP_DEPLOYMENT_JSON_PATH:?You must set APP_DEPLOYMENT_JSON_PATH}\"\nif [ \"${DB_DEPLOYMENT:-true}\" == \"true\" ]; then\n\techo \"${DB_DEPLOYMENT_JSON_PATH:?You must set DB_DEPLOYMENT_JSON_PATH}\"\nelse\n\tDB_DEPLOYMENT_JSON_PATH=/dev/null\nfi\n\nAZURE_DEPLOY_SCRIPT=`pwd`/deploy-azure.sh\nrepourl=https://github.com/Azure/acs-engine.git\nssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts\nif [ -d acs-engine ]; then \n (cd acs-engine && git pull); \nelse \n echo \"cloning\"\n git clone $repourl;\nfi\ncd acs-engine\nrm -rf ./scripts/deploy-azure.sh\nrm -rf ./deployments\n\ndocker build --pull -t acs-engine .\ndocker version\n\nls -al $APP_DEPLOYMENT_JSON_PATH\nls -al $DB_DEPLOYMENT_JSON_PATH\nls -al $AZURE_DEPLOY_SCRIPT\n\ndocker run \\\n\t--privileged \\\n\t--security-opt seccomp:unconfined \\\n\t-v /var/run/docker.sock:/var/run/docker.sock \\\n\t-v `pwd`:/gopath/src/github.com/Azure/acs-engine \\\n\t-v ${APP_DEPLOYMENT_JSON_PATH}:/gopath/src/github.com/Azure/acs-engine/deployments/deployment/app \\\n\t-v ${DB_DEPLOYMENT_JSON_PATH}:/gopath/src/github.com/Azure/acs-engine/deployments/deployment/db \\\n\t-v ${AZURE_DEPLOY_SCRIPT}:/gopath/src/github.com/Azure/acs-engine/scripts/deploy-azure.sh \\\n\t-v ~/.azure:/root/.azure \\\n\t-w /gopath/src/github.com/Azure/acs-engine \\\n\t--rm \\\n\tacs-engine /bin/bash ./scripts/deploy-azure.sh\n\nchown -R \"$(logname):$(id -gn $(logname))\" . ~/.azure\n" }, { "alpha_fraction": 0.6805555820465088, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 23.16666603088379, "blob_id": "cf6aa6bbb81cc022dd9e2bbd5fb16400166ea6ed", "content_id": "6c553ae499e88f4aa3bdc35dca26288d1fd5af27", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 144, "license_type": "permissive", "max_line_length": 81, "num_lines": 6, "path": "/ansible/roles/elasticsearch/test/integration/package-5x/serverspec/default_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'package_spec'\n\n\ndescribe 'Package Tests v 5.x' do\n include_examples 'package::init', \"5.2.2\", [\"ingest-attachment\",\"ingest-geoip\"]\nend" }, { "alpha_fraction": 0.6514692902565002, "alphanum_fraction": 0.6676750183105469, "avg_line_length": 30.263513565063477, "blob_id": "8d57f4770cdd92a321059192e09a97331e7e2d51", "content_id": "95a4bfd129e8d81d56b9ba83dacdbfab6052bf52", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4628, "license_type": "permissive", "max_line_length": 122, "num_lines": 148, "path": "/ansible/roles/elasticsearch/test/integration/helpers/serverspec/config_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'spec_helper'\n\nshared_examples 'config::init' do |es_version,plugins|\n\n describe user('elasticsearch') do\n it { should exist }\n end\n \n describe group('elasticsearch') do\n it { should have_gid 333 }\n end\n\n describe user('elasticsearch') do\n it { should have_uid 333 }\n end\n\n describe service('node1_elasticsearch') do\n it { should be_running }\n end\n\n describe package('elasticsearch') do\n it { should be_installed }\n end\n\n describe file('/etc/elasticsearch/node1/elasticsearch.yml') do\n it { should be_file }\n end\n\n #test configuration parameters have been set - test all appropriately set in config file\n describe file('/etc/elasticsearch/node1/elasticsearch.yml') do\n it { should contain 'http.port: 9401' }\n it { should contain 'transport.tcp.port: 9501' }\n it { should contain 'node.data: true' }\n it { should contain 'node.master: true' }\n it { should contain 'cluster.name: custom-cluster' }\n it { should contain 'node.name: node1' }\n it { should contain 'bootstrap.memory_lock: true' }\n it { should contain 'discovery.zen.ping.unicast.hosts: localhost:9501' }\n it { should contain 'path.conf: /etc/elasticsearch/node1' }\n it { should contain 'path.data: /opt/elasticsearch/data-1/localhost-node1,/opt/elasticsearch/data-2/localhost-node1' }\n it { should contain 'path.logs: /opt/elasticsearch/logs/localhost-node1' }\n end\n\n #test directories exist\n describe file('/etc/elasticsearch/node1') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/opt/elasticsearch/data-1/localhost-node1') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/opt/elasticsearch/data-2/localhost-node1') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/opt/elasticsearch/logs/localhost-node1') do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n\n #test we started on the correct port was used\n describe command('curl -s \"localhost:9401\"') do\n #TODO: This is returning an empty string\n #its(:stdout) { should match /\\\"status\\\" : 200/ }\n its(:exit_status) { should eq 0 }\n end\n\n #test to make sure mlock was applied\n describe command('curl -s \"localhost:9401/_nodes/process?pretty\" | grep mlockall') do\n its(:stdout) { should match /true/ }\n its(:exit_status) { should eq 0 }\n end\n\n\n describe 'version check' do\n it 'should be reported as version '+es_version do\n command = command('curl -s localhost:9401 | grep number')\n expect(command.stdout).to match(es_version)\n expect(command.exit_status).to eq(0)\n end\n end\n\n for plugin in plugins\n describe file('/usr/share/elasticsearch/plugins/'+plugin) do\n it { should be_directory }\n it { should be_owned_by 'elasticsearch' }\n end\n #confirm plugins are installed and the correct version\n describe command('curl -s localhost:9401/_nodes/plugins | grep \\'\"name\":\"'+plugin+'\",\"version\":\"'+es_version+'\"\\'') do\n its(:exit_status) { should eq 0 }\n end\n end\n\n #explit test to make sure ingest-geoip is not installed\n describe file('/usr/share/elasticsearch/plugins/ingest-geoip') do\n it { should_not exist }\n end\n #confirm plugins are installed and the correct version\n describe command('curl -s localhost:9200/_nodes/plugins | grep \\'\"name\":\"ingest-geoip\",\"version\":\"'+es_version+'\"\\'') do\n its(:exit_status) { should eq 1 }\n end\n\n describe file('/etc/init.d/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/default/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/sysconfig/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/usr/lib/systemd/system/elasticsearch.service') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/elasticsearch.yml') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/logging.yml') do\n it { should_not exist }\n end\n\n #Init vs Systemd tests\n #Ubuntu 15 and up\n #Debian 8 and up\n #Centos 7 and up\n\n if (((os[:family] == 'redhat' || os[:family] == 'centos') && os[:release].to_f >= 7.0) ||\n (os[:family] == 'ubuntu' && os[:release].to_f >= 15.0) ||\n (os[:family] == 'debian' && os[:release].to_f >= 8.0))\n describe file('/usr/lib/systemd/system/node1_elasticsearch.service') do\n it { should be_file }\n it { should contain 'LimitMEMLOCK=infinity' }\n end\n else\n describe file('/etc/init.d/node1_elasticsearch') do\n it { should be_file }\n end\n end\nend\n\n" }, { "alpha_fraction": 0.6823104619979858, "alphanum_fraction": 0.7256317734718323, "avg_line_length": 68.5, "blob_id": "0003e957c4d158b604d837eb92fb40e33fa3a66a", "content_id": "c1eda3df3328dce84ac5f5078acdcfdcbda14b13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 277, "license_type": "permissive", "max_line_length": 181, "num_lines": 4, "path": "/utils/certbot/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM certbot/certbot:v1.24.0\nRUN apk add --update coreutils curl\nRUN curl -LO \"https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl\" && install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl\nCMD [\"/usr/local/bin/kubectl\"]" }, { "alpha_fraction": 0.6677215099334717, "alphanum_fraction": 0.6835442781448364, "avg_line_length": 30.600000381469727, "blob_id": "44cc83ca35db1b587aaeb68ae77eabac80a4618b", "content_id": "edac66f839a648fd86e974213092ad93b3f7ef6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 316, "license_type": "permissive", "max_line_length": 54, "num_lines": 10, "path": "/ansible/installDeps.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "if grep -q Alpine /etc/os-release; then\n apk -v --update --no-cache add jq\n apk -v add ansible=2.3.0.0-r1\nelse\n sudo apt-get update -y\n sudo apt-get -y install software-properties-common\n sudo apt-add-repository ppa:ansible/ansible -y\n sudo apt-get update -y\n sudo apt-get -y install ansible\nfi\n" }, { "alpha_fraction": 0.6884273290634155, "alphanum_fraction": 0.7067260146141052, "avg_line_length": 68.72413635253906, "blob_id": "a26012dc608ef121c6fb45c5c5877cc054b26d41", "content_id": "1fd121f219a0987cf39eb202ef1c06e842f7b64a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2022, "license_type": "permissive", "max_line_length": 383, "num_lines": 29, "path": "/ansible/roles/desktop-deploy/templates/build.sh.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -eo pipefail\n\ncd {{offline_repo_location}}/\n\n# Run the docker image and run the OS Specific build along with environment specific build\ndocker run -d --env-file envfile --env ELECTRON_CACHE=\"/root/.cache/electron\" --env ELECTRON_BUILDER_CACHE=\"/root/.cache/electron-builder\" --name offline_deploy -w /project electronuserland/builder:16-wine sleep infinity\ndocker cp . offline_deploy:/project/\ndocker exec offline_deploy npm install -g [email protected]\ndocker exec offline_deploy bash -x /project/setupOfflineInstaller.sh\n\n# Copy the built artifacts\nif [ \"{{offline_installer_type}}\" == \"windows32bit\" ];\nthen\n docker cp 'offline_deploy:/project/app_dist/dist/{{installer_version}}/win/ia32/{{environment_name}} Setup {{installer_version}}.exe' '{{offline_repo_location}}/desktop_uploader_assets/{{time}}/{{environment_name}}_{{installer_version}}_windows32bit.exe'\n\n elif [ \"{{offline_installer_type}}\" == \"windows64bit\" ];\n then\n docker cp 'offline_deploy:/project/app_dist/dist/{{installer_version}}/win/x64/{{environment_name}} Setup {{installer_version}}.exe' '{{offline_repo_location}}/desktop_uploader_assets/{{time}}/{{environment_name}}_{{installer_version}}_windows64bit.exe'\n\n elif [ \"{{offline_installer_type}}\" == \"linux64bit\" ];\n then\n docker cp 'offline_deploy:/project/app_dist/dist/{{installer_version}}/linux/x64/{{environment_name}}_{{installer_version}}_amd64.deb' '{{offline_repo_location}}/desktop_uploader_assets/{{time}}/{{environment_name}}_{{installer_version}}_linux64bit.deb'\nfi\n\n# Generate the latest.json file\necho \"{\\\"version\\\":\\\"{{installer_version}}\\\",\\\"windows\\\":{\\\"32bit\\\":\\\"{{environment_name}}_{{installer_version}}_windows32bit.exe\\\",\\\"64bit\\\":\\\"{{environment_name}}_{{installer_version}}_windows64bit.exe\\\"},\\\"linux\\\":{\\\"64bit\\\":\\\"{{environment_name}}_{{installer_version}}_linux64bit.deb\\\"}}\" | jq '.' | tee -a '{{offline_repo_location}}/desktop_uploader_assets/{{time}}/latest.json'\n\necho \"Build the installer succesfully\"\n" }, { "alpha_fraction": 0.5049680471420288, "alphanum_fraction": 0.5195173621177673, "avg_line_length": 21.188976287841797, "blob_id": "38ab629bbf4c0e8e7fa663daeaaed9b02b4b8e56", "content_id": "d6124ede81614a1b81d32c44b4ed9b75b19302c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2818, "license_type": "permissive", "max_line_length": 220, "num_lines": 127, "path": "/ansible/roles/keycloak-provision/templates/keycloak-service.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n### BEGIN INIT INFO\n# Provides: keycloak\n# Required-Start: $remote_fs\n# Required-Stop: $remote_fs\n# Should-Start: $all\n# Should-Stop: $all\n# Default-Start: 3 4 5\n# Default-Stop: 0 1 6\n### END INIT INFO\n\nkeycloakuser=keycloak\nkeycloakpath=/opt/keycloak/bin\n_JAVA_OPTIONS='-Dlog4j2.formatMsgNoLookups=true'\n# Normal output log\nLOGOUT=/var/log/keycloak.out.log\n# Error output log\nLOGERR=/var/log/keycloak.err.log\n \n## script start here\n \n\nfunction echo_failure() { echo -en \"\\n[FAILED]\"; }\nfunction echo_success() { echo -en \"\\n[OK]\"; }\n[ -f /etc/rc.d/init.d/functions ] && source /etc/rc.d/init.d/functions\n \nFINDPID=\"pgrep -u $keycloakuser -n -f standalone.sh\";\nfunction _is_running() {\n $FINDPID 1>/dev/null\n return $?\n}\n \nfunction stop_keycloak() {\n _is_running\n if [ $? -ne 0 ]; then\n echo -n \"$0 is not running, cannot stop.\"\n echo_failure\n echo\n return 1\n else\n echo -n \"Stopping $0...\"\n \n $FINDPID | xargs ps h -o pid --ppid | xargs kill\n sleep 1\n _is_running\n if [ $? -eq 0 ]; then\n echo_failure\n echo\n return 1\n else\n echo_success\n echo\n return 0\n fi\n fi\n \n}\n \nfunction status() {\n _is_running\n if [ $? -eq 0 ]; then\n echo -n \"$0 is running.\"\n echo_success\n echo\n return 0\n else\n echo -n \"$0 does not run.\"\n # echo_failure\n # echo\n # return 1\n fi\n}\n \nfunction start_keycloak() {\n _is_running\n if [ $? -eq 0 ]; then\n echo -n \"$0 already running.\"\n echo_failure\n echo\n return 1\n else\n echo -n \"Starting $0...\"\n # Make sure log files exist and are writable by $PDIUSER first\n touch $LOGOUT $LOGERR\n chown $keycloakuser:$keycloakuser $LOGOUT $LOGERR\n su - $keycloakuser -c \"cd $keycloakpath && (nohup sh ./standalone.sh -b={{ansible_default_ipv4.address}} -bprivate={{ansible_default_ipv4.address}} --server-config standalone-ha.xml 0<&- 1>>$LOGOUT 2>>$LOGERR &)\"\n sleep 1\n _is_running\n if [ $? -eq 0 ]; then\n echo_success\n echo\n return 0\n else\n echo_failure\n echo\n return 1\n fi\n fi\n}\n \ncase \"$1\" in\n start)\n start_keycloak\n exit $?\n ;;\n stop)\n stop_keycloak\n exit $?\n ;;\n reload|force-reload|restart|force-restart)\n stop_keycloak\n if [ $? -eq 0 ]; then\n start_keycloak\n exit $?\n else\n exit 1\n fi\n ;;\n status)\n status\n exit $?\n ;;\n *)\n echo \"Usage: $0 {start|stop|restart|status}\"\n exit 2\nesac\nexit 0\n" }, { "alpha_fraction": 0.4747474789619446, "alphanum_fraction": 0.49494948983192444, "avg_line_length": 23.75, "blob_id": "0eb03f0131e93ba74aa559ae20bf79e01d7981aa", "content_id": "e29f1a7fbd57023a9e9b85c900dd34fc779d65bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 99, "license_type": "permissive", "max_line_length": 67, "num_lines": 4, "path": "/ansible/roles/stop-jmeter/templates/stop-jmeter.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\npid=$(ps -ef | grep jmeter | awk -F \" \" '{print $2}' | tr \"\\n\" \" \")\nsudo kill -9 $pid\n" }, { "alpha_fraction": 0.62730872631073, "alphanum_fraction": 0.6286279559135437, "avg_line_length": 29.918367385864258, "blob_id": "4483eb3d1d084a8128a95703a908e2e96ecad204", "content_id": "82b0efa05cd142bf8c560738b889a654436c8ed4", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1516, "license_type": "permissive", "max_line_length": 119, "num_lines": 49, "path": "/ansible/roles/elasticsearch/filter_plugins/custom.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "__author__ = 'dale mcdiarmid'\n\nimport re\nimport os.path\n\ndef modify_list(values=[], pattern='', replacement='', ignorecase=False):\n ''' Perform a `re.sub` on every item in the list'''\n if ignorecase:\n flags = re.I\n else:\n flags = 0\n _re = re.compile(pattern, flags=flags)\n return [_re.sub(replacement, value) for value in values]\n\ndef append_to_list(values=[], suffix=''):\n if isinstance(values, basestring):\n values = values.split(',')\n return [str(value+suffix) for value in values]\n\ndef array_to_str(values=[],separator=','):\n return separator.join(values)\n\ndef extract_role_users(users={}):\n role_users=[]\n for user,details in users.iteritems():\n if \"roles\" in details:\n for role in details[\"roles\"]:\n role_users.append(role+\":\"+user)\n return role_users\n\ndef filename(filename=''):\n return os.path.splitext(os.path.basename(filename))[0]\n\ndef filter_reserved(user_roles={}):\n not_reserved = []\n for user_role,details in user_roles.items():\n if not \"metadata\" in details or not \"_reserved\" in details[\"metadata\"] or not details[\"metadata\"][\"_reserved\"]:\n not_reserved.append(user_role)\n return not_reserved\n\n\nclass FilterModule(object):\n def filters(self):\n return {'modify_list': modify_list,\n 'append_to_list':append_to_list,\n 'array_to_str':array_to_str,\n 'extract_role_users':extract_role_users,\n 'filter_reserved':filter_reserved,\n 'filename':filename}\n\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5144927501678467, "avg_line_length": 33.5, "blob_id": "3a6fb236e8cf6e1d0976afa63dae453282ab4b8d", "content_id": "1e4e040281f708cb64118693b66c3bb0cd71da29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 828, "license_type": "permissive", "max_line_length": 97, "num_lines": 24, "path": "/deploy/gitOPS/disableBranchProtection.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nread -p \"Enter Github Username: \" user\nread -sp \"Enter Github Password: \" pass\necho \" \" \nIFS=','\ngrep -v -e '#' -e \"^$\" github.csv | while read -ra LINE\ndo\n repo_name=\"${LINE[0]}\"\n branch_name=\"${LINE[1]}\"\n echo \"----------------------------------------------------\"\n echo -e '\\033[0;32m'$repo_name' '$branch_name'\\033[0m'\n echo \"----------------------------------------------------\"\n curl -u $user:$pass -XDELETE \\\n -H \"Accept: application/vnd.github.loki-preview+json\" \\\n -d '{\n \"protection\": {\n \"enabled\": null\n },\n \"restrictions\": null,\n \"required_status_checks\": null,\n \"enforce_admins\": null,\n \"required_pull_request_reviews\": null\n }' \"https://api.github.com/repos/project-sunbird/$repo_name/branches/$branch_name/protection\"\ndone\n" }, { "alpha_fraction": 0.7230769395828247, "alphanum_fraction": 0.7230769395828247, "avg_line_length": 9.833333015441895, "blob_id": "361fc96a0085476a30e681d654e1b07fe2b2af62", "content_id": "db3e0e21969200d2c0250f30d5bd824e5510fbbe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 65, "license_type": "permissive", "max_line_length": 15, "num_lines": 6, "path": "/ansible/static-files/healthDependenices.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\napk update curl\napk add curl\napk update jq\napk add jq\n" }, { "alpha_fraction": 0.6585366129875183, "alphanum_fraction": 0.6910569071769714, "avg_line_length": 23.600000381469727, "blob_id": "4e40fd0527fe10c4060325e2ddd875e0d9b48682", "content_id": "aa7e6977b70179872be1b0737026c6cb3c0e7c47", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 123, "license_type": "permissive", "max_line_length": 64, "num_lines": 5, "path": "/ansible/roles/elasticsearch/test/integration/xpack-5x/serverspec/default_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'xpack_spec'\n\ndescribe 'Xpack Tests v 5.x' do\n include_examples 'xpack::init', \"5.2.2\", [\"ingest-attachment\"]\nend\n" }, { "alpha_fraction": 0.801980197429657, "alphanum_fraction": 0.801980197429657, "avg_line_length": 32.66666793823242, "blob_id": "8c24dee7023d7b97b2f398def7f4463a47ebfd2b", "content_id": "e93074534ae9e0c98e1b040e2914cfc616552340", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 101, "license_type": "permissive", "max_line_length": 52, "num_lines": 3, "path": "/ansible/roles/postgres-migration/files/sunbird_programs/V4.4.1.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "UPDATE public.program SET\ntarget_type = 'collections'::programtargettype WHERE\ntarget_type IS NULL ;\n" }, { "alpha_fraction": 0.7517730593681335, "alphanum_fraction": 0.7765957713127136, "avg_line_length": 27.200000762939453, "blob_id": "703817f959d7c11def474d44400e6fc033170cb2", "content_id": "17a504516c3dc118e03e9a7c05e73856a05e3580", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 282, "license_type": "permissive", "max_line_length": 43, "num_lines": 10, "path": "/images/azure-ambari-prometheus-exporter/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM python:3.9.0-alpine\nMAINTAINER Revathi Kotla <[email protected]>\nRUN mkdir /src\nWORKDIR /src\nCOPY requirements.txt /src/requirements.txt\nRUN pip install -r requirements.txt\nCOPY collector.py /src/collector.py\nCOPY components.yaml /src/components.yaml\nEXPOSE 9999\nCMD [\"python\", \"collector.py\"]\n" }, { "alpha_fraction": 0.8442407250404358, "alphanum_fraction": 0.8528814911842346, "avg_line_length": 47.3963623046875, "blob_id": "3d74308db1715951722f09bbc2424d19404134e6", "content_id": "311b7512a05de61c7bd5a2985870c54d4ae20253", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 13309, "license_type": "permissive", "max_line_length": 233, "num_lines": 275, "path": "/ansible/artifacts/sunbird/login/messages/messages_en.properties", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "doLogIn=Login\nlogin=LOGIN\ndoRegister=Sign Up\ndoSignIn=Sign In\nsignIn=Sign in\ndoSignWithGoogle=with Google\ndoSignWithState=Login with State System\ndoCancel=Cancel\ndoSubmit=Submit\ndoReset=Reset\ndoYes=Yes\ndoNo=No\ndoContinue=Continue\ndoAccept=Accept\ndoDecline=Decline\ndoForgotPassword=Forgot password?\ndoClickHere=Click here\ndoImpersonate=Impersonate\nkerberosNotConfigured=Kerberos Not Configured\nkerberosNotConfiguredTitle=Kerberos Not Configured\nbypassKerberosDetail=Either you are not logged in via Kerberos or your browser is not set up for Kerberos login. Please click continue to login in through other means\nkerberosNotSetUp=Kerberos is not set up. You cannot login.\nregisterWithTitle=Register with {0}\nregisterWithTitleHtml={0}\nloginTitle=Log in to {0}\nloginTitleHtml={0}\nimpersonateTitle={0} Impersonate User\nimpersonateTitleHtml=<strong>{0}</strong> Impersonate User</strong>\nrealmChoice=Realm\nunknownUser=Unknown user\nloginTotpTitle=Mobile Authenticator Setup\nloginProfileTitle=Update Account Information\nenterCode=Enter the code we sent to you\nloginTimeout=You took too long to sign in. Sign in process starting from beginning.\noauthGrantTitle=Grant Access\noauthGrantTitleHtml={0}\nerrorTitle=We''re sorry...\nerrorTitleHtml=We''re <strong>sorry</strong> ...\nemailVerifyTitle=Email verification\nemailForgotTitle=Forgot Your Password?\nupdatePasswordTitle=Update Password\nnewPasswordTitle=Create New Password\nenterEmailPhonenumberToGetCode=Enter your Email Address/ Mobile number and we will send you instructions on how to reset your password\ncodeSuccessTitle=Success code\ncodeErrorTitle=Error code\\: {0}\n\ntermsTitle=Terms and Conditions\ntermsTitleHtml=Terms and Conditions\ntermsText=<p>Terms and conditions to be defined</p>\n\nrecaptchaFailed=Invalid Recaptcha\nrecaptchaNotConfigured=Recaptcha is required, but not configured\nconsentDenied=Consent denied.\n\nnoAccount=Don''t have an account?\nusername=Username or Mobile number\ngoBack=<<Go Back\nmergeAccountMessage=Enter Mobile number / Email Address OR use Login with Google to identify the account from which you want to merge usage details\nmigrateAccountMessage=Confirm the password for the DIKSHA account you want to merge of click Login with Google to sign in using your Gmail account\ninCorrectPasswordError=The password entered is incorrect. Enter the password again.\nemailOrPhone=Email Address / Mobile Number\nplaceholderForEmailOrPhone=Enter Email Address / Mobile Number\nfirstName=First name\ngivenName=Given name\nfullName=Full name\nlastName=Last name\nfamilyName=Family name\nemail=Email\npassword=Password\nplaceholderForPassword=Enter Password\npasswordConfirm=Confirm Password\npasswordNew=New Password\npasswordNewConfirm=New Password confirmation\nrememberMe=Remember me\nauthenticatorCode=One-time code\naddress=Address\nstreet=Street\nlocality=City or Locality\nregion=State, Province, or Region\npostal_code=Zip or Postal code\ncountry=Country\nemailVerified=Email verified\ngssDelegationCredential=GSS Delegation Credential\n\nloginTotpStep1=Install <a href=\"https://freeotp.github.io/\" target=\"_blank\">FreeOTP</a> or Google Authenticator on your mobile. Both applications are available in <a href=\"https://play.google.com\">Google Play</a> and Apple App Store.\nloginTotpStep2=Open the application and scan the barcode or enter the key\nloginTotpStep3=Enter the one-time code provided by the application and click Submit to finish the setup\nloginTotpOneTime=One-time code\n\noauthGrantRequest=Do you grant these access privileges?\ninResource=in\n\nemailVerifyInstruction1=An email with instructions to verify your email address has been sent to you.\nemailVerifyInstruction2=Haven''t received a verification code in your email?\nemailVerifyInstruction3=to re-send the email.\n\nemailLinkIdpTitle=Link {0}\nemailLinkIdp1=An email with instructions to link {0} account {1} with your {2} account has been sent to you.\nemailLinkIdp2=Haven''t received a verification code in your email?\nemailLinkIdp3=to re-send the email.\nemailLinkIdp4=If you already verified the email in different browser\nemailLinkIdp5=to continue.\n\nbackToLogin= Back to Sign In\n\ncopyCodeInstruction=Please copy this code and paste it into your application:\n\npageExpiredTitle=Page has expired\npageExpiredMsg1=To restart the sign in process\npageExpiredMsg2=To continue the sign in process\n\npersonalInfo=Personal Info:\nrole_admin=Admin\nrole_realm-admin=Realm Admin\nrole_create-realm=Create realm\nrole_create-client=Create client\nrole_view-realm=View realm\nrole_view-users=View users\nrole_view-applications=View applications\nrole_view-clients=View clients\nrole_view-events=View events\nrole_view-identity-providers=View identity providers\nrole_manage-realm=Manage realm\nrole_manage-users=Manage users\nrole_manage-applications=Manage applications\nrole_manage-identity-providers=Manage identity providers\nrole_manage-clients=Manage clients\nrole_manage-events=Manage events\nrole_view-profile=View profile\nrole_manage-account=Manage account\nrole_manage-account-links=Manage account links\nrole_read-token=Read token\nrole_offline-access=Offline access\nclient_account=Account\nclient_security-admin-console=Security Admin Console\nclient_admin-cli=Admin CLI\nclient_realm-management=Realm Management\nclient_broker=Broker\n\ninvalidUserMessage=Invalid Email Address/Mobile number or password. Please try again with valid credentials\ninvalidEmailMessage=Invalid email address.\naccountDisabledMessage=Account is disabled, contact admin.\naccountTemporarilyDisabledMessage=Your account has been locked due to too many incorrect login attempts. You can re-attempt to login after 24 hours. Please get in touch with the help desk team for support\nexpiredCodeMessage=Sign in timeout. Please Sign In again.\nexpiredActionMessage=Action expired. Please continue with Sign In now.\nexpiredActionTokenNoSessionMessage=Action expired.\nexpiredActionTokenSessionExistsMessage=Action expired. Please start again.\n\nmissingFirstNameMessage=Please specify first name.\nmissingLastNameMessage=Please specify last name.\nmissingEmailMessage=Please specify email.\nmissingUsernameMessage=Please specify Email or Mobile number.\nmissingPasswordMessage=Please specify password.\nmissingTotpMessage=Please specify authenticator code.\nnotMatchPasswordMessage=Passwords don''t match.\n\ninvalidPasswordExistingMessage=Invalid existing password.\ninvalidPasswordConfirmMessage=Password confirmation doesn''t match.\ninvalidTotpMessage=Invalid authenticator code.\n\nusernameExistsMessage=Username already exists.\nemailExistsMessage=Email already exists.\n\nfederatedIdentityExistsMessage=User with {0} {1} already exists. Please Sign In to account management to link the account.\n\nconfirmLinkIdpTitle=Account already exists\nfederatedIdentityConfirmLinkMessage=User with {0} {1} already exists. How do you want to continue?\nfederatedIdentityConfirmReauthenticateMessage=Authenticate as {0} to link your account with {1}\nconfirmLinkIdpReviewProfile=Review profile\nconfirmLinkIdpContinue=Add to existing account\n\nconfigureTotpMessage=You need to set up Mobile Authenticator to activate your account.\nupdateProfileMessage=You need to update your user profile to activate your account.\nupdatePasswordMessage=Enter the new password you would like to use to Sign In.\nverifyEmailMessage=You need to verify your email address to activate your account.\nlinkIdpMessage=You need to verify your email address to link your account with {0}.\n\nemailSentMessage=You should receive an email shortly with further instructions.\nemailSendErrorMessage=Failed to send email, please try again later.\n\naccountUpdatedMessage=Your password has been updated.\naccountPasswordUpdatedMessage=Your password has been updated.\n\nnoAccessMessage=No access\n\ninvalidPasswordMinLengthMessage=Invalid password: minimum length {0}.\ninvalidPasswordMinDigitsMessage=Invalid password: must contain at least {0} numerical digits.\ninvalidPasswordMinLowerCaseCharsMessage=Invalid password: must contain at least {0} lower case characters.\ninvalidPasswordMinUpperCaseCharsMessage=Invalid password: must contain at least {0} upper case characters.\ninvalidPasswordMinSpecialCharsMessage=Invalid password: must contain at least {0} special characters.\ninvalidPasswordNotUsernameMessage=Invalid password: must not be equal to the username.\ninvalidPasswordRegexPatternMessage=Invalid password: fails to match regex pattern(s).\ninvalidPasswordHistoryMessage=Invalid password: must not be equal to any of last {0} passwords.\ninvalidPasswordGenericMessage=Invalid password: new password doesn''t match password policies.\n\nfailedToProcessResponseMessage=Failed to process response\nhttpsRequiredMessage=HTTPS required\nrealmNotEnabledMessage=Realm not enabled\ninvalidRequestMessage=Invalid Request\nfailedLogout=Sign out failed\nunknownLoginRequesterMessage=Unknown login requester\nloginRequesterNotEnabledMessage=Login requester not enabled\nbearerOnlyMessage=Bearer-only applications are not allowed to initiate browser login\nstandardFlowDisabledMessage=Client is not allowed to initiate browser login with given response_type. Standard flow is disabled for the client.\nimplicitFlowDisabledMessage=Client is not allowed to initiate browser login with given response_type. Implicit flow is disabled for the client.\ninvalidRedirectUriMessage=Invalid redirect uri\nunsupportedNameIdFormatMessage=Unsupported NameIDFormat\ninvalidRequesterMessage=Invalid requester\nregistrationNotAllowedMessage=Registration not allowed\nresetCredentialNotAllowedMessage=Reset Credential not allowed\n\npermissionNotApprovedMessage=Permission not approved.\nnoRelayStateInResponseMessage=No relay state in response from identity provider.\ninsufficientPermissionMessage=Insufficient permissions to link identities.\ncouldNotProceedWithAuthenticationRequestMessage=Could not proceed with authentication request to identity provider.\ncouldNotObtainTokenMessage=Could not obtain token from identity provider.\nunexpectedErrorRetrievingTokenMessage=Unexpected error when retrieving token from identity provider.\nunexpectedErrorHandlingResponseMessage=Unexpected error when handling response from identity provider.\nidentityProviderAuthenticationFailedMessage=Authentication failed. Could not authenticate with identity provider.\nidentityProviderDifferentUserMessage=Authenticated as {0}, but expected to be authenticated as {1}\ncouldNotSendAuthenticationRequestMessage=Could not send authentication request to identity provider.\nunexpectedErrorHandlingRequestMessage=Unexpected error when handling authentication request to identity provider.\ninvalidAccessCodeMessage=Invalid access code.\nsessionNotActiveMessage=Session not active.\ninvalidCodeMessage=An error occurred, please sign in again through your application.\nidentityProviderUnexpectedErrorMessage=Unexpected error when authenticating with identity provider\nidentityProviderNotFoundMessage=Could not find an identity provider with the identifier.\nidentityProviderLinkSuccess=You successfully verified your email. Please go back to your original browser and continue there with the login.\nstaleCodeMessage=This page is no longer valid, please go back to your application and login again\nrealmSupportsNoCredentialsMessage=Realm does not support any credential type.\nidentityProviderNotUniqueMessage=Realm supports multiple identity providers. Could not determine which identity provider should be used to authenticate with.\nemailVerifiedMessage=Your email address has been verified.\nstaleEmailVerificationLink=The link you clicked is a old stale link and is no longer valid. Maybe you have already verified your email?\nidentityProviderAlreadyLinkedMessage=Federated identity returned by {0} is already linked to another user.\nconfirmAccountLinking=Confirm linking the account {0} of identity provider {1} with your account.\nconfirmEmailAddressVerification=Confirm validity of e-mail address {0}.\nconfirmExecutionOfActions=Perform the following action(s)\n\nlocale_ca=Catal\\u00E0\nlocale_de=Deutsch\nlocale_en=English\nlocale_es=Espa\\u00F1ol\nlocale_fr=Fran\\u00e7ais\nlocale_it=Italian\nlocale_ja=\\u65E5\\u672C\\u8A9E\nlocale_nl=Nederlands\nlocale_no=Norsk\nlocale_pt_BR=Portugu\\u00EAs (Brasil)\nlocale_pt-BR=Portugu\\u00EAs (Brasil)\nlocale_ru=\\u0420\\u0443\\u0441\\u0441\\u043A\\u0438\\u0439\nlocale_lt=Lietuvi\\u0173\nlocale_zh-CN=\\u4e2d\\u6587\\u7b80\\u4f53\nlocale_sv=Svenska\n\nbackToApplication=&laquo; Back to Application\nmissingParameterMessage=Missing parameters\\: {0}\nclientNotFoundMessage=Client not found.\nclientDisabledMessage=Client disabled.\ninvalidParameterMessage=Invalid parameter\\: {0}\nalreadyLoggedIn=You are already logged in.\ndifferentUserAuthenticated=You are already authenticated as different user ''{0}'' in this session. Please logout first.\nbrokerLinkingSessionExpired=Requested broker account linking, but current session is no longer valid.\nproceedWithAction=&raquo; Click here to proceed\n\nrequiredAction.CONFIGURE_TOTP=Configure OTP\nrequiredAction.terms_and_conditions=Terms and Conditions\nrequiredAction.UPDATE_PASSWORD=Update Password\nrequiredAction.UPDATE_PROFILE=Update Profile\nrequiredAction.VERIFY_EMAIL=Verify Email\nuser_not_found=This Email Address/Mobile Number doesn''t belong to a valid user\np3pPolicy=CP=\"This is not a P3P policy!\"\nusernamePlaceholder = Enter your Registered Email address/Mobile number\npasswordPlaceholder = Enter your password\nloginDiksha = Welcome to SUNBIRD\nregisterHere = Register here\n" }, { "alpha_fraction": 0.49005424976348877, "alphanum_fraction": 0.49005424976348877, "avg_line_length": 31.52941131591797, "blob_id": "b13371b2453344676061b1b3052df089da5915ad", "content_id": "6cc97d076e7b5279b4675a99a0c5c2f2ab80f511", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 553, "license_type": "permissive", "max_line_length": 94, "num_lines": 17, "path": "/ansible/roles/monit/templates/slack.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nMONIT_IP=\"{{ inventory_hostname }}\"\nCOLOR=${MONIT_COLOR:-$([[ $MONIT_DESCRIPTION == *\"succeeded\"* ]] && echo good || echo danger)}\n\n/usr/bin/curl \\\n -X POST \\\n -s \\\n --data-urlencode \"payload={ \\\n \\\"channel\\\": \\\"#{{ monit_slack_channel }}\\\", \\\n \\\"username\\\": \\\"{{ monit_slack_user }}\\\", \\\n \\\"pretext\\\": \\\"$MONIT_IP | $MONIT_DATE\\\", \\\n \\\"color\\\": \\\"$COLOR\\\", \\\n \\\"icon_emoji\\\": \\\":bangbang:\\\", \\\n \\\"text\\\": \\\"$MONIT_SERVICE - $MONIT_DESCRIPTION\\\" \\\n }\" \\\n {{ monit_slack_webhook_url }}\n" }, { "alpha_fraction": 0.6163922548294067, "alphanum_fraction": 0.6201915740966797, "avg_line_length": 36.71492385864258, "blob_id": "81d7403f6857f38f6676b54a01b6275f664ae9f0", "content_id": "79f5c2c6d319fb9cfbe40f8e53ab25a01128e2b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25274, "license_type": "permissive", "max_line_length": 115, "num_lines": 670, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/keycloak_admin.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Marcos Pereira <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# Unless otherwise stated in the comments, \"id\", in e.g. user_id, refers to the\n# internal Keycloak server ID, usually a uuid string\nfrom keycloak.urls_patterns import URL_ADMIN_CLIENT_ROLE\nfrom .urls_patterns import \\\n URL_ADMIN_USERS_COUNT, URL_ADMIN_USER, URL_ADMIN_USER_CONSENTS, \\\n URL_ADMIN_SEND_UPDATE_ACCOUNT, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_GET_SESSIONS, \\\n URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENTS, URL_ADMIN_CLIENT, URL_ADMIN_CLIENT_ROLES, URL_ADMIN_REALM_ROLES, \\\n URL_ADMIN_GROUP, URL_ADMIN_GROUPS, URL_ADMIN_GROUP_CHILD, URL_ADMIN_USER_GROUP,\\\n URL_ADMIN_GROUP_PERMISSIONS, URL_ADMIN_USER_CLIENT_ROLES, URL_ADMIN_USER_STORAGE, URL_ADMIN_REALM\n\nfrom .keycloak_openid import KeycloakOpenID\n\nfrom .exceptions import raise_error_from_response, KeycloakGetError\n\nfrom .urls_patterns import (\n URL_ADMIN_USERS,\n)\n\nfrom .connection import ConnectionManager\nimport json\n\n\nclass KeycloakAdmin:\n\n def __init__(self, server_url, username, password, realm_name='master', client_id='admin-cli', verify=True):\n \"\"\"\n\n :param server_url: Keycloak server url\n :param username: admin username\n :param password: admin password\n :param realm_name: realm name\n :param client_id: client id\n :param verify: True if want check connection SSL\n \"\"\"\n self._username = username\n self._password = password\n self._client_id = client_id\n self._realm_name = realm_name\n\n # Get token Admin\n keycloak_openid = KeycloakOpenID(server_url=server_url, client_id=client_id, realm_name=realm_name,\n verify=verify)\n self._token = keycloak_openid.token(username, password)\n\n self._connection = ConnectionManager(base_url=server_url,\n headers={'Authorization': 'Bearer ' + self.token.get('access_token'),\n 'Content-Type': 'application/json'},\n timeout=60,\n verify=verify)\n\n @property\n def realm_name(self):\n return self._realm_name\n\n @realm_name.setter\n def realm_name(self, value):\n self._realm_name = value\n\n @property\n def connection(self):\n return self._connection\n\n @connection.setter\n def connection(self, value):\n self._connection = value\n\n @property\n def client_id(self):\n return self._client_id\n\n @client_id.setter\n def client_id(self, value):\n self._client_id = value\n\n @property\n def username(self):\n return self._username\n\n @username.setter\n def username(self, value):\n self._username = value\n\n @property\n def password(self):\n return self._password\n\n @password.setter\n def password(self, value):\n self._password = value\n\n @property\n def token(self):\n return self._token\n\n @token.setter\n def token(self, value):\n self._token = value\n\n def get_users(self, query=None):\n \"\"\"\n Get users Returns a list of users, filtered according to query parameters\n\n :return: users list\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_get(URL_ADMIN_USERS.format(**params_path), **query)\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def create_user(self, payload):\n \"\"\"\n Create a new user Username must be unique\n\n UserRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation\n\n :param payload: UserRepresentation\n\n :return: UserRepresentation\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_post(URL_ADMIN_USERS.format(**params_path),\n data=json.dumps(payload))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)\n\n def users_count(self):\n \"\"\"\n User counter\n\n :return: counter\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_user_id(self, username):\n \"\"\"\n Get internal keycloak user id from username\n This is required for further actions against this user.\n\n UserRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation\n\n :param username: id in UserRepresentation\n\n :return: user_id\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"username\": username}\n data_raw = self.connection.raw_get(URL_ADMIN_USERS.format(**params_path))\n data_content = raise_error_from_response(data_raw, KeycloakGetError)\n\n for user in data_content:\n this_use_rname = json.dumps(user[\"username\"]).strip('\"')\n if this_use_rname == username:\n return json.dumps(user[\"id\"]).strip('\"')\n\n return None\n\n def get_user(self, user_id):\n \"\"\"\n Get representation of the user\n\n :param user_id: User id\n\n UserRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation\n\n :return: UserRepresentation\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id}\n data_raw = self.connection.raw_get(URL_ADMIN_USER.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def update_user(self, user_id, payload):\n \"\"\"\n Update the user\n\n :param user_id: User id\n :param payload: UserRepresentation\n\n :return: Http response\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id}\n data_raw = self.connection.raw_put(URL_ADMIN_USER.format(**params_path),\n data=json.dumps(payload))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def delete_user(self, user_id):\n \"\"\"\n Delete the user\n\n :param user_id: User id\n\n :return: Http response\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id}\n data_raw = self.connection.raw_delete(URL_ADMIN_USER.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def set_user_password(self, user_id, password, temporary=True):\n \"\"\"\n Set up a password for the user. If temporary is True, the user will have to reset\n the temporary password next time they log in.\n\n http://www.keycloak.org/docs-api/3.2/rest-api/#_users_resource\n http://www.keycloak.org/docs-api/3.2/rest-api/#_credentialrepresentation\n\n :param user_id: User id\n :param password: New password\n :param temporary: True if password is temporary\n\n :return:\n \"\"\"\n payload = {\"type\": \"password\", \"temporary\": temporary, \"value\": password}\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id}\n data_raw = self.connection.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),\n data=json.dumps(payload))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def consents_user(self, user_id):\n \"\"\"\n Get consents granted by the user\n\n :param user_id: User id\n\n :return: consents\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id}\n data_raw = self.connection.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):\n \"\"\"\n Send a update account email to the user An email contains a\n link the user can click to perform a set of required actions.\n\n :param user_id:\n :param payload:\n :param client_id:\n :param lifespan:\n :param redirect_uri:\n\n :return:\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id}\n params_query = {\"client_id\": client_id, \"lifespan\": lifespan, \"redirect_uri\": redirect_uri}\n data_raw = self.connection.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),\n data=payload, **params_query)\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def send_verify_email(self, user_id, client_id=None, redirect_uri=None):\n \"\"\"\n Send a update account email to the user An email contains a\n link the user can click to perform a set of required actions.\n\n :param user_id: User id\n :param client_id: Client id\n :param redirect_uri: Redirect uri\n\n :return:\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id}\n params_query = {\"client_id\": client_id, \"redirect_uri\": redirect_uri}\n data_raw = self.connection.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),\n data={}, **params_query)\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_sessions(self, user_id):\n \"\"\"\n Get sessions associated with the user\n\n :param user_id: id of user\n\n UserSessionRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_usersessionrepresentation\n\n :return: UserSessionRepresentation\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id}\n data_raw = self.connection.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_server_info(self):\n \"\"\"\n Get themes, social providers, auth providers, and event listeners available on this server\n\n ServerInfoRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_serverinforepresentation\n\n :return: ServerInfoRepresentation\n \"\"\"\n data_raw = self.connection.raw_get(URL_ADMIN_SERVER_INFO)\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_groups(self):\n \"\"\"\n Get groups belonging to the realm. Returns a list of groups belonging to the realm\n\n GroupRepresentation\n http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation\n\n :return: array GroupRepresentation\n \"\"\"\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_get(URL_ADMIN_GROUPS.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_group(self, group_id):\n \"\"\"\n Get group by id. Returns full group details\n\n GroupRepresentation\n http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation\n\n :return: Keycloak server response (GroupRepresentation)\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": group_id}\n data_raw = self.connection.raw_get(URL_ADMIN_GROUP.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_group_by_name(self, name_or_path, search_in_subgroups=False):\n \"\"\"\n Get group id based on name or path.\n A straight name or path match with a top-level group will return first.\n Subgroups are traversed, the first to match path (or name with path) is returned.\n\n GroupRepresentation\n http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation\n\n :param name: group name\n :param path: group path\n :param search_in_subgroups: True if want search in the subgroups\n :return: Keycloak server response (GroupRepresentation)\n \"\"\"\n\n groups = self.get_groups()\n\n # TODO: Review this code is necessary\n for group in groups:\n if group['name'] == name_or_path or group['path'] == name_or_path:\n return group\n elif search_in_subgroups and group[\"subGroups\"]:\n for subgroup in group[\"subGroups\"]:\n if subgroup['name'] == name_or_path or subgroup['path'] == name_or_path:\n return subgroup\n\n return None\n\n def create_group(self, name=None, client_roles={}, realm_roles=[], sub_groups=[], path=None, parent=None):\n \"\"\"\n Create a group in the Realm\n\n GroupRepresentation\n http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation\n\n :param name: group name\n :param client_roles: (Dict) Client roles to include in groupp # Not demonstrated to work\n :param realm_roles: (List) Realm roles to include in group # Not demonstrated to work\n :param sub_groups: (List) Subgroups to include in groupp # Not demonstrated to work\n :param path: group path\n :param parent: parent group's id. Required to create a sub-group.\n\n :return: Keycloak server response (GroupRepresentation)\n \"\"\"\n\n data = {\"name\": name or path,\n \"path\": path,\n \"clientRoles\": client_roles,\n \"realmRoles\": realm_roles,\n \"subGroups\": sub_groups}\n\n if parent is None:\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_post(URL_ADMIN_GROUPS.format(**params_path),\n data=json.dumps(data))\n else:\n params_path = {\"realm-name\": self.realm_name, \"id\": parent}\n data_raw = self.connection.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),\n data=json.dumps(data))\n\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)\n\n def group_set_permissions(self, group_id, enabled=True):\n \"\"\"\n Enable/Disable permissions for a group. Cannot delete group if disabled\n\n :param group_id: id of group\n :param enabled: boolean\n :return: Keycloak server response\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name, \"id\": group_id}\n data_raw = self.connection.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),\n data=json.dumps({\"enabled\": enabled}))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def group_user_add(self, user_id, group_id):\n \"\"\"\n Add user to group (user_id and group_id)\n\n :param group_id: id of group\n :param user_id: id of user\n :param group_id: id of group to add to\n :return: Keycloak server response\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id, \"group-id\": group_id}\n data_raw = self.connection.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def group_user_remove(self, user_id, group_id):\n \"\"\"\n Remove user from group (user_id and group_id)\n\n :param group_id: id of group\n :param user_id: id of user\n :param group_id: id of group to add to\n :return: Keycloak server response\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id, \"group-id\": group_id}\n data_raw = self.connection.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def delete_group(self, group_id):\n \"\"\"\n Deletes a group in the Realm\n\n :param group_id: id of group to delete\n :return: Keycloak server response\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name, \"id\": group_id}\n data_raw = self.connection.raw_delete(URL_ADMIN_GROUP.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def get_clients(self):\n \"\"\"\n Get clients belonging to the realm Returns a list of clients belonging to the realm\n\n ClientRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation\n\n :return: Keycloak server response (ClientRepresentation)\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_get(URL_ADMIN_CLIENTS.format(**params_path))\n \n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_client(self, client_id):\n \"\"\"\n Get representation of the client\n\n ClientRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation\n\n :param client_id: id of client (not client-id)\n :return: Keycloak server response (ClientRepresentation)\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name, \"id\": client_id}\n data_raw = self.connection.raw_get(URL_ADMIN_CLIENT.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_client_id(self, client_name):\n \"\"\"\n Get internal keycloak client id from client-id.\n This is required for further actions against this client.\n\n :param client_name: name in ClientRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation\n :return: client_id (uuid as string)\n \"\"\"\n\n clients = self.get_clients()\n\n for client in clients:\n if client_name == client['name']:\n return client[\"id\"]\n\n return None\n\n def create_client(self, payload):\n \"\"\"\n Create a client\n\n ClientRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation\n\n :param payload: ClientRepresentation\n :return: Keycloak server response (UserRepresentation)\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_post(URL_ADMIN_CLIENTS.format(**params_path),\n data=json.dumps(payload))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)\n\n def delete_client(self, client_id):\n \"\"\"\n Get representation of the client\n\n ClientRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation\n\n :param client_id: keycloak client id (not oauth client-id)\n :return: Keycloak server response (ClientRepresentation)\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name, \"id\": client_id}\n data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def get_realm_roles(self):\n \"\"\"\n Get all roles for the realm or client\n\n RoleRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation\n\n :return: Keycloak server response (RoleRepresentation)\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name}\n data_raw = self.connection.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_client_roles(self, client_id):\n \"\"\"\n Get all roles for the client\n\n :param client_id: id of client (not client-id)\n\n RoleRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation\n\n :return: Keycloak server response (RoleRepresentation)\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name, \"id\": client_id}\n data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_client_role(self, client_id, role_name):\n \"\"\"\n Get client role id by name\n This is required for further actions with this role.\n\n :param client_id: id of client (not client-id)\n :param role_name: role’s name (not id!)\n\n RoleRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation\n\n :return: role_id\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": client_id, \"role-name\": role_name}\n data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def get_client_role_id(self, client_id, role_name):\n \"\"\"\n Warning: Deprecated\n\n Get client role id by name\n This is required for further actions with this role.\n\n :param client_id: id of client (not client-id)\n :param role_name: role’s name (not id!)\n\n RoleRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation\n\n :return: role_id\n \"\"\"\n role = self.get_client_role(client_id, role_name)\n return role.get(\"id\")\n\n def create_client_role(self, payload):\n \"\"\"\n Create a client role\n\n RoleRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation\n\n :param payload: id of client (not client-id), role_name: name of role\n :return: Keycloak server response (RoleRepresentation)\n \"\"\"\n\n params_path = {\"realm-name\": self.realm_name, \"id\": self.client_id}\n data_raw = self.connection.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),\n data=json.dumps(payload))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)\n\n def delete_client_role(self, role_name):\n \"\"\"\n Create a client role\n\n RoleRepresentation\n http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation\n\n :param role_name: role’s name (not id!)\n \"\"\"\n params_path = {\"realm-name\": self.realm_name, \"id\": self.client_id, \"role-name\": role_name}\n data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def assign_client_role(self, user_id, client_id, roles):\n \"\"\"\n Assign a client role to a user\n\n :param client_id: id of client (not client-id)\n :param user_id: id of user\n :param client_id: id of client containing role,\n :param roles: roles list or role (use RoleRepresentation)\n :return Keycloak server response\n \"\"\"\n\n payload = roles if isinstance(roles, list) else [roles]\n params_path = {\"realm-name\": self.realm_name, \"id\": user_id, \"client-id\": client_id}\n data_raw = self.connection.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),\n data=json.dumps(payload))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)\n\n def sync_users(self, storage_id, action):\n \"\"\"\n Function to trigger user sync from provider\n\n :param storage_id:\n :param action:\n :return:\n \"\"\"\n data = {'action': action}\n params_query = {\"action\": action}\n\n params_path = {\"realm-name\": self.realm_name, \"id\": storage_id}\n data_raw = self.connection.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),\n data=json.dumps(data), **params_query)\n return raise_error_from_response(data_raw, KeycloakGetError)\n\n def import_realm(self, payload):\n \"\"\"\n Imports a realm from a full representation of that realm\n\n Realmrepresentation\n http://www.keycloak.org/docs-api/2.5/rest-api/index.html#_import_a_realm\n\n :param payload: Realmrepresentation\n\n :return: Realmrepresentation\n \"\"\"\n data_raw = self.connection.raw_post(URL_ADMIN_REALM, \n data = json.dumps(payload))\n return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)" }, { "alpha_fraction": 0.7435064911842346, "alphanum_fraction": 0.7456709742546082, "avg_line_length": 50.33333206176758, "blob_id": "3b231d410fdc07c42b6fbd06b471cb697197e25e", "content_id": "b57212950b4b22de76174803be0969ca78e79ba1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2772, "license_type": "permissive", "max_line_length": 102, "num_lines": 54, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/urls_patterns.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Marcos Pereira <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# OPENID URLS\nURL_WELL_KNOWN = \"realms/{realm-name}/.well-known/openid-configuration\"\nURL_TOKEN = \"realms/{realm-name}/protocol/openid-connect/token\"\nURL_USERINFO = \"realms/{realm-name}/protocol/openid-connect/userinfo\"\nURL_LOGOUT = \"realms/{realm-name}/protocol/openid-connect/logout\"\nURL_CERTS = \"realms/{realm-name}/protocol/openid-connect/certs\"\nURL_INTROSPECT = \"realms/{realm-name}/protocol/openid-connect/token/introspect\"\nURL_ENTITLEMENT = \"realms/{realm-name}/authz/entitlement/{resource-server-id}\"\n\n# ADMIN URLS\nURL_ADMIN_USERS = \"admin/realms/{realm-name}/users\"\nURL_ADMIN_USERS_COUNT = \"admin/realms/{realm-name}/users/count\"\nURL_ADMIN_USER = \"admin/realms/{realm-name}/users/{id}\"\nURL_ADMIN_USER_CONSENTS = \"admin/realms/{realm-name}/users/{id}/consents\"\nURL_ADMIN_SEND_UPDATE_ACCOUNT = \"admin/realms/{realm-name}/users/{id}/execute-actions-email\"\nURL_ADMIN_SEND_VERIFY_EMAIL = \"admin/realms/{realm-name}/users/{id}/send-verify-email\"\nURL_ADMIN_RESET_PASSWORD = \"admin/realms/{realm-name}/users/{id}/reset-password\"\nURL_ADMIN_GET_SESSIONS = \"admin/realms/{realm-name}/users/{id}/sessions\"\nURL_ADMIN_USER_CLIENT_ROLES = \"admin/realms/{realm-name}/users/{id}/role-mappings/clients/{client-id}\"\nURL_ADMIN_USER_GROUP = \"admin/realms/{realm-name}/users/{id}/groups/{group-id}\"\n\nURL_ADMIN_SERVER_INFO = \"admin/serverinfo\"\n\nURL_ADMIN_GROUPS = \"admin/realms/{realm-name}/groups\"\nURL_ADMIN_GROUP = \"admin/realms/{realm-name}/groups/{id}\"\nURL_ADMIN_GROUP_CHILD = \"admin/realms/{realm-name}/groups/{id}/children\"\nURL_ADMIN_GROUP_PERMISSIONS = \"admin/realms/{realm-name}/groups/{id}/management/permissions\"\n\nURL_ADMIN_CLIENTS = \"admin/realms/{realm-name}/clients\"\nURL_ADMIN_CLIENT = \"admin/realms/{realm-name}/clients/{id}\"\nURL_ADMIN_CLIENT_ROLES = \"admin/realms/{realm-name}/clients/{id}/roles\"\nURL_ADMIN_CLIENT_ROLE = \"admin/realms/{realm-name}/clients/{id}/roles/{role-name}\"\n\nURL_ADMIN_REALM_ROLES = \"admin/realms/{realm-name}/roles\"\n\nURL_ADMIN_USER_STORAGE = \"admin/realms/{realm-name}/user-storage/{id}/sync\"\nURL_ADMIN_REALM = \"admin/realms\"\n" }, { "alpha_fraction": 0.7414187788963318, "alphanum_fraction": 0.7559115290641785, "avg_line_length": 37.55882263183594, "blob_id": "8bcbbf717a7f31875b11150184dac072143d6e4c", "content_id": "66c4d95c61c106f5f30e4df39db2eadb66760f88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1311, "license_type": "permissive", "max_line_length": 167, "num_lines": 34, "path": "/images/android-jenkins-swarm-agent/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM cloudposse/jenkins-swarm-slave\n\nUSER root\n\nRUN apt-get install -y unzip\nRUN add-apt-repository ppa:openjdk-r/ppa\nRUN apt-get update\nRUN apt-get install -y openjdk-8-jdk\n\n# Installs Android SDK\nENV ANDROID_SDK_FILENAME sdk-tools-linux-3859397.zip\nENV ANDROID_SDK_URL https://dl.google.com/android/repository/${ANDROID_SDK_FILENAME}\nENV ANDROID_API_LEVELS android-25\nENV ANDROID_BUILD_TOOLS_VERSION 25.0.3\nENV ANDROID_HOME /opt/android-sdk-linux\nENV SWARM_CLIENT_VERSION 3.3\nENV PATH ${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools:${ANDROID_HOME}/tools/bin\n\nRUN mkdir -p /opt/jenkins && mkdir -p /opt/android-sdk-linux && cd /opt/android-sdk-linux && \\\n wget -q ${ANDROID_SDK_URL} && \\\n unzip -a -q ${ANDROID_SDK_FILENAME} && \\\n rm ${ANDROID_SDK_FILENAME}\n\nENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64\nRUN yes | sdkmanager --licenses\nRUN sdkmanager \"tools\" \"platform-tools\"\nRUN sdkmanager \"build-tools;${ANDROID_BUILD_TOOLS_VERSION}\"\nRUN sdkmanager \"platforms;${ANDROID_API_LEVELS}\"\n\nRUN wget -q https://repo.jenkins-ci.org/releases/org/jenkins-ci/plugins/swarm-client/${SWARM_CLIENT_VERSION}/swarm-client-${SWARM_CLIENT_VERSION}.jar -P /home/jenkins/\n\nADD ./images/android-jenkins-swarm-agent/custom-jenkins-slave.sh /opt/custom-jenkins-slave.sh\n\nENTRYPOINT /opt/custom-jenkins-slave.sh\n" }, { "alpha_fraction": 0.6960340142250061, "alphanum_fraction": 0.7243626117706299, "avg_line_length": 48.02777862548828, "blob_id": "58f23185c822cb392ef562106721c7cdc6985be7", "content_id": "306d4f7d8a5e00da4952af0da2f3f6286145a106", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3530, "license_type": "permissive", "max_line_length": 145, "num_lines": 72, "path": "/deploy/cassandra_restore_v2.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# This program will copy the snapshots to cassandra data directory\n# This program will only work in linux, as it's utilizing 'cp' for copying as shutil and copy_tree\n# are not handling hardlink, existing directory combo.\n#\n# Author Rajesh Rajendran <[email protected]>\n\n# Restore process is based on the following approach\n# Ref: https://docs.datastax.com/en/cassandra-oss/2.1/cassandra/operations/ops_snapshot_restore_new_cluster.html\n\n# Steps:\n# Update token ring:\n# sudo systemctl stop cassandra\n# open /etc/cassadandra/cassandra.yaml and append\n# initial_token: < contentents from tokenring.txt from the backup directory (only from that node). >\n# rm -rf /var/lib/cassandra/*\n# sudo systemctl start cassandra\n# Restore the schema, from backup directory.\n# cqlsh -f /path/to/backup-dir/db_schema.sql\n# Restore data.\n# sudo systemctl stop cassandra.\n# sudo python3 cassandra_restore_copy.py --snapshotdir <path to backup dir>\n# sudo chown -R cassandra:cassandra /var/lib/cassandra\n# sudo systemctl start cassandra\n# Important:\n# Clean up initial_token:\n# Once `nodetool status` is UN for all nodes\n# open /etc/cassandra/cassandra.yaml and remove `initial_token`.\n# Note: Don't have to restart cassandra after removing initial_token.\n\nimport os\nimport shutil\nfrom argparse import ArgumentParser\nfrom collections import defaultdict\nfrom subprocess import STDOUT, call\nimport concurrent.futures\nparser = ArgumentParser(description=\"Restore cassandra snapshot\")\nparser.add_argument(\"-d\", \"--datadirectory\", metavar=\"datadir\", default='/var/lib/cassandra/data',\n help=\"Path to cassadandra keyspaces. Default /var/lib/cassadra/data\")\nparser.add_argument(\"-w\", \"--workers\", metavar=\"workers\",\n default=os.cpu_count(), help=\"Number of workers to use. Default same as cpu cores {}\".format(os.cpu_count()))\nparser.add_argument(\"--snapshotdir\", default=\"cassandra_backup\", metavar=\"< Default: cassandra_backup >\", help=\"snapshot directory name or path\")\nargs = parser.parse_args()\n# copy function\ndef customCopy(root, root_target_dir):\n print(\"copying {} to {}\".format(root, root_target_dir))\n # Shuti and cp_tree are not good enough for nested hard links.\n call([\"cp -arl \" + root + \" \" + root_target_dir],shell=True, stderr=STDOUT)\n# ks_tb_pair = {ks_name: ['table1', 'table2']}\nks_tb_pair = defaultdict(list)\ndef create_ks_tb_pair(path):\n # containes parsed path\n # backupdir/sunbirdplugin/announcement-6bc5074070ef11e995fbf564f8591b58\n # [backupdir,sunbirdplugin,announcement-6bc5074070ef11e995fbf564f8591b58]\n parsed_data = path.split('/')\n # splitting parsed_data[-1] with '-' because we don't need UUID\n ks_tb_pair[parsed_data[-2]].append(parsed_data[-1].split('-')[0])\n # print(ks_tb_pair)\n # Copy content to datadirectory\n customCopy(path+'/*', args.datadirectory+os.sep+parsed_data[-2]+os.sep+parsed_data[-1].split(\"-\")[0]+\"-*\")\n# Traverse through backup dir and create keyspace table pair\n# Unix autocompletion for directory will append '/', which will break restore process\nsnap_dir = args.snapshotdir.rstrip('/')\nroot_levels = snap_dir.count(os.sep)\nfor root, dirs, files in os.walk(snap_dir):\n # our tables will be under /keyspace/table\n if root.count(os.sep) == root_levels + 2:\n # output will be like\n # backupdir/sunbirdplugin/announcement-6bc5074070ef11e995fbf564f8591b58\n # backupdir/sunbirdplugin/groupmember-8c7eb6c070ef11e9858587f867de3ce2\n # print(root)\n create_ks_tb_pair(root)\n" }, { "alpha_fraction": 0.604361355304718, "alphanum_fraction": 0.6137071847915649, "avg_line_length": 31, "blob_id": "655b9101159551860186d19889f91856ca818e9e", "content_id": "d8335fb0aa95fcf5dcbd10da7a8a722d47dee4ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 321, "license_type": "permissive", "max_line_length": 117, "num_lines": 10, "path": "/pipelines/build/nodebb/build.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "\n#!/bin/bash -xv\n# Build script\nset -eo pipefail\nbuild_tag=$1\nname=nodebb\nnode=$2\norg=$3\n\ndocker build -f ./NodeBB/Dockerfile --label commitHash=$(git rev-parse --short HEAD) -t ${org}/${name}:${build_tag} .\necho {\\\"image_name\\\" : \\\"${name}\\\", \\\"image_tag\\\" : \\\"${build_tag}\\\", \\\"node_name\\\" : \\\"$node\\\"} > metadata.json\n" }, { "alpha_fraction": 0.7613240480422974, "alphanum_fraction": 0.7700348496437073, "avg_line_length": 46.91666793823242, "blob_id": "792a53aaa97d3b3886b056e56fde6a4285471f14", "content_id": "e1217a9d9ecb2e7d6385923ec1e8b42d96b58279", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 574, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/ansible/roles/jenkins-backup-upload/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "### Jenkins backup upload\n\nThis role uploads backup taken by [ThinBackup plugin](https://plugins.jenkins.io/thinBackup)\n\n\n### PreRequisites\n\n* Jenkins should have [ThinBackup plugin](https://plugins.jenkins.io/thinBackup) installed\n* Configure [ThinBackup plugin settings](https://ci.server/jenkins/thinBackup/backupsettings)\n\t* Set the backup dir as `/jenkins-backup`\n\t* Ensure backup is minimal by excluding job artifacts etc\n\t* Ensure there is a periodic backup which runs before upload. Example if upload runs `@midnight`, schedule backup at 11PM using cron `0 23 * * *`" }, { "alpha_fraction": 0.6697606444358826, "alphanum_fraction": 0.681485116481781, "avg_line_length": 25.230770111083984, "blob_id": "25a0331704d8b49474740707a2f9946b121ed271", "content_id": "6272ed2bf9827eeb38cdc187c3e8f1ef8ed28bc8", "detected_licenses": [ "JSON", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2047, "license_type": "permissive", "max_line_length": 77, "num_lines": 78, "path": "/ansible/roles/elasticsearch/test/integration/helpers/serverspec/standard_spec.rb", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "require 'spec_helper'\n\nshared_examples 'standard::init' do |es_version|\n\n describe user('elasticsearch') do\n it { should exist }\n end\n\n describe service('node1_elasticsearch') do\n it { should be_running }\n end\n\n describe package('elasticsearch') do\n it { should be_installed }\n end\n\n describe file('/etc/elasticsearch/node1/elasticsearch.yml') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/node1/log4j2.properties') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/node1/jvm.options') do\n it { should be_file }\n it { should be_owned_by 'elasticsearch' }\n end\n\n describe file('/etc/elasticsearch/node1/elasticsearch.yml') do\n it { should contain 'node.name: localhost-node1' }\n it { should contain 'cluster.name: elasticsearch' }\n it { should contain 'path.conf: /etc/elasticsearch/node1' }\n it { should contain 'path.data: /var/lib/elasticsearch/localhost-node1' }\n it { should contain 'path.logs: /var/log/elasticsearch/localhost-node1' }\n end\n\n describe 'Node listening' do\n it 'listening in port 9200' do\n expect(port 9200).to be_listening\n end\n end\n\n describe 'version check' do\n it 'should be reported as version '+es_version do\n command = command('curl -s localhost:9200 | grep number')\n expect(command.stdout).to match(es_version)\n expect(command.exit_status).to eq(0)\n end\n end\n\n describe file('/etc/init.d/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/default/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/etc/sysconfig/elasticsearch') do\n it { should_not exist }\n end\n\n describe file('/usr/lib/systemd/system/elasticsearch.service') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/elasticsearch.yml') do\n it { should_not exist }\n end\n\n describe file('/etc/elasticsearch/logging.yml') do\n it { should_not exist }\n end\n\nend\n\n" }, { "alpha_fraction": 0.6659436225891113, "alphanum_fraction": 0.6702820062637329, "avg_line_length": 40.90909194946289, "blob_id": "5d066c40cfd0348afa3463a43d7ed8add972eb4c", "content_id": "29ac08e67787d59f84b7b0df021cd0be44698b51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 922, "license_type": "permissive", "max_line_length": 226, "num_lines": 22, "path": "/images/android-jenkins-swarm-agent/custom-jenkins-slave.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd $HOME\n\n# If `docker run` first argument start with `-` the user is passing jenkins swarm launcher arguments\nif [[ $# -lt 1 ]] || [[ \"$1\" == \"-\"* ]]; then\n\n # Jenkins swarm slave\n #JAR=`ls -1 /usr/share/jenkins/swarm-client-*.jar | tail -n 1`\n JAR=/home/jenkins/swarm-client-${SWARM_CLIENT_VERSION}.jar\n PARAMS=\"\"\n # if -master is not provided and using --link jenkins:jenkins\n if [[ \"$@\" != *\"-master \"* ]] && [ ! -z \"$JENKINS_MASTER_PORT\" ]; then\n PARAMS=\"$PARAMS -master http://$JENKINS_MASTER_HOST:$JENKINS_MASTER_PORT/jenkins\"\n fi\n CMD=\"java $JAVA_OPTS -jar $JAR -fsroot $HOME -username `cat $JENKINS_SLAVE_USERNAME` -password `cat $JENKINS_SLAVE_PASSWORD` -mode $JENKINS_SLAVE_MODE -name $JENKINS_SLAVE_NAME -executors $JENKINS_SLAVE_EXECUTORS $PARAMS $@\"\n echo Running $CMD\n exec $CMD\nfi\n\n# Argument passed was not jenkins, so we assume the user wants to run their own process\nexec \"$@\"\n" }, { "alpha_fraction": 0.6866537928581238, "alphanum_fraction": 0.7040618658065796, "avg_line_length": 38.69230651855469, "blob_id": "8110e5e96c9736e5a256b5343b3c8964a7074f50", "content_id": "7e7a3bccdba13a4345c2728b5040103a38217d2a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 517, "license_type": "permissive", "max_line_length": 74, "num_lines": 13, "path": "/images/ansible/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM alpine:3.5\n# making an addtional layer as ssh and python are necessory\n# so caching will be efficient\nRUN apk --update --no-cache add openssh python-dev\nRUN apk --update --no-cache add build-base libffi-dev openssl-dev py-pip \\\n && pip install cffi && pip install ansible==2.4.1 \\\n && pip uninstall -y cffi \\\n && apk del build-base libffi-dev openssl-dev &&rm -rf /root/cache \\\n && mkdir /ansible \nENV ANSIBLE_HOST_KEY_CHECKING=False\nENV SSH_AUTH_SOCK=/ssh-agent\nWORKDIR /ansible\nCMD [\"nc\", \"-k\", \"-l\", \"8000\"]\n\n" }, { "alpha_fraction": 0.6797520518302917, "alphanum_fraction": 0.7148760557174683, "avg_line_length": 59.5, "blob_id": "5a9a39cb9c4c1befa7051fdc42f6a5ff7c44495f", "content_id": "60ecf22866f92ad7abb2f4119439714a9409c30d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 484, "license_type": "permissive", "max_line_length": 95, "num_lines": 8, "path": "/images/BuildImages/player/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "from node:8.11-slim\nRUN echo \"deb http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list\nRUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -\nRUN apt-get update && apt-get -y install libxpm4 libxrender1 libgtk2.0-0 libnss3 libgconf-2-4 \\\n xvfb gtk2-engines-pixbuf \\\n xfonts-cyrillic xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable \\\n google-chrome-stable git \\\n && apt-get clean && rm -rf /var/lib/apt/lists/\n" }, { "alpha_fraction": 0.613043487071991, "alphanum_fraction": 0.6173912882804871, "avg_line_length": 24.66666603088379, "blob_id": "c65692cbefba744a484c2f866d3978ed927b04b6", "content_id": "d8ac443c9ac44b9a51ede74dc7c7e2ec17a287c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 230, "license_type": "permissive", "max_line_length": 77, "num_lines": 9, "path": "/images/docker-registry/docker-entrypoint.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\nhtpasswd -bBn $REGISTRY_INITIAL_USER \"$REGISTRY_INITIAL_PASSWORD\" >> htpasswd\ncase \"$1\" in\n *.yaml|*.yml) set -- registry serve \"$@\" ;;\n serve|garbage-collect|help|-*) set -- registry \"$@\" ;;\n\nesac\nexec \"$@\"" }, { "alpha_fraction": 0.6209150552749634, "alphanum_fraction": 0.6326797604560852, "avg_line_length": 31.553192138671875, "blob_id": "46e4c29aca579ebd06055e7dc7fcf12d04052b8e", "content_id": "5c1fcb6f48558ae7904e05fe85aa56cc3dbbd0ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1530, "license_type": "permissive", "max_line_length": 345, "num_lines": 47, "path": "/deploy/myChecks.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Author: S M Y ALTAMASH <[email protected]> \"\"\"\n\nimport os\nimport re\nimport sys\nimport subprocess\nfrom urllib.request import Request, urlopen\nfrom urllib.error import URLError, HTTPError\n\n\nprotocol=sys.argv[1]\nserverIP=sys.argv[2]\nmydictionary={\"MONIT\":\"{}://{}:2812\".format(protocol,serverIP),\"PROMETHEUS\":\"{}://{}:9090\".format(protocol,serverIP),\"Alertmanager\":\"{}://{}:9093/alertmanager\".format(protocol,serverIP),\"KEYCLOAK\":\"{}://{}/auth\".format(protocol,serverIP),\"SUNBIRD PORTAL\":\"{}://{}\".format(protocol,serverIP),\"GRAFANA\":\"{}://{}/grafana\".format(protocol,serverIP)}\n\ndef checkStatus(req,name):\n\ttry:\n\t\tresponse = urlopen(req)\n\texcept HTTPError as e:\n\t\tprint(str(name) + ' ' + str(\" is not Working\"))\n\texcept URLError as e:\n\t\tprint(str(name) + ' ' + str(' is not Working'))\n\telse:\n\t\tprint(str(name) + ' ' + str(\" is working\"))\n\ndef checkAvailibility():\n\tfor k in mydictionary:\n\t\tcheckStatus(mydictionary[k],k)\n\ndef checkContainerReplication():\n\tprint(\"Checking Container Replication:-\\n\")\n\treslt=(subprocess.check_output(\"sudo docker service ls | grep \\\" 0/\\\" | awk '{ print $2 }'\", shell=True)).splitlines()\n\tfor val in reslt:\n\t\tprint(\"Container \"+str(val,\"utf-8\")+\" Failed to replicate\")\n\n\nprint(\"\\n-----------------------------------------\\n\")\nprint(\"Checking The service Working Status:-\\n\")\ncheckAvailibility()\nprint(\"\\n-----------------------------------------\\n\")\n\ncheckContainerReplication()\nprint(\"\\n-----------------------------------------\\n\")\n\n\n\n#print(\"\\nThe King Never Fails To Win His Destiny\\n\")\n" }, { "alpha_fraction": 0.7648183703422546, "alphanum_fraction": 0.7648183703422546, "avg_line_length": 51.29999923706055, "blob_id": "1eba70fa24e15cf66bd122e4ed7a5d1419eac54e", "content_id": "24a871884d44be264db2dac007456ad78cdde3d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 523, "license_type": "permissive", "max_line_length": 164, "num_lines": 10, "path": "/images/keycloak/docker-entrypoint.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nexport HOSTNAME_IP=$(hostname -i)\necho \"hostname -i returned: $HOSTNAME_IP\"\necho \"export POSTGRES_PASSWORD=`cat /run/secrets/postgresql_keycloak_pass`\" >> ~/.bashrc\ncd keycloak/bin\n./add-user-keycloak.sh -u $KEYCLOAK_ADMIN_USERNAME -p $KEYCLOAK_ADMIN_INITIAL_PASSWORD\nsource ~/.bashrc\necho \"TCPPING_INITIAL_HOSTS: $TCPPING_INITIAL_HOSTS\"\nexec /opt/jboss/keycloak/bin/standalone.sh -b $HOSTNAME_IP -Djboss.bind.address.private=$HOSTNAME_IP -Djboss.jgroups.tcpping.initial_hosts=$TCPPING_INITIAL_HOSTS $@\nexit $?\n" }, { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.782608687877655, "avg_line_length": 12.800000190734863, "blob_id": "354c83e76eac15ece96de6c7ace3d762f5673b67", "content_id": "9f3b525c49f27197a857d01911dce4ae8de37109", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 69, "license_type": "permissive", "max_line_length": 24, "num_lines": 5, "path": "/ansible/roles/cert-templates/templates/generateVars.sh.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nnpm install\nsource setVars.sh \nbash createStaticJson.sh\n" }, { "alpha_fraction": 0.6492069363594055, "alphanum_fraction": 0.6514201164245605, "avg_line_length": 26.93814468383789, "blob_id": "8e0cbd1c2e725e64b8e0eeec4247ffe6c4e6e3a7", "content_id": "94eca779542b9af1639490af19c564db62c07ffd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2713, "license_type": "permissive", "max_line_length": 135, "num_lines": 97, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/authorization/permission.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Marcos Pereira <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n\nclass Permission:\n \"\"\"\n Consider this simple and very common permission:\n\n A permission associates the object being protected with the policies that must be evaluated to determine whether access is granted.\n\n X CAN DO Y ON RESOURCE Z\n\n where …\n X represents one or more users, roles, or groups, or a combination of them. You can\n also use claims and context here.\n Y represents an action to be performed, for example, write, view, and so on.\n Z represents a protected resource, for example, \"/accounts\".\n\n https://keycloak.gitbooks.io/documentation/authorization_services/topics/permission/overview.html\n\n \"\"\"\n\n def __init__(self, name, type, logic, decision_strategy):\n self._name = name\n self._type = type\n self._logic = logic\n self._decision_strategy = decision_strategy\n self._resources = []\n self._scopes = []\n\n def __repr__(self):\n return \"<Permission: %s (%s)>\" % (self.name, self.type)\n\n def __str__(self):\n return \"Permission: %s (%s)\" % (self.name, self.type)\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n\n @property\n def type(self):\n return self._type\n\n @type.setter\n def type(self, value):\n self._type = value\n\n @property\n def logic(self):\n return self._logic\n\n @logic.setter\n def logic(self, value):\n self._logic = value\n\n @property\n def decision_strategy(self):\n return self._decision_strategy\n\n @decision_strategy.setter\n def decision_strategy(self, value):\n self._decision_strategy = value\n\n @property\n def resources(self):\n return self._resources\n\n @resources.setter\n def resources(self, value):\n self._resources = value\n\n @property\n def scopes(self):\n return self._scopes\n\n @scopes.setter\n def scopes(self, value):\n self._scopes = value\n\n" }, { "alpha_fraction": 0.8518518805503845, "alphanum_fraction": 0.8518518805503845, "avg_line_length": 66.5, "blob_id": "d660a9489db63c8f08fd4d11ecc3bd623395709a", "content_id": "079b6d1cfa6b5e24bc710836aba1f6d963537add", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 135, "license_type": "permissive", "max_line_length": 68, "num_lines": 2, "path": "/ansible/roles/postgres-migration/files/sunbird_programs/V3.9.0.0.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "ALTER TABLE program ADD COLUMN targetPrimaryCategoryNames text[];\nALTER TABLE nomination ADD COLUMN targetPrimaryCategoryNames text[];\n" }, { "alpha_fraction": 0.5901088714599609, "alphanum_fraction": 0.6004169583320618, "avg_line_length": 30.169675827026367, "blob_id": "882b11b335364cf449678e970ffc2944ad10eb03", "content_id": "1dbec026abad911de950bd8a63fb33183f33fd7e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 8634, "license_type": "permissive", "max_line_length": 95, "num_lines": 277, "path": "/images/kong/plugins/0.14.1/rate-limiting/policies/init.lua", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "local singletons = require \"kong.singletons\"\nlocal timestamp = require \"kong.tools.timestamp\"\nlocal redis = require \"resty.redis\"\nlocal policy_cluster = require \"kong.plugins.rate-limiting.policies.cluster\"\nlocal reports = require \"kong.reports\"\n\n\nlocal ngx_log = ngx.log\nlocal shm = ngx.shared.kong_rate_limiting_counters\nlocal pairs = pairs\nlocal fmt = string.format\n\n\nlocal NULL_UUID = \"00000000-0000-0000-0000-000000000000\"\n\n\nlocal function get_ids(conf)\n conf = conf or {}\n\n local api_id = conf.api_id\n\n if api_id and api_id ~= ngx.null then\n return nil, nil, api_id\n end\n\n api_id = NULL_UUID\n\n local route_id = conf.route_id\n local service_id = conf.service_id\n\n if not route_id or route_id == ngx.null then\n route_id = NULL_UUID\n end\n\n if not service_id or service_id == ngx.null then\n service_id = NULL_UUID\n end\n\n return route_id, service_id, api_id\nend\n\n\nlocal get_local_key = function(conf, identifier, period_date, name)\n local route_id, service_id, api_id = get_ids(conf)\n\n if api_id == NULL_UUID then\n return fmt(\"ratelimit:%s:%s:%s:%s:%s\", route_id, service_id, identifier, period_date, name)\n end\n\n return fmt(\"ratelimit:%s:%s:%s:%s\", api_id, identifier, period_date, name)\nend\n\n\nlocal EXPIRATIONS = {\n second = 1,\n minute = 60,\n hour = 3600,\n day = 86400,\n month = 2592000,\n year = 31536000,\n}\n\n\nreturn {\n [\"local\"] = {\n increment = function(conf, limits, identifier, current_timestamp, value)\n local periods = timestamp.get_timestamps(current_timestamp)\n for period, period_date in pairs(periods) do\n if limits[period] then\n local cache_key = get_local_key(conf, identifier, period_date, period)\n local newval, err = shm:incr(cache_key, value, 0, EXPIRATIONS[period])\n if not newval then\n ngx_log(ngx.ERR, \"[rate-limiting] could not increment counter \",\n \"for period '\", period, \"': \", err)\n return nil, err\n end\n end\n end\n\n return true\n end,\n usage = function(conf, identifier, current_timestamp, name)\n local periods = timestamp.get_timestamps(current_timestamp)\n local cache_key = get_local_key(conf, identifier, periods[name], name)\n local current_metric, err = shm:get(cache_key)\n if err then\n return nil, err\n end\n return current_metric and current_metric or 0\n end\n },\n [\"cluster\"] = {\n increment = function(conf, limits, identifier, current_timestamp, value)\n local db = singletons.dao.db\n local route_id, service_id, api_id = get_ids(conf)\n\n local ok, err\n\n if api_id == NULL_UUID then\n ok, err = policy_cluster[db.name].increment(db, limits, route_id, service_id,\n identifier, current_timestamp, value)\n\n else\n ok, err = policy_cluster[db.name].increment_api(db, limits, api_id, identifier,\n current_timestamp, value)\n end\n\n if not ok then\n ngx_log(ngx.ERR, \"[rate-limiting] cluster policy: could not increment \",\n db.name, \" counter: \", err)\n end\n\n return ok, err\n end,\n usage = function(conf, identifier, current_timestamp, name)\n local db = singletons.dao.db\n local route_id, service_id, api_id = get_ids(conf)\n local row, err\n\n if api_id == NULL_UUID then\n row, err = policy_cluster[db.name].find(db, route_id, service_id,\n identifier, current_timestamp, name)\n else\n row, err = policy_cluster[db.name].find_api(db, api_id, identifier,\n current_timestamp, name)\n end\n\n if err then\n return nil, err\n end\n\n return row and row.value or 0\n end\n },\n [\"redis\"] = {\n increment = function(conf, limits, identifier, current_timestamp, value)\n local red = redis:new()\n red:set_timeout(conf.redis_timeout)\n local ok, err = red:connect(conf.redis_host, conf.redis_port)\n if not ok then\n ngx_log(ngx.ERR, \"failed to connect to Redis: \", err)\n return nil, err\n end\n\n local times, err = red:get_reused_times()\n if err then\n ngx_log(ngx.ERR, \"failed to get connect reused times: \", err)\n return nil, err\n end\n\n if times == 0 and conf.redis_password and conf.redis_password ~= \"\" then\n local ok, err = red:auth(conf.redis_password)\n if not ok then\n ngx_log(ngx.ERR, \"failed to auth Redis: \", err)\n return nil, err\n end\n end\n\n if times ~= 0 or conf.redis_database then\n -- The connection pool is shared between multiple instances of this\n -- plugin, and instances of the response-ratelimiting plugin.\n -- Because there isn't a way for us to know which Redis database a given\n -- socket is connected to without a roundtrip, we force the retrieved\n -- socket to select the desired database.\n -- When the connection is fresh and the database is the default one, we\n -- can skip this roundtrip.\n\n local ok, err = red:select(conf.redis_database or 0)\n if not ok then\n ngx_log(ngx.ERR, \"failed to change Redis database: \", err)\n return nil, err\n end\n end\n\n local keys = {}\n local expirations = {}\n local idx = 0\n local periods = timestamp.get_timestamps(current_timestamp)\n for period, period_date in pairs(periods) do\n if limits[period] then\n local cache_key = get_local_key(conf, identifier, period_date, period)\n local exists, err = red:exists(cache_key)\n if err then\n ngx_log(ngx.ERR, \"failed to query Redis: \", err)\n return nil, err\n end\n\n idx = idx + 1\n keys[idx] = cache_key\n if not exists or exists == 0 then\n expirations[idx] = EXPIRATIONS[period]\n end\n end\n end\n\n red:init_pipeline()\n for i = 1, idx do\n red:incrby(keys[i], value)\n if expirations[i] then\n red:expire(keys[i], expirations[i])\n end\n end\n\n local _, err = red:commit_pipeline()\n if err then\n ngx_log(ngx.ERR, \"failed to commit pipeline in Redis: \", err)\n return nil, err\n end\n local ok, err = red:set_keepalive(10000, 100)\n if not ok then\n ngx_log(ngx.ERR, \"failed to set Redis keepalive: \", err)\n return nil, err\n end\n\n return true\n end,\n usage = function(conf, identifier, current_timestamp, name)\n local red = redis:new()\n red:set_timeout(conf.redis_timeout)\n local ok, err = red:connect(conf.redis_host, conf.redis_port)\n if not ok then\n ngx_log(ngx.ERR, \"failed to connect to Redis: \", err)\n return nil, err\n end\n\n local times, err = red:get_reused_times()\n if err then\n ngx_log(ngx.ERR, \"failed to get connect reused times: \", err)\n return nil, err\n end\n\n if times == 0 and conf.redis_password and conf.redis_password ~= \"\" then\n local ok, err = red:auth(conf.redis_password)\n if not ok then\n ngx_log(ngx.ERR, \"failed to connect to Redis: \", err)\n return nil, err\n end\n end\n\n if times ~= 0 or conf.redis_database then\n -- The connection pool is shared between multiple instances of this\n -- plugin, and instances of the response-ratelimiting plugin.\n -- Because there isn't a way for us to know which Redis database a given\n -- socket is connected to without a roundtrip, we force the retrieved\n -- socket to select the desired database.\n -- When the connection is fresh and the database is the default one, we\n -- can skip this roundtrip.\n\n local ok, err = red:select(conf.redis_database or 0)\n if not ok then\n ngx_log(ngx.ERR, \"failed to change Redis database: \", err)\n return nil, err\n end\n end\n\n reports.retrieve_redis_version(red)\n\n local periods = timestamp.get_timestamps(current_timestamp)\n local cache_key = get_local_key(conf, identifier, periods[name], name)\n local current_metric, err = red:get(cache_key)\n if err then\n return nil, err\n end\n\n if current_metric == ngx.null then\n current_metric = nil\n end\n\n local ok, err = red:set_keepalive(10000, 100)\n if not ok then\n ngx_log(ngx.ERR, \"failed to set Redis keepalive: \", err)\n end\n\n return current_metric or 0\n end\n }\n}\n" }, { "alpha_fraction": 0.5942028760910034, "alphanum_fraction": 0.6202898621559143, "avg_line_length": 19.294116973876953, "blob_id": "6fda0e9066c854020281393fd09670ef7c13e561", "content_id": "21d7fa708ffafff428dba7da883383731f8862df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 345, "license_type": "permissive", "max_line_length": 63, "num_lines": 17, "path": "/deploy/install-deps.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Build script\n# set -o errexit\n\nansible_version=2.5.0.0\n\n# Checking for ansible\ncase \"$(ansible --version 2> /dev/null | head -n1)\" in \n *2.5.0*)\n ;;\n *)\n # Install Ansible\n sudo apt update \n sudo apt install -y python python-pkg-resources python-pip\n sudo pip install ansible==$ansible_version\n ;;\nesac\n" }, { "alpha_fraction": 0.5480940937995911, "alphanum_fraction": 0.5837793946266174, "avg_line_length": 30.943004608154297, "blob_id": "3c648b5368dd2c7b11494d920e0d3cccd71e3009", "content_id": "805785681d758244d3a7cf54567cbccc7fa6386d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 6165, "license_type": "permissive", "max_line_length": 142, "num_lines": 193, "path": "/deploy/sanity.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Author Rajesh Rajendran <[email protected]>\n\nconfig_dir=.sunbird\nbold=$(tput bold)\nnormal=$(tput sgr0)\nssh_user=${1:-$(whoami)}\nssh_key=$2\n\n# Application versions\nes_version=5.4\ndocker_version=\"17.06|18.03\"\npostgres_version=9.5\ncassandra_version=3.9\njava_version=1.8.0_162\nubuntu_version=16.04\ndocker_manager_ram=2\ndocker_node_ram=6\nes_ram=3\ndb_ram=3\n\necho -e \"\\n\\e[0;36m${bold}checking for sunbird prerequisites...${normal}\"\necho -e \"\\e[0;32msuccess \\e[0;31mfatal \\e[0;33mwarning\"\n\nif [ ! -z $ssh_key ];then\n # Refreshing ssh-agent\n eval $(ssh-agent) &> /dev/null\n # Adding key to ssh-agent\n ssh-add $ssh_key &> /dev/null\nfi\n\nif [ -d .sunbird/ignore ]; then mkdir -p .sunbird/ignore; fi\nrm -rf .sunbird/ignore/*\n\n# Sourcing the variables\nsource $config_dir/generate_host.sh &> /dev/null\n\nnssh() {\n ssh -o \"UserKnownHostsFile /dev/null\" -o \"StrictHostKeyChecking false\" -o \"LogLevel ERROR\" $@\n return $?\n}\n\nresult() {\n if [[ $1 -ne 0 ]];then\n echo -e \"\\e[0;31m${bold} FAILED${normal}\"\n fail=1\n else\n echo -e \"\\e[0;32m${bold} OK${normal}\"\n fi\n}\n\nssh_connection() {\n echo -en \"\\e[0;35m SSH connection to $1 \"\n nssh -o ConnectTimeout=2 $ssh_user@$1 exit 0 &> /dev/null\n result $?\n}\n\nram() {\n nssh $ssh_user@$1 free -g | awk '{print $2}' | head -n2 | tail -1\n}\n\ncheck_compatibility() {\n\t\n\t# Checking the compatibility of installed applications with supported versions and RAM requirement.\n\t# eg: check_compatibility version <installed_application_version> <supported_version1,2,3,4>\n\t# eg: check_compatibility <required_RAM_size in GB> <server_ram_size in GB>\n\t\n\t# Creating array out of service versions\n IFS=',' read -ra service_versions <<<$3\n local version=$2\n\tlocal compatibility=0\n case $1 in\n version)\n\t\t\tfor service_version in ${service_versions[@]}; do\n\t\t\t\t[[ \"$version\" =~ \"$service_version\" ]] && compatibility=1 && break || compatibility=0\n\t\t\tdone\n\t\t\tif [[ $compatibility == 0 ]];then\n\t\t\t\techo -e \"\\e[0;31m${bold} INCOMPATIBLE \\n \\e[0;32mSupported Versions: ${service_versions[@]} ${normal}\" \n\t\t\telse\n\t\t\t\techo -e \"\\e[0;32m${bold} OK ${normal}\"\n\t\t\tfi\n\t\t\t;;\n ram)\n\t\t\tfor service_version in ${service_versions[@]}; do\n if [[ $service_version -le $version ]]; then\n echo -e \"\\e[0;32m${bold} OK ${normal}\"\n else\n echo -e \"\\e[0;33m${bold} NOT ENOUGH ${normal}\"\n echo -e \"\\e[0;33m${bold} Minimum Requirement: ${version} ${normal}\"\n fi\n done\n\t\t\t;;\n esac\n\nunset service_versions\n}\n\n# Checks for elastic search\ncheck_es() {\n echo -e \"\\n\\e[0;36m ${bold}Checking elasticsearch${normal}\"\n ips $1\n for ip in ${arr[@]}; do\n ssh_connection $ip\n # Checking for elastic search version\n if [ $(nc -z $ip 9200; echo $?) -eq 0 ];then\n local version=$(nssh $ssh_user@$ip curl -sS $ip:9200 | grep number| awk '{print $3}')\n echo -ne \"\\e[0;35m Elastic search Version: \\e[0;32m$version\"\n check_compatibility version \"$version\" \"$es_version\" es\n else \n echo -e \"\\e[0;35m Elastic search Version: \\e[0;32m${bold}Not Installed${normal} \"\n fi\n # Check RAM\n local ram_=$(($(ram $ip)+1))\n echo -ne \"\\e[0;35m Elastic search RAM: \\e[0;32m${ram_}G \"\n check_compatibility ram $ram_ \"$es_ram\"\n done\n}\n\n\ncheck_cassandra() {\n echo -e \"\\n\\e[0;36m ${bold}Checking Cassandra${normal}\"\n ips $1\n for ip in ${arr[@]}; do\n ssh_connection $ip\n # Checking for cassandra version\n if [ $(nc -z $ip 9042; echo $? ) -eq 0 ];then\n local version=$(nssh $ssh_user@$ip \"cqlsh localhost 9042 -e 'select release_version from system.local;'\" | tail -3 | head -n1)\n echo -ne \"\\e[0;35m Cassandra Version: \\e[0;32m$version \"\n check_compatibility version \"$version\" \"$cassandra_version\" cassandra\n else \n echo -e \"\\e[0;35m Cassandra Version: \\e[0;32m${bold}Not Installed${normal} \"\n fi\n done\n}\n\ncheck_postgres() {\n echo -e \"\\n\\e[0;36m ${bold}Checking Postgres${normal}\"\n ips $1\n for ip in ${arr[@]}; do\n ssh_connection $ip\n # Checking for Postgres Version\n if [ $(nc -z $ip 5432; echo $? ) -eq 0 ];then\n local version=$(nssh $ssh_user@$ip pg_config --version)\n echo -ne \"\\e[0;35m Postgres Version: \\e[0;32m$version \"\n check_compatibility version \"$version\" \"$postgres_version\" postgres\n else \n echo -e \"\\e[0;35m Postgres Version: \\e[0;32m${bold}Not Installed${normal} \"\n fi\n done\n}\n\n# Checking docker\ncheck_docker() {\n echo -e \"\\n\\e[0;36m ${bold}Checking Docker $2 ${normal}\"\n ips $1\n for ip in ${arr[@]}; do\n ssh_connection $ip\n if [ $(nssh $ssh_user@$ip which docker &> /dev/null; echo $?) -eq 0 ];then\n local version=$(nssh $ssh_user@$ip docker --version | head -n1 | awk '{print $3\" \"$4\" \"$5}')\n echo -ne \"\\e[0;35m Docker Version: \\e[0;32m$version \"\n version=$(echo -ne \"$version\" | cut -c1-5)\n if [[ $version =~ ($docker_version) ]];then\n echo -e \"\\e[0;32m${bold} OK ${normal}\"\n touch \".sunbird/ignore/${service_name}\"\n else\n echo -e \"\\e[0;31m${bold} FATAL${normal}\"\n echo -e \"\\e[0;31m${bold} Sunbird has been tested with Docker version $docker_version. Please Install $docker_version${normal}\"\n fail=1\n fi\n else\n echo -e \"\\e[0;35m Docker Version: \\e[0;32m${bold}Not Installed${normal} \"\n fi\n local ram_=$(($(ram $ip)+1))\n echo -ne \"\\e[0;35m Docker $2 RAM: \\e[0;32m${ram_}G \"\n local docker_ram=docker_${2}_ram\n check_compatibility ram $ram_ $docker_ram\n done\n}\n\n\n\ncheck_es $elasticsearch_ips\ncheck_docker $swarm_manager_ips manager\ncheck_docker $swarm_node_ips node\npostgres_ips=$postgres_master_ips,$postgres_slave_ips\ncheck_postgres $postgres_ips\ncheck_cassandra $cassandra_ips\n\nif [[ $fail ]];then\n echo -e \"\\n\\e[0;31m ${bold}PLEASE RECTIFY THE ISSUES AND RUN AGAIN${normal}\\n\"\n exit 1\nfi\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5076923370361328, "avg_line_length": 28.545454025268555, "blob_id": "08c77e51cca2783f71858704b962dc9558888e33", "content_id": "2e09126ff2456fbcd99529b90d33838bb6e5c012", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 650, "license_type": "permissive", "max_line_length": 96, "num_lines": 22, "path": "/deploy/utilities/rotateKey.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Author S M Y <[email protected]>\nRGName=$1\nKeyFileLocation=$2\nvmnames=( $(az vm list-ip-addresses -o table -g $RGName | awk 'NR>2{print $1}' | tr \"\\n\" \" \") )\n\nif [ $# -ne 2 ];\nthen\n\techo \"Usage: bash rotateKey.sh ResourceGroupName KeyFileLocation\"\nfi\n\nfor name in \"${vmnames[@]}\"\ndo\n\t#Rotating SSH Pem Key\n\techo \"changing key for server $name my master\"\n\techo \"------------------------------------------------------------------\"\n\taz vm user update --name $name \\\n\t\t\t --resource-group $RGName \\\n\t\t\t --username ops \\\n\t\t\t --ssh-key-value \"$(cat $KeyFileLocation)\"\n\techo \"------------------------------------------------------------------\"\ndone\n" }, { "alpha_fraction": 0.5796349048614502, "alphanum_fraction": 0.5910232663154602, "avg_line_length": 39.3445930480957, "blob_id": "0cbf8ad3fc9668c8126c7af80e7bb25a93d68d26", "content_id": "97ec1792dfa5312c4b6c5d2fa4563e7577a3037a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5971, "license_type": "permissive", "max_line_length": 85, "num_lines": 148, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/tests/test_connection.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Marcos Pereira <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nfrom httmock import urlmatch, response, HTTMock, all_requests\n\nfrom ..connection import ConnectionManager\n\n\ntry:\n import unittest\nexcept ImportError:\n import unittest2 as unittest\n\n \nclass TestConnection(unittest.TestCase):\n \n def setUp(self):\n self._conn = ConnectionManager(\n base_url=\"http://localhost:8080/\",\n headers={}, \n timeout=60)\n\n @all_requests\n def response_content_success(self, url, request):\n headers = {'content-type': 'application/json'}\n content = b'response_ok'\n return response(200, content, headers, None, 5, request)\n \n def test_raw_get(self): \n with HTTMock(self.response_content_success):\n resp = self._conn.raw_get(\"/known_path\")\n self.assertEqual(resp.content, b'response_ok')\n self.assertEqual(resp.status_code, 200) \n\n def test_raw_post(self):\n\n @urlmatch(path=\"/known_path\", method=\"post\")\n def response_post_success(url, request):\n headers = {'content-type': 'application/json'}\n content = 'response'.encode(\"utf-8\")\n return response(201, content, headers, None, 5, request)\n \n with HTTMock(response_post_success):\n resp = self._conn.raw_post(\"/known_path\",\n {'field': 'value'})\n self.assertEqual(resp.content, b'response')\n self.assertEqual(resp.status_code, 201)\n\n def test_raw_put(self):\n @urlmatch(netloc=\"localhost\", path=\"/known_path\", method=\"put\")\n def response_put_success(url, request):\n headers = {'content-type': 'application/json'}\n content = 'response'.encode(\"utf-8\")\n return response(200, content, headers, None, 5, request)\n\n with HTTMock(response_put_success):\n resp = self._conn.raw_put(\"/known_path\",\n {'field': 'value'})\n self.assertEqual(resp.content, b'response')\n self.assertEqual(resp.status_code, 200)\n\n def test_raw_get_fail(self):\n\n @urlmatch(netloc=\"localhost\", path=\"/known_path\", method=\"get\")\n def response_get_fail(url, request):\n headers = {'content-type': 'application/json'}\n content = \"404 page not found\".encode(\"utf-8\")\n return response(404, content, headers, None, 5, request)\n \n with HTTMock(response_get_fail):\n resp = self._conn.raw_get(\"/known_path\")\n\n self.assertEqual(resp.content, b\"404 page not found\")\n self.assertEqual(resp.status_code, 404) \n \n def test_raw_post_fail(self):\n\n @urlmatch(netloc=\"localhost\", path=\"/known_path\", method=\"post\")\n def response_post_fail(url, request):\n headers = {'content-type': 'application/json'}\n content = str([\"Start can't be blank\"]).encode(\"utf-8\")\n return response(404, content, headers, None, 5, request)\n \n with HTTMock(response_post_fail):\n resp = self._conn.raw_post(\"/known_path\",\n {'field': 'value'})\n self.assertEqual(resp.content, str([\"Start can't be blank\"]).encode(\"utf-8\"))\n self.assertEqual(resp.status_code, 404)\n\n def test_raw_put_fail(self):\n\n @urlmatch(netloc=\"localhost\", path=\"/known_path\", method=\"put\")\n def response_put_fail(url, request):\n headers = {'content-type': 'application/json'}\n content = str([\"Start can't be blank\"]).encode(\"utf-8\")\n return response(404, content, headers, None, 5, request)\n\n with HTTMock(response_put_fail):\n resp = self._conn.raw_put(\"/known_path\",\n {'field': 'value'})\n self.assertEqual(resp.content, str([\"Start can't be blank\"]).encode(\"utf-8\"))\n self.assertEqual(resp.status_code, 404)\n\n def test_add_param_headers(self):\n self._conn.add_param_headers(\"test\", \"value\")\n self.assertEqual(self._conn.headers,\n {\"test\": \"value\"})\n\n def test_del_param_headers(self):\n self._conn.add_param_headers(\"test\", \"value\")\n self._conn.del_param_headers(\"test\")\n self.assertEqual(self._conn.headers, {})\n \n def test_clean_param_headers(self):\n self._conn.add_param_headers(\"test\", \"value\")\n self.assertEqual(self._conn.headers,\n {\"test\": \"value\"})\n self._conn.clean_headers()\n self.assertEqual(self._conn.headers, {})\n\n def test_exist_param_headers(self):\n self._conn.add_param_headers(\"test\", \"value\")\n self.assertTrue(self._conn.exist_param_headers(\"test\"))\n self.assertFalse(self._conn.exist_param_headers(\"test_no\"))\n \n def test_get_param_headers(self):\n self._conn.add_param_headers(\"test\", \"value\")\n self.assertTrue(self._conn.exist_param_headers(\"test\"))\n self.assertFalse(self._conn.exist_param_headers(\"test_no\"))\n \n def test_get_headers(self):\n self._conn.add_param_headers(\"test\", \"value\")\n self.assertEqual(self._conn.headers,\n {\"test\": \"value\"})\n" }, { "alpha_fraction": 0.6091476082801819, "alphanum_fraction": 0.6209286451339722, "avg_line_length": 23.474576950073242, "blob_id": "c9f643125c92e8694f66d4f67e96299079d6d403", "content_id": "6069ddb21d83ae34f37fab642cabdbf05c9327a7", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1443, "license_type": "permissive", "max_line_length": 94, "num_lines": 59, "path": "/ansible/roles/cassandra/templates/cassandra_backup.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nexport PATH=/sbin:/bin:/usr/sbin:/usr/bin:/opt/java/bin\n\nDATE=`date +%Y%m%d`\n\nSNAME=\"snapshot-$DATE\"\n\nBACKUPDIRECTORY=\"/data/cassandra/backup/\"\n\nif [ ! -d \"$BACKUPDIRECTORY\" ]; then\n echo \"Directory $BACKUPDIRECTORY not found, creating...\"\n mkdir $BACKUPDIRECTORY\nfi\n\nif [ ! -d \"$BACKUPDIRECTORY\" ]; then\n echo \"Directory $BACKUPDIRECTORY not found, exit...\"\n exit\nfi\n\necho\necho \"Snapshot name: $SNAME\"\necho \"Clear all snapshots\"\nnodetool -h 127.0.0.1 clearsnapshot\n\ncd $BACKUPDIRECTORY\npwd\nrm -rf *\n\necho \"Taking snapshot\"\nnodetool -h 127.0.0.1 snapshot -t $SNAME\nSFILES=`ls -1 -d /data/cassandra/data/*/*/snapshots/$SNAME`\nfor f in $SFILES\ndo\n echo \"Process snapshot $f\"\n TABLE=`echo $f | awk -F/ '{print $(NF-2)}'`\n KEYSPACE=`echo $f | awk -F/ '{print $(NF-3)}'`\n\n if [ ! -d \"$BACKUPDIRECTORY/$SNAME\" ]; then\n mkdir $BACKUPDIRECTORY/$SNAME\n fi\n\n if [ ! -d \"$BACKUPDIRECTORY/$SNAME/$KEYSPACE\" ]; then\n mkdir $BACKUPDIRECTORY/$SNAME/$KEYSPACE\n fi\n\n mkdir $BACKUPDIRECTORY/$SNAME/$KEYSPACE/$TABLE\n find $f -maxdepth 1 -type f -exec mv -t $BACKUPDIRECTORY/$SNAME/$KEYSPACE/$TABLE/ {} +\ndone\ncd $BACKUPDIRECTORY\nzip -r cassandra_backup_`date +%Y%m%d`.zip .\ncd -\necho \"Clear Incremental Backups\"\nSFILES=`ls -1 -d /data/cassandra/data/*/*/backups/`\nfor f in $SFILES\ndo\n echo \"Clear $f\"\n rm -f $f*\ndone" }, { "alpha_fraction": 0.7804877758026123, "alphanum_fraction": 0.8170731663703918, "avg_line_length": 26.33333396911621, "blob_id": "6aee434c7084cccfe6921ad6aaed30e693520968", "content_id": "0b9913076d5dc36e8f49ab9c46ae6f81751f659d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go Module", "length_bytes": 82, "license_type": "permissive", "max_line_length": 72, "num_lines": 3, "path": "/exporters/Go/tcp-logger/go.mod", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "module github.com/project-sunbird/sunbird-devops/exporters/Go/tcp-logger\n\ngo 1.17\n" }, { "alpha_fraction": 0.6535432934761047, "alphanum_fraction": 0.6771653294563293, "avg_line_length": 41.33333206176758, "blob_id": "1a8d8e6b97f5fc7c0fd9a23a3ff8d880255ec440", "content_id": "4c474b3c0cbc9d22b7665983053284b871bd39ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 127, "license_type": "permissive", "max_line_length": 99, "num_lines": 3, "path": "/images/cassandra_jmx_exporter/metadata.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# return version\necho '{\"name\":\"cassandra_jmx_exporter\",\"version\":\"0.11\",\"org\":\"sunbird\",\"hubuser\":\"purplesunbird\"}'\n" }, { "alpha_fraction": 0.6877394914627075, "alphanum_fraction": 0.6992337107658386, "avg_line_length": 31.625, "blob_id": "b3a695233718b8ffebe1f86e7ec4de516fa1a34b", "content_id": "d37c4287dfa376f2d8712eab9ad87230510d9b07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 522, "license_type": "permissive", "max_line_length": 202, "num_lines": 16, "path": "/deploy/grafana/backup.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# How to run\n# docker run --rm -v /etc/passwd:/etc/passwd -u $(id -u):$(id -g) -v$(pwd):/work -v $(pwd)/backup.sh:/work/backup.sh rjshrjndrn/wizzy /work/backup.sh https://grafna/url admin password <import or export>\nurl=$1\nusername=$2\npassword=$3\nmode=${4:-import}\nitem=${5:-dashboards}\nscript=$(echo $0)\ncd $(dirname \"$script\")\necho ${mode}ing grafafna in $(dirname \"$script\")\nwizzy init\nwizzy set grafana url $url\nwizzy set grafana username $username\nwizzy set grafana password $password\nwizzy $mode $item\n" }, { "alpha_fraction": 0.6545454263687134, "alphanum_fraction": 0.6888889074325562, "avg_line_length": 44.09090805053711, "blob_id": "86d42d9ac55ee2b5b4eba9bea51ea78c845a7fd4", "content_id": "26188c9ed55ad5d27205fb231967418ac30d5271", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 495, "license_type": "permissive", "max_line_length": 149, "num_lines": 11, "path": "/ansible/roles/jmeter-deploy/templates/upload_jmeter_logs.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nIP_ADDR=`curl http://169.254.169.254/latest/meta-data/local-ipv4`\nscenario_id=$1\nINSTANCE=`echo $IP_ADDR | sed 's/\\.//g'`\nLOG_FILE_NAME=\"${scenario_id}_${INSTANCE}\"\ncd /mnt/data/benchmark/logs/$scenario_id\ncp -r logs \"${LOG_FILE_NAME}_logs\"\ntar -czvf \"${LOG_FILE_NAME}_logs.tar.gz\" \"${LOG_FILE_NAME}_logs\"\naws s3 cp \"/mnt/data/benchmark/logs/$scenario_id/${LOG_FILE_NAME}_logs.tar.gz\" s3://ekstep-backups-sandbox/lp_service_logs/LP-PE/ --region ap-south-1\nrm -rf ${LOG_FILE_NAME}_log*" }, { "alpha_fraction": 0.743251621723175, "alphanum_fraction": 0.7455182075500488, "avg_line_length": 47.049503326416016, "blob_id": "7f0fe4bd03cd6e0ef060f52efd79a125cfd45fcf", "content_id": "917409c98c7577d8e07597b3a721610dad5a2245", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4853, "license_type": "permissive", "max_line_length": 126, "num_lines": 101, "path": "/deploy/generate-config.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ \"$#\" -ne 3 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <implementation-name> <environment-name> <type>\"\n echo -e \"\\nOPTIONS\\n\"\n echo \"type: core, azure\"\n echo \"implementation-name: Name of the implementation organization or the project using sunbird eg: ntp, nile\"\n echo \"environment-name: Name of the environment for which config should be generated. eg: dev, staging, production\"\n exit 1\nfi\n\nset -e\n\nIMPLEMENTATION_NAME=$1\nENVIRONMENT_NAME=$2\nCONFIG_TYPE=$3\n\nIMPLEMENTATION_DEVOPS_DIR=\"$IMPLEMENTATION_NAME-devops\"\n\nSCRIPT_BASE_DIR=$(dirname $0)\necho \"SCRIPT_BASE_DIR\" $SCRIPT_BASE_DIR\nSUNBIRD_DEVOPS_FOLDER=$SCRIPT_BASE_DIR/.. # TODO: This should be derived from script base path\necho \"SUNBIRD_DEVOPS_FOLDER\" $SUNBIRD_DEVOPS_FOLDER\nSAMPLE_ENVIRONMENT_NAME=sample\n\nBACKUP_SUFFIX=-`date +\"%Y-%m-%d-%H-%M-%S\"`.bak\n\nif [ $3 == \"core\" ]; then\n echo -e \"Creating core service/db configuration files...\\n\"\n sleep 1\n SAMPLE_INVENTORY_FILE=$SUNBIRD_DEVOPS_FOLDER/ansible/inventories/sample/hosts\n SAMPLE_GROUP_VARS_DIR=$SUNBIRD_DEVOPS_FOLDER/ansible/inventories/sample/group_vars\n SAMPLE_GROUP_VARS_FILE=$SAMPLE_GROUP_VARS_DIR/sample\n\n ENVIRONMENT_INVENTORY_DIR=$IMPLEMENTATION_DEVOPS_DIR/ansible/inventories/$ENVIRONMENT_NAME\n ENVIRONMENT_GROUP_VARS_DIR=$ENVIRONMENT_INVENTORY_DIR/group_vars\n\n ENVIRONMENT_INVENTORY_HOSTS_FILE=$ENVIRONMENT_INVENTORY_DIR/hosts\n ENVIRONMENT_GROUP_VARS_FILE=$ENVIRONMENT_GROUP_VARS_DIR/$ENVIRONMENT_NAME\n\n ENVIRONMENT_SECRET_FILE=$ENVIRONMENT_INVENTORY_DIR/secrets.yml\n\n # Create inventory\n mkdir -p $ENVIRONMENT_INVENTORY_DIR\n cp --backup --suffix $BACKUP_SUFFIX $SAMPLE_INVENTORY_FILE $ENVIRONMENT_INVENTORY_HOSTS_FILE\n sed -i -e s/\"$SAMPLE_ENVIRONMENT_NAME\"/\"$ENVIRONMENT_NAME\"/g $ENVIRONMENT_INVENTORY_HOSTS_FILE\n\n # Create group_vars\n mkdir -p $ENVIRONMENT_GROUP_VARS_DIR\n cp --backup --suffix $BACKUP_SUFFIX $SAMPLE_GROUP_VARS_FILE $ENVIRONMENT_GROUP_VARS_FILE\n sed -i -e s/\"$SAMPLE_ENVIRONMENT_NAME\"/\"$ENVIRONMENT_NAME\"/g $ENVIRONMENT_GROUP_VARS_FILE\n ## Additional group_vars\n cp --backup --suffix $BACKUP_SUFFIX $SAMPLE_GROUP_VARS_DIR/postgresql-master $ENVIRONMENT_GROUP_VARS_DIR/postgresql-master\n\n # Create secrets\n if [ ! -e \"$ENVIRONMENT_SECRET_FILE\" ]; then\n touch \"$ENVIRONMENT_SECRET_FILE\"\n fi\n\n echo \"Successfully generated $IMPLEMENTATION_DEVOPS_DIR directory with environment $ENVIRONMENT_NAME\"\n echo \"Please review & edit files $ENVIRONMENT_INVENTORY_HOSTS_FILE and $ENVIRONMENT_GROUP_VARS_FILE\"\n echo \"You can remove backup files by running find $IMPLEMENTATION_DEVOPS_DIR -name *.bak -type f -delete\"\nelif [ $3 == \"azure\" ]; then\n echo \"Creating azure cloud configuration files...\"\n sleep 1\n APP_DEPLOY_PARAMS_DIR=$IMPLEMENTATION_DEVOPS_DIR/$ENVIRONMENT_NAME/azure/app\n SAMPLE_APP_DEPLOY_PARAMS_DIR=$SUNBIRD_DEVOPS_FOLDER/cloud/azure/arm/swarm/acs-engine\n SAMPLE_DEPLOY_PARAMS_COMMON_FILE=$SAMPLE_APP_DEPLOY_PARAMS_DIR/common/azuredeploy.json\n SAMPLE_DEPLOY_PARAMS_JSON_FILE=$SAMPLE_APP_DEPLOY_PARAMS_DIR/production.sample/azuredeploy.parameters.json.sample\n SAMPLE_DEPLOY_ENV_FILE=$SAMPLE_APP_DEPLOY_PARAMS_DIR/production.sample/env.sh\n\n mkdir -p $APP_DEPLOY_PARAMS_DIR\n echo \"Created $APP_DEPLOY_PARAMS_DIR\"\n cp $SAMPLE_DEPLOY_PARAMS_COMMON_FILE $APP_DEPLOY_PARAMS_DIR/azuredeploy.json\n cp $SAMPLE_DEPLOY_PARAMS_JSON_FILE $APP_DEPLOY_PARAMS_DIR/azuredeploy.parameters.json\n cp $SAMPLE_DEPLOY_ENV_FILE $APP_DEPLOY_PARAMS_DIR/env.sh\n sed -i -e s/\"$SAMPLE_ENVIRONMENT_NAME\"/\"$ENVIRONMENT_NAME\"/g $APP_DEPLOY_PARAMS_DIR/azuredeploy.parameters.json\n sed -i -e s/\"$SAMPLE_ENVIRONMENT_NAME\"/\"$ENVIRONMENT_NAME\"/g $APP_DEPLOY_PARAMS_DIR/env.sh\n echo \"Copied Azure ARM template and params for Application\"\n echo \"Please update azuredeploy.parameters.json and env.sh\"\n\n echo \"Creating DB VM configuration files...\"\n\n DB_DEPLOY_PARAMS_DIR=$IMPLEMENTATION_DEVOPS_DIR/$ENVIRONMENT_NAME/azure/db\n SAMPLE_DB_DEPLOY_PARAMS_DIR=$SUNBIRD_DEVOPS_FOLDER/cloud/azure/arm/vm\n SAMPLE_DEPLOY_PARAMS_COMMON_FILE=$SAMPLE_DB_DEPLOY_PARAMS_DIR/azuredeploy.json\n SAMPLE_DEPLOY_PARAMS_JSON_FILE=$SAMPLE_DB_DEPLOY_PARAMS_DIR/azuredeploy.parameters.json.sample\n\n mkdir -p $DB_DEPLOY_PARAMS_DIR\n echo \"Created $DB_DEPLOY_PARAMS_DIR\"\n cp $SAMPLE_DEPLOY_PARAMS_COMMON_FILE $DB_DEPLOY_PARAMS_DIR/azuredeploy.json\n cp $SAMPLE_DEPLOY_PARAMS_JSON_FILE $DB_DEPLOY_PARAMS_DIR/azuredeploy.parameters.json\n sed -i -e s/\"$SAMPLE_ENVIRONMENT_NAME\"/\"$ENVIRONMENT_NAME\"/g $DB_DEPLOY_PARAMS_DIR/azuredeploy.parameters.json\n echo \"Copied Azure ARM template and params for DB\"\n echo \"Please update azuredeploy.parameters.json\"\nelse\n echo \"invalid option\"\nfi\nunset APP_DEPLOYMENT_JSON_PATH\nunset DB_DEPLOYMENT_JSON_PATH\n" }, { "alpha_fraction": 0.6892539262771606, "alphanum_fraction": 0.6960985660552979, "avg_line_length": 38.513511657714844, "blob_id": "0a978c2801dbabbdbf4b5807ed90388196e12462", "content_id": "43a64651d7e4e932f8a896d3cfc4a67e41ca061a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1461, "license_type": "permissive", "max_line_length": 230, "num_lines": 37, "path": "/ansible/roles/jmeter-deploy/templates/run_scenario.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nscenario_id=$1\nnumThreads=$2\nrampupTime=$3\nctrlLoops=$4\nJMETER_HOME={{ jmeter.home }}apache-jmeter-4.0\nSCENARIO_LOGS={{ jmeter.home }}logs\necho \"Executing $scenario_id\"\n\nif [ -f {{ jmeter.home }}logs/$scenario_id ]\nthen\n\trm {{ jmeter.home }}logs/$scenario_id\nfi\n\necho \"Instance Id: {{ ansible_default_ipv4.address }}\"\nIP_ADDR=`echo \"{{ ansible_default_ipv4.address }}\" | sed 's/\\.//g'`\n\nJMX_FILE_PATH={{ jmeter.home }}current_scenario/{{ jmeter.current_scenario }}.jmx\n\nmkdir {{ jmeter.home }}logs/$scenario_id\nmkdir {{ jmeter.home }}logs/$scenario_id/logs\nmkdir {{ jmeter.home }}logs/$scenario_id/server/\nrm {{ jmeter.home }}current_scenario/*.jmx\ncp {{ jmeter.home }}scenarios/base_{{ jmeter.current_scenario }}.jmx $JMX_FILE_PATH\n#cp {{ jmeter.home }}scenarios/{{ jmeter.current_input_file }} {{ jmeter.home }}current_scenario/{{ jmeter.current_input_file }}\nsed -i \"s/THREADS_COUNT/${numThreads}/g\" $JMX_FILE_PATH\nsed -i \"s/RAMPUP_TIME/${rampupTime}/g\" $JMX_FILE_PATH\nsed -i \"s/CTRL_LOOPS/${ctrlLoops}/g\" $JMX_FILE_PATH\nsed -i \"s/AUTH_KEY/AUTH_KEY/g\" $JMX_FILE_PATH\nsed -i \"s/SCENARIO_ID/${scenario_id}/g\" $JMX_FILE_PATH\nsed -i \"s/IP_ADDR/${IP_ADDR}/g\" $JMX_FILE_PATH\n\n\nnohup $JMETER_HOME/bin/jmeter.sh -n -t $JMX_FILE_PATH -R{{ jmeter.client_hosts }} -l $SCENARIO_LOGS/$scenario_id/logs/output.xml -j $SCENARIO_LOGS/$scenario_id/logs/jmeter.log > $SCENARIO_LOGS/$scenario_id/logs/scenario.log 2>&1 &\n\necho \"Execution of $scenario_id Complete.\"" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 24.33333396911621, "blob_id": "507d46ed0f24bc153b3f9e194fd67ea3c55ac689", "content_id": "51d77a363f3f819f5b0f1d4d05aece91e5266f0b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 75, "license_type": "permissive", "max_line_length": 54, "num_lines": 3, "path": "/images/logstash/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM logstash:2.4.1\n\nRUN apt-get update && apt-get -y install openjdk-8-jdk" }, { "alpha_fraction": 0.5878419280052185, "alphanum_fraction": 0.5981763005256653, "avg_line_length": 43.4594612121582, "blob_id": "a3c5d7e4bd992be8776a12653095f3a94eb970eb", "content_id": "5b886ef1de7d7ea3a49bc4efb597b9e404c63202", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1645, "license_type": "permissive", "max_line_length": 131, "num_lines": 37, "path": "/ansible/static-files/kong-api-scripts/kong_api_csv_to_yaml.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "import argparse, sys\nfrom collections import OrderedDict\nimport csv\nimport yaml\n\ndef setup_yaml():\n \"\"\" https://stackoverflow.com/a/31609484/69362 \"\"\"\n represent_dict_order = lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items())\n yaml.add_representer(OrderedDict, represent_dict_order)\n\ndef convert_csv_to_yaml(apis_csv_file):\n reader = csv.DictReader(apis_csv_file, delimiter=',')\n apis = []\n for row in reader:\n apis.append(OrderedDict([\n ('name', row['NAME']),\n ('request_path', row['REQUEST PATH']),\n ('upstream_url', row['UPSTREAM PATH']),\n ('strip_request_path', True),\n ('plugins', [\n OrderedDict([('name', 'jwt')]),\n OrderedDict([('name', 'cors')]),\n \"{{ statsd_pulgin }}\",\n OrderedDict([('name', 'acl'), ('config.whitelist', row[\"WHITELIST GROUP\"])]),\n OrderedDict([('name', 'rate-limiting'), ('config.hour', row[\"RATE LIMIT\"]), ('config.limit_by', row[\"LIMIT BY\"])]),\n OrderedDict([('name', 'request-size-limiting'), ('config.allowed_payload_size', row[\"REQUEST SIZE LIMIT\"])]),\n ])\n ]))\n yaml.dump(apis, sys.stdout, default_flow_style=False)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Converts APIs CSV to yaml that can be used in ansible')\n parser.add_argument('apis_csv_file_path', help='Path of the csv file containing apis data')\n args = parser.parse_args()\n setup_yaml()\n with open(args.apis_csv_file_path) as apis_csv_file:\n convert_csv_to_yaml(apis_csv_file)\n" }, { "alpha_fraction": 0.5972539782524109, "alphanum_fraction": 0.6224256157875061, "avg_line_length": 18.863636016845703, "blob_id": "53a588184205c22146156af8ef6320e5f8bc3ca3", "content_id": "9626864c2411a7ef5e15668cea479f8838e36ec5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 437, "license_type": "permissive", "max_line_length": 95, "num_lines": 22, "path": "/scripts/syntax-check-hook.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncheckSyntax(){\nfilenames=$(git diff --cached --name-only --diff-filter=ACM)\nflag=0\nfor i in $filenames\ndo\n if [[ \"$i\" =~ (.yaml|.yml) ]]; then\n ansible-playbook -i ./ansible/inventories/sample --syntax-check $i\n if [[ $? -ne 0 ]]; then\n flag=1\n fi\n fi\ndone\n\nif [[ $flag -eq 1 ]]; then\n echo -e \"\\e[1;36m\\nAnsible syntax error found. Please correct these and then commit.\\e[0;37m\"\n exit 1\nfi\n}\n\ncheckSyntax\n" }, { "alpha_fraction": 0.6977687478065491, "alphanum_fraction": 0.7099391222000122, "avg_line_length": 24.947368621826172, "blob_id": "9a85cb29439b07a57e638a8ab9137949f4716ee8", "content_id": "09c0c1140ec71170cce0597f75742cfb478aee11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 493, "license_type": "permissive", "max_line_length": 105, "num_lines": 19, "path": "/images/kong/docker-entrypoint.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\nrm -f /tmp/logpipe\nmkfifo -m 666 /tmp/logpipe\n# This child process will still receive signals as per https://github.com/Yelp/dumb-init#session-behavior\ncat <> /tmp/logpipe 1>&1 &\n\n# Disabling nginx daemon mode\nexport KONG_NGINX_DAEMON=\"off\"\n\n# Setting default prefix (override any existing variable)\nexport KONG_PREFIX=\"/usr/local/kong\"\n\n# Prepare Kong prefix\nif [ \"$1\" = \"/usr/local/openresty/nginx/sbin/nginx\" ]; then\n kong prepare -p \"/usr/local/kong\"\nfi\n\nexec \"$@\"\n" }, { "alpha_fraction": 0.8199320435523987, "alphanum_fraction": 0.8289920687675476, "avg_line_length": 21.075000762939453, "blob_id": "dffb35fbaffa9a6c1bf996ccb513a3157ed2fbd8", "content_id": "2deb083d04dc5146f3febf7b47be60de3b7d7022", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 883, "license_type": "permissive", "max_line_length": 96, "num_lines": 40, "path": "/ansible/roles/cassandra-db-update/templates/alter_externalId_table.cql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "copy sunbird.usr_external_identity(provider,\nidtype,\nexternalid,\ncreatedby,\ncreatedon,\nlastupdatedby,\nlastupdatedon,\noriginalexternalid,\noriginalidtype,\noriginalprovider,\nuserid) to 'usr_external_identity.csv' with header=true and numprocesses=8 and maxattempts=10;\n\nDROP TABLE IF EXISTS sunbird.usr_external_identity;\n\nCREATE TABLE sunbird.usr_external_identity(\nexternalId text,\nprovider text,\nidType text,\nuserId text,\ncreatedOn timestamp,\nlastUpdatedOn timestamp,\ncreatedBy text,\nlastUpdatedBy text,\noriginalExternalId text,\noriginalIdType text,\noriginalProvider text,\nPRIMARY KEY(userId, idType, provider));\n\n\ncopy sunbird.usr_external_identity(provider,\nidtype,\nexternalid,\ncreatedby,\ncreatedon,\nlastupdatedby,\nlastupdatedon,\noriginalexternalid,\noriginalidtype,\noriginalprovider,\nuserid) from 'usr_external_identity.csv' with header=true and chunksize=2000 and numprocesses=8;\n" }, { "alpha_fraction": 0.5561290383338928, "alphanum_fraction": 0.5580645203590393, "avg_line_length": 35.03488540649414, "blob_id": "8ba3cb9727487ee192aae16138fd582e3d68a13f", "content_id": "4a1d86dbeba8b6911332d783e5aa62d11795ee7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3100, "license_type": "permissive", "max_line_length": 84, "num_lines": 86, "path": "/ansible/roles/keycloak-deploy/files/python-keycloak-0.12.0/keycloak/authorization/__init__.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017 Marcos Pereira <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nimport ast\nimport json\n\nfrom .permission import Permission\nfrom .policy import Policy\nfrom .role import Role\n\n\nclass Authorization:\n \"\"\"\n Keycloak Authorization (policies, roles, scopes and resources).\n\n https://keycloak.gitbooks.io/documentation/authorization_services/index.html\n\n \"\"\"\n\n def __init__(self):\n self._policies = {}\n\n @property\n def policies(self):\n return self._policies\n\n @policies.setter\n def policies(self, value):\n self._policies = value\n\n def load_config(self, data):\n \"\"\"\n Load policies, roles and permissions (scope/resources).\n\n :param data: keycloak authorization data (dict)\n :return:\n \"\"\"\n for pol in data['policies']:\n if pol['type'] == 'role':\n policy = Policy(name=pol['name'],\n type=pol['type'],\n logic=pol['logic'],\n decision_strategy=pol['decisionStrategy'])\n\n config_roles = json.loads(pol['config']['roles'])\n for role in config_roles:\n policy.add_role(Role(name=role['id'],\n required=role['required']))\n\n self.policies[policy.name] = policy\n\n if pol['type'] == 'scope':\n permission = Permission(name=pol['name'],\n type=pol['type'],\n logic=pol['logic'],\n decision_strategy=pol['decisionStrategy'])\n\n permission.scopes = ast.literal_eval(pol['config']['scopes'])\n\n for policy_name in ast.literal_eval(pol['config']['applyPolicies']):\n self.policies[policy_name].add_permission(permission)\n\n if pol['type'] == 'resource':\n permission = Permission(name=pol['name'],\n type=pol['type'],\n logic=pol['logic'],\n decision_strategy=pol['decisionStrategy'])\n\n permission.resources = ast.literal_eval(pol['config']['resources'])\n\n for policy_name in ast.literal_eval(pol['config']['applyPolicies']):\n self.policies[policy_name].add_permission(permission)\n\n" }, { "alpha_fraction": 0.875, "alphanum_fraction": 0.875, "avg_line_length": 11, "blob_id": "bbd1d6fe203f699bb45699b591a91785652bb91d", "content_id": "acbda796da0802b57556f46df5e05a9ee135c179", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 48, "license_type": "permissive", "max_line_length": 17, "num_lines": 4, "path": "/images/azure-ambari-prometheus-exporter/requirements.txt", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "PyYAML\nprometheus_client\nrequests\nexpiring-dict\n" }, { "alpha_fraction": 0.6661999225616455, "alphanum_fraction": 0.6735243201255798, "avg_line_length": 31.575439453125, "blob_id": "ff6109fa05f4365514094dde4201be497252de89", "content_id": "e627012f95be535f0ab841dd285cdd433ded8e99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 18568, "license_type": "permissive", "max_line_length": 85, "num_lines": 570, "path": "/images/proxy/prometheus.lua", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "-- vim: ts=2:sw=2:sts=2:expandtab\n--\n-- This module uses a single dictionary shared between Nginx workers to keep\n-- all metrics. Each counter is stored as a separate entry in that dictionary,\n-- which allows us to increment them using built-in `incr` method.\n--\n-- Prometheus requires that (a) all samples for a given metric are presented\n-- as one uninterrupted group, and (b) buckets of a histogram appear in\n-- increasing numerical order. We satisfy that by carefully constructing full\n-- metric names (i.e. metric name along with all labels) so that they meet\n-- those requirements while being sorted alphabetically. In particular:\n--\n-- * all labels for a given metric are presented in reproducible order (the one\n-- used when labels were declared). \"le\" label for histogram metrics always\n-- goes last;\n-- * bucket boundaries (which are exposed as values of the \"le\" label) are\n-- presented as floating point numbers with leading and trailing zeroes.\n-- Number of of zeroes is determined for each bucketer automatically based on\n-- bucket boundaries;\n-- * internally \"+Inf\" bucket is stored as \"Inf\" (to make it appear after\n-- all numeric buckets), and gets replaced by \"+Inf\" just before we\n-- expose the metrics.\n--\n-- For example, if you define your bucket boundaries as {0.00005, 10, 1000}\n-- then we will keep the following samples for a metric `m1` with label\n-- `site` set to `site1`:\n--\n-- m1_bucket{site=\"site1\",le=\"0000.00005\"}\n-- m1_bucket{site=\"site1\",le=\"0010.00000\"}\n-- m1_bucket{site=\"site1\",le=\"1000.00000\"}\n-- m1_bucket{site=\"site1\",le=\"Inf\"}\n-- m1_count{site=\"site1\"}\n-- m1_sum{site=\"site1\"}\n--\n-- \"Inf\" will be replaced by \"+Inf\" while publishing metrics.\n--\n-- You can find the latest version and documentation at\n-- https://github.com/knyar/nginx-lua-prometheus\n-- Released under MIT license.\n\n\n-- Default set of latency buckets, 5ms to 10s:\nlocal DEFAULT_BUCKETS = {0.005, 0.01, 0.02, 0.03, 0.05, 0.075, 0.1, 0.2, 0.3,\n 0.4, 0.5, 0.75, 1, 1.5, 2, 3, 4, 5, 10}\n\n-- Metric is a \"parent class\" for all metrics.\nlocal Metric = {}\nfunction Metric:new(o)\n o = o or {}\n setmetatable(o, self)\n self.__index = self\n return o\nend\n\n-- Checks that the right number of labels values have been passed.\n--\n-- Args:\n-- label_values: an array of label values.\n--\n-- Returns:\n-- an error message or nil\nfunction Metric:check_label_values(label_values)\n if self.label_names == nil and label_values == nil then\n return\n elseif self.label_names == nil and label_values ~= nil then\n return \"Expected no labels for \" .. self.name .. \", got \" .. #label_values\n elseif label_values == nil and self.label_names ~= nil then\n return \"Expected \" .. #self.label_names .. \" labels for \" ..\n self.name .. \", got none\"\n elseif #self.label_names ~= #label_values then\n return \"Wrong number of labels for \" .. self.name .. \". Expected \" ..\n #self.label_names .. \", got \" .. #label_values\n else\n for i, k in ipairs(self.label_names) do\n if label_values[i] == nil then\n return \"Unexpected nil value for label \" .. k .. \" of \" .. self.name\n end\n end\n end\nend\n\nlocal Counter = Metric:new()\n-- Increase a given counter by `value`\n--\n-- Args:\n-- value: (number) a value to add to the counter. Defaults to 1 if skipped.\n-- label_values: an array of label values. Can be nil (i.e. not defined) for\n-- metrics that have no labels.\nfunction Counter:inc(value, label_values)\n local err = self:check_label_values(label_values)\n if err ~= nil then\n self.prometheus:log_error(err)\n return\n end\n if value ~= nil and value < 0 then\n self.prometheus:log_error_kv(self.name, value, \"Value should not be negative\")\n return\n end\n\n self.prometheus:inc(self.name, self.label_names, label_values, value or 1)\nend\n\nlocal Gauge = Metric:new()\n-- Set a given gauge to `value`\n--\n-- Args:\n-- value: (number) a value to set the gauge to. Should be defined.\n-- label_values: an array of label values. Can be nil (i.e. not defined) for\n-- metrics that have no labels.\nfunction Gauge:set(value, label_values)\n if value == nil then\n self.prometheus:log_error(\"No value passed for \" .. self.name)\n return\n end\n local err = self:check_label_values(label_values)\n if err ~= nil then\n self.prometheus:log_error(err)\n return\n end\n self.prometheus:set(self.name, self.label_names, label_values, value)\nend\n\n\n-- Increase a given gauge by `value`\n--\n-- Args:\n-- value: (number) a value to add to the gauge (a negative value when you\n-- need to decrease the value of the gauge). Defaults to 1 if skipped.\n-- label_values: an array of label values. Can be nil (i.e. not defined) for\n-- metrics that have no labels.\nfunction Gauge:inc(value, label_values)\n local err = self:check_label_values(label_values)\n if err ~= nil then\n self.prometheus:log_error(err)\n return\n end\n self.prometheus:inc(self.name, self.label_names, label_values, value or 1)\nend\n\nlocal Histogram = Metric:new()\n-- Record a given value in a histogram.\n--\n-- Args:\n-- value: (number) a value to record. Should be defined.\n-- label_values: an array of label values. Can be nil (i.e. not defined) for\n-- metrics that have no labels.\nfunction Histogram:observe(value, label_values)\n if value == nil then\n self.prometheus:log_error(\"No value passed for \" .. self.name)\n return\n end\n local err = self:check_label_values(label_values)\n if err ~= nil then\n self.prometheus:log_error(err)\n return\n end\n self.prometheus:histogram_observe(self.name, self.label_names, label_values, value)\nend\n\nlocal Prometheus = {}\nPrometheus.__index = Prometheus\nPrometheus.initialized = false\n\n-- Generate full metric name that includes all labels.\n--\n-- Args:\n-- name: string\n-- label_names: (array) a list of label keys.\n-- label_values: (array) a list of label values.\n-- Returns:\n-- (string) full metric name.\nlocal function full_metric_name(name, label_names, label_values)\n if not label_names then\n return name\n end\n local label_parts = {}\n for idx, key in ipairs(label_names) do\n local label_value = (string.format(\"%s\", label_values[idx])\n :gsub(\"[^\\032-\\126]\", \"\") -- strip non-printable characters\n :gsub(\"\\\\\", \"\\\\\\\\\")\n :gsub('\"', '\\\\\"'))\n table.insert(label_parts, key .. '=\"' .. label_value .. '\"')\n end\n return name .. \"{\" .. table.concat(label_parts, \",\") .. \"}\"\nend\n\n-- Construct bucket format for a list of buckets.\n--\n-- This receives a list of buckets and returns a sprintf template that should\n-- be used for bucket boundaries to make them come in increasing order when\n-- sorted alphabetically.\n--\n-- To re-phrase, this is where we detect how many leading and trailing zeros we\n-- need.\n--\n-- Args:\n-- buckets: a list of buckets\n--\n-- Returns:\n-- (string) a sprintf template.\nlocal function construct_bucket_format(buckets)\n local max_order = 1\n local max_precision = 1\n for _, bucket in ipairs(buckets) do\n assert(type(bucket) == \"number\", \"bucket boundaries should be numeric\")\n -- floating point number with all trailing zeros removed\n local as_string = string.format(\"%f\", bucket):gsub(\"0*$\", \"\")\n local dot_idx = as_string:find(\".\", 1, true)\n max_order = math.max(max_order, dot_idx - 1)\n max_precision = math.max(max_precision, as_string:len() - dot_idx)\n end\n return \"%0\" .. (max_order + max_precision + 1) .. \".\" .. max_precision .. \"f\"\nend\n\n-- Extract short metric name from the full one.\n--\n-- Args:\n-- full_name: (string) full metric name that can include labels.\n--\n-- Returns:\n-- (string) short metric name with no labels. For a `*_bucket` metric of\n-- histogram the _bucket suffix will be removed.\nlocal function short_metric_name(full_name)\n local labels_start, _ = full_name:find(\"{\")\n if not labels_start then\n -- no labels\n return full_name\n end\n local suffix_idx, _ = full_name:find(\"_bucket{\")\n if suffix_idx and full_name:find(\"le=\") then\n -- this is a histogram metric\n return full_name:sub(1, suffix_idx - 1)\n end\n -- this is not a histogram metric\n return full_name:sub(1, labels_start - 1)\nend\n\n-- Makes a shallow copy of a table\nlocal function copy_table(table)\n local new = {}\n if table ~= nil then\n for k, v in ipairs(table) do\n new[k] = v\n end\n end\n return new\nend\n\n-- Check metric name and label names for correctness.\n--\n-- Regular expressions to validate metric and label names are\n-- documented in https://prometheus.io/docs/concepts/data_model/\n--\n-- Args:\n-- metric_name: (string) metric name.\n-- label_names: label names (array of strings).\n--\n-- Returns:\n-- Either an error string, or nil of no errors were found.\nlocal function check_metric_and_label_names(metric_name, label_names)\n if not metric_name:match(\"^[a-zA-Z_:][a-zA-Z0-9_:]*$\") then\n return \"Metric name '\" .. metric_name .. \"' is invalid\"\n end\n for _, label_name in ipairs(label_names or {}) do\n if label_name == \"le\" then\n return \"Invalid label name 'le' in \" .. metric_name\n end\n if not label_name:match(\"^[a-zA-Z_][a-zA-Z0-9_]*$\") then\n return \"Metric '\" .. metric_name .. \"' label name '\" .. label_name ..\n \"' is invalid\"\n end\n end\nend\n\n-- Initialize the module.\n--\n-- This should be called once from the `init_by_lua` section in nginx\n-- configuration.\n--\n-- Args:\n-- dict_name: (string) name of the nginx shared dictionary which will be\n-- used to store all metrics\n-- prefix: (optional string) if supplied, prefix is added to all\n-- metric names on output\n--\n-- Returns:\n-- an object that should be used to register metrics.\nfunction Prometheus.init(dict_name, prefix)\n local self = setmetatable({}, Prometheus)\n dict_name = dict_name or \"prometheus_metrics\"\n self.dict = ngx.shared[dict_name]\n if self.dict == nil then\n ngx.log(ngx.ERR,\n \"Dictionary '\", dict_name, \"' does not seem to exist. \",\n \"Please define the dictionary using `lua_shared_dict`.\")\n return self\n end\n self.help = {}\n if prefix then\n self.prefix = prefix\n else\n self.prefix = ''\n end\n self.type = {}\n self.registered = {}\n self.buckets = {}\n self.bucket_format = {}\n self.initialized = true\n\n self:counter(\"nginx_metric_errors_total\",\n \"Number of nginx-lua-prometheus errors\")\n self.dict:set(\"nginx_metric_errors_total\", 0)\n return self\nend\n\nfunction Prometheus:log_error(...)\n ngx.log(ngx.ERR, ...)\n self.dict:incr(\"nginx_metric_errors_total\", 1)\nend\n\nfunction Prometheus:log_error_kv(key, value, err)\n self:log_error(\n \"Error while setting '\", key, \"' to '\", value, \"': '\", err, \"'\")\nend\n\n-- Register a counter.\n--\n-- Args:\n-- name: (string) name of the metric. Required.\n-- description: (string) description of the metric. Will be used for the HELP\n-- comment on the metrics page. Optional.\n-- label_names: array of strings, defining a list of metrics. Optional.\n--\n-- Returns:\n-- a Counter object.\nfunction Prometheus:counter(name, description, label_names)\n if not self.initialized then\n ngx.log(ngx.ERR, \"Prometheus module has not been initialized\")\n return\n end\n\n local err = check_metric_and_label_names(name, label_names)\n if err ~= nil then\n self:log_error(err)\n return\n end\n\n if self.registered[name] then\n self:log_error(\"Duplicate metric \" .. name)\n return\n end\n self.registered[name] = true\n self.help[name] = description\n self.type[name] = \"counter\"\n\n return Counter:new{name=name, label_names=label_names, prometheus=self}\nend\n\n-- Register a gauge.\n--\n-- Args:\n-- name: (string) name of the metric. Required.\n-- description: (string) description of the metric. Will be used for the HELP\n-- comment on the metrics page. Optional.\n-- label_names: array of strings, defining a list of metrics. Optional.\n--\n-- Returns:\n-- a Gauge object.\nfunction Prometheus:gauge(name, description, label_names)\n if not self.initialized then\n ngx.log(ngx.ERR, \"Prometheus module has not been initialized\")\n return\n end\n\n local err = check_metric_and_label_names(name, label_names)\n if err ~= nil then\n self:log_error(err)\n return\n end\n\n if self.registered[name] then\n self:log_error(\"Duplicate metric \" .. name)\n return\n end\n self.registered[name] = true\n self.help[name] = description\n self.type[name] = \"gauge\"\n\n return Gauge:new{name=name, label_names=label_names, prometheus=self}\nend\n\n\n-- Register a histogram.\n--\n-- Args:\n-- name: (string) name of the metric. Required.\n-- description: (string) description of the metric. Will be used for the HELP\n-- comment on the metrics page. Optional.\n-- label_names: array of strings, defining a list of metrics. Optional.\n-- buckets: array if numbers, defining bucket boundaries. Optional.\n--\n-- Returns:\n-- a Histogram object.\nfunction Prometheus:histogram(name, description, label_names, buckets)\n if not self.initialized then\n ngx.log(ngx.ERR, \"Prometheus module has not been initialized\")\n return\n end\n\n local err = check_metric_and_label_names(name, label_names)\n if err ~= nil then\n self:log_error(err)\n return\n end\n\n for _, suffix in ipairs({\"\", \"_bucket\", \"_count\", \"_sum\"}) do\n if self.registered[name .. suffix] then\n self:log_error(\"Duplicate metric \" .. name .. suffix)\n return\n end\n self.registered[name .. suffix] = true\n end\n self.help[name] = description\n self.type[name] = \"histogram\"\n\n self.buckets[name] = buckets or DEFAULT_BUCKETS\n self.bucket_format[name] = construct_bucket_format(self.buckets[name])\n\n return Histogram:new{name=name, label_names=label_names, prometheus=self}\nend\n\n-- Set a given dictionary key.\n-- This overwrites existing values, so it should only be used when initializing\n-- metrics or when explicitely overwriting the previous value of a metric.\nfunction Prometheus:set_key(key, value)\n local ok, err = self.dict:safe_set(key, value)\n if not ok then\n self:log_error_kv(key, value, err)\n end\nend\n\n-- Increment a given metric by `value`.\n--\n-- Args:\n-- name: (string) short metric name without any labels.\n-- label_names: (array) a list of label keys.\n-- label_values: (array) a list of label values.\n-- value: (number) value to add (a negative value when you need to decrease\n-- the value of the gauge). Optional, defaults to 1.\nfunction Prometheus:inc(name, label_names, label_values, value)\n local key = full_metric_name(name, label_names, label_values)\n if value == nil then value = 1 end\n\n local newval, err = self.dict:incr(key, value)\n if newval then\n return\n end\n -- Yes, this looks like a race, so I guess we might under-report some values\n -- when multiple workers simultaneously try to create the same metric.\n -- Hopefully this does not happen too often (shared dictionary does not get\n -- reset during configuation reload).\n if err == \"not found\" then\n self:set_key(key, value)\n return\n end\n -- Unexpected error\n self:log_error_kv(key, value, err)\nend\n\n-- Set the current value of a gauge to `value`\n--\n-- Args:\n-- name: (string) short metric name without any labels.\n-- label_names: (array) a list of label keys.\n-- label_values: (array) a list of label values.\n-- value: (number) the new value for the gauge.\nfunction Prometheus:set(name, label_names, label_values, value)\n local key = full_metric_name(name, label_names, label_values)\n self:set_key(key, value)\nend\n\n-- Record a given value into a histogram metric.\n--\n-- Args:\n-- name: (string) short metric name without any labels.\n-- label_names: (array) a list of label keys.\n-- label_values: (array) a list of label values.\n-- value: (number) value to observe.\nfunction Prometheus:histogram_observe(name, label_names, label_values, value)\n self:inc(name .. \"_count\", label_names, label_values, 1)\n self:inc(name .. \"_sum\", label_names, label_values, value)\n\n -- we are going to mutate arrays of label names and values, so create a copy.\n local l_names = copy_table(label_names)\n local l_values = copy_table(label_values)\n\n -- Last bucket. Note, that the label value is \"Inf\" rather than \"+Inf\"\n -- required by Prometheus. This is necessary for this bucket to be the last\n -- one when all metrics are lexicographically sorted. \"Inf\" will get replaced\n -- by \"+Inf\" in Prometheus:collect().\n table.insert(l_names, \"le\")\n table.insert(l_values, \"Inf\")\n self:inc(name .. \"_bucket\", l_names, l_values, 1)\n\n local label_count = #l_names\n for _, bucket in ipairs(self.buckets[name]) do\n if value <= bucket then\n -- last label is now \"le\"\n l_values[label_count] = self.bucket_format[name]:format(bucket)\n self:inc(name .. \"_bucket\", l_names, l_values, 1)\n end\n end\nend\n\n-- Prometheus compatible metric data as an array of strings.\n--\n-- Returns:\n-- Array of strings with all metrics in a text format compatible with\n-- Prometheus.\nfunction Prometheus:metric_data()\n if not self.initialized then\n ngx.log(ngx.ERR, \"Prometheus module has not been initialized\")\n return\n end\n\n local keys = self.dict:get_keys(0)\n -- Prometheus server expects buckets of a histogram to appear in increasing\n -- numerical order of their label values.\n table.sort(keys)\n\n local seen_metrics = {}\n local output = {}\n for _, key in ipairs(keys) do\n local value, err = self.dict:get(key)\n if value then\n local short_name = short_metric_name(key)\n if not seen_metrics[short_name] then\n if self.help[short_name] then\n table.insert(output, string.format(\"# HELP %s%s %s\\n\",\n self.prefix, short_name, self.help[short_name]))\n end\n if self.type[short_name] then\n table.insert(output, string.format(\"# TYPE %s%s %s\\n\",\n self.prefix, short_name, self.type[short_name]))\n end\n seen_metrics[short_name] = true\n end\n -- Replace \"Inf\" with \"+Inf\" in each metric's last bucket 'le' label.\n if key:find('le=\"Inf\"', 1, true) then\n key = key:gsub('le=\"Inf\"', 'le=\"+Inf\"')\n end\n table.insert(output, string.format(\"%s%s %s\\n\", self.prefix, key, value))\n else\n self:log_error(\"Error getting '\", key, \"': \", err)\n end\n end\n return output\nend\n\n-- Present all metrics in a text format compatible with Prometheus.\n--\n-- This function should be used to expose the metrics on a separate HTTP page.\n-- It will get the metrics from the dictionary, sort them, and expose them\n-- aling with TYPE and HELP comments.\nfunction Prometheus:collect()\n ngx.header.content_type = \"text/plain\"\n ngx.print(self:metric_data())\nend\n\nreturn Prometheus\n" }, { "alpha_fraction": 0.7258526086807251, "alphanum_fraction": 0.7361935973167419, "avg_line_length": 42.28571319580078, "blob_id": "ad278e63e945f175893b8a2cd2c8753bffe866d1", "content_id": "4eec7614a1aa4c28316ea29ac59b8906b110b837", "detected_licenses": [ "MIT", "JSON" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4545, "license_type": "permissive", "max_line_length": 319, "num_lines": 105, "path": "/ansible/roles/es7/docs/ssl-tls-setup.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# X-Pack Security SSL/TLS\n\nThe role allows configuring HTTP and transport layer SSL/TLS for the cluster. You will need to generate and provide your own PKCS12 or PEM encoded certificates as described in [Encrypting communications in Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/configuring-tls.html#configuring-tls).\n\nBy default this role will upload the certs to your elasticsearch servers. If you already copied the certs by your own way, set `es_ssl_upload` to `false` (default: `true`) \n\nIf you don't want this role to add autogenerated SSL configuration to elasticsearch.yml set `es_enable_auto_ssl_configuration` to `false` (default: `true`).\n\nThe following should be configured to ensure a security-enabled cluster successfully forms:\n\n* `es_enable_http_ssl` Default `false`. Setting this to `true` will enable HTTP client SSL/TLS\n* `es_enable_transport_ssl` - Default `false`. Setting this to `true` will enable transport layer SSL/TLS\n\nWhen using a [PKCS12](https://www.elastic.co/guide/en/elasticsearch/reference/current/security-settings.html#security-http-pkcs12-files) keystore and truststore:\n\n* `es_ssl_keystore` path to your PKCS12 keystore (can be the same as `es_ssl_truststore`)\n* `es_ssl_keystore_password` set this if your keystore is protected with a password\n* `es_ssl_truststore` path to your PKCS12 keystore (can be the same as `es_ssl_keystore`)\n* `es_ssl_truststore_password` set this if your truststore is protected with a password\n\nWhen using [PEM encoded](https://www.elastic.co/guide/en/elasticsearch/reference/current/security-settings.html#_pem_encoded_files_3) certificates:\n\n* `es_ssl_key` path to your SSL key\n* `es_ssl_key_password` set this if your SSL key is protected with a password\n* `es_ssl_certificate` the path to your SSL certificate\n\n## Generating an SSL keystore\n\nWith a password:\n\n```shell\n$ bin/elasticsearch-certutil ca --out ./my-ca.p12 --pass \"ca_password\"\n$ bin/elasticsearch-certutil cert --ca ./my-ca.p12 --ca-pass \"ca_password\" --out ./my-keystore.p12 --pass \"keystore_password\"\n```\n\nWithout a password:\n\n```shell\n$ bin/elasticsearch-certutil ca --out ./my-ca.p12 --pass \"\"\n$ bin/elasticsearch-certutil cert --ca ./my-ca.p12 --out ./my-keystore.p12 --pass \"\"\n```\n\n## Additional optional SSL/TLS configuration\n\n* `es_enable_auto_ssl_configuration` Default `true`. Whether this role should add automatically generated SSL config to elasticsearch.yml.\n* `es_ssl_certificate_path` Default `{{ es_conf_dir }}/certs`. The location where certificates should be stored on the ES node.\n* `es_ssl_verification_mode` Default `certificate`. See [SSL verification_mode](https://www.elastic.co/guide/en/elasticsearch/reference/current/security-settings.html#ssl-tls-settings) for options.\n* `es_ssl_certificate_authority` PEM encoded certificate file that should be trusted.\n* `es_validate_certs` Default `yes`. Determines if ansible should validate SSL certificates when performing actions over HTTPS. e.g. installing templates and managing native users.\n\n## Example SSL/TLS configuration\n\n```yaml\n- name: Elasticsearch with SSL/TLS enabled\n hosts: localhost\n roles:\n - role: elastic.elasticsearch\n vars:\n es_config:\n node.name: \"node1\"\n cluster.name: \"custom-cluster\"\n discovery.seed_hosts: \"localhost:9301\"\n http.port: 9201\n transport.port: 9301\n node.data: false\n node.master: true\n bootstrap.memory_lock: true\n xpack.security.authc.realms.file.file1.order: 0\n xpack.security.authc.realms.native.native1.order: 1\n es_heap_size: 1g\n es_api_basic_auth_username: \"elastic\" # This is the default user created by the installation of elasticsearch\n es_api_basic_auth_password: \"changeme\" # This is the default password created by the installation of elasticsearch\n es_enable_http_ssl: true\n es_enable_transport_ssl: true\n es_ssl_keystore: \"files/certs/my-keystore.p12\"\n es_ssl_truststore: \"files/certs/my-ca.p12\"\n es_ssl_keystore_password: \"keystore_password\"\n es_ssl_truststore_password: \"ca_password\"\n es_validate_certs: no\n```\n\n## Changing the default password of elastic user\n\nTo change the default password of user elastic: \n\n* Add this line to your playbook:\n\n```\nvars:\n es_api_basic_auth_username: \"elastic\"\n es_api_basic_auth_password: \"changeme\"\n es_users:\n native:\n elastic:\n password: \"<new password>\"\n```\n\n* Deploy your playbook\n* Update your playbook with:\n\n```\nvars:\n es_api_basic_auth_username: \"elastic\"\n es_api_basic_auth_password: \"<new password>\"\n```\n" }, { "alpha_fraction": 0.494017094373703, "alphanum_fraction": 0.5008547306060791, "avg_line_length": 33.411766052246094, "blob_id": "12ef88614394d5dbedddfbfbb65c77b547635623", "content_id": "8ed4efe0ecb22ca9e0413fd9054991ce00e141dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 585, "license_type": "permissive", "max_line_length": 174, "num_lines": 17, "path": "/deploy/deploy-badger.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory-path>\"\n exit 1\nfi\n\ninventory_path=\"$1\" \norg=\"sunbird\" \n# Importing versions\nsource version.env\n\n#Deploy Badger \necho \"@@@@@@@@@ Badger \" \nansible-playbook -i $inventory_path ../ansible/deploy-badger.yml [email protected] --extra-vars \"hub_org=${org} image_name=badger image_tag=${BADGER_SERVICE_VERSION}\"\n" }, { "alpha_fraction": 0.508155107498169, "alphanum_fraction": 0.5386009216308594, "avg_line_length": 27.4536075592041, "blob_id": "93923ba56a55e2dfad07dd981c7e4ed60b5a8db2", "content_id": "b20f00b5ee4f57fa1c51d3b0b5162c4845e161fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2759, "license_type": "permissive", "max_line_length": 234, "num_lines": 97, "path": "/ansible/roles/secor/templates/secor-service.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# chkconfig: 2345 95 05\n# description: {{ description }}\n\n# Source function library.\n. /lib/lsb/init-functions\n\nservice_name=$1\nprog=\"$service_name\"\nPIDFILE=\"{{ script_dir }}/$service_name.pid\"\nDESC=\"Secor Service\"\nGREP_KEY=secor.main.ConsumerMain\nDAEMON=/usr/bin/java\nDAEMON_ARGS=\"-- -Xms256M -Xmx1024M -ea -Duser.timezone=UTC -Dsecor_group=$service_name -Dlog4j.configuration=log4j.properties -Dconfig=secor.partition.properties -cp secor-0.24-SNAPSHOT.jar:lib/* com.pinterest.secor.main.ConsumerMain\"\nDAEMON_HOME=\"/mnt/$service_name\"\nSBIN_HOME=\"{{ script_dir }}\"\n\n#echo \"All value sets\"\n\nstart() {\n if [ -f $PIDFILE ]; then\n PID=`cat $PIDFILE`\n if [ -z \"`pgrep $PID`\" ] && [ \"$PID\" != \"`ps aux|grep -vE 'grep|runuser|bash'|grep -w \"$GREP_KEY\"|awk '{print $2}'`\" ]; then\n printf \"%s\\n\" \"Process dead but pidfile exists\"\n else\n printf \"$prog is already running!\\n\"\n fi\n else\n printf \"%-50s\" \"Starting $prog ...\"\n cd $DAEMON_HOME\n start-stop-daemon --start --quiet --background --name $service_name -d $DAEMON_HOME --exec $DAEMON $DAEMON_ARGS >/mnt/secor/logs/$service_name-service.log 2>&1\n sleep 10\n PID=`ps aux|grep -vE 'grep|runuser|bash'|grep -w \"$GREP_KEY\"|awk '{print $2}'`\n if [ -z \"$PID\" ]; then\n printf \"[ \\e[31mFAIL\\033[0m ]\\n\"\n exit 1\n else\n echo $PID > $PIDFILE\n printf \"[ \\e[32mOK\\033[0m ]\\n\"\n fi\n fi\n}\n\nstop() {\n printf \"%-50s\" \"Shutting down $prog:\"\n if [ -f $PIDFILE ]; then\n PID=`cat $PIDFILE`\n start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE 2>/dev/null\n sleep 5\n PID=`ps aux|grep -vE 'grep|runuser|bash'|grep -w \"$GREP_KEY\"|awk '{print $2}'`\n if [ ! -z \"$PID\" ]; then\n printf \"[ \\e[31mFAIL\\033[0m ]\\n\"\n exit 1\n else\n rm -f $PIDFILE\n printf \"[ \\e[32mOK\\033[0m ]\\n\"\n fi\n else\n printf \"[ \\e[32mNOT RUNNING\\033[0m ]\\n\" \n fi\n}\n\ncheck_status() {\n printf \"%-50s\" \"Checking $prog ...\"\n if [ -f $PIDFILE ]; then\n PID=`cat $PIDFILE`\n if [ -z \"`pgrep $PID`\" ] && [ \"$PID\" != \"`ps aux|grep -vE 'grep|runuser|bash'|grep -w \"$GREP_KEY\"|awk '{print $2}'`\" ]; then\n printf \"%s\\n\" \"Process dead but pidfile exists\"\n else\n printf \"[ \\e[32mRUNNING\\033[0m ]\\n\"\n fi\n else\n printf \"[ \\e[31mSTOPPED\\033[0m ]\\n\"\n fi\n}\n\ncase \"$2\" in\n start)\n start\n ;;\n stop)\n stop\n ;;\n status)\n check_status\n ;;\n restart)\n stop\n start\n ;;\n *)\n echo \"Usage: $prog {start|stop|status|restart}\"\n exit 1\n ;;\nesac\nexit 0" }, { "alpha_fraction": 0.7175572514533997, "alphanum_fraction": 0.7251908183097839, "avg_line_length": 26.526315689086914, "blob_id": "ee299901eb31dabaf09aa9329f8c37f8f05acf40", "content_id": "5039ad751c3c125d113c9ea696381f5af7f4f149", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 524, "license_type": "permissive", "max_line_length": 256, "num_lines": 19, "path": "/deploy/deploy-telemetry.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory-path>\"\n exit 1\nfi\n\nINVENTORY_PATH=$1\n\nENV=sample\nORG=sunbird\n# Getting image versions\nsource version.env\n\n\necho \"Redeploy telemetry service\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy.yml --tags \"stack-sunbird\" --extra-vars \"hub_org=${ORG} image_name=telemetry-service image_tag=${TELEMETRY_SERVICE_VERSION} service_name=telemetry-service deploy_telemetry=True\" --extra-vars @config.yml\n\n" }, { "alpha_fraction": 0.7485875487327576, "alphanum_fraction": 0.7740113139152527, "avg_line_length": 28.58333396911621, "blob_id": "f4c10ec46b93f4f68e780e7b3610f3ac98c0a999", "content_id": "955261bd1ba98c92393516c8e004d171fee7d597", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 354, "license_type": "permissive", "max_line_length": 159, "num_lines": 12, "path": "/images/postgres_exporter/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM alpine:3.6\n\nARG POSTGRES_EXPORTER_VERSION=v0.2.2\n\nRUN apk --no-cache add openssl\n\nRUN wget -O /usr/local/bin/postgres_exporter https://github.com/wrouesnel/postgres_exporter/releases/download/$POSTGRES_EXPORTER_VERSION/postgres_exporter && \\\n chmod +x /usr/local/bin/postgres_exporter\n\nEXPOSE 9187\n\nENTRYPOINT [\"/usr/local/bin/postgres_exporter\"]" }, { "alpha_fraction": 0.790861189365387, "alphanum_fraction": 0.8014059662818909, "avg_line_length": 55.900001525878906, "blob_id": "42261acf4ff68b60a6bb9c6f321083852d50d30f", "content_id": "f1df2a727c548a793dcb1c6d45c279e0c58b0952", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 569, "license_type": "permissive", "max_line_length": 118, "num_lines": 10, "path": "/images/keycloak/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM jboss/keycloak-postgres:latest\n\nRUN rm /opt/jboss/keycloak/standalone/configuration/standalone-ha.xml\nCOPY ./images/keycloak/standalone-ha.xml /opt/jboss/keycloak/standalone/configuration/\nCOPY ./images/keycloak/postgresql-9.4.1212.jar /opt/jboss/keycloak/modules/system/layers/keycloak/org/postgresql/main/\nCOPY ./images/keycloak/module.xml /opt/jboss/keycloak/modules/system/layers/keycloak/org/postgresql/main/\nCOPY ./images/keycloak/docker-entrypoint.sh /opt/jboss/\nENTRYPOINT [\"/opt/jboss/docker-entrypoint.sh\"]\n\nCMD [\"--server-config\", \"standalone-ha.xml\"]\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.6507936716079712, "avg_line_length": 17.071428298950195, "blob_id": "27ea8593d1a506c236a79bf3d5c2993e03391fa9", "content_id": "3c0ad658d7f716e1b58a5dd3c863b6f1f906fef3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 252, "license_type": "permissive", "max_line_length": 80, "num_lines": 14, "path": "/ansible/roles/jmeter-deploy/templates/test_data.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nstart=$1\nend=$2\n\nif [ -f {{ jmeter.home }}scenarios/input_data.csv ]\nthen\n\trm {{ jmeter.home }}scenarios/input_data.csv\nfi\n\nfor i in `seq $start $end`\ndo\n echo \"LP_PT_$i,LP_PT_$i\" >> {{ jmeter.home }}scenarios/create_input_data.csv\ndone" }, { "alpha_fraction": 0.716738224029541, "alphanum_fraction": 0.7510729432106018, "avg_line_length": 28.25, "blob_id": "3496265d3e7d7d4a79f274dd746b8eef2cf2b3c5", "content_id": "fc461cbf1e6aa2d2286a9fbe01e6a8cbf769d0a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 233, "license_type": "permissive", "max_line_length": 70, "num_lines": 8, "path": "/deploy/docker-swam-node-post-install.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nset -x\n\n# This is to ensure we don't get below error\n# Failed to start container manager: inotify_init: too many open files\n# Reference: https://github.com/moby/moby/issues/1044\nsysctl -w fs.inotify.max_user_instances=8192" }, { "alpha_fraction": 0.5171455144882202, "alphanum_fraction": 0.5329008102416992, "avg_line_length": 55.73684310913086, "blob_id": "b3c01011a33febe3cc170fcb0f87bc2489a52f3e", "content_id": "48041b2849258708194f5c8cbb45c5dc94c9b0fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1079, "license_type": "permissive", "max_line_length": 182, "num_lines": 19, "path": "/deploy/utilities/getEsData.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n####################################################\n# Author S M Y ALTAMASH <[email protected]> #\n# Script gets the Latest Logs of proxy from Log-es #\n####################################################\n# NOTE: Have jq installed before running this script\nfor index in $(curl -s localhost:9200/_cat/indices | grep -v kibana | awk '{print $3}' | tr \"\\n\" \" \");\ndo\n echo \"Index:$index\"\n # Get the Total Hits for the Proxy Container\n hits=$(curl -s -X GET \"http://localhost:9200/$index/_search?pretty\" -H 'Content-Type: application/json' -d'{\"query\":{\"match\":{\"program\":\"proxy_proxy*\"}}}' | jq '.hits.total')\n\n # Increase the query size\n curl -XPUT \"http://localhost:9200/$index/_settings\" -d \"{ \\\"index\\\" : { \\\"max_result_window\\\" : \\\"$hits\\\" } }\" -H \"Content-Type: application/json\"\n\n # Save the Logs in the file\n curl -s -X GET \"http://localhost:9200/$index/_search?size=$hits\" -H 'Content-Type: application/json' -d'{\"query\":{\"match\":{\"program\":\"proxy_proxy*\"}}}' > $index.json\n echo \"################################\"\ndone\n\n" }, { "alpha_fraction": 0.702036440372467, "alphanum_fraction": 0.7122186422348022, "avg_line_length": 44.53658676147461, "blob_id": "fe226572c6395fbbdf5057166db03857f276b77b", "content_id": "c001bac1aaf8097c2ed4c6200338982dc7bd3942", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1866, "license_type": "permissive", "max_line_length": 208, "num_lines": 41, "path": "/kubernetes/ansible/static-files/kong-api-scripts/common.py", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "import urllib2, json, logging\nfrom retry import retry\n\nlogging.basicConfig()\n\n# Due to issue https://github.com/Mashape/kong/issues/1912\n# We can't loop through all apis page by page\n# Hence this work around which fetches apis with page size limited to max_page_size\n# max_page_size ensures we don't bring down DB by fetching lot of rows\n# If we reach a state we have more apis than max_page_size,\n# Increase value of max_page_size judiciously\ndef get_apis(kong_admin_api_url):\n max_page_size = 2000\n apis_url_with_size_limit = \"{}/apis?size={}\".format(kong_admin_api_url, max_page_size)\n apis_response = json.loads(retrying_urlopen(apis_url_with_size_limit).read())\n total_apis = apis_response[\"total\"]\n if(total_apis > max_page_size):\n raise Exception(\"There are {} apis existing in system which is more than max_page_size={}. Please increase max_page_size in ansible/kong_apis.py if this is expected\".format(total_apis, max_page_size))\n else:\n return apis_response[\"data\"]\n\ndef get_api_plugins(kong_admin_api_url, api_name):\n get_plugins_max_page_size = 2000\n api_pugins_url = \"{}/apis/{}/plugins\".format(kong_admin_api_url, api_name)\n get_api_plugins_url = \"{}?size={}\".format(api_pugins_url, get_plugins_max_page_size)\n saved_api_details = json.loads(retrying_urlopen(get_api_plugins_url).read())\n return saved_api_details[\"data\"]\n\n\ndef json_request(method, url, data=None):\n request_body = json.dumps(data) if data is not None else None\n request = urllib2.Request(url, request_body)\n if data:\n request.add_header('Content-Type', 'application/json')\n request.get_method = lambda: method\n response = retrying_urlopen(request)\n return response\n\n@retry(exceptions=urllib2.URLError, tries=5, delay=2, backoff=2)\ndef retrying_urlopen(*args, **kwargs):\n return urllib2.urlopen(*args, **kwargs)" }, { "alpha_fraction": 0.8571428656578064, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 27, "blob_id": "fb961ce7a40e8841acedc2f357b1faa840c11152", "content_id": "fa2d5d0e2746f3a389c518f1c515029ec89f19ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "permissive", "max_line_length": 27, "num_lines": 1, "path": "/ansible/roles/ml-analytics-service/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "data-pipeline ansible roles\n" }, { "alpha_fraction": 0.7716894745826721, "alphanum_fraction": 0.7853881120681763, "avg_line_length": 42.79999923706055, "blob_id": "778cb956d41dd7140ac8222f63b386748a9cf775", "content_id": "2d3e51bce71676e4c89e7429c03ac08255cae42e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 219, "license_type": "permissive", "max_line_length": 64, "num_lines": 5, "path": "/images/BuildImages/Android/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM circleci/android:api-28-node8-alpha\nMAINTAINER Rajesh Rajendran <[email protected]>\nWORKDIR /home/circleci\n# node-sass is not installing as it's executing external scripts\nRUN sudo npm install -g ionic cordova node-sass --unsafe-perm\n" }, { "alpha_fraction": 0.5985086560249329, "alphanum_fraction": 0.6163866519927979, "avg_line_length": 29.329700469970703, "blob_id": "ce841c36883ecf5c50c4816cd3eb2de4ba8ce400", "content_id": "b7e0676ac3cd493358378d8a688c82b8b4e21633", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11131, "license_type": "permissive", "max_line_length": 139, "num_lines": 367, "path": "/ansible/roles/nginx/README.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "nginx\n=====\n\nThis role installs and configures the nginx web server. The user can specify\nany http configuration parameters they wish to apply their site. Any number of\nsites can be added with configurations of your choice.\n\n[![Build Status](https://travis-ci.org/jdauphant/ansible-role-nginx.svg?branch=master)](https://travis-ci.org/jdauphant/ansible-role-nginx)\n[![Ansible Galaxy](https://img.shields.io/ansible/role/466.svg)](https://galaxy.ansible.com/jdauphant/nginx/)\n\nRequirements\n------------\n\nThis role requires Ansible 2.0 or higher and platform requirements are listed\nin the metadata file. (Some older version of the role support Ansible 1.4)\nFor FreeBSD a working pkgng setup is required (see: https://www.freebsd.org/doc/handbook/pkgng-intro.html )\n\nInstall\n-------\n\n```sh\nansible-galaxy install jdauphant.nginx\n```\n\nRole Variables\n--------------\n\nThe variables that can be passed to this role and a brief description about\nthem are as follows. (For all variables, take a look at [defaults/main.yml](defaults/main.yml))\n\n```yaml\n# The user to run nginx\nnginx_user: \"www-data\"\n\n# A list of directives for the events section.\nnginx_events_params:\n - worker_connections 512\n - debug_connection 127.0.0.1\n - use epoll\n - multi_accept on\n\n# A list of hashes that define the servers for nginx,\n# as with http parameters. Any valid server parameters\n# can be defined here.\nnginx_sites:\n default:\n - listen 80\n - server_name _\n - root \"/usr/share/nginx/html\"\n - index index.html\n foo:\n - listen 8080\n - server_name localhost\n - root \"/tmp/site1\"\n - location / { try_files $uri $uri/ /index.html; }\n - location /images/ { try_files $uri $uri/ /index.html; }\n bar:\n - listen 9090\n - server_name ansible\n - root \"/tmp/site2\"\n - location / { try_files $uri $uri/ /index.html; }\n - location /images/ {\n try_files $uri $uri/ /index.html;\n allow 127.0.0.1;\n deny all;\n }\n\n# A list of hashes that define additional configuration\nnginx_configs:\n proxy:\n - proxy_set_header X-Real-IP $remote_addr\n - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for\n upstream:\n - upstream foo { server 127.0.0.1:8080 weight=10; }\n geo:\n - geo $local {\n default 0;\n 127.0.0.1 1;\n }\n gzip:\n - gzip on\n - gzip_disable msie6\n\n# A list of hashes that define configuration snippets\nnginx_snippets:\n error_pages:\n - error_page 500 /http_errors/500.html\n - error_page 502 /http_errors/502.html\n - error_page 503 /http_errors/503.html\n - error_page 504 /http_errors/504.html\n\n# A list of hashes that define user/password files\nnginx_auth_basic_files:\n demo:\n - foo:$apr1$mEJqnFmy$zioG2q1iDWvRxbHuNepIh0 # foo:demo , generated by : htpasswd -nb foo demo\n - bar:$apr1$H2GihkSo$PwBeV8cVWFFQlnAJtvVCQ. # bar:demo , generated by : htpasswd -nb bar demo\n\n```\n\nExamples\n========\n\n## 1) Install nginx with HTTP directives of choice, but with no sites configured and no additionnal configuration:\n\n```yaml\n- hosts: all\n roles:\n - {role: nginx,\n nginx_http_params: [\"sendfile on\", \"access_log /var/log/nginx/access.log\"]\n }\n```\n\n## 2) Install nginx with different HTTP directives than in the previous example, but no\nsites configured and no additional configuration.\n\n```yaml\n- hosts: all\n roles:\n - {role: nginx,\n nginx_http_params: [\"tcp_nodelay on\", \"error_log /var/log/nginx/error.log\"]}\n```\n\nNote: Please make sure the HTTP directives passed are valid, as this role\nwon't check for the validity of the directives. See the nginx documentation\nfor details.\n\n## 3) Install nginx and add a site to the configuration.\n\n```yaml\n- hosts: all\n\n roles:\n - role: nginx\n nginx_http_params:\n - sendfile \"on\"\n - access_log \"/var/log/nginx/access.log\"\n nginx_sites:\n bar:\n - listen 8080\n - location / { try_files $uri $uri/ /index.html; }\n - location /images/ { try_files $uri $uri/ /index.html; }\n nginx_configs:\n proxy:\n - proxy_set_header X-Real-IP $remote_addr\n - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for\n```\n\n## 4) Install nginx and add extra variables to default config\n\n```yaml\n-hosts: all\n vars:\n - my_extra_params:\n - client_max_body_size 200M\n# retain defaults and add additional `client_max_body_size` param\n roles:\n - role: jdauphant.nginx\n nginx_http_params: \"{{ nginx_http_default_params + my_extra_params }}\"\n```\n\nNote: Each site added is represented by a list of hashes, and the configurations\ngenerated are populated in /etc/nginx/site-available/ and linked from /etc/nginx/site-enable/ to /etc/nginx/site-available.\n\nThe file name for the specific site configuration is specified in the hash\nwith the key \"file_name\", any valid server directives can be added to the hash.\nAdditional configurations are created in /etc/nginx/conf.d/\n\n## 5) Install Nginx, add 2 sites (different method) and add additional configuration\n\n```yaml\n---\n- hosts: all\n roles:\n - role: nginx\n nginx_http_params:\n - sendfile on\n - access_log /var/log/nginx/access.log\n nginx_sites:\n foo:\n - listen 8080\n - server_name localhost\n - root /tmp/site1\n - location / { try_files $uri $uri/ /index.html; }\n - location /images/ { try_files $uri $uri/ /index.html; }\n bar:\n - listen 9090\n - server_name ansible\n - root /tmp/site2\n - location / { try_files $uri $uri/ /index.html; }\n - location /images/ { try_files $uri $uri/ /index.html; }\n nginx_configs:\n proxy:\n - proxy_set_header X-Real-IP $remote_addr\n - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for\n```\n\n## 6) Install Nginx, add 2 sites, add additional configuration and an upstream configuration block\n\n```yaml\n---\n- hosts: all\n roles:\n - role: nginx\n nginx_error_log_level: info\n nginx_http_params:\n - sendfile on\n - access_log /var/log/nginx/access.log\n nginx_sites:\n foo:\n - listen 8080\n - server_name localhost\n - root /tmp/site1\n - location / { try_files $uri $uri/ /index.html; }\n - location /images/ { try_files $uri $uri/ /index.html; }\n bar:\n - listen 9090\n - server_name ansible\n - root /tmp/site2\n - if ( $host = example.com ) { rewrite ^(.*)$ http://www.example.com$1 permanent; }\n - location / {\n try_files $uri $uri/ /index.html;\n auth_basic \"Restricted\";\n auth_basic_user_file auth_basic/demo;\n }\n - location /images/ { try_files $uri $uri/ /index.html; }\n nginx_configs:\n proxy:\n - proxy_set_header X-Real-IP $remote_addr\n - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for\n upstream:\n # Results in:\n # upstream foo_backend {\n # server 127.0.0.1:8080 weight=10;\n # }\n - upstream foo_backend { server 127.0.0.1:8080 weight=10; }\n nginx_auth_basic_files:\n demo:\n - foo:$apr1$mEJqnFmy$zioG2q1iDWvRxbHuNepIh0 # foo:demo , generated by : htpasswd -nb foo demo\n - bar:$apr1$H2GihkSo$PwBeV8cVWFFQlnAJtvVCQ. # bar:demo , generated by : htpasswd -nb bar demo\n```\n\n## 7) Install Nginx, add a site and use special yaml syntax to make the location blocks multiline for clarity\n\n```yaml\n---\n- hosts: all\n roles:\n - role: nginx\n nginx_http_params:\n - sendfile on\n - access_log /var/log/nginx/access.log\n nginx_sites:\n foo:\n - listen 443 ssl\n - server_name foo.example.com\n - set $myhost foo.example.com\n - |\n location / {\n proxy_set_header Host foo.example.com;\n }\n - |\n location ~ /v2/users/.+?/organizations {\n if ($request_method = PUT) {\n set $myhost bar.example.com;\n }\n if ($request_method = DELETE) {\n set $myhost bar.example.com;\n }\n proxy_set_header Host $myhost;\n }\n```\n## 8) Example to use this role with my ssl-certs role to generate or copie ssl certificate ( https://galaxy.ansible.com/list#/roles/3115 )\n```yaml\n - hosts: all\n roles:\n - jdauphant.ssl-certs\n - role: jdauphant.nginx\n nginx_configs:\n ssl:\n - ssl_certificate_key {{ssl_certs_privkey_path}}\n - ssl_certificate {{ssl_certs_cert_path}}\n nginx_sites:\n default:\n - listen 443 ssl\n - server_name _\n - root \"/usr/share/nginx/html\"\n - index index.html\n```\n## 9) Site configuration using a custom template.\nInstead of defining a site config file using a list of attributes,\nyou may use a hash/dictionary that includes the filename of an alternate template.\nAdditional values are accessible within the template via the `item.value` variable.\n```yaml\n- hosts: all\n\n roles:\n - role: nginx\n nginx_sites:\n custom_bar:\n template: custom_bar.conf.j2\n server_name: custom_bar.example.com\n```\nCustom template: custom_bar.conf.j2:\n```handlebars\n# {{ ansible_managed }}\nupstream backend {\n server 10.0.0.101;\n}\nserver {\n server_name {{ item.value.server_name }};\n location / {\n proxy_pass http://backend;\n }\n}\n```\nUsing a custom template allows for unlimited flexibility in configuring the site config file.\nThis example demonstrates the common practice of configuring a site server block\nin the same file as its complementary upstream block.\nIf you use this option:\n* _The hash **must** include a `template:` value, or the configuration task will fail._\n* _This role cannot check tha validity of your custom template.\nIf you use this method, the conf file formatting provided by this role is unavailable,\nand it is up to you to provide a template with valid content and formatting for NGINX._\n\n## 10) Install Nginx, add 2 sites, use snippets to configure access controls\n```yaml\n---\n- hosts: all\n roles:\n - role: nginx\n nginx_http_params:\n - sendfile on\n - access_log /var/log/nginx/access.log\n nginx_snippets:\n accesslist_devel:\n - allow 192.168.0.0/24\n - deny all\n nginx_sites:\n foo:\n - listen 8080\n - server_name localhost\n - root /tmp/site1\n - include snippets/accesslist_devel.conf\n - location / { try_files $uri $uri/ /index.html; }\n - location /images/ { try_files $uri $uri/ /index.html; }\n bar:\n - listen 9090\n - server_name ansible\n - root /tmp/site2\n - location / { try_files $uri $uri/ /index.html; }\n - location /images/ { try_files $uri $uri/ /index.html; }\n```\n\nDependencies\n------------\n\nNone\n\nLicense\n-------\nBSD\n\nAuthor Information\n------------------\n\n- Original : Benno Joy\n- Modified by : DAUPHANT Julien\n" }, { "alpha_fraction": 0.6931637525558472, "alphanum_fraction": 0.6995230317115784, "avg_line_length": 27.590909957885742, "blob_id": "48525db8586124352435cbd81612d89f99c9e8c8", "content_id": "daef0374e3c9d61cf9b6181b82f2dfa88e28adde", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 629, "license_type": "permissive", "max_line_length": 177, "num_lines": 22, "path": "/deploy/deploy-proxy.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n echo \"ERROR: Illegal number of parameters\"\n echo \"Usage: $0 <inventory-path>\"\n exit 1\nfi\n\nINVENTORY_PATH=$1\n\nORG=sunbird\n# Getting versions\nsource version.env\n\n# Bootstrap swarm\necho \"@@@@@@@@@ Bootstrap swarm\"\nansible-playbook -i $INVENTORY_PATH ../ansible/bootstrap.yml --extra-vars \"hosts=swarm-manager\" --tags bootstrap_swarm [email protected]\n\n# Re-deploy Proxy\necho \"Redeploy Proxy\"\nansible-playbook -i $INVENTORY_PATH ../ansible/deploy.yml --tags \"stack-proxy\" --extra-vars \"hub_org=${ORG} image_name=proxy image_tag=${PROXY_VERSION}\" [email protected]\n" }, { "alpha_fraction": 0.6362757086753845, "alphanum_fraction": 0.6554772853851318, "avg_line_length": 48.924137115478516, "blob_id": "07905c58a548adbe587ef006878cb3bb2f42ea0e", "content_id": "57b62388ef4b6c1352505cfc75efaa9dd4447501", "detected_licenses": [ "MIT", "JSON" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7239, "license_type": "permissive", "max_line_length": 429, "num_lines": 145, "path": "/ansible/roles/es7/docs/multi-instance.md", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "# Multi-instance Support\n\nStarting with ansible-elasticsearch:7.1.1, installing more than one instance of Elasticsearch **on the same host** is no longer supported.\n\nSee [554#issuecomment-496804929](https://github.com/elastic/ansible-elasticsearch/issues/554#issuecomment-496804929) for more details about why we removed it.\n\n## Upgrade procedure\n\nIf you have single-instances hosts and want to upgrade from previous versions of the role:\n\n### Procedure with data move\n\nThis procedure will allow you to move your data to the new standard paths (see [#581](https://github.com/elastic/ansible-elasticsearch/issues/581)):\n\n1. Stop Elasticsearch before the migration\n\n2. Migrate your data to the new standard paths:\n```\n# mv /etc/elasticsearch/${ES_INSTANCE_NAME}/* /etc/elasticsearch/ && rm -fr /etc/elasticsearch/${ES_INSTANCE_NAME}/\nmv: overwrite '/etc/elasticsearch/elasticsearch.keystore'? y\n# mv /var/lib/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/* /var/lib/elasticsearch/ && rm -fr /var/lib/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/\n# ls /var/lib/elasticsearch/\nnodes\n# mv /var/log/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/* /var/log/elasticsearch/ && rm -fr /var/log/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/\n# rm -fr /var/run/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/\n```\n\n3. Update playbook (remove `es_conf_dir`, `es_data_dirs`, `es_log_dir`, `es_pid_dir` and `es_instance_name` variables)\n\n4. Update ansible-role to new version ([7.1.1](https://github.com/elastic/ansible-elasticsearch/releases/tag/7.1.1) at the time of writing) and deploy ansible-role\n\n5. After ansible-role new deployment, you can do some cleanup of old Init file and Default file:\n\nExample:\n```\n$ systemctl stop elasticsearch\n$ mv /etc/elasticsearch/${ES_INSTANCE_NAME}/* /etc/elasticsearch/ && rm -fr /etc/elasticsearch/${ES_INSTANCE_NAME}/\nmv: overwrite '/etc/elasticsearch/elasticsearch.keystore'? y\n$ mv /var/lib/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/* /var/lib/elasticsearch/ && rm -fr /var/lib/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/\n$ ls /var/lib/elasticsearch/\nnodes\n$ mv /var/log/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/* /var/log/elasticsearch/ && rm -fr /var/log/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/\n$ rm -fr /var/run/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}/\n$ ansible-galaxy install --force elastic.elasticsearch,7.1.1\n- changing role elastic.elasticsearch from 6.6.0 to 7.1.1\n- downloading role 'elasticsearch', owned by elastic\n- downloading role from https://github.com/elastic/ansible-elasticsearch/archive/7.1.1.tar.gz\n- extracting elastic.elasticsearch to /home/jmlrt/.ansible/roles/elastic.elasticsearch\n- elastic.elasticsearch (7.1.1) was installed successfully\n$ ansible-playbook playbook.yml\n\n...\n\nTASK [elastic.elasticsearch : Create Directories]\nok: [localhost] => (item=/var/run/elasticsearch)\nok: [localhost] => (item=/var/log/elasticsearch)\nchanged: [localhost] => (item=/etc/elasticsearch)\nok: [localhost] => (item=/var/lib/elasticsearch)\n\nTASK [elastic.elasticsearch : Copy Configuration File]\nchanged: [localhost]\n\nTASK [elastic.elasticsearch : Copy Default File]\nchanged: [localhost]\n\nTASK [elastic.elasticsearch : Copy jvm.options File]\nchanged: [localhost]\n\n...\n\nRUNNING HANDLER [elastic.elasticsearch : restart elasticsearch]\nchanged: [localhost]\n\n...\n\nPLAY RECAP\nlocalhost : ok=26 changed=6 unreachable=0 failed=0 skipped=116 rescued=0 ignored=0\n$ find /etc -name '${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}*'\n/etc/default/node1_elasticsearch\n/etc/systemd/system/multi-user.target.wants/node1_elasticsearch.service\n```\n\n### Procedure without data move\n\nThis procedure will allow you to keep your data to the old paths:\n\n1. Override these variables to match previous values:\n```yaml\nes_conf_dir: /etc/elasticsearch/${ES_INSTANCE_NAME}\nes_data_dirs:\n - /var/lib/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}\nes_log_dir: /var/log/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}\nes_pid_dir: /var/run/elasticsearch/${INVENTORY_HOSTNAME}-${ES_INSTANCE_NAME}\n```\n\n2. Deploy ansible-role. **Even if these variables are overrided, Elasticsearch config file and default option file will change, which imply an Elasticsearch restart.**\n\n3. After ansible-role new deployment, you can do some cleanup of old Init file and Default file.\n\nExample:\n```bash\n$ ansible-playbook -e '{\"es_conf_dir\":\"/etc/elasticsearch/node1\",\"es_data_dirs\":[\"/var/lib/elasticsearch/localhost-node1\"],\"es_log_dir\":\"/var/log/elasticsearch/localhost-node1\",\"es_pid_dir\":\"/var/run/elasticsearch/localhost-node1\"}' playbook.yml\n...\nTASK [elasticsearch : Create Directories] **********************************************************************************************************************************************************************************************************************\nok: [localhost] => (item=/var/run/elasticsearch/localhost-node1)\nok: [localhost] => (item=/var/log/elasticsearch/localhost-node1)\nok: [localhost] => (item=/etc/elasticsearch/node1)\nok: [localhost] => (item=/var/lib/elasticsearch/localhost-node1)\n\nTASK [elasticsearch : Copy Configuration File] *****************************************************************************************************************************************************************************************************************\nchanged: [localhost]\n\nTASK [elasticsearch : Copy Default File] ***********************************************************************************************************************************************************************************************************************\nchanged: [localhost]\n...\nPLAY RECAP *****************************************************************************************************************************************************************************************************************************************************\nlocalhost : ok=32 changed=3 unreachable=0 failed=0\n\n$ find /etc -name 'node1_elasticsearch*'\n/etc/default/node1_elasticsearch\n/etc/systemd/system/multi-user.target.wants/node1_elasticsearch.service\n$ rm /etc/default/node1_elasticsearch /etc/systemd/system/multi-user.target.wants/node1_elasticsearch.service\n```\n\n## Workaround\n\nIf you use more than one instance of Elasticsearch on the same host (with different ports, directory and config files), you are still be able to install Elasticsearch 6.x and 7.x in multi-instance mode by using ansible-elasticsearch commit [25bd09f](https://github.com/elastic/ansible-elasticsearch/commit/25bd09f6835b476b6a078676a7d614489a6739c5) (last commit before multi-instance removal) and overriding `es_version` variable:\n\n```sh\n$ cat << EOF >> requirements.yml # require git\n- src: https://github.com/elastic/ansible-elasticsearch\n version: 25bd09f\n name: elasticsearch\nEOF\n$ ansible-galaxy install -r requirements.yml\n$ cat << EOF >> playbook.yml\n- hosts: localhost\n roles:\n - role: elasticsearch\n vars:\n es_instance_name: \"node1\"\n es_version: 7.1.1 # or 6.8.0 for example\nEOF\n$ ansible-playbook playbook.yml\n```\n" }, { "alpha_fraction": 0.7159090638160706, "alphanum_fraction": 0.7840909361839294, "avg_line_length": 16.600000381469727, "blob_id": "73bfdb2f663df7a923c8d853527a54deb7649fb4", "content_id": "61e9945e8c8932355414b52b2eb6bf53726bc17a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go Module", "length_bytes": 88, "license_type": "permissive", "max_line_length": 44, "num_lines": 5, "path": "/exporters/Go/kafka-topic-exporter/go.mod", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "module kafka-topic-exporter/main\n\ngo 1.13\n\nrequire github.com/segmentio/kafka-go v0.3.7\n" }, { "alpha_fraction": 0.5536760091781616, "alphanum_fraction": 0.559531569480896, "avg_line_length": 25.96491241455078, "blob_id": "7788db8a8fcbd2615abf2525f08715d32f667baa", "content_id": "4073fea0742c17c4668c14e3940cacc5fe668669", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1537, "license_type": "permissive", "max_line_length": 97, "num_lines": 57, "path": "/deploy/gitOPS/enableBranchProtection.sh_bak", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\nread -p \"Enter the username: \" user\nread -sp \"Enter the password:\" pass\necho \" \"\nread -p \"Enter the repo name:\" repo_name\nread -p \"Enter the branch name:\" branch_name\necho -e \"status check: \\n 1. codacy \\n 2. circleci \\n 3. both\"\nread -p \"enter number:\" check\ncheck=${check:-3}\nstatusChecks=0\nread -p \"enter username for merge access:\" users\nUsers=\\\"$users\\\"\ngithubUsers=$(echo $Users | sed 's/,/\\\",\\\"/g')\n\nif [[ $check == \"1\" ]]; then\n statusChecks='\"Codacy/PR Quality Review\"'\nelif [[ $check == \"2\" ]]; then\n\tstatusChecks='\"ci/circleci: build\"'\nelif [[ $check == \"3\" ]]; then\n\tstatusChecks='\"Codacy/PR Quality Review\",\n \"ci/circleci: build\"'\nelse\n\techo \"Select correct option!\"\nfi\necho $statusChecks\necho $githubUsers\n\ncurl -u $user:$pass -XPUT \\\n -H 'Accept: application/vnd.github.luke-cage-preview+json' \\\n -d '{\n \"protection\": {\n \"enabled\": true\n },\n\n \"enforce_admins\": true,\n \"required_pull_request_reviews\": {\n \"dismiss_stale_reviews\": true,\n \"require_code_owner_reviews\": false,\n \"required_approving_review_count\": 1\n },\n\n \"required_status_checks\": {\n \"strict\": true,\n \"contexts\": [\n '\"$statusChecks\"'\n ]\n },\n \n \"restrictions\": {\n \"users\": [\n '\"$githubUsers\"'\n ],\n \"teams\": [\n \"null\"\n ]\n }\n }' \"https://api.github.com/repos/project-sunbird/$repo_name/branches/$branch_name/protection\"\n" }, { "alpha_fraction": 0.6296296119689941, "alphanum_fraction": 0.6693121790885925, "avg_line_length": 41.11111068725586, "blob_id": "457b42e783195feedfed5fb39106bfced49b7d8d", "content_id": "dcd1851c4c539ab4340f6a9990f38f9ebc6577db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 378, "license_type": "permissive", "max_line_length": 150, "num_lines": 9, "path": "/ansible/roles/jmeter-deploy/templates/cleanup_data.j2", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncurl -X POST -H \"Content-Type: application/json\" -H \"Cache-Control: no-cache\" -d '{\n \"request\": {\n \"searchProperty\": \"name\",\n \"searchOperator\": \"startsWith\",\n \"searchString\": \"LP_PT_\"\n } \n}' \"http://internal-SANDBOX-LP-ELB-229261891.ap-south-1.elb.amazonaws.com:8080/learning-service/v1/exec/content_qe_deleteContentBySearchStringInField\"" }, { "alpha_fraction": 0.7094017267227173, "alphanum_fraction": 0.7435897588729858, "avg_line_length": 22.399999618530273, "blob_id": "555fde20fb505bec7e565eefd274c0820f7eff90", "content_id": "c55c560f90fd26d406ecf8e36d2be0587e6348a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 117, "license_type": "permissive", "max_line_length": 34, "num_lines": 5, "path": "/exporters/Go/kafka-topic-exporter/Dockerfile", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "FROM scratch\nLABEL maintainer=\"Rajesh Rajendran<[email protected]>\"\nADD kafka-topic-exporter /\nEXPOSE 8000\nCMD [\"/kafka-topic-exporter\"]\n" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.6691729426383972, "avg_line_length": 21.33333396911621, "blob_id": "53208f9aaff2ebe11549a3d029c78530a01d196c", "content_id": "8db224291bce5b5b15045945b954c128263e4bb9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 133, "license_type": "permissive", "max_line_length": 35, "num_lines": 6, "path": "/images/keycloak/installDeps.sh", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Build script\n# set -o errexit\n# apk -v --update --no-cache add jq\n# apk -v add ansible=2.3.0.0-r1\napt-get install ansible" }, { "alpha_fraction": 0.7275132536888123, "alphanum_fraction": 0.7275132536888123, "avg_line_length": 30.5, "blob_id": "7d790d06191128d899fccd54babc8be7b22ff34b", "content_id": "ada819c60f6c7ea1355e7c740358861940ecb006", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 378, "license_type": "permissive", "max_line_length": 56, "num_lines": 12, "path": "/ansible/roles/postgresql-data-update/templates/enc_postgres.sql", "repo_name": "project-sunbird/sunbird-devops", "src_encoding": "UTF-8", "text": "CREATE TYPE \"enum_Keys_type\" AS ENUM ('MASTER','OTHER');\nCREATE TABLE \"Keys\" (\n id SERIAL PRIMARY KEY,\n public text NOT NULL,\n private text NOT NULL,\n type \"enum_Keys_type\" NOT NULL,\n active boolean DEFAULT true NOT NULL,\n reserved boolean DEFAULT false NOT NULL,\n \"createdAt\" timestamp with time zone NOT NULL,\n \"updatedAt\" timestamp with time zone NOT NULL\n);\ncommit;\n" } ]
204
fatelei/cassandra-backup
https://github.com/fatelei/cassandra-backup
9ba232d25c31962074a397f8e780b059d53c686c
b593e72df7c9d6e8e2e07af5e86b0f5add0fd5e8
a3d50a702427c0a5faab87c2cf3f51761fe3eedb
refs/heads/master
2020-12-24T17:45:11.539116
2016-06-16T11:10:28
2016-06-16T11:10:28
61,284,504
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5691489577293396, "alphanum_fraction": 0.5957446694374084, "avg_line_length": 14.666666984558105, "blob_id": "3e71d686b1bad4180aebc25987f4a08ee66f224c", "content_id": "9590bcfae24832abb84dfd39d5695cf90ea7982a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 188, "license_type": "no_license", "max_line_length": 44, "num_lines": 12, "path": "/cassandra_backup/__init__.py", "repo_name": "fatelei/cassandra-backup", "src_encoding": "UTF-8", "text": "# -*- coding: utf8 -*-\n\"\"\"\ncassandra_backup.\n\n~~~~~~~~~~~~~~~~~\n\nCassandra backup tools.\nIt wraps the cassandra's nodetool, and sends\nbackup files to amazon s3.\n\"\"\"\n\n__version__ = \"1.0.0\"\n" }, { "alpha_fraction": 0.5979112386703491, "alphanum_fraction": 0.6083551049232483, "avg_line_length": 25.413793563842773, "blob_id": "2db06aea0fc6c8ebe8502aa6573ecbd3d2b594ca", "content_id": "056abb3d26cf340320dff4ca8ded9626eb63ee01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 766, "license_type": "no_license", "max_line_length": 54, "num_lines": 29, "path": "/setup.py", "repo_name": "fatelei/cassandra-backup", "src_encoding": "UTF-8", "text": "# -*- coding: utf8 -*-\n\"\"\"cassandra_backup.\"\"\"\n\nfrom setuptools import setup\n\nfrom cassandra_backup import __version__\n\n\nsetup(\n name=\"cassandra_backup\",\n version=__version__,\n description=\"cassandra backup tools\",\n install_requres=[\n \"boto3==1.3.1\"\n ],\n packages=[\"cassandra_backup\"],\n zip_safe=False,\n url=\"https://github.com/fatelei/cassandra-backup\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Console\",\n \"Environment :: Web Environment\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Programming Language :: Python :: 2.7\",\n \"Topic :: Software Development :: Libraries\",\n ],\n license=\"BSD License\"\n)\n" }, { "alpha_fraction": 0.3764705955982208, "alphanum_fraction": 0.38823530077934265, "avg_line_length": 9.625, "blob_id": "db4ec3494c714ab9ec0b8dc8cd170486ad191a71", "content_id": "64dc51526297e5c82848ea5dd2e252c1a8bfbd90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "no_license", "max_line_length": 22, "num_lines": 8, "path": "/cassandra_backup/core/__init__.py", "repo_name": "fatelei/cassandra-backup", "src_encoding": "UTF-8", "text": "# -*- coding: utf8 -*-\n\"\"\"\ncassandra_backup.core.\n\n~~~~~~~~~~~~~~~~~~~~~~\n\nCore.\n\"\"\"\n" }, { "alpha_fraction": 0.5461254715919495, "alphanum_fraction": 0.5498154759407043, "avg_line_length": 13.263157844543457, "blob_id": "adb6f11631ad51bdd765e134043d14ed0eea2100", "content_id": "a97f5b3ec36d9409bde94891ec1b59b81aa906a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 42, "num_lines": 19, "path": "/cassandra_backup/validator.py", "repo_name": "fatelei/cassandra-backup", "src_encoding": "UTF-8", "text": "# -*- coding: utf8 -*-\n\"\"\"\ncassandra_backup.validator.\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nValidator.\n\"\"\"\n\nimport os\n\n\ndef validate_path(path):\n \"\"\"Validate the path is exists or not.\n\n :param str path: Path\n :return: A boolean.\n \"\"\"\n return os.path.isdir(path)\n" }, { "alpha_fraction": 0.4130209982395172, "alphanum_fraction": 0.416121244430542, "avg_line_length": 37.7066650390625, "blob_id": "a9f36cb77d2d03eca23ffd4a845ecceba1feaf74", "content_id": "1cb1c32de34b30bbdba05a515b2c41ba42d6ab47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2903, "license_type": "no_license", "max_line_length": 67, "num_lines": 75, "path": "/cassandra_backup/cli.py", "repo_name": "fatelei/cassandra-backup", "src_encoding": "UTF-8", "text": "# -*- coding: utf8 -*-\n\"\"\"\ncassandra_backup.main.\n\n~~~~~~~~~~~~~~~~~~~~~~\n\nCommand line tools.\n\"\"\"\n\nimport argparse\n\n\ndef cli():\n \"\"\"Setup command line arguments.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"cassandra backup command tools.\")\n parser.add_argument(\"--op\",\n type=str,\n metavar=\"op\",\n dest=\"op_type\",\n help=\"operation type\",\n required=True)\n parser.add_argument(\"--aws-key-id\",\n type=str,\n metavar=\"aws key id\",\n dest=\"aws_key_id\",\n help=\"aws key id, optional\")\n parser.add_argument(\"--aws-access-key-id\",\n type=str,\n metavar=\"aws-access-key-id\",\n dest=\"aws_access_key_id\",\n help=\"aws access key id, optional\")\n parser.add_argument(\"--aws-secret-access-key\",\n type=str,\n metavar=\"aws-secret-access-key\",\n dest=\"aws_secret_access_key\",\n help=\"aws secret access key, optional\")\n parser.add_argument(\"--s3-bucket-name\",\n type=str,\n metavar=\"s3-bucket-name\",\n dest=\"s3_bucket_name\",\n help=\"s3 bucket name, required\",\n required=True)\n parser.add_argument(\"--s3-region\",\n type=str,\n metavar=\"s3-region\",\n dest=\"s3_region\",\n help=\"s3 region name, optional\")\n parser.add_argument(\"--hosts\",\n type=str,\n metavar=\"hosts\",\n dest=\"hosts\",\n help=\"hosts are need to backup or restore\",\n required=True)\n parser.add_argument(\"--cassandra-dir\",\n type=str,\n metavar=\"cassandra-dir\",\n dest=\"cassandra_dir\",\n help=\"cassandra installed location\",\n required=True)\n parser.add_argument(\"--cassandra-data-dir\",\n type=str,\n metavar=\"cassandra-data-dir\",\n dest=\"cassandra_data_dir\",\n help=\"cassandra data stored location\")\n parser.add_argument(\"--keyspace\",\n type=str,\n metavar=\"keyspace\",\n dest=\"keyspace\",\n help=\"cassandra keyspace, optional\")\n parser.add_argument(\"--table\",\n type=str,\n metavar=\"table\",\n dest=\"table\",\n help=\"table in keyspace, optional\")\n" }, { "alpha_fraction": 0.8139534592628479, "alphanum_fraction": 0.8139534592628479, "avg_line_length": 20.5, "blob_id": "69a1b68f8e593cdf82d362b54cfb9bef533eb521", "content_id": "f1001e5e9fd4b68dd13633869b6bf133cf219386", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "no_license", "max_line_length": 23, "num_lines": 2, "path": "/README.md", "repo_name": "fatelei/cassandra-backup", "src_encoding": "UTF-8", "text": "# cassandra-backup\nCassandra backup tools.\n" } ]
6
MK-Ware/computer_vision_tools
https://github.com/MK-Ware/computer_vision_tools
d96f0bb5006ab927d7f65bd78139263b86864a30
20a93a67a0c416689e9f97cefaeb72d00c5766e0
af4db10ce134dce9c4e8b51d30ea81d89f623998
refs/heads/master
2023-04-29T17:53:50.612664
2017-11-21T19:04:47
2017-11-21T19:04:47
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4962742030620575, "alphanum_fraction": 0.497764527797699, "avg_line_length": 43.733333587646484, "blob_id": "b5571244b0ec0a799718d5fb49f8580eda5d40c3", "content_id": "a1aeb838b78f87f995d5068a12d0b176a1b00b1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 671, "license_type": "permissive", "max_line_length": 113, "num_lines": 15, "path": "/README.md", "repo_name": "MK-Ware/computer_vision_tools", "src_encoding": "UTF-8", "text": "# computer_vision_tools\nA set of tools aimed at computer vision... Still a work in progress\n\n\nI will be using opencv and python for the most part. Feel free to provide feedback and contribute code.\n_______________________________________________________________________________________________________________\n\n# Dependencies so far\n-opencv3: https://pypi.python.org/pypi/opencv-contrib-python\n or: https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv\n \n-matplotlib: https://pypi.python.org/pypi/matplotlib\n\n-numpy: https://pypi.python.org/pypi/numpy\n_________________________________________________________________________________________________________________\n" }, { "alpha_fraction": 0.5371684432029724, "alphanum_fraction": 0.5621964931488037, "avg_line_length": 34.17567443847656, "blob_id": "9170ccbe931936c62aae1641db976fb1f4daefec", "content_id": "5982f845babbad5c5ee5ad7774adbd255d21abab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2677, "license_type": "permissive", "max_line_length": 116, "num_lines": 74, "path": "/feature_matcher.py", "repo_name": "MK-Ware/computer_vision_tools", "src_encoding": "UTF-8", "text": "import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nclass FeatureMatcher:\r\n\r\n def __init__(self, train_img, min_hessian=400, min_matches=10):\r\n\r\n self._train = cv2.imread(train_img, 0)\r\n self._orig_train = cv2.imread(train_img)\r\n self._min_matches = min_matches\r\n self._flann_trees = 0\r\n self.SURF = cv2.xfeatures2d.SURF_create(min_hessian)\r\n self._res = None\r\n\r\n def match(self, query_img, kd_trees=5):\r\n\r\n query = cv2.imread(query_img, 0)\r\n orig_query = cv2.imread(query_img)\r\n kp_t, desc_t = self.SURF.detectAndCompute(self._train, None)\r\n kp_q, desc_q = self.SURF.detectAndCompute(query, None)\r\n\r\n FLANN_INDEX_KDTREE = 0\r\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=kd_trees)\r\n search_params = dict(checks=50)\r\n\r\n flann = cv2.FlannBasedMatcher(index_params, search_params)\r\n matches = flann.knnMatch(desc_q, desc_t, k=2)\r\n\r\n good_matches = []\r\n for m, n in matches:\r\n if m.distance < 0.7 * n.distance:\r\n good_matches.append(m)\r\n\r\n if len(good_matches) > self._min_matches:\r\n src_pts = np.float32([kp_q[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)\r\n dst_pts = np.float32([kp_t[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)\r\n\r\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\r\n matchesMask = mask.ravel().tolist()\r\n\r\n h, w = query.shape\r\n pts = np.float32([[0, 0], [0, h-1], [w-1, h-1], [w-1, 0]]).reshape(-1, 1, 2)\r\n dst = cv2.perspectiveTransform(pts, M)\r\n\r\n query = cv2.polylines(query, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)\r\n\r\n draw_params = dict(matchColor=(0, 255, 0), singlePointColor=None,\r\n matchesMask=matchesMask, flags=2)\r\n self._res = cv2.drawMatches(orig_query, kp_q, self._orig_train, kp_t, good_matches, None, **draw_params)\r\n\r\n else:\r\n print(\"Couldn't find enough matches: {}\".format(len(good_matches),\r\n self._min_matches))\r\n\r\n def save_match(self, path=\"Result\"):\r\n\r\n cv2.imwrite(\"result.jpg\", self._res)\r\n return True\r\n\r\n def show_match(self):\r\n\r\n plt.imshow(self._res), plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n train_img = input(\"Enter your training image (please provide full path): \")\r\n query_img = input(\"Enter your query image (please provide full path): \")\r\n\r\n job = FeatureMatcher(train_img)\r\n job.match(query_img)\r\n job.save_match()\r\n job.show_match()\r\n" } ]
2
AlleyCorner/shiyanlou
https://github.com/AlleyCorner/shiyanlou
d22c99616b274daf06276c428be2f6adcbd4631c
ab9b5599ae09429a81008de5ac605bbf7c3bce73
cb9ae85fe28bf1a55f4df992328774d4e2cf2ba6
refs/heads/master
2021-09-05T21:13:23.014036
2018-01-31T02:51:15
2018-01-31T02:51:15
114,060,280
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.45326337218284607, "alphanum_fraction": 0.4932764768600464, "avg_line_length": 31.78494644165039, "blob_id": "94abb8aaed8c73fa624f557c7446cd9087d89fff", "content_id": "5b231efae34936a36d8bf832993d9d09e435d053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3049, "license_type": "no_license", "max_line_length": 136, "num_lines": 93, "path": "/calculator2.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n\nimport sys\nargs = sys.argv[1:]\nindex = args.index('-c')\nconfigfile = args[index+1]\nindex = args.index('-d')\nuserdatafile = args[index+1]\nindex = args.index('-o')\noutputfile = args[index+1]\n\nclass Config(object):\n def __init__(self,configfile):\n self._config = {}\n with open(configfile,'r') as files:\n for line in files.readlines():\n if not line:\n continue\n item = line.split('=')\n key = item[0].strip()\n value = item[1].strip()\n self._config[key] = value\n def get_config(self,text):\n return self._config[text]\n def get_social(self):\n count = 0.00\n for key,value in self._config.items():\n if str(key) == 'JiShuL':\n continue\n elif str(key) == 'JiShuH':\n continue\n else:\n count += float(value)\n return count\nclass UserData(object):\n def __init__(self,userdatafile):\n self.userdata = {}\n with open(userdatafile,'r') as files:\n for line in files.readlines():\n item = line.split(',')\n key = item[0].strip()\n value = item[1].strip()\n self.userdata[key] = value\n def cal(self,value):\n config = Config(configfile)\n if(float(value) <= float(config.get_config('JiShuL'))):\n social = float(config.get_config('JiShuL'))*config.get_social()\n elif(float(value) >= float(config.get_config('JiShuH'))):\n social = float(config.get_config('JiShuH'))*config.get_social()\n else:\n social = float(value)*float(config.get_social())\n return social\n def calculator(self,pay,social):\n try:\n c = pay\n a = c-social-3500\n except:\n print(\"Parameter Error\")\n if(a <= 0):\n b = 0.00\n elif(a <= 1500 and a>=0):\n b = a*0.03\n elif(a>1500 and a<=4500):\n b = a*0.1-105\n elif(a>4500 and a<=9000):\n b = a*0.2-555\n elif(a>9000 and a<=35000):\n b = a*0.25-1005\n elif(a>35000 and a<=55000):\n b = a*0.3-2755\n elif(a>55000 and a<=80000):\n b = a*0.35-5505\n elif(a>80000):\n b = a*0.45-13505\n else:\n print(\"Error!\")\n b = 0.00\n return b,c-b-social\n def dumptofile(self,outputfile):\n with open(outputfile,'a') as files:\n for key,value in self.userdata.items():\n lists=[]\n ID = int(key)\n pay = int(value)\n social = self.cal(value)\n tax,salary = self.calculator(pay,social)\n files.write(str(ID)+','+str(pay)+','+str(format(social,'.2f'))+','+str(format(tax,'.2f'))+','+str(format(salary,'.2f')))\n files.write(\"\\n\")\ntry:\n textfile = UserData(userdatafile)\n textfile.dumptofile(outputfile)\nexcept:\n print('Error')\n" }, { "alpha_fraction": 0.601965606212616, "alphanum_fraction": 0.6130220890045166, "avg_line_length": 24.4375, "blob_id": "d2c170fb0e2c5fe2dcb0f27544fadfa9b57f5ac2", "content_id": "6f585be21b07bae11f8b259e5683564cb6384179", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 814, "license_type": "no_license", "max_line_length": 56, "num_lines": 32, "path": "/challange6/news/app.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "from flask import Flask,render_template,abort\nimport json\nimport os\n\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n path = '/home/shiyanlou/files'\n files = os.listdir(path)\n titles = []\n for file in files:\n f = open(path+'/'+file)\n text = json.loads(f.read())\n titles.append(text.get('title'))\n f.close()\n return render_template('index.html',titles = titles)\n\[email protected]('/files/<filename>')\ndef file(filename):\n path = '/home/shiyanlou/files/'+filename+'.json'\n if not os.path.isfile(path):\n abort(404)\n with open(path,'r') as file:\n text = json.loads(file.read())\n return render_template('file.html',text = text)\n\[email protected](404)\ndef not_found(error):\n return render_template('404.html')\nif __name__=='__main__':\n app.run()\n" }, { "alpha_fraction": 0.49882903695106506, "alphanum_fraction": 0.5134660601615906, "avg_line_length": 31.846153259277344, "blob_id": "55866892615c98515a65660c7d79518173360b99", "content_id": "b2c3dafcdb89e5c1e9a419077739aa65b143149d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1708, "license_type": "no_license", "max_line_length": 108, "num_lines": 52, "path": "/challange11/shiyanlou/spiders/github.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "'''\n#!usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass GithubSpider(scrapy.Spider):\n name = 'github'\n\n @property\n def start_urls(self):\n url_tmp1 = \"https://github.com/shiyanlou?page={}&tab=repositories\"\n return (url_tmp1.format(i) for i in range(1,4))\n for url in urls:\n yield scrapy.Request(url = url,callback = self.parse)\n def parse(self, response):\n i = 0\n while i < 30:\n i += 1\n path = ('//*[@id=\"user-repositories-list\"]/ul/li[{}]').format(i)\n for text in response.xpath(path):\n# item = ShiyanlouItem({\n yield{\n 'name':(\"\".join(item.xpath(path+'/div[1]/h3/a/text()').re('(.+)'))).strip(),\n 'update_time':(\"\".join(item.xpath(path+'/div[3]/relative-time').re('datetime=\"(.+)\"')))}\n# yield item\n \n'''\n\n#! usr/bin/env python3\n\nfrom shiyanlou.items import ShiyanlouItem\nimport scrapy\n\nclass GithubSpider(scrapy.Spider):\n name = 'github'\n @property\n def start_urls(self):\n url_tmp1 = 'https://github.com/shiyanlou?page={}&tab=repositories'\n \n return (url_tmp1.format(i) for i in range(1,4))\n\n def parse(self,response):\n i=0\n while i<30:\n i += 1\n path = ('//*[@id=\"user-repositories-list\"]/ul/li[{}]').format(i)\n for text in response.xpath(path):\n item = ShiyanlouItem({\n 'name':(\"\".join(text.xpath(path+'/div[1]/h3/a/text()').re('(.+)'))).strip(),\n 'update_time':\"\".join(text.xpath(path+'/div[3]/relative-time').re('datetime=\"(.+)\"'))})\n yield item\n" }, { "alpha_fraction": 0.5228426456451416, "alphanum_fraction": 0.5380710363388062, "avg_line_length": 33.260868072509766, "blob_id": "0c6214a315ce6c1916f3037041363f50afdeaa41", "content_id": "584bd6f839583e8c2d97d4ee546c35d459431c33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 788, "license_type": "no_license", "max_line_length": 106, "num_lines": 23, "path": "/challange10.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "#! usr/bin/env python3\n\nimport scrapy\n\nclass ShiyanlouGitHubSpider(scrapy.Spider):\n name = 'shiyanlou'\n\n def start_requests(self):\n url_tmp1 = 'https://github.com/shiyanlou?page={}&tab=repositories'\n\n urls = (url_tmp1.format(i) for i in range(1,4))\n for url in urls:\n yield scrapy.Request(url=url,callback=self.parse)\n\n def parse(self,response):\n i=0\n while i<30:\n i += 1\n path = ('//*[@id=\"user-repositories-list\"]/ul/li[{}]').format(i)\n for item in response.xpath(path):\n yield{\n 'name':(\"\".join(item.xpath(path+'/div[1]/h3/a/text()').re('(.+)'))).strip(),\n 'update_time':\"\".join(item.xpath(path+'/div[3]/relative-time').re('datetime=\"(.+)\"'))}\n" }, { "alpha_fraction": 0.2928176820278168, "alphanum_fraction": 0.4654695987701416, "avg_line_length": 23.133333206176758, "blob_id": "d9358e2064f58a0aea5cbb1e60fc34dff0a7697b", "content_id": "5c523f98a1e029b52109fa9c51772b703d9e46f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 724, "license_type": "no_license", "max_line_length": 45, "num_lines": 30, "path": "/calculator.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport sys\nfor arg in sys.argv[1:]:\n try:\n argList=arg.split(':')\n c = int(argList[-1])\n d = c*(0.08+0.02+0.005+0.06)\n a = c-d-3500\n except:\n print(\"Parameter Error\")\n if(a <= 0):\n b = 0.00\n elif(a <= 1500 and a>=0):\n b = a*0.03\n elif(a>1500 and a<=4500):\n b = a*0.1-105\n elif(a>4500 and a<=9000):\n b = a*0.2-555\n elif(a>9000 and a<=35000):\n b = a*0.25-1005\n elif(a>35000 and a<=55000):\n b = a*0.3-2755\n elif(a>55000 and a<=80000):\n b = a*0.35-5505\n elif(a>80000):\n b = a*0.45-13505\n else:\n print(\"Error!\")\n b = 0.00\n print(argList[0]+':'+format(c-d-b,\".2f\"))\n" }, { "alpha_fraction": 0.4950128197669983, "alphanum_fraction": 0.5340552926063538, "avg_line_length": 23.36805534362793, "blob_id": "6a6874f1e95378a742334e7448690117c8dda39e", "content_id": "22960fbc31ada7ed88689dd1a6ec7a42036ed0f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3509, "license_type": "no_license", "max_line_length": 174, "num_lines": 144, "path": "/calculator3.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n\nimport sys\nfrom multiprocessing import Process,Queue,Lock\nimport getopt\nimport configparser\nfrom datetime import datetime\n\nque1 = Queue()\nque2 = Queue()\n\n'''\nargs = sys.argv[1:]\nindex = args.index('-c')\nconfigfile = args[index+1]\nindex = args.index('-d')\nuserdatafile = args[index+1]\nindex = args.index('-o')\noutputfile = args[index+1]\n'''\ncity = 'DEFAULT'\noption,test = getopt.getopt(sys.argv[1:],'C:c:d:o:')\nfor opt,val in option:\n if opt == '-C':\n city = val.upper()\n if opt == '-c':\n configfile = val\n if opt == '-d':\n userdatafile = val\n if opt == '-o':\n outputfile = val\ndef userdata():\n lists = []\n with open(userdatafile,'r') as files:\n for line in files.readlines():\n item = line.split(',')\n lists.append(item[0].strip())\n lists.append(item[1].strip())\n que1.put(lists)\n\ndef get_social(config):\n count = 0.00\n for key,value in config.items():\n\n if str(key) == 'jishul':\n continue\n elif str(key) == 'jishuh':\n continue\n else:\n count += float(value)\n return count\n\ndef cal(value,config,count):\n\n if(float(value) <= float(config['jishul'])):\n social = float(config['jishul'])*count\n elif(float(value) >= float(config['jishuh'])):\n social = float(config['jishuh'])*count\n else:\n social = float(value)*count\n return social\n\ndef get_tax(pay,social):\n try:\n c = pay\n a = c-social-3500\n except:\n print(\"Parameter Error\")\n if(a <= 0):\n b = 0.00\n elif(a <= 1500 and a>=0):\n b = a*0.03\n elif(a>1500 and a<=4500):\n b = a*0.1-105\n elif(a>4500 and a<=9000):\n b = a*0.2-555\n elif(a>9000 and a<=35000):\n b = a*0.25-1005\n elif(a>35000 and a<=55000):\n b = a*0.3-2755\n elif(a>55000 and a<=80000):\n b = a*0.35-5505\n elif(a>80000):\n b = a*0.45-13505\n else:\n print(\"Error!\")\n b = 0.00\n return b,c-b-social\n\n\ndef calculator():\n newdata = []\n config = {}\n data = que1.get()\n \n con = configparser.ConfigParser()\n con.read(configfile)\n section = con.items(city)\n for getkey,getval in section:\n key = getkey\n value = getval\n config[key] = value\n\n\n count = get_social(config)\n for i in data[::2]:\n ID = int(i)\n pay = int(data[data.index(i)+1])\n social = cal(pay,config,count)\n tax,salary = get_tax(pay,social)\n t = datetime.now()\n strnewdata = str(ID)+','+str(pay)+','+str(format(social,'.2f'))+','+str(format(tax,'.2f'))+','+str(format(salary,'.2f'))+','+datetime.strftime(t,'%Y-%m-%d %H:%M:%S')\n newdata.append(strnewdata)\n que2.put(newdata)\n\ndef writefile():\n data = que2.get()\n with open(outputfile,'a') as files:\n for i in data:\n files.write(i)\n files.write('\\n')\n\n\n'''\n ID = data[::2]\n pay = data[1::2]\n with open(configfile,'r') as files:\n for line in files.readlines:\n item = line.split(',')\n social.append(item[0].strip())\n social.append(item[1].strip())\n social.index('JiShuL')\n social_name = social[::2]\n social_mony = social[1::2]\n'''\n \ndef main():\n lock = Lock()\n Process(target = userdata).start()\n Process(target = calculator).start()\n Process(target = writefile).start()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7240075469017029, "alphanum_fraction": 0.7334593534469604, "avg_line_length": 34.266666412353516, "blob_id": "e21e530536a9c73a4c404eabdbea4765e9e5f2d7", "content_id": "30a0463fb07f266b7df2c1d893b17e9da740b20d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 529, "license_type": "no_license", "max_line_length": 73, "num_lines": 15, "path": "/challange11/shiyanlou/models.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column,String,Integer\n\nengine = create_engine('mysql+mysqldb://root:@localhost/shiyanlougithub')\nBase = declarative_base()\nclass Repository(Base):\n __tablename__ = 'repositories'\n id = Column(Integer,primary_key = True)\n name = Column(String(64))\n update_time = Column(String(64))\nBase.metadata.create_all(engine)\nif __name__ == '__main__':\n Base.metadata.create_all(engine)\n" }, { "alpha_fraction": 0.6366748213768005, "alphanum_fraction": 0.6474327445030212, "avg_line_length": 29.073530197143555, "blob_id": "aa86111cf6c1b92eb95d7ac4d6e935afc72e07d7", "content_id": "bd23e6b567fc273e97a46a0bc26ff30d1b8b126f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2045, "license_type": "no_license", "max_line_length": 86, "num_lines": 68, "path": "/challange7/app.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "from flask import Flask,render_template\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom datetime import datetime\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/li'\ndb = SQLAlchemy(app)\n\nclass File(db.Model):\n id = db.Column(db.Integer,primary_key = True)\n title = db.Column(db.String(80))\n created_time = db.Column(db.DateTime)\n category_id = db.Column(db.Integer,db.ForeignKey('category.id'))\n content = db.Column(db.Text)\n category = db.relationship('Category',backref=db.backref('file',lazy = 'dynamic'))\n\n def __init__(self,title,content,category_time = None):\n self.title = title\n self.content = content\n if category_time == None:\n category_time = datetime.utcnow()\n self.category_time = category_time\n def __repr__(self):\n return '<File %r>'%self.title\n\n\nclass Category(db.Model):\n id = db.Column(db.Integer,primary_key = True)\n name = db.Column(db.String(80))\n \n def __init__(self,name):\n self.name = name\n\n def __repr__(self):\n return '<Category %r>' %self.name\nclass Test(db.Model):\n \n id = db.Column(db.Integer,primary_key = True)\n name = db.Column(db.String(80))\n \n def __init__(self,name):\n self.name = name\n\n def __repr__(self):\n return '<Test %r>' %self.name\njava = Category('Java')\npython = Category('Python')\nfile1 = File('Hello Java','File Content - Java is cool!',datetime.utcnow())\nfile2 = File('Hello python','File Content - Python is cool!',datetime.utcnow())\ndb.session.add(java)\ndb.session.add(python)\ndb.session.add(file1)\ndb.session.add(file2)\ndb.session.commit()\[email protected]('/')\ndef index():\n return render_template('index.html',files = File.query.all())\n\[email protected]('/files/<file_id>')\ndef file(file_id):\n file_item = File.query.get_or_404(file_id)\n return render_template('files.html',file_item=file_item)\[email protected](404)\ndef not_found(error):\n return render_template('404.html'),404\n\nif __name__ == '__main__':\n app.run()\n" }, { "alpha_fraction": 0.5644444227218628, "alphanum_fraction": 0.581333339214325, "avg_line_length": 22.93617057800293, "blob_id": "31914fe4bc38ccdc1afd4167eabb8a8f04fe7776", "content_id": "85dbfc1781ef8cfa90252e3c6aa339e67298fd5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1125, "license_type": "no_license", "max_line_length": 42, "num_lines": 47, "path": "/cal.py", "repo_name": "AlleyCorner/shiyanlou", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n\nimport sys\nfrom multiprocessing import Process,Queue\n\nque1 = Queue()\nque2 = Queue()\n\nargs = sys.argv[1:]\nidnex = args.index('-c')\nconfigfile = args[index+1]\nindex = args.index('-d')\nuserdatafile = args[index+1]\nidnex = args.index('-o')\noutpufile = args[idnex+1]\n\nclass userData(object):\n def __init__\n with open(userdatafile,'r') as files:\n for line in files.readlines:\n item = line.split(',')\n lists.append(item[0].strip())\n lists.append(item[1].strip())\n que1.put(lists)\n\ndef calculator():\n newdata = []\n social = []\n data = que1.get()\n ID = data[::2]\n pay = data[1::2]\n with open(configfile,'r') as files:\n for line in files.readlines:\n item = line.split(',')\n social.append(item[0].strip())\n social.append(item[1].strip())\n social.index('JiShuL')\n social_name = social[::2]\n social_mony = social[1::2]\n \ndef main()\n Process(target = userdata).start()\n Process(target = calculator).start()\n Process(target = writefie).start()\n\nif __name__ == '__main__':\n mian()\n" } ]
9
vakiazaraiah/sandbox
https://github.com/vakiazaraiah/sandbox
ab52df769e38b59ee164f16fd36b11633e2fe695
81c0ba2cd75c7dc203f063f8810a878f5e02c9b2
e58b282c14ae3738d937aead7c43f0f2b519674c
refs/heads/master
2019-07-26T10:28:38.908974
2018-08-16T01:19:19
2018-08-16T01:19:19
86,210,578
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6051282286643982, "alphanum_fraction": 0.6102564334869385, "avg_line_length": 20.77777862548828, "blob_id": "a4afb2d6622b3e4c127ee4c26d147e8c1eedde5a", "content_id": "ee7e170192b4422303c3a9fc7fe4a7bf0a1c466c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 195, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/password_entry.py", "repo_name": "vakiazaraiah/sandbox", "src_encoding": "UTF-8", "text": "\"\"\"Azaraiah Vaki\"\"\"\npassword = input(\"Enter password// \")\n\nwhile len(password) < 4:\n print(\"Invalid passeword\")\n password = input(\"Enter password// \")\n\nfor char in password:\n print(\"*\", end='')" }, { "alpha_fraction": 0.7878788113594055, "alphanum_fraction": 0.7878788113594055, "avg_line_length": 32, "blob_id": "f8213cc416a3cd85d78cc7ad17942f4191fba56e", "content_id": "b0f641d3cb2278cbfb7f6eb82f1917a3a16776bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 66, "license_type": "no_license", "max_line_length": 55, "num_lines": 2, "path": "/README.md", "repo_name": "vakiazaraiah/sandbox", "src_encoding": "UTF-8", "text": "# Sandbox\nA program that is used return stars for each character.\n" } ]
2
freifunk-luebeck/alfred2zone
https://github.com/freifunk-luebeck/alfred2zone
87ea80628b5a76a7271039800e5a0c94a8b68dd2
dba771303ffacc01a4b274ff0bb2b31616dea759
dc764b195b48495333c65c72d6e3d4a9603392d2
refs/heads/master
2020-04-24T16:47:11.106505
2015-07-02T10:08:10
2015-07-02T10:11:32
21,298,578
1
3
null
null
null
null
null
[ { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.4583333432674408, "avg_line_length": 11, "blob_id": "0d3f37569954b4df2b52d3e06290c41da0f07234", "content_id": "0a4177ffaf7bd8a4921b4786825c1ef8a40e2bf6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24, "license_type": "permissive", "max_line_length": 11, "num_lines": 2, "path": "/README.md", "repo_name": "freifunk-luebeck/alfred2zone", "src_encoding": "UTF-8", "text": "alfred2zone\n===========\n" }, { "alpha_fraction": 0.515418529510498, "alphanum_fraction": 0.5700440406799316, "avg_line_length": 23.673913955688477, "blob_id": "f9390688eafa21efff86b8670bece6d3917b56b2", "content_id": "002154f57399be01a26c661b887c0b5046a18ee8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1135, "license_type": "permissive", "max_line_length": 130, "num_lines": 46, "path": "/alfred2zone.py", "repo_name": "freifunk-luebeck/alfred2zone", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport json\nimport sys\nimport re\nfrom ipaddress import *\nfrom time import time\n\nValidHostnameRegex = \"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$\"\n#prefix = IPv6Network('fdef:ffc0:3dd7::/64')\nprefix = IPv6Network('2001:67c:2d50::/48')\n\ndata = json.load(sys.stdin)[\"nodes\"].values()\n\nprint(\"\"\"$TTL 600 ; 10 minutes\n@ IN SOA srv01.luebeck.freifunk.net. info.luebeck.freifunk.net. (\n %i ; serial\n 600 ; refresh (10min)\n 30 ; retry (30s)\n 3600 ; expire (1 hour)\n 60 ; minimum (1 minute)\n )\n\t NS srv01.luebeck.freifunk.net.\n \"\"\" % time())\n\nHostnameRegex = re.compile(ValidHostnameRegex)\n\nfor e in data:\n node = e[\"nodeinfo\"]\n try:\n hostname = node['hostname']\n if HostnameRegex.match(hostname) == None:\n continue\n\n address = None\n\n for a in node['network']['addresses']:\n a = IPv6Address(a)\n if a in prefix:\n address = a\n break\n\n if address:\n print(\"%s\\tAAAA\\t%s\" % (hostname, address))\n except:\n pass\n" }, { "alpha_fraction": 0.7416267991065979, "alphanum_fraction": 0.760765552520752, "avg_line_length": 51.25, "blob_id": "38c072b921549f897cbf94788c799dd7b6237e50", "content_id": "8f03b7bfb7219d94385a3df0a0a1e4c92040f4c4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 209, "license_type": "permissive", "max_line_length": 148, "num_lines": 4, "path": "/update.sh", "repo_name": "freifunk-luebeck/alfred2zone", "src_encoding": "UTF-8", "text": "#!/bin/bash\nexport LC_ALL=en_US.UTF-8\ncurl https://map.luebeck.freifunk.net/data/nodes.json | /usr/bin/python3 /usr/local/bin/alfred2zone/alfred2zone.py > /var/cache/bind/nodes.ffhl.zone\n/usr/sbin/rndc reload\n" } ]
3
Kv-045DevOps/SRM-UI
https://github.com/Kv-045DevOps/SRM-UI
f42aaf517d5833b5c0c19e428c6e7a00643bec53
8a5533b65012393f8db511df3cc5101ca3811e36
4e51d0a7da3deb7fa55f339274d94120c99fad07
refs/heads/master
2020-04-14T20:12:51.609894
2019-01-04T09:20:48
2019-01-04T09:20:48
164,085,644
0
2
null
2019-01-04T09:17:07
2019-01-04T09:21:13
2019-01-23T15:19:04
HTML
[ { "alpha_fraction": 0.28809523582458496, "alphanum_fraction": 0.28809523582458496, "avg_line_length": 19.047618865966797, "blob_id": "48ca4325625fc81dfdd1649c6327133f932196e5", "content_id": "f49c9d8097a6b2ef73b3006447d14063db79cfe6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 420, "license_type": "no_license", "max_line_length": 37, "num_lines": 21, "path": "/app/templates/salaries.html", "repo_name": "Kv-045DevOps/SRM-UI", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Salaries</title>\n </head>\n <body>\n <ol>\n {% for i in a %}\n <li>{{i}}</li>\n <ul>\n {% for j in a[i] %}\n </br>\n {% for k in j %}\n <li>{{k}} : {{j[k]}}</li>\n {% endfor %}\n {% endfor %}\n </ul>\n {% endfor %}\n </ol>\n </body>\n</html>" }, { "alpha_fraction": 0.5666666626930237, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 14, "blob_id": "a6317cbcfb1ae8be51229423b56be6d63ed9f57d", "content_id": "e3965f660354fddbcd24a9286875e2a3c31a97e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 30, "license_type": "no_license", "max_line_length": 16, "num_lines": 2, "path": "/README.md", "repo_name": "Kv-045DevOps/SRM-UI", "src_encoding": "UTF-8", "text": "# UI Service\n## Kv-045.DevOps\n" }, { "alpha_fraction": 0.6415198445320129, "alphanum_fraction": 0.6629955768585205, "avg_line_length": 21.700000762939453, "blob_id": "40a0c7dd853876bdad1ef1ccaa43b4a2fcfa2240", "content_id": "036c2772d089bfd32e0e4a35028b1bd36cfcdff7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1816, "license_type": "no_license", "max_line_length": 71, "num_lines": 80, "path": "/app/routes.py", "repo_name": "Kv-045DevOps/SRM-UI", "src_encoding": "UTF-8", "text": "from app import app\nimport flask\nimport requests\nimport json\n\nPOST_SERVICE_URL = \"http://127.0.0.1:5001/posting\"\nVIEW_SERVICE_URL = \"http://127.0.0.1:5003/get-one\"\n\nSEND_DATA_FMT = {\"department\":\n\t\t\t{\"name\": None},\n\t\t\"team\": {\"depart_id\": None,\n\t\t\t\"name\": None,\n\t\t\t\"manager_id\": None},\n\t\t\"employee\": {\"team_id\": None,\n\t\t\t\"name\": None,\n\t\t\t\"sname\": None,\n\t\t\t\"exp\": None,\n\t\t\t\"position\": None,\n\t\t\t\"salary\": None,\n\t\t\t\"coefficient\": None}}\n\n\ndef get_info():\n\tresponse = requests.get(VIEW_SERVICE_URL)\n\treturn response.content\n\n\ndef send_info(info: dict):\n\tinfo = json.dumps(info)\n\theaders = {'Content-Type': 'application/json'}\n\tresponse = requests.post(POST_SERVICE_URL, data=info, headers=headers)\n\tif response.status_code == 200:\n\t\treturn True\n\telse:\n\t\treturn False\n\[email protected](\"/salaries\", methods=['GET'])\ndef get_all():\n a = json.loads(get_info())\n print(type(a))\n return flask.render_template(\"salaries.html\", a=a)\n\n\n\n\[email protected](\"/\")\ndef index():\n\treturn flask.render_template(\"index.html\")\n\ndef\ttry_send(key, form):\n\t\"\"\"\n\t\tFunction parse user input and tries to send data to POST service\n\t\"\"\"\n\tdata2sent = dict(SEND_DATA_FMT)\n\tfor i in SEND_DATA_FMT[key]:\n\t\tif i not in form:\n\t\t\tprint(i)\n\t\t\treturn flask.make_response((\"ERROR 1\", 500))\n\t\tdata2sent[key][i] = form[i]\n\tfor i in data2sent:\n\t\tif i != key:\n\t\t\tdata2sent[i] = None\n\tif not send_info(data2sent):\n\t\t\treturn flask.make_response((\"ERROR 2\", 500))\n\treturn flask.make_response((\"OK\", 200))\n\n\[email protected](\"/create-department\", methods=['POST'])\ndef create_departament():\n\treturn try_send('department', flask.request.form)\n\n\[email protected](\"/create-team\", methods=['POST'])\ndef create_team():\n\treturn try_send('team', flask.request.form)\n\n\[email protected](\"/hire-employee\", methods=['POST'])\ndef hire_employee():\n\treturn try_send('employee', flask.request.form)\n" } ]
3
Avidson/Bulk-Mailer
https://github.com/Avidson/Bulk-Mailer
e9fe72e273c7aa064377ad63ab12123853a68431
22d0920fdb281677843c92e1fe177817cf4a8513
f761fc3d715be7515c359a522b1fc8309da6de14
refs/heads/main
2023-08-25T07:42:46.196390
2021-10-22T08:54:20
2021-10-22T08:54:20
419,801,675
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6349557638168335, "alphanum_fraction": 0.6452802419662476, "avg_line_length": 30.511627197265625, "blob_id": "ab9787d9de6f1becd4dd22121dfe459b0fbfbdd0", "content_id": "3d4a8e9848304436849c1b54e2fa7e2b1a037a90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1356, "license_type": "no_license", "max_line_length": 93, "num_lines": 43, "path": "/new_mailer/forms.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "from django import forms \nfrom django.core.files.uploadedfile import SimpleUploadedFile\nimport ckeditor\nimport PIL as Image\nfrom ckeditor.widgets import CKEditorWidget\nfrom django_quill.fields import QuillFormField\n#from .models import EmailModel\nfrom django.forms import ModelForm\nfrom multi_email_field.forms import MultiEmailField \n\n\n\n#class EmailForm(forms.ModelForm):\n # class Meta:\n # model = EmailModel\n # fields = ['to', 'from_email','bcc', 'reply_to', 'subject', 'message', 'attachment' ]\n\n\nclass EmailForm(forms.Form):\n to = forms.EmailField(required=True, widget=forms.TextInput(attrs={\n 'size' : '90',\n 'placeholder' : 'To'\n }))\n from_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={\n 'size' : '90',\n 'placeholder' : 'From Email',\n \n }))\n bcc = MultiEmailField(widget=forms.TextInput(attrs={\n 'size' : '90',\n 'placeholder' : 'Bcc',\n 'row' :4 }))\n reply_to = forms.EmailField(required=True, widget=forms.TextInput(attrs={\n 'size' : '90',\n 'placeholder' : 'Reply to this address(s)'\n }))\n \n subject = forms.CharField(max_length=100, widget=forms.TextInput(attrs={\n 'size' : '90',\n 'placeholder' : 'Subject'\n }))\n message = QuillFormField()\n #attachment = forms.FileField(required=False)\n\n" }, { "alpha_fraction": 0.7264957427978516, "alphanum_fraction": 0.7264957427978516, "avg_line_length": 17, "blob_id": "396135b68cf1785a2329905eec01d8de3bf9a783", "content_id": "c28a1d628973e28579de227609c4cf7ce4fec260", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 54, "num_lines": 13, "path": "/new_mailer/urls.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path, include\nfrom .views import mail_sender\nfrom django.views import View\n\n\n\napp_name = 'new_mailer'\n\n\nurlpatterns = [\n path('send_mail/', mail_sender, name='send_mail' )\n]\n" }, { "alpha_fraction": 0.5227963328361511, "alphanum_fraction": 0.5805470943450928, "avg_line_length": 18.352941513061523, "blob_id": "64be52b592bd85209b23b8c10551b6c06e4547fa", "content_id": "fc78748a97e63751824702f30cfa43e8d880ac81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/new_mailer/migrations/0002_rename_emailform_emailmodel.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.3 on 2021-05-20 17:33\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('new_mailer', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='EmailForm',\n new_name='EmailModel',\n ),\n ]\n" }, { "alpha_fraction": 0.549839198589325, "alphanum_fraction": 0.610932469367981, "avg_line_length": 18.4375, "blob_id": "f359b06c7ef3acaef055d416ca3313b750823878", "content_id": "15ca353f119a48619dab846adf55e223697aa940", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 59, "num_lines": 16, "path": "/new_mailer/migrations/0003_delete_emailmodel.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.3 on 2021-05-21 06:27\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('new_mailer', '0002_rename_emailform_emailmodel'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='EmailModel',\n ),\n ]\n" }, { "alpha_fraction": 0.7553191781044006, "alphanum_fraction": 0.7553191781044006, "avg_line_length": 17.799999237060547, "blob_id": "97e3167ef5287d0937ce850802a8e038c44a373d", "content_id": "fc754b9d5f22eb52a391bb581d923fb9cf5f0d58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/new_mailer/apps.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass NewMailerConfig(AppConfig):\n name = 'new_mailer'\n" }, { "alpha_fraction": 0.7517985701560974, "alphanum_fraction": 0.7517985701560974, "avg_line_length": 38.85714340209961, "blob_id": "e5eb7a88eaafc8f1e25212b33b8386cf7cae0f17", "content_id": "32a755b86dc43745b258e79589b870c300f2ee27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 94, "num_lines": 7, "path": "/new_mailer/admin.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n#from.models import EmailModel\n# Register your models here.\n\nclass EmailModelAdmin(admin.ModelAdmin):\n list_display = ('to', 'from_email', 'bcc', 'reply_to', 'subject', 'message', 'attachment')\nadmin.site.register(EmailModel, EmailModelAdmin)" }, { "alpha_fraction": 0.604236364364624, "alphanum_fraction": 0.604236364364624, "avg_line_length": 30.421052932739258, "blob_id": "9d9809d032610ba03216983bbe2c2a9c63304c7a", "content_id": "2b4a4ce8f637818e70894972ac8b66690a37b97f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1794, "license_type": "no_license", "max_line_length": 98, "num_lines": 57, "path": "/new_mailer/views.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .forms import EmailForm\nfrom django.core.mail import EmailMessage, send_mail, send_mass_mail, BadHeaderError, EmailMessage\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom PIL import Image\nimport ckeditor \nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.files import File \nfrom django.core import mail \n\n# Create your views here.\n\n\n@login_required\ndef mail_sender(request):\n \n form = EmailForm(request.POST)\n sent = False\n connection.open()\n if request.method == 'POST':\n form = EmailForm(request.POST)\n\n if form.is_valid():\n cd = form.cleaned_data\n subject = request.POST.get(f\"{cd['subject']}\")\n message = request.POST.get(f\"{cd['message']}\")\n from_email = request.POST.get(f\"{cd['from_email']}\")\n bcc = request.POST.get(f\"{cd['bcc']}\")\n reply_to = request.POST.get(f\"{cd['reply_to']}\")\n fd = request.POST.get(f\"{cd['attachment']}\")\n with mail.get_connection() as connection:\n email = mail.EmailMessage(subject, message, from_email, [cd['to', 'to']],\n [cd['bcc']], reply_to=[cd['reply_to']], connection=connection).send()\n sent = True\n\n connection.send_messages(email)\n connection.close()\n res = email.send(fail_silently=False)\n res()\n \n \n \n else:\n form = EmailForm()\n\n context = {\n 'form' : form,\n 'sent' : sent\n\n }\n return render(request, 'new_mailer/send_mail.html', context)\n\n\ndef index_page(request, *args, **kwargs):\n\n return render(request, 'home.html', {})\n\n\n\n" }, { "alpha_fraction": 0.7072310447692871, "alphanum_fraction": 0.712522029876709, "avg_line_length": 27.25, "blob_id": "cca742704ce01d24a5ae20046850228713c359c9", "content_id": "71d8572bbb842a1289fd1ae5b79d1973da1dd41c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 567, "license_type": "no_license", "max_line_length": 61, "num_lines": 20, "path": "/new_mailer/models.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django_quill.fields import QuillField\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nimport ckeditor\nimport PIL as Image\nfrom django.core.files import File\n# Create your models here.\n\n\n#class EmailModel(models.Model):\n # to = models.EmailField()\n # from_email = models.EmailField()\n # bcc = models.EmailField()\n # reply_to = models.EmailField()\n # subject = models.CharField(max_length=200)\n # message = QuillField()\n # attachment = models.FileField()\n\n # def __str__(self):\n # return self.to\n\n\n" }, { "alpha_fraction": 0.6372073292732239, "alphanum_fraction": 0.6433241963386536, "avg_line_length": 23.43814468383789, "blob_id": "e12e7a24fe2cbe8d85f451e5a0d5dbebc5fc933c", "content_id": "cdeb4e746ba54b04ed19ca2182e92c3fe08d8611", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4741, "license_type": "no_license", "max_line_length": 91, "num_lines": 194, "path": "/newmailer/settings.py", "repo_name": "Avidson/Bulk-Mailer", "src_encoding": "UTF-8", "text": "\"\"\"\nDjango settings for newmailer project.\n\nGenerated by 'django-admin startproject' using Django 2.2.22.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.2/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.2/ref/settings/\n\"\"\"\n\nimport os\nfrom pathlib import Path \n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\n\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'new_mailer',\n 'ckeditor',\n 'ckeditor_uploader',\n 'django_quill',\n 'multi_email_field',\n\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'newmailer.urls'\n\n\nX_FRAME_OPTIONS = 'SAMEORIGIN'\n\nMEDIA_URL = '/media/'\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'newmailer.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.2/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nCKEDITOR_UPLOAD_PATH = 'content/ckeditor/'\n\nCKEDITOR_CONFIGS = {\n 'default': {\n 'disableNativeSpellChecker': False,\n 'resize_dir': 'both',\n 'width': '100%',\n 'toolbar': 'Custom',\n 'toolbar_Custom': [\n ['Undo', 'Redo'],\n ['Find', 'Replace'],\n ['Source'],\n ['Maximize'],\n '/',\n ['Format', 'Bold', 'Italic', 'Underline', 'Strike'],\n ['RemoveFormat'],\n ['NumberedList','BulletedList', '-', 'Outdent', 'Indent'],\n ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],\n ['Subscript', 'Superscript'],\n ['SpecialChar', 'PasteText',],\n ['Link', 'Unlink'],\n ],\n 'allowedContent': True,\n 'extraAllowedContent': 'iframe[*]',\n },\n}\n\nTEXT_ADDITIONAL_TAGS = [\n 'iframe',\n]\n\nTEXT_ADDITIONAL_ATTRIBUTES = [\n 'scrolling',\n 'allowfullscreen',\n 'webkitallowfullscreen',\n 'mozallowfullscreen',\n 'frameborder',\n 'src',\n 'height',\n 'width',\n]\n\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.2/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.2/howto/static-files/\n\nMEDIA_URL = '/media/'\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nSTATIC_URL = '/static/'\n# The static dir is where django will also look for static files to serve in the app\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, \"static\"),\n \n]\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\n\n\n# Redirect to home URL after login (Default redirects to /accounts/profile/)\nLOGIN_REDIRECT_URL = '/'\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n" } ]
9
TheConsciousBone/APKinstaller
https://github.com/TheConsciousBone/APKinstaller
3df5510f9dd0ce9638e83b2f906e63668194d0dc
05b8c40fdf28895602b4407d0899e1be7944640e
e8546c714a6774986550b2522c9739b142f19182
refs/heads/main
2023-07-03T04:27:18.646479
2021-08-09T15:54:58
2021-08-09T15:54:58
394,340,326
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6246006488800049, "alphanum_fraction": 0.6246006488800049, "avg_line_length": 27.809524536132812, "blob_id": "af2b0921cc109e2ef664db28319e4f0d8d97ea5f", "content_id": "ae1851c8dd60393d6f6493792878b2c52fcf1d5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 71, "num_lines": 21, "path": "/APKinstaller.py", "repo_name": "TheConsciousBone/APKinstaller", "src_encoding": "UTF-8", "text": "import os\r\nprint(\"Please insure that an Android device is connected.\")\r\nLOCATE = input(\"FIle location (drag and drop the file here)? \")\r\nCONFIRM = (\"\")\r\n\r\nprint(\"The file location is:\", LOCATE)\r\nCONFIRM = input(\"Please confirm your choice. Input Y or N to choose. \")\r\nif CONFIRM == \"Y\":\r\n print(\"Confirmed. Installing to connected device now.\")\r\n os.system('\"cd C:\\\\adb\"')\r\n os.system('\"adb devices\"')\r\n os.system(\"adb install \" + LOCATE)\r\nelse:\r\n if CONFIRM == \"N\":\r\n print(\"Cancelled.\")\r\n else:\r\n print(\"Invalid input. Run the executer again.\")\r\n\r\n\r\n\r\n# os.system('\"cmd command goes here\"')\r\n" }, { "alpha_fraction": 0.7689969539642334, "alphanum_fraction": 0.7689969539642334, "avg_line_length": 46, "blob_id": "630dfb4654b1e589867460bce5bbd9dafaf2df20", "content_id": "bd9c82147144a7b619c29de4a81f3878d2577983", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 329, "license_type": "no_license", "max_line_length": 123, "num_lines": 7, "path": "/README.md", "repo_name": "TheConsciousBone/APKinstaller", "src_encoding": "UTF-8", "text": "Hello! This is a simple APK installer that uses ADB. \n\n\nTo use it, download the .exe file from the releases page and make sure your ADB files are at the path: C:\\adb\nIf they aren't, the script will fail.\n\nMake sure the Android device connected has USB debugging enabled, otherwise the script will not be able to install the APK.\n" } ]
2
Schmorris/First_LinearRegression
https://github.com/Schmorris/First_LinearRegression
f90f8c0fdd6b6f258187a7d807e07046b0457674
3a24d949ba912f43e10baa9d42af6b22ccd82f6b
c49146ac3f3e698631c0510e144d557ed1288689
refs/heads/master
2022-12-07T11:53:47.745708
2020-08-30T09:48:04
2020-08-30T09:48:04
291,441,860
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7116654515266418, "alphanum_fraction": 0.7263389825820923, "avg_line_length": 33.07500076293945, "blob_id": "87f6747359bf208ac1484ff43bfb4c47c4e6936f", "content_id": "fc9eb62afb904a800db9af373891ed55f34ff067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 123, "num_lines": 40, "path": "/tutorial1.py", "repo_name": "Schmorris/First_LinearRegression", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np \nimport matplotlib.pyplot as plt \n\ndata = keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = data.load_data()\n\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\n\ntrain_images = train_images/255.0\ntest_images = test_images/255.0\n\n#Creating a model\nmodel = keras.Sequential([# Defining a Sequence of layers in order\n\tkeras.layers.Flatten(input_shape=(28,28)),\n\tkeras.layers.Dense(128, activation='relu'),#rectified linear unit as activation function \n\tkeras.layers.Dense(10)#picks values for each neuron so all of the values add up to one\n\t])\n\nmodel.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n\n#train the model\nmodel.fit(train_images, train_labels, epochs=5)#epochs= how often it sees the image for example. Just tweak\n\n#test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n\n#print('\\nTest accuracy:', test_acc)\n\nprediction = model.predict(test_images)\n\nfor i in range(5):\n\tplt.grid(False)\n\tplt.imshow(test_images[i], cmap=plt.cm.binary)\n\tplt.xlabel('Actual: ' + class_names[test_labels[i]])\n\tplt.title('Prediction: ' + class_names[np.argmax(prediction[i])])\n\tplt.show()\n" } ]
1
putcn/aws_runner
https://github.com/putcn/aws_runner
5dabe83f1f1ded6e2ad019fa9b28a4e7c90a80cb
78ed2c567943943ad35643066f96991d08845e0b
3a8ced56ac48eaccb12758898357aa7d8733e205
refs/heads/master
2022-04-30T23:18:55.645846
2020-12-08T20:46:11
2020-12-08T20:46:11
132,957,779
0
1
null
2018-05-10T21:48:13
2020-12-08T20:46:14
2022-03-29T21:55:00
Python
[ { "alpha_fraction": 0.5764706134796143, "alphanum_fraction": 0.7411764860153198, "avg_line_length": 11.142857551574707, "blob_id": "62e3644de3283d867632316807b5233cf9adb194", "content_id": "51befbef5420d6409f80f25f62f76cbf94879cd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 85, "license_type": "no_license", "max_line_length": 19, "num_lines": 7, "path": "/client/requirements.txt", "repo_name": "putcn/aws_runner", "src_encoding": "UTF-8", "text": "netaddr==0.7.19\nboto3==1.6.21\nnamesgenerator==0.3\nparamiko==2.4.2\nscp\nrequests\nnumpy\n" }, { "alpha_fraction": 0.6790123581886292, "alphanum_fraction": 0.6790123581886292, "avg_line_length": 40, "blob_id": "b4a1d0f281d3c1c9aa813f6c3de2434d06c44871", "content_id": "8b5b45064de58ab586e91a6632916465c6b48f41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 81, "license_type": "no_license", "max_line_length": 68, "num_lines": 2, "path": "/master/trainer.sh.template", "repo_name": "putcn/aws_runner", "src_encoding": "UTF-8", "text": "#!/bin/bash \nnvidia-docker run --network=\"host\" -i {ENV} {DOCKER_IMAGE} {COMMAND}" }, { "alpha_fraction": 0.603837251663208, "alphanum_fraction": 0.6136081218719482, "avg_line_length": 27.871795654296875, "blob_id": "34f415b9cbc979f04688783dedec747e3542df7f", "content_id": "7ac7371fabb19fda38f61a37d57b1f7a7e7d99ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5629, "license_type": "no_license", "max_line_length": 91, "num_lines": 195, "path": "/client/cluster_launcher.py", "repo_name": "putcn/aws_runner", "src_encoding": "UTF-8", "text": "import argparse\nimport logging\nimport csv\nimport os\n\nfrom abclient import Abclient\n\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument(\n '--key_name', type=str, default=\"\", help=\"required, key pair name\")\nparser.add_argument(\n '--security_group_id',\n type=str,\n default=\"\",\n help=\"required, the security group id associated with your VPC\")\n\nparser.add_argument(\n '--vpc_id',\n type=str,\n default=\"\",\n help=\"The VPC in which you wish to run test\")\nparser.add_argument(\n '--subnet_id',\n type=str,\n default=\"\",\n help=\"The Subnet_id in which you wish to run test\")\n\nparser.add_argument(\n '--pserver_instance_type',\n type=str,\n default=\"c5.2xlarge\",\n help=\"your pserver instance type, c5.2xlarge by default\")\nparser.add_argument(\n '--trainer_instance_type',\n type=str,\n default=\"p2.8xlarge\",\n help=\"your trainer instance type, p2.8xlarge by default\")\n\nparser.add_argument(\n '--task_name',\n type=str,\n default=\"\",\n help=\"the name you want to identify your job\")\nparser.add_argument(\n '--pserver_image_id',\n type=str,\n default=\"ami-da2c1cbf\",\n help=\"ami id for system image, default one has nvidia-docker ready, \\\n use ami-1ae93962 for us-east-2\")\n\nparser.add_argument(\n '--pserver_command',\n type=str,\n default=\"\",\n help=\"pserver start command, format example: python,vgg.py,batch_size:128,is_local:yes\"\n)\n\nparser.add_argument(\n '--trainer_image_id',\n type=str,\n default=\"ami-da2c1cbf\",\n help=\"ami id for system image, default one has nvidia-docker ready, \\\n use ami-1ae93962 for us-west-2\")\n\nparser.add_argument(\n '--trainer_command',\n type=str,\n default=\"\",\n help=\"trainer start command, format example: python,vgg.py,batch_size:128,is_local:yes\"\n)\n\nparser.add_argument(\n '--availability_zone',\n type=str,\n default=\"us-east-2a\",\n help=\"aws zone id to place ec2 instances\")\n\nparser.add_argument(\n '--trainer_count', type=int, default=1, help=\"Trainer count\")\n\nparser.add_argument(\n '--pserver_count', type=int, default=1, help=\"Pserver count\")\n\nparser.add_argument(\n '--action', type=str, default=\"create\", help=\"create|cleanup|status\")\n\nparser.add_argument('--pem_path', type=str, help=\"private key file\")\n\nparser.add_argument(\n '--pserver_port', type=str, default=\"5436\", help=\"pserver port\")\n\nparser.add_argument(\n '--docker_image', type=str, default=\"busybox\", help=\"training docker image\")\n\nparser.add_argument(\n '--master_server_port', type=int, default=5436, help=\"master server port\")\n\nparser.add_argument(\n '--master_server_public_ip', type=str, help=\"master server public ip\")\n\nparser.add_argument(\n '--master_docker_image',\n type=str,\n default=\"putcn/paddle_aws_master:latest\",\n help=\"master docker image id\")\n\nparser.add_argument(\n '--no_clean_up',\n type=str2bool,\n default=False,\n help=\"whether to clean up after training\")\n\nparser.add_argument(\n '--online_mode',\n type=str2bool,\n default=False,\n help=\"is client activly stays online\")\n\nargs = parser.parse_args()\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\nmetrics = {}\n\nmetrics_csv_file_name = \"metrics.csv\"\nis_metrics_file_created = False\nlog_path = os.path.join(os.path.dirname(__file__), \"logs/\")\n\ndef save_metrics_data(str_msg):\n #parse msg\n logging.info(\"found metrics data, saving it to csv file\")\n logging.info(str_msg)\n global is_metrics_file_created\n metrics_raw = str_msg.split(\",\")\n with open(log_path + metrics_csv_file_name, 'a') as csvfile:\n csv_fieldnames = []\n csv_write_data = {}\n for metric in metrics_raw:\n metric_data = metric.split(\"=\")\n metric_key = metric_data[0].strip()\n metric_val = float(metric_data[1].strip())\n if not metric_key in metrics:\n metrics[metric_key] = []\n metric_repo = metrics[metric_key]\n metric_repo.append(metric_val)\n csv_fieldnames.append(metric_key)\n csv_write_data[metric_key] = metric_val\n writer = csv.DictWriter(csvfile, fieldnames=csv_fieldnames)\n if not is_metrics_file_created:\n writer.writeheader()\n is_metrics_file_created = True\n writer.writerow(csv_write_data)\n logging.info(\"csv file appended\")\n\ndef log_handler(source, id):\n filename = id + \".log\"\n with open(log_path + filename, \"a\") as log_file:\n line_count = 0\n for line in iter(source.readline, \"\"):\n logging.info(line)\n log_file.write(line)\n line_count += 1\n if line_count >2 :\n log_file.flush()\n os.fsync(log_file.fileno())\n line_count = 0\n if (line.startswith(\"**metrics_data: \")):\n #found key data, trying to add to csv\n line = line.replace(\"**metrics_data: \", \"\")\n save_metrics_data(line)\n \n\nabclient = Abclient(args, log_handler)\n\ndef print_arguments():\n print('----------- Configuration Arguments -----------')\n for arg, value in sorted(vars(args).iteritems()):\n print('%s: %s' % (arg, value))\n print('------------------------------------------------')\n\n\nif __name__ == \"__main__\":\n print_arguments()\n if args.action == \"create\":\n abclient.create()" }, { "alpha_fraction": 0.5303676128387451, "alphanum_fraction": 0.5348724722862244, "avg_line_length": 35.56470489501953, "blob_id": "c58a47e6aa58901ba791c1768aedefcece101977", "content_id": "eef84761749df53906429a6eb889ed9660568414", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12431, "license_type": "no_license", "max_line_length": 100, "num_lines": 340, "path": "/client/abclient.py", "repo_name": "putcn/aws_runner", "src_encoding": "UTF-8", "text": "import argparse\nimport os\nimport time\nimport math\nimport logging\nimport copy\nimport threading\n\nimport netaddr\nimport boto3\nimport namesgenerator\nimport paramiko\nfrom scp import SCPClient\nimport requests\n\n#Ab stands for aws benchmark\n\nclass Abclient(object):\n def __init__(self, args, log_handler, thread_lock = threading.Lock()):\n self.args = args\n self.init_args()\n self.log_handler = log_handler\n self.ec2client = boto3.client('ec2')\n self.thread_lock = thread_lock\n\n def init_args(self):\n args = self.args\n if not args.key_name or not args.security_group_id:\n raise ValueError(\"key_name and security_group_id are required\")\n\n if not args.task_name:\n args.task_name = self.generate_task_name()\n logging.info(\"task name generated %s\" % (args.task_name))\n\n if not args.pem_path:\n args.pem_path = os.path.expanduser(\"~\") + \"/\" + args.key_name + \".pem\"\n if args.security_group_id:\n args.security_group_ids = (args.security_group_id, )\n \n def generate_task_name(self):\n return namesgenerator.get_random_name()\n \n def create_subnet(self):\n with self.thread_lock:\n args = self.args\n # if no vpc id provided, list vpcs\n logging.info(\"start creating subnet\")\n if not args.vpc_id:\n logging.info(\"no vpc provided, trying to find the default one\")\n vpcs_desc = self.ec2client.describe_vpcs(\n Filters=[{\n \"Name\": \"isDefault\",\n \"Values\": [\"true\", ]\n }], )\n if len(vpcs_desc[\"Vpcs\"]) == 0:\n raise ValueError('No default VPC')\n args.vpc_id = vpcs_desc[\"Vpcs\"][0][\"VpcId\"]\n vpc_cidrBlock = vpcs_desc[\"Vpcs\"][0][\"CidrBlock\"]\n\n logging.info(\"default vpc fount with id %s and CidrBlock %s\" %\n (args.vpc_id, vpc_cidrBlock))\n\n if not vpc_cidrBlock:\n logging.info(\"trying to find cidrblock for vpc\")\n vpcs_desc = self.ec2client.describe_vpcs(\n Filters=[{\n \"Name\": \"vpc-id\",\n \"Values\": [args.vpc_id, ],\n }], )\n if len(vpcs_desc[\"Vpcs\"]) == 0:\n raise ValueError('No VPC found')\n vpc_cidrBlock = vpcs_desc[\"Vpcs\"][0][\"CidrBlock\"]\n logging.info(\"cidrblock for vpc is %s\" % vpc_cidrBlock)\n\n # list subnets in vpc in order to create a new one\n\n logging.info(\"trying to find ip blocks for new subnet\")\n subnets_desc = self.ec2client.describe_subnets(\n Filters=[{\n \"Name\": \"vpc-id\",\n \"Values\": [args.vpc_id, ],\n }], )\n\n ips_taken = []\n for subnet_dec in subnets_desc[\"Subnets\"]:\n ips_taken.append(subnet_dec[\"CidrBlock\"])\n\n ip_blocks_avaliable = netaddr.IPSet(\n [vpc_cidrBlock]) ^ netaddr.IPSet(ips_taken)\n # adding 10 addresses as buffer\n cidr_prefix = 32 - math.ceil(\n math.log(args.pserver_count + args.trainer_count + 10, 2))\n if cidr_prefix <= 16:\n raise ValueError('Too many nodes to fit in current VPC')\n\n for ipnetwork in ip_blocks_avaliable.iter_cidrs():\n try:\n subnet_cidr = ipnetwork.subnet(int(cidr_prefix)).next()\n logging.info(\"subnet ip block found %s\" % (subnet_cidr))\n break\n except Exception:\n pass\n\n if not subnet_cidr:\n raise ValueError(\n 'No avaliable subnet to fit required nodes in current VPC')\n\n logging.info(\"trying to create subnet\")\n subnet_desc = self.ec2client.create_subnet(\n CidrBlock=str(subnet_cidr),\n VpcId=args.vpc_id,\n AvailabilityZone=args.availability_zone)\n\n subnet_id = subnet_desc[\"Subnet\"][\"SubnetId\"]\n\n subnet_waiter = self.ec2client.get_waiter('subnet_available')\n # sleep for 1s before checking its state\n time.sleep(1)\n subnet_waiter.wait(SubnetIds=[subnet_id, ])\n\n logging.info(\"subnet created\")\n\n logging.info(\"adding tags to newly created subnet\")\n self.ec2client.create_tags(\n Resources=[subnet_id, ],\n Tags=[{\n \"Key\": \"Task_name\",\n 'Value': args.task_name\n }])\n return subnet_id\n\n def run_instances(self, image_id, instance_type, count=1, role=\"MASTER\", cmd=\"\"):\n args = self.args\n ec2client = self.ec2client\n response = ec2client.run_instances(\n ImageId=image_id,\n InstanceType=instance_type,\n MaxCount=count,\n MinCount=count,\n UserData=cmd,\n DryRun=False,\n InstanceInitiatedShutdownBehavior=\"stop\",\n KeyName=args.key_name,\n Placement={'AvailabilityZone': args.availability_zone},\n NetworkInterfaces=[{\n 'DeviceIndex': 0,\n 'SubnetId': args.subnet_id,\n \"AssociatePublicIpAddress\": True,\n 'Groups': args.security_group_ids\n }],\n TagSpecifications=[{\n 'ResourceType': \"instance\",\n 'Tags': [{\n \"Key\": 'Task_name',\n \"Value\": args.task_name + \"_master\"\n }, {\n \"Key\": 'Role',\n \"Value\": role\n }]\n }])\n\n instance_ids = []\n for instance in response[\"Instances\"]:\n instance_ids.append(instance[\"InstanceId\"])\n\n if len(instance_ids) > 0:\n logging.info(str(len(instance_ids)) + \" instance(s) created\")\n else:\n logging.info(\"no instance created\")\n #create waiter to make sure it's running\n\n logging.info(\"waiting for instance to become accessible\")\n waiter = ec2client.get_waiter('instance_status_ok')\n waiter.wait(\n Filters=[{\n \"Name\": \"instance-status.status\",\n \"Values\": [\"ok\"]\n }, {\n \"Name\": \"instance-status.reachability\",\n \"Values\": [\"passed\"]\n #}, {\n # \"Name\": \"instance-state-name\",\n # \"Values\": [\"running\"]\n }],\n InstanceIds=instance_ids)\n\n instances_response = ec2client.describe_instances(InstanceIds=instance_ids)\n\n return instances_response[\"Reservations\"][0][\"Instances\"]\n\n def create(self):\n args = self.args\n self.init_args()\n\n # create subnet\n if not args.subnet_id:\n args.subnet_id = self.create_subnet()\n\n # create master node\n\n master_instance_response = self.run_instances(\n image_id=\"ami-7a05351f\", instance_type=\"t2.nano\")\n\n logging.info(\"master server started\")\n\n args.master_server_public_ip = master_instance_response[0][\n \"PublicIpAddress\"]\n args.master_server_ip = master_instance_response[0][\"PrivateIpAddress\"]\n\n logging.info(\"master server started, master_ip=%s, task_name=%s\" %\n (args.master_server_public_ip, args.task_name))\n\n # cp config file and pems to master node\n\n ssh_key = paramiko.RSAKey.from_private_key_file(args.pem_path)\n ssh_client = paramiko.SSHClient()\n ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh_client.connect(\n hostname=args.master_server_public_ip, username=\"ubuntu\", pkey=ssh_key)\n\n with SCPClient(ssh_client.get_transport()) as scp:\n scp.put(os.path.expanduser(\"~\") + \"/\" + \".aws\",\n recursive=True,\n remote_path='/home/ubuntu/')\n scp.put(args.pem_path,\n remote_path='/home/ubuntu/' + args.key_name + \".pem\")\n\n logging.info(\"credentials and pem copied to master\")\n\n # set arguments and start docker\n if args.online_mode:\n kick_off_cmd = \"docker run -i -v /home/ubuntu/.aws:/root/.aws/\"\n else:\n kick_off_cmd = \"docker run -d -v /home/ubuntu/.aws:/root/.aws/\"\n \n kick_off_cmd += \" -v /home/ubuntu/\" + args.key_name + \".pem:/root/\" + args.key_name + \".pem\"\n kick_off_cmd += \" -v /home/ubuntu/logs/:/root/logs/\"\n kick_off_cmd += \" -p \" + str(args.master_server_port) + \":\" + str(\n args.master_server_port)\n kick_off_cmd += \" \" + args.master_docker_image\n\n args_to_pass = copy.copy(args)\n args_to_pass.action = \"create\"\n del args_to_pass.pem_path\n del args_to_pass.security_group_ids\n del args_to_pass.master_docker_image\n del args_to_pass.master_server_public_ip\n for arg, value in sorted(vars(args_to_pass).iteritems()):\n if str(value):\n kick_off_cmd += ' --%s %s' % (arg, value)\n\n logging.info(kick_off_cmd)\n stdin, stdout, stderr = ssh_client.exec_command(command=kick_off_cmd)\n \n if self.args.online_mode:\n stdout_thread = threading.Thread(\n target=self.log_handler,\n args=(\n stdout,\n \"stdout\", ))\n stderr_thread = threading.Thread(\n target=self.log_handler,\n args=(\n stderr,\n \"stderr\", ))\n stdout_thread.start()\n stderr_thread.start()\n\n stdout_thread.join()\n stderr_thread.join()\n\n return_code = stdout.channel.recv_exit_status()\n logging.info(return_code)\n if return_code != 0:\n raise Exception(\"Error while kicking off master\")\n if self.args.online_mode:\n logging.info(\"training task finished, going to clean up instances\")\n self.cleanup()\n else:\n logging.info(\n \"master server finished init process, visit %s to check master log\" %\n (self.get_master_web_url(\"/status\")))\n \n def _hard_cleanup(self):\n args = self.args\n task_name = args.task_name\n ec2client = self.ec2client\n if args.no_clean_up:\n logging.info(\"no clean up option set, going to leave the setup running\")\n return\n #shutdown all ec2 instances\n print(\"going to clean up \" + task_name + \" instances\")\n instances_response = ec2client.describe_instances(Filters=[{\n \"Name\": \"tag:Task_name\",\n \"Values\": [task_name, task_name + \"_master\"]\n }])\n\n instance_ids = []\n if len(instances_response[\"Reservations\"]) > 0:\n for reservation in instances_response[\"Reservations\"]:\n for instance in reservation[\"Instances\"]:\n instance_ids.append(instance[\"InstanceId\"])\n\n ec2client.terminate_instances(InstanceIds=instance_ids)\n\n instance_termination_waiter = ec2client.get_waiter(\n 'instance_terminated')\n instance_termination_waiter.wait(InstanceIds=instance_ids)\n\n #delete the subnet created\n\n subnet = ec2client.describe_subnets(Filters=[{\n \"Name\": \"tag:Task_name\",\n \"Values\": [task_name]\n }])\n\n if len(subnet[\"Subnets\"]) > 0:\n ec2client.delete_subnet(SubnetId=subnet[\"Subnets\"][0][\"SubnetId\"])\n # no subnet delete waiter, just leave it.\n logging.info(\"Clearnup done\")\n return\n \n\n def cleanup(self):\n if self.args.online_mode:\n logging.info(\"online mode: true, hard cleanup\")\n self._hard_cleanup()\n else:\n logging.info(\"online mode: false, keep master running\")\n print requests.post(self.get_master_web_url(\"/cleanup\")).text\n\n\n def status(self):\n print requests.post(self.get_master_web_url(\"/status\")).text\n\n\n def get_master_web_url(self, path):\n args = self.args\n return \"http://\" + args.master_server_public_ip + \":\" + str(\n args.master_server_port) + path" }, { "alpha_fraction": 0.5988562107086182, "alphanum_fraction": 0.6004902124404907, "avg_line_length": 41.24137878417969, "blob_id": "7472876b112e34cce17aa948937f7ab89d6465ee", "content_id": "196ff93e850b345ff1653982eb703239bf97efdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1224, "license_type": "no_license", "max_line_length": 83, "num_lines": 29, "path": "/master/train_command.py", "repo_name": "putcn/aws_runner", "src_encoding": "UTF-8", "text": "import copy\n\nclass TrainCommand(object):\n def __init__(self, command_string, defaults = {}):\n self.parameter_map = copy.copy(defaults)\n self.commands_processed = []\n if command_string:\n self.parse(command_string)\n def update(self, dic):\n self.parameter_map.update(dic)\n def _stringify(self, major_seperator, sub_parameter_pattern):\n commands_processed = copy.copy(self.commands_processed)\n for key, val in self.parameter_map.iteritems():\n commands_processed.append(sub_parameter_pattern % (key, val))\n return major_seperator.join(commands_processed)\n def to_python_command(self):\n return self._stringify(\" \", \"--%s %s\")\n def parse(self, command_string):\n parameter_map = self.parameter_map\n commands_processed = self.commands_processed\n for seg in command_string.split(\",\"):\n if \":\" in seg:\n parameters = seg.split(\":\")\n #key has to be a string\n parameter_map[parameters[0].strip()] = (str(parameters[1])).strip()\n else:\n commands_processed.append(seg.strip())\n def unparse(self):\n return self._stringify(\",\", \"%s:%s\")" } ]
5
bigtonylewis/python-xmlsec
https://github.com/bigtonylewis/python-xmlsec
0ce51537cc31bfc320f88efed31b938afab7b892
c73298a2d515069ee557dd2b86a0059c79f4300a
25a2fe7ddd36cb4ca94ce3a0fdd623dcee765bc4
refs/heads/master
2020-12-25T16:13:34.095016
2014-12-12T19:41:18
2014-12-12T19:41:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.737500011920929, "avg_line_length": 39, "blob_id": "e4620260c9b4349d933f4634e03eb3af5f7ef2c8", "content_id": "d2c8a8f5c359ac43f0a9b49737f2753fecca84d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 80, "license_type": "permissive", "max_line_length": 61, "num_lines": 2, "path": "/src/xmlsec/meta.py", "repo_name": "bigtonylewis/python-xmlsec", "src_encoding": "UTF-8", "text": "version = '0.2.0'\ndescription = 'Python bindings for the XML Security Library.'\n" } ]
1
weigethoughts/blog
https://github.com/weigethoughts/blog
1c46d8244296b03c284d1a67adf58365d99428fa
ff4d3c5f04b670e622331ea394a0add6b7e28913
52996da67ab4369d4347a452f87ac1f0aa678fe9
refs/heads/master
2021-01-21T12:00:46.976919
2020-06-20T21:03:31
2020-06-20T21:03:31
91,764,630
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7902197241783142, "alphanum_fraction": 0.7902197241783142, "avg_line_length": 43.09375, "blob_id": "70c38fa9d38beae43cd9644c73fa07961d117b39", "content_id": "0a0e3445c67f0706c736a2861cfb820dae2e43d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 296, "num_lines": 32, "path": "/_documents/my-epistemology.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n My Epistemology\ndescription: >\n An essay in which I explain how I know things.\ntype: essay\nstatus: incomplete\n---\n\nA metaphysical belief is “true” when it correctly describes reality.\n\nAn epistemological belief is “true” when, if it is followed, it leads us to true metaphysical beliefs.\n\nAn epistemological belief can be true while also not being useful.\n\nFew, if any, beliefs are certain. We can not “prove” many beliefs.\n\nStill, we can and do use certain rules to establish how likely or unlikely beliefs are.\n\nIt is often useful to consider sets of interconnected beliefs—a “belief system.”\n\nOne may ask if a set of beliefs is internally consistent—thus, in some cases, we can disprove the belief system without disproving any particular belief.\n\nAn internally consistent belief system may still be “wrong.”\n\nWe are free agents existing in reality. We begin our lives without consciousness and it slowly appears. We can not escape our existence in reality, and our metaphysical and epistemological belief system must begin somewhere; we must adopt our first epistemological beliefs without a foundation.\n\nOur epistemological and metaphysical beliefs are intertwined; we are bound by reality, and the assumptions we make about reality inform how we decide what we know about reality, and vice versa.\n\nOur brains have a limited physical extent.\n\nLanguage is limited, but not hopelessly so.\n" }, { "alpha_fraction": 0.6915017366409302, "alphanum_fraction": 0.6915017366409302, "avg_line_length": 32.03845977783203, "blob_id": "fec67e62b493b74d1f494513869ab083623aea7f", "content_id": "fc3d34a1302483f8023afe49b323b84848b2ed6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 859, "license_type": "no_license", "max_line_length": 87, "num_lines": 26, "path": "/Makefile", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "SHELL := /bin/bash -o pipefail -e\n.SUFFIXES:\n\nCSSMIN_BIN := node_modules/clean-css-cli/bin/cleancss\nIMGMIN_BIN := node_modules/imagemin-cli/cli.js imagemin --plugin=pngquant --plugin=svgo\n\ndocuments=$(patsubst documents/%.md,_documents/%.md,$(wildcard documents/*.md))\nposts=$(patsubst posts/%.md,_posts/%.md,$(wildcard posts/*.md))\n\nall: _includes/stylesheet.min.css $(documents) $(posts)\n\n_includes/stylesheet.min.css: _includes/stylesheet.css\n\t$(CSSMIN_BIN) $< -o $@\n\n_documents/%.md: documents/%.md ./scripts/process.py ./scripts/typography.sed\n\t cat $< | sed -E -f ./scripts/typography.sed | ./scripts/process.py > $@\n\n_posts/%.md: posts/%.md ./scripts/process.py ./scripts/typography.sed\n\t cat $< | sed -E -f ./scripts/typography.sed | ./scripts/process.py > $@\n\n.PHONY: clean\n\nclean:\n\trm -rf _includes/stylesheet.min.css\n\trm -rf _site\n\trm _documents/*\n" }, { "alpha_fraction": 0.7756875157356262, "alphanum_fraction": 0.7810168266296387, "avg_line_length": 140.72055053710938, "blob_id": "6968bf60dbe483a289ee6b2d0b19b6b1d40f6650", "content_id": "480c5ad160fd0d38dba56a4eb468ccbbb610994b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 94433, "license_type": "no_license", "max_line_length": 1840, "num_lines": 662, "path": "/_documents/the-histories-herodotus.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: |\n _The Histories_ by Herodotus\ndescription: Notes on _The Histories_ by Herodotus\ntype: note\n---\n\n## Scope\n\nThe purpose of the book:\n\n<blockquote class=\"prose\">\n<p>Herodotus of Halicarnassus here displays his inquiry, so that human achievements may not become forgotten in time, and great and marvellous deeds—some displayed by Greeks, some by barbarians—may not be without their glory; and especially to show why the two peoples fought with each other. <cite>(1.1)</cite></p>\n</blockquote>\n\nHerodotus provides an extensive background for the personalities involved in the war, including many entertaining and implausible stories.\n\n<blockquote class=\"prose\">\n<p>Well, then, let these accounts told by the Egyptians be put to use by anyone who finds such things credible. My entire account is governed by the rule that I write down precisely what I am told by everyone, just as I heard it. <cite>(2.123)</cite></p>\n</blockquote>\n\nHe often adds his opinions after relaying the stories of others. He is motivated by his major topic—the Greco-Persian Wars—but also by relaying marvels that he has found.\n\n<blockquote class=\"prose\">\n<p>I am going to extend my account of Egypt at some length here and give additional details about it, because this country has more marvels and monuments that defy description than any other. <cite>(2.35)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>I have given a rather lengthy account of the Samians because they achieved the three greatest engineering works of all the Hellenes. First, they dug a tunnel through a 900-foot-high mountain. <cite>(3.59)</cite></p>\n</blockquote>\n\nHe, as do other ancient historians, avoid covering material covered by other well-known accounts:\n\n<blockquote class=\"prose\">\n<p>Let that be the extent of what is said on this topic. For others have told of the deeds they performed to obtain their positions as kings over the Dorians, even though they were Egyptians, so I shall leave that subject alone. I shall, however, record what the accounts of others have not already covered. <cite>(6.55)</cite></p>\n</blockquote>\n\nHis writing is conversational, and he does not have a strict sense of what sort of material belongs in his account and what does not. I like the broad scope. Herodotus discusses\n\n- Geography\n- Customs of various peoples\n- The causes of natural wonders\n\nHerodotus does not pander his readers with an outline, but expects them to keep track of his path themselves.\n\n## Outline\n\n- Proem, 1.1 Purpose\n- 1.2–5 Abduction of women\n- 1.6–29 The Lydian Kings\n- 1.30–94 Croesus’ Reign\n- 1.95–216 King Cyrus the Great\n- 2.1–34 Egyptian Geography\n- 2.35–98 Egyptian Customs\n- 2.99–182 Egyptian History\n- 3.1–38 Cambyses’ reign and conquest of Egypt\n- 3.39–60 Spartans vs Polykrates of Samos\n- 3.61–87 Magi revolt and Darius’ accession\n- 3.88–160 Reign of Darius\n- 4.1–82 Scythian geography and customs\n- 4.83–144 Darius’ expedition to Scythia\n- 4.145–205 Libya and the Persians\n- 5.1–29 Darius’ campaign in the Hellespont and Thrace\n- 5.30–6.41 The Ionian revolt\n- 6.41–50 Darius’ campaign begins\n- 6.50–93 Kleomenes King of Sparta, Aegina, Athens\n- 6.94–7.7 Darius’ campaign; Marathon; Aftermath\n- 7.8–177 Xerxes’ preparation and march to Greece\n- 7.178–239 Battle of Thermopylae\n- 8.1–26 Battles of Atemision\n- 8.40–125 Battle of Salamis\n- 8.126–9.24 Events during Winter\n- 9.25–89 Battle of Plataea\n- 9.90–122 Battle of Mycale; Aftermath\n\n## Epistemology\n\n<blockquote class=\"prose\">\n<p>For of all the Egyptians, the Heliopolitans are said to be the most learned in tradition. I have no desire to relate what I heard about matters concerning the gods, other than their names alone, since I believe that all people understand these things equally. But when my discussion forces me to mention these things, I shall do so. As to matters concerning the human world, they were in agreement. <cite>(2.3–4)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>The Hellenes tell many different naive stories, and their myth of Herakles is especially foolish. <cite>(2.45)</cite></p>\n</blockquote>\n\n## Religion\n\nHerodotus was pious.\n\n<blockquote class=\"prose\">\n<p>It is on this lake that they have nocturnal performances reenacting the sufferings of the gods, which the Egyptians call the mysteries. Now, although I know all the details of these rites, may my reverence ensure that they remain unspoken. I feel the same way about the rite of Demeter which the Hellenes call the Thesmophoria, so may my reverence ensure that they also remain unspoken, except for that which one can say without offense to religion. <cite>(2.171)</cite></p>\n</blockquote>\n\nHe believed in divine justice:\n\n<blockquote class=\"prose\">\n<p>[The Trojan war] took place—and here I am declaring my own opinion—because a divine force arranged matters so that the Trojans, by there total ruin and destruction, would clearly demonstrate to all humans the fundamental truth that when great injustices are committed, retribution from the gods is also great. That, at least, is what I think. <cite>(2.12)</cite></p>\n</blockquote>\n\nHerodotus believed that the Egyptians worshiped the same gods that the Greeks worshiped. To a modern person, it seems more likely that the gods and their stories developed largely (but not completely) independently. Herodotus’ willingness to associate foreign gods with Greek gods is consistent with the fact that he believed these gods existed and were present throughout the world.\n\n<blockquote class=\"prose\">\n<p>The Hellenes believe that Herakles, Dionysos, and Pan are the youngest of the gods. But the Egyptians hold that Pan is the most ancient of these three and belongs to the first group of gods, called “The Eight Gods.” Herakles belongs to the second group, called “The Twelve Gods,” and Dionysos belongs to the third, who were born from “The Twelve.” <cite>(2.145)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>The Arabians believe that Dionysos and Ourania are the only gods who exist, and they claim that they cut their hair to look just like the haircut of Dionysos. They shear the hair around the head in a ring and shave under the temples. Dionysos they call Orotalt; Ourania, Alilat. <cite>(3.8)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>The only gods they [the Scythians] try to appease are Hestia, who is their most important divinity, Zeus, and Earth, whom they consider to be the wife of Zeus; after these, they worship Apollo, Ourania Aphrodite, Herakles, and Ares. While these are the traditional gods of all the Scythians, the Royal Scythians also scarifies to Poseidon. In the Scythian language, Hestia is called Tabiti; Zeus, Papaios (and most correctly so, in my opinion); Earth is called Api; Apollo, Goitosyros; Ourania Aphrodite, Argimpasa; and Poseidon, Thagimasadas. It is not their custom to erect statues, altars, or temples, except for Ares. <cite>(4.59)</cite></p>\n</blockquote>\n\n## Quotes From Book I\n\nThe story of Gyges is entertaining. It is interesting that Gyges says “right and wrong were distinguished long ago,” as if all ethical questions are easy to answer:\n\n<blockquote class=\"prose\">\n<p>Gyges gave a cry of horror. “Master,” he said “what an improper suggestion! Do you tell me to look at the queen when she has no clothes on? No, no: ‘when she takes off her clothing, she does away with her shame’—you know what they say of women. Let us learn from experience. Right and wrong were distinguished long ago—and I’ll tell you one thing that is right: a man should mind his own business. I do not doubt that your wife is the most beautiful of women; so for goodness’ sake do not ask me to behave contrary to custom.” <cite>(1.8)</cite></p>\n</blockquote>\n\nIronically, the shamed queen soon forces Gyges to make a difficult ethical decision—die, or kill his friend the king.\n\nSolon’s says a happy life requires a good death and the prosperity of the person’s polis:\n\n<blockquote class=\"prose\">\n<p>When Solon had made as thorough an inspection [of the royal treasuries] as opportunity allowed, Croesus said: “Well, my Athenian friend, I have heard a great deal about your knowledge. I cannot resist my desire to ask you a question: who is the happiest man you have ever seen?”</p>\n<p>The point of the question was that Croesus supposed himself to be the happiest of men. Solon, however, refused to flatter, and answered in strict accordance with his view of the truth. “An Athenian,” he said, “called Tellus.”</p>\n<p>Croesus was taken aback. “And what,” he asked sharply, “is your reason for this choice?”</p>\n<p>“There are good reasons,” said Solon; “first, his city was prosperous, and he had fine sons, and lived to see children born to each of them, and all these children surviving; secondly, he had wealth enough by our standards; and he had a glorious death. In a battle with the neighboring town of Eleusis, he fought for his countrymen, routed the enemy, and died like a brave man; and the Athenians paid him the high honor of a public funeral on the spot where he fell.”</p>\n<p>All these details about the happiness of Tellus, Solon doubtless intended as a moral lesson for the king; Croesus, however, thinking he would at least be awarded second prize, asked who was the next happiest person whom Solon had seen.</p>\n<p>“Two young men of Argos,” was the reply; “Cleobis and Biton. They had enough to live on comfortably; and their physical strength is proved not merely by their success in athletics, but much more by the following incident. The Argives were celebrating the fetival of Hera, and it was most important that the mother of the two young men should drive to the temple in her ox-caft; but it so happened that the oxen were late in coming back from the fields. Her two sons therefore, as there was no time to lose, harnessed themselves to the cart and dragged it along, with their mother inside, for a distace of nearly six miles, until they reached the temple. After this exploit, which was witnessed by the assembled crowd, they had a most enviable death—a heaven-sent proof of how much better it is to be dead than alive. Men kept crowding round them and congratulating them on their strength, and women kept telling the mother how lucky she was to have such sons, when, in sheer pleasure at this public recognition of her sons’ act, she prayed the goddess Hera, before whose shrine she stood, to grant Gleobis and Biton, who ha dbrough her such honour, the greatest blessing that can fall to mortal man.</p>\n<p>“After her prayer came the ceremonies of sacrifice and feasting; and the two lads, when all was over, fell asleep in the temple—and that was the end of them, for they never spoke again.</p>\n<p>“The Argives, considering them to be the best of men, had statues made of them, which they sent to Delphi.</p>\n<p>“I know God is envious of human prosperity and likes to trouble us; and you question me about the lot of man. Listen then: as the years lengthen out, there is much both to see and to suffer which one would wish otherwise. … You seem to be very rich, and you rule a numerous people; but the question you asked me I will not answer, until I know that you have died happily. Great wealth can make a man no happier than moderate means, unless he has the luck to continue in prosperity to the end. Many very rich men have been unfortunate, and many with moderate competence have had good luck. The former are better off than the latter in two respects only, whereas the poor but lucky man has the advantage in many ways; for though the rich have the means to satisfy their appetites and to bear calamities, and the poor have not, the poor, if they are lucky, are more likely to keep clear of trouble, and will have besides the blessings of a sound body, health, freedom from trouble, fine children, and good looks.” <cite>(1.30–33)</cite></p>\n</blockquote>\n\nThe value-system, which underlies Solon’s stories, is quite different than our own. The overriding importance of the Polis, and the view of their fellow men, contrasts with our modern individualism. The view that death is the better than life is odd, and unusual (think of Achilles’ ghosts’ comments in the _Odyssey_). The importance of strength and of dieing in battle also seem peculiar to the times Herodotus lived.\n\nEmigrating after a famine:\n\n<blockquote class=\"prose\">\n<p>There was still no remission of their suffering [from famine]—indeed it grew worse; so the King divided the population into two groups and determined by drawing lots which should emigrate and which should remain at home. He appointed himself to rule the section whose lot determined that they should remain, and his son Tyrrhenus to command the emigrants. The lots were drawn, and one section went down to the coast at Smyrna, where they built vessels, put aboard all their household effects and sailed in search of a livelihood elsewhere. <cite>(1.94)</cite></p>\n</blockquote>\n\nPersian customs:\n\n<blockquote class=\"prose\">\n<p>Of all days in the year a Persian most distinguishes his birthday, and celebrates it with a dinner of special magnificence. A camel or a donkey baked whole in the oven and served up at table, and the poor some smaller beast. The main dishes at their meals are few, but they have many sorts of dessert, the various courses being served separately. It is this custom that has made them say that the Greeks leave the table hungry, because they never have anything worth mentioning after the first course: they think that if the Greeks did, they should go on eating. They are very fond of wine, and no one is allowed to vomit or urinate in the presence of another person.</p>\n<p>If an important decision is to be made, they discuss the question when they are drunk, and the following day the master of the house where the discussion was held submits their decision for reconsideration when they are sober. If they still approve it, it is adopted; if not, it is abandoned. …</p>\n<p>No race is so ready to adopt foreign ways as the Persian; for instance, they wear the Median costume because they think it handsomer than their own, and their soldiers wear the Egyptian corslet. Pleasures, too, of all sorts they are quick to indulge in when they get to know about them—a notable instance is pederasty, which they learned from the Greeks. Every man has a number of wives, and a much greater number of concubines. After prowess in fighting, the chief proof of manliness is to be the father of a large family of boys. Those who have most sons receive an annual present from the king—on the principle that there is strength in numbers. The period of a boy’s education is between the ages of five and twenty, and they are taught three things only: to ride, to use the bow, and to speak the truth. Before the age of five a boy lives with the women and never sees his father, the object being to spare the father distress if the child should die in the early stages of its upbringing. In my view this is a sound practice. I admire also the custom which forbids even the king himself to put a man to death for a single offense, and any Persian under similar circumstances to punish a servant by an irreparable injury. Their way is to balance faults against services, and then, if the faults are greater and more numerous, anger may take its course. <cite>(1.133–137)</cite></p>\n</blockquote>\n\nFate of the Lycians of Xanthus:\n\n<blockquote class=\"prose\">\n<p>The fate of the Lycians of Xanthus makes a different story. When Harpagus advanced into the plain of Xanthus, they met him in battle, though greatly outnumbered, and fought with much gallantry; at length, however, they were defeated and forced to retire within their walls, whereupon they collected their women, children, slaves, and other property and shut them up in the citadel, set fire to it and burnt it to the ground. Then having sworn to do or die, they marched out to meet the enemy and were killed to a man. <cite>(1.176)</cite></p>\n</blockquote>\n\nBabylonian engagement custom:\n\n<blockquote class=\"prose\">\n<p>In every village once a year all the girls of marriageable age used to be collected together in one place, while the men stood round them in a circle; an auctioneer then called each one in turn to stand up and offered her for sale, beginning with the best-looking and going on to the second best a soon as the first had been sold for a good price. Marriage was the object of the transaction. The rich men who wanted wives bid against each other for the prettiest girls, while the humbler folk, who had no use for good looks in a wife, were actually paid to take the ugly ones, for when the auctioneer had got through all the pretty girls he would call upon the plain ones, or even perhaps a crippled one, to stand up, and then ask who was willing to take the least money to marry her—and she was offered to whoever accepted the smallest sum. The money came from the sale of the beauties, who in this way provided dowries for their ugly or misshapen sisters. …</p>\n<p>This admirable practice has now fallen into disuse and they have of late years hit upon another scheme, namely the prostitution of all girls of the lower classes to provide some relief from the poverty which followed upon the conquest with its attendant hardship and general ruin. <cite>(1.196)</cite></p>\n</blockquote>\n\nBabylonian Aphrodite cult:\n\n<blockquote class=\"prose\">\n<p>There is one custom amongst the people which is wholly shameful: every woman who is a native of the country must once in her life go and sit in the temple of Aphrodite and there give herself to a strange man. … Once a woman has taken her seat she is not allowed to go home until a man has thrown a silver coin into her lap and taken her outside to lie with her. As he throws the coin, the man has to say, “in the name of the goddess Mylitta”—that being the Assyrian name for Aphrodite. The value of the coin is of no consequence; once thrown it becomes sacred, and the law forbids that it should ever be refused. The woman has no privilege of choice—she must go with the first man who throws her the money. When she has lain with him, her duty to the goddess is discharged and she may go home, after which it will be impossible to seduce her by any offer, however large. Tall, handsome women soon manage to get home again, but the ugly ones stay a long time before they can fulfill the condition which the law demands, some of them, indeed, as much as three or four years. <cite>(1.199)</cite></p>\n</blockquote>\n\nMassagetae customs:\n\n<blockquote class=\"prose\">\n<p>Every [Massagetae] man has a wife, but all wives are used promiscuously. If a man wants a woman, all he does is to hang up his quiver in front of her wagon and then enjoy her without misgiving. They have one way only of determining the appropriate time to die, namely this: when a man is very old, all his relatives give a party and include him in a general sacrifice of cattle; then they boil the flesh and eat it. This they consider to be the best sort of death. Those who die of disease are not eaten but buried, and it is held a misfortune not to have lived long enough to be sacrificed. They have no agriculture, but live on meat and fish, of which there is an abundant supply in the Araxes. They are milk-drinkers. The only god they worship is the sun, to which they sacrifice horses: the idea behind this is to offer the swiftest of mortal creatures to the swiftest of the gods. <cite>(1.216)</cite></p>\n</blockquote>\n\n## Quotes From Book II\n\nThe account of why the Egyptians came to believe the Phrygians were the oldest men:\n\n<blockquote class=\"prose\">\n<p>Now, before Psammetichos became king, the Egyptians used to believe that they were the earliest humans. But upon assuming the kingship Psammetichos became eager to ascertain which people were really the first; and ever since his reign, the Egyptians consider that the Phrygians lived before they did, but that they themselves existed prior to all the rest of humanity. Unable to find a means of discovering who were the first humans by making inquiries, Psammetichos devised an experiment. He selected two newborn children from ordinary people and gave them to a shepherd to take into his flocks and raise according to the following instructions: no one was to utter a word in their presence; the shepherd should place them in a secluded hut by themselves and at appropriate intervals bring in the goats, give the children their fill of milk, and then tend to the rest of their needs. The reason he gave these instructions was because he wished to listen to the children after they had outgrown their inarticulate crying and to find out what word they would speak first. And everything turned out as he planned, for the shepherd had followed his orders for two years when one day, as he opened the door entering, both children rushed at him with outstretched hands, crying out “bekos.” At first the shepherd kept quiet about having heard this, but when the word bekos was repeated again and again as he came and went in his care for the children, he told his master. At his command the shepherd brought the children into his presence, and Psammetichos himself heard the word. When he inquired which people might use the word bekos, he discovered that the word bekos means “bread” in the Phrygian language. Thus the Egyptians accepted this evidence and concluded that the Phrygians are older than themselves. <cite>(2.2)</cite></p>\n</blockquote>\n\nWhether or not the Egyptians believed this account or performed this experiment, it seems clear that some group (be it Herodotus or his listeners) found this account plausible. There is a certain logic to the argument, and it also demonstrates the basic conception of performing an “experiment” to learn about the natural world. They assume that language is innate, and that a child would innately begin speaking the first language. They also don’t seem to consider that the children could have, by chance, made up a word that matched an existing language.\n\nHerodotus seems to believe the world is quite old:\n\n<blockquote class=\"prose\">\n<p>I believe that perhaps present-day Egypt was once a gulf just like this [the Red Sea], which would have extended from the sea in the north toward Ethiopia in this south, and that the other gulf extending from the Southern Sea north toward Syria nearly ran together with it at their extremities, but they were separated from each other by a small strip of land passing between them. Now then, if the Nile’s flow were diverted into this Arabian gulf, what would prevent it from filling up the gulf with silt in 20,000 years? For my part, I suppose it might fill it up with silt in only 10,000 years. Well, then, given all the years that passed before I was born, why could not a gulf much larger than this have been silted up by a river as great and powerful as the Nile? <cite>(2.11)</cite></p>\n</blockquote>\n\nIn several places in Herodotus, it seems the Greeks (in this case the Ionians) wanted to believe the world was innately symmetrical and ordered. Thus, they want to believe there is a clean division between the continents.\n\n<blockquote class=\"prose\">\n<p>Now, if my understanding of these matters is correct, then the Ionians’ conception of Egypt is absurd, and even if their view of Egypt were correct, their simple arithmetic would be all wrong! For when they claim that the whole earth is made up of three parts—Europe, Asia, and Libya—they in fact should add the Delta of Egypt as a fourth part. Indeed, by their own definition, the Nile is what divides Asia and Libya; but the fact is that the Nile splits and flows around the Delta from its apex, so that the Delta itself lies between Asia and Libya.</p>\n<p>Let me dismiss the view of the Ionians now and instead describe to you my own opinions on these matters. I believe it best to characterize Egypt as all the territory inhabited by Egyptians, just as Cilicia is populated by Cilicians and Assyria by the Assyrians; and as we have seen, there are no boundaries between Asia and Libya other than the boundaries of the land which is inhabited by the Egyptians. <cite>(2.16–17)</cite></p>\n</blockquote>\n\nHerodotus argues that there are not geometrically pure boundaries, and that Egypt is where the Egyptians are. This conception is more consistent with my own—words are often vague, recursive representations of patterns, such as “where the Egyptians are.” But I may be misunderstanding Herodotus, because in the next fragment, he presents an argument using an oracle from Ammon, which may refute my understanding of what he says. Perhaps I am applying a 21st century expectations to him.\n\nA fun passage discussing the cause of the Nile’s flooding:\n\n<blockquote class=\"prose\">\n<p>Certain Hellenes, however, wanting to win fame for their cleverness, have expressed three different explanations concerning this river …</p>\n<p>The second explanation is even less knowledgeable than the one just mentioned and, if I may say so, more astonishing. Its claim is that the Nile causes this phenomenon because it flows from Ocean, and that Ocean flows around the entire world.</p>\n<p>The third theory, though ostensibly much more plausible, is in fact the most erroneous. Indeed, this theory makes no sense at all when it claims that the Nile’s flood comes from melting snow which flows from the interior of Libya through the middle of Ethiopia and then issues forth into Egypt. Well, now, how could flood come from melting snow if its water flows from the warmest regions to those which are for the most part cooler? A man could at least try to think logically about such things … [Herodotus gives various arguments against this second theory]</p>\n<p>And the man who spoke of Ocean, transporting his story into the realm of the unknown, cannot possibly be refuted. For I, at least, have no certain knowledge that such a river Ocean exists; I think, rather, that Homer or one of the poets before him invented the name and introduced it into his poetry.</p>\n<p>If one were to say, however, that after finding fault with the opinions already proposed about the unknown, one should declare his own ideas, I shall reveal to you why I think the Nile floods in summer. I believe that during the winter the sun is driven off its usual course by storms and travels to the region of the sky above Libya. <cite>(2.20–23)</cite></p>\n</blockquote>\n\nAs in the story about Psammetichos’ experiment, it seems that rational and empirical explanations are being pursued. I’m impressed that Herodotus dismissed the second argument as not refutable and conjectures that a poet made it up.\n\nA bizarre story about cats:\n\n<blockquote class=\"prose\">\n<p>Many animals live with these people, but many more would do so if it were not for the fate of the cats. When the female cats have given birth, they no longer associate with the males, who, however, still seek intercourse with them, but without success. So in response, the males outsmart the females by stealing away and then killing their offspring, although they do not eat them after killing them. The females, bereft of their babies, feel a desire for more and so go back to the males, for they are fond of offspring.</p>\n<p>And whenever a fire breaks out, some divine seizure comes over the cats. The Egyptians stand at intervals and try to keep the cats safe, but if they fail to extinguish the fire, the cats slip between or leap over them and rush into the flames. When this happens, the Egyptians are overcome by intense grief. All those who live in a household where a cat has died a natural death shave their eyebrows. For the death of a dog, however, they shave their entire body and head. <cite>(2.66)</cite></p>\n</blockquote>\n\nA comical story about a Pharaoh that simultaneously hints at the Greek (and perhaps also Egyptian) view of women:\n\n<blockquote class=\"prose\">\n<p>They say that when Sesostris died, his son Pheros inherited the kingdom. He performed no military feats, but was blinded in the following incident: during his reign the river flooded over the land to a greater extent than ever before; it rose to a height of twenty-seven feet, and when it overflowed the fields, the winds drove it to surge in waves like a sea. They say that this kin, in reckless arrogance, took a spear and cast it into the eddies in the middle of the river, and that immediately afterward, his eyes were afflicted with disease and he became blind. His blindness continued for ten years until, in the eleventh year, there came an oracular response from the city of Bouto stating that the duration of the his punishment was over now and that he would regain his sight by washing his eyes with the urine of a woman who had been with her husband alone, having had no experience of any other men. And so he first tried this with the urine of his own wife, but this failed to restore his sight. He then tried all other women, one after the other, and when he finally regained his sight, he brought together into one city—which is now called Red Soil–all the women he had tried except for the one whose urine had restored his sight. When they were gathered together there, he set them all on fire along with the city itself. But he took as his own wife the woman with whose urine he had washed his eyes and regained his sight. <cite>(2.111)</cite></p>\n</blockquote>\n\nAccording to the Egyptian priests, Helen never made it to Troy—violent winds pushed Paris off course, and after landing in Egypt and learning what had happened, they retained Helen:\n\n<blockquote class=\"prose\">\n<p>That is what the Egyptian priests said, and I agree with their argument, considering that if Helen had been in Troy, the Trojans would certainly have returned her to the Hellenes, whether Paris concurred or not. For neither Priam nor his kin could have been so demented that they would have willingly endangered their own persons, their children, and their city just so that Paris could have Hellen. Surely the Trojans would have realized this even in the first years of the war and would have given her up. <cite>(2.120)</cite></p>\n</blockquote>\n\nIt is astounding how influential Homer was in the ancient world; it is as if all the Greek writers thought in terms of Homer and the _Iliad_.\n\nThere is a fantastical story about an architect, his two sons, the Pharaoh, and his daughter, in Book II fragment 121, but it is too long to transcribe. I recommend reading it.\n\nApparently some of the Egyptians believed in reincarnation:\n\n<blockquote class=\"prose\">\n<p>The Egyptians are in fact the first to have claimed that the human soul is immortal and that each time the body perishes, it enters at birth another living being; and whenever it has gone through the lives of all types of creatures living on land or sea, or flying in the air, it again enters at birth the body of a human. This cycle is said to take 3,000 years. There are certain Hellenes—some who lived earlier, some later—who have adopted the theory as though it were their very own. <cite>(2.123)</cite></p>\n</blockquote>\n\nThe Pharaoh prostitutes his daughter:\n\n<blockquote class=\"prose\">\n<p>The priests said that Cheops sank to such depths of wickedness that when he ran short of money, he placed his own daughter in a brothel and ordered her to charge a certain sum of silver, although they neglected to tell me the exact amount she was to demand. She did as her father ordered, but, intending to leave behind a memorial of her own, she asked each man who came to her for the gift of one stone. And from these stones, they said, was built the pyramid that stands in the middle of the three that are situated in front of the great pyramid. Each of its sides measures 150 feet. <cite>(2.126)</cite></p>\n</blockquote>\n\nThe Pharaoh Amasis’ advice about working too much:\n\n<blockquote class=\"prose\">\n<p>Amasis established the following daily routine for himself. He worked diligently on serious matters of government from dawn until the peak market hour [about 10 a.m.], but after that he would drink and banter with his drinking companions. His close friends and family were disturbed by this behavior and admonished him: “Sire, you are not conducting yourself properly by pursuing worthless pastimes. You ought to be seated solemnly upon your stately throne, transacting affairs of state throughout the day; that way, the Egyptians would know that they were being governed by a competent man, and your reputation would improve. But as it is, you are not acting at all like a king.” Amasis retorted: “When archers need to use their bows, they string them tightly, but when they have finished using them, they relax them. For if a bow remained tightly strung all the time, it would snap and would be of no use when someone needed it. The same principle applies to the daily routine of a human being: if someone wants to work seriously all the time and not let himself ease off for his share of play, he will go insane without even knowing it, or at the least suffer a stroke. And it is because I recognize this maxim that I allot a share of my time to each aspect of life.” <cite>(2.173)</cite></p>\n</blockquote>\n\n## Quotes From Book III\n\nGreek culture held these two, somewhat contradictory, beliefs: that men should compete and strive for excellence “be the best,” but also that they should not strive with the gods. Both beliefs are present in Homer (the former being especially clear in the *Iliad*, and the later perhaps more so in the *Odyssey*), as well as Herodotus. This story is a nice example of the latter belief:\n\n<blockquote class=\"prose\">\n<p>Now Amasis did not fail to notice Polykrates’ [a Greek tyrant] exceptionally good fortune, and it worried him; so when his luck continued to improve still further, Amasis wrote him a letter and sent it to Samos. The letter said, “From Amasis to Polykrates: It is a pleasure to hear that a friend and ally is doing well, but I am not pleased by your exceptional good fortune, since I know that god is jealous. Actually, what I sincerely want for both myself and for those I care about is good fortune in one matter but failure in another, and thus a life of continually alternating fortune rather than of success in everything. For I have never yet heard of anyone enjoying good fortune in all things who did not ultimately die in total disaster. And so now listen to me and deal with your perpetual good fortune as I advise. You must think about what you have and select your most valuable possession, whatever would most break your heart were you to lose it; and then throw that object away so that it will never reach a human being again. If, after this, your good fortune persists and does not alternate with suffering, apply the remedy I have suggested once again.”</p>\n<p>When Polykrates read this latter, he realized that Amasis had given him very good advice, so he searched for the one heirloom in his possession whose loss would most afflict his heart and selected a signet ring that he wore, an emerald set in gold which had been crafted by Theodoros of Samos son of Telekles. And so when he decided that his ring was the object he should throw away, he manned a penteconter, got on board, and ordered the men to put out to sea. When they had reached a distance far from Samos, he took off his ring and, as all the men sailing with him looked on, tossed it into the sea. That done, he sailed home and mourned his loss.</p>\n<p>But then, four or five days later, a fisherman caught a huge and beautiful fish; and thinking that it was only right to present it to Polykrates as a gift, he took it to the doors of Polykrates’ home and announced that he wished to be admitted into the presence of Polykrates. When this request was granted, he offered the fish to Polykrates with these words: “Sire, when I caught this fish, I did not think it right to take it to market, although I do make my living by my own labor. Instead, I decided it was worthy of you and your rule. So I bring this fish and give it to you now as a present.” Polykrates was delighted to hear this little speech and replied, “You are very kind; I thank you twice over, both for your words and for your gift, and I invite you to dine with us.” The fisherman went home every flattered by the esteem shown him by Polykrates. But when the servants cut open the huge fish, they discovered the ring of Polykrates within its belly. As soon as they saw it, they took it out and gleefully brought it to him and, as they gave it to him, explained how they had found it. Polykrates realized that this was an act of god, so he wrote down everything he had done and what had happened to him, then sent the whole story in a letter to Egypt.</p>\n<p>When Amasis read this letter, he realized that it was impossible for one person to rescue another from what he was destined to experience: he knew that Polykrates was not going to continue to enjoy good fortune in everything and come to a happy end, since even what he had attempted to throw away had been restored to him. So Amasis sent a herald to Samos to announce that he was breaking off their alliance of friendship. <cite>(3.40–42)</cite></p>\n</blockquote>\n\nAnd Polykrates did meet a terrible end, in fact, his death was so gruesome Herodotus says he didn’t want to describe it. Most historians today believe that Polykrates broke off the relationship with Amasis when Cambyses conquered the Phoenicians (who had a great navy), and thus threatened Samos. The story provides insight into the Greek’s beliefs about good fortune.\n\nThe ethnic cleansing of the Magi, after over-throwing the short-lived conspiracy by the two Magi brothers to pose as Smerdis:\n\n<blockquote class=\"prose\">\n<p>After the conspirators had killed both Magi, they cut off their heads and, leaving their own wounded men there, since they were too weak to go with them but could help guard the acropolis, the other five ran outside carrying the heads of the Magi. There, with great shouts they called out to the other Persians, describing all that had happened and showing them the heads. As they spread the news, they also killed every Magus they found in their path. When the Persians learned from them about the Magi’s criminal fraud and what had just occurred, they decided it was right for them to join in the killing, too, so, drawing their daggers, they slew every Magus they found, and if nightfall had not ended the slaughter, there would not have been a single Magus left alive. The Persians commemorate this day as their most important public holiday and celebrate it with a great festival they call the Murder of the Magi. And during this entire day all Magi must keep within their houses—none are permitted to appear outside. <cite>(3.79)</cite></p>\n</blockquote>\n\nAfter the Magi revolt is put down, the seven Persians purportedly debated the merits of monarchy, oligarchy, and democracy. Here is the argument for Democracy:\n\n<blockquote class=\"prose\">\n<p>“I think it best that we no longer be ruled by one of ourselves as a monarch, since that kind of government is neither pleasant nor good. You have seen how Cambyses became outrageously arrogant, and you have all experienced the insolence of the Magus directly. How could monarchy be a harmonious and coherent system when it permits the ruler to do whatever he wishes, to be accountable to no one? Even the best of men, if placed in this position of power, would lose his normal mental balance, for arrogance will grow within him as he enjoys all the good things at hand, as will envy, too, which is always a fundamental component of human nature. All evil lies in these two traits, and he manifests both of them. … The rule of the majority, however, not only has the most beautiful and powerful name of all, equality, but in practice, the majority does not act at all like a monarch. Indeed, the majority chooses its magistrates by lot, it holds all of these officials accountable to an audit, and it refers all resolution to the authority of the public. I therefore propose that we abandoned monarchy and raise the majority to a ruling position, for in the many is the whole.” <cite>(3.80)</cite></p>\n</blockquote>\n\nIt seems impossible that this conversation ever occurred, partly because Herodotus’ presentation of democracy has a few uniquely Athenian components. Here are the arguments for oligarchy:\n\n<blockquote class=\"prose\">\n<p>I am in favor of what Otanes says in his attempt to put an end to tyranny, but when he tells us to transfer power to the majority, he has strayed far from good judgement. For nothing can be both more unintelligent or insolent than the worthless, ineffectual mob. If men want to escape the arrogance of a tyrant, it is absolutely intolerable that they should then fall victim to the arrogance of the undisciplined common people. For whatever the tyrant may do, he at least knows what he is doing, whereas the people have no idea of what they are doing. How could someone who has not been educated, who has never seen anything good or decent, be knowledgeable about anything? He pushes and shoves and stumbles into affairs without thought, like a raging torrent. <cite>(3.81)</cite></p>\n</blockquote>\n\nAnd finally, here is Darius’ winning argument for monarchy:\n\n<blockquote class=\"prose\">\n<p>What Megabyzos claimed about the majority seems right to me, but what he said about oligarchy seems wrong. For if we compare the best examples in theory of these three types of government—the best democracy, the best oligarchy, and the best monarchy—I declare that monarchy surpasses the other two by far. For obviously nothing can be better than the one man who is the best. And since he has the best judgement, he would be a blameless administrator of the majority, and thus, too, he would best be able to maintain silence about his plans to oppose enemies. In an oligarchy, on the other hand, many men strive to achieve excellence, and thus private rivalries tend to become public hostilities. For each man wants to be the head of affairs and desires that his own opinions prevail; so that they ultimately become extremely hostile toward one another, which leads to the emergence of factions, which in turn produces bloodshed, and then, also demonstrates just how much monarchy excels the others. Then again, when the people rule, incompetence will always inevitably be the result. While this incompetence is present, these inept men do not themselves engage in public hostilities, but instead form strong friendships among one another as they incompetently manage the commonwealth together. This situation goes on until one of them steps forth as leader of the people and stops the others from continuing such actions, after which this man is effectively declared to be a monarch, which again proves that monarchy is the best of the three. <cite>(3.82)</cite></p>\n</blockquote>\n\nAn interesting observation about how frequently animals reproduce:\n\n<blockquote class=\"prose\">\n<p>The Arabians say that the entire world would be filled with these snakes if it were not for a certain phenomenon that happens to them, and which, I believe, also happens to vipers. And this phenomenon indeed makes sense: for divine providence in its wisdom created all creatures that are cowardly and that serve as food for others to reproduce in great numbers so as to assure that some would be left despite the constant consumption of them, while it has made sure that those animals which are brutal and aggressive predators reproduce very few offspring. The hare, for example, is hunted by every kind of beast, bird, and man, and so reproduces prolifically. Of all animals, she is the only one that conceives while she is already pregnant; her womb can contain at the same time young that are furry, bare of fur, just recently formed, and still being conceived. <cite>(3.108)</cite></p>\n</blockquote>\n\nI think Herodotus’ observation is clever, and it seems reasonable. It is similar to people who say that God created each animal with its own job and role; while perhaps true in a deeper sense, it is not true in the direct sense, since evolution has optimized for the fine balance between species.\n\nFantastical thoughts about the end of the earth:\n\n<blockquote class=\"prose\">\n<p>It is clear that gold exists in by far the greatest quantities to the north of Europe, but I cannot say with certainty how it comes to be there. It is reported that there are one-eyed men called Arimaspians who snatch it away from griffins, but I cannot believe in the existence of one-eyed men who are born that way, and who would still have in all other respects a nature just like that of other humans. In any case, these peripheral regions which surround and enclose the rest of the Earth on all sides quite reasonably contain the very things we value as most beautiful and rare. <cite>(3.116)</cite></p>\n</blockquote>\n\nNote that Herodotus (inconsistently with his discussion of the number of continents in Book II), applies deductive reasoning to geography, with poor results. This expectation that geography can be reasoned about is similar to the expectation that the laws of physics should act a certain way, although I believe we are right and they were wrong. Still, when seen as a parallel like this, such arguments may feel less silly to us.\n\nThe Babylonians, when they revolted, killed many of their women:\n\n<blockquote class=\"prose\">\n<p>After the navy sailed off to Samos, the Babylonians revolted. They had prepared for this rebellion well in advance, for during the entire period of disorder when the Magus ruled and the Seven revolted, they were making preparations for a siege, and somehow no on noticed them doing it. When they did revolt openly, each man set aside his mother and one woman he selected from his household to prepare his food. These women were saved; all the other women were brought together and strangled in order to prevent them from consuming the supply of food. <cite>(3.150)</cite></p>\n</blockquote>\n\n## Quotes From Book IV\n\nSailing around Africa:\n\n<blockquote class=\"prose\">\n<p>After he [king Nechos of Egypt] stopped excavation work on the canal, which extended from the Nile to the Arabian Gulf, he sent some Phoenicians off on boats with orders to sail around Libya and back through the Pillars of Herakles into the Mediterranean Sea and to return by that route to Egypt And so the Phoenicians set out from the Erythraean Sea and sailed the Southern Sea. Whenever autumn came, they would put in to shore at whatever region of Libya they happened to have reached in order to sow seeds. There they would wait for the harvest, and after reaping their crops, they would sail on again. This they did for two years, and in the third, they came around through the Pillars of Herakles and returned to Egypt. They mentioned something else which I do not find credible, though someone else may: that when they were sailing around Libya, the sun was on their right as they went. <cite>(4.42)</cite></p>\n</blockquote>\n\nAn account of Scythian soothsayers:\n\n<blockquote class=\"prose\">\n<p>Whenever the king of the Scythians falls ill, he sends for three of the most distinguished soothsayers, and they perform prophecies in the first way that I described. What they generally report is that some person has sworn falsely by the royal hearth, and they accuse one of the townspeople by name. In fact, it is the Scythian custom that when someone wants to swear the most solemn kind of oath, he most often does so by the royal hearth. The man named by these prophets is immediately apprehended and brought to the soothsayers, who charge that their prophecy has revealed him to be a perjurer on the royal hearth and thus to be the cause of the king’s present pain. When the accused man protest vehemently and denies the charge, the king responds by sending for twice as many soothsayers. If they, too, condemn the man as a perjurer through their prophecies, the man is immediately beheaded, and the first three prophets divide up his possessions by lot. But if they recently summoned soothsayers in addition to the other three absolve him of the charge, then other soothsayers come, and again more besides. If the majority of all these acquit the man, it is decreed that the first three prophets themselves must die. <cite>(4.68)</cite></p>\n</blockquote>\n\nThe tradition implies skepticism of the soothsayers’ ability and motives. This description is an example of superstition leading to injustice, although in this situation, the soothsayers take the role of judges.\n\nHere is an incredible story about the supposed development of the belief in immortality:\n\n<blockquote class=\"prose\">\n<p>As to immortality, the Getai believe that they do not really die, but that when one of them passes away, he goes to Salmoxis, a sort of divinity whom some of them also call Gebeleizis. Every fifth year they send off one of their number, who has been selected by lot to serve as a messenger to Salmoxis, with instructions as to what they want at that particular time. This is how they dispatch him. Three men who are appointed to the task each hold a javelin, while others seize the hands and feet of the man being sent to Salmoxis, swing him up in the air, and throw him onto the points of the javelins. If the man dies from being impaled, they believe that the god is well disposed toward them; but if he does not die, they blame the messenger himself, accusing him of being a bad man, and seek another to send in his place. They give the messenger instructions while he is still alive. These same Thracians shoot their arrows up into the sky, aiming at thunder and lightning as they shout threats at the god, and they believe that no other god exists but their own.</p>\n<p>I have heard from the Hellenes who inhabit the Hellespont and the Pontus, however, that this Salmoxis was actually a human being who had been enslaved and served Pythagoras son of Mnesarchos on Samos. But he was eventually freed, and then he acquired abundant wealth there before returning to his own land. Now while the Thracians live a crude life and are rather stupid, Salmoxis knew the Ionian way of life and character, which is more profound than that of the Thracians, and he had associated with Hellenes, including Pythagoras, certainly not the feeblest thinker of the Hellenes. And so he had a banqueting hall built where he hosted and entertained the leading men of the town, and he taught them that neither he nor they, his drinking companions, nor their descendants would die, but that they would come to a place where they would live on and have all good things. And as he was composing these lessons and relating them to his guests, he was also constructing an underground chamber. When it was completely finished, he vanished from the sight of the Thracians, by descending into the chamber and spending three years there. The Thracians missed him and grieved for him as though he had died, but in the fourth year he appeared to them, and thus what Salmoxis had thought them became credible. That, at least, is what they say he did.</p>\n<p>I myself do not believe this story about him and the underground chamber, although I don’t discount it completely. I do think, however, that this Salmoxis lived many years before Pythagoras. But whether Salmoxis was born a human being or exists as some sort of native divinity among the Getai, let us bid him farewell. At any rate, that is how the Getai were subdued by the Persians, and they were now following along with the rest of the army. <cite>(4.94–96)</cite></p>\n</blockquote>\n\nHerodotus’, following a Greek sort of “geographic reasoning”, compares Scythia to a square (although it is not at all square like):\n\n<blockquote>\n<p>And so the shape of Scythia is square: two of its sides reach down to the sea, and these and its coastal and inland margins make it equal on all sides.</p>\n</blockquote>\n\nA story about legalistically evading an oath:\n\n<blockquote class=\"prose\">\n<p>There was in Axos a merchant, Themision of Thera, with whom Etearchos pledged guest-friendship and whom he asked to swear to perform whatever service he would request. When Themision had sworn the oath, Etearchos brought forth his daughter and handed her over to him with instructions to take her away and throw her into the sea. Infuriated at being deceived by the oath in this way, Themision renounced his pact of guest-friendship, and then, to release himself from obligation under the oath he had sworn to Etearchos, he sailed away with the girl, tied a rope around her, lowered her down into the sea, and then, after pulling her back up, took her with him back to Thera. <cite>(4.154)</cite></p>\n</blockquote>\n\nSexual customs of the Auseans:\n\n<blockquote class=\"prose\">\n<p>They share intercourse with their women in common, promiscuously like beasts, and do not dwell together as couples. Whenever a woman’s child has developed sufficiently, the men get together within three months, and whichever of them the child resembles most is acknowledged as his father. <cite>(4.180)</cite></p>\n</blockquote>\n\n## Quotes from Book V\n\nThe life-denying Getai:\n\n<blockquote class=\"prose\">\n<p>When a child is born to them [the Getai], his relatives sit around him and grieve over all the evils he will have to endure later, recounting all things that humans must suffer. But when someone dies, they have fun and take pleasure in burying him in the ground, reciting over him all the evils he has escaped and how he is now in a state of complete bliss. <cite>(5.4)</cite></p>\n</blockquote>\n\nThe contest among Krestonian wives:\n\n<blockquote class=\"prose\">\n<p>Each man has many wives, and whenever a man dies, a great contest with fierce rivalry is held among his wives and their families concerning which of them was the wife whom he loved the most. The woman who is judged most worthy of this honor is eulogized by both the mean and the women, after which her closest relative cuts her throat over the grave and she is buried with her husband. The other wives consider their rejection a terrible misfortune and the greatest possible disgrace. <cite>(5.5)</cite></p>\n</blockquote>\n\nThe Thracian customs:\n\n<blockquote class=\"prose\">\n<p>They sell their children for export abroad and do not keep watch over their unmarried daughters, but instead allow them to have intercourse with any man they want. They purchase their wives, however, from the women’s parents for very high prices and then guard them quite strictly. To have tattoos is a mark of nobility, while having none is a sign of baseness. The idle man of leisure is most admired, and the man who works the soil is most despised. The most honorable way to make a living is thought to be by war and plunder. Those are their most remarkable customs. <cite>(5.6)</cite></p>\n</blockquote>\n\nDarius’ comment about friendship:\n\n<blockquote class=\"prose\">\n<p>Of all possessions the most valuable is a friend who is both intelligent and well intentioned. <cite>(5.24)</cite></p>\n</blockquote>\n\nSending a message on a slave’s tattooed head:\n\n<blockquote class=\"prose\">\n<p>Histiaios had wanted to tell Aristagoras to revolt but could not safely send such and instruction to him, since the roads were guarded. And so he had chosen his most trustworthy slave, shaved his head, tattooed it with his message, and waited for the hair to grow back. As soon as it had done so, he sent the slave off with instructions to do nothing other than go to Miletus and, once there, to tell Aristagoras to shave off his hair and look at his head. <cite>(5.35)</cite></p>\n</blockquote>\n\nThe Athenian women stab a man to death with pins:\n\n<blockquote class=\"prose\">\n<p>That is the account told by the Argives and Aeginetans, and they agree with the Athenians that only one Athenian returned home to Attica safe and sound, except that the Argives say that it was they who destroyed the Attic army from which the one man survived, while the Athenians attribute the loss of the army to a divine force. Actually that one man did not survive long either, but perished in the following way. After he had returned to Athens he reported the disaster, and when the wives of the men who had served with him against Aegina heard of it, they became outraged that of all the men, he alone had come back safely. They took hold of him on all sides and, as they all asked him where their own husbands were, they stabbed him with the pins of the cloaks; and so that is how he, too, died. To the Athenians, what the women had done seemed an even more terrible disaster than the loss of the army. They could find no other penalty to impose upon the women except to make them change their style of dress to the Ionian fashion. Prior to this, the Athenian women had worn Dorian clothing, which most resembles the Corinthian style, but now they changed to wearing a linen tunic, so they would have no pins to use. <cite>(5.87)</cite></p>\n</blockquote>\n\nHerodotus’ comments about democracy in Athens:\n\n<blockquote class=\"prose\">\n<p>So the Athenians had increased in strength, which demonstrates that an equal voice in government has beneficial impact not merely in one way, but in every way: the Athenians, while ruled by tyrants, were no better in war than any of the peoples living around them, but once they were rid of tyrants, they became by far the best of all. Thus it is clear that they were deliberately slack while repressed, since they were working for a master, but that after they were freed, they became ardently devoted to working hard so as to win achievements for themselves as individuals. <cite>(5.78)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>When Aristgoras appeared before the Athenian people, he repeated the same things that he had said in Sparta about the good things in Asia and about Persian warfare—that they used neither shields nor spears and how easy it would be to subdue them. In addition, he told them that Miletus was originally and Athenian colony, and therefore, since the Athenians were a great power, it was only fair and reasonable for them to offer protection to the Milesians There was nothing he failed to promise them, since he was now in dire need, and at last he managed to win them over. For it would seem to be easier to deceive and impose upon a whole throng of people than to do so to just an individual, since he had failed with Kleomenes of Lacedaemon, who was alone, but then succeeded with 30,000 Athenians. After the Athenians had been won over, they voted to dispatch twenty ships to help the Ionians and appointed Melanthion, a man of the city who was distinguished in every respect, as commander over them. These ships turned out to be the beginning of evils for both Hellenes and barbarians. <cite>(5.97)</cite></p>\n</blockquote>\n\nDarius’ comments when he first hears about the Athenians:\n\n<blockquote class=\"prose\">\n<p>It is said that when Darius first heard this report, he disregarded the Ionians, since he knew that they at least would not escape punishment for their revolt; but he inquired who the Athenians were, and after he had been told, he asked for a bow. He took the bow, set an arrow on its string, and shot the arrow toward the heavens. And as it flew high into the air, he said: “Zeus, let it be granted to me to punish the Athenians.” After saying this, he appointed one of his attendants to repeat to him three times whenever his dinner was served: “My lord, remember the Athenians.” <cite>(5.105)</cite></p>\n</blockquote>\n\nOnesilos’ head:\n\n<blockquote class=\"prose\">\n<p>Because Onesilos had besieged the Amathousians, they cut off his head and took it to Amathous, where they hung it up over the city gates. The head eventually became hollow as it hung there, and then swarms of bees entered it and filled it with honeycombs. <cite>(5.114)</cite></p>\n</blockquote>\n\n## Quotes from Book VI\n\nChios’ bad omens:\n\n<blockquote class=\"prose\">\n<p>It often happens that signs are given whenever great evils are about to fall upon a city or nation. And in fact remarkable signs had appeared to the Chians before these events occurred. First, they had sent a chorus of 100 youths to Delphi, and only two of them returned home; the other ninety-eight were struck down and carried off by plague. Secondly and simultaneously, just a short time before the naval battle, a roof in the city collapsed on a group of boys as they were learning their letters, with the result that out of 120 children, only one escaped with his life. Those were the signs sent by the go in advance. Then the naval battle overcame the city and brought it to its knees, and in addition to that, after the naval battle, Histiaios came leading his Lesbian troops, and as the Chians had recently been badly mauled, he vanquished them quite easily. <cite>(6.27)</cite></p>\n</blockquote>\n\nThe Ionians defeated a third time:\n\n<blockquote class=\"prose\">\n<p>At this point the Persians made good on the threats that they had voiced earlier against the Ionians when they were camped opposite them. For after they had completed their conquest of the cities, they picked out the most handsome boys and castrated them, making them eunuchs instead of males with testicles. And they dragged off the most beautiful of the virgins to the King. After they had carried out these threats, they also set fire to the cities and to their sanctuaries, too. Thus the Ionians were reduced to slavery for the third time, the first being at the hands of the Lydians, and then twice in succession by the Persians. <cite>(6.32)</cite></p>\n</blockquote>\n\nThe funeral privileges granted to Spartan kings:\n\n<blockquote class=\"prose\">\n<p>Those are the privileges granted by the Spartan community to the kings while they live; after their death they receive the following honors. Horse-men carry the news of the king’s death throughout all of Laconia, and in every city, women walk about beating on cauldrons; and whenever this occurs, two free people from each household, a man and a woman, must defile themselves, otherwise they incur large fines. One custom observed by the Lacedaemonians at the death of their kings is the same as that practiced by a majority of the barbarians in Asia when their kings die: whenever a king of the Lacedaemonians dies, a fixed number of the <em>periokoi</em> from all of Lacedaemon, in addition to the Spartans, must attend the funeral to grieve. And when many thousands of people have gathered there—<em>periokoi</em>, helots, and Spartans—men mingling together with women, all beating their heads vigorously, they wail continuously and loudly, proclaiming that this king who has just died had proved himself to be the best. <cite>(6.58)</cite></p>\n</blockquote>\n\nThe Oracle at Delphi was widely respected, yet understood to be plagued by human foibles:\n\n<blockquote class=\"prose\">\n<p>The controversy continued until finally the Spartans decided to ask the oracle at Delphi whether Demaratos was or was not the son of Ariston. It was Kleomenes who had come up with the idea to refer this question to the Pythia, and he next gained the support of Kobon son of Aristophantos, who wielded the greatest influence at Delphi and who then persuaded Periallos the Pythia thus, when the sacred delegates presented their question, the Pythia asserted that Demaratos was not the son of Ariston. Later, however, these intrigues became known, and as a result, <obon was exiled from Delphi, while Periallos the Pythia was ousted from her position of honor. <cite>(6.66)</cite></p>\n</blockquote>\n\nThe Greeks and Romans believed that gods would come down and sleep with their women. One wonders if this was a protective excuse used by dishonest wives. Here is such an example from Herodotus:\n\n<blockquote class=\"prose\">\n<p>“On the third night after the night on which Ariston had brought me to his home, an apparition in the likeness of Ariston came to me, and after lying with me, put the garlands it had been wearing on me. The apparition left, and then Ariston came; when he saw me wearing the garlands, he asked who had given them to me. I told him it was he himself, but he refused to admit it. Then I swore an oath and said that it was not right for him to deny it, since only a short time before, he had come in and given me the garlands after lying with me. Seeing that I had sworn to it on oath, Ariston realized that this had been the act of a divinity. For the garlands had evidently come from the shrine of the hero called Astrabakos which is set up at the doors of the courtyard, and the prophets had proclaimed this very Astrabakos to be a hero.” <cite>(6.69)</cite></p>\n</blockquote>\n\nThe Greeks drank their wine diluted with water, and believe that not doing so could be harmful:\n\n<blockquote class=\"prose\">\n<p>The Spartans, however, say that Kleomenes became deranged not because of any divine force, but because he had become, through his association with Scythians, a drinker of undiluted wine. <cite>(6.84)</cite></p>\n</blockquote>\n\nDarius seemed like a reasonable and civiized king:\n\n<blockquote class=\"prose\">\n<p>Datis and Artaphrenes sailed to Asia and brought the captive Eretrian slaves to Susa. Darius the King had been nursing a bitter grudge against the Eretrians before they were brought to him as slaves, because they had struck first and been the aggressors. But when he saw them delivered up to him as his subjects, he did them no further harm but instead settled them at his royal station in the land of the Kissians called Arderikka <cite>(6.119)</cite></p>\n</blockquote>\n\nClearly sports were very important in Greece; Herodotus frequently mentions the athletic accomplishments of individuals in Book 6.\n\nViews on marriage and the choice of women:\n\n<blockquote class=\"prose\">\n<p>Furthermore, he treated his daughters in the following exceptional way: when they came of age, he generously granted them the most extravagant gift by giving them in marriage to the man whom each of them had selected for herself from among all Athenian men. <cite>(6.122)</cite></p>\n</blockquote>\n\nA fanciful story about Croesus’ wealth:\n\n<blockquote class=\"prose\">\n<p>When Alkmeon arrived there, Croesus offered him a gift of as much gold as he could carry away on his person at one time. So Alkmeon devised and carried out an effective way to deal with such a gift. He put on a large tunic, leaving a deep fold hanging down from it, and high boots, the widest he could find, then entered the treasury to which he was led. Diving into the heap of gold dust, he first packed as much gold along his shins as his boots could hold; next, he filled the entire fold forming a pocket with gold, sprinkled the hair on his head with gold dust, put some more into his mouth, and finally left the treasury, barely able to drag his boots along with him, resembling anything but a human being, with his mouth full and puffed out! When Croesus saw him, he was overcome with laughter and offered to give Alkmeon not only all that he had with him but an additional amount equal to that which he was now carrying. That is how the house of the Alkmeonids became extremely wealthy, and in this way Alkmeon became rich enough to keep a four-horse chariot and team, with which he won an Olympic victory. <cite>(6.125)</cite></p>\n</blockquote>\n\nA story of the leading suitor break-dancing away his marriage:\n\n<blockquote class=\"prose\">\n<p>When the day came that had been appointed for the wedding feast and for Kleisthenes to declare which man he had chosen out of all of them, Kleisthenes sacrificed 100 cattle and served a feast to the suitors and to all the people of Sicyon. After the meal, the suitors participated in a competition in music and in speeches delivered to everyone there. As the drinking progressed, Hippokleides, who was already commanding much attention from the others, ordered the flute player to play a dance tune for him. The flute player complied, and while I suppose Hippokleides pleased himself with his dancing, Kleisthenes, as he watched, was annoyed at everything he saw. After pausing for a moment, Hippokleides ordered that a table be brought to him; then he stepped up on the table and first danced some Laconian steps, and then some Attic ones, too. But the third thing he did was to turn upside down and, with his head resting on the table, gesticulate with his legs waving in the air. Now during the first and second of these dances, Kleisthenes restrained himself and did not blurt out his thoughts, although he felt somewhat disgusted at the thought that Hippokleides might still become his son-in-law, but when he saw him waving his legs around, he could no longer contain himself and said, “Son of Teisandros, you have just danced away your marriage!” And the young man replied, “For Hippokleides, no problem!” <cite>(6.129)</cite></p>\n</blockquote>\n\n## Quotes from Book VII\n\nThe good advice Xerxes’ uncle Atrabanos affords him, among the assembly of Persian nobles:\n\n<blockquote class=\"prose\">\n<p>“For I find that the greatest profit comes from planning with care and deliberation. Then, if you should be impeded by any adversity, your plan is still a good one but fails only because of bad luck. On the other hand, one who has done a poor job of planning, even if good luck attends him, nonetheless eventually discovers that his plan was a bad one.” <cite>(7.10.delta)</cite></p>\n</blockquote>\n\nA possible natural cause of the Greek belief in the jealousy of the gods:\n\n<blockquote class=\"prose\">\n<p>“Further, you see how the god strikes with his thunderbolt those creatures that tower above the rest, and does not permit them to be so conspicuous, while those who are small do not at all provoke him. And you see how he always hurls his missiles at those houses and trees that are the largest and tallest. For the god likes to lop off whatever stands out above the rest; and so, on a similar principle, a huge army is destroyed by a small one; for whenever the god has become resentful toward an army, he casts panic or lightning into it, and it is thus completely destroyed through no fault of its own. For the god will not tolerate pride in anyone but himself.” <cite>(7.10.epislon)</cite></p>\n</blockquote>\n\nAn interesting comment about slander:\n\n<blockquote class=\"prose\">\n<p>“For slander is a most terrible crime, one in which two people commit the injustice and a third is the victim of it. The one who slanders commits and injustice against the one who is not present, while the person who listens to him does wrong by believing him before learning if his claims are accurate. And the man who is absent from their talk is wronged, being slandered by the one and assumed to be bad by the other.” <cite>(7.10.eta)</cite></p>\n</blockquote>\n\nArtabanos educates Xerxes as to the nature of dreams:\n\n<blockquote class=\"prose\">\n<p>“I, being much older than you, shall teach you what sorts of things these dreams which make their way to humans actually are. Most of the visions visiting our dreams tend to be what one is thinking about during the day. During the days before this dream our minds have been engaged in dealing with this military campaign more than anything else. Now, if this dream is not what I judge it to be after all, but something divine whose meaning you yourself have found and summarized, then let it appear and instruct me as it has you. But if it really wants to appear, it should not be more likely to appear to me just because I am wearing your clothes rather than my own, or resting in your bed instead of min. For whatever it is that appears to you in your sleep could not possibly be so stupid as to see me and think that I am you on the evidence of clothing.” <cite>(7.16.beta–gamma)</cite></p>\n</blockquote>\n\nHerodotus’ expounds on the great size of the Persian expedition:\n\n<blockquote class=\"prose\">\n<p>During four full years following the conquest of Egypt, Xerxes prepared his army and gathered provisions for it. Then, in the course of the fifth year, he set out on his campaign with an enormous body of troops. In fact, of all the expeditions we know of, this was by far the largest. Darius’ expedition against the Scythians looks like nothing in comparison with that of Xerxes, and the same is true of the Scythian expedition when the Scythians chased the Cimmerians into Media and then subjugated and occupied almost the whole interior of Asia, which was the reason Darius later attempted to punish them. Nor can we compare the expedition of the sons of Atreus against Troy, according to the traditional account, nor that of the Mysians and Teukrians before the Trojan Ware, when they had crossed over to Europe at the Bosporus, subjugated all the Thracians, advanced down to the Ionian Sea, and marched as far south as the Peneios River. All these expeditions combined, even with others added to them, could not possibly equal the size of the expedition of Xerxes, for what nation of Asia did Xerxes not lead to Hellas? What body of water did his forces not drink dry except for the greatest rivers? <cite>(7.20–1)</cite></p>\n</blockquote>\n\nAn interesting story while traveling to Greece:\n\n<blockquote class=\"prose\">\n<p>While Xerxes was traveling along this road he discovered a plane tree that so impressed him with its beauty that he endowed it with golden ornaments and entrusted it to one of the Immortals as its guardian. <cite>(7.31)</cite></p>\n</blockquote>\n\nXerxes reviewing the army at Abydos:\n\n<blockquote class=\"prose\">\n<p>Atrabanos his uncle, the man who in the first instance had spoken his mind so freely in trying to dissuade Xerxes from undertaking the campaign, was by his side; and when he saw how Xerxes wept, he said to him: “My lord, surely there is a strange contradiction in what you do now and what you did a moment ago. Then you called yourself a happy man—and now you weep.”</p>\n<p>“I was thinking,” Xerxes replied; “and it came into my mind how pitifully short human life is—for of all these thousands of men not one will be alive in a hundred years’ time.”</p>\n<p>“Yet,” said Atrabanos, “we suffer sadder things in life even than that. Short as it is, there is not a main in the world, either here or elsewhere, who is happy enough not to wish—not once only but again and again—to be dead rather than alive. Troubles come, diseases afflict us; and this makes life, despite its brevity, seem all too long. So heavy is the burden of it that death is a refuge which we all desire, and it is common proof amongst us that God who gave us a taste of this world’s sweetness has been jealous in his giving.” <cite>(7.46)</cite></p>\n</blockquote>\n\nLife is short, but technology saves many today from the troubles Atrabanos enumerated. I, for one, have not yet wished I were dead.\n\nXerxes’ comments to Atrabanos about taking risks:\n\n<blockquote class=\"prose\">\n<p>“There is good sense,” Xerxes answered, “in everything you have said; nevertheless you ought not to be so timid always, or to think of every accident which might possibly overtake us. If upon the proposal of a plan you were always to weight equally all possible chances, you would never do anything. I would much rather take a risk and run into trouble half the time than keep out of any trouble through being afraid of everything.”</p>\n<p>“If you dispute whatever is said to you, but can never prove your objections, you are as likely to be wrong as the other man—indeed there is nothing to choose between you. And as for proof—how can a man ever be certain? Certainty, surely, is beyond human grasp. But however that may be, the usual thing is that profit comes to those who are willing to act, not to the precautious and hesitant. Just think how the power of Persia has grown: if my predecessors had felt as you do—or even if they had not, but had taken the advice of men who did—-you would have never seen our country in its present glory.” <cite>(7.50)</cite></p>\n</blockquote>\n\nThe deposed Spartan king Demaratus’ comments to Xerxes, when asked whether the Greeks would fight such a great army:\n\n<blockquote class=\"prose\">\n<p>“I think highly of all Greeks of the Dorian lands, but what I am about to say will apply not to all Dorians, but to the Spartans only. First then, they will not under any circumstances accept terms from you which would mean slavery for Greece; secondly, they will fight you even if the rest of Greece submits. Moreover, there is no use in asking if their numbers are adequate to enable them to do this; suppose a thousand of them take the field—then that thousand will fight you; and so will any number, greater than this or less.” <cite>(7.102)</cite></p>\n</blockquote>\n\nGeological formations attributed to Poseidon:\n\n<blockquote class=\"prose\">\n<p>The natives of Thessaly have a tradition that the gorge which forms the outlet for the river was made by Poseidon, and the story is a reasonable one; for if one believes that it is Poseidon who shakes the Earth and that chasms caused by earthquake are attributable to him, then the mere sight of this place would be enough to make one say that it is Poseidon’s handiwork. It certainly appears to me that the cleft in the mountains had been caused by an earthquake. <cite>(7.129)</cite></p>\n</blockquote>\n\nThe Spartan’s and Athenian kill the Persian ambassadors:\n\n<blockquote class=\"prose\">\n<p>To Athens and Sparta Xerxes sent no demand for submission because of what happened to the messengers whom Darius had sent on a previous occasion: at Athens they were thrown into the pit like criminals, at Sparta they were pushed into a well and told that if they wanted earth and water for the king, to get them from there. <cite>(7.133)</cite></p>\n</blockquote>\n\nThe Spartans believed they were cursed for doing this, and so sent two ambassadors to Persia to be killed as a reparation.\n\n<blockquote class=\"prose\">\n<p>On their way to Susa they visited Hydarnes, a Persian by birth who was in command of the whole Asiatic seaboard; and by him they were given a hospitable welcome and invited to dinner. During the meal Hydarnes said: “Why is it, Lacedaemonians, that you refuse to be friends with the king? You have only to look at me and the position I enjoy to see that he knows how to reward merit. Now Xerxes believes that you, too, are men of merit; and both of you, if only you would submit, might find yourselves in authority over lands in Greece which he would give you.”</p>\n<p>“Hydarnes,” came the answer, “the advice you give us does not spring from a full knowledge of the situation. You know one half of what is involved, but not the other half. You understand well enough what slavery is, but freedom you have never experienced, so you do not know if it tastes sweet or bitter. If you ever did come to experience it, you would advice us to fight for it not with spears only, but with axes too.”</p>\n<p>After this they continued their journey to Susa, and the first thing that happened when they entered the presence of the king was that the men of the royal bodyguard ordered—and, indeed, attempted to compel—them to bow down to the ground in the act of worship. The two Spartans, however, declared that they would never do such a thing, even though the guards should push their heads down on to the floor. It was not, they said, the custom in Sparta to worship a mere man like themselves, and it was not for that purpose that they had come to Persia. So they persisted in their refusal, adding words to the following effect: “King of the Medes, the Spartans sent us here to suffer punishment in reparation for the murder of the Persian messengers in Sparta”; to which Xerxes with truly noble generosity replied that he would not behave like the Spartans, who by murdering the ambassadors of a foreign power had broken the law which all the world holds sacred. He had no intention of doing the very thing for which he blamed them, or, by taking reprisals, of freeing the Spartans from the burden of their crime. <cite>(7.135–6)</cite></p>\n</blockquote>\n\nHerodotus’ devout comment about human initiative, vs the gods:\n\n<blockquote class=\"prose\">\n<p>It was the Athenians who—after the gods—drove back the Persian king. Not even the terrifying warnings of the oracle at Delphi could persuade them to abandon Greece; they stood firm and had the courage to meet the invader. <cite>(7.139)</cite></p>\n</blockquote>\n\nThe Greeks uniting against a common enemy:\n\n<blockquote class=\"prose\">\n<p>At a conference of the Greek states who were loyal to the general cause guarantees were exchanged, and the decision was reached that the first thing to be done was to patch up their own quarrels and stop any fighting which happened to be going on amongst members of the confederacy. There were a number of such disputes at the time, the most serious being the quarrel between Athens and Aegina. <cite>(7.145)</cite></p>\n</blockquote>\n\nHerodotus’ skepticism about the Magi’s magic:\n\n<blockquote class=\"prose\">\n<p>The storm lasted three days, after which the Magi brought it to an end by sacrificial offerings, and by further offerings to Thetis and the sea-nymphs—or, of course, it may be that the wind just dropped naturally. <cite>(7.192)</cite></p>\n</blockquote>\n\nHerodotus’ comments, after the Greek poli send their troops to Thermopylae:\n\n<blockquote class=\"prose\">\n<p>The other Greeks had induced these two towns to send troops by a message to the effect that they themselves were merely and advance force, and that the main body of the allies was daily expected; the sea, moreover, was strongly held by the fleet of Athens and Aegina and the other naval forces. Thus there was no cause for alarm—for, after all, it was not a god who threatened Greece, but a man, and there neither was nor would ever be a man not born with a good chance of misfortune—and the greater the man, the greater the misfortune. The present enemy was no exception; he too was human, and was sure to be disappointed of his great expectations. <cite>(7.203)</cite></p>\n</blockquote>\n\nLeonidas’ genealogy:\n\n<blockquote class=\"prose\">\n<p>The contingents of the various states were under their own officers, but the most respected was Leonidas the Spartan, who was in command of the whole army. Leonidas traced his descent directly back to Heracles, through Anaxandrides and Leon (his father and grandfather), Eurycratides, Anaxander, Eurycrates, Polydorus, Alcamenes, Telechles, Archelaus, Agesilaus, Doryssus, Leobotas, Echestratus, Agis, Eurysthenes, Aristodemus, Aristomachus, Cleodaeus—and so to Hyllus, who was Heracles’ son. <cite>(7.204)</cite></p>\n</blockquote>\n\nThe last stand of the Spartans:\n\n<blockquote class=\"prose\">\n<p>As the Persian army advanced to the assault, the Greeks under Leonidas, knowing that they were going to their deaths, went out into the wider part of the pass much further than they had done before; in the previous days’ fighting they had been holding the wall and making sorties from behind it into the narrow neck, but now they fought outside the narrows. Many of the barbarians fell; behind them the company commanders plied their whips indiscriminately, driving the men on. Many fell into the sea and were drowned, and still more were trampled to death by one another. No one could count the number of dead. The Greeks, who knew that the enemy were on their way round the mountain track and that death was inevitable, put forth all their strength and fought with fury and desperation. By this time most of their spears were broken, and they were killing Persians with their swords.</p>\n<p>In the course of that fight Leonidas fell, having fought most gallantly, and many distinguished Spartans with him—their names I have learned, as those of men who deserve to be remembered…</p>\n<p>There was a bitter struggle over the body of Leonidas; four times the Greeks drove the enemy off, and at last by their valour rescued it. So it went on, until the troops with Ephialtes were close at hand; and then, when the Greeks knew that they had come, the character of the fighting changed. They withdrew again into the narrow neck of the pass, behind the wall, and took up a position in a single compact body… Here they resisted to the last, with their swords if they had them, and, if not, with their hands and teeth, until the Persians, coming on from the front over the ruins of the wall and closing in from behind, finally overwhelmed them with missile weapons. <cite>(7.223–5)</cite></p>\n</blockquote>\n\n## Quotes from Book VIII\n\nThemistocles’ clever attempts and swaying the Ionians:\n\n<blockquote class=\"prose\">\n<p>Themistocles took the fastest ships and called on the way at all the places where drinking water was to be found, and cut notices on the rocks near by for the Ionians to read—as they did when they moved up on the following day. “Men of Ionian”—his messages ran—”it is wrong that you should make ware upon your fathers and help to bring Greeks into subjection. The best thing you can do is to join our side; if this is impossible, you might at least remain neutral, and ask the Carians to do the same. If you are unable to do either, but are held by a compulsion so strong that it puts desertion out of the question, there is still another course open to you: in the next battle, remember that you and we are of the same blood, that our quarrel with Persian arose originally on your account—and fight badly.”</p>\n<p>In leave this message Themistocles probably had two possibilities in mind: in the first place, it might, if the kings did not get to know of it, induce the Ionians to come over to the Greeks, and, secondly, if it were reported to Xerxes and made the ground of an accusation against the Ionians, they would be distrusted and now allowed, in consequence, to take part in engagements at sea. <cite>(8.22)</cite></p>\n</blockquote>\n\nComments about the Persian’s fighting at Salamis:\n\n<blockquote class=\"prose\">\n<p>The greater part of the Persian fleet suffered severely in the battle, the Athenians and Aeginetans accounting for a great many of their ships. Since the Greek fleet worked together as a whole, while the Persians had lost formation and were no longer fighting on an plan, that was what was bound to happen. None the less they fought well that day–far better than in the actions of off Euboea. Every man of them did his best for fear of Xerxes, feeling that the king’s eye was on him. <cite>(8.86)</cite></p>\n</blockquote>\n\nHerodotus’ description of the Persian courier system:\n\n<blockquote class=\"prose\">\n<p>No mortal thing travels faster than these Persian couriers. The whole idea is a Persian invention, and works like this: riders are stationed along the road, equal in number to the number of days the journey takes—a man and a horse for each day. Nothing stops these couriers from covering their allotted stage in the quickest possible time—neither snow, rain, heat, nor darkness. The first, and the end of his stage, passes the dispatch to the second, the second to the third, and so on along the line, as in the Greek torch-race which is held in honour of Hephaestus. <cite>(8.98)</cite></p>\n</blockquote>\n\nThemistocles’ takes credit for the Athenians not pursuing Xerxes:\n\n<blockquote class=\"prose\">\n<p>At dawn the following day the Greeks, seeing that the Persian army had not moved, thought that the fleet would still be lying at Phalerum; so they prepared to defend themselves in expectation of another attach by sea. But the moment they learned that the fleet was gone, they resolved to give chase, and did actually sail in pursuit as far as Andros, but without getting a sight of any enemy ships. At Andros they brought up and held a conference, at which Themistocles proposed that they should carry on through the islands direct for the Hellespont, and break the bridges. …</p>\n<p>Themistocles, finding the majority against him, suddenly shifted his ground and addressed himself to the Athenians—who of all the confederates were the most vexed at the enemy’s escape, and were anxious to go on to the Hellespont alone, if the others refused to accompany them. “From my own experience,” Themistocles began, “and still more from what others have told me, I know very well that people who are beaten and cornered will often hit out again and make amends for their previous failure to play the man. Now we’ve had the luck to save ourselves and our country by the repulse of this great force, which seemed, like a cloud, to darken the sea. That force is now in flight—let it go,. Indeed it was not we who performed this exploit; it was the gods and the heroes, who were jealous that one man in his godless pride should be king of Asia and of Europe too–a man who does not know the difference between the sacred and profane, who burns and destroys the statues of the gods, and dared to lash the sea with whips and bid it with fetters …”</p>\n<p>Once he had persuaded them to accept his proposal, Themistocles lost no time in getting a message through to Xerxes. The men he chose for this purpose were all people he could trust to keep his instructions secret, even under torture. The party crossed to Attica, and then, while the others waited by the boat, Sicinnus went to find Xerxes, and deliver this message. “I have come,” he said, “on behalf of Themistocles, son of Necles and the confederacy. I am to inform you that Themistocles of Athens, in his desire to server your interests, has stopped the Greeks from pursuing your navy and destroying the bridges on the Hellespont, which is what they wished to do. You may now, therefore, march your army home without danger of interference.” <cite>(8.108–10)</cite></p>\n</blockquote>\n\nXerxes retreat:\n\n<blockquote class=\"prose\">\n<p>Xerxes now left Mardonius in Thessaly and made his way with all speed to the Hellespont. He reached the crossing in forty-five days, but with hardly a fraction of his army intact. During the march the troops lived off the country as best they could, eating grass where they found no grain, and stripping the bark and leaves off trees of all sorts, cultivated or wild, to stay their hunger. They left nothing anywhere, so hard were the put to it for supplies. Plague and dysentery attacked them; many died, and others who fell sick were left behind in the various town along the route. <cite>(8.115)</cite></p>\n</blockquote>\n\n## Quotes from Book IX\n\nThe Athenians demonstrate that their ethical system centered on groups, and not individuals (also, Herodotus’ sexism is subtly portrayed by his surprise that the women took their own initiative):\n\n<blockquote class=\"prose\">\n<p>One of the councilors, a man named Lycidas, expressed the opinion that the best course would be to admin the proposals which Murchides brought, and to submit them for approval to the general assembly of the people. This was his expressed opinion—whether he had been bribed by Mardonius to express it or really thought so. In any case, the Athenians, both those in the council and those outside, were so enraged when they heard it that they surrounded Lycidas and stoned him to death. Murchides they allowed to depart unharmed. With all the uproar in Salamis over Lycidas, the Athenian women soon found out what had happened; whereupon, without a word from the men, they got together, and, each one urging on her neighbor and taking her along with the crowd, flocked to Lycidas’ house and stoned his wife and children. <cite>(9.5)</cite></p>\n</blockquote>\n\nPausanias compares a royal Persian meal with a Spartan meal, after the battle of Plataea:\n\n<blockquote class=\"prose\">\n<p>It is said that Xerxes on his retreat from Greece left his tent with Mardonius. When Pausanias saw it, with its embroidered hangings and gorgeous decorations in silver and gold, he summoned Mardonius’ bakers and cooks and told them to prepare a meal of the same sort as they were accustomed to prepare for their former master. The order was obeyed; and when Pausanias saw gold and silver couches all beautifully draped, and gold and silver tables, and everything prepared for the feast with great magnificence, he could hardly believe his eyes for the good things set before him, and, just for a joke, ordered his own servants to get read an ordinary Spartan dinner. The difference between the two meals was indeed remarkable, and, when both were ready, Pausanias laughed and sent for the Greek commanding officers. When they arrived, he invited them to take a look at the two tables, saying, “Men of Greece, I asked you here in order to show you the folly of the Persians, who, living in this style, came to Greece to rob us of our poverty.” <cite>(9.82)</cite></p>\n</blockquote>\n\nThe fake tombs at the battle of Plataea:\n\n<blockquote class=\"prose\">\n<p>Unlike these tombs, which were real ones containing the bodies of the dead, all the other funeral mounds which are to be seen at Plataea were, so far as my information goes, erected merely for show: they are empty, and were put up to impress posterity by the various states who were ashamed of having taken no part in the battle. <cite>(9.85)</cite></p>\n</blockquote>\n\nHerodotus’ justification for believing gods are involved in human affairs:\n\n<blockquote class=\"prose\">\n<p>Many things make plain to me that the hand of God is active in human affairs—for how else could it be, when the Persian defeat at Mycale was about to take place on the same day as his defeat at Plataea, that a rumor of this kind should reach the Greek army, giving every man greater courage for the coming battle and a fiercer determination to risk his life for his country? <cite>(9.100)</cite></p>\n</blockquote>\n\n*Some quotations are taken from Andrea L. Purvis’s 2007 translation of* The Histories*, published by Anchor Books, others are taken from Aubrey de Sélincourt’s translation.*\n\n" }, { "alpha_fraction": 0.3952702581882477, "alphanum_fraction": 0.5101351141929626, "avg_line_length": 12.454545021057129, "blob_id": "beeb4ddc43b2e4be901612a6fc4867d24e577f6f", "content_id": "3f7df5c580838416cdf3e22b7a517fbba3d44aa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "no_license", "max_line_length": 57, "num_lines": 22, "path": "/scripts/gen_1_11.py", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "stories = [\n 35, # creation 1\n 20, # creation 2\n 25, # sin\n 16,\n 26 - 16,\n 32,\n 22 + 24 + 22 + 17,\n 10,\n 32,\n 9,\n 22,\n]\n\nheight = 550 # px\n\nverses = sum(stories)\n\nstory_heights = [round(s/verses*height) for s in stories]\n\nfor h in story_heights:\n print(h)\n" }, { "alpha_fraction": 0.42506298422813416, "alphanum_fraction": 0.42695215344429016, "avg_line_length": 17.465116500854492, "blob_id": "69405f660a68a771b11c207de8993557d3f0293c", "content_id": "f16f426c92f0e1e8ffd4971b0b8830688e33636b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3178, "license_type": "no_license", "max_line_length": 51, "num_lines": 172, "path": "/scripts/test_process.py", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "from process import translate_markdown\n\nimport pytest\n\n\ndef assert_translate(input, expected_output):\n actual_output = []\n translate_markdown(input, actual_output.append)\n assert actual_output == expected_output\n\n\ndef test_basic_quote():\n assert_translate([\n '> Hello',\n ], [\n '<blockquote>',\n '<p>Hello</p>',\n '</blockquote>',\n ])\n\n\ndef test_two_paragraph_quote():\n assert_translate([\n '> One',\n '> Two',\n ], [\n '<blockquote>',\n '<p>One</p>',\n '<p>Two</p>',\n '</blockquote>',\n ])\n\n\ndef test_two_paragraph_w_newline_quote():\n assert_translate([\n '> One',\n '>',\n '> Two',\n ], [\n '<blockquote>',\n '<p>One</p>',\n '<p>Two</p>',\n '</blockquote>',\n ])\n\n\ndef test_hidden_citation():\n assert_translate([\n '> One',\n '> - Hello',\n ], [\n '<blockquote>',\n '<p>One</p>',\n '<cite>— Hello</cite>',\n '</blockquote>',\n ])\n\n\ndef test_poetry_empty_citation():\n assert_translate([\n '> One',\n '> ~',\n ], [\n '<blockquote class=\"poetry\">',\n '<p>One</p>',\n '</blockquote>',\n ])\n\n\ndef test_prose_empty_citation():\n assert_translate([\n '> One',\n '> =',\n ], [\n '<blockquote class=\"prose\">',\n '<p>One</p>',\n '</blockquote>',\n ])\n\n\ndef test_indents():\n assert_translate([\n '> One',\n '> Two',\n ], [\n '<blockquote>',\n '<p>One</p>',\n '<p class=\"indent\">Two</p>',\n '</blockquote>',\n ])\n\n\ndef test_poetry_blank_lines():\n assert_translate([\n '> One',\n '> Two',\n '>',\n '> Three',\n '> ~',\n ], [\n '<blockquote class=\"poetry\">',\n '<p>One</p>',\n '<p>Two</p>',\n '<br>',\n '<p>Three</p>',\n '</blockquote>',\n ])\n\n\ndef test_italics_in_quote():\n assert_translate([\n '> One *then* two',\n ], [\n '<blockquote>',\n '<p>One <em>then</em> two</p>',\n '</blockquote>',\n ])\n\n\ndef test_italics_in_prose_quote():\n assert_translate([\n '> One *then* two',\n '> =',\n ], [\n '<blockquote class=\"prose\">',\n '<p>One <em>then</em> two</p>',\n '</blockquote>',\n ])\n\n\[email protected]\ndef test_italics_in_quote_w_asterisk():\n assert_translate([\n r'> One *then\\* two*',\n ], [\n '<blockquote>',\n '<p>One <em>then* two</em></p>',\n '</blockquote>',\n ])\n\n\ndef test_inline_citation():\n assert_translate([\n '> Test',\n '> - (p. 2)',\n ], [\n '<blockquote>',\n '<p>Test <cite>(p. 2)</cite></p>',\n '</blockquote>',\n ])\n\n\ndef test_inline_citation_poetry():\n assert_translate([\n '> Test',\n '> ~ (p. 2)',\n ], [\n '<blockquote class=\"poetry\">',\n '<p>Test <cite>(p. 2)</cite></p>',\n '</blockquote>',\n ])\n\n\ndef test_inline_citation_prose():\n assert_translate([\n '> Test',\n '> = (p. 2)',\n ], [\n '<blockquote class=\"prose\">',\n '<p>Test <cite>(p. 2)</cite></p>',\n '</blockquote>',\n ])\n" }, { "alpha_fraction": 0.7502304315567017, "alphanum_fraction": 0.7502304315567017, "avg_line_length": 59.27777862548828, "blob_id": "e248fe2816f5f7b85143b939e6ac04f1e83f6957", "content_id": "67c5d5b5803572a216ffd9382ddb3c406a5af9fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3289, "license_type": "no_license", "max_line_length": 360, "num_lines": 54, "path": "/_posts/2020-06-12-sophocles-ode-to-man.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Sophocles’ Ode to Man\ndescription: >\n Many a wonder lives and moves, but the wonder of all is man …\n---\n\nThis chorus, my favorite in *Antigone*, is sung after the Theban king unjustly threatens a messenger with unwelcome news:\n\n<blockquote class=\"poetry\">\n<p>Many a wonder lives and moves, but the wonder of all is man,</p>\n<p>That courses over the gray ocean, carried of southern gale,</p>\n<p>Faring amidst high-swelling seas that rudely surge around,</p>\n<p>And Earth, supreme of mighty Gods, eldest, imperishable,</p>\n<p>Eternal, he with patient furrow wears and wears away</p>\n<p>As year by year the plough-shares turn and turn—</p>\n<p>Subduing her unwearied strength with children of the steed.</p>\n<br>\n<p>And wound in woven coils of nets he seizes for his prey</p>\n<p>The airy tribe of birds and wilding armies of the chase,</p>\n<p>And sea-born millions of the deep—man is so crafty-wise.</p>\n<p>And now with engine of his wit he tames to his will</p>\n<p>The mountain-ranging beast whose lair is in the country wild;</p>\n<p>And now his yoke has passed upon the mane</p>\n<p>Of horse with proudly crested neck and tireless mountain bull.</p>\n<br>\n<p>Wise utterance and wind-swift thought, and city-molding mind,</p>\n<p>And shelter from the clear-eyed power of biting frost,</p>\n<p>He has taught him, and to shun the sharp, roof-penetrating rain—</p>\n<p>Full of resource, without device he meets no coming time;</p>\n<p>From Death alone he shall not find reprieve;</p>\n<p>No league may gain him that relief; but even for fell disease,</p>\n<p>That long hath baffled wisest leech, he hath contrived a cure.</p>\n<br>\n<p>Inventive beyond wildest hope, endowed with boundless skill,</p>\n<p>One while he moves toward evil, and one while toward good,</p>\n<p>According as he loves his land and fears the gods above.</p>\n<p>Weaving the laws into his life and steadfast oath of Heaven,</p>\n<p>High in the State he moves but outcast he,</p>\n<p>Who hugs dishonor to his heart and follows paths of crime</p>\n<p>Ne’er may he come beneath my roof, nor think like thoughts with me.</p>\n</blockquote>\n\nWonderful man! The thinker and innovator, solving problems for good and for evil. I share Sophocles’ optimism and his appreciation of technological innovation.\n\nHis marvels were the triremes, the ploughs, and the laws and walls of the city. Don’t fear the wild animals, the rain, and the winter! Now we worry that our deep nets will extinguish the “sea-born millions of the deep,” and we have moved on to marvel at our machines: computers, spaceships, and automobiles. As before, we know technology can be used for evil.\n\nWhile we now know Earth was not the “eldest of the gods,” humanity can still be called the “wonder of all”—as best we know, we are the most complex and interesting bundles of atoms in the universe. Likewise, we know that we will die; if not soon, then when the universe does.\n\nAthens had defeated the Persian empire, and their empire was steadily growing, when Antigone was written. How much was his optimism tied to the success of his state?\n\nWhy did Sophocles include this Chorus, and why is it located where it is in the play? Is it ironic?\n\n*The translation is modernized from “The Seven Plays in English Verse” by Lewis Campbell.*\n" }, { "alpha_fraction": 0.7890751361846924, "alphanum_fraction": 0.7899033427238464, "avg_line_length": 122.08252716064453, "blob_id": "c52c8fb8388b53d04e87699944a8c0482a04b228", "content_id": "311f8acc51d2bde1a87de1926fde79aa89b71655", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25355, "license_type": "no_license", "max_line_length": 1605, "num_lines": 206, "path": "/documents/seneca.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Seneca\ndescription: >\n Notes on Seneca's Philosphy and Plays\ntype: note\n---\n\nLucius Annaeus Seneca, known as Seneca or \"Seneca the Younger,\" was born around 4 BCE in Corduba and raised in Rome, where he was trained in rhetoric and philosophy. In 41 CE, Seneca was exiled to the island of Corsica by the emperor Claudius, but was allowed to return in 49 to become a tutor to Nero. When Nero became emperor in 54, Seneca became his adviser. Seneca's influence over Nero declined with time, and in 65 Seneca was forced to take his own life for alleged complicity in a conspiracy to assassinate Nero, in which he was likely to have been innocent.\n\nSeneca wrote philosophical letters and tragedies.\n\n## On The Shortness of Life\n\nHere is how I would summarize this letter:\n\nMany feel life is short, but it is long enough if---instead of wasting it laboring, drinking, lusting, sporting, studying trivia, accruing wealth, or chasing fame---you study philosophy and contemplate the past.\n\nHere is the central idea, in Seneca's words:\n\n> It is not that we have a short time to live, but that we waste a lot of it. Life is long enough, and a sufficiently generous amount has been given to us for the highest achievements if it were all well invested. But when it is wasted in heedless luxury and spent on no good activity, we are forced at last by death's final constraint to realize that it has passed away before we knew it was passing.\n\nSeneca believes many activities are wasteful, as demonstrated by some of my favorite quotes:\n\n> How many find riches a burden! How many burst a blood vessel by their eloquence and their daily striving to show off their talents! How many are pale from constant pleasures! How many are left no freedom by the crowd of clients surrounding them!\n\n> People are frugal in guarding their personal property; but as soon as it comes to squandering time they are most wasteful of the one thing in which it is right to be stingy.\n\n> You will hear many people saying \"When I am fifty I shall retire into leisure; when I am sixty I shall give up public duties.\" And what guarantee do you have of a longer life? How stupid to forget our mortality, and put off sensible plans to our fiftieth and sixtieth years, aiming to begin life from a point at which few have arrived!\n\n> Assuredly your lives, even if they last more than a thousand years, will shrink into the tiniest span: those vices will swallow up any space of time. The actual time you have---which reason can prolong though it naturally passes quickly---inevitably escapes you rapidly: for you do not craps it or hold it back of try to delay that swiftest of all things, but you let it slip away as though it were something superfluous and replaceable.\n\n> It is the mind which is tranquil and free from care which can roam through all the stages of its life: the minds of the preoccupied, as if harnessed in a yoke, cannot turn round and look behind them. So their lives vanish into an abyss; and just as it is no use pouring any amount of liquid into a container without a bottom to catch and hold it, so it does not matter how much time we are given if there is nowhere for it to settle; it escapes through the cracks and holes of the mind.\n\n> They are not at leisure whose pleasures involve a serious commitment. For example, nobody will dispute that those people are busy about nothing who spend their time on useless literary studies: even among the Romans there is now a large company of these. It used to be a Greek failing to want to know how many oarsmen Ulysses had, whether the _Iliad_ or the _Odyssey_ was written first, and whether too they were by the same author, and other questions of this kind, which if you keep them to yourself in no way enhance your private knowledge, and if you publish them make you appear more a bore than a scholar. But now the Romans too have been afflicted by the pointless enthusiasm for useless knowledge.\n\nI doubt that Seneca thinks reading literature is useless, or even that analyzing it has no merit. I spend a lot of time analyzing literature. Usually I write detailed outlines and transcribe my favourite quotes. Seneca's comments have made me ask myself: Why bother with a detailed outlines of, for example, Ovid's _Metamorphoses_? Perhaps this is useless, but I enjoy it, and familiarity with the classics lets one follow other authors' (including philosophers) and painters' references. Selecting and transcribing quotes and writing outlines helps me remember and appreciate what I read.\n\nWhy read fiction? Non-fiction, like the Philosophy Seneca urges us to read, condenses experience into lessons. Fiction provides the raw experiences, and the reader is left to learn what they will from them. The _Iliad_ teaches you about war and how the ancient Greeks viewed it. Seneca may regard the physical world as brute and dirty, but as a materialist I think the most abstract Philosophy is built up from experiences of the real world, and it may be foolish to skip to the reduction others have made vs experiencing it yourself. For this reason, I think fiction can be worthwhile too.\n\n> Some men, after they having crawled thought a thousand indignities to the supreme dignity, have been assailed by the gloomy thought that all their labors were for the sake of an epitaph.\n\nI can imagine myself falling into this trap, pursuing fame and honor, only to realize you have spent your whole life. I have noticed that the opinion of others motivates me more than it should.\n\n> Even their pleasures are uneasy and made anxious by various fears, and at the very height of their rejoicing, the worrying thought steals over them 'how long will this last?' This feeling has caused kings to bewail their power, and they were not so much delighted by the greatness of their fortune as terrified by the fear of its inevitable end.\n\nSo how should we act? We should live as if tomorrow is our last day:\n\n> Everyone hustles his life along, and is troubled by a longing for the future and a weariness of the present. But the man who spends all his time on his own needs, who organizes every day as though it were his last, neither longs for nor fears the next day. For what new pleasures can an hour now bring him? He has tried everything, and enjoyed everything to repletion. For the rest, Fortune can dispose as she likes: his life is now secure. Nothing can be taken from this life, and you can only add to it as if giving to a man who is already full and satisfied food which he does not want but can hold. So you must not think a man has lived long because he has white hair and wrinkles. He has only existed long.\n\nWe should spend more time recalling the past:\n\n> Life is divided into three periods, past, present, and future. Of these, the present is short, the future is doubtful, the past is certain. For this last is the one over which Fortune has lost her power, which cannot be brought back to anyone's control. But this is what preoccupied people lose: for they have not time to look back at their past, and even if they did, it is not pleasant to recall activities they are ashamed of. So they are unwilling to cast their minds back to to times ill spent, which they dare not relive if their vices in recollection become obvious.\n\nThe past is durable, so we can enjoy it. Recollection helps us identify waste.\n\nWe should also study philosophy:\n\n> Of all people only those are at leisure who make time for philosophy, only those are really alive. For they not only keep a good watch over their own lifetimes, but they annex every age to theirs. All the years that have passed before them are added to their own. Unless we are very ungrateful, all those distinguished founders of holy creeds were born for us and prepared for us a way of life. By the toil of others we are led into the presence of things which have been brought from darkness into light. We are excluded from no age, but we have access to them all; and if we are prepared to loftiness of mind to pass beyond the narrow confines of human weakness, there is a long period of time through which we can roam.\n\nReading philosophy allows us to extend our years with the wisdom of great writers, who, unlike living friends, won't make demands of our precious time.\n\nSeneca believed philosophy could teach us:\n\n> the substance of god, and his will, his mode of life, his shape; what fate awaits your soul; where nature lays us to rest when released from our bodies; what is the force which supports all the heaviest elements of this world at the center, suspends the light elements above, carries fire to the highest part, and sets the stars in motion with their proper changes---and learn other things in succession which are full of tremendous marvels\n\nI agree with most of Seneca's thoughts and advice in this letter. Most people do complain about the shortness of life while also spending their time poorly. I do. But Seneca's metaphysical beliefs---the existence of the soul and driving purpose of the universe, in particular---may make him dismiss the good things in life too quickly. There may be an afterlife, but it seems unlikely, and so I am left to regard our earthly lives as more valuable than he. Based on the way Seneca acted, he may have had his doubts about the unseen afterlife too.\n\nDue to _On the Shortness of Life_, I will read more philosophy and less literature, contemplate my past to identify pointless activities, spend less time pursuing these activities.\n\n*Quotations are taken from C.D.N Costa's 1997 translation.*\n\n## Consolation to Helvia\n\nHere is how I would summarize this letter:\n\nYou are grieving over my son's death, but recall the challenges you have overcome. I, though exiled, am happy. You should be happy too; liberal studies will make you happy forever, but in the interim your family can.\n\nHere is an outline of the letter:\n\n- Why I hadn't written earlier\n- My approach: Enumerate past misfortune to toughen you\n- List of Helvia's past misfortunes\n- Don't worry about me: Exile hasn't been too bad; find happiness within\n - It is part of our divine nature to move\n - Historically, humans are always migrating\n - We take universal nature and our individual virtue with us\n - Barren Corsica focuses one on the spiritual over material\n - Counter: masking poverty with philosophy; Rebuttal: poor are happier\n - If one trouble can be born, many can\n- Don't worry about lost protection\n- Don't miss me\n- Don't make excuses because you are a woman\n- Study philosophy, which is better than temporary diversions\n- Consolations, needed until you master philosophy\n - Your other two sons\n - Grandchildren\n - Your father\n - Your sister; respectable in Egypt; save husband in shipwreck\n- Conclusion: I'm happy studying earth and heaven; don't miss me\n\nHere are several interesting quotes:\n\n> Everlasting misfortune does have one blessing, that it ends up by toughening those whom it constantly afflicts.\n\n> We are born under circumstances that would be favorable if we did not abandon them. It was nature's intention that there should be no need of great equipment for a good life: every individual can make himself happy. External goods are of trivial importance and without much influence in either direction: prosperity does not elevate the sage and adversity does not depress him. For he has always made the effort to rely as much as possible on himself and to derive all delight from himself.\n\n> No man has been shattered by the blows of Fortune unless he was first deceived by her favors. Those who loved her gifts as if they were their own for ever, who wanted to be admired on account of them, are laid low and grieve when the false and transient pleasures desert their vain and childish minds, ignorant of every stable pleasure. But the man who is not puffed up in good times does not collapse either when they change.\n\nIn this letter, Seneca makes a couple reasonable claims but provides, what we now know to be incorrect, natural explanations for them.\n\nFor example, when discussing the pains of being deprived of Rome, he makes a statement about wanderlust:\n\n> I've come across people who say that there is a sort of inborn restlessness in the human spirit and an urge to change one's abode; for man is endowed with a mind which is changeable and unsettled: nowhere at rest, it darts about and directs its thoughts to all places known and unknown, a wanderer which cannot endure repose and delights chiefly in novelty.\n\nObservations of myself and my friends lead me to believe this is true, yet Seneca's explanation is certainly not true:\n\n> This will not surprise you if you consider its original source. It was not made from heavy, earthly material, but came down from that heavenly spirit: but heavenly things are by nature always in motion, fleeing and driven on extremely fast. Look at the planets which light up the world: not one is at rest ... How silly then to imagine that the human mind, which is formed of the same elements as divine beings, objects to movement and change of abode, while the divine nature finds delight and even self-preservation in continual and very rapid change.\n\n> For how little have we lost, when the two finest things of all will accompany us wherever we go, universal nature and our individual virtue. Believe me, this was the intention of whoever formed the universe, whether all-powerful god, or incorporeal reason creating mighty works, or divine spirit penetrating all things from greatest to smallest with even pressure, or fate and the unchanging sequence of causation---this, I say, was the intention, that only the most worthless of our possessions would come into the power of another. Whatever is best for a human being lies outside human control: it can be neither given nor taken away. The world you see, nature's greatest and most glorious creation, and the human mind which gazes and wonders at it, and is the most splendid part of it, these are our own everlasting possessions and will remain with us as long as we ourselves remain. So, eager and upright, let us hasten with bold steps wherever circumstances take us, and let us journey through any countries whatever: there can be no place of exile within the world since nothing within the world is alien to men.\n\nSeneca's suggests his mother read philosophy:\n\n> Return now to these studies and they will keep you safe. They will comfort you, they will delight you; and if they genuinely penetrate your mind, never again will grief enter there, or anxiety, or the distress caused by futile and pointless suffering. Your heart will have room for none of these, for to all other failings it has long been closed. Those studies are your most dependable protection, and they alone can snatch you from Fortune's grip.\n\nOn the poor:\n\n> For how little is needed to support a man. And who can lack this if they have any virtue at all? As far as I am concerned, I have not lost wealth but distractions.\n\nRighteousness is tied to the size of the sacrifice:\n\n> All the poets have given renown to the woman who offered to die in place of her husband. But this is nobler, to risk one's life to bury one's husband for that love is greater which wins less through equal danger.\n\n*Quotations are taken from C.D.N Costa's 1997 translation.*\n\n## On Tranquillity of Mind\n\nSerenus asks Seneca for help with problems of the mind. He opens with:\n\n> When I look at myself, Seneca, some of my vices appeared clearly on the surface, so that I could lay my hands on them; some were more hidden away in the depths; some were not there all the time but return at intervals.\n\nWhat apparent, hidden, and intermittent vices do you have?\n\nSerenus next provides three examples where his mind wavers between good and poor states. I relate to all three. The first is simplicity vs wealth. It is difficult, when in the presence of others, to not waver in one's desire for simple material things. It is easy to let go of the sensory desires, but more difficult to relax the desire for social validation. One asks, \"do my dinner guests think I am poor, unmotivated, or inept?\"\n\n> After being long given up to frugality I have found myself surrounded by the lavish splendor of luxury echoing all about me. My vision wavers somewhat, for I can raise my mind to face it more easily than my eyes. And so I come back not a worse but a sadder man; I don't move with my head so high among my trivial possessions; and a secret gnawing doubt undermines me whether that life is superior.\n\nI also relate to the second source of Serenus' doubts---helping others. Serenus waivers between a monastic inward focus and an external interest in humankind. The ripples in his resolve for the public good originate in the time-consuming and mundane nature of the endeavor; most of my attempts to volunteer are abandoned for the same reasons. One feels that the time is poorly spent.:\n\n> I decide to achieve public office---not, of course, because of the purple robe and the lictors' rods, but so that I can be more ready with help for my friends and relations, for all my fellow-citizens, and then for all mankind. But when something has assailed my mind, which is not used to being battered; when something has happened which either is unworthy of me or cannot easily be dealt with; when unimportant things become time-consuming; I take refuge in leisure and make my way more quickly home. I decide to restrict my life within its walls, saying, \"Let no one rob me of a single day who is not going to make me an adequate return for such a loss. Let my mind be fixed on itself, cultivate itself, have no external interest---nothing that seeks the approval of another; let it cherish the tranquility that has no part in public or private concerns.\" But when my mind is excited by reading a convincing account of something and spurred on by noble examples, I long to rush into the forum, to speak on behalf of one man and offer help to another, which will at least be an attempt to assist even if it does not succeed, or to curb the pride of someone else grown arrogant by success.\n\nLike Serenus, emotive movies and stories push back my desire to contribute to others.\n\nFinally, I strongly feel the impulse to write for posterity. Fame is a powerful force.\n\n> \"Where is the need,\" I ask, \"to compose something to last for ages? Why not stop trying to prevent posterity being silent about you? You were born to die, and a silent funeral is less bothersome. So if you must fill your time, write something in a simple style for your own use and not for publication: less toil is needed if you study only for the day.\"\n\nSeneca, as seems typical, provides a general response:\n\n> We are, therefore, seeking how the mind can follow a smooth and steady course, well disposed to itself, happily regarding its own condition and with no interruption to this pleasure, but remaining in a state of peace with no ups and downs: that will be tranquility. Let us consider in general how this can be achieved: you will then extract what you like from the communal remedy.\n\nI find it somewhat annoying that he does not recognize the particulars of Serenus' questions, but instead provides general advice and tells him to \"extract what you like\" from it.\n\n> You must consider whether your nature is more suited to practical activity or to quiet study and reflection, and incline in the direction your natural faculty and disposition take you.\n\n> Let us learn to increase our self-restraint, to curb luxury, to moderate ambition, to soften anger, to regard poverty without prejudice, to practise frugality, even if many are ashamed of it, to apply to nature's needs the remedies that are cheaply available, to curb as if in fetters unbridled hopes and a mind obsessed with the future., and to aim to acquire our riches from ourselves rather than from Fortune. It is not possible that all the manifold and unfair disasters of life can be so repelled so that storm winds will not still assail those who spread their sails ambitiously.\n\n> He who fears death will never do anything worthy of a living man.\n\n> Even in our studies, where expenditure is most worth while, its justification depends on its moderation. What is the point of having countless books and libraries whose titles the owner could scarcely read through in his whole lifetime? The mass of books burdens the student without instructing him, and it is far better to devote yourself to a few authors than to get lost among many.\n\n> In any situation in life you will find delights and relaxations and pleasures if you are prepared to make light of your troubles and not let them distress you.\n\nSeneca's comments sound religious:\n\n> So what you need is not those more radical remedies which we have now finished with---blocking yourself here, being angry with yourself there, threatening yourself sternly somewhere else---but the final treatment, confidence in yourself and the belief that you are on the right path, and not lead astray by the many tracks which cross yours of people who are hopelessly lost, though some are wandering not far from the truth path. But what you are longing for is great and supreme and nearly divine---not to be shaken.\n\nOn picking friends:\n\n> Still, you must especially avoid those who are gloomy and always lamenting, and who grasp at every pretext for complaint. Though a man's loyalty and kindness may not be in doubt, a companion who is agitated and groaning about everything is an enemy to peace of mind.\n\nOn the certainty of troubles:\n\n> But he who knows that this was the condition laid down for him at the moment of his conception will live on those terms, and at the same time he will guarantee with a similar strength of mind that no events take him by surprise. For by foreseeing anything that can happen as though it will happen he will soften the onslaught of all his troubles, which present no surprises to those who are ready and waiting for them, but fall heavily on those who are careless in the expectation that all will be well. There is disease, imprisonment, disaster, fire: none of these is unexpected---I did know in what riotous company Nature had enclosed me.\n\nOn resting the mind:\n\n> The mind should not be kept continuously at the same pitch of concentration, but given amusing diversions. Socrates did not blush to play with small children; Cato soothed his mind with wine when it was tired from the cares of state ... Our minds must relax: they will rise better and keener after a rest.\n\nOn pulling inward:\n\n> The mind must be recalled from external objects into itself: it must trust in itself, rejoice in itself, admire its own things; it must withdraw as much as possible from the affairs of others and devote its attention to itself; it must not feel losses and should take a kindly view even of misfortunes.\n\nOn occasional intoxication:\n\n> Occasionally we should even come to the point of intoxication, sinking into drink but not being totally flooded by it; for it does wash away cares, and stirs the mind to its depths, and heals sorrow just as it heals certain diseases. Liber was not named because he loosens the tongue, but because he liberates the mind from its slavery to cares, emancipates it, invigorates it, and emboldens it for all its undertakings. But there is a healthy moderation in wine, as in liberty.\n\nOn living a fake life:\n\n> There is also another not inconsiderable source of anxieties, if you are too concerned to assume a pose and do not reveal yourself openly to anyone, like many people whose lives are false and aimed only at outward show. For it is agonizing always to be watching yourself in fear of being caught when your usual mask has slipped.\n\nOn despairing of immorality:\n\n> But there is no point in banishing the causes of private sorrow, for sometimes we are gripped by a hatred of the human race. When you consider how rare is simplicity and how unknown is innocence, how you scarcely ever find loyalty except when it is expedient, what a host of successful crimes you come across, and all the things equally hateful that men gain and lose through lust, and how ambition is now so far from setting limits to itself that it acquires a lustre from viciousness---all this drives the mind into a darkness whose shadows overwhelm it, as though those virtues were overturned which is not possible for and not useful to possess. We must therefore school ourselves to regard all commonly held vices as not hateful by ridiculous, and we should imitate Democritus rather than Heraclitus. For whenever these went out in public, the latter used to weep and the former to laugh; the latter thought all our activities sorrows, the former, follies. So we should make light of all things and endure them with tolerance: it is more civilized to make fun of life than to bewail it. Bear in mind too that he deserves better of the human race as well who laughs at it than he who grieves over it; since the one allows it a fair prospect of hope, while the other stupidly laments over things he cannot hope will be put right. And, all things considered, it is the mark of a greater mind not to restrain laughter than not to restrain tears, since laughter expresses the gentlest of our feelings, and reckons that nothing is great or serious or even wretched in all the trappings of our existence.\n\n*Quotations are taken from C.D.N Costa's 1997 translation.*\n" }, { "alpha_fraction": 0.6545354127883911, "alphanum_fraction": 0.6981921792030334, "avg_line_length": 43.91843795776367, "blob_id": "01da142e4c6f4a5e780d24bb2312ed5c7113072c", "content_id": "a8a9dd98573a47cf82f05916e8b6d12a40289323", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12672, "license_type": "no_license", "max_line_length": 397, "num_lines": 282, "path": "/documents/the-pentateuch.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: The Pentateuch\ndescription: >\n Notes on the Pentateuch\ntype: note\n---\n\n<style>\nmain > ol{list-style-type:upper-roman}\nul:first-child{padding-left:1.4rem}\nmain > ul:first-child li{font-weight:normal}\nmain > ul:first-child > li{font-weight:bold}\n.js main > ul:first-child li{cursor:pointer}\n.js main > ul:first-child li li li{cursor:default}\n.js .hidden-children > ul:first-child{display:none}\n.hidden-no-js{display:none}\n.js .hidden-no-js{display:block}\n</style>\n\n## My Beliefs\n\nThe Pentateuch is the first five books of all bibles (Jewish, Catholic, Eastern Orthodox, Oriental Orthodox, and Protestant). Here are some of my beliefs about the Pentateuch, derived from study of the Pentateuch, historical sources, and commentaries:\n\n1. The Pentateuch is a beautiful and compelling story of the creation of the world, the patriarchs, and the Israelite's exodus from Egypt and journey through the wilderness.\n2. Some of the stories and laws were adapted from older polytheistic Mesopotamian stories and laws to emphasize the Israelite's all-powerful and moral God and his love of humanity.\n3. The Pentateuch, while largely Monotheistic, contains remnants from Israel's polytheistic past when Yahweh was one god among many.\n4. There is some historical truth in the Pentateuch, beginning with the patriarchs, but that many details are symbolic or exaggerated.\n5. The Pentateuch was combined from multiple sources a long time after when the events were said to have occurred. Although it largely tells a cohesive story, inconsistencies in the individual sources are evident and were likely intentionally included.\n6. The laws in the Pentateuch were progressive compared to their neighbors, that modern critiques of the laws often misunderstand their historical context, but that the laws treat women as inferior to men.\n7. The authors of the Pentateuch had an ancient Mesopotamian (and incorrect) understanding of the physical world.\n\n## Outline\n\n<p class=\"hidden-no-js hidden-print\">\n <span class=\"hidden-sm\">Set outline depth: &nbsp;</span>\n <a href=\"#\" onclick=\"setDepth(2,event)\">Major Sections</a> ·\n <a href=\"#\" onclick=\"setDepth(3,event)\">Chapters</a>\n</p>\n\n- Genesis\n - Primeval history (1--11.26)\n - Creation in seven days (1--2.4a)\n - Creation in a garden (2.4b--2.25)\n - Fall into sin (3)\n - Cain and Abel; Cain genealogy (4)\n - Seth Genealogy (5)\n - Divine-human reproduction (6.1--6.4)\n - The flood; covenant; curse of Ham (6.5--9)\n - Table of nations (10)\n - Tower of Babel (11.1--11.9)\n - Shem genealogy (11.10--11.26)\n - Abraham (11.27--25.18)\n - First promise; journey; sister lie Pharaoh (11.27--12)\n - Lot and Abram split (13)\n - Militant Abram saves Lot (14)\n - Second promise (15)\n - Hagar and Ishmael (16)\n - Circumcision covenant (17)\n - Annunciation of Isaac (18.1--18.15)\n - Sodom and Gomorrah (18.16--19.29)\n - Lot impregnates his daughters (19.30--19.38)\n - Sister lie Abimelech (20)\n - Birth of Isaac; Ishmael dismissed; Abimelech dispute (21)\n - The testing of Abraham (22)\n - Death and burial of Sarah (23)\n - Finding a wife for Isaac (24)\n - Death of Abraham; genealogy (25.1--25.18)\n - Jacob (25.19--36)\n - Birth and birthright (25.19--25.34)\n - Promise; sister lie Abimelech; abundance; Esau's wives (26)\n - Jacob steals the blessing (27)\n - Jacob's ladder (28)\n - Jacob marries Leah and Rachel (29)\n - Jacob's children; sheep story (30)\n - Jacob leaves Laban (31)\n - Preparation for Esau; wrestles with God; reunites (32--33)\n - Rape of Dinah and slaughter (34)\n - Promise and renaming; Reuben lies with Bilah (35)\n - Descendants of Esau (36)\n - Joseph (37--50)\n - Joseph sold into slavery (37)\n - Judah and Tamar (38)\n - Joseph at Potiphar's house (39)\n - The cupbearer and baker (40)\n - Joseph interprets Pharaoh's dreams; promoted (41)\n - First reunion (42)\n - Second reunion (43)\n - Silver goblet incident (44)\n - Joseph reveals himself (45)\n - Jacob comes to Egypt (46)\n - Joseph saves and enslaves Egypt (47)\n - Jacob adopts Joseph's sons (48)\n - Jacob's blessing (49)\n - Nervous brothers; Joseph's death (50)\n- Exodus\n - Out of Egypt (1--18)\n - Pharaoh oppresses the Israelites (1)\n - Moses born, murders, flees, marries (2)\n - Moses called; objections; God nearly kills Moses (3--4)\n - First encounter with Pharaoh (5)\n - Promise and mission reaffirmed; genealogy (6)\n - First nine plagues (7--10)\n - The tenth plague and festivals (11--13)\n - Crossing the Sea of Reeds (14)\n - The Song of the Sea; Marah (15.1--15.21)\n - Murmuring; Manah (15.21--17.7)\n - Attack of the Amalekites (17.8--17.16)\n - Jethro visit (18)\n - Sinai and the covenant (19--25)\n - Theophany (19)\n - Decalogue (20.1--20.14)\n - People's response to theophany (20.15--20.18)\n - The Covenant Collection (20.19--23)\n - The covenant ceremony (24)\n - Sanctuary and new covenant (25--40)\n - Instructions for the tabernacle (25--31)\n - Golden calf; God's displeasure; Moses pleads (32--33)\n - Restoration of the covenant (34)\n - Creation of the tabernacle (35--40)\n- Leviticus\n - Sacrifice (1--7)\n - Burnt offerings (1)\n - Cereal offerings (2)\n - Sacrifice of well-being (3)\n - Purification offering (4--5.13)\n - Reparation offering (5.14--6.7)\n - Ritual institutions (6.8--7)\n - Dedication of the tabernacle (8--10)\n - Consecration of Aaron (8)\n - Day of revelation; Nadab and Abihu die (9--10)\n - Ritual purity (11--16)\n - Dietary laws (11)\n - Purification and childbirth (12)\n - Purification and skin disease (13--14)\n - Purification and bodily discharge (15)\n - Annual purging of the temple (16)\n - The Holiness Collection (17--26)\n - Slaughter and blood (17)\n - Abominations of the Canaanites (18)\n - Holiness of individuals (19)\n - Molech worship and sexual crimes (20)\n - Worship and holiness (21--22)\n - Holy times (23)\n - Oil and loaves; blaspheming (24)\n - Sabbatical and jubilee (25)\n - Blessing and curse (26)\n - Addendum (27)\n- Numbers\n - The camp and tabernacle (1--9)\n - Census of first generation (1)\n - Arrangement of camp (2)\n - Levite duties and census (3--4)\n - Purity; jealous husband (5)\n - Nazarites; priestly blessing (6)\n - Tabernacle offerings of dedication (7)\n - Dedication of the Levites (8)\n - The second passover; cloud and wilderness march (9)\n - Wilderness journey (10--21)\n - Trumpets (10.1--10.10)\n - Departure from Sinai (10.11--10.36)\n - Murmuring; quails (11)\n - Aaron and Miriam (12)\n - Spies in the promised land (13 -14)\n - Miscellaneous laws (15)\n - Korah's revolt (16--17)\n - Compensation for Levites (18)\n - Red cow (19)\n - Moses doubts; Edomites prevent crossing; Aaron dies (20)\n - Defeat King Arad; bronze serpent; journey north (21)\n - Threats on the plains of Moab (22--25)\n - Balak and Balaam (22--24)\n - Plague (25)\n - Preparations for the promised land (26--36)\n - Second census (26)\n - Zelophad daughters; Moses's death predicted; Joshua chosen (27)\n - Calendar of sacrifices (28--29)\n - Women and vows (30)\n - Vengeance against Midianites (31)\n - Settling the Transjordan (32)\n - Catalog of wilderness journey (33)\n - Division of the land (34)\n - Cities of refuge; homicide laws (35)\n - Zelophad daughters revision (36)\n- Deuteronomy\n - First discourse (1--4)\n - Historical recap (1--3)\n - Admonition to follow the law (4)\n - Second discourse: preamble (5--11)\n - The Decalogue (5)\n - Sermon on the first commandment (6)\n - The war of conquest (7)\n - Temptation to pride and self-sufficiency (8)\n - Why the Israelites are given the land (9)\n - Obedience as a condition for the land (10--11)\n - Second discourse: laws (12--25)\n - Centralization of worship (12)\n - Unconditional loyalty (13)\n - Obligations of holiness (14)\n - Remission of debts and manumission of slaves (15.1--15.18)\n - Sacrifice of first born (15.19--15.23)\n - The festival calendar (16.1--16.17)\n - Laws of public officials (16.18--18)\n - Cities of refuge; integrity of judicial system (19)\n - Rules for holy war (20)\n - Miscellaneous civil and family laws (21--25)\n - Second discourse: conclusion (26--28)\n - Conclusion (26)\n - Ceremonies at Shechem upon entry (27)\n - Blessing and curse (28)\n - Third discourse (29--30)\n - Didactic historical review (29)\n - Reassurance of restoration (30)\n - Death of Moses (31--34)\n - Moses's arrangements for death (31)\n - The Song of Moses (32)\n - The blessing of Moses (33)\n - The death of Moses (34)\n\nNote: occasionally, when a section divide ends near a chapter division, I round the section division to the nearest chapter outline. E.g., the \"Song of Moses\" section begins with the last verse of Deuteronomy 31, but the outline section starts with Deuteronomy 32.\n\n## Mosaic Authorship\n\nThere are a number of verses that are difficult to explain if it is believed that Moses wrote the entire Pentateuch. The Pentateuch does not claim that Moses wrote it, outside of some laws in Exodus and Deuteronomy.\n\nHere is a list of some anachronistic verses which are difficult to explain if Moses authored the Pentateuch. Note that traditionalists have devised explanations for all of these anachronisms, but I find that most of the explanations stretch plausibility, especially when all of these verses are considered collectively.\n\n> Abram passed through the land to the place of Shechem, to the oak of Moreh. At that time, *Canaanites were in the land.*\n> = Genesis 12.6\n\nThe Canaanites were in the control of the land for Moses's entire lifetime. Thus, the clarification \"at that time, Canaanites were in the land\" implies that the Canaanites were no-longer in the land when the author was writing, and that they were clarifying this for their audience.\n\n> There was strife between the herdsmen of Abram’s livestock and the herdsmen of Lot’s livestock. *The Canaanites and the Perizzites lived in the land at that time.*\n> = Genesis 13.7\n\nSimilar logic applies to this verse in chapter 13.\n\n> When Abram heard that his relative was taken captive, he led out his three hundred eighteen trained men, born in his house, and pursued *as far as Dan*.\n> = Genesis 14.14\n\nThe town of Dan was named after the conquest, according to Joshua and Judges:\n\n> The border of the children of Dan went out beyond them; for the children of Dan went up and fought against Leshem, and took it, and struck it with the edge of the sword, and possessed it, and lived therein, *and called Leshem, Dan, after the name of Dan their forefather*.\n> = Joshua 19.47\n\n> They called the name of the city Dan, after the name of Dan their father, who was born to Israel; however *the name of the city used to be Laish*.\n> = Judges 18.29\n\nNote that Joshua and Judges disagree regarding the name of the city prior to being renamed.\n\nSome have suggested that the Dan referenced in Genesis is a different place. While possible, this seems unlikely because the phrase \"from Dan to Beer-sheba\" is used in the historical books to indicate the full extent of Israel. Thus, the use of Dan in Genesis 14 is consistent with this conception of Dan as the northernmost point of the nation.\n\n> These are the words which Moses spoke to all Israel *beyond the Jordan* in the wilderness\n> = Deuteronomy 1.1\n\nThe phrase \"beyond the Jordan\" implies that the author is on the Western side. Moses did not cross the Jordan, thus it seems that author can not be Moses.\n\n> (The Emim lived there before, a great and numerous people, and tall as the Anakim. These also are considered to be Rephaim, as the Anakim; but the Moabites call them Emim. The Horites also lived in Seir in the past, but the children of Esau succeeded them. They destroyed them from before them, and lived in their place, *as Israel did to the land of his possession, which Yahweh gave to them*.)\n> = Deuteronomy 12.10 - 12\n\nThe phrase \"as Israel did to the land\" implies that the conquest has already taken place.\n\n<script>\ndocument.documentElement.classList.add('js')\nul=document.querySelectorAll('main > ul')[0]\nul.onclick=function(e){\n if(e.target.tagName === 'LI')\n e.target.classList.toggle('hidden-children')\n}\nfunction setDepth(d,e){\n e.preventDefault()\n var s=''\n while(d--){\n s+='li '\n ul.querySelectorAll(s).forEach(function(li){\n if(d!=0)\n li.classList.remove('hidden-children')\n else\n li.classList.add('hidden-children')\n })\n }\n}\n</script>\n" }, { "alpha_fraction": 0.7899384498596191, "alphanum_fraction": 0.7918115854263306, "avg_line_length": 70.86538696289062, "blob_id": "51819801fdfbf3dd32a7d12ca11c38803c43a577", "content_id": "34cab6e6336f6028d2961a18d559e7ddd815f5da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3799, "license_type": "no_license", "max_line_length": 513, "num_lines": 52, "path": "/_documents/altera-higher-level-concepts.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Altera: Higher Level Concepts\ndescription: >\n A brief exploration of higher level concepts in our world, as they could be realized in Altera.\ntype: essay\nstatus: incomplete\n---\n\n## Thoughts on Nook Reproduction\n\nNooks reproduce “asexually” in the sense that each time a Nook reproduces, the younger Nook that splits off can be considered the “child” of the older “parent”. Note that the child and parent are nearly indistinguishable, so it is more similar to an amoeba reproducing than a human.\n\nA given Nook could have many “descendants” if its children all manage to eat a lot of food, and in turn reproduce.\n\nDuring the course of time, one can imagine several different “species” of Nooks being produced, each with different survival strategies and levels of sophistication.\n\nMore advanced Nooks could “breed” less sophisticated Nooks to perform certain functions for them. They could do this by controlling the less sophisticated Nook’s food supply, and selectively eating their children if they do not act according to the traits they are breeding for.\n\nNote that a more advanced Nook could not determine which specifies another Nook is from, except by their movement patterns. I.e., when sitting still, all Nooks of a particular weight appear identically. This could present opportunities for one species to hide themselves as if they were another.\n\nIn this way, advanced Nooks could breed Nooks to perform various duties for them.\n\n## Walls\n\nNooks of weight 255 could form walls. These walls would protect the inner contents of the wall, since no other Nooks could circumvent them. Such walls would require a lot of food to construct, and would thus be very valuable. Walls could also be multiple layers thick.\n\n## Communication Chains\n\nBecause nooks can only see within a 9x9 grid, if a group of Nooks wanted to communicate information more quickly than is possible by an individual moving across the world, they could set up a chain of Nooks spaced 9 squares apart, and they could send signals back and forth at a rate of 9x the speed it would be possible otherwise.\n\n## Decay\n\nBecause each Nook looses one-weight during each starvation event, “structures” and individuals would need to be replenished occasionally. One strategy to break through a wall would be to lay “siege” to it, and starve out the Nooks forming the wall, or the inner contents of the Nooks within the wall.\n\n## Language\n\nNooks could “speak” with one another by moving in certain patterns know by other Nooks to mean certain things.\n\nNooks could “write” by spatially arranging food according to a pattern.\n\nThe patterns involved in Writing may be related to the patterns involved in speech, like they are in our world.\n\n## Art\n\nWriting could be used to communicate information, but also could be a form of “art”. Perhaps a sequence of food arranged a certain way would be a form of “literature”.\n\nNooks could also move in certain patterns that don’t communicate information. This could be seen to be “dance,” although the distinction between dance and speech perhaps is unclear.\n\nLikewise, one can imagine less advanced Nooks being trained or bred to act and dance in certain patterns, which are beautiful to Nooks.\n\nE.g., imagine a species of Nook that always reproduced to the right if there is another Nook of the same weight above it. Further, imagine other species of Nooks that act in precisely specified ways. Advanced Nooks could combine these various specifies of Nooks such that, upon being triggered, the collection of Nooks evolves in some beautifully arranged (possibly cyclical) pattern. Maybe one of the advanced Nooks could guide along the evolution of these lesser Nooks—acting like a “composer” in some sense.\n" }, { "alpha_fraction": 0.7626091837882996, "alphanum_fraction": 0.7662627100944519, "avg_line_length": 88.7760009765625, "blob_id": "748fe503800ba39b7aebff7e02e5858af8c85ba0", "content_id": "5f9cc2083ef8717580a8f09e5b507b0e18245a7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11278, "license_type": "no_license", "max_line_length": 926, "num_lines": 125, "path": "/_documents/ecclesiastes.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ecclesiastes\ndescription: >\n Ecclesiastes\ntype: note\n---\n\nEcclesiastes is a beautiful and has compelled me to challenge my own views of meaning and purpose.\n\nHere are its opening words:\n\n<blockquote>\n<p>The words of the Teacher, the son of David, king in Jerusalem.</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p> Vanity of vanities, says the Teacher,</p>\n<p class=\"indent\"> vanity of vanities! All is vanity.</p>\n<p> What do people gain from all the toil</p>\n<p class=\"indent\"> at which they toil under the sun?</p>\n<p> A generation goes, and a generation comes,</p>\n<p class=\"indent\"> but the earth remains forever.</p>\n<p> The sun rises and the sun goes down,</p>\n<p class=\"indent\"> and hurries to the place where it rises.</p>\n<p> The wind blows to the south,</p>\n<p class=\"indent\"> and goes around to the north;</p>\n<p> round and round goes the wind,</p>\n<p class=\"indent\"> and on its circuits the wind returns.</p>\n<p> All streams run to the sea,</p>\n<p class=\"indent\"> but the sea is not full;</p>\n<p> to the place where the streams flow,</p>\n<p class=\"indent\"> there they continue to flow.</p>\n<p> All things are wearisome;</p>\n<p class=\"indent\"> more than one can express;</p>\n<p> the eye is not satisfied with seeing,</p>\n<p class=\"indent\"> or the ear filled with hearing.</p>\n<p> What has been is what will be,</p>\n<p class=\"indent\"> and what has been done is what will be done;</p>\n<p class=\"indent\"> there is nothing new under the sun.</p>\n<p> Is there a thing of which it is said,</p>\n<p class=\"indent\"> “See, this is new”?</p>\n<p> It has already been,</p>\n<p class=\"indent\"> in the ages before us.</p>\n<p> The people of long ago are not remembered,</p>\n<p class=\"indent\"> nor will there be any remembrance</p>\n<p> of people yet to come</p>\n<p class=\"indent\"> by those who come after them.</p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>I, the Teacher, when king over Israel in Jerusalem, applied my mind to seek and to search out by wisdom all that is done under heaven; it is an unhappy business that God has given to human beings to be busy with. I saw all the deeds that are done under the sun; and see, all is vanity and a chasing after wind. <cite>(1.2–14)</cite></p>\n</blockquote>\n\nEcclesiastes has perplexed Christians and Jews for centuries because its message appears inconsistent with the other books of the Hebrew Bible.\n\nIn verse 1 the author of the book introduces the Teacher, whose dour speech fills most of the remainder of the book. In his speech, the speaker expands on the main idea, “All is vanity” and attempts to answer the question “What do people gain from all their toil?”\n\nWhen the Teacher’s speech is over, the author provides a brief epilogue:\n\n<blockquote class=\"prose\">\n<p>Besides being wise, the Teacher also taught the people knowledge, weighing and studying and arranging many proverbs. The Teacher sought to find pleasing words, and he wrote words of truth plainly.</p>\n<p>The sayings of the wise are like goads, and like nails firmly fixed are the collected sayings that are given by one shepherd. Of anything beyond these, my child, beware. Of making many books there is no end, and much study is a weariness of the flesh.</p>\n<p>The end of the matter; all has been heard. Fear God, and keep his commandments; for that is the whole duty of everyone. For God will bring every deed into judgment, including every secret thing, whether good or evil. <cite>(12.9–14)</cite></p>\n</blockquote>\n\nVarious approaches may be used to resolve the mismatch between Ecclesiastes and the rest of the Hebrew Bible:\n\n- Remove Ecclesiastes from the canon—claim it was not inspired.\n- Dismiss the need for consistency between the books of the Hebrew Bible; perhaps they are a collection of inspired voices, all of which are appropriate and useful in certain situations, but collectively are not consistent. (E.g., similar to how many verses in Proverbs contradict one another.)\n- Assert that the author’s final statements in the epilogue supersede and to some sense reprimand the ideas of the Teacher in the main speech. Perhaps the author thought the Teacher’s arguments were worth listening to, but that ultimately we must follow god’s commandments anyway.\n- Interpret the phrase “under the sun” to mean that the Teacher is knowingly and explicitly contrasting a philosophy based on human wisdom with a full understanding of God’s wisdom.\n- Provide interpretations of the problematic verses on an as-needed basis.\n\nSome problematic verses:\n\n<blockquote class=\"prose\">\n<p>Moreover I saw under the sun that in the place of justice, wickedness was there, and in the place of righteousness, wickedness was there as well. I said in my heart, God will judge the righteous and the wicked, for he has appointed a time for every matter, and for every work. I said in my heart with regard to human beings that God is testing them to show that they are but animals. For the fate of humans and the fate of animals is the same; as one dies, so dies the other. They all have the same breath, and humans have no advantage over the animals; for all is vanity. All go to one place; all are from the dust, and all turn to dust again. Who knows whether the human spirit goes upward and the spirit of animals goes downward to the earth? So I saw that there is nothing better than that all should enjoy their work, for that is their lot; who can bring them to see what will be after them? <cite>(3.16–22)</cite></p>\n</blockquote>\n\nIt is clear that the Teacher does not believe in a pleasant afterlife. As a consolation, enjoy your work while you are alive, for that is as good as it gets.\n\n<blockquote class=\"prose\">\n<p>In the day of prosperity be joyful, and in the day of adversity consider; God has made the one as well as the other, so that mortals may not find out anything that will come after them. In my vain life I have seen everything; there are righteous people who perish in their righteousness, and there are wicked people who prolong their life in their evildoing. Do not be too righteous, and do not act too wise; why should you destroy yourself? Do not be too wicked, and do not be a fool; why should you die before your time? It is good that you should take hold of the one, without letting go of the other; for the one who fears God shall succeed with both. <cite>(7.14–18)</cite></p>\n</blockquote>\n\nWait, one should not be too righteous? And one fears God shall succeed with both righteousness and wickedness?\n\n<blockquote class=\"prose\">\n<p>Everything that confronts them is vanity, since the same fate comes to all, to the righteous and the wicked, to the good and the evil, to the clean and the unclean, to those who sacrifice and those who do not sacrifice. As are the good, so are the sinners; those who swear are like those who shun an oath. This is an evil in all that happens under the sun, that the same fate comes to everyone. Moreover, the hearts of all are full of evil; madness is in their hearts while they live, and after that they go to the dead. But whoever is joined with all the living has hope, for a living dog is better than a dead lion. The living know that they will die, but the dead know nothing; they have no more reward, and even the memory of them is lost. Their love and their hate and their envy have already perished; never again will they have any share in all that happens under the sun.</p>\n<p>Go, eat your bread with enjoyment, and drink your wine with a merry heart; for God has long ago approved what you do. Let your garments always be white; do not let oil be lacking on your head. Enjoy life with the wife whom you love, all the days of your vain life that are given you under the sun, because that is your portion in life and in your toil at which you toil under the sun. Whatever your hand finds to do, do with your might; for there is no work or thought or knowledge or wisdom in Sheol, to which you are going. <cite>(9.1b–10)</cite></p>\n</blockquote>\n\nIn these verses, as in those quoted from chapter 3 above, it is clear that the author does not believe in a pleasant afterlife. The dead are no longer “under the sun,” since they are in Sheol.\n\nApparent internal contradictions:\n\n<blockquote class=\"prose\">\n<p>Then I saw the wicked buried; they used to go in and out of the holy place, and were praised in the city where they had done such things. This also is vanity. Because sentence against an evil deed is not executed speedily, the human heart is fully set to do evil. Though sinners do evil a hundred times and prolong their lives, yet I know that it will be well with those who fear God, because they stand in fear before him, but it will not be well with the wicked, neither will they prolong their days like a shadow, because they do not stand in fear before God.</p>\n<p>There is a vanity that takes place on earth, that there are righteous people who are treated according to the conduct of the wicked, and there are wicked people who are treated according to the conduct of the righteous. I said that this also is vanity. <cite>(8.10–14)</cite></p>\n</blockquote>\n\nI do not find the interpretation that “under the sun” should mean that the Teacher is speaking as-if he did not have knowledge of God, or that he is restricting his discussion to the human world. Throughout Ecclesiastes the Teacher discusses God. He tells his audience to enjoy life, usually in a conciliatory tone, implying that this is the best we can expect to get out of life.\n\nIn the most direct sense, the Teacher is wrong!\n\nOur understanding of they physical world is more correct than that of ancient peoples. The Teacher, as most others in his time, believed that the water from the sea flowed back to the rivers through tunnels in the ground. The Earth itself will someday be destroyed when our sun explodes.\n\nEcclesiastes is thought to be written between 600 and 200 BCE. The Greeks invented many new ideas during these centuries—ideas that are still affecting the world today.\n\nSince the invention of writing, we remember some famous people from long ago, for example, the king Hammurabi.\n\nIn a deeper sense, the Teacher is correct.\n\nMost of us will not be remembered a few hundred years from now and perhaps 10,000 years from now Hammurabi will be less well known.\n\nPerhaps humanity will continue to have new ideas and invent new technologies, but this “progress” will halt eventually. (It seems reasonable that there is a finite number of genuinely new ideas and phenomena for us to discover).\n\nWhile the Teacher’s understanding of physical reality was incomplete, it seems unlikely that an understanding of modern physics would alter his thinking.\n\nYet, in the deepest sense, I think the Teacher is wrong.\n\nIf our existence is meaningless because it is transient, or because it is not unique, then one must wonder where could meaning possibly come from? I think the only possible answers are that there must be meaning found even within our transient lives or that there is some mystical meta-physical source of meaning which is not found in our finite universe.\n\nThus, while our existence is but a breath, to be blown away and forgotten, we can find meaning in it or hope that there is a hidden meaning beyond the metaphysical veil.\n" }, { "alpha_fraction": 0.470752090215683, "alphanum_fraction": 0.6155988574028015, "avg_line_length": 31.636363983154297, "blob_id": "635163aa96fc1bbba6d25d9b3ff90b0fe524227e", "content_id": "cec5ec8bcf2ce6cefb31a80eebbb3df1743cce0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 359, "license_type": "no_license", "max_line_length": 68, "num_lines": 11, "path": "/scripts/test_interp_line_numbers.py", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "from interp_line_numbers import interp_line_numbers\n\n\ndef test_exact_match():\n assert interp_line_numbers(1, 10, 1, 10, 2, 6) == (2, 6)\n assert interp_line_numbers(1, 10, 1, 10, 1, 10) == (1, 10)\n\n\ndef test_full_range():\n assert interp_line_numbers(1, 10, 5, 10, 5, 10) == (1, 10)\n assert interp_line_numbers(1, 10, 103, 105, 103, 105) == (1, 10)\n" }, { "alpha_fraction": 0.7391668558120728, "alphanum_fraction": 0.7425185441970825, "avg_line_length": 41.406089782714844, "blob_id": "6b7d0fd66bb924ada6f3ee8d06a7900619262a7c", "content_id": "5b832031e4292f79be1b8fab40a39aab0c3600bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8354, "license_type": "no_license", "max_line_length": 389, "num_lines": 197, "path": "/documents/sophocles-theban-plays.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Sophocles' Theban Plays\ndescription: >\n Notes on Sophocles' Theban Plays\ntype: note\n---\n\n## Oedipus the King\n\nAngered Tiresias implicates Oedipus:\n\n> So, you mock my blindness? Let me tell you this.\n> You with your precious eyes,\n> you're blind to the corruption of your life,\n> to the house you live in, those you live with---\n> who _are_ your parents? Do you know? All unknowing\n> you are the scourge of your own flesh and blood,\n> the dead below the earth and the living here above,\n> and the double lash of your mother and your father's curse\n> will whip you from this land one day, their footfall\n> treading you down in terror, darkness shrouding\n> your eyes that can see the light!\n\nThe following quotations expresses two ideas central to the Greek world view. First, that the gods strip down the over-proud man, the man filled with hubris. Second, that we competition is healthy.\n\n> Destiny guide me always\n> Destiny guide me filled with reverence\n> pure in word and deed.\n> Great laws tower above us, reared on high\n> born for the brilliant vault of heaven---\n> Olympian Sky their only father,\n> nothing mortal, no man gave them birth,\n> their memory deathless, never lost in sleep:\n> within them lives a mighty god, the god does not\n> grow old. Pride breeds the tyrant\n> violent pride, gorging, crammed to bursting\n> with all that is overripe and rich with ruin---\n> clawing up to the heights, headlong pride\n> crashes down the abyss---sheer doom!\n> No footing helps, all foothold lost and gone.\n> But the healthy strife that makes the city strong---\n> I pray that god will never end that wrestling:\n> god, my champion, I will never let you go.\n\nThese two ideas are present in many of the ancient Greek works; Hesiod, near the opening of _Works and Days_, speaks of strife that causes men to compete with one another, doing people good; Herodotus' stories highlight his belief that the gods tore down overproud men---he also explicitly discusses this idea; the _Iliad_ is filled with proud men striving with one other to \"be the best.\"\n\nThe Chorus, after Oedipus is revealed:\n\n> O the generations of men\n> the dying generations---adding the total\n> of all your lives I find they come to nothing...\n> does there exist, is there a man on earth\n> who seizes more joy than just a dream, a vision?\n> And the vision no sooner dawns than dies\n> blazing into oblivion.\n> You are my great example, you, your life\n> your destiny, Oedipus, man of misery---\n> I count no man blest.\n\nOedipus, chases after his wife and mother Jocasta:\n\n> His wife,\n> no wife, his mother, where can eh find the mother earth\n> that cropped two crops at once, himself and all his children?\n> He was raging---one of the dark powers pointing the way,\n> with a great shattering cry---someone, something leading him on---\n> he hurled at the twin doors and bending the bolts back\n> out of their sockets, crashed through the chamber.\n> And there we saw the woman hanging by the neck,\n> cradled high in a woven noose, spinning,\n> swinging back and forth. And when he saw her,\n> giving a low, wrenching sob that broke our hearts,\n> slipped the halter from her throat, he eased her down,\n> in a slow embrace he laid her down, poor thing...\n> then, what came next, what horror we beheld!\n> He rips off her brooches, the long gold pins\n> holding her robes---and lifting them high,\n> looking straight up into the points,\n> he digs them down the sockets of his eyes, crying, \"You,\n> you'll see no more the pain I suffered, all the pain I caused!\n> Too long you looked on the ones you never should have seen,\n> blind to the ones you longed to see, to know! Blind\n> from this hour on! Blind in the darkness---blind!\"\n> His voice like a dirge, rising, over and over\n> raising the pins, raking them down his eyes.\n> And at each stroke blood spurts from the roots,\n> splashing his beard, a swirl of it, nerves and clots---\n> black hail of blood pulsing, gushing down.\n\nThe Chorus, at the end of the play:\n\n> People of Thebes, my countrymen, look on Oedipus.\n> He solved the famous riddle with his brilliance,\n> he rose to power, a man beyond all power.\n> Who could behold his greatness without envy?\n> Now what a black sea of terror has overwhelmed him.\n> Now as we keep our watch and wait the final day,\n> count no many happy till he dies, free of pain at last.\n\nThis metric for judging the happy life is in Herodotus' fable of Solon meeting Croesus.\n\n## Oedipus at Colonus\n\n> Oh Theseus,\n> dear friend, only the gods can never age,\n> the gods can never die. All else in the world\n> almighty Time obliterates, crushes all\n> to nothing. The earth's strength wastes away,\n> the strength of a man's body wastes and dies---\n> faith dies, and bad faith comes to life,\n> and the same wind of friendship cannot blow forever,\n> holding steady and strong between two friends,\n> much less between two cities.\n> For some of us soon, for others later,\n> joy turns to hate and back again to love.\n> And even if all is summer sunshine now\n> between yourself and Thebes,\n> infinite Time, sweeping through its rounds\n> gives birth to infinte nights and days...\n> and a day will come when the treaties of an hour,\n> the pacts firmed by a handclasp will snap---\n> at the slightest word a spear will hurl them to the winds---\n> some far-off day when my dead body, slumbering, buried\n> cold in death, will drain their hot blood down,\n> if Zeus is still Zeus and Apollow the son of god\n> speaks clear and true.\n> ~ (685--707)\n\n> Here, stranger,\n> here in the land of horses are a glory\n> you have reached the noblest home on earth\n> Colonus glistening, brilliant in the sun---\n> where the nightingale sings on,\n> her dying music rising clear,\n> hovering always, never leavning,\n> down the shadows deepening green\n> she haunts the glades, the wine-dark ivy,\n> dense and dark the untrodden, sacred wood of god\n> rich with laurel and olives never touched by the sun\n> untouched by storms that blast from every quarter---\n> where the Reveler Dionysus strides the earth forever\n> where the wild nymphs are dancing round him\n> nymphs who nursed his life.\n> And here it blooms, fed by the dews of heaven\n> lovely, clustering, morning-fresh forever,\n> narcissus, crown of the Great Goddesss\n> Mother and Daughter dying\n> into life from the dawn of time,\n> and the gold crocus bursts like break of day\n> and the springs will never sleep, will never fail,\n> the fountainhead of Cephisus flowing nomad\n> quickening life forever, fresh each day---\n> life rising up with the river's pure tide\n> flowing over the plains, the swelling breats of earth---\n> nor can the dancing Muses bear to leave this land\n> or the Goddess Aphrodite, the charioteer\n> with the golden reins of love.\n> ~ (761--89)\n\n> Suffer us to live here ... even in these straights\n> our life is not as pitiful as you'd think,\n> so long as we find joy in every hour.\n> ~ (909--11)\n\nOedipus declaring his innocence to Creon, in front of Theseus and the Athenians:\n\n> Unctuous, shameless---where do you think your insults\n> do more damage, my old age or yours? Bloodshed\n> incest, misery, all your mouth lets fly at me,\n> I have suffered it all, and all against my will!\n> Such was the pleasure of the gods, raging,\n> perhaps, against our race from ages past.\n> But as for me alone---\n> say my unwilling crimes against myself\n> and against my own were payment from the gods\n> for something criminal deep inside me...no, look hard,\n> you'll find no guilt to accuse me of---I am innocent!\n> ...\n> And my mother...\n> wretched man, have you no shame? Your own sister!\n> Her marriage---forcing me to talk of that marriage!\n> Oh I'll tell it all, I won't be silent, not now,\n> you and your blasphemous mouth have gone so far.\n> She was my mother, yes, she bore me---\n> oh the horror---I knew nothing, she knew nothing!---\n> and once she'd born me then she bore me children,\n> her disgrace. But at least I know one thing:\n> you slander her and me of your own free will,\n> but I made her my bride against my will,\n> I repeat this to the world againnst my will. No,\n> I'll not be branded guilty, not in that marriage,\n> not in the murder of my father, all those crimes\n> you heap on me relentlessly, harrowing my heart.\n> ~ (1095--1131)\n\n*Quotations are taken from Robert Fagles' 1982 translation of* The Three Theban Plays*, published by Penguin Classics.*\n" }, { "alpha_fraction": 0.7947402000427246, "alphanum_fraction": 0.7960230708122253, "avg_line_length": 56.74074172973633, "blob_id": "1cd27839833d68b3f05010070c9ef4c7dc5f96fe", "content_id": "4c22226fe5ef6af4c53147089fcf86d2687bad71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1571, "license_type": "no_license", "max_line_length": 224, "num_lines": 27, "path": "/_documents/justice.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Justice\ndescription: >\n A meandering contemplation of justice\ntype: essay\nstatus: incomplete\n---\n\nIf everyone was perfect, we would not need justice. Thus justice is distinguished from a moral code; justice exists independently as a mean of addressing failures to follow a moral code.\n\nThere seems to be two levels of justice. The current system, and the underlying ideal.\n\nA justice system is instituted by a country as a means to identifying and addressing unfairness in its society. There are many possible systems, each defining unfairness differently and addressing it differently.\n\nMost of us believe there is a right system of justice. This can be seen when we say “the criminal justice system is unjust.” We are appealing to the higher ideal of justice, beyond the particular flawed system in question.\n\nIn this essay we consider the ideal of justice apart from particular flawed systems of justice.\n\nWithout attempting to define fairness, we can make some useful observations. First, unfairness comes broadly from two places:\n\n1. Our circumstances in the world (being born rich or poor)\n2. Other conscious beings impinging on our well-being\n\nThe first form of unfairness is often called “social justice” or “distributive justice,” because it is considered with the distribution of goods within a society.\n\nAn interesting ethical question is: can the first form of unfairness exist if everyone was perfect? In other words, should moral wealthy people give their money to the poor so as to flatten out the distribution of goods?\n" }, { "alpha_fraction": 0.7210963368415833, "alphanum_fraction": 0.7313085198402405, "avg_line_length": 46.36591339111328, "blob_id": "17ba0eaa150286788697457d6feaf7722f8df18b", "content_id": "d5cc78d45aa1816aa7d2407c9a20a65ced1f27f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19271, "license_type": "no_license", "max_line_length": 476, "num_lines": 399, "path": "/_documents/the-odyssey.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n The _Odyssey_\ndescription: >\n Notes on the _Odyssey_\ntype: note\nstatus: incomplete\n---\n\n## Background\n\nThe ancients believed that the *Odyssey* was composed by the blind poet Homer. Modern scholars debate when it was composed and by whom, but most agree it was written between 725 BCE and 675 BCE. It has almost always been held that that the *Odyssey* was written after the *Iliad,* because it refers to material in the *Iliad* frequently, while avoiding any direct duplication.\n\n## Structure and Outline\n\nThe poem has about 12,000 lines of hexameter verse in the ancient Greek, and is split into 24 books. The opening summarizes the theme of the epic:\n\n<blockquote class=\"poetry\">\n<p>Sing to me of the man, Muse, the man of twists and turns</p>\n<p>driven time and again off course, once he had plundered</p>\n<p>the hallowed heights of Troy.</p>\n<p>Many cities of men he saw and learned their minds,</p>\n<p>many pains he suffered, heartsick on the open sea,</p>\n<p>fighting to save his life and bring his comrades home.</p>\n<p>But he could not save them from disaster, hard as he strove—</p>\n<p>the recklessness of their own ways destroyed them all,</p>\n<p>the blind fools, they devoured the cattle of the Sun</p>\n<p>and the Sungod wiped from sight the day of their return.</p>\n<p>Launch out on his story Muse, daughter of Zeus,</p>\n<p>start from where you will—sing for our time too. <cite>(1.1–10)</cite></p>\n</blockquote>\n\nIt is interesting that the poet tells the muse to “start from where you will.”\n\nHere is an outline:\n\n1. The gods pity Odysseus; Athena inspires Telemachus\n2. The assembly at Ithaca; Telemachus secretly sets sail\n3. Nestor recalls his return; sacrifice to Athena; departure for Lacedaemon\n4. Menelaus recalls his return; the suitors plot their ambush\n5. Hermes visits Calypso; Odysseus’ raft; sails then swims to Phaeacia\n6. Athena guides the princess to bring aid to Odysseus\n7. King Alcinous promises to bring Odysseus home\n8. Athletic games; song of Ares and Aphrodite; songs of Troy\n9. Encounter in Polyphemus the Cyclops’ cave; Odysseus is cursed\n10. Blown home and back; Laestrygonians destroy the fleet; year with Circe\n11. Odysseus talks to ghosts in the kingdom of the dead\n12. Return to Circe; the Sirens; Scylla and Charybdis; Helios’ cattle; Calypso\n13. Athena greets Odysseus on Ithaca; Poseidon petrifies the Phaeacians\n14. Disguised Odysseus talks to the loyal swineherd Eumaeus\n15. Telemachus returns with gifts and a seer; Eumaeus’ story\n16. Odysseus and Telemachus meet and plan revenge; the suitors conspire\n17. Mingling with the suitors\n18. Odysseus fights a hobo and chides the disloyal maidens\n19. Penelope questions disguised Odysseus; Eurycleia sees the scar\n20. Odysseus rests and receives omens; Apollo’s feast\n21. The trial of the bow; Odysseus signals the attack\n22. Slaughter of the suitors and the disloyal maidens\n23. Odysseus and Penelope reunited\n24. Achilles and Agamemnon greet the suitor’s ghosts; Odysseus and Laeretes; final battle and peace\n\n## Justice, Morality, and the Gods\n\nEarly in book 1, the gods are in full assembly—curiously similar to the assemblies the Greeks held—and Zeus makes an interesting statement:\n\n<blockquote class=\"poetry\">\n<p>“Ah how shameless—the way these mortals blame the gods.</p>\n<p>From us alone, they say, come all their miseries, yes,</p>\n<p>but they themselves, with their own reckless ways,</p>\n<p>compound their pains beyond their proper share.</p>\n<p>Look at Aegisthus now …</p>\n<p>above and beyond <em>his</em> share he stole Atrides’ wife,</p>\n<p>he murdered the warlord coming home from Troy</p>\n<p>though he knew it meant his own total ruin.” <cite>(1.31–37)</cite></p>\n</blockquote>\n\nFrom the start of the *Odyssey,* the gods seem more concerned with morals and justice than in the *Iliad.*\n\nZeus’ implication that men should have a “proper share” of pains is interesting. In the Abrahamic religions, pain and suffering are the result of the fall of man. After the fall, there doesn’t seem to be an expectation that these pains are distributed evenly. In the Greek religion, they had the myth of Pandora’s box, which is in someways similar to the story of Adam and Eve, but even after the fall it appears there is a sense that miseries should be distributed evenly.\n\nShortly after Zeus’ comment, Athena responds:\n\n<blockquote class=\"poetry\">\n<p>“Let them all die so, all who do such things.</p>\n<p>But my heart breaks for Odysseus …</p>\n<p>he, straining for no more than a glimpse</p>\n<p>of hearth-smoke drifting up from his own land,</p>\n<p>Odysseus longs to die … Olympian Zeus,</p>\n<p>have you no care for <em>him</em> in your lofty heart?</p>\n<p>Did he never win your favor with sacrifices</p>\n<p>burned besides the ships on the broad plain of Troy?” <cite>(1.46–63)</cite></p>\n</blockquote>\n\nZeus replies that, no, he is happy with Odysseus, but that Poseidon is the one to blame.\n\nThe Greeks’ explanation for the existence of pain and suffering appears to be three fold:\n\n- We all should have a “fair share”\n- Some we bring on ourselves through unjust acts\n- Some is due to other gods\n\nThe assembly in book 2 provides some insight into justice in ancient Greece. Telemachus appears to escalate through three authorities. First, is his own strength, second is the people of Ithaca:\n\n<blockquote class=\"poetry\">\n<p>“Now we have no man like Odysseus in command</p>\n<p>to drive this curse from the house. We ourselves?</p>\n<p>We’re hardly the ones to fight them off. All we’d do</p>\n<p>is parade our wretched weakness. A boy inept at battle.</p>\n<p>Oh I’d swing to attack if I had the power in me.</p>\n<p>By god, it’s intolerable, what they do—disgrace,</p>\n<p>my house a shambles! You should be ashamed yourselves,</p>\n<p>mortified in the face of neighbors living round about!</p>\n<p>Fear the gods’ wrath—before they wheel in outrage</p>\n<p>and make these crimes recoil on your heads.” <cite>(2.57-67)</cite></p>\n</blockquote>\n\nAnd when the towns people refuse to do anything, Telemachus escalates to the third authority—the gods:\n\n<blockquote class=\"poetry\">\n<p>“But if you decide the fare is better, richer here,</p>\n<p>destroying one man’s goods and going scot-free,</p>\n<p>all right then, carve away!</p>\n<p>But I’ll cry out to the everlasting gods in hopes</p>\n<p>that Zeus will pay you back with a vengeance—all of you</p>\n<p>destroyed in my house while I go scot-free myself!” <cite>(2.141–5)</cite></p>\n</blockquote>\n\nIt seems that fear of the gods was the main source of justice in Greek society. Since there were no contracts or court system to build trust between individuals, people relied on oaths—and the fear of the gods if one broke their oath—to build trust. Similarly, if one could not find justice through strength of your fellow men, you could threaten the wrongdoers with a curse. If they feared the gods, they may respond.\n\nIn such a society an atheist or godless person could not be trusted. Right after Telemachus threatens the suitors with a curse, Zeus sends a sign down in the form of two eagles. One of the old townsmen, who excelled in reading omens and bird signs, said that the eagles were a sign from Zeus that the suitors would get what is coming to them. And the suitors respond:\n\n<blockquote class=\"poetry\">\n<p>“Stop, old man!”</p>\n<p>Eurymachus, Polybus’ son, rose up to take him on.</p>\n<p>“Go home and babble your omens to your children—</p>\n<p>save <em>them</em> from some catastrophe coming soon.</p>\n<p>I’m a better hand than you at reading portents.</p>\n<p>Flocks of birds go fluttering under the sun’s rays,</p>\n<p>not all are fraught with meaning.” <cite>(2.177–83)</cite></p>\n</blockquote>\n\n## The Gods\n\nAthena rebukes Telemachus for doubting the power of the gods to return his father:\n\n<blockquote class=\"poetry\">\n<p>“Hope, hope as I will,</p>\n<p>that day will never dawn…</p>\n<p>not even if the gods should will it so.” “Telemachus!”</p>\n<p>Pallas Athena broke in sharply, her eyes afire—</p>\n<p>“What’s this nonsense slipping through your teeth?</p>\n<p>It’s light work for a willing god to save a mortal</p>\n<p>even half the world away. Myself, I’d rather</p>\n<p>sail through years of trouble and labor home</p>\n<p>and see that blessed day, than hurry home</p>\n<p>to die at my own hearth like Agamemnon,</p>\n<p>killed by Aegisthus’ cunning—by his own wife.</p>\n<p>But the great leveler, Death: not even the gods</p>\n<p>can defend a man, not even one they love, that day</p>\n<p>when fate takes hold and lays him out at last.” <cite>(3.228–39)</cite></p>\n</blockquote>\n\nAthena reveals herself to many people at once:\n\n<blockquote class=\"poetry\">\n<p>With that the bright-eyed goddess winged away</p>\n<p>in an eagle’s form and flight.</p>\n<p>Amazement fell on all the Achaeans there.</p>\n<p>The old king, astonished by what he’d seen,</p>\n<p>grasped Telemachus’ hand and cried out to the prince,</p>\n<p>“Dear boy—never fear you’ll be a coward or defenseless,</p>\n<p>not if at your young age the gods will guard you so.” <cite>(3.372–7)</cite></p>\n</blockquote>\n\n## Women\n\nThe Greeks did not treat women well.\n\n<blockquote class=\"poetry\">\n<p>“So, mother,</p>\n<p>go back to your quarters. Tend to your own tasks,</p>\n<p>the distaff and the loom, and keep the women</p>\n<p>working hard as well. As for giving orders,</p>\n<p>men will see to that, but I most of all:</p>\n<p>I hold the reins of power in this house.” Astonished,</p>\n<p>she withdrew to her own room. She took to heart</p>\n<p>the clear good sense in what her son had sad. <cite>(1.355–62)</cite></p>\n</blockquote>\n\nAgamemnon’s ghost’s rant against women:\n\n<blockquote class=\"poetry\">\n<p>“‘But she—</p>\n<p>the queen hell-bent on outrage—bathes in shame</p>\n<p>not only herself but the whole breed of womankind,</p>\n<p>even the honest ones to come, forever down the years!’”</p>\n<p>So he declared and I cried out, ‘How terrible!</p>\n<p>Zeus from the very start, the thunder king</p>\n<p>has hated the race of Atreus with a vengeance—</p>\n<p>his trustiest weapon women’s twisted wiles.</p>\n<p>What armies of us died for the sake of Helen…</p>\n<p>Clytemnestra schemed your death while you were worlds away!’” <cite>(11.432–40)</cite></p>\n</blockquote>\n\n## The Good Life\n\n<blockquote class=\"poetry\">\n<p>Alcinous, majesty, shining among your island people,</p>\n<p>what a fine thing it is to listen to such a bard</p>\n<p>as we have here—the man sings like a god.</p>\n<p>The crown of life, I’d say. There’s nothing better</p>\n<p>than when deep joy holds sway throughout the realms</p>\n<p>and banqueters up and down the palace sit in ranks,</p>\n<p>enthralled to hear the bard, and before them all, the tables</p>\n<p>heaped with bread and meats, and drawing wine from a mixing-bowl</p>\n<p>the steward makes his rounds and keeps the winecups flowing.</p>\n<p>This, to my mind, is the best that life can offer. <cite>(9.2–10)</cite></p>\n</blockquote>\n\nMy wife observed that is perhaps not a coincidence that Homer’s Odysseus believes a talented bard’s story is the best that life has to offer.\n\n## The Muses\n\nHomer, like Hesiod, implies that the Muse provides divine inspiration to bards.\n\n<blockquote class=\"poetry\">\n<p>“I respect you, Demodocus, more than any man alive—</p>\n<p>surely the Muse has taught you, Zeus’s daughter,</p>\n<p>or god Apollo himself. How true to life,</p>\n<p>all too true … you sing the Achaeans’ fate,</p>\n<p>all they did and suffered, all they soldiered through,</p>\n<p>as if you were there yourself or heard from one who was.”</p>\n<p>⋯</p>\n<p>Stirred now by the Muse, the bard launched out</p>\n<p>in a fine blaze of song, starting at just the point</p>\n<p>where the main Achaean force, setting their camps afire,</p>\n<p>hard boarded the oarswept ships and sailed for home … <cite>(8.486–501)</cite></p>\n</blockquote>\n\n## Other Interesting Quotes\n\nHelen uses a strange drug while feasting with Menelaus, Telemachus, and Pisastratus:\n\n<blockquote class=\"poetry\">\n<p>Then Zeus’s daughter Helen thought of something else.</p>\n<p>Into the mixing-bowl from which they drank their wine</p>\n<p>she slipped a drug, heart’s-ease, dissolving anger,</p>\n<p>magic to make us all forget our pains…</p>\n<p>No one who drank it deeply, mulled in wine,</p>\n<p>could let a tear roll down his cheeks that day,</p>\n<p>not even if his mother should die, his father die,</p>\n<p>not even if right before his eyes some enemy brought down</p>\n<p>a brother or darling son with a sharp bronze blade. <cite>(4.218–25)</cite></p>\n</blockquote>\n\nIn Odysseus’ speech to the princess Nausicaa, he describes the ideal marriage:\n\n<blockquote class=\"poetry\">\n<p>“And may the good gods give you all your heart desires:</p>\n<p>husband, and house, and lasting harmony too.</p>\n<p>No finer, greater gift in the world than that…</p>\n<p>when man and woman possess their home, two minds,</p>\n<p>two hearts that work as one. Despair to their enemies,</p>\n<p>a joy to all their friends. Their own best claim to glory.” <cite>(6.180–4)</cite></p>\n</blockquote>\n\nOdysseus’ description of hunger:\n\n<blockquote class=\"poetry\">\n<p>“But despite my misery, let me finish dinner.</p>\n<p>The belly’s a shameless dog, there’s nothing worse.</p>\n<p>Always insisting, pressing, it never lets us forget—</p>\n<p>destroyed as I am, my heart racked with sadness,</p>\n<p>sick with anguish, still it keeps demanding,</p>\n<p>‘Eat, drink!’ It blots out all the memory</p>\n<p>of my pain, commanding, ‘Fill me up!’” <cite>(7.214-20)</cite></p>\n</blockquote>\n\nOdysseus is cursed by the Cyclops—causing his journey home to be so long:\n\n<blockquote class=\"poetry\">\n<p>“Hear me—</p>\n<p>Poseidon, god of the sea-blue mane who rocks the earth!</p>\n<p>If I really am your son and you claim to be my father—</p>\n<p>come, grant that Odysseus, raider of cities,</p>\n<p>Laertes’ son who makes his home in Ithaca,</p>\n<p>never reaches home. Or if he’s fated to see</p>\n<p>his people once again and reach his well-built house</p>\n<p>and his own native country, let him come home late</p>\n<p>and come a broken man—all shipmates lost,</p>\n<p>alone in a stranger’s ship—</p>\n<p>and let him find a world of pain at home!” <cite>(9.527–35)</cite></p>\n</blockquote>\n\nAchilles in the underworld:\n\n<blockquote class=\"poetry\">\n<p>“‘But you, Achilles,</p>\n<p>there’s not a man in the world more blest than you—</p>\n<p>there never has been, never will be one.</p>\n<p>Time was, when you were alive, we Argives</p>\n<p>honored you as a god, and now down here, I see,</p>\n<p>you lord it over the dead in all your power.</p>\n<p>So grieve no more at dying, great Achilles.’</p>\n<p>I reassured the ghost, but he broke out, protesting,</p>\n<p>‘No winning words about death to <em>me</em>, shining Odysseus!</p>\n<p>By god, I’d rather slave on earth for another man—</p>\n<p>some dirt-poor tenant farmer who scrapes to keep alive—</p>\n<p>than rule down here over all the breathless dead.’” <cite>(11.482–92)</cite></p>\n</blockquote>\n\nSisyphus in the underworld:\n\n<blockquote class=\"poetry\">\n<p>“And I saw Sisyphus too, bound to his own torture,</p>\n<p>grappling his monstrous boulder with both arms working,</p>\n<p>heaving, hands struggling, legs driving, he kept on</p>\n<p>thrusting the rock uphill toward the brink, but just</p>\n<p>as it teetered, set to topple over—time and again</p>\n<p>the immense weight of the thing would wheel it back and</p>\n<p>the ruthless boulder would bound and tumble down to the plain again—</p>\n<p>so once again he would heave, would struggle to thrust it up,</p>\n<p>sweat drenching his body, dust swirling above his head.” <cite>(11.593–600)</cite></p>\n</blockquote>\n\nThe swineherd Eumaeus and disguised Odysseus trading stories:\n\n<blockquote class=\"poetry\">\n<p>“We two will keep to the shelter here, eat and drink</p>\n<p>and take some joy in each other’s heartbreaking sorrows,</p>\n<p>sharing each other’s memories. Over the years, you know,</p>\n<p>a man finds solace even in old sorrows, true, a man</p>\n<p>who’s weathered many blows and wandered many miles.” <cite>(15.398–402)</cite></p>\n</blockquote>\n\nThe death of Argos:\n\n<blockquote class=\"poetry\">\n<p>Infested with ticks, half-dead with neglect,</p>\n<p>here lay the hound, old Argos.</p>\n<p>But the moment he sensed Odysseus standing by</p>\n<p>he thumbed his tail, nuzzling low, and his ears dropped,</p>\n<p>though he had no strength to drag himself an inch</p>\n<p>toward his master. Odysseus glanced to the side</p>\n<p>and flicked away a tear, hiding it from Eumaeus</p>\n<p>⋯</p>\n<p>With that he entered the well-constructed palace,</p>\n<p>strode through the halls and joined the proud suitors.</p>\n<p>But the dark shadow of death closed down on Argos’ eyes</p>\n<p>the instant he saw Odysseus, twenty years away. <cite>(17.300–27)</cite></p>\n</blockquote>\n\nOdysseus’ advice for the suitor Amphinomus:\n\n<blockquote class=\"poetry\">\n<p>Of all that breathes and crawls across the earth,</p>\n<p>our mother earth breeds nothing feebler than a man.</p>\n<p>So long as the gods grant him power, spring in his knees,</p>\n<p>he thinks he will never suffer affliction down the years.</p>\n<p>But then, when the happy gods bring on the long hard times,</p>\n<p>bear them he must, against his will, and steel his heart.</p>\n<p>Our lives, our mood and mind as we pass across the earth,</p>\n<p>turn as the days turn…</p>\n<p>as the father of men and gods makes each day dawn. <cite>(18.130–7)</cite></p>\n</blockquote>\n\n## Similes\n\nWhen Odysseus reaches Phaeacia after swimming for two days:\n\n<blockquote class=\"poetry\">\n<p>Then when Dawn with her lovely locks brought on</p>\n<p>the third day, the wind fell in an instant,</p>\n<p>all glazed to a dead calm, and Odysseus,</p>\n<p>scanning sharply, raised high by a groundswell,</p>\n<p>looked up and saw it—landfall, just ahead.</p>\n<p>Joy … warm as the joy that children feel</p>\n<p>when they see their father’s life dawn again,</p>\n<p>one who’s lain on a sickbed racked with torment,</p>\n<p>wasting away, slowly, under some angry power’s onslaught—</p>\n<p>So warm, Odysseus’ joy when he saw that shore, those trees,</p>\n<p>as he swam on, anxious to plant his feet on solid ground again. <cite>(5.390–9)</cite></p>\n</blockquote>\n\nJust as the children worried about death for several days, so did Odysseus as he floated in the sea.\n\nLater in the story, when Odysseus has reached his home and is plotting his revenge, Homer gives us this great simile:\n\n<blockquote class=\"poetry\">\n<p>But he himself kept tossing, turning,</p>\n<p>intent as a cook before some white-hot blazing fire</p>\n<p>who rolls his sizzling sausage back and forth,</p>\n<p>packed with fat and blood—keen to broil it quickly,</p>\n<p>tossing, turning it, this way, that way—so he cast about:</p>\n<p>how could he get these shameless suitors in his clutches,</p>\n<p>one man facing a mob? <cite>(20.25–30)</cite></p>\n</blockquote>\n\n*All quotations are taken from Robert Fagle’s excellent 1996 translation of the* Odyssey. *Line numbers are approximate.*\n" }, { "alpha_fraction": 0.7016043066978455, "alphanum_fraction": 0.7144384980201721, "avg_line_length": 21.80487823486328, "blob_id": "08c4de5dae3cc6a3650e3767f901984efe072017", "content_id": "91e67abfe8c2aab09d2ae745e2281f38a0b65c94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 943, "license_type": "no_license", "max_line_length": 135, "num_lines": 41, "path": "/_documents/david-hockney.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n David Hockney\ndescription: >\n Notes David Hockney\ntype: note\n---\n\n## Life\n\nBorn in Bradford England in summer 1937. He is a figurative painter. He moved to Los Angeles in 1964.\n\n## Quotes From 2014 Documentary\n\n<blockquote>\n<p>We grow small trying to become great.</p>\n</blockquote>\n\n<blockquote>\n<p>New ways of seeing mean new ways of feeling.</p>\n</blockquote>\n\n<blockquote>\n<p>I do believe painting can change the world.</p>\n</blockquote>\n\n<blockquote>\n<p>I think the absence of love is fear. If one can understand love, one can, to a certain extent, be fearless.</p>\n</blockquote>\n\n<blockquote>\n<p>The urge to represent is very deep within us.</p>\n</blockquote>\n\n<blockquote>\n<p>When you stop doing something, it doesn’t mean you are rejecting it. You’re saying, I wish to take a look round another corner.</p>\n</blockquote>\n\n<blockquote>\n<p>Friends … that’s really the only thread running through my life.</p>\n</blockquote>\n" }, { "alpha_fraction": 0.7292942404747009, "alphanum_fraction": 0.7385899424552917, "avg_line_length": 49.42647171020508, "blob_id": "dbfecd222105c1bee1f69e392a8ebb43c9e5d705", "content_id": "0730489e999044880e1242bc2a1b6bbb4a84498a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27845, "license_type": "no_license", "max_line_length": 502, "num_lines": 544, "path": "/_documents/the-iliad.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n The _Iliad_\ndescription: >\n Notes on the _Iliad_\ntype: note\n---\n\n## Background\n\nThe *Iliad* is the greatest Greek epic poem. The ancients believed that it was composed by the blind poet Homer. Modern scholars debate when it was composed and by whom, but most agree it was written around 700 BCE.\n\n## Structure and Outline\n\nThe poem is about 16,000 lines of hexameter verse in the ancient Greek, and is split into 24 books.\n\n1. Agamemnon and Achilles quarrel; Thetis appeals to Zeus\n2. Agamemnon tests the troops; the armies gather and are listed\n3. Helen reviews the champions; Paris and Menelaus duel\n4. Zeus and Hera bicker; the truce erupts in war\n5. Diomedes fights Aphrodite, Apollo, and Ares\n6. Hector returns to Troy; Diomedes and Glaucus become friends\n7. Ajax duels Hector to a draw; the Acheaens build a wall\n8. Zeus turns the tide; the Trojans camp outside their walls\n9. Agamemnon despairs; the embassy to Achilles fails\n10. Odysseus and Diomedes maraud through the Night\n11. Agamemnon and others are injured; Nestor’s plea to Patroclus\n12. Five Trojan battalions storm the wall; Hector breaks through\n13. Poseidon and the Aeantes’ defend the ships\n14. Hera distracts Zeus; Poseidon rallies; Ajax injures Hector\n15. Poseidon is dismissed; Apollo revives Hector and charges the ships\n16. The Myrmidons push back; Sarpedon dies; Patroclus dies\n17. Menelaus leads the fight for Patroclus’s body\n18. Thetis and Achilles mourn; Hephaestus forges new armor\n19. Agamemnon and Achilles make amends, mourn, and arm\n20. The Olympian gods arm; Achilles fights Aeneas then Hector\n21. Achilles fights the river; the gods fight each other\n22. Priam laments; Achilles and Athena kill Hector\n23. Patroclus’s burial and funeral games\n24. The gods help Priam retrieve Hector’s body; Hector is buried\n\n## The Gods\n\nSome gods are described as human-like while others are abstract. Gods are born, and humans can fight and harm them, as Diomedes does:\n\n<blockquote class=\"poetry\">\n<p>He gouged Aphrodite just where the wristbone joins the palms</p>\n<p>and immortal blood came flowing quickly from the goddess,</p>\n<p>the ichor that courses through their veins, the blessed gods—</p>\n<p>they eat no bread, they drink no shining wine, and so</p>\n<p>the gods are bloodless, so we call them deathless. <cite>(5.338–42)</cite></p>\n</blockquote>\n\nThe Greeks associate eating our food with mortality. This is seen in a number of other verses as well:\n\n<blockquote class=\"poetry\">\n<p>“No, my friend,</p>\n<p>I have no desire to fight the blithe immortals.</p>\n<p>But if you’re a man who eats the crops of the earth,</p>\n<p>a mortal born for death—here, come closer,</p>\n<p>the sooner you will meet your day to die!” <cite>(6.141–4)</cite></p>\n</blockquote>\n\nThere are passages that imply gods can be killed:\n\n<blockquote class=\"poetry\">\n<p>And despite the god’s undying lust for battle</p>\n<p>Ares might have wasted away there on the spot</p>\n<p>if the monster’s stepmother, beautiful Eriboea</p>\n<p>had not sent for Hermes, and out of the cauldron</p>\n<p>Hermes stole him away—the War-god breathing his last,</p>\n<p>all but broken down by the ruthless iron chains. <cite>(5.387–91)</cite></p>\n</blockquote>\n\nBut I think the gods were always thought to be deathless. What does it mean to be deathless? Humans that die go to Hades, gods are trapped in Tartarus… the two outcomes seem similar.\n\nIn the *Iliad,* the gods are involved with most important events and decisions. They drive the men to battle, plant ideas and dreams, guide or deflect arrows and spears, and control natural forces. Yet, despite being pervasive, Homer keeps the Greek gods largely hidden within natural forces or doppelgängers. Occasionally an individual hero recognizes and converses with them. There are a couple times when the gods appears to many humans. For example, when Apollo leads the charge against the Greeks:\n\n<blockquote class=\"poetry\">\n<p>And Apollo far in the lead, the god’s feet kicking</p>\n<p>the banks of the deep trench down with a god’s ease,</p>\n<p>tumbled earth in the pit between, bridging it with a dike</p>\n<p>immense and wide and long as a hurtling spear will fly</p>\n<p>when a man makes practice casts to test his strength.</p>\n<p>Holding formation now the Trojans rolled across it,</p>\n<p>Apollo heading them, gripping the awesome storm-shield</p>\n<p>and he tore that Argive rampart down with the same ease</p>\n<p>some boy at the seashore knocks sand castles down—</p>\n<p>he no sooner builds his playthings up, child’s play,</p>\n<p>than he wrecks them all with hands and kicking feet,</p>\n<p>just for the sport of it. <cite>(15.355–64)</cite></p>\n</blockquote>\n\nHomer’s portrayal of the gods reflects the fact that the gods don’t exist—the Greeks imagined them. Since the Greeks never saw the gods outside of dreams or visions, Homer’s listeners would find it unconvincing if he portrayed the gods more visibly.\n\nThis line of thinking also explains why the Greek gods were, and must be, so fickle. The Greeks believed their sacrifices and prayers swayed the gods to act with good will towards them, but they also recognized that their sacrifices were frequently ignored. Thus, Homer weaves a two-layered story of gods vying with one another and against fate while the humans below despair and wonder at the gods—in the same way the Greeks must have despaired at the random chance they believed to be a god.\n\nThe Greeks not only needed to explain the need for sacrifices, but also why they did not work. Those who believe in a single just god are in a similar situation—they need to explain how their god is just but evil exists.\n\n## Sacrifices\n\nThe Greeks believed their gods enjoyed and demanded sacrifices:\n\n<blockquote class=\"poetry\">\n<p>“I [Zeus] honor sacred Ilium most with my immortal heart:</p>\n<p>Priam and men of Priam who hurls the strong ash spear.</p>\n<p>Never once did my altar lack its share of victims,</p>\n<p>winecups tipped and the deep smoky savor. These,</p>\n<p>these are the gifts we claim—they are our rights.” <cite>(4.46–9)</cite></p>\n</blockquote>\n\nAnd there were some expectations that the gods would respect their sacrifices. For example after Zeus turns the tide of battle in Book 8, Agamemnon begins a prayer with this:\n\n<blockquote class=\"poetry\">\n<p>“Father Zeus, when did you ever strike a mighty king</p>\n<p>with such mad blindness—then tear away his glory? Not once,</p>\n<p>I swear, did I pass some handsome shrine of yours,</p>\n<p>sailing my oar-swept ship on our fatal voyage here,</p>\n<p>but on each I burned the fat and thighs of oxen,</p>\n<p>longing to raze Troy’s sturdy walls to the roots.” <cite>(8.234–41)</cite></p>\n</blockquote>\n\nThe most clearly described animal sacrifice occurs near the beginning of the *Iliad*:\n\n<blockquote class=\"poetry\">\n<p>At once the men arranged the sacrifice for Apollo,</p>\n<p>making the cattle ring his well-built altar,</p>\n<p>then they rinsed their hands and took up barley.</p>\n<p>Rising among them Chryses stretched his arms to the sky</p>\n<p>and prayed in a high resounding voice, “Hear me, Apollo!</p>\n<p>God of the silver bow who strides the walls of Chryse</p>\n<p>and Cilla sacrosanct—lord in power of Tenedos!</p>\n<p>If you honored me last time and heard my prayer</p>\n<p>and rained destruction down on all Achaea’s ranks,</p>\n<p>now bring my prayer to pass once more. Now, at last,</p>\n<p>driving this killing plague from the armies of Achaea!”</p>\n<br>\n<p>His prayer went up and Phoebus Apollo heard him.</p>\n<p>And soon as the men had prayed and flung the barley,</p>\n<p>first they lifted back the heads of the victims,</p>\n<p>slit their throats, skinned them and carved away</p>\n<p>the meat from the thighbones and wrapped them in fate,</p>\n<p>a double fold sliced clean and topped with strips of flesh.</p>\n<p>And the old man burned these over dried split wood</p>\n<p>and over the quarters poured out glistening wine</p>\n<p>while young men at his side held five-pronged forks.</p>\n<p>Once they had burned the bones and tasted the organs</p>\n<p>they cut the rest into pieces, pierced them with spits,</p>\n<p>roasted them to a turn and pulled them off the fire.</p>\n<p>The work done, the feast laid out, they ate well</p>\n<p>and no man’s hunger lacked a share of the banquet.</p>\n<p>When they had put aside desire for food and drink,</p>\n<p>the young me brimmed the mixing bowls with wine</p>\n<p>and tipping first drops for the god in every cup</p>\n<p>they poured full rounds for all. And all day long</p>\n<p>they appeased the god with song, raising a ringing hymn</p>\n<p>to the distant archer god who drives away the plague,</p>\n<p>those young Achaean warriors singing out his power,</p>\n<p>and Apollo listened, his great heart warm with joy. <cite>(1.447–75)</cite></p>\n</blockquote>\n\nPlagues and natural disasters were believed to be caused by gods. An example of this is seen at the beginning of the *Iliad*:\n\n<blockquote class=\"poetry\">\n<p>“So home we sail …</p>\n<p>if we can escape our death—if war and plague</p>\n<p>are joining forces now to crush the Argives.</p>\n<p>But wait: let us question a holy man,</p>\n<p>a prophet, even a man skilled with dreams—</p>\n<p>dreams as well can come our way from Zeus—</p>\n<p>come, someone tell us why Apollo rages so,</p>\n<p>whether he blames us for a vow we failed, or sacrifice.</p>\n<p>If only the god would share the smoky savor of lambs</p>\n<p>and full-grown goats, Apollo might be willing, still,</p>\n<p>somehow, to save us from this plague.” <cite>(1.58-67)</cite></p>\n</blockquote>\n\n## The Rage of Achilles\n\nTraditionally, the first word of an epic poem identifies its central theme:\n\n<blockquote class=\"poetry\">\n<p>Rage—Goddess, sing the rage of Peleus’ son Achilles,</p>\n<p>murderous, doomed, that cost the Achaeans countless losses,</p>\n<p>hurling down to the House of Death so many sturdy souls,</p>\n<p>great fighters’ souls, but made their bodies carrion,</p>\n<p>feasts for the dogs and birds,</p>\n<p>and the will of Zeus was moving towards its end.</p>\n<p>Begin, Muse, when the two first broke and clashed,</p>\n<p>Agamemnon lord of men and brilliant Achilles. <cite>(1.1–8)</cite></p>\n</blockquote>\n\nDuring most of the *Iliad,* Achilles wrath is directed at Agamemnon because he disgraced Achilles in front of all the Greeks by stealing his concubine, Briseis. It isn’t until book 18, when Achilles learns that Patroclus died, that his wrath is then re-directed towards Hector.\n\n<blockquote class=\"poetry\">\n<p>“Then let me die at once”—</p>\n<p>Achilles burst out, despairing—”since it was not my fate</p>\n<p>to save my dearest comrade from his death! Look,</p>\n<p>a world away from his fatherland he’s perished,</p>\n<p>lacking me, my fighting strength, to defend him.</p>\n<p>But now, since I shall not return to my fatherland …</p>\n<p>nor did I bring one ray of hope to my Patroclus,</p>\n<p>nor to the rest of all my steadfast comrades,</p>\n<p>countless ranks struck down by mighty Hector—</p>\n<p>No, no, here I sit by the ships …</p>\n<p>a useless, dead weight on the good green earth—</p>\n<p>I, no man my equal among the bronze-armed Achaeans,</p>\n<p>not in battle, only in wars of words that others win.</p>\n<p>If only strife could die from the lives of gods and men</p>\n<p>and anger that drives the sanest man to flare in outrage—</p>\n<p>bitter gall, sweeter than dripping streams of honey,</p>\n<p>that swarms in people’s chests and blinds like smoke—</p>\n<p>just like the anger Agamemnon king of men</p>\n<p>has roused within me now … Enough.</p>\n<p>Let bygones be bygones. Done is done.</p>\n<p>Despite my anguish I will beat it down,</p>\n<p>the fury mounting inside me, down by force.</p>\n<p>But now I’ll go and meet that murderer head-on,</p>\n<p>that Hector who destroyed the dearest life I know.” <cite>(18.96–115)</cite></p>\n</blockquote>\n\nAnd, after Achilles kills Hector, he is still not at peace. It isn’t until King Priam, willed by Zeus, visits Achilles to ransom for Hector’s body, that Achilles’ wrath seems to subside:\n\n<blockquote class=\"poetry\">\n<p>“Revere the gods, Achilles! Pity me in my own right,</p>\n<p>remember your own father! I deserve more pity …</p>\n<p>I have endured what no one on earth has ever done before—</p>\n<p>I put to my lips the hands of the man who killed my son.”</p>\n<br>\n<p>Those words stirred within Achilles a deep desire</p>\n<p>to grieve for his own father. Taking the old man’s hand</p>\n<p>he gently moved him back. And overpowered by memory</p>\n<p>both men gave way to grief. Priam wept freely</p>\n<p>for man-killing Hector, throbbing, crouching</p>\n<p>before Achilles’ feet as Achilles wept himself,</p>\n<p>now for his father, now for Patroclus once again,</p>\n<p>and their sobbing rose and fell throughout the house.</p>\n<p>Then, when brilliant Achilles had had his fill of tears</p>\n<p>and the longing for it had left his mind and body,</p>\n<p>he rose from his seat, raised the old man by the hand</p>\n<p>and filled with pity now for his gray head and gray beard,</p>\n<p>he spoke out winging words, flying straight to the heart:</p>\n<p>“Poor man, how much you’ve born—pain to break the spirit!” <cite>(24.503–18)</cite></p>\n</blockquote>\n\nSo, the *Iliad*, is in many ways a poem about the wrath of Achilles, which is lit in Book 1 and only extinguished towards the end of Book 24.\n\nSome interpret the *Iliad* as a poem about growth and moral progress—Achilles’ god-like wrath is humanized by Priam. Others see Achilles’ rage and general attitude as being consistent throughout the book.\n\n## War and Violence\n\nWar and violence permeate the *Iliad.* One of the first things a modern reader notices in the *Iliad* is that Homer provides the names of nearly every character that dies:\n\n<blockquote class=\"poetry\">\n<p>Who was the first he slaughtered, who the last,</p>\n<p>Hector the son of Priam, now Zeus gave him glory?</p>\n<p>Asaeus first, Autonous next and then Opites,</p>\n<p>Dolops, Clytius’ son, and Opheltius, Agelaus,</p>\n<p>Aesymnus and Orus, Hipponous staunch in combat.</p>\n<p>These were the Argive captains Hector killed <cite>(11.299–304)</cite></p>\n</blockquote>\n\nNone of the Argive captains were mentioned before or afterwards. It feels like Homer is giving them dignity and immortality to each man who died. There are 255 named deaths in the *Iliad.* Many die terribly:\n\n<blockquote class=\"poetry\">\n<p>Idomeneus skewered Erymas straight through the mouth,</p>\n<p>the merciless brazen spearpoint raking through,</p>\n<p>up under the brain to split his glistening skull—</p>\n<p>teeth shattered out, both eyes brimmed to the lids</p>\n<p>with a gush of blood and both nostrils spurting,</p>\n<p>mouth gaping, blowing convulsive sprays of blood</p>\n<p>and death’s dark cloud closed around his corpse. <cite>(16.345–50)</cite></p>\n</blockquote>\n\nThe frequency of deaths creates a dizzying sense of violence and terror. Often, Homer will provide some background about the man who is about to die. He also references the family who is left behind:\n\n<blockquote class=\"poetry\">\n<p>Never would he repay his loving parents now</p>\n<p>for the gift of rearing—his life cut short so soon,</p>\n<p>brought down by the spear of lionhearted Ajax. <cite>(17.302–3)</cite></p>\n</blockquote>\n\nPriam’s lament, as he watches Achilles sprint towards Hector down below the gates, is especially stirring:\n\n<blockquote class=\"poetry\">\n<p>Back, come back! Inside the walls, my boy!</p>\n<p>Rescue the men of Troy and the Trojan women—</p>\n<p>don’t hand the great glory to Peleus’ son,</p>\n<p>bereft of your own sweet life yourself. Pity me too!—</p>\n<p>still in my senses, true, but a harrowed, broken man</p>\n<p>marked out by doom—past the threshold of old age…</p>\n<p>and Father Zeus will waste me with a hideous fate,</p>\n<p>and after I’ve lived to look on so much horror!</p>\n<p>My sons laid low, my daughters dragged away</p>\n<p>and the treasure-chambers looted, helpless babies</p>\n<p>hurled to the earth in the red barbarity of war…</p>\n<p>my sons’ wives hauled off by the Argives’ bloody hands!</p>\n<p>And I, I last of all—the dogs before my doors</p>\n<p>will eat me raw, once some enemy brings me down</p>\n<p>with his sharp bronze sword or spits me with a spear,</p>\n<p>wrenching the life out of my body, yes, the very dogs</p>\n<p>I bred in my own halls to share my table, guard my gates—</p>\n<p>mad, rabid at heart they’ll lap their master’s blood</p>\n<p>and loll before my doors. <cite>(22.56–71)</cite></p>\n</blockquote>\n\n## Armor and Weapons\n\nEveryone in the *Iliad* is obsessed with armor and weapons. Armor provided protection and was valuable. It also proved your bravery in battle:\n\n<blockquote class=\"poetry\">\n<p>But the Cretan captain Idomeneus countered, “Spears?</p>\n<p>If it’s spears you want, you’ll find not one but twenty,</p>\n<p>all propped on my shelter’s shining inner wall:</p>\n<p>Trojan weapons, stripped from the men I kill.</p>\n<p>It’s not <em>my</em> way, I’d say, to fight at a distance,</p>\n<p>out of enemy range.</p>\n<p>So I take my plunder—spears, bossed shields,</p>\n<p>helmets and breastplates, gleaming, polished bright.” <cite>(13.259–65)</cite></p>\n</blockquote>\n\nWhen Patroclus leads the Myrmidons into battle, Achilles prays to Zeus for his safety and for his armor’s return:\n\n<blockquote class=\"poetry\">\n<p>“But once he repels the roaring onslaught from the ships</p>\n<p>let him come back to me and our fast fleet—unharmed—</p>\n<p>with all my armor round him, all our comrades</p>\n<p>fighting round my friend!” <cite>(16.246–8)</cite></p>\n</blockquote>\n\nAnd not too long after, Patroclus kills Sarpedon. And Sarpedon’s last words, shouted out to his comrade Glaucus, are:\n\n<blockquote class=\"poetry\">\n<p>“You’ll hang your head in shame—every day of your life—</p>\n<p>if the Argives strip my armor here at the anchored ships</p>\n<p>where I have gone down fighting. Hold on, full force—</p>\n<p>spur all our men to battle!” Death cut him short. <cite>(16.498–500)</cite></p>\n</blockquote>\n\nEven Ares strips his fallen enemies’ armor:\n\n<blockquote class=\"poetry\">\n<p>The god was just stripping giant Periphas bare—</p>\n<p>the Aeotolians’ best fighter, Ochesius’ noble son—</p>\n<p>the blood-smeared Ares was tearing off his gear … <cite>(5.842–4)</cite></p>\n</blockquote>\n\n## The Elite\n\nThe *Iliad* is almost exclusively focused on the heroes and commanders of the two armies. The “rank and file” are almost completely ignored.\n\nHere is an example from book 2, when Odysseus is turning back the soldiers after Agammemnon’s test:\n\n<blockquote>\n<p>When he caught some common soldier shouting out,</p>\n<p>he’d beat him with the scepter, dress him down:</p>\n<p>“You <em>fool</em>—sit still! Obey the commands of others,</p>\n<p>your superiors—you, you deserter, rank coward,</p>\n<p>you count for nothing, neither in war nor council.</p>\n<p>How can all Achaeans be masters here in Troy?</p>\n<p>Too many kings can ruin an army—mob rule!</p>\n<p>Let there be one commander, one master only,</p>\n<p>endowed by the son of crooked-minded Cronus</p>\n<p>with kingly scepter and royal rights of custom:</p>\n<p>whatever one man needs to lead his people well.”</p>\n</blockquote>\n\n## Similes\n\nHomer uses short and extended similes throughout the *Iliad.* Here are my favorite similes.\n\nWhen Diomedes asks Glaucus about his heritage, he begins his response with this beautiful simile:\n\n<blockquote class=\"poetry\">\n<p>Like the generations of leaves, the lives of mortal men.</p>\n<p>Now the wind scatters the old leaves across the earth,</p>\n<p>now the living timber bursts with the new buds</p>\n<p>and spring comes round again. And so with men:</p>\n<p>as one generation comes to life, another dies away. <cite>(6.146–9)</cite></p>\n</blockquote>\n\nHector returns to Troy to ask his mother to sacrifice to Athena and calm raging Diomedes. Homer describes his, and Paris’, return to the fight as follows:\n\n<blockquote class=\"poetry\">\n<p>Both men bent on combat, on they fought like wind</p>\n<p>when a god sends down some welcome blast to sailors</p>\n<p>desperate for it, worked to death at the polished oars,</p>\n<p>beating the heavy seas, their arms slack with the labor—</p>\n<p>so welcome that brace of men appeared to the Trojans</p>\n<p>desperate for their captains. <cite>(7.3–7)</cite></p>\n</blockquote>\n\nThere are many similes describing death. Here is a particularly powerful one:\n\n<blockquote class=\"poetry\">\n<p>As a garden poppy, burst into red bloom, bends,</p>\n<p>drooping its head to one side, weighed down</p>\n<p>by its full seeds and a sudden spring shower,</p>\n<p>so Gorgythion’s head fell limp over one shoulder,</p>\n<p>weighed down by his helmet. <cite>(8.306-9)</cite></p>\n</blockquote>\n\nThere are also many similes comparing fighting in battle to hunting animals. I believe this is the most powerful such simile:\n\n<blockquote class=\"poetry\">\n<p>Think how a lion, mauling the soft weak young</p>\n<p>of a running deer, clamped in his massive jaws,</p>\n<p>cracks their backbones with a snap—he’s stormed in,</p>\n<p>invading the lair to tear their tender hearts out</p>\n<p>and the mother doe, even if she’s close by,</p>\n<p>what can she do to save her fawns? She’s helpless—</p>\n<p>terrible trembling racks her body too—and suddenly</p>\n<p>off she bounds through the glades and the thick woods,</p>\n<p>drenched in sweat, leaping clear of the big cat’s pounce.</p>\n<p>So not a single Trojan could save those two from death,</p>\n<p>they fled themselves before the Argive charge. <cite>(11.113–22)</cite></p>\n</blockquote>\n\nMany similes liken war scenes to peacetime scenes:\n\n<blockquote class=\"poetry\">\n<p>Thick-and-fast as the snows that fall on a winter dawn</p>\n<p>when Zeus who rules the world brings on a blizzard,</p>\n<p>displaying to all mankind his weaponry of war…</p>\n<p>and he puts the winds to sleep, drifting on and on</p>\n<p>until he has shrouded over the mountains’ looming peaks</p>\n<p>and the headlands jutting sharp, the lowlands deep in grass</p>\n<p>and the rich plowed work of farming men, and the drifts fall</p>\n<p>on the gray salt surf and the harbors and down along the beaches</p>\n<p>and only breakers beating against the drifts can hold them off</p>\n<p>but all else on the earth they cover over, snows from the sky</p>\n<p>when Zeus comes storming down—now so thick-and-fast</p>\n<p>they volleyed rocks from both sides, some at the Trojans,</p>\n<p>some from Trojans against the Argives, salvos landing,</p>\n<p>the whole long rampart thundering under blows. <cite>(12.278–89)</cite></p>\n</blockquote>\n\nThis simile describes a beautiful scene:\n\n<blockquote class=\"poetry\">\n<p>As a stallion full-fed at the manger, stalled too long,</p>\n<p>breaking free of his tether gallops down the plain,</p>\n<p>out for his favorite plunge in a river’s cool currents,</p>\n<p>thundering in his pride—his head flung back, his mane</p>\n<p>streaming over his shoulders, sure and sleek in his glory,</p>\n<p>knees racing him on to the fields and stallion-haunts he loves—</p>\n<p>so Hector hurtled on, his legs driving, his knees pumping,</p>\n<p>spurring his reinsmen once he heard the god’s command. <cite>(15.262–8)</cite></p>\n</blockquote>\n\nI like this simile, because it makes me think of my wife—she likes to imagine we are in Paris or Rome or some romantic city.\n\n<blockquote class=\"poetry\">\n<p>Quick as a thought goes flashing through a man</p>\n<p>who’s traveled the world—”Ah to be there, or there!”—</p>\n<p>as his mind swarms with journeys, fresh desires—</p>\n<p>so quick in her eager flight flew noble Hera now</p>\n<p>and scaling steep Olympus went among the gods. <cite>(15.79–83)</cite></p>\n</blockquote>\n\nMany of Homer’s similes make surprising, but compelling comparisons, such as this simile to a horsefly—I had never thought of a horsefly as daring:\n\n<blockquote class=\"poetry\">\n<p>She put fresh strength in his back, spring in his knees</p>\n<p>and filled his heart with the horsefly’s raw daring—</p>\n<p>brush it away from a man’s flesh and back it comes,</p>\n<p>biting, attacking, crazed for sweet human blood. <cite>(17.570–3)</cite></p>\n</blockquote>\n\n## Other Interesting Quotes\n\nThe description of Nestor’s cup, and strange food:\n\n<blockquote class=\"poetry\">\n<p>First Hecamede pushed a table up toward them,</p>\n<p>handsome, sanded smooth, with blue enamel legs,</p>\n<p>and on it she set a basket, braided in bronze</p>\n<p>with onions in it, a relish for the drink,</p>\n<p>and pale gold honey along with barley meal,</p>\n<p>the grain’s blessed yield. And there in the midst</p>\n<p>the grand, glowing cup the old king brought from home,</p>\n<p>studded with golden nails, fitted with handles,</p>\n<p>four all told and two doves perched on each,</p>\n<p>heads bending to drink and made of solid gold</p>\n<p>and twin supports ran down to form the base.</p>\n<p>An average man would strain to lift it off the table</p>\n<p>when it was full, but Nestor, old as he was,</p>\n<p>could hoist it up with ease.</p>\n<p>In this cup the woman skilled as a goddess</p>\n<p>mixed them a strong drink with Pramnian wine,</p>\n<p>over it shredded goat cheese with bronze grater</p>\n<p>and scattered barley into it, glistening pure white,</p>\n<p>then invited them to drink when she had mulled it all. <cite>(11.626–41)</cite></p>\n</blockquote>\n\nThe Olympian trinity:\n\n<blockquote class=\"poetry\">\n<p>“Three brothers we are, sprung from Cronus,</p>\n<p>all of us brought to birth by Rhea—Zeus and I,</p>\n<p>Hades the third, lord of the dead beneath the earth.</p>\n<p>The world was split three ways. Each received his realm.</p>\n<p>When we shook the lots I drew the sea, my foaming eternal home,</p>\n<p>and Hades drew the land of the dead engulfed in haze and night</p>\n<p>and Zeus drew the heavens, the clouds and the high clear sky,</p>\n<p>but the earth and Olympus heights are common to us all.” <cite>(15.187–94)</cite></p>\n</blockquote>\n\nZeus’ comment about mankind, during the fight over Patroclus’ body:\n\n<blockquote class=\"poetry\">\n<p>“There is nothing alive more agonizing than man</p>\n<p>of all that breathe and crawl across the earth. <cite>(17.447–8)</cite></p>\n</blockquote>\n\nAchilles’ horse prophesies his death:\n\n<blockquote class=\"poetry\">\n<p>And Roan Beauty the horse with flashing hoofs</p>\n<p>spoke up from under the yoke, bowing his head low</p>\n<p>so his full mane came streaming down the yoke-pads</p>\n<p>down along the yoke to sweep the ground…</p>\n<p>The white-armed goddess Hera gave him voice:</p>\n<p>“Yes! we will save your life—this time too—</p>\n<p>master, mighty Achilles! But the day of death</p>\n<p>already hovers near, and we are not to blame</p>\n<p>but a great god <em>is</em> and the strong force of fate.” <cite>(19.404-10)</cite></p>\n</blockquote>\n\nWhen Zeus lets the gods back into the fray during the final battle, the world is shaken to its core:\n\n<blockquote class=\"poetry\">\n<p>The whole world quaked, the slopes of Ida with all her springs</p>\n<p>and all her peaks and the walls of Troy and all Achaea’s ships.</p>\n<p>And terror-struck in the underworld, Hades lord of the dead</p>\n<p>cringed and sprang from his throne and screamed shrill,</p>\n<p>fearing the god who rocks the ground above his realm,</p>\n<p>giant Poseidon, would burst the earth wide open now</p>\n<p>and lay bare to mortal men and immortal gods at last</p>\n<p>the houses of the dead—the dank, moldering horrors</p>\n<p>that fill the deathless gods themselves with loathing. <cite>(20.60-7)</cite></p>\n</blockquote>\n\n*All quotations are taken from Robert Fagle’s 1990 translation of the* Iliad. *Line numbers are approximate.*\n" }, { "alpha_fraction": 0.7724248766899109, "alphanum_fraction": 0.7754071950912476, "avg_line_length": 89.8125, "blob_id": "24bda5a4fb537b9405d85cb65da4f0742d15c392", "content_id": "c0b5595c6076b2d838e3d4e77a3d54f1c3cd88b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4395, "license_type": "no_license", "max_line_length": 456, "num_lines": 48, "path": "/_posts/2020-06-18-euthyphro-initial-impressions.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Initial Impression of _Euthyphro_\ndescription: >\n What is piety? Is it possible to define? Here are my first thoughts on the first of Plato’s dialogues I have read.\n---\n\nI just finished reading _Euthyphro_ and would like to collect my first impressions. It is the first of Plato’s dialogues that I have read, besides bits of the _Republic_ in college. It is amazing.\n\nSocrates runs into Euthyphro, a priest and prophet, at an Athenian court. He is suing his father for murdering someone who in turn murdered their slave. Socrates asks him what piety is, for surely he must know if he suing his own father! In the remainder of the dialogue they discuss the nature of piety. After attempting several definitions of the word, all of which Socrates dismantles, Euthyphro must leave since he is “in a hurry.”\n\nThroughout the discussion Socrates is very analytical. After they become stuck, having rejected a few definitions, he approaches the problem from a new angle by comparing piety and justice; if you can not solve a problem, compare it to other related problems. He also uses many examples and analogies; to understand what is meant by “caring for the gods” he considers horse breeders, hunters caring for their dogs, and “cattle-raisers.”\n\nTwo passages stuck out. I believe the first is famous:\n\n<blockquote class=\"prose\">\n<p>SOCRATES: Consider this: Is the pious loved by the gods because it is pious, or is it pious because it is loved by the god? <cite>(10a)</cite></p>\n</blockquote>\n\nIt is an important question, for if piety (or righteousness generally) exists apart from the gods, then one can imagine an absolute moral standard apart from the gods.\n\nThe second passage shows that Socrates thinks a mathematically simple definition of _piety_ is possible:\n\n<blockquote class=\"prose\">\n<p>SOCRATES: If the pious is part of the just, we must, it seems, find out what part of the just it is. Now if you asked me something of what we mentioned just now, such as what part of number is the even, and what number that is, I would say it is the number that is divisible into two equal, not unequal, parts. Or do you not think so?</p>\n<p>EUTHYPHRO: I do.</p>\n<p>SOCRATES: Try in this way to tell me what part of the just the pious is … <cite>(12d)</cite></p>\n</blockquote>\n\nI think Socrates is mistaken, and no simple definition is possible due to how language is produced and used. Euthyphro likely agrees, since after Socrates refutes several definitions, he says:\n\n<blockquote class=\"prose\">\n<p>EUTHYPHRO: I told you a short while ago, Socrates, that it is a considerable task to acquire any precise knowledge of these things, but, to put it simply, I say that if a man knows how to say and do what is pleasing to the gods at prayer and sacrifice, those are pious actions such as preserve both private houses and public affairs of state. The opposite of these pleasing actions are impious and overturn and destroy everything. <cite>(14b)</cite></p>\n</blockquote>\n\nPlato probably was aware of the counter-argument that _piety_ can not be defined. Given his belief in ideal forms, he must believe such definitions are possible, or at least that the forms could exist without being definable. I look forward to reading more of Plato’s works to learn his thoughts on this matter.\n\nThroughout the dialogue, Socrates’ earnest and self-degrading comments feel ironically insulting:\n\n<blockquote class=\"prose\">\n<p>SOCRATES: Yet you are younger than I by as much as you are wiser. As I say, you are making difficulties because of your wealth of wisdom. Pull yourself together, my dear sir, what I am saying is not difficult to grasp. <cite>(12a)</cite></p>\n</blockquote>\n\nEarly in the book Euthyphro says he has never foretold something that did not happen. How can such sophisticated thinkers also believe they can predict the future if (as seems to be the case) they couldn’t? It is unclear whether Socrates, like the doubting crowd Euthyphro complains about, is skeptical.\n\nIt is interesting that Euthyphro knows off-hand, as if it were public knowledge, that Socrates has “divine signs” that keep coming to him. What is this about? It is also strange that they seem distinct from Euthyphro’s prophecy.\n\n_Quotes are from G. M. A. Grube’s “Plato - Five Dialogues: Euthyphro, Apology, Crito, Meno, Phaedo, 2nd Ed.” published by Hackett Classics in 2002._\n" }, { "alpha_fraction": 0.7335243821144104, "alphanum_fraction": 0.7335243821144104, "avg_line_length": 16.450000762939453, "blob_id": "18e9ae5b7fcd8e030584891b0c89f52425d95b84", "content_id": "debaf387a8c6f4cd108a37b5036fb402a56d4825", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 349, "license_type": "no_license", "max_line_length": 32, "num_lines": 20, "path": "/documents/western-literature.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Timeline of Western Literature\ndescription: >\n Timeline of Western Literature\ntype: note\nstatus: incomplete\n---\n\n- Ancient Summerian Tales\n- The Enuma Elish\n- The Atrahasis\n- The Epic of Gilgamesh\n- The Egyptian Book of the Dead\n- Works and Days\n- The Theogony\n- The Iliad\n- The Odyssey\n- Pindar's Odes\n- Greek Lyric Poetry (Sappho)\n" }, { "alpha_fraction": 0.7426509857177734, "alphanum_fraction": 0.753105640411377, "avg_line_length": 46.82548904418945, "blob_id": "3b3124b6686920ed4c96409628b17ac2de22e6c2", "content_id": "f1fc1d887837197874fa24af999b097c6b244800", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24396, "license_type": "no_license", "max_line_length": 502, "num_lines": 510, "path": "/documents/the-iliad.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n The _Iliad_\ndescription: >\n Notes on the _Iliad_\ntype: note\n---\n\n## Background\n\nThe *Iliad* is the greatest Greek epic poem. The ancients believed that it was composed by the blind poet Homer. Modern scholars debate when it was composed and by whom, but most agree it was written around 700 BCE.\n\n## Structure and Outline\n\nThe poem is about 16,000 lines of hexameter verse in the ancient Greek, and is split into 24 books.\n\n1. Agamemnon and Achilles quarrel; Thetis appeals to Zeus\n2. Agamemnon tests the troops; the armies gather and are listed\n3. Helen reviews the champions; Paris and Menelaus duel\n4. Zeus and Hera bicker; the truce erupts in war\n5. Diomedes fights Aphrodite, Apollo, and Ares\n6. Hector returns to Troy; Diomedes and Glaucus become friends\n7. Ajax duels Hector to a draw; the Acheaens build a wall\n8. Zeus turns the tide; the Trojans camp outside their walls\n9. Agamemnon despairs; the embassy to Achilles fails\n10. Odysseus and Diomedes maraud through the Night\n11. Agamemnon and others are injured; Nestor's plea to Patroclus\n12. Five Trojan battalions storm the wall; Hector breaks through\n13. Poseidon and the Aeantes' defend the ships\n14. Hera distracts Zeus; Poseidon rallies; Ajax injures Hector\n15. Poseidon is dismissed; Apollo revives Hector and charges the ships\n16. The Myrmidons push back; Sarpedon dies; Patroclus dies\n17. Menelaus leads the fight for Patroclus's body\n18. Thetis and Achilles mourn; Hephaestus forges new armor\n19. Agamemnon and Achilles make amends, mourn, and arm\n20. The Olympian gods arm; Achilles fights Aeneas then Hector\n21. Achilles fights the river; the gods fight each other\n22. Priam laments; Achilles and Athena kill Hector\n23. Patroclus's burial and funeral games\n24. The gods help Priam retrieve Hector's body; Hector is buried\n\n## The Gods\n\nSome gods are described as human-like while others are abstract. Gods are born, and humans can fight and harm them, as Diomedes does:\n\n> He gouged Aphrodite just where the wristbone joins the palms\n> and immortal blood came flowing quickly from the goddess,\n> the ichor that courses through their veins, the blessed gods---\n> they eat no bread, they drink no shining wine, and so\n> the gods are bloodless, so we call them deathless.\n> ~ (5.338--42)\n\nThe Greeks associate eating our food with mortality. This is seen in a number of other verses as well:\n\n> \"No, my friend,\n> I have no desire to fight the blithe immortals.\n> But if you're a man who eats the crops of the earth,\n> a mortal born for death---here, come closer,\n> the sooner you will meet your day to die!\"\n> ~ (6.141--4)\n\nThere are passages that imply gods can be killed:\n\n> And despite the god's undying lust for battle\n> Ares might have wasted away there on the spot\n> if the monster's stepmother, beautiful Eriboea\n> had not sent for Hermes, and out of the cauldron\n> Hermes stole him away---the War-god breathing his last,\n> all but broken down by the ruthless iron chains.\n> ~ (5.387--91)\n\nBut I think the gods were always thought to be deathless. What does it mean to be deathless? Humans that die go to Hades, gods are trapped in Tartarus... the two outcomes seem similar.\n\nIn the *Iliad,* the gods are involved with most important events and decisions. They drive the men to battle, plant ideas and dreams, guide or deflect arrows and spears, and control natural forces. Yet, despite being pervasive, Homer keeps the Greek gods largely hidden within natural forces or doppelgängers. Occasionally an individual hero recognizes and converses with them. There are a couple times when the gods appears to many humans. For example, when Apollo leads the charge against the Greeks:\n\n> And Apollo far in the lead, the god's feet kicking\n> the banks of the deep trench down with a god's ease,\n> tumbled earth in the pit between, bridging it with a dike\n> immense and wide and long as a hurtling spear will fly\n> when a man makes practice casts to test his strength.\n> Holding formation now the Trojans rolled across it,\n> Apollo heading them, gripping the awesome storm-shield\n> and he tore that Argive rampart down with the same ease\n> some boy at the seashore knocks sand castles down---\n> he no sooner builds his playthings up, child's play,\n> than he wrecks them all with hands and kicking feet,\n> just for the sport of it.\n> ~ (15.355--64)\n\nHomer's portrayal of the gods reflects the fact that the gods don't exist---the Greeks imagined them. Since the Greeks never saw the gods outside of dreams or visions, Homer's listeners would find it unconvincing if he portrayed the gods more visibly.\n\nThis line of thinking also explains why the Greek gods were, and must be, so fickle. The Greeks believed their sacrifices and prayers swayed the gods to act with good will towards them, but they also recognized that their sacrifices were frequently ignored. Thus, Homer weaves a two-layered story of gods vying with one another and against fate while the humans below despair and wonder at the gods---in the same way the Greeks must have despaired at the random chance they believed to be a god.\n\nThe Greeks not only needed to explain the need for sacrifices, but also why they did not work. Those who believe in a single just god are in a similar situation---they need to explain how their god is just but evil exists.\n\n## Sacrifices\n\nThe Greeks believed their gods enjoyed and demanded sacrifices:\n\n> \"I [Zeus] honor sacred Ilium most with my immortal heart:\n> Priam and men of Priam who hurls the strong ash spear.\n> Never once did my altar lack its share of victims,\n> winecups tipped and the deep smoky savor. These,\n> these are the gifts we claim---they are our rights.\"\n> ~ (4.46--9)\n\nAnd there were some expectations that the gods would respect their sacrifices. For example after Zeus turns the tide of battle in Book 8, Agamemnon begins a prayer with this:\n\n> \"Father Zeus, when did you ever strike a mighty king\n> with such mad blindness---then tear away his glory? Not once,\n> I swear, did I pass some handsome shrine of yours,\n> sailing my oar-swept ship on our fatal voyage here,\n> but on each I burned the fat and thighs of oxen,\n> longing to raze Troy's sturdy walls to the roots.\"\n> ~ (8.234--41)\n\nThe most clearly described animal sacrifice occurs near the beginning of the *Iliad*:\n\n> At once the men arranged the sacrifice for Apollo,\n> making the cattle ring his well-built altar,\n> then they rinsed their hands and took up barley.\n> Rising among them Chryses stretched his arms to the sky\n> and prayed in a high resounding voice, \"Hear me, Apollo!\n> God of the silver bow who strides the walls of Chryse\n> and Cilla sacrosanct---lord in power of Tenedos!\n> If you honored me last time and heard my prayer\n> and rained destruction down on all Achaea's ranks,\n> now bring my prayer to pass once more. Now, at last,\n> driving this killing plague from the armies of Achaea!\"\n>\n> His prayer went up and Phoebus Apollo heard him.\n> And soon as the men had prayed and flung the barley,\n> first they lifted back the heads of the victims,\n> slit their throats, skinned them and carved away\n> the meat from the thighbones and wrapped them in fate,\n> a double fold sliced clean and topped with strips of flesh.\n> And the old man burned these over dried split wood\n> and over the quarters poured out glistening wine\n> while young men at his side held five-pronged forks.\n> Once they had burned the bones and tasted the organs\n> they cut the rest into pieces, pierced them with spits,\n> roasted them to a turn and pulled them off the fire.\n> The work done, the feast laid out, they ate well\n> and no man's hunger lacked a share of the banquet.\n> When they had put aside desire for food and drink,\n> the young me brimmed the mixing bowls with wine\n> and tipping first drops for the god in every cup\n> they poured full rounds for all. And all day long\n> they appeased the god with song, raising a ringing hymn\n> to the distant archer god who drives away the plague,\n> those young Achaean warriors singing out his power,\n> and Apollo listened, his great heart warm with joy.\n> ~ (1.447--75)\n\nPlagues and natural disasters were believed to be caused by gods. An example of this is seen at the beginning of the *Iliad*:\n\n> \"So home we sail ...\n> if we can escape our death---if war and plague\n> are joining forces now to crush the Argives.\n> But wait: let us question a holy man,\n> a prophet, even a man skilled with dreams---\n> dreams as well can come our way from Zeus---\n> come, someone tell us why Apollo rages so,\n> whether he blames us for a vow we failed, or sacrifice.\n> If only the god would share the smoky savor of lambs\n> and full-grown goats, Apollo might be willing, still,\n> somehow, to save us from this plague.\"\n> ~ (1.58-67)\n\n## The Rage of Achilles\n\nTraditionally, the first word of an epic poem identifies its central theme:\n\n> Rage---Goddess, sing the rage of Peleus' son Achilles,\n> murderous, doomed, that cost the Achaeans countless losses,\n> hurling down to the House of Death so many sturdy souls,\n> great fighters' souls, but made their bodies carrion,\n> feasts for the dogs and birds,\n> and the will of Zeus was moving towards its end.\n> Begin, Muse, when the two first broke and clashed,\n> Agamemnon lord of men and brilliant Achilles.\n> ~ (1.1--8)\n\nDuring most of the *Iliad,* Achilles wrath is directed at Agamemnon because he disgraced Achilles in front of all the Greeks by stealing his concubine, Briseis. It isn't until book 18, when Achilles learns that Patroclus died, that his wrath is then re-directed towards Hector.\n\n> \"Then let me die at once\"---\n> Achilles burst out, despairing---\"since it was not my fate\n> to save my dearest comrade from his death! Look,\n> a world away from his fatherland he's perished,\n> lacking me, my fighting strength, to defend him.\n> But now, since I shall not return to my fatherland ...\n> nor did I bring one ray of hope to my Patroclus,\n> nor to the rest of all my steadfast comrades,\n> countless ranks struck down by mighty Hector---\n> No, no, here I sit by the ships ...\n> a useless, dead weight on the good green earth---\n> I, no man my equal among the bronze-armed Achaeans,\n> not in battle, only in wars of words that others win.\n> If only strife could die from the lives of gods and men\n> and anger that drives the sanest man to flare in outrage---\n> bitter gall, sweeter than dripping streams of honey,\n> that swarms in people's chests and blinds like smoke---\n> just like the anger Agamemnon king of men\n> has roused within me now ... Enough.\n> Let bygones be bygones. Done is done.\n> Despite my anguish I will beat it down,\n> the fury mounting inside me, down by force.\n> But now I'll go and meet that murderer head-on,\n> that Hector who destroyed the dearest life I know.\"\n> ~ (18.96--115)\n\nAnd, after Achilles kills Hector, he is still not at peace. It isn't until King Priam, willed by Zeus, visits Achilles to ransom for Hector's body, that Achilles' wrath seems to subside:\n\n> \"Revere the gods, Achilles! Pity me in my own right,\n> remember your own father! I deserve more pity ...\n> I have endured what no one on earth has ever done before---\n> I put to my lips the hands of the man who killed my son.\"\n>\n> Those words stirred within Achilles a deep desire\n> to grieve for his own father. Taking the old man's hand\n> he gently moved him back. And overpowered by memory\n> both men gave way to grief. Priam wept freely\n> for man-killing Hector, throbbing, crouching\n> before Achilles' feet as Achilles wept himself,\n> now for his father, now for Patroclus once again,\n> and their sobbing rose and fell throughout the house.\n> Then, when brilliant Achilles had had his fill of tears\n> and the longing for it had left his mind and body,\n> he rose from his seat, raised the old man by the hand\n> and filled with pity now for his gray head and gray beard,\n> he spoke out winging words, flying straight to the heart:\n> \"Poor man, how much you've born---pain to break the spirit!\"\n> ~ (24.503--18)\n\nSo, the *Iliad*, is in many ways a poem about the wrath of Achilles, which is lit in Book 1 and only extinguished towards the end of Book 24.\n\nSome interpret the *Iliad* as a poem about growth and moral progress---Achilles' god-like wrath is humanized by Priam. Others see Achilles' rage and general attitude as being consistent throughout the book.\n\n## War and Violence\n\nWar and violence permeate the *Iliad.* One of the first things a modern reader notices in the *Iliad* is that Homer provides the names of nearly every character that dies:\n\n> Who was the first he slaughtered, who the last,\n> Hector the son of Priam, now Zeus gave him glory?\n> Asaeus first, Autonous next and then Opites,\n> Dolops, Clytius' son, and Opheltius, Agelaus,\n> Aesymnus and Orus, Hipponous staunch in combat.\n> These were the Argive captains Hector killed\n> ~ (11.299--304)\n\nNone of the Argive captains were mentioned before or afterwards. It feels like Homer is giving them dignity and immortality to each man who died. There are 255 named deaths in the *Iliad.* Many die terribly:\n\n> Idomeneus skewered Erymas straight through the mouth,\n> the merciless brazen spearpoint raking through,\n> up under the brain to split his glistening skull---\n> teeth shattered out, both eyes brimmed to the lids\n> with a gush of blood and both nostrils spurting,\n> mouth gaping, blowing convulsive sprays of blood\n> and death's dark cloud closed around his corpse.\n> ~ (16.345--50)\n\nThe frequency of deaths creates a dizzying sense of violence and terror. Often, Homer will provide some background about the man who is about to die. He also references the family who is left behind:\n\n> Never would he repay his loving parents now\n> for the gift of rearing---his life cut short so soon,\n> brought down by the spear of lionhearted Ajax.\n> ~ (17.302--3)\n\nPriam's lament, as he watches Achilles sprint towards Hector down below the gates, is especially stirring:\n\n> Back, come back! Inside the walls, my boy!\n> Rescue the men of Troy and the Trojan women---\n> don't hand the great glory to Peleus' son,\n> bereft of your own sweet life yourself. Pity me too!---\n> still in my senses, true, but a harrowed, broken man\n> marked out by doom---past the threshold of old age...\n> and Father Zeus will waste me with a hideous fate,\n> and after I've lived to look on so much horror!\n> My sons laid low, my daughters dragged away\n> and the treasure-chambers looted, helpless babies\n> hurled to the earth in the red barbarity of war...\n> my sons' wives hauled off by the Argives' bloody hands!\n> And I, I last of all---the dogs before my doors\n> will eat me raw, once some enemy brings me down\n> with his sharp bronze sword or spits me with a spear,\n> wrenching the life out of my body, yes, the very dogs\n> I bred in my own halls to share my table, guard my gates---\n> mad, rabid at heart they'll lap their master's blood\n> and loll before my doors.\n> ~ (22.56--71)\n\n## Armor and Weapons\n\nEveryone in the *Iliad* is obsessed with armor and weapons. Armor provided protection and was valuable. It also proved your bravery in battle:\n\n> But the Cretan captain Idomeneus countered, \"Spears?\n> If it's spears you want, you'll find not one but twenty,\n> all propped on my shelter's shining inner wall:\n> Trojan weapons, stripped from the men I kill.\n> It's not *my* way, I'd say, to fight at a distance,\n> out of enemy range.\n> So I take my plunder---spears, bossed shields,\n> helmets and breastplates, gleaming, polished bright.\"\n> ~ (13.259--65)\n\nWhen Patroclus leads the Myrmidons into battle, Achilles prays to Zeus for his safety and for his armor's return:\n\n> \"But once he repels the roaring onslaught from the ships\n> let him come back to me and our fast fleet---unharmed---\n> with all my armor round him, all our comrades\n> fighting round my friend!\"\n> ~ (16.246--8)\n\nAnd not too long after, Patroclus kills Sarpedon. And Sarpedon's last words, shouted out to his comrade Glaucus, are:\n\n> \"You'll hang your head in shame---every day of your life---\n> if the Argives strip my armor here at the anchored ships\n> where I have gone down fighting. Hold on, full force---\n> spur all our men to battle!\" Death cut him short.\n> ~ (16.498--500)\n\nEven Ares strips his fallen enemies' armor:\n\n> The god was just stripping giant Periphas bare---\n> the Aeotolians' best fighter, Ochesius' noble son---\n> the blood-smeared Ares was tearing off his gear ...\n> ~ (5.842--4)\n\n## The Elite\n\nThe *Iliad* is almost exclusively focused on the heroes and commanders of the two armies. The \"rank and file\" are almost completely ignored.\n\nHere is an example from book 2, when Odysseus is turning back the soldiers after Agammemnon's test:\n\n> When he caught some common soldier shouting out,\n> he'd beat him with the scepter, dress him down:\n> \"You _fool_---sit still! Obey the commands of others,\n> your superiors---you, you deserter, rank coward,\n> you count for nothing, neither in war nor council.\n> How can all Achaeans be masters here in Troy?\n> Too many kings can ruin an army---mob rule!\n> Let there be one commander, one master only,\n> endowed by the son of crooked-minded Cronus\n> with kingly scepter and royal rights of custom:\n> whatever one man needs to lead his people well.\"\n\n## Similes\n\nHomer uses short and extended similes throughout the *Iliad.* Here are my favorite similes.\n\nWhen Diomedes asks Glaucus about his heritage, he begins his response with this beautiful simile:\n\n> Like the generations of leaves, the lives of mortal men.\n> Now the wind scatters the old leaves across the earth,\n> now the living timber bursts with the new buds\n> and spring comes round again. And so with men:\n> as one generation comes to life, another dies away.\n> ~ (6.146--9)\n\nHector returns to Troy to ask his mother to sacrifice to Athena and calm raging Diomedes. Homer describes his, and Paris', return to the fight as follows:\n\n> Both men bent on combat, on they fought like wind\n> when a god sends down some welcome blast to sailors\n> desperate for it, worked to death at the polished oars,\n> beating the heavy seas, their arms slack with the labor—\n> so welcome that brace of men appeared to the Trojans\n> desperate for their captains.\n> ~ (7.3--7)\n\nThere are many similes describing death. Here is a particularly powerful one:\n\n> As a garden poppy, burst into red bloom, bends,\n> drooping its head to one side, weighed down\n> by its full seeds and a sudden spring shower,\n> so Gorgythion's head fell limp over one shoulder,\n> weighed down by his helmet.\n> ~ (8.306-9)\n\nThere are also many similes comparing fighting in battle to hunting animals. I believe this is the most powerful such simile:\n\n> Think how a lion, mauling the soft weak young\n> of a running deer, clamped in his massive jaws,\n> cracks their backbones with a snap---he's stormed in,\n> invading the lair to tear their tender hearts out\n> and the mother doe, even if she's close by,\n> what can she do to save her fawns? She's helpless---\n> terrible trembling racks her body too---and suddenly\n> off she bounds through the glades and the thick woods,\n> drenched in sweat, leaping clear of the big cat's pounce.\n> So not a single Trojan could save those two from death,\n> they fled themselves before the Argive charge.\n> ~ (11.113--22)\n\nMany similes liken war scenes to peacetime scenes:\n\n> Thick-and-fast as the snows that fall on a winter dawn\n> when Zeus who rules the world brings on a blizzard,\n> displaying to all mankind his weaponry of war...\n> and he puts the winds to sleep, drifting on and on\n> until he has shrouded over the mountains' looming peaks\n> and the headlands jutting sharp, the lowlands deep in grass\n> and the rich plowed work of farming men, and the drifts fall\n> on the gray salt surf and the harbors and down along the beaches\n> and only breakers beating against the drifts can hold them off\n> but all else on the earth they cover over, snows from the sky\n> when Zeus comes storming down---now so thick-and-fast\n> they volleyed rocks from both sides, some at the Trojans,\n> some from Trojans against the Argives, salvos landing,\n> the whole long rampart thundering under blows.\n> ~ (12.278--89)\n\nThis simile describes a beautiful scene:\n\n> As a stallion full-fed at the manger, stalled too long,\n> breaking free of his tether gallops down the plain,\n> out for his favorite plunge in a river's cool currents,\n> thundering in his pride---his head flung back, his mane\n> streaming over his shoulders, sure and sleek in his glory,\n> knees racing him on to the fields and stallion-haunts he loves—\n> so Hector hurtled on, his legs driving, his knees pumping,\n> spurring his reinsmen once he heard the god's command.\n> ~ (15.262--8)\n\nI like this simile, because it makes me think of my wife---she likes to imagine we are in Paris or Rome or some romantic city.\n\n> Quick as a thought goes flashing through a man\n> who's traveled the world---\"Ah to be there, or there!\"---\n> as his mind swarms with journeys, fresh desires---\n> so quick in her eager flight flew noble Hera now\n> and scaling steep Olympus went among the gods.\n> ~ (15.79--83)\n\nMany of Homer's similes make surprising, but compelling comparisons, such as this simile to a horsefly---I had never thought of a horsefly as daring:\n\n> She put fresh strength in his back, spring in his knees\n> and filled his heart with the horsefly's raw daring---\n> brush it away from a man's flesh and back it comes,\n> biting, attacking, crazed for sweet human blood.\n> ~ (17.570--3)\n\n## Other Interesting Quotes\n\nThe description of Nestor's cup, and strange food:\n\n> First Hecamede pushed a table up toward them,\n> handsome, sanded smooth, with blue enamel legs,\n> and on it she set a basket, braided in bronze\n> with onions in it, a relish for the drink,\n> and pale gold honey along with barley meal,\n> the grain's blessed yield. And there in the midst\n> the grand, glowing cup the old king brought from home,\n> studded with golden nails, fitted with handles,\n> four all told and two doves perched on each,\n> heads bending to drink and made of solid gold\n> and twin supports ran down to form the base.\n> An average man would strain to lift it off the table\n> when it was full, but Nestor, old as he was,\n> could hoist it up with ease.\n> In this cup the woman skilled as a goddess\n> mixed them a strong drink with Pramnian wine,\n> over it shredded goat cheese with bronze grater\n> and scattered barley into it, glistening pure white,\n> then invited them to drink when she had mulled it all.\n> ~ (11.626--41)\n\nThe Olympian trinity:\n\n> \"Three brothers we are, sprung from Cronus,\n> all of us brought to birth by Rhea---Zeus and I,\n> Hades the third, lord of the dead beneath the earth.\n> The world was split three ways. Each received his realm.\n> When we shook the lots I drew the sea, my foaming eternal home,\n> and Hades drew the land of the dead engulfed in haze and night\n> and Zeus drew the heavens, the clouds and the high clear sky,\n> but the earth and Olympus heights are common to us all.\"\n> ~ (15.187--94)\n\nZeus' comment about mankind, during the fight over Patroclus' body:\n\n> \"There is nothing alive more agonizing than man\n> of all that breathe and crawl across the earth.\n> ~ (17.447--8)\n\nAchilles' horse prophesies his death:\n\n> And Roan Beauty the horse with flashing hoofs\n> spoke up from under the yoke, bowing his head low\n> so his full mane came streaming down the yoke-pads\n> down along the yoke to sweep the ground...\n> The white-armed goddess Hera gave him voice:\n> \"Yes! we will save your life---this time too---\n> master, mighty Achilles! But the day of death\n> already hovers near, and we are not to blame\n> but a great god *is* and the strong force of fate.\"\n> ~ (19.404-10)\n\nWhen Zeus lets the gods back into the fray during the final battle, the world is shaken to its core:\n\n> The whole world quaked, the slopes of Ida with all her springs\n> and all her peaks and the walls of Troy and all Achaea's ships.\n> And terror-struck in the underworld, Hades lord of the dead\n> cringed and sprang from his throne and screamed shrill,\n> fearing the god who rocks the ground above his realm,\n> giant Poseidon, would burst the earth wide open now\n> and lay bare to mortal men and immortal gods at last\n> the houses of the dead---the dank, moldering horrors\n> that fill the deathless gods themselves with loathing.\n> ~ (20.60-7)\n\n*All quotations are taken from Robert Fagle's 1990 translation of the* Iliad. *Line numbers are approximate.*\n" }, { "alpha_fraction": 0.7855660915374756, "alphanum_fraction": 0.7873510718345642, "avg_line_length": 96.31925201416016, "blob_id": "e5b7314cd86251447728d747bb19213c938438a5", "content_id": "03f3ba912ab04170584bd59ce473966c086e31d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 20729, "license_type": "no_license", "max_line_length": 871, "num_lines": 213, "path": "/documents/the-big-picture.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n \"The Big Picture\" by Sean Carroll\ndescription: >\n Notes on \"The Big Picture\" by Sean Carroll\ntype: note\n---\n\n## Part One: Cosmos\n\nCarroll begins the book by proposing a philosophical framework he calls poetic naturalism.\n\nNaturalism:\n\n1. There is only one world, the natural world.\n2. The world evolves according to unbroken patterns, the laws of nature.\n3. The only reliable way of learning about the world is by observing it.\n\nThe poetic aspect comes to the fore when we start talking about the world:\n\n1. There are many ways of talking about the world.\n2. All good ways of talking must be consistent with one another and with the world.\n3. Our purposes in the moment determine the best way of talking.\n\nThe poetic component is a recognition that many human concepts, such as person, cause, choice, reason, justice, morality, and meaning, while not *fundamental* are still *real* and are worthy of our consideration. There is also a warning that we should not apply these higher-level concepts in inappropriate ways.\n\nCarrol's discussion of determinism and free-will is a good example of how poetic naturalism combines deep ontological truths with everyday language:\n\n> [Laplace] realized that there was a simple answer to the question \"What determines what will happen next?\" And the answer is \"The state of the universe right now.\" ...\n>\n> We know that the quantum state of a system, left alone, evolves in a perfectly deterministic fashion, free even of the rare but annoying examples of non-determinism that we can find in classical mechanics. But when we *observe* a system, it seems to behave randomly, rather than deterministically. ...\n>\n> The momentary or Laplacian nature of physical evolution doesn't have much relevance for the choices we face in our everyday lives. For poetic naturalism, the situation is clear. There is one way of talking about the universe that describes it as elementary particles or quantum states, in which Laplace holds sway and what happens next depends only on the state of the system right now. There is also another way of talking about it, where we zoom out a bit and introduce categories like \"people\" and \"choices.\" Unlike our best theory of planets or pendulums, our best theories of human behavior are not deterministic. We don't know any way to predict what a person will do based on what we can readily observe about their current state. Whether we think of human behavior as determined depends on what we know.\n> = (chpt. 4)\n\nThus, if you ask a poetic naturalist \"do humans have free-will,\" they would reply \"fundamentally, no, but the words free-will, choice, and person are useful everyday descriptions of reality.\"\n\nCarroll's presentation of determinism in Chapter 4 is oversimplified, although he does discuss the topic in more depth later in the book. I believe his claim that the world is deterministic is only true within one of several interpretations of quantum mechanics. There is no scientific consensus as to whether the universe is deterministic or not. A great deal of debate still surrounds the so-called \"collapse of the wave function\" and the \"measurement problem.\"\n\nThe Copenhagen interpretation of quantum mechanics says that physical systems do not generally have definite properties prior to being \"measured,\" and only the act of measuring them causes them to taken on certain states. The Copenhagen interpretation has several problems.\n\nThe concept of the \"system\" and the \"surroundings\" are useful for modeling reality and writing equations for small parts of it, but they are not fundamental to our ontology. Thus, what does it mean to say the system is deterministic except when you observe it? We want to know whether the entire universe is deterministic or not. If there are parts of the universe that are not deterministic, even only occasionally when we \"observer\" them, then the entire universe is not deterministic. Determinism is an all-or-nothing phenomena.\n\nCould we consider the entire universe as \"the system,\" such that there is no outside observer who could introduce randomness by \"collapsing the wave function\"? If this is possible then why does the act of dividing the universe into system and surroundings introduce randomness? It would appear that it can not.\n\nOne alternative to the Copenhagen interpretation is put forward by proponents of quantum decoherence. In this way of thinking, the \"collapse of the wave function\" and the \"randomness\" involved are simply useful ways of speaking about our incomplete knowledge of the environment's very complicated wave function. Thus, there is no randomness involved. Quantum decoherence avoids making \"measurements\" and the \"system\" part of our ontology, which I find convincing. Quantum decoherence results in a deterministic universe.\n\nOther alternatives to the Copenhagen interpretation exist, such as the objective-collapse theories, which may or may not result in a deterministic universe.\n\nThus, Carroll conveniently presents his minority-view as if it were the consensus of the scientific community. It wouldn't surprise me if he does this elsewhere in his book.\n\nI enjoyed Carroll's discussion about the arrow of time:\n\n> For every way that a system can evolve forward in time in accordance with the laws of physics, there is another allowed evolution that is just \"running the system backward in time.\" There is nothing in the underlying laws that says things can evolve in one direction in time but not the other. Physical motions, to the best of our understanding, are *reversible*. Both directions of time are on an equal footing.\n>\n> If there is a purported symmetry between past and future, why do so many everyday processes occur only forward and never backwards?\n>\n> Boltzmann and his colleagues argued that we could understand entropy as a feature of how atoms are arranged inside different systems. Rather than thinking of heat and entropy as distinct kinds of things, obeying their own laws of nature, we can think of them as properties of systems made of atoms, and derive those rules from the Newtonian mechanics that applies to everything in the universe. Heat and entropy, in other words, are convenient *ways of talking* about atoms.\n>\n> Given that, Boltzmann suggested that we could identify the entropy of a system with the [logarithm of the] number of different states that would be macroscopically indistinguishable from the state it is actually in. A low-entropy configuration is one where relatively few states would look that way, while a high-entropy one corresponds to many possible states. There are many ways to arrange molecules of cream and coffee so that they look all mixed together; there are far fewer arrangements where all of the cream is on the top and all of the coffee on the bottom.\n>\n> With Boltzmann's definition in hand, it makes complete sense that entropy tends to increase over time. The reason is simple: there are far more states with high entropy than states with low entropy. If you start in a low-entropy configuration and simply evolve in almost any direction, your entropy is extraordinary likely to increase. When the entropy of a system is as high as it can get, we say that the system is in *equilibrium*. In equilibrium, time has no arrow.\n>\n> What Boltzmann successfully explained is why, given the entropy of the universe today, it's very likely to be higher-entropy tomorrow. The problem is that, because the underlying rules of Newtonian mechanics don't distinguish between past and future, precisely the same analysis should predict that the entropy was higher *yesterday*, as well. Nobody thinks the entropy was higher in the past, so we have to add something to our picture.\n>\n> The thing we need to add is an assumption about the initial condition of the observable universe, namely, that it was in a very low-entropy state.\n>\n> What we know is that this initially low entropy is responsible for the \"thermodynamic\" arrow of time, the one that says entropy was lower towards the past and higher toward the future. Amazingly, it seems that this property of entropy is responsible for *all* of the differences between past and future that we know about. Memory, aging, cause and effect---all can be traced to the second law of thermodynamics and in particular to the fact that entropy used to be low in the past.\n> = (chpt. 7)\n\nIt is interesting to consider that \"cause and effect\" are not fundamental entities---they are just useful ways of speaking about reality, like entropy and heat are. Carroll mentions a useful way of defining a \"cause\":\n\n> We can make sense of statements like \"A causes B\" by thinking of different possible worlds: in particular, worlds that were essentially the same except for whether the event A actually occurred. Then, if we see that B occurs in all the worlds where A occurred, and B does not occur when A does not occur, it's safe to say \"A causes B.\"\n> = (chpt. 8)\n\n## Part Two: Understanding\n\nPart two of *The Big Picture* is a summary of Carroll's epistemological system, beginning with Bayesian reasoning.\n\n Bayes's theory can be understood as a generalization of contraposition. In propositional logic, where propositions are either true or false, we have:\n\n```\n(~H -> ~E) -> (E -> H)\n```\n\nBayes's theorem generalizes contraposition for the situation where propositions have a \"probability\" or \"degree of belief\". Here is Bayes's theorem:\n\n```\nP(H|E) = P(H)*P(E|H)/P(E)\n = P(H)*P(E|H)/[P(H)*P(E|H) + P(~H)*P(E|~H)]\n```\n\nBayesian reasoning, while interesting, must be a smaller part of one's epistemological system then Carroll presents it to be. There are many short-comings with Bayesian reasoning that Carroll does not consider, but which I believe are important.\n\n- We determine our prior beliefs, `P(H)`, and our likelihoods, `P(E|H)` using other beliefs---thus our beliefs form a recursive web which does not fit into a clean linear progression from initial belief to final belief as we gather new evidence.\n- How do we decide what hypotheses to consider?\n- Our hypotheses rarely form a clean partition of the space of beliefs, unless restrict ourselves to `H` and `~H`.\n- It is not usually possible to consider all of the evidence we have available, and thus we must rely on second hand accounts and other forms of knowledge besides observations from the real world.\n\nOne of the most intriguing and useful ideas presented is:\n\n> Evidence that favors one alternative automatically disfavors others. ... The converse is also true: if some observation would have favored one theory, but we obtained the opposite of that observation, that result necessarily decreases our credence for the theory.\n\nThis idea is useful, because, if we are considering a hypothesis, H, we can imagine evidence, E, which would make this hypothesis more likely to be true. If this evidence doesn't exist, we can take this as evidence that the hypothesis is not true. Performing thought experiments like this is not particularly difficult. E.g., imagine evidence that would support the hypothesis that \"An all-powerful loving god exists?\" Now, consider which of this evidence does exist, and what evidence doesn't?\n\nI like his analogy of \"planets of belief.\" This analogy helps one visualize the recursive nature of belief and the unavoidable interconnection between epistemology and metaphysics.\n\nI also like (and agree with) Carroll's distinction between faith and reason:\n\n> You will sometimes hear the claim that even science is based on a kind of \"faith,\" for example, in the reliability of our experimental data or in the existence of unbreakable physical laws. That is wrong. As part of the practice of science, we certainly make *assumptions*---our sense data is giving us roughly reliable information about the world, simple explanations are preferable to complex ones, we are not brains in vats, and so forth. But we don't have \"faith\" in those assumptions; they are components of our planets of belief, but they are always subject to revision and improvement and even, if necessary, outright rejection. By its nature, science needs to be completely open to the actual operation of the world, and that means that we stand ready to discard any idea that is no longer useful, no matter how cherished and central it may once have seemed.\n> = (chpt. 15)\n\n## Part Three: Essence\n\nCarroll claims, in Chapter 23, that:\n\n> The laws of physics underlying everyday life are completely known.\n\nThe logic behind our audacious claim is simple:\n\n1. Everything we know says that quantum field theory is the correct framework for describing physics underlying everyday life.\n2. The rules of quantum field theory imply that there can't be any new particles, forces, or interactions that could be relevant to our everyday lives. We've found them all.\n\nNote he is not claiming that we know all there is to know about physics, just that we know everything there is to know that could affect our everyday life.\n\nScience will not be able to explain why the universe exists.\n\nDid the universe always exist, or did it have a beginning? Science also can not tell us about this, since we can not see past the big bang. But poetic naturalism does have some useful things to say about this topic. In particular, it provides a refutation of the arguments from first cause:\n\n> Talking about \"causes\" is not the right vocabulary to use when thinking about how the universe works at a deep level. We need to be asking ourselves not whether the universe had a cause but whether having a first moment in time is compatible with the laws of nature.\n\nPopping into existence and \"having a beginning\" are not the same thing. Popping into existence implies there was a priori moment where there was nothing, but we are talking the entire universe---thus there could not have been a prior moment, rather, the first moment is the one without a prior moment.\n\nEveryday objects don't pop into existence because doing so would break the laws of physics. There is nothing about the laws of physics that precludes it having a first moment.\n\nSome people argue \"sure, you can say that physics doesn't preclude the universe popping into existence, but there are metaphysical arguments which are more general than physics which preclude this!\" But what are your arguments for the metaphysical principle that things (including the universe) can't pop into existence? Isn't this begging the question? While we don't know why it did, we also don't have good reasons to think that it couldn't have.\n\n## Part Four: Complexity\n\nTheodosius Dobzhansky: \"Nothing in biology makes sense except in the light of evolution.\"\n\nEntropy, statistically speaking, always increases for a closed system. Thus, the entropy of the universe is increasing.\n\nComplexity, in some systems with certain properties, can increase and then decrease over time.\n\nMixing milk and coffee together is an example of a system whose complexity increases and then decreases; at the start, the coffee and milk are well separated. There is low entropy and low complexity. Then, as the milk and coffee are mixed, the entropy increases, as does the complexity---there are beautiful and subtle swirls of milk with interesting structures. Finally, once the coffee is mixed enough, the milk and coffee are completely mixed and the entropy has increased further, yet the complexity has decreased.\n\nComplexity is not as well defined as entropy is, although both are not fundamental concepts.\n\nPerhaps humans are like the swirls of the coffee in the coffee cup of the universe?\n\nThe fine-tuning argument for the existence of a god is:\n\n- Slightly changing many physical constants would result in life not being able to exist\n- Life exists\n- The best explanation for the tuned values of the physical constants is a god who wanted life to exist.\n\nCarroll believes this is \"probably the most respectable argument in favor of theism ... but it's still not a very good argument.\" One of the reasons that Carroll doesn't like it is because it uses \"old evidence,\" that life exists, to make the argument. And making a prediction and then gathering \"new evidence\" would be more convincing. I think this particular counter argument is weak. We shouldn't expect to apply the same standards to deep questions about the existence of humans or a god as we do to typical science experiments.\n\nThere are a few issues with the fine-tuning argument which I think are more reasonable. One is that it may not be easy to determine whether a particular set of physical constants would result in life or not.\n\nAnother counter-argument is that some physical theories predict that there are many \"universes\" each with different physical constants---the so-called \"multiverse.\" If there is a multiverse, then we may simply be in the particular \"universe\" that has life-supporting physical constants.\n\nCarroll makes another interesting counter-argument:\n\n> If the laws of physics were chosen so that life could exist, we would expect that each of the various features of those laws would play some important role in the unfolding of life. What we see, on the contrary, is something of a mess. All living beings are made out of the lightest generation of fermions---the electron and the up and down quarks, with occasional appearances from electron neutrinos. But there are two heavier families of particles, which don't play any part in life. Why did God make the top and bottom quarks, for example, and why do they have the masses they do? Under naturalism we would expect a variety of particles, some of which are important to life and some of which are not. That's exactly what we do observer.\n> = (chpt. 36)\n\nFinally, if the universe was fine-tuned so that we could exist, why do we \"live in a galaxy with more than 100 billion stars, in a universe with more than 100 billion galaxies\"? The universe could have easily been much smaller; why make it so enormous if we are the point of it all?\n\n## Part Five: Thinking\n\nCarroll begins his discussion of conciousness with an provocative evolutionary hypothesis: the development of conciousness began when creatures move from the sea to land. Vision is very limited underwater, thus, sea creatures don't have much time to plan their actions and instead must react quickly to events. Once on land, where creatures can see further, there is evolutionary pressure to develop brains that can plan their actions.\n\nThere are some intelligent sea-creatures which seem to break this theory. In particular, octopuses.\n\n> If there is any one aspect of reality that causes people to doubt a purely physical and naturalist conception of the world, it's the existence of conciousness.\n> = (chpt. 37)\n\nThis statement is true for me. But there are many reasons to believe that conciousness is physical:\n\n- Our minds appear to have multiple conflicting impulses warring with each other (Plato's white horse and black horse; the Apostle Paul's \"I do not do what I want to do\").\n- We can see electrical waves created by our brains in fMRIs and EEGs.\n- There are delays between physical events and when we can think about them (part of this is due to delays in sensory information reaching our brain).\n- Examples of individuals with partially damaged brains.\n- Various scientific experiments mapping certain cognitive abilities to parts of our brains.\n\nSome philosophers speak about \"the hard problem\" of conciousness---explaining the existence of qualia, the subjective character of experience. Other philosophers view this as not being a problem, but rather just \"conceptual confusion.\"\n\nThe Zombie Problem: consider a human, now consider an identical copy of the human who does not experience qualia---a zombie. If zombies can exist then naturalism must be incorrect. Some philosophers argue that zombies are conceivable, thus they must be able to exist. But is this true? We can conceive of water without an oxygen atom, but this can not exist.\n\n## Part Six: Caring\n\nMeaning, morality, and purpose are not fundamental parts of the universe but are emergent phenomena. This doesn't mean they are not real. \"Water doesn't stop being wet when you learn it's a compound of hydrogen and oxygen.\"\n\nHumans must be the starting place for any morality, purpose, or meaning.\n\nHume: You can not derive an \"ought\" from an \"is.\"\n\nCarroll's ten considerations:\n\n1. Life isn't forever\n2. Desire is built into life\n3. What matters is what matters to people\n4. We can always do better\n5. It pays to listen\n6. There is no natural way to be\n7. It takes all kinds [of people]\n8. The universe is in our hands\n9. We can do better than happiness\n10. Reality guides us\n\nI think this is an odd set of considerations to point out.\n" }, { "alpha_fraction": 0.7223080992698669, "alphanum_fraction": 0.752189576625824, "avg_line_length": 43.1136360168457, "blob_id": "428431708b25413a5e4cae521812d8405083986f", "content_id": "9e7c50257513635ad83cfe792a719b12f0b5d90c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1982, "license_type": "no_license", "max_line_length": 308, "num_lines": 44, "path": "/_documents/the-book-of-daniel.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n The Book of Daniel\ndescription: >\n Notes on The Biblical Book of Daniel\ntype: note\nstatus: incomplete\n---\n\n## Outline\n\n- Court legends (1 - 6)\n - Daniel is exiled, trained, keeps a pure diet, and is promoted (1)\n - Daniel tells and interprets the statue dream (2)\n - Daniel’s companions are tested in the fiery furnace (3)\n - Nebuchadnezzar narrates Daniel interpreting his tree dream; madness; recovery (4)\n - Daniel interprets the writing on the wall for Belshazzar (5)\n - Darius the Mede sends Daniel into the lion’s den (6)\n- Daniel’s apocalyptic visions (7 - 12)\n - Vision of the four beats (7)\n - Vision of the ram and the he-goat (8)\n - Daniel reinterprets Jeremiah’s prophecy (9)\n - Vision of the last days (10 - 12)\n\n## Historical Inaccuracies\n\nThe book of Daniel has a number of historical inaccuracies.\n\nThe Neo-Babylonian empire had the following kings:\n\n- Nabu-apla-usur 626–605 BC\n- Nabu-kudurri-usur II 605–562 BC\n- Amel-Marduk 562–560 BC\n- Neriglissar 560–556 BC\n- Labaši- Marduk 556 BC\n- Nabonidus 556–539 BC\n\nKing Nabu-kudurri-usur, also known as Nebuchadnezzar, captured Jerusalem in 597 BC and deposed its king Jehoiachin.\n\nBelshazzar was the son of king Nabonidus, who acted as king regent. Nabonodis left his son in control of the throne for a time (which is perhaps why Daniel is made third in command, and not second in command, in chapter 5).\n\nIt seems that author of Daniel changed “Nabonidus” to “Nebuchadnezzar” in chapters 2 through 5. The “Prayer of Nabonidus” fragment found in Dead Sea scrolls seems to lend evidence to this, as it has similarities to chapter 4 of Daniel.\n\nThe Septuagint includes several additions to Daniel. In the “Old Greek” version of “Bel and the Dragon”, the king in the story is Babylonian, while in in Theodotion’s version, the king is Cyrus. Perhaps this is another example of the king in the story being adjusted to fit the external context of the story.\n" }, { "alpha_fraction": 0.7061994671821594, "alphanum_fraction": 0.7385444641113281, "avg_line_length": 25.5, "blob_id": "94e9df50c5578e3fdede830264ea9fa9bece6311", "content_id": "192f3c399b5ec7b82c1968cbf37673a5b73ded4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 371, "license_type": "no_license", "max_line_length": 77, "num_lines": 14, "path": "/documents/the-hittites.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n The Hittites\ndescription: >\n Notes on The Hittites\ntype: note\n---\n\n- The Hittite civilization started c. 1600 BCE and ended c. 1178 BCE.\n- Mostly in modern-day Turkey\n- Their capital was Hattusa\n- Most famous king is Suppiluliuma I (c. 1350 BCE)\n- At one point was the second largest empire in the Mesopotamian, after Egypt\n- Sacked Babylon at some point\n" }, { "alpha_fraction": 0.7910592555999756, "alphanum_fraction": 0.7910592555999756, "avg_line_length": 63.3125, "blob_id": "bd179ed1e5981b68112b983e3f0b74492b35831a", "content_id": "a65a53283daa3c42fe55a1f1c34c5a09726a5de1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1035, "license_type": "no_license", "max_line_length": 367, "num_lines": 16, "path": "/_documents/how-to-decide-if-a-religion-is-true.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n How To Decide if a Religion is True\ndescription: >\n How To Decide if a Religion is True\ntype: essay\nstatus: complete\n---\n\nThe word religion is difficult to define. Here, a religion is be a set of metaphysical claims (statements about the nature of reality) and ethical imperatives (statements about how one should act).\n\nA religion can be said to be true if its metaphysical claims are true.\n\nA religion that does not make metaphysical claims can not be true, nor can it be false. Some religion’s metaphysical claims are implicit, and must be deduced from its rituals and texts. Other religion’s claims are explicit in creeds and catechisms.\n\nMetaphysical claims are less likely to be demonstrably true or false than physical claims. Fortunately, most religions make physical claims as well as metaphysical claims. Furthermore, the metaphysical claims tend to be justified from the physical claims. We can use a religion’s physical claims as a basis to evaluate the believability of its metaphysical claims.\n" }, { "alpha_fraction": 0.7675938606262207, "alphanum_fraction": 0.7675938606262207, "avg_line_length": 68.25263214111328, "blob_id": "96510797638b0811a12c5f011daa640df15afc58", "content_id": "d74ca6cdc193aefbf714f02681447c0e3e3c90d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6654, "license_type": "no_license", "max_line_length": 820, "num_lines": 95, "path": "/_posts/2020-06-14-antigone-historical-context.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Can We Understand _Antigone_ in Context?\ndescription: >\n We know the political and military context in which Sophocles wrote. Is this enough to interpret his plays as his audience would?\n---\n\n{{ page.description }} Since they are long dead, we can’t know for sure. Some say we can’t know at all, but I think this is too pessimistic. The past was different, but not so different we can’t reason about it. For example, imagine how our ancestors, with similarly limited context, would understand our art. What barriers would time raise for their understanding?\n\nThe most immediate source of confusion would be unknown contemporary references. A comedy show, joking about the absurdities in our politics and every day, would become difficult to follow. An epic historical drama, filled with universal themes of war, justice, love, and duty, would remain relatable.\n\nI think _Antigone_ has few contemporary references that would impact the play’s meaning; it is more like the historical epic than the comedy. There are a few; the choral ode after Antigone departs to her death compares her to Danaë, recounts Lycurgus’ death, and then tells a story about a Thracian queen who killed her two sons. The connection between the latter two and _Antigone_ is unclear to us but would have been understood by the Athenian audience.\n\nImplicit cultural norms and values are a second confounding factor. Both the comedy and the epic would assume their audience shares certain values and outlook. For example, a movie may expect its audience to understand and emotionally connect with Christianity in a certain way. Unlike missing references, it would be difficult to detect whether cultural norms had shifted significantly.\n\nFor example, how would exposing a traitor’s corpse be understood by Sophocles’ audience? Newly kinged Creon dictates:\n\n<blockquote class=\"poetry\">\n<p>But as for his blood brother, Polynices,</p>\n<p>who returned from exile, home to his father-city</p>\n<p>and the gods of his race, consumed with one desire—</p>\n<p>to burn them roof to roots—who thirsted to drink</p>\n<p>his kinsmen’s blood and sell the rest to slavery:</p>\n<p>that man—a proclamation has forbidden the city</p>\n<p>to dignify him with burial, mourn him at all.</p>\n<p>No, he must be left unburied, his corpse</p>\n<p>carrion for the birds and dogs to tear,</p>\n<p>an obscenity for the citizens to behold!</p>\n</blockquote>\n\nLetting an enemy’s corpse rot is still repulsive, but so is attempting to sack one’s country with the hopes of plundering it and selling your old comrades to slavery.\n\nAntigone and Creon justify their actions with divine authority, but both have secondary motives. Antigone says:\n\n<blockquote class=\"poetry\">\n<p>And even if I die in the act, that death will be a glory.</p>\n<p>I will lie with the one I love and loved by him—</p>\n<p>an outrage sacred to the gods! I have longer</p>\n<p>to please the dead than please the living here:</p>\n<p>in the kingdom down below I’ll lie forever.</p>\n<p>Do as you like, dishonor the laws</p>\n<p>the gods hold in honor.</p>\n</blockquote>\n\nIn addition to pleasing the gods, she is motived by her love for her brother and by glory.\n\nCreon says his first concern is the state. He doesn’t discount the gods, but believes they would side with him:\n\n<blockquote class=\"poetry\">\n<p>Stop—before you make me choke with anger—the gods!</p>\n<p>You, you’re senile, must you be insane?</p>\n<p>You say—why it’s intolerable—say the gods</p>\n<p>could have the slightest concern for that corpse?</p>\n<p>Tell me, was it for meritorious service</p>\n<p>they proceeded to bury him, prized him so? The hero</p>\n<p>who came to burn their temples ringed with pillars,</p>\n<p>their golden treasures—scorch their hallowed earth</p>\n<p>and fling their laws to the winds.</p>\n<p>Exactly when did you last see the gods</p>\n<p>celebrating traitors? Inconceivable!</p>\n</blockquote>\n\nBut, as is made clear throughout the play, his deeper motive is his insecurity and pride.\n\nWho is justified? Tiresias, the blind prophet, sides with Antigone and berates Creon:\n\n<blockquote class=\"poetry\">\n<p>You’ve robbed the gods below the earth,</p>\n<p>keeping a dead body here in the bright air,</p>\n<p>unburied, unsung, unhallowed by the rites.</p>\n<p>You, you have no business with the dead,</p>\n<p>nor do the gods above—this is violence</p>\n<p>you have forced upon the heavens</p>\n</blockquote>\n\nIt seems unclear whether the Athenians would have expected the gods to be on Creon’s side or Antigone’s.\n\nThe role of prophecy is another cultural norm which, if misunderstood, could alter our understanding of _Antigone_. Since we no longer believe in the Greek gods, we may view Tiresias as a story device and his prophecies as certain. But the ancient Greeks _believed_ in oracles and augury. They were a part of their worldview. Ironically, this means they understood that prophets were political. They could lie and cheat, as is apparent throughout Herodotus and even in the first book of the _Iliad_. It also explains why Creon’s reaction to Tiresias’ prophecy is to call him a “fortuneteller” and dismiss him (although soon he follows his advice). We know how the Greek’s viewed prophecy, so in this case we can envision how Sophocles’ audience understood Tiresias, but what if there are other norms we are not aware of?\n\nIs it a foregone conclusion that the gods side with Antigone, or is Sophocles making a religious or political statement? Could some Athenian audience members have sided with Creon? I think it is difficult for us to be sure.\n\nHow much should we care? If _Antigone_ is beautiful and prompts one to meditate on duty and justice, does it matter if I am layering it with new meanings?\n\n{% comment %}\nFor example, what would be the emotional impact of Creon’s statement, in his opening speech:\n\n<blockquote class=\"poetry\">\n<p>Remember this:</p>\n<p>our country <em>is</em> our safety.</p>\n<p>Only while she voyages true on course</p>\n<p>can we establish friendships, truer than blood itself.</p>\n</blockquote>\n\nIn the play, the Thebes defeated Polynice’s army only days before. This would be relatable to audience, members of which (including Sophocles) who could recall Athens being sacked by the Persians four decades ago. Growing up in America while it is a superpower, I have never worried about my safety. It would not seem so strange, or immoral, to value a friend above country. But any inability I have to relate to the “safety” of the polis is due, not to missing historical context, but only to my own lack of experiences.\n{% endcomment %}\n" }, { "alpha_fraction": 0.7784993052482605, "alphanum_fraction": 0.784415602684021, "avg_line_length": 100.9117660522461, "blob_id": "8ce6e0ff388c1b5064452fd6b4cc85310405eda2", "content_id": "15a7c8650ab12a073ee3f7e293b249c85dc999c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6930, "license_type": "no_license", "max_line_length": 997, "num_lines": 68, "path": "/documents/history-of-the-peloponnesian-war.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n \"History of the Peloponnesian War\" by Thucydides\ndescription: >\n Notes on \"History of the Peloponnesian War\" by Thucydides\ntype: note\n---\n\n## Outline\n\n- 1.1--23 Introduction; Why it was the greatest war; Methodology\n- 1.24--1.51 Cause: Epidamnus and Corcyra\n\n## Purpose\n\nThucydides' first stated purpose was to chronicle the great war.\n\n> Thucydides the Athenian wrote the history of the war fought between Athens and Sparta, beginning the account at the very outbreak of the war, in the belief that it was going to be a great war and more worth writing about than any of those which had taken place in the past.\n> = (1.1)\n\nHe also wanted to help people understand the past, and (perhaps) to avoid repeating mistakes in the future:\n\n> And it may well be that my history will seem less easy to read because of the absence in it of a romantic element. It will be enough for me, however, if these words of mine are judged useful by those who want to understand clearly the events which happened in the past and which (human nature being what it is) will, at some time or other and in much the same ways, be repeated in the future. My work is not a piece of writing designed to meet the taste of an immediate public, but was done to last for ever.\n> = (1.22)\n\nHe also wanted to establish his own excellence and, I believe, to spread his interpretation of the events.\n\n## The Greatest War\n\nWhy did Thucydides' believe the war he chronicled was the greatest war?\n\n> My belief was based on the fact that the two sides were at the very height of their power and preparedness, and I saw, too, that the rest of the Hellenic world was committed to one side or the other; even those who were not immediately engaged were deliberating on the courses which they were to take later. This [war] was the greatest disturbance in the history of the Hellenes, affecting also a large part of the non-Hellenic world, and indeed, I might almost say, the whole of mankind.\n> = (1.1)\n\nHe then explains, using reason and observations from Greek legends, why earlier times were less sophisticated. In these passages Thucydides reasons deeply about human motives. For example, he deduces that earlier people did not have a \"regular system of agriculture, since they lacked the protection of fortifications and at any moment an invader might appear and take their land from them.\" He deduces that earlier cities were placed inland to avoid raiders, but when sea-trade became more important, new cities were placed nearer to the coast. He reasons the kings who accompanied Agamemnon did so because he was powerful, and not because of the oaths they took. He trusts Homer's narrative while being skeptical about the details (reminiscent of Herodotus' argument that Helen was left in Egypt).\n\nThucydides' recognizes how difficult it is to understand the past:\n\n> For though I have found it impossible, because of its remoteness in time, to acquire a really precise knowledge of the distance past or even of the history preceding our own period, yet, after looking back into it as far as I can, all the evidence leads me to conclude that these periods were not great periods either in warfare or in anything else.\n> = (1.1)\n\n> Mycenae certainly was a small place, and many of the towns of that period do not seem to us today to be particularly imposing; yet this is not good evidence for rejecting what the poets and what general tradition have to say about the size of the expedition. Suppose, for example, that the city of Sparta were to become deserted and that only the temples and foundations of buildings remained, I think that future generations would, as time passed, find it very difficult to believe that they place had really been as powerful as it was represented to be.\n> = (1.10)\n\n> In investigating past history, and in forming the conclusions which I have formed, it must be admitted that one cannot rely on every detail which has come down to us by way of tradition. People are inclined to accept all stories of ancient times in an uncritical way---even when these stories concerns their own native countries.\n> = (1.20)\n\n> However, I do not think that one will be far wrong in accepting the conclusions I have reached from the evidence which I have put forward. It is better evidence than that of the poets, who exaggerate the importance of their themes, or of the prose chroniclers, who are less interested in telling the truth than in catching the attention of their public, whose authorities cannot be checked, and whose subject-matter, owing to the passage of time, is mostly lost in the unreliable streams of mythology. We may claim instead to have used only the plainest evidence and to have reached conclusions which are reasonably accurate, considering that we have been dealing with ancient history. As for this present war, even though people are apt to think that the war in which they are fighting is the greatest of all wars and, when it is over, to relapse again into their admiration of the past, nevertheless, if one looks at the facts themselves, one will see that this was the greatest war of all.\n> = (1.21)\n\nAfter commenting on his approach, Thucydides continues arguing that the Peloponnesian war was the greatest war by explaining why he thought it was greater than the war recounted by Herodotus:\n\n> The greatest war in the past was the Persian War; yet in this war the decision was reached quickly as a result of two navel battles and two battles on land.\n> = (1.22)\n\n## The Cause\n\n> What made war inevitable was the growth of Athenian power and the fear which this caused in Sparta.\n> = (1.23)\n\nThe Greek poleis thought of themselves as independent political units. During the war, there was pressure to join the Delian or Peloponnesian leagues. In a limited sense, this was pressure for the Greeks to produce larger political structures. This process is seen during the speech of the Corcyrians to the Athenians:\n\n> What has happened is that our policy in the past appears to have been against our own present interests, and at the same time makes it look inconsistent of us to be asking help from you. It certainly looks inconsistent to be coming here to ask for help when in the past we have deliberately avoided all alliances; and it is because of this very policy that we are now left entirely along to fact a war with Corinth. We used to think that our neutrality was a wise thing, since it prevented us being dragged into danger by other people's policies; now we see it clearly as a lack of foresight and to a source of weakness.\n> = (1.32)\n\nConcerns about being overrun by larger political groups pressures smaller ones to merge. Will this continue until there are two massive groups remaining? Clearly other pressures push for smaller sizes.\n\n*All quotations are taken from Rex Warner's 1954 translation of the* History of the Peloponnesian War*, published by Penguin Classics.*\n" }, { "alpha_fraction": 0.6589272022247314, "alphanum_fraction": 0.701302707195282, "avg_line_length": 43.08783721923828, "blob_id": "0c0960bab06231afcb460a7c22097219000ed320", "content_id": "f8952be0e5eeffed5625b6e95664b1d2705d730a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13253, "license_type": "no_license", "max_line_length": 409, "num_lines": 296, "path": "/_documents/the-pentateuch.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: The Pentateuch\ndescription: >\n Notes on the Pentateuch\ntype: note\n---\n\n<style>\nmain > ol{list-style-type:upper-roman}\nul:first-child{padding-left:1.4rem}\nmain > ul:first-child li{font-weight:normal}\nmain > ul:first-child > li{font-weight:bold}\n.js main > ul:first-child li{cursor:pointer}\n.js main > ul:first-child li li li{cursor:default}\n.js .hidden-children > ul:first-child{display:none}\n.hidden-no-js{display:none}\n.js .hidden-no-js{display:block}\n</style>\n\n## My Beliefs\n\nThe Pentateuch is the first five books of all bibles (Jewish, Catholic, Eastern Orthodox, Oriental Orthodox, and Protestant). Here are some of my beliefs about the Pentateuch, derived from study of the Pentateuch, historical sources, and commentaries:\n\n1. The Pentateuch is a beautiful and compelling story of the creation of the world, the patriarchs, and the Israelite’s exodus from Egypt and journey through the wilderness.\n2. Some of the stories and laws were adapted from older polytheistic Mesopotamian stories and laws to emphasize the Israelite’s all-powerful and moral God and his love of humanity.\n3. The Pentateuch, while largely Monotheistic, contains remnants from Israel’s polytheistic past when Yahweh was one god among many.\n4. There is some historical truth in the Pentateuch, beginning with the patriarchs, but that many details are symbolic or exaggerated.\n5. The Pentateuch was combined from multiple sources a long time after when the events were said to have occurred. Although it largely tells a cohesive story, inconsistencies in the individual sources are evident and were likely intentionally included.\n6. The laws in the Pentateuch were progressive compared to their neighbors, that modern critiques of the laws often misunderstand their historical context, but that the laws treat women as inferior to men.\n7. The authors of the Pentateuch had an ancient Mesopotamian (and incorrect) understanding of the physical world.\n\n## Outline\n\n<p class=\"hidden-no-js hidden-print\">\n <span class=\"hidden-sm\">Set outline depth: &nbsp;</span>\n <a href=\"#\" onclick=\"setDepth(2,event)\">Major Sections</a> ·\n <a href=\"#\" onclick=\"setDepth(3,event)\">Chapters</a>\n</p>\n\n- Genesis\n - Primeval history (1–11.26)\n - Creation in seven days (1–2.4a)\n - Creation in a garden (2.4b–2.25)\n - Fall into sin (3)\n - Cain and Abel; Cain genealogy (4)\n - Seth Genealogy (5)\n - Divine-human reproduction (6.1–6.4)\n - The flood; covenant; curse of Ham (6.5–9)\n - Table of nations (10)\n - Tower of Babel (11.1–11.9)\n - Shem genealogy (11.10–11.26)\n - Abraham (11.27–25.18)\n - First promise; journey; sister lie Pharaoh (11.27–12)\n - Lot and Abram split (13)\n - Militant Abram saves Lot (14)\n - Second promise (15)\n - Hagar and Ishmael (16)\n - Circumcision covenant (17)\n - Annunciation of Isaac (18.1–18.15)\n - Sodom and Gomorrah (18.16–19.29)\n - Lot impregnates his daughters (19.30–19.38)\n - Sister lie Abimelech (20)\n - Birth of Isaac; Ishmael dismissed; Abimelech dispute (21)\n - The testing of Abraham (22)\n - Death and burial of Sarah (23)\n - Finding a wife for Isaac (24)\n - Death of Abraham; genealogy (25.1–25.18)\n - Jacob (25.19–36)\n - Birth and birthright (25.19–25.34)\n - Promise; sister lie Abimelech; abundance; Esau’s wives (26)\n - Jacob steals the blessing (27)\n - Jacob’s ladder (28)\n - Jacob marries Leah and Rachel (29)\n - Jacob’s children; sheep story (30)\n - Jacob leaves Laban (31)\n - Preparation for Esau; wrestles with God; reunites (32–33)\n - Rape of Dinah and slaughter (34)\n - Promise and renaming; Reuben lies with Bilah (35)\n - Descendants of Esau (36)\n - Joseph (37–50)\n - Joseph sold into slavery (37)\n - Judah and Tamar (38)\n - Joseph at Potiphar’s house (39)\n - The cupbearer and baker (40)\n - Joseph interprets Pharaoh’s dreams; promoted (41)\n - First reunion (42)\n - Second reunion (43)\n - Silver goblet incident (44)\n - Joseph reveals himself (45)\n - Jacob comes to Egypt (46)\n - Joseph saves and enslaves Egypt (47)\n - Jacob adopts Joseph’s sons (48)\n - Jacob’s blessing (49)\n - Nervous brothers; Joseph’s death (50)\n- Exodus\n - Out of Egypt (1–18)\n - Pharaoh oppresses the Israelites (1)\n - Moses born, murders, flees, marries (2)\n - Moses called; objections; God nearly kills Moses (3–4)\n - First encounter with Pharaoh (5)\n - Promise and mission reaffirmed; genealogy (6)\n - First nine plagues (7–10)\n - The tenth plague and festivals (11–13)\n - Crossing the Sea of Reeds (14)\n - The Song of the Sea; Marah (15.1–15.21)\n - Murmuring; Manah (15.21–17.7)\n - Attack of the Amalekites (17.8–17.16)\n - Jethro visit (18)\n - Sinai and the covenant (19–25)\n - Theophany (19)\n - Decalogue (20.1–20.14)\n - People’s response to theophany (20.15–20.18)\n - The Covenant Collection (20.19–23)\n - The covenant ceremony (24)\n - Sanctuary and new covenant (25–40)\n - Instructions for the tabernacle (25–31)\n - Golden calf; God’s displeasure; Moses pleads (32–33)\n - Restoration of the covenant (34)\n - Creation of the tabernacle (35–40)\n- Leviticus\n - Sacrifice (1–7)\n - Burnt offerings (1)\n - Cereal offerings (2)\n - Sacrifice of well-being (3)\n - Purification offering (4–5.13)\n - Reparation offering (5.14–6.7)\n - Ritual institutions (6.8–7)\n - Dedication of the tabernacle (8–10)\n - Consecration of Aaron (8)\n - Day of revelation; Nadab and Abihu die (9–10)\n - Ritual purity (11–16)\n - Dietary laws (11)\n - Purification and childbirth (12)\n - Purification and skin disease (13–14)\n - Purification and bodily discharge (15)\n - Annual purging of the temple (16)\n - The Holiness Collection (17–26)\n - Slaughter and blood (17)\n - Abominations of the Canaanites (18)\n - Holiness of individuals (19)\n - Molech worship and sexual crimes (20)\n - Worship and holiness (21–22)\n - Holy times (23)\n - Oil and loaves; blaspheming (24)\n - Sabbatical and jubilee (25)\n - Blessing and curse (26)\n - Addendum (27)\n- Numbers\n - The camp and tabernacle (1–9)\n - Census of first generation (1)\n - Arrangement of camp (2)\n - Levite duties and census (3–4)\n - Purity; jealous husband (5)\n - Nazarites; priestly blessing (6)\n - Tabernacle offerings of dedication (7)\n - Dedication of the Levites (8)\n - The second passover; cloud and wilderness march (9)\n - Wilderness journey (10–21)\n - Trumpets (10.1–10.10)\n - Departure from Sinai (10.11–10.36)\n - Murmuring; quails (11)\n - Aaron and Miriam (12)\n - Spies in the promised land (13 -14)\n - Miscellaneous laws (15)\n - Korah’s revolt (16–17)\n - Compensation for Levites (18)\n - Red cow (19)\n - Moses doubts; Edomites prevent crossing; Aaron dies (20)\n - Defeat King Arad; bronze serpent; journey north (21)\n - Threats on the plains of Moab (22–25)\n - Balak and Balaam (22–24)\n - Plague (25)\n - Preparations for the promised land (26–36)\n - Second census (26)\n - Zelophad daughters; Moses’s death predicted; Joshua chosen (27)\n - Calendar of sacrifices (28–29)\n - Women and vows (30)\n - Vengeance against Midianites (31)\n - Settling the Transjordan (32)\n - Catalog of wilderness journey (33)\n - Division of the land (34)\n - Cities of refuge; homicide laws (35)\n - Zelophad daughters revision (36)\n- Deuteronomy\n - First discourse (1–4)\n - Historical recap (1–3)\n - Admonition to follow the law (4)\n - Second discourse: preamble (5–11)\n - The Decalogue (5)\n - Sermon on the first commandment (6)\n - The war of conquest (7)\n - Temptation to pride and self-sufficiency (8)\n - Why the Israelites are given the land (9)\n - Obedience as a condition for the land (10–11)\n - Second discourse: laws (12–25)\n - Centralization of worship (12)\n - Unconditional loyalty (13)\n - Obligations of holiness (14)\n - Remission of debts and manumission of slaves (15.1–15.18)\n - Sacrifice of first born (15.19–15.23)\n - The festival calendar (16.1–16.17)\n - Laws of public officials (16.18–18)\n - Cities of refuge; integrity of judicial system (19)\n - Rules for holy war (20)\n - Miscellaneous civil and family laws (21–25)\n - Second discourse: conclusion (26–28)\n - Conclusion (26)\n - Ceremonies at Shechem upon entry (27)\n - Blessing and curse (28)\n - Third discourse (29–30)\n - Didactic historical review (29)\n - Reassurance of restoration (30)\n - Death of Moses (31–34)\n - Moses’s arrangements for death (31)\n - The Song of Moses (32)\n - The blessing of Moses (33)\n - The death of Moses (34)\n\nNote: occasionally, when a section divide ends near a chapter division, I round the section division to the nearest chapter outline. E.g., the “Song of Moses” section begins with the last verse of Deuteronomy 31, but the outline section starts with Deuteronomy 32.\n\n## Mosaic Authorship\n\nThere are a number of verses that are difficult to explain if it is believed that Moses wrote the entire Pentateuch. The Pentateuch does not claim that Moses wrote it, outside of some laws in Exodus and Deuteronomy.\n\nHere is a list of some anachronistic verses which are difficult to explain if Moses authored the Pentateuch. Note that traditionalists have devised explanations for all of these anachronisms, but I find that most of the explanations stretch plausibility, especially when all of these verses are considered collectively.\n\n<blockquote class=\"prose\">\n<p>Abram passed through the land to the place of Shechem, to the oak of Moreh. At that time, <em>Canaanites were in the land.</em></p>\n<cite>— Genesis 12.6</cite>\n</blockquote>\n\nThe Canaanites were in the control of the land for Moses’s entire lifetime. Thus, the clarification “at that time, Canaanites were in the land” implies that the Canaanites were no-longer in the land when the author was writing, and that they were clarifying this for their audience.\n\n<blockquote class=\"prose\">\n<p>There was strife between the herdsmen of Abram’s livestock and the herdsmen of Lot’s livestock. <em>The Canaanites and the Perizzites lived in the land at that time.</em></p>\n<cite>— Genesis 13.7</cite>\n</blockquote>\n\nSimilar logic applies to this verse in chapter 13.\n\n<blockquote class=\"prose\">\n<p>When Abram heard that his relative was taken captive, he led out his three hundred eighteen trained men, born in his house, and pursued <em>as far as Dan</em>.</p>\n<cite>— Genesis 14.14</cite>\n</blockquote>\n\nThe town of Dan was named after the conquest, according to Joshua and Judges:\n\n<blockquote class=\"prose\">\n<p>The border of the children of Dan went out beyond them; for the children of Dan went up and fought against Leshem, and took it, and struck it with the edge of the sword, and possessed it, and lived therein, <em>and called Leshem, Dan, after the name of Dan their forefather</em>.</p>\n<cite>— Joshua 19.47</cite>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>They called the name of the city Dan, after the name of Dan their father, who was born to Israel; however <em>the name of the city used to be Laish</em>.</p>\n<cite>— Judges 18.29</cite>\n</blockquote>\n\nNote that Joshua and Judges disagree regarding the name of the city prior to being renamed.\n\nSome have suggested that the Dan referenced in Genesis is a different place. While possible, this seems unlikely because the phrase “from Dan to Beer-sheba” is used in the historical books to indicate the full extent of Israel. Thus, the use of Dan in Genesis 14 is consistent with this conception of Dan as the northernmost point of the nation.\n\n<blockquote class=\"prose\">\n<p>These are the words which Moses spoke to all Israel <em>beyond the Jordan</em> in the wilderness</p>\n<cite>— Deuteronomy 1.1</cite>\n</blockquote>\n\nThe phrase “beyond the Jordan” implies that the author is on the Western side. Moses did not cross the Jordan, thus it seems that author can not be Moses.\n\n<blockquote class=\"prose\">\n<p>(The Emim lived there before, a great and numerous people, and tall as the Anakim. These also are considered to be Rephaim, as the Anakim; but the Moabites call them Emim. The Horites also lived in Seir in the past, but the children of Esau succeeded them. They destroyed them from before them, and lived in their place, <em>as Israel did to the land of his possession, which Yahweh gave to them</em>.)</p>\n<cite>— Deuteronomy 12.10 - 12</cite>\n</blockquote>\n\nThe phrase “as Israel did to the land” implies that the conquest has already taken place.\n\n<script>\ndocument.documentElement.classList.add('js')\nul=document.querySelectorAll('main > ul')[0]\nul.onclick=function(e){\n if(e.target.tagName === 'LI')\n e.target.classList.toggle('hidden-children')\n}\nfunction setDepth(d,e){\n e.preventDefault()\n var s=''\n while(d--){\n s+='li '\n ul.querySelectorAll(s).forEach(function(li){\n if(d!=0)\n li.classList.remove('hidden-children')\n else\n li.classList.add('hidden-children')\n })\n }\n}\n</script>\n" }, { "alpha_fraction": 0.7924003005027771, "alphanum_fraction": 0.7928547263145447, "avg_line_length": 154.80531311035156, "blob_id": "d53aed3d74b738096af4cd172f798885f580d12f", "content_id": "dcbe28704b8c8b4e1fc53af39db43a1889243f45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17722, "license_type": "no_license", "max_line_length": 912, "num_lines": 113, "path": "/_documents/the-future-of-art.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n The Future of Art\ndescription: >\n I predict the future of art, and give my reasons for this prediction.\ntype: essay\nstatus: incomplete\n---\n\nThe definition of the word “art” is subjective—some people may have a broader view than others. It is insightful to understand what is generally meant by the word “art.” Further, I believe that the future of art lies in the broadening of this definition.\n\nI enjoy looking at sunsets, but is a sunset art? Is a pattern of ant tunnels art? One could call the ants artists—or are only humans allowed to be artists? While washing dishes, I may cause startling and beautiful patterns to form in the soap bubbles. I pause to look at them, and I find them beautiful. Most people do not consider sunsets, ant tunnels, or accidentally created soap bubbles patterns art. Thus I suggest art must have an intentional creator.\n\nI enjoy the taste of cheap New York pizza. While the pizza is intentionally created, is it art? Why not? Is it the transience of the pizza? Or is it how it is experienced—by an individual, in an irreproducible manner? Is it because too little effort was put into its creation? Or perhaps it is because the senses of taste, smell, and feeling—the crunch and swirl of masticated pizza in your mouth—is inferior to the senses of vision and hearing? We will consider each of these objections in turn, beginning with the last.\n\nI see no reason why the lower senses—taste, smell, and feeling—can not join hearing and sight as senses capable of appreciating art.\n\nThe ears and eyes produce sensory information at a higher rate than our tongue, nose, or the sensory organs of feeling. One could say they have higher bandwidth. For this reason, the lower senses are less interesting to the artist. The space of possible “touch sensations” and “taste sensations” is smaller than the space of “visual sensations” or “audible sensations,” so there is less room for artistic expression and exploration.\n\nThe lower senses can make more room for creativity by extending the length of time over which their art is enjoyed. During an hour-long yoga session our organs of feeling may produce as much information content as our eyes while looking at a painting for a minute. Of course music already does this, as do movies. The space of “all possible 30-minute movies” must be larger than the space of “all possible yoga classes.”\n\nMost early movies only used a small portion of their space. They involved humans, in normal human places, talking and doing normal human things. Modern movies have begun to move outside this narrow band and have begun to explore the huge space beyond it.\n\nThe yogi and the dancer are constrained by the range of motion allowed by our physical bodies. Ballerinas rarely develop new, vastly different movements that have not been done before. The choreography (and the music) together allow for creativity, but not as much in the movements.\n\nCombinations of the senses allow for even higher bandwidths. Silent films vs audio films. Stereo audio. There was a brief fad when movie theaters incorporated smells into the story by coordinating the release of chemicals into the air while the video unfolded—a modest increase in bandwidth. Three-dimensional movies increase the bandwidth of movies. This increases the space of sensory experiences the artist can explore.\n\nBooks rely on our imagination to bring all our senses into the artistic experience—”the old man smelled of cigars.”\n\nUntil now, we have been focused on our senses, but what about our motor control? A being can be viewed as a having senses (to learn about their environment), a control system (to remember and decide and react) and motor controls (to affect the environment).\n\nPaintings and sculptures only incorporate the senses into the experience. Even the ballet, while relying on the motor control of the dancers, does not allow the viewer to interact with it. I would be jailed if I tried to etch my name into a famous statue at the Louvre, and I would be thrown out if I stood up and began shouting during a symphony. Interactions with the art by the viewer are prohibited.\n\nGrowing up I read “choose your own adventure” books. These books allowed the reader to interact with the art through the use of motor control (by turning to particular pages). Some modern artists have interactive art exhibits, wherein the viewer can manipulate the art in some limited way, or even take it with them.\n\nVideo games are the ultimate form of art because they have the potential to allow users to interact with it. Today, video games use the sense of sight and sound, but even this is not enough. The trend has continued to be towards total immersion, where all of our senses, and the full range of our motor control, can be utilized in the artistic experience. Also, the word video game implies that it is a game, with a concrete purpose and goal like a game (but defining what a game is could be as tricky as defining art). Some types of video games don’t have concrete purposes beyond viewing the world created in them. In this sense, video games do not need to allow for interactivity. One could be a ghost, allowed to move (as a viewer moves around a sculpture), but unable to interact. In this sense, virtual reality can be seen as a generalization of video games beyond the “video” and beyond the “game.”\n\nVirtual reality allows the highest bandwidth artistic experience—a perfect virtual reality would be indistinguishable from our current reality. The universe creator would be the ultimate artist. The laws of physics of the universe would be artwork. The size and shape and colors and sounds and smells of the universe would be artwork.\n\nA conservative may find these interactive forms of art gimmicky. Perhaps artificially bright and neon paints were considered gimmicky when they came out as well. Our sense of what is art is anchored in what we are used to defining as such, but it may not be a reasonable definition.\n\nInteractivity does complicate any definition of art. A painting may not be seen the same way by all viewers. I have several favorite paintings at the Metropolitan Museum of Art that I revisit frequently; they have almost become friends in a sense, and my experience viewing them has changed over time as my worldview and situation changes. I am sure this is also the case for different viewers of a painting, each coming to it with their own biases, knowledge, and memories.\n\nStill, virtual reality offers deeper and more varied levels of interaction. Two viewers of a virtual reality may have completely different experiences. For example, a virtual reality can allow viewers to build things within it. In this case, the viewer becomes an artist within the art. This complexity doesn’t exist with non-interactive forms of art.\n\nWe have been considering the different amounts of information content allowed in different forms of art–bandwidth times time. However, just because a movie has more information content in it than a painting, doesn’t mean that information content is more artistic. A painter may exert themselves for many years on a canvas, but I can capture a video of the dog walkers on my street that has a good deal more information content than the painting. Similarly, it would be insulting to compare a great symphony with a cheaply thrown together soap opera.\n\nAll this is to say that the potential for video games and virtual reality is there. Video games are increasingly popular, but, they (like movies in their early days) have only explored a tiny thread of the full space of possibilities. Most video games follow consistent patterns of interaction. A player with a persistently present weapon walks, runs, and climbs through a three-dimensional universe filled with attacking enemies. A player controls military units on a two-dimensional board. These exceedingly limited forms of video games are only touching the surface of what is possible.\n\nDiscussions of bandwidth and information content only highlight the *potential* of the medium. The highest form of virtual reality art must surpass that of painting because paintings can be wholly contained in a virtual reality. An inhumanly voluminous virtual reality builder could create a virtual museum, filled with virtual paintings, which collectively are more astounding and impressive than the Louvre. It is possible (although unlikely because no one could accomplish a feat in a lifetime).\n\nSo far, we have been discussing art in terms of the senses that consume this art. This sort of discussion lumps painting with drawing with etching. The method by which the visual art is created is not considered. It seems short-sighted to define art in terms of how it was created, but this goes back to intentionally. A photo of a sunset may be deemed art, while a sunset itself is not, unless the sunset was created by god, or you are in a virtual reality with a sunset created by another being.\n\nThe method does seem to have some importance, however, because I can take a photo on my phone of a famous photo in a museum. If I am careful enough, the two may not even be distinguishable. Most would not call my photo of the photo art, while the original photo is. Also, we care a good deal about who painted a painting. The original Starry Night is considered art, while a perfectly executed copy of the art is not. Why is this? To the average viewer, the replica and the original are indistinguishable.\n\nIt is as if the amount of effort, in addition to potentiality, matters. My photo of the photo was easy. The copy of a Van Gogh was easier than the original. The soap opera TV show was easier than the Sistine Chapel. My recording of the dog walkers was easier than the symphony.\n\nWhat about modern art—large, uniform blue canvases. One could argue that, although the effort of the production is minimal, the effort of breaking out of past prejudices was not. This is why my blue canvas is less worthwhile than XXX’s.\n\nNote that the ants worked hard on their tunnels, so intentionality and effort be essential to our definition.\n\nMust the intention be to be beautiful, however? Architecture is often considered a traditional form of art, but buildings almost always have a purpose beyond being beautiful. What is the difference between design (of a car, furniture, or software user interfaces) and art?\n\nA motif of Gombrich’s book is that understanding the purpose of art helps one appreciate it. As the book travels through the history of art, he propounds why the artists of that period made the art. For most of history, art was made with a purpose besides being beautiful. Primitive people made art for magical purposes. Egyptians painted to account for the buried person’s possessions. Medieval painters sculpted and painted to educate about the Bible and the saints. Often paintings were ways of capturing the likeness of a person or an event.\n\nA painter may not have a purpose besides self-expression, but that doesn’t seem to make the graphics designer, with the purpose of selling things, less of an artist. If it did, the innumerable paintings of the Virgin Mary at the Louvre could not be considered art. It seems that it is the intentions and efforts of the artist, working in any medium under any constraints, to make something, to express themselves, that makes something art.\n\nI think Gombrich would partially agree with me.\n\n<blockquote>\n<p>For most of the paintings and statues which are now lined up along the wall of our museums and galleries were not meant to be displayed as Art. They were made for a definite occasion and a definite purpose which were in the artist’s mind when he set to work.</p>\n<p>Those ideas, on the other hand, that we outsiders usually work about, ideas about beauty and expression, are rarely mentioned by artists. It was not always like that, but it was for many centuries in the past, and it is so again now. The reason</p>\n<p>What an artist worries about as he plans his pictures, makes his sketches, or wonders whether he has completed a canvas, is something much more difficult to put into words. Perhaps he would say he worries about whether</p>\n<p>… finish copying pages 32-33.</p>\n</blockquote>\n\nThe idea of an artist “getting it right” is, essentially, dodging the most difficult part of defining art.\n\nGombrich says that we may feel that fussing over flowers, dresses, or food may not warrant so much attention. I think they could warrant as much attention. A great chef may feel their food is art. The arranger of flowers may feel their presentation is art. It seems to me that it is only the relatively limited space of possibilities that distinguishes cooking or flower arrangement from painting.\n\nAlthough a famous chef may consider their food art, nobody would consider a simple meal art. Again, it is the degree of effort and intent behind this. Thus many medieval paintings of Madonna are not art. Many buildings are not art. Many video games and TV shows are not art. But all of these can be art.\n\nSome modern sculptors don’t fabricate their works–they have teams of people fabricate their designs. Does this make their works less art? I don’t think so. Similarly, a television show, although involving many people, does not mean all of them are artists. Some or all of them may be. The means of fabrication does not seem to matter.\n\nDo financial incentives matter? Is the poor artist purer than the marketer? I don’t think so. They have different constraints to consider. The church paid the great 16th century painters in Rome were sought after and paid handsomely for their work. Money certainly matters for art. It is easy to imagine that medieval painters tired of painting religious figures and figures from Greek mythology, but that is where the money was.\n\nToday the money is in movies, television, and video games. For this reason, and because of the larger space provided for creativity, I believe that video games and video are where the most interesting and profound new forms of art will appear.\n\nThis isn’t to say I think painting is dead. A painting can be viewed as a single image contained in a movie or a video game. The ideas that have been explored in painting over the centuries will surely be applied to the higher dimensionality forms of art, such as video games. The exchange will likely be bi-directional as well.\n\nPaintings and other lower dimensional forms of art have an advantage over video games and movies—we have limited time and our minds are finite, so although the possibilities are larger for a video game, artists (especially working alone) and viewers may not be able to take advantage of the space, and the pure dimensional advantages may be limited.\n\nTeams of people working together certainly can. I believe that a great movie, while certainly different, can compete favorably with a great painting. To the painting lover this may sound like sacrilege, but consider that a great movie provides potentially hours of entertainment. Despite my love for paintings, I have never stared at one for hours. Also, a great documentary about a subject can stir me more strongly than a painting can. A great movie can more consistently stir my emotions than paintings can. Movies can contain stories, and they can educate.\n\nOne way in which I like paintings better than movies is that they are apart from time. They give me time to reflect, and to think about myself. I can investigate the colors and forms and textures in the painting in detail.\n\nForms of art that exist in time don’t allow this. I can’t experience a sound statically outside of time—it only exists in time. Similarly for a movie, while I can pause and examine a frame, the evolution of the frames is most interesting. Paintings are calmer and more patient. Video games can have both. Carefully crafted experiences and locations in a virtual reality can cause the viewer to reflect, while at other times control can be taken from the viewer, and they can be forced to view a particular scene.\n\nBecause videos and video games usually require the cooperation of many people, they are expensive to build. The high cost of development adds pressure on video game developers and producers to stay close to the beaten path, to only explore the well-beaten corner of the space of all possible movies.\n\nPainters have similar dilemmas, but the scope and magnitude of a single person is less. A great painter, on commissions, may risk upsetting their benefactor to try some new creative expression.\n\nOver time, as consumers demand more variety, and our society becomes wealthier, and our tools for developing video and video games becomes cheaper, I think artists will explore the space further.\n\n{% comment %}\nTODO: discuss the consumption experience (must art be viewed in a museum?)\n\nTODO: discuss replicability (fake copies of paintings; duplication of digital content)\n{% endcomment %}\n\nSo what is art? I don’t think we have a full definition, but I think it has to do with the intentions and effort of the artist. I don’t think the medium matters, except with regards to the space of possibility afforded by that medium. I think that virtual reality affords the largest space of possibility to the artist, and thus, I believe there is more room for creative expression in video games than in traditional art forms like painting or sculpture.\n\nOld European paintings and sculptures are safely regarded as art, but video games may not be. What separates the two?\n" }, { "alpha_fraction": 0.7900280952453613, "alphanum_fraction": 0.7900280952453613, "avg_line_length": 88, "blob_id": "27e8d4f396c94e983a88909afaf13be9e8504c29", "content_id": "a50c130bade69b0fa2aa05cf7600997fae83db54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4272, "license_type": "no_license", "max_line_length": 566, "num_lines": 48, "path": "/documents/definitions.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Definitions\ndescription: >\n Philosophical discussion benefits from precise and shared\n definitions. I discuss the two questions we can ask about definitions---are\n they useful, and are they what was meant?\ntype: essay\nstatus: incomplete\nredirect_from:\n - /on-definitions\n---\n\nWhen two people converse, each person assumes the other is using words like themself. Yet frequently, neither person could define the words they are using.\n\n> If you show a picture to a three-year-old and ask if there is a tree in it, you will likely get the correct answer. If you ask a thirty-year-old what the definition of a tree is, you will likely get an inconclusive answer. We didn't learn what a tree is by studying the mathematical definition of trees. We learned it by looking at trees.\n> - Y. S. Abu-Mostafa, Learning From Data\n\nIt is difficult to define words because they are contextual and recursive.\n\nWhen a veterinarian asks whether a recently sedated dog is conscious, we know they are asking if the dog is a awake. When a contemplative person asks whether a dog is conscious, we know they are asking if the dog's mind is somehow like a human's mind.\n\nWhen a botanist is told by their friend to \"turn right after the fourth tree,\" they know when to turn, despite the second and third plants being shrubs.\n\nWords can have several meanings. The word \"conscious\" can mean awake, or self-aware. We infer the appropriate use from context.\n\nThe more fundamental problem with definitions is that they are recursive.\n\nA dictionary contains these two definitions\n\n- consciousness: the fact of awareness by the mind of itself and the world\n- self-aware: having conscious knowledge of one's own character and feelings.\n\nIf our language is also recursive, where does meaning come from in our language? I think that the meaning of abstract words like consciousness is built up from more concrete words in a huge web of definitions. At the lowest level, the meaning of words comes directly from association with our sensory inputs and motor outputs. Thus, meaning bubbles up from the concrete uses at the bottom, to their more abstract uses at the top.\n\nRecursive definitions are especially problematic during abstract philosophical discussions. I have had heated conversations resolve after someone defines their words and we realize we had been agreeing all along!\n\nI think this is one of the reasons why many philosophical treatises begin by defining their terms. Philosophical definitions are different than the definitions we find in a dictionary. A formal definition is an intended equivalence between a word and other words.\n\nThe definition of the word \"definition\" has two uses. The first is what I will refer to as the standard definition---\"what people usually mean.\" The second is a formal equivalence between a word and other words.\n\nA standard definition is wrong when it is not what people usually mean. For example, the word \"book\" does not mean \"yellow fruit.\" On the other hand, a formal definition can not be wrong---it can only be useless. We can formally define the word \"book\" to mean \"yellow fruit\" if we like, but it is not very useful. This distinction between standard definitions and formal definitions is often obscured because, to aid our memory, we often provide formal definitions for words that are very similar to that same word's standard definition.\n\nWords that are too broad or too narrow are not useful for making distinctions. Everyday words make distinctions that are useful in everyday life. Specialists develop lingo to make finer distinctions.\n\nWhat people \"usually mean\" by a word varies in time and place, but it is essentially an empirical question.\n\nWords and their definitions do not exist in isolation; definitions can have ethical and political implications. When this is the case, people often will say a definition is \"wrong\" even though it may be what people \"usually mean\" by the word. For example, people say things like \"we should change how we define beauty to be more inclusive.\" This statement is not saying the definition of beauty is wrong because it is, empirically, not what people usually mean by the word beauty. Rather, they are saying the word is wrong because it leads to unethical behavior.\n" }, { "alpha_fraction": 0.7289890646934509, "alphanum_fraction": 0.7369062304496765, "avg_line_length": 29.98113250732422, "blob_id": "356fa6db887e1d8945f95927aad4ac548b75eee4", "content_id": "83235112fe345cec19dc7db0765f970b2d193816", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1642, "license_type": "no_license", "max_line_length": 264, "num_lines": 53, "path": "/README.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "# Arts and Metaphysics\n\n## Design Goals\n\n- Minimal styling so that myself (and other readers) can focus on the content\n- Optimize reading the documents:\n - on a laptop\n - on a phone\n - printed copy of the document\n- Allow me to write in a version of markdown that is tailored for my needs\n\n## Building\n\nRun `make` to compile static assets.\n\nStart a test server using `run`.\n\n## Typographical Substitutions\n\n- `---` is replaced with an \"em dash\"\n- `--` is replaced with an \"en dash\"\n- `...` at the start of a line is replaced with \"centered triple dots\"\n- Straight quotes are replaced with curly quotes everywhere\n\n## Citations\n\nThe final line of a quote indicates whether it is poetry and may contain a citation:\n\n- Quote with citation: `- This is a non-poetry quote`\n- Poetry with citation: `~ This is poetry`\n- Poetry without a citation `~`\n- Prose with citation: `= This is prose`\n- Prose without a citation `=`\n\nInline citations must start with an open parenthesis.\n\n## References\n\nReferences are in pseudo form of the Oxford Style. I prune some stuff that isn't necessary (e.g. who cares about the publisher these days, lots of books are self-published). See [this site](http://guides.library.uwa.edu.au/c.php?g=325241&p=2177430) for examples.\n\n## Titles\n\nBook names which are present in the titles of document are surrounded by quotes, instead of italics. This is due to how browsers and search engines treat the `<title>` tag and meta data.\n\n## Open Issues\n\n- Test RSS feed\n- Make the sitemap more sophisticated\n\n## Known Issues\n\n- Quoted poetry has extra new lines in Safari \"Reader Mode.\"\n- Dialogue is not formatted properly.\n" }, { "alpha_fraction": 0.7827883958816528, "alphanum_fraction": 0.7832340598106384, "avg_line_length": 130.28192138671875, "blob_id": "8e6ebd9e2d22d5908f084d626c2a83836ad9cdb0", "content_id": "063f25b8e5b3232f08c225c609be57e68ac4b169", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25111, "license_type": "no_license", "max_line_length": 1174, "num_lines": 188, "path": "/_documents/as-a-driven-leaf.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Critique of “As a Driven Leaf”\ndescription: >\n A philosophical critique of “As a Driven Leaf,” the story of a 1st century rabbi searching for truth in a Roman world.\ntype: essay\nstatus: complete\n---\n\n## Introduction\n\nRabbi Milton Steinberg wrote *As a Driven Leaf* and published it in 1939. It is a novel about Elisha ben Ayubah’s exploration of faith and reason, leading to his excommunication and tragic end as he fails to resolve the questions that haunted him. According to the foreword by Chaim Potok, Elisha’s struggles paralleled Steinberg’s, who was considered a heretic by some.\n\nThe book is a tragedy within a tragedy—Elisha’s story is set in Palestine and Syria during the Jewish-Roman wars.\n\nI enjoyed the book thoroughly. The outer story of the Jews within the Roman Empire is vivid, and I can relate to Elisha and his struggles.\n\nElisha’s intellectual journey has three stages:\n\n1. Implicit faith in religion, developed with reason\n2. A complete rejection of “faith,” and exclusive reliance on reason\n3. A considered faith, developed with reason\n\nIn this essay I critique arguments presented in four of Elisha’s conversations, each occurring at different points along his journey.\n\n## Conversation After Rejecting Faith\n\nThe first conversation is with Akiba, a close friend of Elisha and a fellow rabbi.\n\n<blockquote>\n<p>“Elisha, what strange things have you been thinking? I knew that you were disturbed but I never dreamed it had gone so far. Am I correct in believing…”</p>\n<p>“Yes,” came the toneless reply, “everything is gone, not steadily and all the time, but quite generally—everything except for faith in God … I am going to start at the beginning, by laying aside all prejudices, all preconceived notions, all my beliefs and affirmations.”</p>\n<p>“I am afraid,” Akiba faltered, “that I do not understand. What will be gained if you substitute blanket denial for a wavering faith?”</p>\n<p>“Let me put it this way. We have both studied Euclid’s <em>Elements of Geometry</em>. You must have been impressed by the lucidity of the reasoning and the sureness of its results. For some time, I have been conscious of the contrast between the method of the Greeks and ours. Their success, I am convinced, followed from the fact that they started from the foundations. We, on the contrary, have always tried to bolster our pre-established case.”</p>\n</blockquote>\n\nEuclid’s *Elements of Geometry* derives a set of theorems (called Euclidean Geometry) from a set of assumptions, or axioms. Although Euclid’s formulation had several flaws, its method remains the basis of mathematics to this day.\n\nElisha, like most of us, wants his religious beliefs to be as certain as Euclidean geometry. This approach ultimately fails because he can’t find certain axioms to base his religious beliefs on. We will discuss this in more detail later.\n\n<blockquote>\n<p>“Akiba, we have been friends for many years … you must undertake this effort with me. Let us start at the beginning together.”</p>\n<p>“But I still do not understand,” Akiba had protested, “how you can expect me to discard beliefs even tentatively if I am really possessed by them. Your suggestion is like the procedure of those Greek philosophers who say, ‘I do not trust my reason, but I will use it to prove that I have no right to use it.’ A man may insist that he lays a doctrine aside, but if it is integral to him, he will carry it with him wherever he goes and will inevitably find it again since it has never left him.”</p>\n</blockquote>\n\nAkiba’s argument here is invalid. I agree that reason can not prove or disprove itself, but this does not imply that we can not set aside our beliefs to analyze them. Our core beliefs can obscure implicit axioms in our reasoning, but once these axioms are identified, our reason is no longer bound by them. An atheist can realize that the proselytizer may be worried for his soul, and a Muslim can understand why the Qu’ran can not argue for its own validity to a non-believer.\n\nSteinberg may have intended for Akiba to convey that our core beliefs influence which axioms we have faith in. If this is so, then I agree. Or perhaps Akiba wants Elisha to recognize that he is putting faith in reason and that we all must put faith in our axioms.\n\nHowever, some axioms are more “believable” than others. If we include “reason” (vaguely defined) among our axioms, we can reason about the believably of our other axioms, but without reason we are lost. Even with reason, there are few foundational axioms for us to put our faith in, and it is ultimately up to the individual to have faith in what they find most “believable,” despite not having certainty. And with this faith, to implicitly or explicitly answer the ethical question—how should one live?\n\n<blockquote>\n<p>“The purpose of life,” said Akiba softly, “is to live well. Whatever contributes toward that end is right and true. My first and last criterion concerning my proposition is: Does it help men live better? You may remember a lecture in which I asserted ‘All is foreseen by God, yet man possesses freedom of will.’ “</p>\n<p>“But Akiba…”</p>\n<p>“Hear me out, Elisha, please. I am aware that, judged by the logic of Aristotle, my thesis is a contradiction in terms. But there is a higher logic, a rationality that springs from the necessities of human nature. Does not man face life with greater assurance if he believes that a benevolent providence foresees the future? And yet he must at the same time be confident that his will is free, otherwise moral effort is meaningless altogether. Doctrines in themselves are not important to me, but their consequences are. For example, I urge upon men that they regard themselves as embodiments of the divine essence. If I convince them, their days are endowed with a sense of abiding significance and unturning glory. Then not all the misfortunes and degradations to which they may be subjected can take from them their feeling of oneness with angels and stars. And as for our people, persecuted and dispersed, they live under the shadow of death, cherishing a dream that is recurrently shattered by the caprice of tyrants and then dreamed again half in despair. What can enable such a people to persist except a conviction of a special relationship to God?”</p>\n<p>“And the objective truth of that conviction?” Elisha broke in impatiently.</p>\n<p>“A large and terrible question, I grant. Nevertheless, the first and ultimate consideration, I insist, must be of effects. If any doctrine enlarges life, then it possesses truth in realms beyond Aristotle’s logic.”</p>\n<p>“… Yours is a good principle to be sure. Alas, it proves too much. It justifies everything and its opposite. What is more, you know as well as I that if there be no God, it is a lie to speak about Him no matter how well such a falsehood functions. And your readiness to believe, your willingness to accept doctrines on blind faith and then to defend them on grounds of expediency …”</p>\n<p>“By what right,” Akiba protested, “do you presume to call my attitude blind? Belief need not be unseeing. Is it a darkening of council to admit that truth is not a matter of the mind alone, but of the heart and experience also? Since it cannot be obtained by reason unaided, faith is indispensable both as a base on which thought may stand, and as a check-rein when logic goes astray.</p>\n</blockquote>\n\nWhen Akiba claims “if any doctrine enlarges life, then it possesses truth,” I think he means that the truth of your axioms is indicated by the ethical outcomes they produce. This view presupposes the central importance of humans and how they act. This belief is strange, but logically consistent. Before discussing further, it is useful to define some terms.\n\nI think the three primary questions (and their loosely defined field of philosophy) are:\n\n- Metaphysics — What is the nature of reality?\n- Epistemology — How does one know?\n- Ethics — What should I do?\n\nMost philosophies (or worldviews) answer these questions recursively. For example, the modern scientific worldview claims that the laws of nature describe how our bodies sense the world and these senses are deemed the basis of all knowledge—including the laws of nature. Thus our metaphysics informs our epistemology which informs our metaphysics.\n\nThe recursion between epistemology and metaphysics seems unavoidable. Ethics, on the other hand, is typically derived from the other two fields. But it doesn’t have to be—Akiba argues that ethics can inform epistemology. Here is an expanded form of his argument:\n\n1. Humans and how they live are of utmost importance.\n2. The universe should be consistent with this importance.\n3. Judaism makes people live well, so it is more likely true.\n\nThis argument is unconvincing unless you agree with the first two axioms, but it is internally consistent.\n\nAkiba’s comments about the difficulty of removing oneself from his beliefs apply; a religious person may not be aware of their axioms when deciding what to believe. They are apparent once disclosed, but the collective validity of the axioms and anything deduced from them is still unclear.\n\nFor ethics to affect metaphysics or epistemology, we must assume that humans (or conscious beings generally) are special. This importance may be justified if one believes we have souls or that the creator is especially interested in the organization of our brain matter. These metaphysical claims are possible. If we are not special in *some* sense, however, then ethics must be isolated from metaphysics and epistemology.\n\nI think one of the thesis of *As a Drive Leaf* is that ethics should inform our epistemology and our metaphysics. Besides Akiba’s arguments, Milton Steinberg hints that the Jewish survival through so much terrible persecution over the years contributes to the Jewish religious tradition’s validity.\n\nAkiba has a few more interesting comments:\n\n<blockquote>\n<p>“He who wishes to trace a circle must first select out of all space one point about which to draw it. … The utility of the circle in practice will determine ultimately whether the point has been well placed. So with faith. It is the axis about which we move—an axis that must be posited as an act of will. The fate of man determines whether he has located it properly. That is all I am saying—that belief is the beginning, that it may be tested by experience, but that it must exist, or nothing can be.”</p>\n</blockquote>\n\nAkiba is aware of the truth that Elisha has not yet discovered, that some faith is unavoidable.\n\nIt is interesting to note that Akiba considers faith “an act of will”—most Christians also believe this. I think it is only partially true; if a belief seems highly implausible, will can not produce faith.\n\n## Conversation While Exclusively Relying on Reason\n\nThe second conversation is between Elisha and Demonax—a philosopher who has decided to focus more on ethics than metaphysics. It takes place while Elisha remains confident in the power of reason.\n\n<blockquote>\n<p>“Let me explain,” Demonax continued. “To you philosophy is a science. To me it is an art. To you it is a method of discovering truth. To me it is a guide to noble living … I am the expositor not of a theory but of a skill. As a flute teacher imparts his art, first by personal example and then by simple, practical principles, without too much concern over the nature of sound, so I attempt to influence people to live beautifully by striving to live so myself, and by communicating those rules of conduct that have stood the test of time.”</p>\n<p>“But,” Elisha demurred, “no art can be entirely divorced from theory.”</p>\n<p>“Perfectly true,” Demonax replied. “That is why I have some interest in metaphysics, but only in the barest and most essential minimum of it. It is guidance in their behavior which men need, a vision of immediate, attainable objective to which they can dedicate themselves, not high-flown schemes of reality. Of the latter a man has enough if he attains to a reasonable belief in God and a fairly consistent picture of the universe and man’s role in it.”</p>\n<p>“But even that minimum,” Elisha protested, “must be thought through. You would not say that men should accept belief in God unless first they have reasoned their way to it clearly, consistently and indisputably. Or that they ought to adopt a code of morality unless they have convinced themselves of its validity.”</p>\n<p>“… I have studied all the major metaphysical systems with care and found not a single issue which they have demonstrated absolutely. To make matters worse, there is not one conclusion on which they agree.”</p>\n</blockquote>\n\nDemonax’s derision towards “high-flown schemes of reality” is likely a reference to Aristotle’s *Organon*, which divided reality into ten categories: substance, quantity, quality, relation, place, time, situation, condition, action, and passion.\n\nDemonax, like Akiba, does can not think we can find a certain foundation for our ethics. Unlike Akiba, who puts his faith in Judaism, Demonax thinks ethics only needs “reasonable belief in God and a fairly consistent picture of the universe and man’s role in it.” But how do we know man’s role within the universe? Assuming there is a God, does it care how we act? And even if it does, how should we act? Perhaps Demonax views ethics as the empirical science of making men happier, and as a science, we can observe and refine our approach.\n\n<blockquote>\n<p>“But after all,” Elisha objected, “there is just as little agreement in the realm of practical principle [applied ethics] as in that of theory [metaphysics]. Your own argument can be turned against you …”</p>\n<p>“You are right,” he said. “I am not altogether logical. Here I tell you that the quest after metaphysical certainty is not worth while because after several centuries of effort it has not attained its objectives. And at the very same moment I say that one ought to devote his efforts to teaching people how to behave although there is no agreement as to the better life and, so far as we are aware, no one has ever lived it in its completeness. But the contradiction is not mine. It is nature’s. The human scene is not some philosopher’s garden, but a confusing, dark struggle. Through its noise and obscurity men grope, all seeking for serenity, few finding it. And some of us, though we have not completely demonstrated our principles, believe that we know how they may make themselves both better and happier. Can we withdraw into books and their abstrusities when men need insight into their souls, balms for their wounds, and healing of their sorrows? …”</p>\n<p>“But if so,” Elisha cried out, “it will go on forever. If they possess no certainty and are never fully convinced of anything men will always take refugee in aphorisms and maxims. I am not insensitive to human suffering, but the slow cure is sometimes the surer … only if there be first an indisputable interpretation of reality and a moral system drawn from it, will men be able to live, as engineers and architects work, with assurance.”</p>\n</blockquote>\n\nI can imagine this conversation occurring between the mature Milton Steinberg and his younger self. “Can we withdraw into our books…?”\n\nI occasionally doubt the utility of philosophical investigations. Some investigation is appropriate, but once you have considered the main arguments, why continue? Shouldn’t we focus on our more immediate problems? I believe that privileged like myself are obligated to give back.\n\nLike Elisha, I think one answer is that the philosophical investigation is a form of giving back. This answer requires you to believe that there is more to discover, and that you are well-suited to discover it.\n\nMy fear is that I am not able, and that I use the investigations as an excuse to avoid the messy, uncomfortable work of making the world a better place. Demonax seemed to feel similarly.\n\n## Conversation While Realizing the Necessity of Faith\n\nThe third conversation is between Elisha and a philosopher who, like Elisha, believes we can develop a firm metaphysical foundation—this conversation is when Elisha loses his faith in the possibility of a solid metaphysical foundation.\n\n<blockquote>\n<p>“See,” he [the philosopher] urged, “how generous nature has been with us, equipping our minds from birth with sure truths for which we need not labor and which no sane person ever challenges. Will the boldest skeptic deny that two and two equal four, no more, no less; that the whole is the sum of its parts; that equals, added to equals, yield equals; that every effect must have a cause; that A cannot be B and its opposite at the same time, that …? But why belabor so obvious a point? Each of you can list dozens, hundreds, perhaps thousands of principles of like character.”</p>\n<p>⋯</p>\n<p>“As you spoke,” Elisha [said] … “I detected a gap in your argument—you left unabridged the interval between innate ideas and the syllogism you quoted. After all it is a far cry from the assertion that if equals are added to equals the results are equals, and the major premise, ‘All men are mortal.’ The former is indeed a judgment of pure reason. The latter, on the other hand, involves the concepts ‘men’ and ‘mortality’ and an inference as to their association—all derived from sense and hence subject to all the uncertainties of physical experience.</p>\n<p>“Now my question is this: how do you make the transition from innate ideas to such generalizations as the universal mortality of humanity? …</p>\n</blockquote>\n\nElisha’s question is perceptive. How can we transition the innate certainty we have in logic and mathematics to reality?\n\nEuclidean geometry is useful because it is a good model of physical space. But, unlike the Greeks, we know that Euclidean geometry is an imperfect model of physical space; it is accurate in Earth’s gravitational field, but it does not describe space near massive objects. Thus Euclid’s derivations may seem like certain statements about reality, but they are not. The derivations are, in fact, isolated from reality. They correspond with it as much as the axioms used to derive them correspond with reality.\n\nThis disconnect between mathematics and reality is subtle. Many engineers and scientists I have met haven’t considered it. I suspect this is why the disconnect is highlighted prominently in the introductory chapter of an excellent math textbook:\n\n<blockquote>\n<p>Why does arithmetic have such wide application in spite of the abstractness of its concept?</p>\n<p>The answer is simple. The concepts and conclusions of arithmetic, which generalize an enormous amount of experience, reflect in abstract form those relationships in the actual world that are met with constantly and everywhere…</p>\n<p>At the same time every abstract concept, in particular the concept of a number, is limited in its significance as a result of its very abstractedness. In the first place, when applied to any concrete object it reflects only one aspect of the object and therefor gives only an incomplete picture of it… In the second place, abstract concept cannot be applied everywhere without certain limiting conditions.</p>\n<cite>— A. D. Aleksandrov, et al., Mathematics: Its Content, Methods, and Meaning</cite>\n</blockquote>\n\nThus, I think the answer to Elisha’s question is “you can’t make the transition.” Any mathematical model may correspond to reality in every situation we have experienced thus far, but it is always possible we will observe new situations. Even more problematically, even if a mathematical model perfectly described reality today, reality may change in the future!\n\nThis disconnect between mathematical certainty and reality is the first of two reasons Elisha decides faith is unavoidable. The following quotes demonstrate his second reason:\n\n<blockquote>\n<p>“You have posited the validity of the deductive process. But what happens when you form a syllogism. You take major premise A, minor premise B and deduce conclusion C. You say when you are though that C follows inevitably from A and B. But what do you mean by that? Only that you have a sentiment of congruity, an emotion of fittingness. Are sentiments the stuff of rational demonstration?</p>\n<p>“Besides, I have been rereading the skeptical philosophers recently and have been impressed by one of their standard arguments. Every syllogism, they contend, rests on a first premise. Either you posit that premise as an act of faith, in which case it is patently impossible to speak of its absolute sureness, or else you derive it from another syllogism … Somewhere you must stop and say, ‘Here I shall believe without proof.’ Then what becomes of the claim to certainty?”</p>\n</blockquote>\n\nElisha questions our mind’s ability to reason. If our minds evolved to work well within the physical laws of our world, then perhaps the innate logical and mathematical truths that “feel” certain, do so because we evolved that sense of certainty? Could we imagine a different universe where the laws of logic would *not* feel certain?\n\nAfter this conversation, Elisha abandons his strict rejection of faith.\n\n## Conversation After Recognizing the Necessity of Faith\n\nThe final conversation is between Elisha and Meir, his favorite student, years later. In it Elisha beautifully summarizes his conclusion that we must rely on faith and reason:\n\n<blockquote>\n<p>“… neither reality outside man, nor feeling within him, is altogether logical. There will then always be in the crucible of thought a residue of the irrational never to be resolved into lucidity … man’s mind is too frail, too inadequate an instrument to achieve certainty.</p>\n<p>“… For all truth rests ultimately on some act of faith, geometry on axioms, the sciences on the assumptions of the objective existence and orderliness of the world of nature. In every realm one must lay down postulates or he shall have nothing at all. So with morality and religion. Faith and reason are not antagonists. On the contrary, salvation is through the commingling of the two, the former to establish first premises, the latter to purify them of confusion and to draw the fullness of their implications. It is not certainty which one acquires so, only plausibility, but that is the best we can hope for.”</p>\n<p>“… In all men there is a relentless drive to know and understand. My destiny became one episode in an eternal drama. In generations to come, others will desert the beliefs of their fathers and go seeking what I thought, others will put their trust in the intellect and strive to build philosophies and moralities after the fashion of the geometry book. If only I could discover some way of bequeathing to them my hard-won conclusion, that the light of man’s logic is too frail, unaided, to prevail against the enveloping darkness, that to reason faith is a prerequisite—then my career should not have been unavailing…”</p>\n</blockquote>\n\nMeir loved Elisha:\n\n<blockquote>\n<p>“But, Master,” Meir pleaded, “back there is all that you have failed to find—a faith—a God…”</p>\n<p>“Yes,” Elisha said reflectively, “—and no. It is true that I seek, that I have always sought what they have in the city yonder. That is the fantastic intolerable paradox of my life, that I have gone questing for what I possessed initially—a belief to invest my days with dignity and meaning, a pattern of behavior through which man might most articulately express his devotion to his fellows. In a sense it has all been a long arduous journey in a circle, whereby I have returned to my point of departure.</p>\n<p>“And yet I may not enter. For those who lie there insist, at least in our generation, on the total acceptance without reservation of their revealed religion. And I cannot surrender the liberty of my mind to any authority. Free reason, my son, is a heady wine. It has failed to sustain my heart, but having drunk of it, I can never be content with a less fiery drought.”</p>\n<p>“Then what awaits you, Master?”</p>\n<p> Elisha raised his eyes to the distant hills.</p>\n<p>“Older, sadder, wiser, I go seeking now, through faith and reason compounded, the answer to this baffling pageant which is the world.”</p>\n</blockquote>\n\n## Conclusion\n\n*As a Driven Leaf* is a wonderful book. The philosophical discussions were well thought out and essential, and the story provides an emotional and intellectual backdrop for these conversations that enhances their meaning.\n\nWhile reading the book, I felt a strong connection with the Steinberg, and as Chaim Potok says in the foreword, I would have loved to meet him.\n" }, { "alpha_fraction": 0.6957781314849854, "alphanum_fraction": 0.721647322177887, "avg_line_length": 41.017391204833984, "blob_id": "2adc2dc5f0b2542c9eab49bf8b318e18de6abf1b", "content_id": "c2fd1945060a4cb46b00325db5580a3d0745a634", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4878, "license_type": "no_license", "max_line_length": 299, "num_lines": 115, "path": "/_documents/ancient-egypt.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ancient Egypt\ndescription: >\n Notes on Ancient Egypt\ntype: note\n---\n\n## History\n\nThe Egyptian priest Manetho grouped the pharaohs into 31 dynasties. Modern Egyptologists tend to count the early, Macedonian, and Ptolemaic pharaohs as three additional dynasties, for a total of 34 dynasties. The dynasties are grouped into the following periods (all dates are BCE and approximate):\n\n1. Predynastic (5000–3000), Dynasty 0\n2. Early Dynastic (3000–2625), Dynasties 1–3\n3. Old Kingdom (2625–2130), Dynasties 4–8\n4. First Intermediate Period (2130–1980), Dynasties 9–11\n5. Middle Kingdom (1980–1630), Dynasties 12–14\n6. Second Intermediate Period (1630–1539), Dynasties 15–17\n7. New Kingdom (1539–1075), Dynasties 18–20\n8. Third Intermediate Period (1075–656), Dynasties 21–25\n9. Late Period (664–332), Dynasties 26–31\n10. Hellenistic Period (332–30), Dynasties 32–33\n\n## Wisdom Literature\n\nHere are a few excerpts from the Toby Wilkinson translation of the *Teaching of Ptahhotep,* generally believed to have been composed in the first half of the Twelth Dynasty (c. 1850):\n\n<blockquote class=\"poetry\">\n<p>If you come across a disputatious man in the heat of the moment,</p>\n<p>who has authority over you as a superior,</p>\n<p>bend your arms in respect and bow.</p>\n<p>For if you vex him, he will not be friendly to you.</p>\n<p>Diminish his bad speech</p>\n<p>by not opposing him while he is in the heat of the moment.</p>\n<p>He will be called an ignoramus</p>\n<p>while your self-control will equal his wealth.</p>\n<br>\n<p>If you come across a disputatious man</p>\n<p>who is your equal, your match,</p>\n<p>you will make your esteem greater than his by keeping silent.</p>\n<p>While he is saying bad things,</p>\n<p>there will be much discussion by the judges</p>\n<p>and your name will be good in the opinion of the elders.</p>\n<br>\n<p>If you come across a disputatious man</p>\n<p>who is a poor man, not your equal,</p>\n<p>do not be aggressive to him simply because he is weak.</p>\n<p>Leave him alone and he will confute himself.</p>\n<p>Do not answer him back merely to lighten your heart</p>\n<p>Do not vent your anger against your opponent,</p>\n<p>for wretched is he who injures a poor man.</p>\n<p>What you wish will be done anyway:</p>\n<p>you will beat him through the elders’ disapproval.</p>\n<br>\n<p>If you are a man in a position of trust,</p>\n<p>sent by one elder to another,</p>\n<p>stick to the matter for which he sent you;</p>\n<p>give him the message exactly as he told you.</p>\n<p>Beware of slanderous speech</p>\n<p>which embroils one elder with another.</p>\n<p>Do not shun the truth, do not go beyond it;</p>\n<p>but an outburst should not be repeated.</p>\n<p>Do not speak against anyone</p>\n<p>great or small: it is bad for the spirit.</p>\n<br>\n<p>If you are a leader</p>\n<p>whose authority is unhindered,</p>\n<p>you should achieve many things.</p>\n<p>Be mindful of tomorrow:</p>\n<p>a dispute does not come in the midst of praises</p>\n<p>but when the crocodile charges in, hatred arises.</p>\n<br>\n<p>If you are a leader,</p>\n<p>listen quietly to the plea of a petitioner.</p>\n<p>Do not rebuff him from what he planned to say:</p>\n<p>a victim loves to vent his anger</p>\n<p>more than to achieve what he came for.</p>\n<p>As for someone who rebuffs a petition,</p>\n<p>it is said, ‘Why does he reject it?’</p>\n<p>Not all that is petitioned for comes about,</p>\n<p>but a good hearing soothes the heart.</p>\n<br>\n<p>If you are a man of virtue</p>\n<p>who sits in his master’s hall,</p>\n<p>turn your mind to virtuous things.</p>\n<p>Your silence will be more effective than idle chatter.</p>\n<p>Speak only when you have thought of a solution,</p>\n<p>for it is only the skilled who should speak in the council.</p>\n<p>Speaking is more difficult than all other tasks</p>\n<p>he who does it fluently makes it his servant.</p>\n<br>\n<p>If you are powerful, gain respect</p>\n<p>through knowledge and pleasant speech.</p>\n<p>Do not command unless it befits:</p>\n<p>hostility gets you into trouble.</p>\n<p>Do not be arrogant lest you be humiliated,</p>\n<p>do not be silent lest you be rebuked.</p>\n<p>When you reply to the speech of a hothead,</p>\n<p>avert your face and control yourself.</p>\n<p>The ire of the hothead sweeps by:</p>\n<p>he who treads carefully, his path is clear.</p>\n<p>He who is troubled all day long</p>\n<p>has no happy time,</p>\n<p>while he who is frivolous all day long</p>\n<p>cannot establish a household;</p>\n<p>but he who aims to complete a task</p>\n<p>is like someone who steers a matter safely to land,</p>\n<p>and another matter is held fast.</p>\n<p>He who listens to his heart will regret.</p>\n<br>\n<p>Punish with authority, teach thoroughly,</p>\n<p>then suppression of wrongdoing remains a good deed.</p>\n<p>Punishment that is not deserved</p>\n<p>turns a complainant into an opponent.</p>\n</blockquote>\n" }, { "alpha_fraction": 0.7064240574836731, "alphanum_fraction": 0.7318570613861084, "avg_line_length": 39.00877380371094, "blob_id": "b704cc0b2a0574e2dcc4eee20e522ac166cb0a30", "content_id": "32f9a5049d50bff6502409220b9a92c890bf3ab3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4617, "license_type": "no_license", "max_line_length": 164, "num_lines": 114, "path": "/_documents/the-hebrew-bible.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n “The Old Testament”\ndescription: >\n Notes on “The Old Testament”\ntype: note\n---\n\n## Selected Timeline\n\n- c. 1208 Merneptah Stele - First reference to Israel outside the Old Testament\n- c. 1200 Bronze Age Collapse\n- c. 1025 - 1005 Saul’s Kingship\n- 1005 - 965 David’s Kingship\n- 968 - 928 Solomon’s Kingship\n- 925 Shisak’s Campaign through Canaan\n- 701 Hezekiah’s revolt crushed\n- 671 Assyrian King Esarhaddon’s subjugation of Egypt\n- 612 Babylonians capture the Assyrian capital\n- 640 - 609 King Josiah\n- 609 Battle of Megiddo\n- 597 Babylonian Seige of Jerusalem\n- 586 Successful Babylonian Seige; destruction of the temple\n- 539 Fall of Babylon to the Persians\n\n## Observations\n\n- The writers of the Old Testament had a middle-eastern (and incorrect) understanding of many natural phenomena\n - They believed the sky was a dome (or firmament) that was held up by mountains; there was water up above this dome; the dome occasionally opened to let rain fall\n- The writers of the Old Testament reference middle-eastern and Canaanite mythology frequently\n- The writers of the Old Testament were unaware of several fundamental theological Christian beliefs\n - The existence of Heaven\n- There are a number of small inconsistencies in the Old Testament\n\n## Bibles\n\n- Different groups of Christians include different books in their respective bibles:\n - Protestants\n - Catholics\n - Greek Orthodox\n - Russian Orthodox\n - Syriac Orthodox\n- Major textual traditions\n - Masoretic texts\n - Authoritative text for Rabbinic Judaism\n - Copied by the Masoretes between the 7th - 10th century BCE\n - Septuagint\n - Translated during the 3rd century BCE\n - Written in Koine Greek\n - Writers of the New Testament used this\n - Includes books not included in the Masoretic texts\n - Disagrees with the Masoretic texts in some places\n - Basis of\n- Minor textual traditions\n - Samaritan Pentateuch\n - Jews who stayed behind during the exile\n - Adherents of “Samaritanism”, a religion similar to Judaism but which they claim\n - Peshitta\n - Dead sea scrolls\n- Biblical Criticism\n - Abraham Ibn Ezra (1100s CE)\n - Thomas Hobbes, Benedict Spinoza, Richard Simon\n- Age of the World\n - Many attempts to calculate it from the Bible\n - Differences in textual traditions\n - Septuagint often adds 100 years to patriarch’s lifespans\n - Samaritan Pentateuch uses a different ages, and includes (Cannon, also included in Luke)\n - Within a single textual tradition, Samuel, Kings, Chronicles, Ezra, and Nehemiah provide different and conflicting dates\n- Biblical Archaeology\n - Geologist James Hutton analyzed rock formations and believed they were quite old and part of an on-going process\n - By 1830s philosophers generally accepted that the Earth was much older than the Bible had been thought to say it was\n - Knowledge of Sumerian, Akkadian, and Egyptian were lost by the time Roman Empire was Christianized\n - Our only history of the Middle East that was known was in the Bible\n - Napoleon’s expedition\n - Rossetta Stone was used in 1822 to decipher Egyptian hieroglyphics\n - Austen Henry Layard (1817 - 1894)\n - Excavated Numrud and Nineveh\n - Assyrian palace reliefs\n - 1851 library of Ashurbanipal\n - Amarna letters\n - Discovered around 1187\n - Written in Akkadian (Canaanite dialect)\n - Letters between Egyptian administration and other Kings and Queens\n - Archaeology of Canaan\n - Only started towards end of 1800s\n - Sir William Matthew Flinders Petrie (1853 - 1942)\n - Systematic and careful\n - Biggest step towards modern archeology\n - Some of his methdods have been challeneged and revised since\n - Focused on pottery and small items vs. big finds\n - Discovered Merneptah stele in 1896\n - John Garstein\n - Dug during the 1930s\n - Pushed for adoption of divisions into Stone, Bronze, and Iron ages\n - Uggarit\n - City-state north of Israel\n - Gods\n - El (the father creator god; old)\n - Baal (kills the Sea monster and is promoted to rule the world)\n - Describes creatures similar to Leviathan, Behometh, and Rahab in the bible\n- Names of God in the Bible\n - El\n - El Shaddai\n - Elohim\n - plural form of El\n - ten times more common than El\n - when used with plural verb, means “gods”\n - when used with singular verb, means “Israel’s god”\n - often used as “ha Elohim,” translated to “the one true god”\n - in some places, it is unclear whether Elohim means “gods” or “Israel’s god”\n - this practice was common even among Israels neighbors\n - Adonei\n - Yaweh\n - Revealed to Moses in Exodus 6.2\n" }, { "alpha_fraction": 0.7751126885414124, "alphanum_fraction": 0.7751126885414124, "avg_line_length": 68.02222442626953, "blob_id": "ca08a91cc66a016bbe4dde0dee33770278987d28", "content_id": "867e8607e0d99e57ed2a62b6126a273d8d5d2af8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6213, "license_type": "no_license", "max_line_length": 820, "num_lines": 90, "path": "/posts/2020-06-14-antigone-historical-context.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Can We Understand _Antigone_ in Context?\ndescription: >\n We know the political and military context in which Sophocles wrote. Is this enough to interpret his plays as his audience would?\n---\n\n{{ page.description }} Since they are long dead, we can't know for sure. Some say we can't know at all, but I think this is too pessimistic. The past was different, but not so different we can't reason about it. For example, imagine how our ancestors, with similarly limited context, would understand our art. What barriers would time raise for their understanding?\n\nThe most immediate source of confusion would be unknown contemporary references. A comedy show, joking about the absurdities in our politics and every day, would become difficult to follow. An epic historical drama, filled with universal themes of war, justice, love, and duty, would remain relatable.\n\nI think _Antigone_ has few contemporary references that would impact the play's meaning; it is more like the historical epic than the comedy. There are a few; the choral ode after Antigone departs to her death compares her to Danaë, recounts Lycurgus' death, and then tells a story about a Thracian queen who killed her two sons. The connection between the latter two and _Antigone_ is unclear to us but would have been understood by the Athenian audience.\n\nImplicit cultural norms and values are a second confounding factor. Both the comedy and the epic would assume their audience shares certain values and outlook. For example, a movie may expect its audience to understand and emotionally connect with Christianity in a certain way. Unlike missing references, it would be difficult to detect whether cultural norms had shifted significantly.\n\nFor example, how would exposing a traitor's corpse be understood by Sophocles' audience? Newly kinged Creon dictates:\n\n> But as for his blood brother, Polynices,\n> who returned from exile, home to his father-city\n> and the gods of his race, consumed with one desire---\n> to burn them roof to roots---who thirsted to drink\n> his kinsmen's blood and sell the rest to slavery:\n> that man---a proclamation has forbidden the city\n> to dignify him with burial, mourn him at all.\n> No, he must be left unburied, his corpse\n> carrion for the birds and dogs to tear,\n> an obscenity for the citizens to behold!\n> ~\n\nLetting an enemy's corpse rot is still repulsive, but so is attempting to sack one's country with the hopes of plundering it and selling your old comrades to slavery.\n\nAntigone and Creon justify their actions with divine authority, but both have secondary motives. Antigone says:\n\n> And even if I die in the act, that death will be a glory.\n> I will lie with the one I love and loved by him---\n> an outrage sacred to the gods! I have longer\n> to please the dead than please the living here:\n> in the kingdom down below I'll lie forever.\n> Do as you like, dishonor the laws\n> the gods hold in honor.\n> ~\n\nIn addition to pleasing the gods, she is motived by her love for her brother and by glory.\n\nCreon says his first concern is the state. He doesn't discount the gods, but believes they would side with him:\n\n> Stop---before you make me choke with anger---the gods!\n> You, you're senile, must you be insane?\n> You say---why it's intolerable---say the gods\n> could have the slightest concern for that corpse?\n> Tell me, was it for meritorious service\n> they proceeded to bury him, prized him so? The hero\n> who came to burn their temples ringed with pillars,\n> their golden treasures---scorch their hallowed earth\n> and fling their laws to the winds.\n> Exactly when did you last see the gods\n> celebrating traitors? Inconceivable!\n> ~\n\nBut, as is made clear throughout the play, his deeper motive is his insecurity and pride.\n\nWho is justified? Tiresias, the blind prophet, sides with Antigone and berates Creon:\n\n> You've robbed the gods below the earth,\n> keeping a dead body here in the bright air,\n> unburied, unsung, unhallowed by the rites.\n> You, you have no business with the dead,\n> nor do the gods above---this is violence\n> you have forced upon the heavens\n> ~\n\nIt seems unclear whether the Athenians would have expected the gods to be on Creon's side or Antigone's.\n\nThe role of prophecy is another cultural norm which, if misunderstood, could alter our understanding of _Antigone_. Since we no longer believe in the Greek gods, we may view Tiresias as a story device and his prophecies as certain. But the ancient Greeks _believed_ in oracles and augury. They were a part of their worldview. Ironically, this means they understood that prophets were political. They could lie and cheat, as is apparent throughout Herodotus and even in the first book of the _Iliad_. It also explains why Creon's reaction to Tiresias' prophecy is to call him a \"fortuneteller\" and dismiss him (although soon he follows his advice). We know how the Greek's viewed prophecy, so in this case we can envision how Sophocles' audience understood Tiresias, but what if there are other norms we are not aware of?\n\nIs it a foregone conclusion that the gods side with Antigone, or is Sophocles making a religious or political statement? Could some Athenian audience members have sided with Creon? I think it is difficult for us to be sure.\n\nHow much should we care? If _Antigone_ is beautiful and prompts one to meditate on duty and justice, does it matter if I am layering it with new meanings?\n\n{% comment %}\nFor example, what would be the emotional impact of Creon's statement, in his opening speech:\n\n> Remember this:\n> our country _is_ our safety.\n> Only while she voyages true on course\n> can we establish friendships, truer than blood itself.\n> ~\n\nIn the play, the Thebes defeated Polynice's army only days before. This would be relatable to audience, members of which (including Sophocles) who could recall Athens being sacked by the Persians four decades ago. Growing up in America while it is a superpower, I have never worried about my safety. It would not seem so strange, or immoral, to value a friend above country. But any inability I have to relate to the \"safety\" of the polis is due, not to missing historical context, but only to my own lack of experiences.\n{% endcomment %}\n" }, { "alpha_fraction": 0.580589234828949, "alphanum_fraction": 0.584055483341217, "avg_line_length": 25.227272033691406, "blob_id": "39604886005dd15c20922afaa3c5f0dd7adeb7fc", "content_id": "ec59a438a2d356aa03f63eed4fa79d2c1ccaaa84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 577, "license_type": "no_license", "max_line_length": 78, "num_lines": 22, "path": "/all.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\nlayout: basic\ntitle: All Pieces\ndescription: Here is the full list of my writing, most of them are incomplete.\n---\n{{ page.description }}\n\n## All Writings\n\n{% assign groups = site.documents | group_by: 'type' | sort: 'name' %}\n{% for group in groups %}\n <h2>{{ group.name | capitalize }}s</h2>\n <ul class=\"index\">\n {% assign documents = group.items | sort: 'title' %}\n {% for d in documents %}\n <li>\n <a title=\"{{ d.description | xml_escape | normalize_whitespace }}\"\n href=\"{{ d.url }}\">{{ d.title }}</a>\n </li>\n {% endfor %}\n </ul>\n{% endfor %}\n" }, { "alpha_fraction": 0.7377722859382629, "alphanum_fraction": 0.7499743103981018, "avg_line_length": 240.788818359375, "blob_id": "ef5bc2eec60ff34355fabfefe2f4ed0a934d5d0e", "content_id": "0f8bd7151e58de6cd2925e8b85e2f60b25a2123e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 39918, "license_type": "no_license", "max_line_length": 2077, "num_lines": 161, "path": "/_documents/source-theories-and-genesis-1-11.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: Source Theories and Genesis 1 - 11\ndescription: >\n An interactive investigation of the purported source theories for Genesis 1 - 11.\ntype: note\n---\n\n<style>\n.hidden-no-js{display:none}\n.js .hidden-no-js{display:block}\n\n.b{color:#000}\n.y{color:#B14}\n.p{color:#41B}\n.hide-y .y{display:none}\n.hide-p .p{display:none}\n</style>\n\n## Introduction\n\nMany people believe that the Genesis 1 - 11 was combined from older sources, which themselves evolved over a long period of time, and was combined into the form we have now by a master editor or redactor. One particular source theory is the “Documentary Hypothesis,” although there are others. The belief in multiple sources does not necessarily mean that:\n\n- The sources were not divinely inspired and edited,\n- The redactor did not combine the parts into a unified whole, or\n- Moses didn’t write portions of the Pentateuch.\n\nIn this section, I will examine Genesis 1 - 11 to see why scholars believe it is composed from multiple sources, and whether these arguments are persuasive.\n\n## The Creation Accounts\n\n<p class=\"hidden-no-js hidden-print\">\n <span class=\"hidden-sm\">Display: &nbsp;</span>\n <a class=\"b\" href=\"#\" onclick=\"setHighlight('yp',event)\"><span class=\"y\">J</span> and <span class=\"p\">P</span></a> ·\n <a class=\"y\" href=\"#\" onclick=\"setHighlight('y',event)\">Only J</a> ·\n <a class=\"p\" href=\"#\" onclick=\"setHighlight('p',event)\">Only P</a>\n</p>\n\n<blockquote class=\"prose\">\n<p><span class=\"p\">¹ In the beginning, God created the heavens and the earth. ² The earth was formless and empty. Darkness was on the surface of the deep and God’s Spirit was hovering over the surface of the waters.</span></p>\n<p><span class=\"p\">³ God said, “Let there be light,” and there was light. ⁴ God saw the light, and saw that it was good. God divided the light from the darkness. ⁵ God called the light “day”, and the darkness he called “night”. There was evening and there was morning, the first day.</span></p>\n<p><span class=\"p\">⁶ God said, “Let there be an expanse in the middle of the waters, and let it divide the waters from the waters.” ⁷ God made the expanse, and divided the waters which were under the expanse from the waters which were above the expanse; and it was so. ⁸ God called the expanse “sky”. There was evening and there was morning, a second day.</span></p>\n<p><span class=\"p\">⁹ God said, “Let the waters under the sky be gathered together to one place, and let the dry land appear;” and it was so. ¹⁰ God called the dry land “earth”, and the gathering together of the waters he called “seas”. God saw that it was good. ¹¹ God said, “Let the earth yield grass, herbs yielding seeds, and fruit trees bearing fruit after their kind, with their seeds in it, on the earth;” and it was so. ¹² The earth yielded grass, herbs yielding seed after their kind, and trees bearing fruit, with their seeds in it, after their kind; and God saw that it was good. ¹³ There was evening and there was morning, a third day.</span></p>\n<p><span class=\"p\">¹⁴ God said, “Let there be lights in the expanse of the sky to divide the day from the night; and let them be for signs to mark seasons, days, and years; ¹⁵ and let them be for lights in the expanse of the sky to give light on the earth;” and it was so. ¹⁶ God made the two great lights: the greater light to rule the day, and the lesser light to rule the night. He also made the stars. ¹⁷ God set them in the expanse of the sky to give light to the earth, ¹⁸ and to rule over the day and over the night, and to divide the light from the darkness. God saw that it was good. ¹⁹ There was evening and there was morning, a fourth day.</span></p>\n<p><span class=\"p\">²⁰ God said, “Let the waters abound with living creatures, and let birds fly above the earth in the open expanse of the sky.” ²¹ God created the large sea creatures and every living creature that moves, with which the waters swarmed, after their kind, and every winged bird after its kind. God saw that it was good. ²² God blessed them, saying, “Be fruitful, and multiply, and fill the waters in the seas, and let birds multiply on the earth.” ²³ There was evening and there was morning, a fifth day.</span></p>\n<p><span class=\"p\">²⁴ God said, “Let the earth produce living creatures after their kind, livestock, creeping things, and animals of the earth after their kind;” and it was so. ²⁵ God made the animals of the earth after their kind, and the livestock after their kind, and everything that creeps on the ground after its kind. God saw that it was good.</span></p>\n<p><span class=\"p\">²⁶ God said, “Let’s make man in our image, after our likeness. Let them have dominion over the fish of the sea, and over the birds of the sky, and over the livestock, and over all the earth, and over every creeping thing that creeps on the earth.” ²⁷ God created man in his own image. In God’s image he created him; male and female he created them. ²⁸ God blessed them. God said to them, “Be fruitful, multiply, fill the earth, and subdue it. Have dominion over the fish of the sea, over the birds of the sky, and over every living thing that moves on the earth.” ²⁹ God said, “Behold, I have given you every herb yielding seed, which is on the surface of all the earth, and every tree, which bears fruit yielding seed. It will be your food. ³⁰ To every animal of the earth, and to every bird of the sky, and to everything that creeps on the earth, in which there is life, I have given every green herb for food;” and it was so.</span></p>\n<p><span class=\"p\">³¹ God saw everything that he had made, and, behold, it was very good. There was evening and there was morning, a sixth day.</span></p>\n<p><span class=\"p\">¹ The heavens, the earth, and all their vast array were finished. ² On the seventh day God finished his work which he had done; and he rested on the seventh day from all his work which he had done. ³ God blessed the seventh day, and made it holy, because he rested in it from all his work of creation which he had done.</span></p>\n<p><span class=\"p\">⁴ This is the history of the generations of the heavens and of the earth when they were created,</span> <span class=\"y\">in the day that Yahweh God made the earth and the heavens. ⁵ No plant of the field was yet in the earth, and no herb of the field had yet sprung up; for Yahweh God had not caused it to rain on the earth. There was not a man to till the ground, ⁶ but a mist went up from the earth, and watered the whole surface of the ground. ⁷ Yahweh God formed man from the dust of the ground, and breathed into his nostrils the breath of life; and man became a living soul. ⁸ Yahweh God planted a garden eastward, in Eden, and there he put the man whom he had formed. ⁹ Out of the ground Yahweh God made every tree to grow that is pleasant to the sight, and good for food, including the tree of life in the middle of the garden and the tree of the knowledge of good and evil. ¹⁰ A river went out of Eden to water the garden; and from there it was parted, and became the source of four rivers. ¹¹ The name of the first is Pishon: it flows through the whole land of Havilah, where there is gold; ¹² and the gold of that land is good. Bdellium and onyx stone are also there. ¹³ The name of the second river is Gihon. It is the same river that flows through the whole land of Cush. ¹⁴ The name of the third river is Hiddekel. This is the one which flows in front of Assyria. The fourth river is the Euphrates. ¹⁵ Yahweh God took the man, and put him into the garden of Eden to cultivate and keep it. ¹⁶ Yahweh God commanded the man, saying, “You may freely eat of every tree of the garden; ¹⁷ but you shall not eat of the tree of the knowledge of good and evil; for in the day that you eat of it, you will surely die.”</span></p>\n<p><span class=\"y\">¹⁸ Yahweh God said, “It is not good for the man to be alone. I will make him a helper comparable to him.” ¹⁹ Out of the ground Yahweh God formed every animal of the field, and every bird of the sky, and brought them to the man to see what he would call them. Whatever the man called every living creature became its name. ²⁰ The man gave names to all livestock, and to the birds of the sky, and to every animal of the field; but for man there was not found a helper comparable to him. ²¹ Yahweh God caused the man to fall into a deep sleep. As the man slept, he took one of his ribs, and closed up the flesh in its place. ²² Yahweh God made a woman from the rib which he had taken from the man, and brought her to the man. ²³ The man said, “This is now bone of my bones, and flesh of my flesh. She will be called ‘woman,’ because she was taken out of Man.” ²⁴ Therefore a man will leave his father and his mother, and will join with his wife, and they will be one flesh. ²⁵ The man and his wife were both naked, and they were not ashamed.</span></p>\n</blockquote>\n\n## The Fall and Cain and Abel\n\nThe Fall into Sin and the story of Cain and Abel are believed to be entirely from the “J” source, and for this reason, I do not include them here.\n\n## The Genealogies from Adam to Noah\n\n## The Flood Story\n\nSome reasons include:\n\n- The differing style between portions of the text. E.g., Gen 1 vs 2, 4 v 5, 10 v 11.\n- Contradictions in Gen 1 vs 2 (the order that the animals are created is swapped)\n- Genesis 4 and 5 appear to repeat many names, but in one genealogy Cain is the parent and in the other Seth is.\n- Repetitions and differing numbers in the flood.\n\n<p class=\"hidden-no-js hidden-print\">\n <span class=\"hidden-sm\">Display: &nbsp;</span>\n <a class=\"b\" href=\"#\" onclick=\"setHighlight('yp',event)\"><span class=\"y\">J</span> and <span class=\"p\">P</span></a> ·\n <a class=\"y\" href=\"#\" onclick=\"setHighlight('y',event)\">Only J</a> ·\n <a class=\"p\" href=\"#\" onclick=\"setHighlight('p',event)\">Only P</a>\n</p>\n\n<blockquote class=\"prose\">\n<p><span class=\"y\">⁵ Yahweh saw that the wickedness of man was great in the earth, and that every imagination of the thoughts of man’s heart was continually only evil. ⁶ Yahweh was sorry that he had made man on the earth, and it grieved him in his heart. ⁷ Yahweh said, “I will destroy man whom I have created from the surface of the ground—man, along with animals, creeping things, and birds of the sky—for I am sorry that I have made them.” ⁸ But Noah found favor in Yahweh’s eyes.</span></p>\n<p><span class=\"p\">⁹ This is the history of the generations of Noah: Noah was a righteous man, blameless among the people of his time. Noah walked with God. ¹⁰ Noah became the father of three sons: Shem, Ham, and Japheth. ¹¹ The earth was corrupt before God, and the earth was filled with violence. ¹² God saw the earth, and saw that it was corrupt, for all flesh had corrupted their way on the earth.</span></p>\n<p><span class=\"p\">¹³ God said to Noah, “I will bring an end to all flesh, for the earth is filled with violence through them. Behold, I will destroy them and the earth. ¹⁴ Make a ship of gopher wood. You shall make rooms in the ship, and shall seal it inside and outside with pitch. ¹⁵ This is how you shall make it. The length of the ship shall be three hundred cubits, its width fifty cubits, and its height thirty cubits. ¹⁶ You shall make a roof in the ship, and you shall finish it to a cubit upward. You shall set the door of the ship in its side. You shall make it with lower, second, and third levels. ¹⁷ I, even I, will bring the flood of waters on this earth, to destroy all flesh having the breath of life from under the sky. Everything that is in the earth will die. ¹⁸ But I will establish my covenant with you. You shall come into the ship, you, your sons, your wife, and your sons’ wives with you. ¹⁹ Of every living thing of all flesh, you shall bring two of every sort into the ship, to keep them alive with you. They shall be male and female. ²⁰ Of the birds after their kind, of the livestock after their kind, of every creeping thing of the ground after its kind, two of every sort will come to you, to keep them alive. ²¹ Take with you some of all food that is eaten, and gather it to yourself; and it will be for food for you, and for them.” ²² Thus Noah did. He did all that God commanded him.</span></p>\n<p><span class=\"y\">¹ Yahweh said to Noah, “Come with all of your household into the ship, for I have seen your righteousness before me in this generation. ² You shall take seven pairs of every clean animal with you, the male and his female. Of the animals that are not clean, take two, the male and his female. ³ Also of the birds of the sky, seven and seven, male and female, to keep seed alive on the surface of all the earth. ⁴ In seven days, I will cause it to rain on the earth for forty days and forty nights. I will destroy every living thing that I have made from the surface of the ground.”</span></p>\n<p><span class=\"y\">⁵ Noah did everything that Yahweh commanded him.</span></p>\n<p><span class=\"p\">⁶ Noah was six hundred years old when the flood of waters came on the earth.</span> <span class=\"y\">⁷ Noah went into the ship with his sons, his wife, and his sons’ wives, because of the floodwaters. ⁸ Clean animals, unclean animals, birds, and everything that creeps on the ground</span> <span class=\"p\">⁹ went by pairs to Noah into the ship, male and female, as God commanded Noah.</span> <span class=\"y\">¹⁰ After the seven days, the floodwaters came on the earth.</span> <span class=\"p\">¹¹ In the six hundredth year of Noah’s life, in the second month, on the seventeenth day of the month, on that day all the fountains of the great deep burst open, and the sky’s windows opened.</span> <span class=\"y\">¹² It rained on the earth forty days and forty nights.</span></p>\n<p><span class=\"p\">¹³ In the same day Noah, and Shem, Ham, and Japheth—the sons of Noah—and Noah’s wife and the three wives of his sons with them, entered into the ship— ¹⁴ they, and every animal after its kind, all the livestock after their kind, every creeping thing that creeps on the earth after its kind, and every bird after its kind, every bird of every sort. ¹⁵ Pairs from all flesh with the breath of life in them went into the ship to Noah. ¹⁶ Those who went in, went in male and female of all flesh, as God commanded him;</span> <span class=\"y\">then Yahweh shut him in. ¹⁷ The flood was forty days on the earth. The waters increased, and lifted up the ship, and it was lifted up above the earth.</span> <span class=\"p\">¹⁸ The waters rose, and increased greatly on the earth; and the ship floated on the surface of the waters. ¹⁹ The waters rose very high on the earth. All the high mountains that were under the whole sky were covered. ²⁰ The waters rose fifteen cubits higher, and the mountains were covered. ²¹ All flesh died that moved on the earth, including birds, livestock, animals, every creeping thing that creeps on the earth, and every man.</span> <span class=\"y\">²² All on the dry land, in whose nostrils was the breath of the spirit of life, died. ²³ Every living thing was destroyed that was on the surface of the ground, including man, livestock, creeping things, and birds of the sky. They were destroyed from the earth. Only Noah was left, and those who were with him in the ship.</span> <span class=\"p\">²⁴ The waters flooded the earth one hundred fifty days.</span></p>\n<p><span class=\"p\">¹ God remembered Noah, all the animals, and all the livestock that were with him in the ship; and God made a wind to pass over the earth. The waters subsided. ² The deep’s fountains and the sky’s windows were also stopped, and the rain from the sky was restrained.</span> <span class=\"y\">³ The waters continually receded from the earth.</span> <span class=\"p\">After the end of one hundred fifty days the waters receded. ⁴ The ship rested in the seventh month, on the seventeenth day of the month, on Ararat’s mountains. ⁵ The waters receded continually until the tenth month. In the tenth month, on the first day of the month, the tops of the mountains were visible.</span></p>\n<p><span class=\"y\">⁶ At the end of forty days, Noah opened the window of the ship which he had made, ⁷ and he sent out a raven. It went back and forth, until the waters were dried up from the earth. ⁸ He himself sent out a dove to see if the waters were abated from the surface of the ground, ⁹ but the dove found no place to rest her foot, and she returned into the ship to him, for the waters were on the surface of the whole earth. He put out his hand, and took her, and brought her to him into the ship. ¹⁰ He waited yet another seven days; and again he sent the dove out of the ship. ¹¹ The dove came back to him at evening and, behold, in her mouth was a freshly plucked olive leaf. So Noah knew that the waters were abated from the earth. ¹² He waited yet another seven days, and sent out the dove; and she didn’t return to him any more.</span></p>\n<p><span class=\"p\">¹³ In the six hundred first year, in the first month, the first day of the month, the waters were dried up from the earth.</span> <span class=\"y\">Noah removed the covering of the ship, and looked. He saw that the surface of the ground was dry.</span> <span class=\"p\">¹⁴ In the second month, on the twenty-seventh day of the month, the earth was dry.</span></p>\n<p><span class=\"p\">¹⁵ God spoke to Noah, saying, ¹⁶ “Go out of the ship, you, your wife, your sons, and your sons’ wives with you. ¹⁷ Bring out with you every living thing that is with you of all flesh, including birds, livestock, and every creeping thing that creeps on the earth, that they may breed abundantly in the earth, and be fruitful, and multiply on the earth.”</span></p>\n<p><span class=\"y\">¹⁸ Noah went out, with his sons, his wife, and his sons’ wives with him. ¹⁹ Every animal, every creeping thing, and every bird, whatever moves on the earth, after their families, went out of the ship.</span></p>\n<p><span class=\"y\">²⁰ Noah built an altar to Yahweh, and took of every clean animal, and of every clean bird, and offered burnt offerings on the altar. ²¹ Yahweh smelled the pleasant aroma. Yahweh said in his heart, “I will not again curse the ground any more for man’s sake because the imagination of man’s heart is evil from his youth. I will never again strike every living thing, as I have done. ²² While the earth remains, seed time and harvest, and cold and heat, and summer and winter, and day and night will not cease.”</span></p>\n<p><span class=\"p\">¹ God blessed Noah and his sons, and said to them, “Be fruitful, multiply, and replenish the earth. ² The fear of you and the dread of you will be on every animal of the earth, and on every bird of the sky. Everything that moves along the ground, and all the fish of the sea, are delivered into your hand. ³ Every moving thing that lives will be food for you. As I gave you the green herb, I have given everything to you. ⁴ But flesh with its life, that is, its blood, you shall not eat. ⁵ I will surely require accounting for your life’s blood. At the hand of every animal I will require it. At the hand of man, even at the hand of every man’s brother, I will require the life of man. ⁶ Whoever sheds man’s blood, his blood will be shed by man, for God made man in his own image. ⁷ Be fruitful and multiply. Increase abundantly in the earth, and multiply in it.”</span></p>\n<p><span class=\"y\">⁸ God spoke to Noah and to his sons with him, saying, ⁹ “As for me, behold, I establish my covenant with you, and with your offspring after you, ¹⁰ and with every living creature that is with you: the birds, the livestock, and every animal of the earth with you, of all that go out of the ship, even every animal of the earth. ¹¹ I will establish my covenant with you: All flesh will not be cut off any more by the waters of the flood. There will never again be a flood to destroy the earth.” ¹² God said, “This is the token of the covenant which I make between me and you and every living creature that is with you, for perpetual generations: ¹³ I set my rainbow in the cloud, and it will be a sign of a covenant between me and the earth. ¹⁴ When I bring a cloud over the earth, that the rainbow will be seen in the cloud, ¹⁵ I will remember my covenant, which is between me and you and every living creature of all flesh, and the waters will no more become a flood to destroy all flesh. ¹⁶ The rainbow will be in the cloud. I will look at it, that I may remember the everlasting covenant between God and every living creature of all flesh that is on the earth.” ¹⁷ God said to Noah, “This is the token of the covenant which I have established between me and all flesh that is on the earth.”</span></p>\n</blockquote>\n\n## The Genealogies from Noah to Abraham\n\n## Example from David and Goliath Story\n\nWhy would an editor stitch together multiple stories while leaving contradictions in the original text, as source critics believe is done the flood story? Perhaps both sources were believed to be sacred? Or maybe the editor didn’t know which one was correct, and wanted to keep both? But if that is the case, why wouldn’t they explicitly say this—and why would they stitch the stories together, creating an odd hybrid of the two? One can speculate, but it is difficult to understand.\n\nWhile the motivation for splicing stories may be unknown, we do know at least one instance in the biblical texts where splicing occurred—the story of David and Goliath in 1 Samuel.\n\nThe Masoretic tradition—which most western Bible translations are based off—has a second copy of the David and Goliath story spliced into the original story. The Septuagint—a translation of the Old Testament into Greek that Jesus quoted from in the New Testament—does not contain the spliced in story. Note that the Septuagint is often abbreviated using LXX.\n\nHere is the David and Goliath story (1 Samuel 16.17 - 18.6), taken from the Masoretic text. The verses which were added are highlighted in <span class=\"y\">red</span>. Each story reads coherently on its own.\n\nWhen reading the text, note that David is introduced twice (once in the original, and once in the spliced in story). The setting for the story is introduced twice (once in the original, and once in the spliced in story). Also, Saul, who already knew who David was and who his after was, asks “Whose son are you, you young man?” He already knew David and “loved him greatly.” This apparent difficulty in the text can be explained by the fact that two sources were spliced together.\n\n<p class=\"hidden-no-js hidden-print\">\n <span class=\"hidden-sm\">Display: &nbsp;</span>\n <a class=\"b\" href=\"#\" onclick=\"setHighlight('yp',event)\"><span class=\"p\">LXX</span> and <span class=\"y\">Additions</span></a> ·\n <a class=\"p\" href=\"#\" onclick=\"setHighlight('p',event)\">Only LXX</a> ·\n <a class=\"y\" href=\"#\" onclick=\"setHighlight('y',event)\">Only Additions</a>\n</p>\n\n<blockquote class=\"prose\">\n<p><span class=\"p\">¹⁷ Saul said to his servants, “Provide me now a man who can play well, and bring him to me.”</span></p>\n<p><span class=\"p\">¹⁸ Then one of the young men answered, and said, “Behold, I have seen a son of Jesse the Bethlehemite who is skillful in playing, a mighty man of valor, a man of war, prudent in speech, and a handsome person; and Yahweh is with him.”</span></p>\n<p><span class=\"p\">¹⁹ Therefore Saul sent messengers to Jesse, and said, “Send me David your son, who is with the sheep.”</span></p>\n<p><span class=\"p\">²⁰ Jesse took a donkey loaded with bread, and a container of wine, and a young goat, and sent them by David his son to Saul. ²¹ David came to Saul, and stood before him. He loved him greatly; and he became his armor bearer. ²² Saul sent to Jesse, saying, “Please let David stand before me; for he has found favor in my sight.” ²³ When the spirit from God was on Saul, David took the harp, and played with his hand; so Saul was refreshed, and was well, and the evil spirit departed from him.</span></p>\n<p><span class=\"p\">¹ Now the Philistines gathered together their armies to battle; and they were gathered together at Socoh, which belongs to Judah, and encamped between Socoh and Azekah, in Ephesdammim. ² Saul and the men of Israel were gathered together<span class=\"y\">, and encamped in the valley of Elah,</span> and set the battle in array against the Philistines. ³ The Philistines stood on the mountain on the one side, and Israel stood on the mountain on the other side: and there was a valley between them. ⁴ A champion out of the camp of the Philistines named Goliath, of Gath, whose height was six cubits and a span went out. ⁵ He had a helmet <span class=\"y\">of bronze</span> on his head, and he wore a coat of mail; and the weight of the coat was five thousand shekels of bronze. ⁶ He had bronze shin armor on his legs, and a bronze javelin between his shoulders. ⁷ The staff of his spear was like a weaver’s beam; and his spear’s head weighed six hundred shekels of iron. His shield bearer went before him. ⁸ He stood and cried to the armies of Israel, and said to them, “Why have you come out to set your battle in array? Am I not a Philistine, and you servants to Saul? Choose a man for yourselves, and let him come down to me. ⁹ If he is able to fight with me and kill me, then will we be your servants; but if I prevail against him and kill him, then you will be our servants and serve us.” ¹⁰ The Philistine said, “I defy the armies of Israel today! Give me a man, that we may fight together!”</span></p>\n<p><span class=\"p\">¹¹ When Saul and all Israel heard those words of the Philistine, they were dismayed, and greatly afraid.</span> <span class=\"y\">¹² Now David was the son of that Ephrathite of Bethlehem Judah, whose name was Jesse; and he had eight sons. The man was an elderly old man in the days of Saul. ¹³ The three oldest sons of Jesse had gone after Saul to the battle: and the names of his three sons who went to the battle were Eliab the firstborn, and next to him Abinadab, and the third Shammah. ¹⁴ David was the youngest; and the three oldest followed Saul. ¹⁵ Now David went back and forth from Saul to feed his father’s sheep at Bethlehem. ¹⁶ The Philistine came near morning and evening, and presented himself forty days. ¹⁷ Jesse said to David his son, “Now take for your brothers an ephah of this parched grain, and these ten loaves, and carry them quickly to the camp to your brothers; ¹⁸ and bring these ten cheeses to the captain of their thousand, and see how your brothers are doing, and bring back news.” ¹⁹ Now Saul, and they, and all the men of Israel, were in the valley of Elah, fighting with the Philistines. ²⁰ David rose up early in the morning, and left the sheep with a keeper, and took and went, as Jesse had commanded him. He came to the place of the wagons, as the army which was going out to the fight shouted for the battle. ²¹ Israel and the Philistines put the battle in array, army against army. ²² David left his baggage in the hand of the keeper of the baggage, and ran to the army, and came and greeted his brothers. ²³ As he talked with them, behold, the champion, the Philistine of Gath, Goliath by name, came up out of the ranks of the Philistines, and said the same words; and David heard them. ²⁴ All the men of Israel, when they saw the man, fled from him, and were terrified. ²⁵ The men of Israel said, “Have you seen this man who has come up? He has surely come up to defy Israel. The king will give great riches to the man who kills him, and will give him his daughter, and make his father’s house free in Israel.”</span></p>\n<p><span class=\"y\">²⁶ David spoke to the men who stood by him, saying, “What shall be done to the man who kills this Philistine, and takes away the reproach from Israel? For who is this uncircumcised Philistine, that he should defy the armies of the living God?”</span></p>\n<p><span class=\"y\">²⁷ The people answered him in this way, saying, “So shall it be done to the man who kills him.”</span></p>\n<p><span class=\"y\">²⁸ Eliab his oldest brother heard when he spoke to the men; and Eliab’s anger burned against David, and he said, “Why have you come down? With whom have you left those few sheep in the wilderness? I know your pride, and the naughtiness of your heart; for you have come down that you might see the battle.”</span></p>\n<p><span class=\"y\">²⁹ David said, “What have I now done? Is there not a cause?” ³⁰ He turned away from him toward another, and spoke like that again; and the people answered him again the same way. ³¹ When the words were heard which David spoke, they rehearsed them before Saul; and he sent for him.</span><span class=\"p\">³² David said to Saul, “Let no man’s heart fail because of him. Your servant will go and fight with this Philistine.”</span></p>\n<p><span class=\"p\">³³ Saul said to David, “You are not able to go against this Philistine to fight with him; for you are but a youth, and he a man of war from his youth.”</span></p>\n<p><span class=\"p\">³⁴ David said to Saul, “Your servant was keeping his father’s sheep; and when a lion or a bear came, and took a lamb out of the flock, ³⁵ I went out after him, and struck him, and rescued it out of his mouth. When he arose against me, I caught him by his beard, and struck him, and killed him. ³⁶ Your servant struck both the lion and the bear. This uncircumcised Philistine shall be as one of them, since he has defied the armies of the living God.” ³⁷ David said, “Yahweh who delivered me out of the paw of the lion, and out of the paw of the bear, he will deliver me out of the hand of this Philistine.”</span></p>\n<p><span class=\"p\">Saul said to David, “Go!<span class=\"y\"> Yahweh will be with you.</span>” ³⁸ Saul dressed David with his clothing. He put a helmet of bronze on his head, and he clad him with a coat of mail. ³⁹ David strapped his sword on his clothing, and he tried to move; for he had not tested it. David said to Saul, “I can’t go with these; <span class=\"y\">for I have not tested them</span>.” Then David took them off.</span></p>\n<p><span class=\"p\">⁴⁰ He took his staff in his hand, and chose for himself five smooth stones out of the brook, and put them in the pouch of his shepherd’s bag which he had. His sling was in his hand; and he came near to the Philistine.</span> <span class=\"y\">⁴¹ The Philistine walked and came near to David; and the man who bore the shield went before him.</span> <span class=\"p\">⁴² When the Philistine looked around, and saw David, he disdained him; for he was but a youth, and ruddy, and had a good looking face. ⁴³ The Philistine said to David, “Am I a dog, that you come to me with sticks?” The Philistine cursed David by his gods. ⁴⁴ The Philistine said to David, “Come to me, and I will give your flesh to the birds of the sky, and to the animals of the field.”</span></p>\n<p><span class=\"p\">⁴⁵ Then David said to the Philistine, “You come to me with a sword, with a spear, and with a javelin; but I come to you in the name of Yahweh of Armies, the God of the armies of Israel, whom you have defied. ⁴⁶ Today, Yahweh will deliver you into my hand. I will strike you, and take your head from off you. I will give the dead bodies of the army of the Philistines today to the birds of the sky, and to the wild animals of the earth; that all the earth may know that there is a God in Israel, ⁴⁷ and that all this assembly may know that Yahweh doesn’t save with sword and spear; for the battle is Yahweh’s, and he will give you into our hand.”</span></p>\n<p><span class=\"p\">⁴⁸ When the Philistine arose, and walked and came near to meet David,</span> <span class=\"y\">David hurried, and ran toward the army to meet the Philistine.</span> <span class=\"p\">⁴⁹ David put his hand in his bag, took a stone, and slung it, and struck the Philistine in his forehead. The stone sank into his forehead, and he fell on his face to the earth.</span> <span class=\"y\">⁵⁰ So David prevailed over the Philistine with a sling and with a stone, and struck the Philistine, and killed him; but there was no sword in the hand of David.</span> <span class=\"p\">⁵¹ Then David ran, stood over the Philistine, took his sword, drew it out of its sheath, killed him, and cut off his head with it. When the Philistines saw that their champion was dead, they fled. ⁵² The men of Israel and of Judah arose and shouted, and pursued the Philistines as far as Gai and to the gates of Ekron. The wounded of the Philistines fell down by the way to Shaaraim, even to Gath and to Ekron. ⁵³ The children of Israel returned from chasing after the Philistines and they plundered their camp. ⁵⁴ David took the head of the Philistine, and brought it to Jerusalem; but he put his armor in his tent.</span> <span class=\"y\">⁵⁵ When Saul saw David go out against the Philistine, he said to Abner, the captain of the army, “Abner, whose son is this youth?”</span></p>\n<p><span class=\"y\">Abner said, “As your soul lives, O king, I can’t tell.”</span></p>\n<p><span class=\"y\">⁵⁶ The king said, “Inquire whose son the young man is!”</span></p>\n<p><span class=\"y\">⁵⁷ As David returned from the slaughter of the Philistine, Abner took him and brought him before Saul with the head of the Philistine in his hand. ⁵⁸ Saul said to him, “Whose son are you, you young man?”</span></p>\n<p><span class=\"y\">David answered, “I am the son of your servant Jesse the Bethlehemite.”</span></p>\n<p><span class=\"p\">¹ When he had finished speaking to Saul, the soul of Jonathan was knit with the soul of David, and Jonathan loved him as his own soul. ² Saul took him that day, and wouldn’t let him go home to his father’s house any more. ³ Then Jonathan and David made a covenant, because he loved him as his own soul. ⁴ Jonathan stripped himself of the robe that was on him, and gave it to David, and his clothing, even including his sword, his bow, and his sash. ⁵ David went out wherever Saul sent him, and behaved himself wisely; and Saul set him over the men of war. It was good in the sight of all the people, and also in the sight of Saul’s servants.</span></p>\n<p><span class=\"p\">⁶ As they came, when David returned from the slaughter of the Philistine, the women came out of all the cities of Israel, singing and dancing, to meet king Saul, with tambourines, with joy, and with instruments of music. ⁷ The women sang to one another as they played, and said,</span></p>\n<p><span class=\"p\">“Saul has slain his thousands,</span></p>\n<p><span class=\"p\">and David his ten thousands.”</span></p>\n<p><span class=\"p\">⁸ <span class=\"y\">Saul was very angry, and</span> this saying displeased him. He said, “They have credited David with ten thousands, and they have only credited me with thousands. What can he have more but the kingdom?” ⁹ Saul watched David from that day and forward.</span> <span class=\"y\">¹⁰ On the next day, an evil spirit from God came mightily on Saul, and he prophesied in the middle of the house. David played with his hand, as he did day by day. Saul had his spear in his hand; ¹¹ and Saul threw the spear, for he said, “I will pin David to the wall!” David escaped from his presence twice.</span> <span class=\"p\">¹² Saul was afraid of David,</span> <span class=\"y\">because Yahweh was with him, and had departed from Saul.</span> <span class=\"p\">¹³ Therefore Saul removed him from his presence, and made him his captain over a thousand; and he went out and came in before the people.</span></p>\n<p><span class=\"p\">¹⁴ David behaved himself wisely in all his ways; and Yahweh was with him. ¹⁵ When Saul saw that he behaved himself very wisely, he stood in awe of him. ¹⁶ But all Israel and Judah loved David; for he went out and came in before them.</span> <span class=\"y\">¹⁷ Saul said to David, “Behold, my elder daughter Merab, I will give her to you as wife. Only be valiant for me, and fight Yahweh’s battles.” For Saul said, “Don’t let my hand be on him, but let the hand of the Philistines be on him.” ¹⁸ David said to Saul, “Who am I, and what is my life, or my father’s family in Israel, that I should be son-in-law to the king?”</span></p>\n<p><span class=\"y\">¹⁹ But at the time when Merab, Saul’s daughter, should have been given to David, she was given to Adriel the Meholathite as wife.</span> <span class=\"p\">²⁰ Michal, Saul’s daughter, loved David; and they told Saul, and<span class=\"y\"> the thing</span> pleased him. ²¹ Saul said, I will give her to him, that she may be a snare to him, and that the hand of the Philistines may be against him.</span> <span class=\"y\">Therefore Saul said to David, “You shall today be my son-in-law a second time.”</span> <span class=\"p\">²² Saul commanded his servants, “Talk with David secretly, and say, ‘Behold, the king has delight in you, and all his servants love you. Now therefore be the king’s son-in-law.’ ”</span></p>\n<p><span class=\"p\">²³ Saul’s servants spoke those words in the ears of David. David said, “Does it seem to you a light thing to be the king’s son-in-law, since I am a poor man, and little known?”</span></p>\n<p><span class=\"p\">²⁴ The servants of Saul told him<span class=\"y\">, saying,</span> “David spoke like this.”</span></p>\n<p><span class=\"p\">²⁵ Saul said, “Tell David, ‘The king desires no dowry except one hundred foreskins of the Philistines, to be avenged of the king’s enemies.’ ” Now Saul thought he would make David fall by the hand of the Philistines. ²⁶ When his servants told David these words, it pleased David well to be the king’s son-in-law. <span class=\"y\">Before the deadline,</span> ²⁷ David arose and went, he and his men, and killed two hundred men of the Philistines. Then David brought their foreskins<span class=\"y\">, and they gave them in full number to the king,</span> that he might be the king’s son-in-law. Then Saul gave him Michal his daughter as wife. ²⁸ Saul saw<span class=\"y\"> and</span> knew that Yahweh was with David; and Michal, Saul’s daughter, loved him. ²⁹ Saul was even more afraid of David;</span> <span class=\"y\">and Saul was David’s enemy continually. ³⁰ Then the princes of the Philistines went out; and as often as they went out, David behaved himself more wisely than all the servants of Saul, so that his name was highly esteemed.</span></p>\n</blockquote>\n\n## References\n\nToy, E. (2014). The Composition of 1 Samuel 16-18 in Light of The Septuagint. In *The Greek and Hebrew Bible* (pp. 333-362). doi:10.1163/9789004275973\n\nThis book chapter explores the differences in 1 Samuel 16-18 between the Masoretic tradition and the Septuagint in great detail. My presentation is simplified. For example, I do night highlight all of the one-word additions. Furthermore, there are a few places where the Masoretic text is missing words that are in the Septuagint. To read a thorough and detailed analysis, including comparisons of the Greek and Hebrew, I would recommend reading this excellent chapter in detail.\n\n<script>\ndocument.documentElement.classList.add('js')\nfunction setHighlight(h,e){\n e.preventDefault()\n var cl=e.currentTarget.parentElement.nextElementSibling.classList\n if(h=='y')cl.add('hide-p');else cl.remove('hide-p')\n if(h=='p')cl.add('hide-y');else cl.remove('hide-y')\n}\n</script>\n" }, { "alpha_fraction": 0.7181177735328674, "alphanum_fraction": 0.7465332746505737, "avg_line_length": 37.58771896362305, "blob_id": "27ae07d636eb0c0219e1e1ee39fc4e05676be4e3", "content_id": "dfb2800e252f0a249f1932e377ced9f0551fc129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4399, "license_type": "no_license", "max_line_length": 299, "num_lines": 114, "path": "/documents/ancient-egypt.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ancient Egypt\ndescription: >\n Notes on Ancient Egypt\ntype: note\n---\n\n## History\n\nThe Egyptian priest Manetho grouped the pharaohs into 31 dynasties. Modern Egyptologists tend to count the early, Macedonian, and Ptolemaic pharaohs as three additional dynasties, for a total of 34 dynasties. The dynasties are grouped into the following periods (all dates are BCE and approximate):\n\n1. Predynastic (5000--3000), Dynasty 0\n2. Early Dynastic (3000--2625), Dynasties 1--3\n3. Old Kingdom (2625--2130), Dynasties 4--8\n4. First Intermediate Period (2130--1980), Dynasties 9--11\n5. Middle Kingdom (1980--1630), Dynasties 12--14\n6. Second Intermediate Period (1630--1539), Dynasties 15--17\n7. New Kingdom (1539--1075), Dynasties 18--20\n8. Third Intermediate Period (1075--656), Dynasties 21--25\n9. Late Period (664--332), Dynasties 26--31\n10. Hellenistic Period (332--30), Dynasties 32--33\n\n## Wisdom Literature\n\nHere are a few excerpts from the Toby Wilkinson translation of the *Teaching of Ptahhotep,* generally believed to have been composed in the first half of the Twelth Dynasty (c. 1850):\n\n> If you come across a disputatious man in the heat of the moment,\n> who has authority over you as a superior,\n> bend your arms in respect and bow.\n> For if you vex him, he will not be friendly to you.\n> Diminish his bad speech\n> by not opposing him while he is in the heat of the moment.\n> He will be called an ignoramus\n> while your self-control will equal his wealth.\n>\n> If you come across a disputatious man\n> who is your equal, your match,\n> you will make your esteem greater than his by keeping silent.\n> While he is saying bad things,\n> there will be much discussion by the judges\n> and your name will be good in the opinion of the elders.\n>\n> If you come across a disputatious man\n> who is a poor man, not your equal,\n> do not be aggressive to him simply because he is weak.\n> Leave him alone and he will confute himself.\n> Do not answer him back merely to lighten your heart\n> Do not vent your anger against your opponent,\n> for wretched is he who injures a poor man.\n> What you wish will be done anyway:\n> you will beat him through the elders' disapproval.\n>\n> If you are a man in a position of trust,\n> sent by one elder to another,\n> stick to the matter for which he sent you;\n> give him the message exactly as he told you.\n> Beware of slanderous speech\n> which embroils one elder with another.\n> Do not shun the truth, do not go beyond it;\n> but an outburst should not be repeated.\n> Do not speak against anyone\n> great or small: it is bad for the spirit.\n>\n> If you are a leader\n> whose authority is unhindered,\n> you should achieve many things.\n> Be mindful of tomorrow:\n> a dispute does not come in the midst of praises\n> but when the crocodile charges in, hatred arises.\n>\n> If you are a leader,\n> listen quietly to the plea of a petitioner.\n> Do not rebuff him from what he planned to say:\n> a victim loves to vent his anger\n> more than to achieve what he came for.\n> As for someone who rebuffs a petition,\n> it is said, 'Why does he reject it?'\n> Not all that is petitioned for comes about,\n> but a good hearing soothes the heart.\n>\n> If you are a man of virtue\n> who sits in his master's hall,\n> turn your mind to virtuous things.\n> Your silence will be more effective than idle chatter.\n> Speak only when you have thought of a solution,\n> for it is only the skilled who should speak in the council.\n> Speaking is more difficult than all other tasks\n> he who does it fluently makes it his servant.\n>\n> If you are powerful, gain respect\n> through knowledge and pleasant speech.\n> Do not command unless it befits:\n> hostility gets you into trouble.\n> Do not be arrogant lest you be humiliated,\n> do not be silent lest you be rebuked.\n> When you reply to the speech of a hothead,\n> avert your face and control yourself.\n> The ire of the hothead sweeps by:\n> he who treads carefully, his path is clear.\n> He who is troubled all day long\n> has no happy time,\n> while he who is frivolous all day long\n> cannot establish a household;\n> but he who aims to complete a task\n> is like someone who steers a matter safely to land,\n> and another matter is held fast.\n> He who listens to his heart will regret.\n>\n> Punish with authority, teach thoroughly,\n> then suppression of wrongdoing remains a good deed.\n> Punishment that is not deserved\n> turns a complainant into an opponent.\n> ~\n" }, { "alpha_fraction": 0.783728837966919, "alphanum_fraction": 0.7873446345329285, "avg_line_length": 146.5, "blob_id": "e48e84a3cf922e7ba27140fae61aca3929b149c7", "content_id": "5c0dbf817adcd243506e13a80d36733a994511fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8850, "license_type": "no_license", "max_line_length": 842, "num_lines": 60, "path": "/documents/altera-physical-laws.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Altera: Physical Laws\ndescription: >\n A detailed description of the physical laws of Altera.\ntype: essay\nstatus: incomplete\n---\n\n## Physical Laws\n\nUnlike our universe, where we do not have definite knowledge of its physical laws, we *do* have definite knowledge of Altera's physical laws because we have contrived them. In fact, Altera's physical laws are designed so that we could easily simulate them on a computer in our universe.\n\nAltera has two finite spatial dimensions that wrap around on themselves. If an entity moves beyond the edge of Altera, it reappears at the opposing end. Because each dimension is finite, Altera has a definite and fixed size. There exist two types of entities in Altera. Entities exist at particular discrete locations along each dimension. The first type of entity is a \"creature,\" which we shall call a Nook. The second type of entity we shall call \"food.\"\n\nNooks can sense their surroundings and can move. Time progresses in discrete steps. During each time step, Nooks may decide to move onto any of the four immediately adjacent locations, do nothing, or perform one of a small number of other actions which we will introduce shortly.\n\nNooks have a single externally observable property, which we refer to as its \"weight.\" We may represent a weight as a number between 1 and 255. Food has a weight of 1. Nooks may decide to \"eat\" the contents of any one of the four squares immediately adjacent to its current location. If that square contains food, the Nook's weight increases by 1, up until it reaches a maximum weight of 255. We call a Nook whose weight is 255 a \"fat\" Nook. If on the other hand, that square contains another Nook, it will eat it so long as its weight is less its own. Finally, if the square is empty, nothing will occur. When a Nook eats another Nook, its weight becomes the sum of its previous weight and the weight of the Nook that it ate, unless the resulting weight would be greater than 255, in which case the Nook's weight would simply be 255.\n\nIf a Nook moves into a location containing food or another Nook that weights less than itself that other Nook is \"pushed\" into the opposing square. If the opposing square also contains an object, the Nook is still able to push it, so long as the sum of the weights is less than itself, and so on.\n\nNooks have one sense which we shall call \"vision.\" Their vision is discrete, and they can see in all directions simultaneously. At any given moment, their vision allows them to \"see\" a 9x9 grid centered on their location. At each location, they can sense the weight of the being at that location, including themselves at the central square. Thus, food and Nooks with a weight of 1 will appear the same.\n\nNooks may decide to \"reproduce\"---to split themselves into two Nooks. If a Nook decides to reproduce, they must choose which of the adjacent four squares the new Nook will emerge onto. The weight of the parent Nook is split in two; if its original weight was an even number, the parent and child will both have half the original weight; if the original weight was an odd number, the parent will keep the indivisible extra portion. The child Nook will be a nearly identical replica of the parent Nook, but it may undergo a \"mutation\" during the reproductive process. We will discuss this more in the next section.\n\nEvery 65,536 moments in time each Nook's weight drops by 1. This event is called a \"starvation.\" If a Nook's weight is 1 when this occurs, they will \"die\" and the grid location that it had occupied will become empty.\n\nAltera has a single \"conservation law\"---the sum of the weights of all Nooks and food is always equal to the number of spatial locations in the universe. Food appears on squares throughout Altera so as to ensure this is true. The locations are pseudo-random, but new food is always placed on empty squares. Food never moves or decays. Once it has appeared, it occupies its location indefinitely until a Nook eats it or nudges it into another square. There are two events that occur new food to be \"grown\" in Altera. The first is during a starvation. The second occurs when a Nook eats something such that its weight exceeds 255.\n\nThere are several details of Altera's physical laws that we have omitted. In particular, the order in which Nook actions occurs, which can be important in certain situations. For example, if two Nooks of similar weight move into a square at the same time or if a Nook attempts to reproduce but is surrounded by other Nooks.\n\n## Mind\n\nThere is an essential aspect of Altera that we have not discussed---the means by which Nooks \"decide\" how to act. At each moment in time Nooks decide between doing nothing, moving in any of four directions, eating in any of four directions, or reproducing in any of four directions. Hence a Nook must decide between thirteen alternatives at each moment. If a Nook decides to take an action that it is physically incapable of making (for example reproducing when its weight is 1), it will instead do nothing.\n\nWhen making these decisions, Nooks will have available their immediate sensory data---their view of the surroundings and their knowledge of their weight. They also will have some \"memory\" and \"knowledge\" derived from their past interactions with their surroundings. These memory and knowledge is encoded in the Nook's \"mind.\"\n\nThe Nook mind changes over time in two different manners. It changes over the course of a particular Nook's existence, which we refer to as \"acclimatization,\" and it changes each time a Nook reproduces, which we refer to as \"evolution.\" The \"evolution\" process is pseudo-random.\n\nWe will avoid discussing the structure of the Nook mind, because it is not clear what it would be, and because it would be complicated and likely irrelevant to the purposes of this thought experiment. It is worth noting that the state of the mind may be very large. For example, it may have as much information content as the human brain is in our universe. It is likely that evolutionary change would involve altering the structure of the mind---how much data must be retained and what the data means, while acclimatization would involve changing the particular data without altering its structure or meaning.\n\nIt is important to note that the Nook mind would be finite, i.e. it could be represented as a (perhaps very long) series of numbers.\n\n## Comments on Physical Laws\n\nLet's compare our current understanding of our physical laws to Altera's.\n\nOur universe has one time and three spatial dimensions. All of these dimensions appear continuous to us, however, they may be discrete at a small enough scale. Space, time, matter, and energy are intertwined according to general relativity. Altera has time and two spatial dimensions. All are discrete. Matter occupies space and time, but does not affect it; time passes consistently for all Nooks.\n\nIn our universe, motion is an interaction between particles that can be described with mathematical equations. In Altera, movement is an algorithmic phenomena governed by the minds of the Nooks. It is natural, given the nomenclature we are using, to conceive of the Nooks as having a \"will\" that motivates their movements. It is also possible to conceive of the Nooks as \"particles.\"\n\nOur universe has a variety of particles that interact to form atoms, molecules, and organic beings of substantial complexity. Our particles have several properties---a mass and spin, and sometimes a color, flavor, or charge. Their interactions with each other can be described using mathematical equations. Altera has two types of particles---food and Nook. They both have a single property---their weight. They interact with each other in a direct algorithmic manner via the Nook's ability to eat and see other particles. Unlike our universe, where complexity only arises through the composition of simple particles, in Altera, complexity can arise in the individual Nook as well as through composition of many Nooks.\n\nIn our universe, beings sense their surroundings using complex organs built from many particles. These organs have evolved over time, and transmit and amplify the interactions of the constituent particles. Humans have since constructed even more complex sensing tools. Nooks have a sense of vision \"built\" into them directly, or, this is seen as their. If we conceptualize the Nook as a being with a will, then this feels oddly specific. If we conceptualize the Nook as a particle, it seems less odd.\n\n## Determinism\n\nAltera is a completely deterministic world. If a given world state were re \"played\" it would always evolve in an identical manner.\n\nThe Nooks would likely not be aware of this, and it is not even clear that they *could ever* prove whether the world was deterministic.\n" }, { "alpha_fraction": 0.7322613596916199, "alphanum_fraction": 0.7337904572486877, "avg_line_length": 44.86766815185547, "blob_id": "cc1657bceb44b3efd654f20cda75fa5a255ba3e0", "content_id": "cd0c2ebcaf01237ed809ca926e4590808653f216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 105070, "license_type": "no_license", "max_line_length": 550, "num_lines": 2267, "path": "/_documents/metamorphoses.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ovid’s _Metamorphoses_\ndescription: >\n Notes on Ovid’s _Metamorphoses_\ntype: note\nstatus: incomplete\n---\n\n## Introduction\n\nThe *Metamorphoses* is Ovid’s epic poem about change, which opens with these lines:\n\n<blockquote class=\"poetry\">\n<p>My mind leads me to speak now of forms changed</p>\n<p>into new bodies: O gods above, inspire</p>\n<p>this undertaking (which you’ve changed as well)</p>\n<p>and guide my poem in its epic sweep</p>\n<p>from the world’s beginning to the present day.</p>\n</blockquote>\n\nThe poem is about 12,000 lines of hexameter verse in Latin, and is split into 15 books. It was first published in 8 AD.\n\nOvid focuses on telling the many stories using beautiful and light-hearted language. His audience was familiar with the stories he tells, so it is his approach to telling the stories that makes them as entertaining as they are.\n\n## Outline\n\n- Book I\n - Proem; forms changed into new bodies\n - The creation by organizing chaos\n - The four ages of man (gold, silver, bronze, iron)\n - War with the Giants\n - Jove recounts Lycaon’s evil at the divine assembly\n - The great flood from above and below\n - Devout Deucalion and Pyrrha create more humans from mud\n - The earth generates life from the muck\n - Apollo kills the Python (and establishes the Pythian games)\n - Apollo brags to cupid; then woos and chases Daphne\n - Jove rapes Io then turns her into a cow\n - Pan pursues Syrinx; creates the reed pipe\n - Jove begs for Juno to relent and saves Io\n - Phaëthon sets out to prove he is the sun’s son\n- Book II\n - Phaëthon’s foolish wish; Apollo attempts to dissuade him\n - Phaëthon’s doomed ride; burning heaven and earth; death\n - Phaëthon’s sisters become Heliades (and their tears amber)\n - Cycnus turns into a bird as he despairs for Phaëthon\n - Apollo threatens to resign but relents\n - Jove rapes Callisto who births Arcas; turned into constellations\n - Crow warns raven not discloses infidelity; he is turned black\n - The prophetess Ocyrhoë over steps and is turned into a horse\n - Mercury steals cows and the tattletale old man\n - Mercury falls for Herse; Aglauros’s her sister demands gold\n - The house of Envy; Envy infects Aglauros\n - Mercury turns Aglauros to stone\n - Jove becomes a beautiful bull to steal Europa\n- Book III\n - Jove rapes Europa\n - Cadmus kills the dragon; sows the teeth; founds Thebes\n - Actaeon sees Diana naked; transformed into a stag and is hunted\n - Jove impregnates Semele; Juno enacts revenge\n - The judgement of Tiresias\n - Echo is cursed by Jove; she falls for Narcissus\n - Narcissus falls for himself and wastes away\n - King Pentheus rejects Bacchus\n - Acoetes’s story about Bacchus on the boat\n - Pentheus’ mom and sisters kill him in a frenzy\n- Book IV\n - The daughers of Minyas refuse to worship Bacchus\n - Pyramus and Thisbe’s accidental suicide\n - Mars and Venus are caught in infidelity\n - Venus’s revenge against the Sun (via Leucothoë)\n - The fountain of Salmacis and Hermaphrodite\n - The daughters of Minyas transformed\n - Juno in Hades; revenge against Ino and Athamas (and Seleme)\n - Cadmus and Harmonia despair and become snakes\n - Perseus turns Atlas into a mountain\n - Perseus saves Andromeda from the water monster\n - Perseus recalls Medusa’s demise\n- Book V\n - Persues slaughters the suitors\n - Minerva visits the Muses\n - The daughters of Pierus challenge the Muses\n - The rape and kidnap of Proserpina\n - Stellio is turned into a small lizard\n - Ceres searches; Arethusa helps; Appeal to Jove\n - Ascalphus spots Prserpina eating the pomegranate\n - The daughters of Acheloüs transformed into sirens\n - Prosperina’s year divided between husband and mother\n - Arethusa’s recounts Alpheus’ pursuit; becomes fountain\n - Triptolemus scatters seeds; Lyncus of Scythia rejects them\n - The daughters of Pierus transformed into birds\n- Book VI\n - Arachne brags and beats Minerva, but is turned into a spider\n - Niobe brags and her seven sons then daughters are slayed\n - Latona births on Delos; turns unreasonable peasants to frogs\n - Marsyas is stripped\n - Pelops’s ivory chip\n - Tereus marries Procne, rapes her sister Philomela, eats his son\n - Boreas steals Orithya as his bride\n- Book VII\n - Jason arrives; Medea’s monologue; Jason wins her and the fleece\n - Medea’s potion of youth for Aeson\n - Medea fools old Pelias’s daughters into killing him\n - Story-filled flight of Medea; Jason’s betrayal; Medea’s revenge\n - Aegeus marries Medea, who nearly poisons Theseus; celebrations\n - King Minos builds a coalition; Aegina refuses to join\n - Cephalus of Athens requests aid from Aeacus of Aegina\n - The plague at Aegina\n - The Myrmidons prepare for war\n - Aurora rapes Cephalus; jealous, he unfairly tests Procris\n - The plague at Thebes\n - Cephalus accidentally kills Procris\n- Book VIII\n - Scylla betrays Nisus and her country to beautiful King Minos\n - Minos places the Minotaur in Daedulus’s labyrinth\n - Ariadne helps Theseus kill it, who betrays then her\n - Daedalus constructs wings so he and Icarus can flee Crete\n - Daedalus jealously murders his talented nephew Perdix\n - Jealous Diana sends a boar; heroes gather and kill it\n - Meleager kills his uncles; his mother kills him\n - Theseus rests with river Acheloüs after the hunt\n - The Echinades and Perimele islands\n - Devout old Baucis and Philemon\n - Erysichthon cuts Ceres’ tree; sells daughter; eats himself\n- Book IX\n - Acheloüs recounts wrestling with Hercules and losing his horn\n - Hercules save Deianira; Nessus’ revenge by poisoned bloody cloak\n - Hercules’ in pain; recounts deeds; climbs mountain\n - Hercules throws Lichas into the sea; he becomes an island\n - Hercules’ death and apotheosis\n - Alcmena delivers Hercules; tricky servant turned into weasel\n - Dryope turned into a tree for picking berries\n - Iolaüs and Hebe’s prophecy; Zeus blames fate\n - Byblis desires her brother Caunus is rejected\n - Iphis, professed a boy at birth, becomes one on wedding night\n- Book X\n - Orpheus attempts to save Eurydice from the underworld\n - The catalogue of trees\n - Cyparissus accidentally kills the stag; becomes a cypress\n - Songs of Orpheus about boys the gods love and lusting girls\n - Trojan Ganymede becomes Jove’s cupbearer\n - Apollo’s discuss kills his lover Hyacinthus\n - The Propoetides and the Cerastae\n - Pygmalion falls in love with his statue\n - Myrrha fools her father into sleeping with her\n - Venus falls in love with Myrrha’s son Adonis\n - Hippomenes outraces Atalanta with Venus’ apples\n - Adonis impaled by a boar; Venus morphs him into an anemone\n- Book XI\n - Orpheus murdered by the Maenads, who are then turned to tree\n - Midas save Silenus; golden touch; Pan vs Apollo; asses’ ears\n - Apollo and Neptune build the Trojan walls for Laomedon\n - Zeus ordains that Peleus will marry Thetis; rape leads to Achilles\n - Apollo and Mercury rape Daedalion’s daughter; Diana’s jealousy\n - The wolf of Psamathe and Peleus’ flock\n - Ceyx leaves against Alcyone wishes; drowns in an epic storm\n - The house of Sleep; Juno has Alcyone visited in a dream\n - Alcyone despairs; husbands floating body; both turned to birds\n - Aesacus chases the nymph to her death; cliff jump; becomes bird\n- Book XII\n - Iphigenia sacrificed to appease Diana and the winds\n - The house of Rumor\n - Achilles after failed spearing, strangles invincible Cycnus\n - Old Nestor tells stories\n - Caeneus raped; turned into a man\n - Lapiths fight the centaurs; Caeneus burried\n - Hericles kill Nestor’s brothers\n - The death by Paris’ arrow, and glory, of Achilles\n- Book XIII\n - Ajax then Ulysses assert their claim on Achilles’ shield\n - Achille’s ghost demands Hecuba’s daughter\n - Hecuba’s revenges her son; transformed to a dog\n - Aurora’s son Memnon remembered with birds and dew\n - The daughters of Anius make grain; turned to birds\n - Precious goblet; the daughters of Orion\n - Polyphemus, Galatea, and Acis\n - Glaucas tells Scylla of magical grass morphing him into a fish\n- Book XIV\n - Glaucus asks Circe for help; she proposes; rejected, mutates Syclla\n - Aeneas wanders; Dido kills herself\n - The Sibyl helps Aeneas consult dead Anchises and tells her story\n - Macareus escapes Polyphemus and joins Aeneas’ crew\n - Macareus recounts Circe’s island with Ulysses\n - Women tells of Circe spurned, then transforming Picus\n - Impious Acmon transformed into a bird\n - Shepard turned into a bitter olive tree\n - Aeneas’ ships transformed into water nymphs\n - The Heron rises from the ashes of Rome’s enemies\n - The deificiation of Aeneas\n - Vertumnus pursues gardening Pomona while disguised\n - Anaxarete turns to stone after spurned Iphis suicides\n - Pomona accepts Vertumnus\n - A Roman spring\n - The deification of Romulus and his wife\n- Book XV\n - Numa, Rome’s wise second king\n - Myscelus and the founding of Crotona\n - Pythagoras; the transmigration of souls; change everywhere\n - Egeria and Hippolytus\n - Tages; The spear of Romulus; Cipus\n - Apollo’s son moves to Rome\n - The apotheosis of Julius Caesar\n - Ovid’s enduring fame\n\n## Book I\n\nIn Ovid’s creation account, like Hesiod’s, the world begins in Chaos:\n\n<blockquote class=\"poetry\">\n<p>Before the seas and lands had been created,</p>\n<p>before the sky that covers everything,</p>\n<p>Nature displayed a single aspect only</p>\n<p>throughout the cosmos; Chaos was its name,</p>\n<p>a shapeless, unwrought mass of inert bulk</p>\n<p>and nothing more, with the discordant seeds</p>\n<p>of disconnected elements all heaped</p>\n<p>together in anarchic disarray.</p>\n</blockquote>\n\nHowever, unlike Hesiod’s account—which focuses on the sexual creative acts of the gods and their genealogies—Ovid’s ignores the gods almost entirely.\n\nAnd unlike in the Genesis account, where God creates and separates, in Ovid matter existed in the beginning and only had to be separated:\n\n<blockquote class=\"poetry\">\n<p>Although the land and sea and air were present,</p>\n<p>land was unstable, the sea unfit for swimming,</p>\n<p>and air lacked light; shapes shifted constantly,</p>\n<p>and all things were at odds with one another,</p>\n<p>for in a single mass cold strove with warm,</p>\n<p>wet was opposed to dry and soft to hard,</p>\n<p>and weightlessness to matter having weight.</p>\n<p>Some god (or kinder nature) settled this</p>\n<p>dispute by separating earth from heaven,</p>\n<p>and then by separating sea from earth</p>\n<p>and fluid aether from the denser air;</p>\n<p>and after these were separated out</p>\n<p>and liberated from the primal heap,</p>\n<p>he bound the disentangled elements</p>\n<p>each in its place and all in harmony.</p>\n</blockquote>\n\nHe describes how the four winds are separated:\n\n<blockquote class=\"poetry\">\n<p>Nor did that world-creating god permit</p>\n<p>the winds to roam ungoverned through the air;</p>\n<p>for even now, with each of them in charge</p>\n<p>of his own kingdom, and their blasts controlled,</p>\n<p>they scarcely can be kept from shattering</p>\n<p>the world, such is the discord between brothers.</p>\n<p>Eurus went eastward, to the lands of Dawn,</p>\n<p>the kingdoms of Arabia and Persia,</p>\n<p>and to the mountain peaks that lie below</p>\n<p>the morning’s rays; and Zephyr took his place</p>\n<p>on the western shores warmed by the setting sun.</p>\n<p>The frozen north and Scythia were seized</p>\n<p>by bristling Boreas; the lands opposite,</p>\n<p>continually drenched by fog and rain,</p>\n<p>are where the south wind, known as Auster, dwells.</p>\n</blockquote>\n\nAfter creation, Ovid describes the four ages of man. It is similar to Hesiod’s ages of man in _Works and Days_. Here are the vices of the Iron Age:\n\n<blockquote class=\"poetry\">\n<p>Now men demand that the rich earth provide</p>\n<p>more than the crops and sustenance it owes,</p>\n<p>and piercing to the bowels of the earth,</p>\n<p>the wealth long hidden in Stygian gloom</p>\n<p>is excavated and induces evil;</p>\n<p>for iron, which is harmful, and the more</p>\n<p>pernicious gold (now first produced) create</p>\n<p>grim warfare, which has need of both; now arms</p>\n<p>are grasped in bloodstained hands; men live off plunder,</p>\n<p>and guest has no protection from his host,</p>\n<p>nor father-in-law from his daughter’s husband,</p>\n<p>and kindness between brothers is infrequent;</p>\n<p>husband and wife both wish each other dead,</p>\n<p>and wicked stepmothers concoct the bilious</p>\n<p>poisons that turn their youthful victims pale;</p>\n<p>a son goes to a soothsayer to learn</p>\n<p>the date when he will change from heir to owner,</p>\n<p>and piety lies vanquished here below.</p>\n<p>Virgin Astraea, the last immortal left</p>\n<p>on the bloodstained earth, withdraws from it in horror.</p>\n</blockquote>\n\nHere is part of Hesiod’s description of the Iron Age:\n\n<blockquote class=\"poetry\">\n<p>Then fathers won’t get along with their kids anymore,</p>\n<p>Nor guests with their hosts, nor partner with partner,</p>\n<p>And brothers won’t be friends, the way they used to be.</p>\n<p>Nobody’ll honor their parents when they get old</p>\n<p>But they’ll curse them and give them a hard time,</p>\n<p>Godless rascals, and never think about paying them back</p>\n<p>For all the trouble it was to raise them.</p>\n<p>⋯</p>\n<p>And then up to Olympos from the wide-pathed Earth,</p>\n<p>lovely apportions wrapped in white veils,</p>\n<p>off to join the Immortals, abandoning humans</p>\n<p>There go Shame and Nemesis. And horrible suffering</p>\n<p>Will be left for mortal men, and no defense against evil.</p>\n<cite>— Works and Days, 212–35</cite>\n</blockquote>\n\nBoth accounts imply new technologies, such as bronze, iron, and perhaps gold coinage, cause new evils. Both accounts look to an earlier, purer time. A time when the gods still lived on Earth.\n\nUnlike Hesiod, Ovid does does not include the aberrant Age of Heroes in between the bronze and iron ages. The Age of Heroes, unlike the other four, is not named after a metal (it is better than the previous age). I think Hesiod inserted it to meld an older tradition of the metal ages with the Greek’s own tradition of the heroes of Thebes and the Trojan ware.\n\nIn response to the wickedness of the Iron Age, Jove calls for a great flood. Unlike the Babylonian Atrahasis flood myth—wherein the gods regret destroying their source of sacrifices—in Ovid, the gods have more foresight:\n\n<blockquote class=\"poetry\">\n<p>Some of the gods give voice to their approval</p>\n<p>of Jove’s words and aggravate his grumbling,</p>\n<p>while others play their roles with mute assent.</p>\n<p>Nevertheless, all of them were saddened</p>\n<p>by the proposed destruction of the human race</p>\n<p>and wondered what the future form of earth</p>\n<p>could possibly be like, without men on it:</p>\n<p>why, who would bring the incense to their altars?</p>\n</blockquote>\n\nOvid’s description of the flood is powerful:\n\n<blockquote class=\"poetry\">\n<p>One takes to the hills, another to his skiff,</p>\n<p>rowing where once he plowed the earth in rows,</p>\n<p>while yet another sails above his grainfields,</p>\n<p>or glimpses, far below, his sunken villa;</p>\n<p>and here in the topmost branches of an elm</p>\n<p>is someone casting out a fishing line;</p>\n<p>an anchor grazes in a meadow’s grasses,</p>\n<p>or a curved keel sweeps above a vineyard,</p>\n<p>and the seal’s misshapen figure lies at rest</p>\n<p>where the slender goats were lately fond of browsing.</p>\n<p>The Nereids marvel at the sight of groves,</p>\n<p>cities, and dwelling places all submerged,</p>\n<p>while dolphins take possession of the woods</p>\n<p>and shake the lofty branches of the oak</p>\n<p>as they brush by. The wolf swims among sheep,</p>\n<p>the tawny lion and the tiger both</p>\n<p>are carried helplessly upon the waves;</p>\n<p>the boar’s great power, like a lightning bolt,</p>\n<p>does not avail nor do the stag’s swift limbs.</p>\n<p>After his long search for a landing place,</p>\n<p>the bird with weary wings collapses seaward.</p>\n<p>Now unrestrained, the sea conceals the hills,</p>\n<p>and strange new waves beat at the mountaintops;</p>\n<p>the greater part are drowned beneath the waves,</p>\n<p>while those spared drowning perish of starvation.</p>\n</blockquote>\n\nJove stops the flood when he realizes the two human survivors are devout. After describing how the floods recede, Ovid recounts what Deucalian, the last man alive, says to his wife Pyrrha:\n\n<blockquote class=\"poetry\">\n<p>“O sister, wife, and only woman left,</p>\n<p>you whom the bonds of race and family</p>\n<p>and our marriage bed have joined to me,</p>\n<p>we are now joined by our common perils—</p>\n<p>for we two are the crowd that fills the lands</p>\n<p>seen by the rising and the setting sun—</p>\n<p>we two are all: the sea now has the others.</p>\n<p>And our claim upon our lives is still</p>\n<p>doubtful, for those storm clouds frighten me!</p>\n<p>And how would you be feeling, my poor wretch,</p>\n<p>if fate had snatched you from the flood without me?</p>\n<p>How would you bear this terror all alone?</p>\n<p>Who would console you in your unshared grief?</p>\n<p>For trust me, if the sea had taken you,</p>\n<p>I would have followed then, my wife; the sea</p>\n<p>would not have taken one of us, but two.”</p>\n</blockquote>\n\nWhile few stories in the _Metamorphoses_ are original, Ovid gives the old characters a new psychological depth; Deucalion’s terror at being the only human alive is vivid example of this.\n\nOvid explains how life was biogenerated from the muck (an accepted theory at the time):\n\n<blockquote class=\"poetry\">\n<p>It is when heat and moisture join as one</p>\n<p>that life is generated; all living forms</p>\n<p>originate from these opposing sources</p>\n</blockquote>\n\nThe Python is among the forms that are generated, and Ovid tells the tale of Apollo killing the Python (and establishing the Pythian games to ensure memory of his great dead). Next, Ovid weaves in the first rape story of the _Metamorphoses_:\n\n<blockquote class=\"poetry\">\n<p>Daphne, the daughter of the river god</p>\n<p>Peneus, was the first love of Apollo;</p>\n<p>this happened not by chance, but by the cruel</p>\n<p>outrage of Cupid; Phoebus, in the triumph</p>\n<p>of his great victory against the Python,</p>\n<p>observed him bending back his bow and said,</p>\n<p>“What are <em>you</em> doing with such manly arms,</p>\n<p>lascivious boy? That bow befits <em>our</em> brawn,</p>\n<p>wherewith we deal out wounds to savage beasts</p>\n<p>and other mortal foes, unerringly:</p>\n<p>just now with our innumerable arrows</p>\n<p>we managed to lay low the mighty Python,</p>\n<p>whose pestilential belly covered acres!</p>\n<p>Content yourself with kindling love affairs</p>\n<p>with your wee torch—and don’t claim <em>our</em> glory!”</p>\n<p>The son of Venus answered him with this:</p>\n<p>“Your arrow, Phoebus, may strike everything;</p>\n<p>mine will strike you: as animals to gods,</p>\n<p>your glory is so much less than mine!”</p>\n</blockquote>\n\nOvid’s ability to weave one story into the next makes the Metamorphoses a joy to read. Here, Apollo’s pride at defeating the Python causes him to foolishly boast, propelling us into the next story while also presenting a compelling example of overconfidence.\n\nDaphne escapes, but Io is less fortunate. Jove rapes her, and then he turns her into a cow to hide her from Juno, who, knowing as much, convinces him to hand over the cow. Juno places Argus to watch over her:\n\n<blockquote class=\"poetry\">\n<p>… Argus, the watchman with a hundred eyes:</p>\n<p>in strict rotation, his eyes slept in pairs,</p>\n<p>while those that were not sleeping stayed on guard.</p>\n<p>No matter where he stood, he looked at Io,</p>\n<p>even when he had turned his back on her.</p>\n</blockquote>\n\nWhile a cow, Io’s father makes an interesting comment:\n\n<blockquote class=\"poetry\">\n<p>“Nor can I end this suffering by death;</p>\n<p>it is a hurtful thing to be a god,</p>\n<p>for the gates of death are firmly closed against me,</p>\n<p>and our sorrows must go on forever.”</p>\n</blockquote>\n\nJove can’t bear to watch her pain, so he sends Mercury to kill Argus. Mercury lulls Argus to sleep with a tale:\n\n<blockquote class=\"poetry\">\n<p>Now Mercury was ready to continue [his story]</p>\n<p>until he saw that Argus had succumbed,</p>\n<p>for all his eyes had been closed down by sleep.</p>\n<p>He silences himself and waves his wand</p>\n<p>above those languid orbs to fix the spell.</p>\n<p>Without delay he grasps the nodding head</p>\n<p>and where it joins the neck, he severs it</p>\n<p>with his curved blade and flings it bleeding down</p>\n<p>the steep rock face, staining it with gore.</p>\n<p>O Argus, you are fallen, and the light</p>\n<p>in all your lamps is utterly put out:</p>\n<p>one hundred eyes, one darkness all the same!</p>\n<p>But Saturn’s daughter rescued them and set</p>\n<p>those eyes upon the feathers of her bird,</p>\n<p>filling his tail with constellated gems.</p>\n</blockquote>\n\nMany of Ovid’s stories explain the origin of species (especially of birds), rivers, springs, and constellations.\n\nNote that the tale that Mercury tells Argus is about the rape of Syrinx; rape is so common that the story puts Argus to sleep (although his wand may have helped too).\n\n## Book II\n\nThe tale of Phaëthon’s doomed journey is one of my favourite in Ovid. Here is the description of Apollo’s throne room:\n\n<blockquote class=\"poetry\">\n<p>Phoebus sat</p>\n<p>In robes of purple high upon a throne</p>\n<p>that glittered brilliantly with emeralds;</p>\n<p>and in attendance on his left and right</p>\n<p>stood Day and Month and Year and Century,</p>\n<p>and all the Hours, evenly divided;</p>\n<p>fresh Spring was there, adorned with floral crown,</p>\n<p>and Summer, naked, bearing ripened grain,</p>\n<p>and Autumn, stained from treading out her grapes,</p>\n<p>and Winter with his grey and frosty locks.</p>\n</blockquote>\n\nWhen describing the burning Earth, Ovid’s description alludes back to the _Iliad_ (20.60–67):\n\n<blockquote class=\"poetry\">\n<p>The soil cracks everywhere, and now the light</p>\n<p>seeps to the underworld and terrifies</p>\n<p>its ruler and his wife</p>\n</blockquote>\n\nAfter Zeus kills Phaëthon with lightening, Apollo mourns:\n\n<blockquote class=\"poetry\">\n<p>His miserable father, sick with grief,</p>\n<p>drew his cloak up around his head in mourning;</p>\n<p>for one whole day then, if the tale is true,</p>\n<p>the sun was quite put out. The conflagration</p>\n<p>(for the world was still ablaze) provided light;</p>\n<p>that was a time some good came out of evil.</p>\n</blockquote>\n\nThe stories in the _Metamorphoses_ frequently refer to earlier incidents. For example:\n\n<blockquote class=\"poetry\">\n<p>When Apollo heard</p>\n<p>the accusation brought against his lover,</p>\n<p>the laurel resting on his brow slipped down;</p>\n<p>in not as much time as it takes to tell,</p>\n<p>his face, his lyre, his high color fell!</p>\n</blockquote>\n\nAlso, when Juno is departing from Tethys and Oceanus in Book II, she rides up on “peacocks fitted out with Argus’ eyes”—another reference to book I.\n\nThe reference to the laurel tree refers back to the Daphne story in Book I—perhaps hinting that Apollo has already moved on to another lover.\n\nAlmost all of the stories end with physical transformations. I like how Ovid describes Ocyrhoë’s transformation into a horse:\n\n<blockquote class=\"poetry\">\n<p>It seems my human form is being taken:</p>\n<p>the thought of grass for dinner pleases me,</p>\n<p>and open fields, where I can freely ride</p>\n<p>as I become my relative—a mare!</p>\n<p>Whole horse? But why? My father is but a centaur!”</p>\n<p>Her whining, waning, becomes whinnying,</p>\n<p>as mind and speech both grow confused together,</p>\n<p>and for a moment seemed a sound between</p>\n<p>the noise a horse makes and a human word,</p>\n<p>more like someone who imitates a horse,</p>\n<p>before the sound turned clearly into neighing,</p>\n<p>as she went on all fours through the tall grass.</p>\n<p>Her fingers fused together and a single</p>\n<p>band of light horn surrounded them, a hoof.</p>\n<p>Her neck and mouth were both increased in size</p>\n<p>and her long robe was turned into a tail</p>\n<p>while the hair that used to stray across her neck</p>\n<p>became a mane that fell on her right side;</p>\n<p>made over now in voice and form completely,</p>\n<p>this transformation gave her a new name.</p>\n</blockquote>\n\nThe story of Mercury stealing Apollo’s cattle is also told in the Homeric Hymn to Dionysus. Ovid’s version is shorter, and there are differences, but in both there is an old man who betrays the location of the cattle. (In Ovid’s version the man is less devout and gives away the location confidentially and with little hesitation). It is intriguing to see the development of the story over several centuries.\n\nMinerva visits the goddess Envy to have her enact revenge on irreverent follower. The description of Envy is, even for Ovid, exceptionally vivid:\n\n<blockquote class=\"poetry\">\n<p>She headed straight to Envy’s squalid quarters,</p>\n<p>black with corruption, hidden deep within</p>\n<p>a sunless valley where no breezes blow,</p>\n<p>a sad and sluggish place, richly frigid,</p>\n<p>where cheerful fires die upon the hearth</p>\n<p>and fog that never lifts embraces all.</p>\n<p>Arriving here, the warlike maiden stood</p>\n<p>before the house (for heaven’s law denied</p>\n<p>her entrance) and with her spear tip rapped</p>\n<p>upon the doors, which instantly flew open,</p>\n<p>revealing Envy at her feast of snakes,</p>\n<p>a fitting meal for her corrupted nature:</p>\n<p>from such a sight, the goddess turned away.</p>\n<p>The object of her visit sluggishly</p>\n<p>arises from the ground where she’d been sitting,</p>\n<p>leaving behind her interrupted dinner</p>\n<p>of half-eaten reptiles. Stiffly she advances,</p>\n<p>and when she sees the beauty of the goddess</p>\n<p>and of her armor, she cannot help but groan,</p>\n<p>and makes a face, and sighs a wretched sigh.</p>\n<p>Then she grows pale, and her body shrivels up.</p>\n<p>Her glance is sidewise and her teeth are black;</p>\n<p>her nipples drip with poisonous green bile,</p>\n<p>and venom from her dinner coats her tongue;</p>\n<p>she only smiles at sight of another’s grief,</p>\n<p>nor does she know, disturbed by wakeful cares,</p>\n<p>the benefits of slumber; when she beholds</p>\n<p>another’s joy, she falls into decay,</p>\n<p>and rips down only to be ripped apart,</p>\n<p>herself the punishment for being her.</p>\n</blockquote>\n\nAfter Io and Callisto, Jove pursues Europa:\n\n<blockquote class=\"poetry\">\n<p>Majestic power and erotic love</p>\n<p>do not get on together very well,</p>\n<p>nor do they linger long in the same place:</p>\n<p>the father and the ruler of all gods,</p>\n<p>who holds the lightning bolt in his right hand</p>\n<p>and shakes the world when he but nods his head,</p>\n<p>now relinquishes authority and power,</p>\n<p>assuming the appearance of a bull</p>\n<p>to mingle with the other cattle, lowing</p>\n<p>as gorgeously he strolls in the new grass.</p>\n</blockquote>\n\n## Book III\n\nAfter Europa is stolen, her father “in an action bother paternal and perverse” demands that Cadmus, her brother, find her. Unable to, he decides to flee Tyre and found the new city of Boeotian Thebes. Incidentally, Herodotus believed that Cadmus brought the Phoenician alphabet to the Greeks (_The Histories_ 5.58).\n\nWhile founding Thebes, a great serpent kills many of Cadmus’ men, and so he pursues and kills the serpent. Afterwards, Athena instructs him to sow the serpent’s seeds into the ground.\n\n<blockquote class=\"poetry\">\n<p>And then, incredibly, the dull clods stir:</p>\n<p>at first only the little tips of spears</p>\n<p>are visible, emerging from the furrows,</p>\n<p>but these, almost at once are followed by</p>\n<p>the brightly painted waving crests of helmets</p>\n<p>then shoulders, breasts, and arms heavy with weapons,</p>\n<p>and finally a dense-packed mass of shields:</p>\n<p>no different from what you will have seen</p>\n<p>on feats days, in the theater, when the curtain</p>\n<p>lifts from the pit, and the images of men</p>\n<p>painted upon it seem to rise: heads first,</p>\n<p>and then the rest of them, little by little,</p>\n<p>drawn up in one unbroken wave until</p>\n<p>the tiny figures stand erect onstage,</p>\n<p>complete in all respects, from head to feet.</p>\n</blockquote>\n\nAnd then these men fight each other until Athena stops them. These so-called sown men (Spartoi) founded Thebes with Cadmus. I think this is the oddest story in the Metamorphoses, and I wonder what significance it had to the ancient Greeks.\n\n<blockquote class=\"poetry\">\n<p>Thebes has been founded now, and even though</p>\n<p>an exile still, you might seem fortunate</p>\n<p>in having Mars and Venus as your in-laws,</p>\n<p>Cadmus; nor is this all, for in addition</p>\n<p>are offspring worthy of your noble wife,</p>\n<p>your sons and daughters, the pledges of your love,</p>\n<p>and grandsons too, already grown to manhood.</p>\n<p>But “fortunate”? A judgment best reserved</p>\n<p>for a man’s last day: call no one blest, until</p>\n<p>he dies and the last rites are said for him.</p>\n</blockquote>\n\nThis reasoning is pervasive in Herodotus.\n\nActaeon stumbles across the virgin goddess Diana, who spitefully turns him into a stag. He is subsequently torn to pieces by his own pack of hunting dogs. (In the _Epic of Gilgamesh_, when Gilgamesh is rejecting Ishtar’s love entreaties, he mentions how she turned a prior lover into a wolf who was then chased by his own hunting dogs.)\n\nActaeon is caught, and his dogs tear him to pieces.\n\n<blockquote class=\"poetry\">\n<p>And it is said</p>\n<p>he did not die until his countless wounds</p>\n<p>had satisfied Diana’s awful wrath.</p>\n<p>Folks were divided: there were those who found</p>\n<p>the goddess’s actions cruel and unjust,</p>\n<p>while others considered them appropriate</p>\n<p>to the defense of her austere virginity.</p>\n<p>As usual, both parties had their reasons.</p>\n</blockquote>\n\nThroughout the _Metamorphoses_ Ovid playfully questions the god’s morals, as in this quote.\n\nAfter the Actaeon story, Jove falls for Semele—Cadmus’ daughter. Semele becomes pregnant and Juno, to protect her honor, tricks Semele into requesting Jove make love to her the way he does to Juno. Unbeknownst to Semele, this will kill her. Juno takes the form of Semele’s nurse.\n\n<blockquote class=\"poetry\">\n<p>A long, inveigling chat of this and that,</p>\n<p>until Jove’s name came up. Nurse sighted and said,</p>\n<p>“I <em>hope</em> he’s Jupiter—although I doubt it:</p>\n<p>the divinity plea? An all-to-common ploy</p>\n<p>among seducers. Suppose he is, though:</p>\n<p>make him provide assurance of his love;</p>\n<p>if he’s the real thing, ask him to put on</p>\n<p>all of the trappings of his high office</p>\n<p>and embrace you, showing such almighty splendor</p>\n<p>as when he is received by Lady Juno.”</p>\n</blockquote>\n\n(It is difficult to imagine a woman being seduced by a man claiming to be a god.)\n\nAfter Juno gets her revenge on Semele, her next victim is Tiresias. Tiresias is blinded for agreeing with Jove that women enjoy sex more than men. Tiresias is then blinded by Juno, but Jove (since “one god can’t undo another’s doing”) gives him the gift of prophecy. Jove seems to enjoy thwarting Juno’s punishments—consider also the Callisto story.\n\nTiresias is a recurring character in the Greek tragedies.\n\nTiresias’ first prediction is that Narcissus, if he knows himself, will not live to old age. The meaning of this was unclear, until Narcissus falls in love with himself. Then Tiresias becomes famous.\n\n<blockquote class=\"poetry\">\n<p>“But <em>now</em> I get it! <em>I</em> am that other one!</p>\n<p>I’ve finally seen through my own image!</p>\n<p>I burn with love for—<em>me</em>! The spark I kindle</p>\n<p>is the torch I carry: whatever can I do?</p>\n<p>Am I the favor-seeker, or the favor sought?</p>\n<p>“Why seek at all, when all that I desire</p>\n<p>is mine already? Riches in such abundance</p>\n<p>that I’ve been left completely without means!”</p>\n</blockquote>\n\nOvid paints a compelling, yet humorous, picture of obsession with his description of Narcissus’ death:\n\n<blockquote class=\"poetry\">\n<p>His last words were directed to the pool:</p>\n<p>“Alas, dear boy, whom I have vainly cherished!”</p>\n<p>Those words returned to him again, and when</p>\n<p>he cried “Farewell!” “<em>Farewell!</em>” cried Echo back.</p>\n<p>His weary head sank to the grass; death closed</p>\n<p>those eyes transfixed once by their master’s beauty,</p>\n<p>but on the ferry ride across the Styx,</p>\n<p>his gaze into its current did not waver.</p>\n</blockquote>\n\nAcoetes’ story is similar to the seventh Homeric Hymn to Dionysus.\n\n## Book IV\n\nMost of Book IV is a sequence of stories told by the Minyas daughters, who refuse to join Bacchus’ festival.\n\nThe first of their stories, of the suicide of Pyramus and Thisbe, is the original inspiration that lead Shakespeare’s Romeo and Juliet (with a few other versions in between). Pyramus’ suicide is described with an epic simile:\n\n<blockquote class=\"poetry\">\n<p>“He carries Thisbe’s cloak to the tree of their pact,</p>\n<p>and presses tears and kisses on the fabric.</p>\n<p>‘Drink <em>my</em> blood now,’ he says, drawing his sword,</p>\n<p>and thrusting it at once in his own guts:</p>\n<p>a fatal blow; dying, he draws the blade</p>\n<p>out of his burning wound, and his lifeblood</p>\n<p>follows it, jetting high into the air,</p>\n<p>as he lies on his back upon the ground.</p>\n<p>It was as when a water pipe is ruptured</p>\n<p>where the lead has rotted, and it springs a leak:</p>\n<p>a column of water goes hissing through the hole</p>\n<p>and parts the air with its pulsating thrusts;</p>\n<p>splashed with his gore, the tree’s pale fruit grow dark;</p>\n<p>blood soaks its roots and surges up to dye</p>\n<p>the hanging berries purple with its color.”</p>\n</blockquote>\n\nThe two lovers planned to meet at the tomb of Ninus, who was the king of Assyria and husband of Semiramis. Semiramis was a legendary queen of Assyria. She is often associated with the historical queen Sammurāmat who ruled from 811 - 808 BC.\n\nThe story of Hermaphroditus is a rare example of a woman (sort of) raping a man. The description includes a progression of similes:\n\n<blockquote class=\"poetry\">\n<p>“‘I’ve won, the boy is mine!’</p>\n<p>the nymph cries out, and tearing off her clothing,</p>\n<p>she dives into the middle of the pool,</p>\n<p>and though he fights her, holds him in her clutches,</p>\n<p>seizing the kisses he is loath to yield;</p>\n<p>her hands surprise him, coming from below,</p>\n<p>caressing that reluctant breast of his—</p>\n<p>although he strives to tear himself away,</p>\n<p>the nymph—now here, now there—surrounds her prey,</p>\n<p>just as the serpent wraps herself around</p>\n<p>the eagle when he grasps her in his talons</p>\n<p>and takes her up: dangling from his claws,</p>\n<p>she twines herself between his head and feet</p>\n<p>and with her tail, immobilizes him;</p>\n<p>or just as ivy winds around a tree,</p>\n<p>and as the octopus beneath the sea</p>\n<p>securely binds the prey that it has captured</p>\n<p>with tentacles sent out in all directions;</p>\n<p>yet still the boy denies the nymph her bliss’”</p>\n</blockquote>\n\nA description of the underworld:\n\n<blockquote class=\"poetry\">\n<p>There are a thousand ways into this city,</p>\n<p>and open gates on all sides; as the ocean</p>\n<p>receives the rivers from around the world,</p>\n<p>so this place gathers in all mortal souls,</p>\n<p>and never fills, however many come.</p>\n<p>Here bloodless, boneless, bodiless shades stray:</p>\n<p>some make their way to the forum; others seek</p>\n<p>the palace of the ruler of the dead,</p>\n<p>or take up once again the crafts they lived by.</p>\n</blockquote>\n\nJuno’s frustrated jealous rage fills much of the first four books of Ovid. She eventually drives Cadmus and Harmonia into ruin. Although Juno caused much of their suffering, the story of their transformation (which has may favourite imagery in the book) implies that it was Cadmus’ killing of the serpent that lead to his woes:\n\n<blockquote class=\"poetry\">\n<p>“Was it a sacred serpent that I speared,”</p>\n<p>asked Cadmus, “when, newly come from Sidon,</p>\n<p>I sprinkled the viper’s teeth upon the ground,</p>\n<p>and seeded a new crop of human beings?</p>\n<p>If that is what the gods have been avenging</p>\n<p>by their unwavering wrath for all these years,</p>\n<p>why then, I pray that I might be extended</p>\n<p>into a serpent with a gut-like shape—”</p>\n<p>And as he said it he became a serpent</p>\n<p>with a gut-like shape. At once he felt the scales</p>\n<p>begin to grow out on his thickened skin,</p>\n<p>and his dark body lighten up with patches</p>\n<p>of iridescent blue; he fell upon his breast,</p>\n<p>and his two legs were blended into one,</p>\n<p>which, gradually lengthening, became</p>\n<p>an elegant and sharply pointed tail.</p>\n<p>His arms remained unchanged; he held them out,</p>\n<p>and as the tears coursed down his cheeks (which were</p>\n<p>still—for the moment—human), he exclaimed,</p>\n<p>“Come closer to me, O most wretched wife,</p>\n<p>and while there is still something left of me,</p>\n<p>before I am entirely transformed</p>\n<p>to serpent, touch me, take these hands in yours!”</p>\n<p>He would have said much more, but suddenly</p>\n<p>the tip of his tongue divided into two,</p>\n<p>and words no longer would obey his wishes,</p>\n<p>so that whenever he tried to complain</p>\n<p>or grieve, he hissed, and could not manage more,</p>\n<p>for he had been left with no other voice.</p>\n<p>Now striking her bare breast, his wife cries out,</p>\n<p>“Cadmus! Stay as you are! Put off these strange</p>\n<p>shapes now possessing you, unfortunate man!</p>\n<p>Cadmus, what’s happening? Where are your feet?</p>\n<p>Your face? Complexion? Even as I speak,</p>\n<p>where is the rest of you! Heavenly beings,</p>\n<p>will you not also turn me to a snake?”</p>\n<p>The creature’s tongue flicked lightly over her lips,</p>\n<p>and he slipped in between her cherished breasts</p>\n<p>as though he were familiar with the place,</p>\n<p>embraced her, and slid right around her neck.</p>\n<p>Those of his companions who were present</p>\n<p>were horrified, but she just calmly stroked</p>\n<p>the smooth, sleek neck of the crested dragon,</p>\n<p>and at once there were two serpents intertwined,</p>\n<p>who presently went crawling off and found</p>\n<p>a hiding place within a nearby grove.</p>\n</blockquote>\n\nPerseus turns Atlas into a mountain:\n\n<blockquote class=\"poetry\">\n<p>Atlas became a mountain just as large</p>\n<p>as the man had been. His hair and beard became</p>\n<p>a forest, and his arms and shoulders turned</p>\n<p>into adjacent ridges; his head was now</p>\n<p>the mountain’s summit and his bones were rock.</p>\n<p>Each part grew to extraordinary size</p>\n<p>(as you immortals had ordained), until</p>\n<p>the weight of heaven rested on his shoulders.</p>\n</blockquote>\n\n## Book V\n\nPerseus slays many men at his wedding to Andromeda, when her prior betrothed casts a spear at him. The scene seems to contrast and slyly tease Homer’s epic death scenes. One of my favourite is:\n\n<blockquote class=\"poetry\">\n<p>Pedasus, grinning,</p>\n<p>saw how he kept himself and his instrument</p>\n<p>out of harm’s way, and shouted to him, “Sing</p>\n<p>the remainder of your song to the shades below,”</p>\n<p>lodging his shaft above the bard’s left eye;</p>\n<p>and as he fell, his dying fingers struck</p>\n<p>the lyre’s strings, and on that plaintive note</p>\n<p>the poet and his song came to an end.</p>\n</blockquote>\n\nAfter describing dying men, one after another, Ovid says:\n\n<blockquote class=\"poetry\">\n<p>It really would take far too long to name</p>\n<p>the ordinary soldiers</p>\n</blockquote>\n\nMinerva visits the nine muses, who tell of the nine sisters who challenged their supremacy and of the contest between them, and retell the story by which they won the contest. As part of this story, Venus makes the following comment:\n\n<blockquote class=\"poetry\">\n<p>“‘“My son [Cupid], my sword, my strong right arm and source of my power,</p>\n<p>take up that weapon by which all your victims are vanquished</p>\n<p>and send your swift arrows into the breast of the deity</p>\n<p>to whom the last part of the threefold realm was allotted.</p>\n<p>You govern the gods and their ruler; you rule the defeated</p>\n<p>gods of the ocean and govern the one who rules them, too;</p>\n<p>why give up on the dead, when we can extend our empire</p>\n<p>into their realm? A third part of the world is involved here!</p>\n<p>And yet the celestial gods spurn our forbearance,</p>\n<p>and the prestige of Love is diminished, even as mine is.</p>\n<p>Do you not see how Athena and huntress Diana</p>\n<p>have both taken leave of me? The virgin daughter of Ceres</p>\n<p>desires to do likewise—and will, if we let her!</p>\n<p>But if you take pride in our alliance, advance it</p>\n<p>by joining her to her uncle!”‘“</p>\n</blockquote>\n\nVenus’ impulse leads to the rape of Persephone and (so they say) the rotation of the seasons.\n\n## Book VI\n\nThis book continues the theme of divine revenge:\n\n<blockquote class=\"poetry\">\n<p>“To praise is insufficient,” she [Minerva] reflected;</p>\n<p>“we will be praised—and we will not permit</p>\n<p>those who belittle our divinity</p>\n<p>to go unpunished!”</p>\n</blockquote>\n\nMinerva contests the Arachne—an expert weaver. Although she loses, she turns her competitor into a spider.\n\nThis simile from their contest is superb:\n\n<blockquote class=\"poetry\">\n<p>Into their fabrics they weave purple threads</p>\n<p>of Tyrian dye, and place beside them shades</p>\n<p>that lighten imperceptibly from these;</p>\n<p>as when a storm ends and the sun comes out,</p>\n<p>a rainbow’s arch illuminates the sky;</p>\n<p>although a thousand colors shine in it,</p>\n<p>they eye cannot say where one color ends</p>\n<p>and another starts, so gradual the verging;</p>\n<p>there in the middle, the colors look the same,</p>\n<p>while, at the edges, they seem different.</p>\n</blockquote>\n\nThe brief stories of Marsyas the Satyr and Pelops (Tantalus’ son) feel undeveloped and seem to be included because merely due the transformations involved.\n\nThe story of Tereus, the marauder from Thrace, and the Athenian sister-princesses, Procne and Philomela, is disturbing. Procne is given in marriage to Tereus, to prevent the defeat of Athens. After a few years, she asks her wicked husband to retrieve her sister—but he lusts after her:\n\n<blockquote class=\"poetry\">\n<p>And now delay was unendurable:</p>\n<p>he eagerly repeated Procne’s speech,</p>\n<p>and raised his own desires under hers.</p>\n<p>Love lent him eloquence, and when he seemed</p>\n<p>to go beyond the mandate he’d been given,</p>\n<p>he said that this was merely Procne’s wish,</p>\n<p>and added tears, as though they too were part</p>\n<p>of his commission. By the gods above,</p>\n<p>what utter blindness dwells in human hearts!</p>\n<p>Here Tereus achieves a reputation</p>\n<p>for piety while plotting wickedness,</p>\n<p>and criminal behavior wins him praise!</p>\n</blockquote>\n\nAfter trapping Philomela in a house in the woods and raping her, she cries:\n\n<blockquote class=\"poetry\">\n<p>“Nevertheless, if the gods are watching this,</p>\n<p>if heavenly power means anything at all,</p>\n<p>if, with my honor, all has not been lost,</p>\n<p>somehow or other I will punish you;</p>\n<p>I’ll cast aside my modesty and speak</p>\n<p>of what you’ve done; if I escape this place,</p>\n<p>I’ll go among the people with my tale;</p>\n<p>imprisoned here, my voice will fill the trees</p>\n<p>and wring great sobs of grief from senseless rocks!</p>\n<p>Heaven will hear me, and what gods there are,</p>\n<p><em>if</em> there are any gods in all of heaven!”</p>\n<p>Such words provoke the savage tyrant’s wrath</p>\n<p>and fear in equal measure</p>\n</blockquote>\n\nHe proceeds to cut out her tongue.\n\n## Book VII\n\nBook VII begins with the story of Jason and the Golden Fleece.\n\nMedea’s monologues are brilliant.\n\n<blockquote class=\"poetry\">\n<p>“All your resistance is in vain, Medea;</p>\n<p>what god opposes you, I do not know—</p>\n<p>I wonder if this isn’t love, so called,</p>\n<p>or something rather like it—for why else</p>\n<p>would these ordeals imposed upon the strangers</p>\n<p>by my own father seem too harsh to me?</p>\n<p>Because they <em>are</em>! Why do I fear that one</p>\n<p>whom I have only just now seen will die?</p>\n<p>What is the power that can cause such fear?</p>\n<p>There is a fire in your untried heart,</p>\n<p>poor wretched girl! Dislodge it if you can!</p>\n<p>I’d act more sanely, if I only could,</p>\n<p>but this new power overwhelms my will;</p>\n<p>reason advises this, and passion, that;</p>\n<p>I see the better way, and I approve it,</p>\n<p>while I pursue the worse.”</p>\n</blockquote>\n\nThese lines remind me of Paul’s letter to the Romans, where he says:\n\n<blockquote>\n<p>I do not understand my own actions. For I do not do what I want, but I do the very thing I hate. Now if I do what I do not want, I agree that the law is good. But in fact it is no longer I that do it, but sin that dwells within me. For I know that nothing good dwells within me, that is, in my flesh. I can will what is right, but I cannot do it. For I do not do the good I want, but the evil I do not want is what I do. Now if I do what I do not want, it is no longer I that do it, but sin that dwells within me. <cite>(Romans 7.15–20)</cite></p>\n</blockquote>\n\nIn Medea’s speech, we hear her grasp onto a small reason to wish Jason well, and slowly expand and rationalize her thoughts. She continues going back and forth. At some point, she weighs whether she can trust Jason, even if she betrays her father:\n\n<blockquote class=\"poetry\">\n<p>“Will I betray the kingdom of my father,</p>\n<p>only to have the stranger whom I save</p>\n<p>set sail without me for another’s bed,</p>\n<p>leaving Medea to her punishment?</p>\n<p>If he could do that, leave me for another,</p>\n<p>let the ingrate die! But no: that isn’t in him,</p>\n<p>not in his face, not in his noble spirit,</p>\n<p>not in a man as beautiful as he,</p>\n<p>that I should fear duplicity from him,</p>\n<p>or his neglecting what I am deserved.”</p>\n</blockquote>\n\nThese lines may ironically refer to Euripides’ play, _Medea_. Note that beauty and goodness are thought to be correlated.\n\nThe virgin princess weaves back and forth, but, upon seeing Jason again, decides to betray her family and flee with him.\n\n<blockquote class=\"poetry\">\n<p>Here she was resolute, and her impulsive</p>\n<p>ardor would appear to be extinguished—</p>\n<p>but broke out once again at sight of Jason:</p>\n<p>her cheeks reddened, and a suffusing glow</p>\n<p>spread across her countenance completely,</p>\n<p>as when a spark that has been hidden under</p>\n<p>a crust of ash is nourished by a breeze</p>\n<p>and comes to life again as it’s stirred up,</p>\n<p>regaining all the vigor it once had;</p>\n<p>just so her smoldering love, which you’d have thought</p>\n<p>was almost out, came blazing up anew,</p>\n<p>to see the young man standing in her presence,</p>\n<p>and—as it happened—looking even better</p>\n<p>than usual. You would have understood</p>\n<p>and pardoned her for her infatuation.</p>\n</blockquote>\n\nAfter returning to Greece, Jason begs Medea to give his father a potion to lengthen his life. She complies:\n\n<blockquote class=\"poetry\">\n<p>After nine days and nights had seen Medea</p>\n<p>in her dragon-drive chariot, traversing</p>\n<p>the skies above those regions, she returned</p>\n<p>to her own home; her reptiles had been touched</p>\n<p>only by the <em>odors</em> of those herbs,</p>\n<p>and yet they shed the skins of their old age!</p>\n</blockquote>\n\nOvid pokes fun at readers by not including the full list of ingredients:\n\n<blockquote class=\"poetry\">\n<p>When, with these,</p>\n<p>and with a thousand other such ingredients</p>\n<p>(whose names we needn’t bother mentioning),</p>\n<p>the miracle to come had been arranged,</p>\n<p>the foreign woman took a long-dead branch</p>\n<p>from a fruitful olive tree and stirred her pot,</p>\n<p>mixing it thoroughly from top to bottom.</p>\n<p>But look! Almost at once, that stick turned green,</p>\n<p>and just a short time later put out leaves,</p>\n<p>and suddenly was loaded down with fruit!</p>\n</blockquote>\n\nAs Medea flies from this gruesome scene, Ovid lists transformation stories. Then, in a few succinct lines, he tells the story of Jason’s betrayal and Medea’s revenge:\n\n<blockquote class=\"poetry\">\n<p>But after the new bride that Jason took</p>\n<p>was poisoned by the old wife he forsook,</p>\n<p>and fisherfolk off Corinth glimpsed through haze</p>\n<p>the ruined palace of the king ablaze,</p>\n<p>the blade that dripped with her own children’s gore</p>\n<p>enraged their father, whom she fled before,</p>\n<p>her fatal vengeance leaving all undone!</p>\n</blockquote>\n\nAfter Aegeus discovers his unknown son, Theseus, there is a big celebration. Then Ovid gives us this pithy line:\n\n<blockquote class=\"poetry\">\n<p>And yet, no joy is ever unalloyed,</p>\n<p>and worry worms its way into delight</p>\n</blockquote>\n\nAegeus is worried about King Minos, who wants to revenge his dead son. Fortuneatly, Athens has a loyal ally ruling over Aegina. Cephalus seeks aid, and king Aeacus of Aegina recounts the story of the plague:\n\n<blockquote class=\"poetry\">\n<p>“At first the animals</p>\n<p>alone succumbed: the plague confined itself</p>\n<p>to dogs, birds, sheep, cattle, and wild beasts:</p>\n<p>the luckless plowman is quite stunned to see</p>\n<p>his healthy bulls collapsing at their work,</p>\n<p>falling in midfurrow; woolly flocks</p>\n<p>give a few feeble bleats, then, without help,</p>\n<p>shed their thick coats, grow wasted and soon die;</p>\n<p>the stall-bound horse, once famous for his speed,</p>\n<p>but now unworthy of his victories,</p>\n<p>ignores his former honors, whinnying</p>\n<p>as death prepares to scratch him from the race.</p>\n<p>The boar does not remember how to rage,</p>\n<p>nor the deer to trust in swiftness, nor the bear</p>\n<p>to cull the great herds with his fierce attacks;</p>\n<p>a languor seizes all; in woods, in fields,</p>\n<p>along the roads, the fetid corpses lie</p>\n<p>until the air is blighted with the stench.</p>\n<p>I’ll tell you something quite astonishing:</p>\n<p>the greedy dogs and vultures—even wolves!—</p>\n<p>left them untouched; those bodies fell apart,</p>\n<p>sickening us with their apalling odor</p>\n<p>and spreading foul contagion everywhere.</p>\n<p>The plague, grown stronger, now advances on</p>\n<p>the wretched country folk, then rules within</p>\n<p>the walls of the great city. Its first symptom</p>\n<p>is a fierce burning in the viscera,</p>\n<p>the hidden fire indicated by</p>\n<p>a flushed complexion, pain in drawing breath;</p>\n<p>the patient’s roughened tongue swells up with fever,</p>\n<p>and lips that have been parched by the hot winds</p>\n<p>gape widely, snatching at the torpid air—</p>\n<p>no bed nor covering is bearable;</p>\n<p>they fling themselves facedown upon the ground</p>\n<p>to cool their bodies off; but no: the heat</p>\n<p>of their poor bodies warms the earth instead!</p>\n<p>Ungovernable plague! The doctors die,</p>\n<p>their arts a harm to their practitioners,</p>\n<p>and those who are the closest to the sick,</p>\n<p>who serve most faithfully, are first to fall!</p>\n<p>⋯</p>\n<p>Can you imagine what my feelings were?</p>\n<p>Like those of anyone in such a case:</p>\n<p>I hated life and longed to share the fate</p>\n<p>of my own kind, for everywhere I looked</p>\n<p>the dead were strewn in heaps, without distinction,</p>\n<p>like rotten apples shaken from the bough</p>\n<p>or acorns that the wind strips from an oak.</p>\n<p>⋯</p>\n<p>Some freed themselves from the fear they had of death</p>\n<p>by taking their own lives—summoning Fate</p>\n<p>even as Fate prepared to summon them.</p>\n<p>No longer were the bodies of the dead</p>\n<p>carried in processions from the city</p>\n<p>for burial with the customary rites:</p>\n<p>no gates were wide enough for such a throng.</p>\n<p>Either they lay unburied on the ground</p>\n<p>or, without services, were stacked and burned;</p>\n<p>and now there are no honors for the dead;</p>\n<p>dying, men struggle over scraps of wood,</p>\n<p>and are cremated with a stranger’s flame.</p>\n<p>With none to mourn them, unlamented souls</p>\n<p>of parents and their children, the young, the old,</p>\n<p>wander about, their journey uncompleted:</p>\n<p>no wood is left to burn their bodies now,</p>\n<p>no bit of land where they may be interred.”</p>\n</blockquote>\n\n## Book VIII\n\nThe book opens with the story of Scylla, who like Medea, betrays her family and country after falling in love with a man:\n\n<blockquote class=\"poetry\">\n<p>“Love has led me</p>\n<p>into this betrayal; I am Scylla,</p>\n<p>the daughter of King Nisus; I surrender</p>\n<p>myself, my nation, and my gods as well,</p>\n<p>and seek no other recompense but you;</p>\n<p>receive this pledge that guarantees my love,</p>\n<p>this purple lock—which is no lock at all,</p>\n<p>but my father’s head!” She stretched out her foul hand</p>\n<p>with the proffered gift as Minos shrank away,</p>\n<p>shocked by the sight of this unholy act:</p>\n<p>“Shame of the age,” he said, “may the gods forbid you</p>\n<p>their kingdom, and may land and sea deny you!</p>\n<p>Be sure that I will never let so vile</p>\n<p>a monster into Crete”</p>\n</blockquote>\n\nIt is hard to imagine a woman falling in love with a man she hasn’t met and cutting her head off. Ovid’s portrayal of women’s sexual passion feels like pornographic male fantasy.\n\nIronically, when Minos returns to Crete, he realizes his wife had slept with a bull, letting a vile monster onto Crete.\n\n<blockquote class=\"poetry\">\n<p>The scandal of his family had grown</p>\n<p>past all concealment; now the mother’s foul</p>\n<p>adultery was proven by the strange</p>\n<p>form of the Minotaur, half man, half bull.</p>\n<p>Minos determined to remove the cause</p>\n<p>of this opprobrium from his abode,</p>\n<p>enclosing it within a labyrinth</p>\n<p>devised and built by Daedalus, the most</p>\n<p>distinguished of all living architects,</p>\n<p>who framed confusion and seduced the eye</p>\n<p>into a maze of wandering passages.</p>\n<p>Not otherwise than when Maeander pays</p>\n<p>his liquid games in the Phrygian fields</p>\n<p>and flowing back and forth uncertainly,</p>\n<p>observes its own waves bearing down on it,</p>\n<p>and sends its doubtful waters on their ways</p>\n<p>back to their source of down to the open sea:</p>\n<p>so Daedalus provided numberless</p>\n<p>confusing corridors and was himself</p>\n<p>just barely able to find his way out,</p>\n<p>so utterly deceitful was that place.</p>\n</blockquote>\n\nDaedalus builds wings and flees Crete with his son Icarus, who famously dies because he flies too close to the sun. I love these lines, describing bystanders watching:\n\n<blockquote class=\"poetry\">\n<p>Some fisherman whose line jerks with his catch,</p>\n<p>some idle shepherd leaning on his crook,</p>\n<p>some plowman at his plow, looks up and sees</p>\n<p>something astonishing, and thinks them gods,</p>\n<p>who have the power to pass through the air.</p>\n</blockquote>\n\nDaedalus is brilliant, but he also demonstrates terrible academic jealousy:\n\n<blockquote class=\"poetry\">\n<p>For, as it happened, the inventor’s sister,</p>\n<p>quite unaware of what the Fates intended,</p>\n<p>entrusted her own son to his instruction,</p>\n<p>a likely lad of twelve, who had a mind</p>\n<p>with the capacity for principles and precepts;</p>\n<p>and from his observation of the spines</p>\n<p>of fishes, which he’d taken as his model,</p>\n<p>incised a row of teeth in an iron strip</p>\n<p>and thereby managed to invent the saw.</p>\n<p>Likewise, he was the first to bind two arms</p>\n<p>of iron at a joint, so one is fixed</p>\n<p>and the other, as it moves, inscribes a circle.</p>\n<p>Daedalus envied him, and headlong hurled</p>\n<p>this lad of precepts from a precipice,</p>\n<p>the steep acropolis Minerva loves,</p>\n<p>and lying, said the lad had slipped and fallen.</p>\n</blockquote>\n\nWhen the apostle Paul visits Athens, he stood in front of the Areopagus, and said “Athenians, I see how extremely religious you are in every way. For as I went through the city and looked carefully at the objects of your worship, I found among them an altar with the inscription, ‘To an unknown god.’” I wonder if pagans worshiped the unknown god to ensure they aren’t forgetting to sacrifice to a god they are not aware of. The jealous anger of the pagan gods is common, here is a nice example:\n\n<blockquote class=\"poetry\">\n<p>Commencing with the rural deities,</p>\n<p>the gods all got the honors they desired;</p>\n<p>only Diana’s altar was ignored,</p>\n<p>and left, they say, without a gift of incense.</p>\n<p>Even the gods may be provoked to anger!</p>\n<p>“We will not let them get away with this,”</p>\n<p>Diana said, “Dishonored we may be;</p>\n<p>but none will say that we were unavenged!”</p>\n<p>And the spurned goddess sent her vengeful boar</p>\n<p>straightway onto the fields of Calydon:</p>\n<p>a beat as great as the bulls of Epirus,</p>\n<p>and mightier than those of Sicily,</p>\n<p>with blood and fire shining from his eyes</p>\n<p>and a neck stiff with bristles just like spear shafts;</p>\n<p>and as his chest heaved with his grating breast,</p>\n<p>his heavy shoulders dripped with seething spume;</p>\n<p>in length his tusks were like an elephant’s,</p>\n<p>and bolts of lightning issued from his mouth,</p>\n<p>and when he exhaled, trees turned black and died.</p>\n</blockquote>\n\nA band of heroes, including Nestor from the _Iliad_ and Jason of the Golden Fleece, sets out the kill the boar. A few heroes die, and after a fortunate spear ends its life, the heroes bicker over the honors of the dead. One tragedy leads to another, and before long Diana has completed her revenge. Ovid says:\n\n<blockquote class=\"poetry\">\n<p>Not even if some god had given me</p>\n<p>a hundred mouths, each fitted with a tongue,</p>\n<p>and genius suitable to the occasion,</p>\n<p>and all of Helicon for inspiration,</p>\n<p>not even then would I be able to</p>\n<p>describe the sad fate of his wretched sisters,</p>\n<p>who, careless of decorum, beat their breasts,</p>\n<p>and while his corpse was still displayed among them,</p>\n<p>caressed him constantly and gave him kisses,</p>\n<p>and even kissed the bier he was laid out on</p>\n</blockquote>\n\nSome of the heroes, upon their journey home from the hunt, are stopped at the overflowing river Acheloüs. They tell stories with the river to pass the time, including the story of some naiads turned into islands and my favourite story of Baucis and Philemon. Two gods in disguise look for a home to stay in. Many turn them down, but the old couple lets them in and, though pour, try to make them comfortable. The scene seems archetypal—disguised gods testing the devout (consider Abraham being visited by divine messengers).\n\n<blockquote class=\"poetry\">\n<p>“The gods reclined. And with her skirts hitched up,</p>\n<p>the trembling old lady set the table,</p>\n<p>correcting its imbalance with a potsherd</p>\n<p>slipped underneath the shortest of its legs;</p>\n<p>and when the table had been stabilized,</p>\n<p>she scrubbed its surface clean with fragrant mint.”</p>\n</blockquote>\n\nThe visitors magically refill the winebowl, and the couple realize they are gods.\n\n<blockquote class=\"poetry\">\n<p>“They had a single goose, the guardian</p>\n<p>of their small villa, whom they now prepared</p>\n<p>to sacrifice to their immortal guests;</p>\n<p>his swiftness, though, left the old pair exhausted.</p>\n<p>Time after time, he slipped out of their grasp,</p>\n<p>and then, it seemed, sought refuge with the gods,</p>\n<p>who would not let the couple do him in”</p>\n</blockquote>\n\nThe small expressions Ovid uses, like “the guardian of their small villa,” let one imagine the scene with so few words.\n\nThe gods destroy the town (similar to Sodom and Gomorrah), and ask the old couple what reward they want.\n\n<blockquote class=\"poetry\">\n<p>“‘We ask to be allowed to guard your temple</p>\n<p>as its priests, and, since we have lived together</p>\n<p>so many years in harmony, we ask</p>\n<p>that the same hour take us both together,</p>\n<p>and that I should not live to see her tomb</p>\n<p>nor she survive to bury me in min.’”</p>\n</blockquote>\n\nAcheloüs tells the story of Erysichton, who chopped down a sacred tree of Ceres, who soon sent famine to enact her revenge. Erysichton was so hungry he sold his daughter into slavery and eventually ate himself to death:\n\n<blockquote class=\"poetry\">\n<p>“But when at last his illness had consumed</p>\n<p>all that she brought him, and he still craved more,</p>\n<p>the wretched man began to tear his limbs</p>\n<p>asunder, mangling them in his maw,</p>\n<p>and fed his body as he shrank away.”</p>\n</blockquote>\n\n## Book IX\n\nHercules’ contempt of death, and the Greek ideal:\n\n<blockquote class=\"poetry\">\n<p>And as the eager flames began to spread,</p>\n<p>you draped the pelt of the Nemean lion</p>\n<p>over the top, and pillowing your head</p>\n<p>upon your club, you lay there at your ease,</p>\n<p>not otherwise than as you would have been</p>\n<p>reclining at a banquet, flower-wreathed,</p>\n<p>with wine to drink from cups always refilled.</p>\n<p>Now spreading out in every direction,</p>\n<p>the crackling flames came after Hercules,</p>\n<p>whose carefree limbs received them with contempt.</p>\n</blockquote>\n\nSince its lines contain little advice or philosophical insight, I read the _Metamorphoses_ primarily for their beauty and to know the myths referenced so often in paintings and later literature. Ovid’s psychological portrayals of tempted individuals, while maybe not realistic, have made me more empathetic. Media, Scylla, Byblis, and Myrrah—all lusting women, perhaps a weird obsession of Ovid—in particular are interesting. Here are a few quotes from the story of Byblis, who fell in love with her brother, demonstrating how her passion developed:\n\n<blockquote class=\"poetry\">\n<p>Her feelings for him gradually changed,</p>\n<p>and not for the better; when she visited</p>\n<p>her brother, she was elegantly dressed,</p>\n<p>and anxious that he find her beautiful,</p>\n<p>and envious of those who seemed more lovely.</p>\n<p>She was, as yet, unconscious of her feelings,</p>\n<p>and offered up no prayers for satisfaction,</p>\n<p>but burned with inner fire, nonetheless.</p>\n<p>She calls him “Master” now, and now detests</p>\n<p>the thought that they are siblings, and prefers</p>\n<p>that he should call her “Byblis” and not “Sister.”</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“But even if I keep them out of mind,</p>\n<p>there is no wrong in <em>dreaming</em> of such things</p>\n<p>as often as I want to, in my sleep!</p>\n<p>There are no witnesses to our dreams,</p>\n<p>and they provide a pleasure almost real!</p>\n<p>“O Cupid and sweet Venus, what great joys</p>\n<p>were given me! And how real they seemed!</p>\n<p>My marrow melted as I lay asleep!</p>\n<p>How pleasing to remember! But how brief</p>\n<p>those pleasures were–the night, with breakneck speed,</p>\n<p>snatched them away, when they had just begun!”</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“The sons of Aeolus were not afraid</p>\n<p>to sleep with their sisters! How do I know this,</p>\n<p>and why have I come up with this example?</p>\n<p>Where is this leading me? Depart, indecent thoughts,</p>\n<p>and let me love my brother not at all,</p>\n<p>unless my move is sisterly and lawful!”</p>\n</blockquote>\n\nWhen her brother avoids her advances by fleeing to found a colony, Byblis goes insane and, crying in despair, is morphed into a spring.\n\nThe last story in this chapter is relevant for me, since my wife is pregant with a baby girl:\n\n<blockquote class=\"poetry\">\n<p>For, once upon a time, there lived in Phaestus</p>\n<p>a freeborn plebeian named Ligdus, who</p>\n<p>was otherwise unknown and undistinguished,</p>\n<p>with no more property than fame or status,</p>\n<p>and yet devout, and blameless in his life.</p>\n<p>His wife was pregnant. When her time had come,</p>\n<p>he gave her his instructions with these words:</p>\n<p>“There are two things I pray to heaven for</p>\n<p>on your account: an easy birth and a son.</p>\n<p>The other fate is much too burdensome,</p>\n<p>for daughters need what Fortune has denied us:</p>\n<p>a dowry. Therefore—and may God prevent</p>\n<p>this happening, but if, by chance, it does</p>\n<p>and you should be delivered of a girl,</p>\n<p>unwillingly I order this, and beg</p>\n<p>pardon for my impiety—<em>But let it die!</em>”</p>\n<p>He spoke, and tears profusely bathed the cheeks</p>\n<p>of the instructor and instructed both.</p>\n<p>Telethusa continued to implore</p>\n<p>her husband, praying him not to confine</p>\n<p>their hopes so narrowly—to no avail,</p>\n<p>for he would not be moved from his decision.</p>\n<p>Now scarcely able to endure the weight</p>\n<p>of her womb’s burden, as she lay in bed</p>\n<p>at midnight, a dream-vision came to her:</p>\n<p>the goddess Io stood (or seemed to sand)</p>\n<p>before her troubled bed, accompanied</p>\n<p>with solemn pomp by her mysteries.</p>\n</blockquote>\n\nThe relationship between man and woman is, as is usual, unequal.\n\nInfanticide has apparently been practiced by many, if not most, cultures. In Roman society, the man of the household would inspect the baby. Sometimes it would be killed if thought to be illegitimate or, as in this story, they couldn’t afford a girl. (How far has our ethics progressed—probably due mostly to technological advances!)\n\nAs Ovid usually does, he portrays Ligdus in a good light and gives the reader some understanding of how he came to his decision.\n\nIo informs Telthusa to keep the baby, even if it is a girl. It is, and they keep this fact a secret. She grows up, and is arranged to be married! She falls in love with the girl, a family friend. The story is amazing:\n\n<blockquote class=\"poetry\">\n<p>And scarcely holding back her tears, she cries,</p>\n<p>“Oh, what will be the end reserved for Iphis,</p>\n<p>gripped by a strange and monstrous passion known</p>\n<p>to no one else? If the gods had wished to spare me,</p>\n<p>they should have; if they wanted to destroy me,</p>\n<p>they should have given me a natural affliction.</p>\n<p>Cows do not burn for cows, nor mares for mares;</p>\n<p>the ram will have his sheep, the stag his does,</p>\n<p>and birds will do the same when they assemble;</p>\n<p>there are no animals whose females lust</p>\n<p>for other females! I wish that I were dead!</p>\n<p>That Crete might bring forth monsters of all kinds,</p>\n<p>Queen Pasiphaë was taken by a bull,</p>\n<p>yet even <em>that</em> was male-and-female passion!</p>\n<p>My love is much less rational than hers,</p>\n<p>to tell the truth. At least she had the hope</p>\n<p>of satisfaction, taking in the bull</p>\n<p>through guile, and in the image of a cow,</p>\n<p>thereby deceiving the adulterer!</p>\n<p>If every form of ingenuity</p>\n<p>were gathered here from all around the world,</p>\n<p>if Daedalus flew back on waxen wings,</p>\n<p>what could he do? Could all his learnèd arts</p>\n<p>transform me from a girl into a boy?</p>\n<p>Or could <em>you</em> change into a boy, Ianthe?</p>\n</blockquote>\n\nApparently, while male-male homosexuality was common in ancient Rome, female-female homosexuality was not.\n\nIo turned Iphis into a boy at the last minute.\n\n## Book X\n\nOvid economically relays the death of Orpheus’ wife, and how he descends to the underworld to ask for her back. After playing a song:\n\n<blockquote class=\"poetry\">\n<p>These words, accompanied on the plucked strings,</p>\n<p>so moved the bloodless spirits that they wept;</p>\n<p>Tantalus did not seek the receding water,</p>\n<p>and on his wheel lay Ixion, astounded;</p>\n<p>the birds let go the liver, and the daughters</p>\n<p>of Danaüs were resting by their urns,</p>\n<p>while you, O Sisyphus, sat on your stone.</p>\n</blockquote>\n\nWhen an author relies on their audience being well-read, they can paint with great depth and speed by borrowing the images of others.\n\nHades allows Eurydice a second life, but tragically, Orpheus breaks the one condition and looks back at her before leaving the underworld. Ovid’s description is haunting and beautiful, but he quickly dispels the epic aura around the tale with:\n\n<blockquote class=\"poetry\">\n<p>Three times the Sun had finished out the year</p>\n<p>in Pisces of the waters. Orpheus</p>\n<p>had fled completely from the love of women,</p>\n<p>either because it hadn’t worked for him</p>\n<p>or else because the pledge that he had given</p>\n<p>to his Eurydice was permanent;</p>\n<p>no matter: women burned to have the bard,</p>\n<p>and many suffered greatly from rejection.</p>\n<p>Among the Thracians, he originated</p>\n<p>the practice of transferring the affections</p>\n<p>to youthful males, plucking the first flower</p>\n<p>in the brief spring time of their early manhood.</p>\n</blockquote>\n\nThe antecedent of “it” must be Orpheus’ penis, and Ovid casts doubt on motive for staying away from women, conjecturing that it wasn’t of his own choice, and for this reason he turned to young boys. Ovid’s lack of reverence is distasteful to me, even being so far separated from the cultural stories he denigrates—still, he is fun to read.\n\nOrpheus proceeds to tell a number of stories, about gods loving boys and girls with unnatural lusts.\n\nA quote from the story of Hyacinthus, makes light of a similar simile in the _Iliad_:\n\n<blockquote class=\"poetry\">\n<p>“As when a poppy or violet grown in a garden</p>\n<p>among the lilies (whose tongues are thick yellow and bristly)</p>\n<p>breaks, and the flower’s head shrivels, droops, and collapses,</p>\n<p>unable to hold itself up, with downcast demeanor,</p>\n<p>just so the dying boy’s head, now lacking all vigor,</p>\n<p>unable to bear its own weight, lies flat on his shoulder.”</p>\n</blockquote>\n\nHere is the original:\n\n<blockquote class=\"poetry\">\n<p>As a garden poppy, burst into red bloom, bends,</p>\n<p>drooping its head to one side, weighed down</p>\n<p>by its full seeds and a sudden spring shower,</p>\n<p>so Gorgythion’s head fell limp over one shoulder,</p>\n<p>weighed down by his helmet.</p>\n<cite>— Iliad 8.306-9</cite>\n</blockquote>\n\nIn Homer, a great hero has died; in Ovid, a boy-lover dies in a discus accident. Furthermore, Apollo says he will speak about Hyacinthus in his poetry!\n\n<blockquote class=\"poetry\">\n<p>“‘You will be present both in my songs and mu music,</p>\n<p>and a flower will come into being, inscribed with my mourning;</p>\n<p>later, a legend involving the boldest of heroes</p>\n<p>will be conjoined to this flower and read in its markings.’”</p>\n</blockquote>\n\nOrpheus then tells the story of Pygmallion, and how, after being repulsed by the “numerous defects of character Nature had given the feminine spirit,” he falls in love with his statue. Is Ovid demeaning women, or men when he tells of the ridiculous gifts Pygmallion brought:\n\n<blockquote class=\"poetry\">\n<p>he seeks to win its affections with words and with presents</p>\n<p>pleasing to girls, such as seashells and pebbles, tame birds,</p>\n<p>armloads of flowers in thousands of different colors,</p>\n<p>lilies, bright painted balls, curious insects in amber</p>\n</blockquote>\n\nPerhaps Ovid is using the classic story to make fun of men, for helplessly chasing women, and women for being shallowly bought by gifts.\n\nNext Orpheus tells the story of Myrrha, who fell in love with her father and tricked him into sleeping with her. Ovid has the poet warn readers:\n\n<blockquote class=\"poetry\">\n<p>I sing of dire events: depart from me, daughters,</p>\n<p>depart from me, fathers; or, if you find my poems charming,</p>\n<p>believe that I lie, believe these events never happened;</p>\n<p>or, if you believe they did, then believe they were punished.</p>\n</blockquote>\n\n## Book XI\n\nAfter telling stories for most of Book X, Orpheus is torn to pieces by the Maenads. This scene is one of my favorite:\n\n<blockquote class=\"poetry\">\n<p>Meanwhile, as Orpheus compelled the tress</p>\n<p>and beasts to follow him with suchlike songs,</p>\n<p>and made the very stones skip in his wake,</p>\n<p>behold: a raving mob of Thracian women</p>\n<p>with the pelts of wild beasts draped across their breasts</p>\n<p>observed him from the summit of a hill</p>\n<p>setting the words to music on his lyre.</p>\n<p>One of them tossed her hair in the light breeze:</p>\n<p>“Look over there!” she cried. “The one who scorns us!”</p>\n<p>And with no more ado, she cast her lance</p>\n<p>at the vocalizing mouth of Apollo’s seer;</p>\n<p>it struck without wounding, being wreathed in leaves.</p>\n<p>Another’s weapon was the stone she cast,</p>\n<p>that even in midflight was overwhelmed</p>\n<p>by words and music joined in harmony,</p>\n<p>and, as though begging pardon for its mad daring,</p>\n<p>fell at the poet’s feet.</p>\n</blockquote>\n\nOvid’s commentary on Oracles:\n\n<blockquote class=\"poetry\">\n<p>His brother’s transformation and some weird</p>\n<p>portents that followed it left Ceyx perturbed</p>\n<p>and eager to consult the oracles</p>\n<p>that comfort men in their perplexity,</p>\n<p>but on account of Phorbas and his brigands,</p>\n<p>the road to Delphi was too dangerous,</p>\n<p>so he prepared to undertake a journey</p>\n<p>to Phoebus’ shrine at Clarium instead</p>\n</blockquote>\n\nKnowledge of the source of lightening:\n\n<blockquote class=\"poetry\">\n<p>for once they break loose and reach open seas,</p>\n<p>the winds are wholly uncontrollable,</p>\n<p>and earth and sea alike are unprotected;</p>\n<p>indeed, they even vex the clouds in heaven,</p>\n<p>and shake the lightnings from them by collision!</p>\n</blockquote>\n\nI adore the story of Ceyx and Alcyone—a loving couple separated by death but both turned to birds. The description of Ceyx’s death at sea is some of Ovid’s most vivid. It includes a great simile:\n\n<blockquote class=\"poetry\">\n<p>Sails were rain-sodden, waters from above</p>\n<p>were mixed in thoroughly with those below;</p>\n<p>the stars were all put out, and blackest night</p>\n<p>bore down with its own darkness and the storm’s.</p>\n<p>That darkness, nonetheless, was shattered by</p>\n<p>the flickering thunderbolts that lit the sky</p>\n<p>and made the raindrops glitter as they fell.</p>\n<p>Boldly the flood now sprang onto the ship,</p>\n<p>and like a solider, who, surpassing all</p>\n<p>his many comrades, in the last assault</p>\n<p>upon the walls of a beleaguered city,</p>\n<p>after so many tries, achieves his aim,</p>\n<p>and, fired by the love of praise, leaps over,</p>\n<p>and one man holds the wall against a thousand;</p>\n<p>just so, when nine successive waves have battered</p>\n<p>the hull of that tall ship without success,</p>\n<p>the tenth wave rushes in with greater force,</p>\n<p>and does not end its struggle with the weary</p>\n<p>vessel before it penetrates the wall</p>\n<p>of the captured ship.</p>\n</blockquote>\n\n## Book XII\n\nThe characteristic abodes of Envy, Sleep, and Rumor are described in the _Metamorphoses_. Rumor’s house is fun:\n\n<blockquote class=\"poetry\">\n<p>Crowds fill the entryway, a fickle mob</p>\n<p>that comes and goes; and rumors everywhere,</p>\n<p>thousands of fabrications mixed with fact,</p>\n<p>wander the premises, while false reports</p>\n<p>flit all about. Some fill their idle ears</p>\n<p>with others’ words, and some go bearing tales</p>\n<p>elsewhere, while everywhere the fictions grow,</p>\n<p>as everyone adds on to what he’s heard.</p>\n</blockquote>\n\nOvid enjoys making fun of Homer’s heroes. He begins withe Achilles’\n\n<blockquote class=\"poetry\">\n<p>The officers all took their ease, reclining</p>\n<p>on couches where they stuffed themselves with meat</p>\n<p>and drove away their cares and thirst with wine.</p>\n<p>No lyres for this lot, no poetry,</p>\n<p>no flutes of boxwood, pierced with many holes:</p>\n<p>what pleases them is to extend the night</p>\n<p>by telling stories of heroic deeds;</p>\n<p>they reenact old wars, their own and others,</p>\n<p>and are delighted to remember all</p>\n<p>the dangers they’ve endured and gotten through:</p>\n<p>what else has great Achilles to discuss?</p>\n<p>What else is there to speak of in his presence?</p>\n</blockquote>\n\nNext in line is Nestor, who even Homer seemed to poke fun at a bit:\n\n<blockquote class=\"poetry\">\n<p>Nestor replied: “Though my extreme old age</p>\n<p>is something of an obstacle to me,</p>\n<p>and much of what I witnessed in my youth</p>\n<p>I have forgotten, still I remember much,</p>\n<p>and nothing stands out more in memory,</p>\n<p>among so many acts of war and peace,</p>\n<p>than this does. But if great expanse of years</p>\n<p>makes one a living witness of so much</p>\n<p>that happened, I have lived two centuries</p>\n<p>already, and am living in my third!”</p>\n</blockquote>\n\nAnd then there is the ridiculous death descriptions:\n\n<blockquote class=\"poetry\">\n<p>“They eyes leapt forth</p>\n<p>from the disfigured pudding of his face,</p>\n<p>and his nose was driven back into his palate.”</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“He plunged the horns into Gryneus’ eyes</p>\n<p>and gouged them out; one to an antler clung,</p>\n<p>the other dribbled down his beard and hung</p>\n<p>suspended in a mass of clotting gore.”</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“and Dictys, as he fled Pirithoüs</p>\n<p>in fearful haste, toppled over the edge</p>\n<p>of a mountain with two peaks, plunging headlong</p>\n<p>until a giant ash tree broke his fall,</p>\n<p>and left its fractured branches decorated</p>\n<p>with loops of his intestines.</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“and used his sword to open up his belly;</p>\n<p>that fierce, unbridled beast bounded forward</p>\n<p>and spilled his entrails out upon the ground,</p>\n<p>and what spilled out of him, he trod upon,</p>\n<p>and what was trodden on was burst asunder</p>\n<p>and tangled in his legs until he fell,</p>\n<p>his belly emptied of its viscera.”</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“shattered the broad dome of his skull, and pressed</p>\n<p>his fluid brains till they exuded through</p>\n<p>his mouth, his sinuses, his eyes and ears,</p>\n<p>as when the whey pours through the oaken basket</p>\n<p>leaving the curds behind, or as when grapes</p>\n<p>beneath the press drip through the slender sieve,</p>\n<p>and juice is squeezed out through the narrow openings.”</p>\n</blockquote>\n\nOvid includes the sequences of deaths, like Homer:\n\n<blockquote class=\"poetry\">\n<p>“And with that club, he flattened Nedymnus</p>\n<p>and Lycopes, skilled with the javelin,</p>\n<p>and Hippasos, whose breast was covered by</p>\n<p>his uncut beard, and Ripheus, who loomed</p>\n<p>above the tallest tress, and Thereus,</p>\n<p>who caught bears on the peaks of Thessaly</p>\n<p>and fetched them back still living and indignant.”</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“Caeneus had already slaughtered five:</p>\n<p>Styphelus first, then Bromus, Antimachus,</p>\n<p>Elymus, and axe-wielding Pyracmos;</p>\n<p>I don’t recall the manner of their deaths,</p>\n<p>for I took note just of the names and numbers.”</p>\n</blockquote>\n\nHe pokes fun at the Greek’s armor obsession:\n\n<blockquote class=\"poetry\">\n<p>Achilles very shield—that you should be aware</p>\n<p>whose it once was—now instigates a battle,</p>\n<p>and for his arms, arms are now taken up.</p>\n</blockquote>\n\nHe even makes fun of the role the gods played in Homer, perhaps questioning their existence:\n\n<blockquote class=\"poetry\">\n<p>“and when he saw the [thrown tree] coming, Theseus</p>\n<p>moved out of range, upon advice of Pallas—</p>\n<p>or so he would prefer us to believe.”</p>\n</blockquote>\n\nMany stories’ central metamorphosis is physical, in the story of Achilles death, the change is of a living man into a legacy:\n\n<blockquote class=\"poetry\">\n<p>now he is ashes: and the little left</p>\n<p>of great Achilles scarcely fills an urn,</p>\n<p>although his living glory fills the world.</p>\n<p>That glory is the measure of the man,</p>\n<p>and it is this that is Achilles’ essence,</p>\n<p>nor does he feel the emptiness of death.</p>\n</blockquote>\n\n## Book XIII\n\nAjax and Ulysses proclaim to the Greek assembly why they should receive Achilles’ shield.\n\nAjax’ has a few funny arguments:\n\n<blockquote class=\"poetry\">\n<p>“I realize I seek a great reward,</p>\n<p>but having such a rival is demeaning</p>\n<p>and cheats me of the honor I am due:</p>\n<p>Ajax cannot be proud to win a prize,</p>\n<p>no matter how substantial, that Ulysses</p>\n<p>can have the expectation of receiving;</p>\n<p>he has already gotten his reward,</p>\n<p>for when his claim has been rejected, he</p>\n<p>can boast that he and I were fairly matched!”</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“In truth, if I may say so, it’s the prize</p>\n<p>that seeks association with <em>my</em> glory,</p>\n<p>and would be honored much more than would I—</p>\n<p>for it’s the armor would be given Ajax,</p>\n<p>not Ajax the armor.”</p>\n</blockquote>\n\nUlysses wins; his central argument is that his intellect is more important than fighting prowess. He also pulls the jury to his side by emotionally aligning them against Ajax:\n\n<blockquote class=\"poetry\">\n<p>“Nor should it shock us that his [Ajax’] stupid mouth</p>\n<p>should so abuse me, for you also are</p>\n<p>the targets of his indecent reproaches.</p>\n<p>Can it be baseness for me to accuse</p>\n<p>Palamedes unjustly, but correct</p>\n<p>for you to find him guilty of the charges?”</p>\n</blockquote>\n\nThe story of the Cyclops, Polyphemus from the _Odyssey_, wooing Galatea is hilarious. Ovid, as he always does, masterfully ridicules without indulging too much. Thus, Polyphemus’ advances are funny yet not crude. Here are a few of my favorite lines:\n\n<blockquote class=\"poetry\">\n<p>“‘O Galatea, whiter than the snowy white</p>\n<p>flowers that decorate the privet hedge,</p>\n<p>richer in blossoms than the meadow is,</p>\n<p>taller, more slender than an alder tree,</p>\n<p>brighter than crystal, more skittish than a kid,</p>\n<p>smoother than a seashell on the shore</p>\n<p>worn by the ceaseless motion of the waves,</p>\n<p>more pleasing than the shade in summertime</p>\n<p>or sun in winter, swifter than the deer,</p>\n<p>and even more remarkable to see,</p>\n<p>far more conspicuous than the tall plane tree;</p>\n<p>clearer than ice, sweeter than ripe grapes,</p>\n<p>software than swans’ down or the curdled milk,</p>\n<p>and, of you would not always flee from me,</p>\n<p>more beautiful than an irrigated garden.</p>\n<p>Yet you, the very selfsame Galatea,</p>\n<p>are fiercer than an untamed heifer is,</p>\n<p>harder than oak, more feigning than the sea,</p>\n<p>tougher than willow wands or bryony,</p>\n<p>less movable than the rock I’m sitting on,</p>\n<p>rougher than rapids, prouder than a peacock,</p>\n<p>fiercer than fire, bitterer than thistles,</p>\n<p>grumpier than a nursing mother-bear,</p>\n<p>more unresponsive even than the ocean,</p>\n<p>less apt to pity than a stepped-on snake’”</p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“‘Just look how big I am! Not even Jove—</p>\n<p>this Jupiter that you go on about,</p>\n<p>who you say governs heaven—is as big!</p>\n<p>Abundant hair hangs over my fierce face</p>\n<p>and shoulders, shading me, just like a grove;</p>\n<p>but don’t think me unsightly just because</p>\n<p>I am completely covered in dense bristles:</p>\n<p>unsightly is the tree that has no leaves,</p>\n<p>the horse without a mane; birds have their plumage</p>\n<p>and sheep are most attractive in their wool,</p>\n<p>so facial hair and a full body beard</p>\n<p>are really most becoming in a man.</p>\n<p>In the middle of my forehead is one eye,</p>\n<p>as large in its appearance as a shield:</p>\n<p>what of it, then? Does not the mighty Sun</p>\n<p>see everything that happens here on earth?</p>\n<p>And as for eyes, he too has only one!”</p>\n</blockquote>\n\nThe Metropolitan Museum of Art has an original Roman painting, one of the rare survivors, from around the time of Ovid (if I recall). The painting depicts a few scenes of the Polymphemus and Galatea story.\n\nThe story about Glaucas eating magical grass which turns him into a fish is a bizarre (beside the teeth turning into men, in the Jason and Cadmus stories, who then fight one another, this may be the oddest story in the _Metamorphoses_, although I am not sure I could point out why. Perhaps many of the other stories in Ovid would sound odd too, if our culture had not appropriated them. When I read Chinese (or even some Egyptian) stories, they all sound as odd as this one. But the opposite is likely true too.\n\nHere is the especially odd part:\n\n<blockquote class=\"poetry\">\n<p>“Now comes what sounds like fiction, I admit,</p>\n<p>but what advantage would I gain by feigning?</p>\n<p>Lying on the grass, my plunder from the surf</p>\n<p>began to stir, and flipped from side to side,</p>\n<p>as all at once, they strove to leave the earth</p>\n<p>and get back to the water. While I watched,</p>\n<p>dumbfounded and incapable of moving,</p>\n<p>they fled, the lot of them, abandoning</p>\n<p>the shore and their new master for the sea.</p>\n<p>I stood stock-still in wonder a long time,</p>\n<p>asking myself how such a thing could be;</p>\n<p>was it some god—or something in the grass?</p>\n<p>‘How could mere grass,’ I asked, ‘be strong as that?’</p>\n<p>I plucked some and ground it in my teeth,</p>\n<p>and scarcely had I gulped that unknown liquid,</p>\n<p>when suddenly my heart began to pound,</p>\n<p>and my whole sensibility was taken</p>\n<p>with the desire for another element,</p>\n<p>which I could not resist for long: ‘Farewell,</p>\n<p>O earth, which I will nevermore return to,’</p>\n<p>I said, and plunged beneath the ocean’s waves.”</p>\n</blockquote>\n\n## Book XIV\n\nGlaucus, in love with Scylla, asks Circe to help. Instead, she falls in love with him:\n\n<blockquote class=\"poetry\">\n<p>“I pray you will have me! Only spurn</p>\n<p>the one who spurns your passion, and return</p>\n<p>the love of one who loves you: let one deed serve</p>\n<p>two women as they each of them deserve.”</p>\n<p>Glaucus responded to her proposition:</p>\n<p>“The leaves of trees will spring out of the ocean,</p>\n<p>and seaweed will be found on mountain ranges,</p>\n<p>before my love for Scylla ever changes.”</p>\n</blockquote>\n\nAnd so, Circe transforms Syclla into a monster:\n\n<blockquote class=\"poetry\">\n<p>“her private parts deformed into the shapes</p>\n<p>of barking dogs …</p>\n<p>Her lover Glaucus wept at this and fled</p>\n<p>from having any more to do with Circe,</p>\n<p>whose use of potent herbs was too aggressive.”</p>\n</blockquote>\n\nDiomedes recounting the woes of the returning Greeks:\n\n<blockquote class=\"poetry\">\n<p>“I will not long delay you, setting out</p>\n<p>our woes in the order they occurred:</p>\n<p>just say that even Priam would have wept</p>\n<p>to see how Greece was fairing at that time!”</p>\n</blockquote>\n\nAnaxarete, after spurning Iphis’ advances, sees his body and is turned to stone:\n\n<blockquote class=\"poetry\">\n<p>“scarcely had she glimpsed</p>\n<p>the corpse of Iphis laid out on his bier,</p>\n<p>when her eyes hardened and he cold blood ran</p>\n<p>in terror from her body: she attempted</p>\n<p>to step back from the sight, but her feet froze;</p>\n<p>when she attempted to avert her face,</p>\n<p>she was unable to; and very soon</p>\n<p>the stoniness that for so long a time</p>\n<p>had been within her heart spread through her body.”</p>\n</blockquote>\n\n## Book XV\n\nPythagoras’ pagan skepticism:\n\n<blockquote class=\"poetry\">\n<p>lightning is produced by Jove</p>\n<p>or by the winds that tear apart the clouds;</p>\n<p>what causes earthquakes and what keeps the stars</p>\n<p>from flying off, and other hidden things</p>\n</blockquote>\n\nPythagoras on being vegetarian:\n\n<blockquote class=\"poetry\">\n<p>“Mortals, refrain from defiling your bodies with sinful</p>\n<p>feasting, for you have the fruits of the earth and of arbors,</p>\n<p>whose branches bow with their burden; for you the grapes ripen,</p>\n<p>for you the delicious greens are made tender by cooking;</p>\n<p>milk is permitted you too, and thyme-scented honey:</p>\n<p>Earth is abundantly wealthy and freely provides you</p>\n<p>her gentle sustenance, offered without any bloodshed.</p>\n<p>Some of the beasts <em>do</em> eat flesh to allay their own hunger,</p>\n<p>although not all of them, for horses, sheep, and cattle</p>\n<p>feed upon grasses; but those of untameable nature—</p>\n<p>Armenian tigers, furious lions, wolves and bears, too—</p>\n<p>these creatures take pleasure in feasting on what they have slaughtered.</p>\n<p>What an indecency, mingling entrails with entrails,</p>\n<p>fattening one on the flesh from another one’s body,</p>\n<p>saving the life of one by another’s destruction!”</p>\n</blockquote>\n\nPythagoras on the afterlife and fear thereof:\n\n<blockquote class=\"poetry\">\n<p>“O people stunned with the icy terror of dying,</p>\n<p>why do you fear the Styx? Why are you frightened of phantoms</p>\n<p>and names that mean nothing, the empty blather of poets,</p>\n<p>foolish hobgoblins of a world that never existed?</p>\n<p>Here is what happens after you die: your body,</p>\n<p>whether consumed on the pyre of slowly decaying,</p>\n<p>suffers no evil; souls cannot perish, and always,</p>\n<p>on leaving their prior abodes, they come to new ones,</p>\n<p>living on, dwelling again in receptive bodies”</p>\n</blockquote>\n\nPythagoras on unending change:\n\n<blockquote class=\"poetry\">\n<p>“And since I am already embarked upon this great sea,</p>\n<p>have given full sails to the wind, hear me out: nothing</p>\n<p>endures in this world! The whole of it flows, and all is</p>\n<p>formed with a changing appearance; even time passes,</p>\n<p>constant in motion no different from a great river,</p>\n<p>for neither a river nor a transitory hour</p>\n<p>is able to stand still; but just as each wave is driven</p>\n<p>ahead by another, urged on from behind, and urging</p>\n<p>the next wave before it in an unbroken sequence,</p>\n<p>so the times flee and at the same time they follow,</p>\n<p>and always are new; for what has just been is no longer,</p>\n<p>and what has not been will presently come into being,</p>\n<p>and every moment’s occasion is a renewal.”</p>\n</blockquote>\n\nPythagoras on geology, and the changing planet:\n\n<blockquote class=\"poetry\">\n<p>“I truly believe that nothing may keep the same image</p>\n<p>for a long time; the age of gold yields to iron,</p>\n<p>and often places will know a reversal of fortune.</p>\n<p>For with my own eyes, I have seen land that once was quite solid</p>\n<p>change into water, and I have seen land made from ocean;</p>\n<p>seashells have been discovered far from the seashore,</p>\n<p>and rusty anchors right on the summits of mountains;</p>\n<p>a former plain was converted into a valley</p>\n<p>by rushing waters, whose force has leveled great mountains;</p>\n<p>and a onetime marshland has been turned into a desert,</p>\n<p>while thirsty sands have been transformed into marshland.”</p>\n</blockquote>\n\nPythagoras on biological change:\n\n<blockquote class=\"poetry\">\n<p>“Mud contains seeds which generate frogs, at first legless,</p>\n<p>though soon they develop limbs that equip them for swimming,</p>\n<p>and so that these same limbs can be used for long-distance leaping,</p>\n<p>their hind legs are always much greater in length than their forelegs.</p>\n<p>Nor is the bear cub, when newly brought forth by the she-bear,</p>\n<p>other than bear-pulp: by her own purposeful licking,</p>\n<p>the mother bear shapes it and forms it in her own image.</p>\n<p>Do you not see how the larva of bees, makers of honey,</p>\n<p>so well protected within their hexagonal chambers</p>\n<p>of wax, are born without any limbs on their bodies,</p>\n<p>and only later develop legs and the wings used for flying?”</p>\n</blockquote>\n\nPythagoras on the shifts of power:\n\n<blockquote class=\"poetry\">\n<p>“as one nation gains in strength while another collapses:</p>\n<p>once Troy was great, rich in its wealth and its heroes,</p>\n<p>and able to go on bleeding both for ten years;</p>\n<p>now brought to earth, she has nothing to show but her ruins,</p>\n<p>no wealth besides that which lies in her burial chambers.</p>\n<p>Sparta was famous, mighty Mycenae once flourished,</p>\n<p>even as Athens, even as Thebes of the Towers;</p>\n<p>Sparta is worthless now, lofty Mycenae has toppled,</p>\n<p>what but the name remains of the Thebes of Oedipus?</p>\n<p>What but the name remains of Pandion’s Athens?”</p>\n</blockquote>\n\nOvid pandering to Augustus:\n\n<blockquote class=\"poetry\">\n<p>That one approached our altars as a stranger,</p>\n<p>but Caesar is a god in his own city,</p>\n<p>raised up to heaven, changed into a star</p>\n<p>blazing so brilliantly, not by his own</p>\n<p>remarkable success in war and peace,</p>\n<p>not by the battles that were crowned in triumph,</p>\n<p>nor by his service to the commonwealth,</p>\n<p>nor yet by glory that hastened to his side;</p>\n<p>but rather by his offspring, for no deed</p>\n<p>has Caesar done that stands out more than this:</p>\n<p>he is thew father of our own Augustus!</p>\n</blockquote>\n\nOvid predicts his enduring fame:\n\n<blockquote class=\"poetry\">\n<p>My work is finished now: no wrath of Jove</p>\n<p>nor sword nor fire nor futurity</p>\n<p>is capable of laying waste to it.</p>\n<p>Let that day come then, when it wishes to,</p>\n<p>which only has my body in its power,</p>\n<p>and put an end to my uncertain years;</p>\n<p>no matter, for in spirit I will be</p>\n<p>borne up to soar beyond the distant stars,</p>\n<p>immortal in the name I leave behind;</p>\n<p>wherever Roman governance extends</p>\n<p>over the subject nations of the world,</p>\n<p>my words will be upon the people’s lips,</p>\n<p>and if there is truth in poets’ prophesies,</p>\n<p>then in my fame forever I will live.</p>\n</blockquote>\n\n## Metaphysics\n\nThe _Metamorphoses_ were meant to be entertaining, thus it is dangerous to make any theological conclusions from them. Still, some metaphysical comments may represent widely held beliefs from Ovid’s time. For example, the role of fate, present in Homer, is laid out:\n\n<blockquote class=\"poetry\">\n<p>Each of the gods there had a favorite,</p>\n<p>and argued from a partisan position</p>\n<p>against the others, until Jove spoke up:</p>\n<p>“O gods! If you have any reverence</p>\n<p>for us at all, why leap to such confusions?</p>\n<p>Does anyone here imagine himself able</p>\n<p>to overcome the limits set by Fate?</p>\n<p>Iolaüs was given back the years</p>\n<p>he was in need of by the will of Fate;</p>\n<p>not by ambition, not by skill in combat</p>\n<p>will Callirhoë’s sons turn into men</p>\n<p>from infancy, but by the will of Fate,</p>\n<p>which governs even us; I tell you this</p>\n<p>that you might put a better face on it—</p>\n<p>yes, <em>you</em> are ruled by Fate, and <em>I</em> am too.” <cite>(9.619–35)</cite></p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>Her [Venus’] father said, “My dear, are you preparing</p>\n<p>to alter his [Ceasars’] inevitable fate</p>\n<p>all by yourself? It is permitted you</p>\n<p>to enter the Hall of Records kept by the Fates;</p>\n<p>there you will find the labor of the ages,</p>\n<p>the universal script, in bronze and iron,</p>\n<p>which does not fear that clashes in the sky</p>\n<p>or lightning’s rage will bring it down to ruin,</p>\n<p>for it will be eternally secure.</p>\n<p>Here you will find, inscribed on adamant</p>\n<p>that will not perish ever, your son’s fate:</p>\n<p>and I myself have read and noted it,</p>\n<p>and I will now expound on it to you,</p>\n<p>so you may understand what is to come.” <cite>(15.1004–17)</cite></p>\n</blockquote>\n\nMortals had “deficits” that needed to be purged before becoming immortal:\n\n<blockquote class=\"poetry\">\n<p>“The sea god welcomed me, pronounced me fit</p>\n<p>to join their honorable company,</p>\n<p>and asked the Ocean and his consort, Tethys,</p>\n<p>to take away whatever still remained</p>\n<p>of my mortality; and this they did</p>\n<p>first, by the recital of a hymn, nine times,</p>\n<p>to purge me of my evil; then they bade</p>\n<p>me to immerse myself a hundred times</p>\n<p>in just as many rivers” <cite>(13.1378–86)</cite></p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>She [Venus] bade the river god to take Aeneas</p>\n<p>under the surface of his silent stream</p>\n<p>and cleanse him of all mortal deficits;</p>\n<p>he did as she commanded, bathing him,</p>\n<p>and having purged him of this mortal dross,</p>\n<p>restored his best, immortal part to him.</p>\n<p>His mother purified Aeneas’ body,</p>\n<p>anointing it with heavenly perfumes,</p>\n<p>and touched his lips with sweet ambrosia</p>\n<p>and nectar both, so he became a god, <cite>(14.861–72)</cite></p>\n</blockquote>\n\nThe gods are limited in a number of ways. Interestingly, Ovid mentions that gods can’t undue actions of other gods:\n\n<blockquote class=\"poetry\">\n<p>Venus alone knew that the bolt had fallen</p>\n<p>and would have put it back and locked the gates,</p>\n<p>but one god is unable to rescind</p>\n<p>the actions of another.</p>\n</blockquote>\n\nThis sort of question is unique to polytheism.\n\n## Epistemology\n\nOvid does not appear to take the myths he is telling seriously. Throughout the poem, he inserts comic asides. Here I present a few illustrative examples.\n\nOvid avoids stating which god created the universe:\n\n<blockquote class=\"poetry\">\n<p>Some god (or kinder nature) settled this</p>\n<p>dispute by separating earth from heaven</p>\n<p>⋯</p>\n<p>Now when that god (whichever one it was)</p>\n<p>had given Chaos form <cite>(1.26–41)</cite></p>\n</blockquote>\n\nHe slyly implies that we do not know the source of some stories firsthand:\n\n<blockquote class=\"poetry\">\n<p>So that the skies above might be no more</p>\n<p>secure than earth, the race of Giants plotted</p>\n<p>(we hear) to rule in heaven by themselves <cite>(1.205–8)</cite></p>\n</blockquote>\n\nHere he ironically says we have a story on good faith:\n\n<blockquote class=\"poetry\">\n<p>(you needn’t take this part of it on faith,</p>\n<p>for it’s supported by an old tradition)—</p>\n<p>these stones at once begin to lose their hardness</p>\n<p>and their rigidity; slowly they soften;</p>\n<p>once softened, they begin to take on shapes. <cite>(1.556–60)</cite></p>\n</blockquote>\n\nIn other places, he speculates about the gods motives:\n\n<blockquote class=\"poetry\">\n<p>He spoke and threw his arms around her neck,</p>\n<p>imploring her upon his very life,</p>\n<p>and on that of his stepfather, Merops,</p>\n<p>and by the wedding torches of his sisters,</p>\n<p>to give him proof of who his father was.</p>\n<p>Clymene, moved by Phaêthon’s petition</p>\n<p>(or by the insult to her own good name), <cite>(1.1055–64)</cite></p>\n</blockquote>\n\nHe openly questions the plausibility of the stories and the gods:\n\n<blockquote class=\"poetry\">\n<p>Her [Semele’s] child was torn out of her womb unfinished</p>\n<p>and—this part is scarcely credible—was sewn</p>\n<p>into his father’s thigh, where he was brought to term. <cite>(3.400-2)</cite></p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>She has a virgin’s face, and, if our poets</p>\n<p>are not to be completely disbelieved <cite>(13.1063–4)</cite></p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>“but war continued,</p>\n<p>since both sides each had gods supporting them,</p>\n<p>and courage, which is just as good as gods” <cite>(14.811–3)</cite></p>\n</blockquote>\n\n## Structure\n\nThe _Metamorphoses_’ Stories flow together roughly following time, but not completely. For example, Atlas is said to be carrying the world on his shoulders in book II but does not receive his burden until book IV, and Hercules’ apotheosis occurs in book IX but he is present during the sack of Troy in book XI.\n\nStories are often grouped together by family (the Cadmus stories in books III and IV) or by region (the Anatolian stories in book VI).\n\nNested stories at two or three levels are common (on occasion, as with the Arethusa and Alpheus in book V, four levels are present).\n\nThe connections between stories are often weak, for example:\n\n<blockquote class=\"poetry\">\n<p>Rumor might very well have spread the news</p>\n<p>of this unprecedented transformation [of Byblis into a spring]</p>\n<p>throughout the hundred towns of Crete, if they</p>\n<p>had not just had a wonder of their own</p>\n<p>to talk about—the change that came to Iphis. <cite>(9.960–4)</cite></p>\n</blockquote>\n\n## Similes\n\nApollo’s sudden love for Daphne:\n\n<blockquote class=\"poetry\">\n<p>Now just as in a field the harvest stubble</p>\n<p>is all burned off, or as hedges are set ablaze</p>\n<p>when, if by chance, some careless traveler</p>\n<p>should brush one with his torch or toss away</p>\n<p>the still-smoldering brand at break of day—</p>\n<p>just so the smitten god went up in flames</p>\n<p>until his heart was utterly afire,</p>\n<p>and hope sustained his unrequited passion. <cite>(1.678–85)</cite></p>\n</blockquote>\n\nApollo chasing Daphne, after being unable to woo her:\n\n<blockquote class=\"poetry\">\n<p>But the young god had no further interest</p>\n<p>in wasting his fine words on her; admonished</p>\n<p>by his own passion, he accelerates,</p>\n<p>and runs as swiftly as a Gallic hound</p>\n<p>chasing a rabbit through an open field;</p>\n<p>the one seeks shelter and the other, prey—</p>\n<p>he clings to her, is just about to spring,</p>\n<p>with his long muzzle straining at her heels,</p>\n<p>while she, not knowing whether she’s been caught,</p>\n<p>in one swift burst, eludes those snapping jaws,</p>\n<p>no longer the anticipated feast;</p>\n<p>so he in hope and she in terror race. <cite>(1.732–44)</cite></p>\n</blockquote>\n\n## Rape\n\nAeacus’s casual comment about his wife being worthy:\n\n<blockquote class=\"poetry\">\n<p>“Her name was Procris: it’s likelier you’ve heard</p>\n<p>about her ravished sister, Orithyia,</p>\n<p>but were you to compare the two of them</p>\n<p>in looks and manner, Procris was more worthy</p>\n<p>of being ravished!” <cite>(6.990–5)</cite></p>\n</blockquote>\n\nSometimes the raped women seem to be proud that they attracted the gods and have semi-divine offspring, but, if their flights are not evidence enough of their unwillingness, then Ovid makes it clear other times:\n\n<blockquote class=\"poetry\">\n<p>“And after Neptune had taken his delight</p>\n<p>by ravishing the maiden, he announced,</p>\n<p>‘Whatever you desire will be granted!</p>\n<p>Fear no refusal; ask and it is given.’</p>\n<p>Caenis replied: ‘The injury you’ve done me</p>\n<p>requires a great wish to be set right,</p>\n<p>that I might never suffer this again,</p>\n<p>allow that I may be no more a woman,</p>\n<p>and you will have fulfilled me utterly.’” <cite>(12.292–301)</cite></p>\n</blockquote>\n\n## Other Interesting Quotes\n\nOvid’s description of the heavens is humorous, as the gods themselves have household gods:\n\n<blockquote class=\"poetry\">\n<p>When the nighttime sky is clear, there can be seen</p>\n<p>a highway visible in heaven, named</p>\n<p>the Milky Way, distinguished for its whiteness.</p>\n<p>Gods take this path to the royal apartments</p>\n<p>of Jove the Thunderer; on either side</p>\n<p>are palaces with folding doors flung wide,</p>\n<p>and filled with guests of their distinguished owners;</p>\n<p>plebeian gods reside in other sections,</p>\n<p>but here in this exclusive neighborhood,</p>\n<p>the most renowned of heaven’s occupants</p>\n<p>have <em>their</em> own household deities enshrined;</p>\n<p>and if I were permitted to speak freely,</p>\n<p>I would not hesitate to call this enclave</p>\n<p>the Palatine of heaven’s ruling class. <cite>(1.229–42)</cite></p>\n</blockquote>\n\nTowards the end of Book I, Clymenes tells her son that:\n\n<blockquote class=\"poetry\">\n<p>“It will not be a great task to discover</p>\n<p>the place where your father [Apollo] keeps his household gods.” <cite>(1.1074–5)</cite></p>\n</blockquote>\n\nProcne carries of her son Itys, to murder him and feed him to her evil husband:\n\n<blockquote class=\"poetry\">\n<p>Now resolute, she carries Itys off,</p>\n<p>just as a tiger on the Ganges’ banks</p>\n<p>will drag a nursing fawn through the dense woods <cite>(6.922-4)</cite></p>\n</blockquote>\n\nAll quotations are taken from Charles Martin’s 2004 translation. Line numbers refer to the translation and not the original Latin.*\n" }, { "alpha_fraction": 0.7075318098068237, "alphanum_fraction": 0.7309311628341675, "avg_line_length": 68.19867706298828, "blob_id": "e76f65d593be2cece7b7db90c13b2e290a9b8b34", "content_id": "0216d85c0bff8e9661bb398903fa486c1d5ed9df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21199, "license_type": "no_license", "max_line_length": 1057, "num_lines": 302, "path": "/_documents/the-historical-books.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: Joshua, Judges, Samuel, and Kings\ndescription: >\n Notes on the historical books of the Hebrew Bible\ntype: note\n---\n\n<style>\nmain > ol{list-style-type:upper-roman}\nul:first-child{padding-left:1.4rem}\nmain > ul:first-child li{font-weight:normal}\nmain > ul:first-child > li{font-weight:bold}\n.js main > ul:first-child li{cursor:pointer}\n.js main > ul:first-child li li li{cursor:default}\n.js .hidden-children > ul:first-child{display:none}\n.hidden-no-js{display:none}\n.js .hidden-no-js{display:block}\n</style>\n\n## Outline\n\n<p class=\"hidden-no-js hidden-print\">\n <span class=\"hidden-sm\">Set outline depth: &nbsp;</span>\n <a href=\"#\" onclick=\"setDepth(2,event)\">Major Sections</a> ·\n <a href=\"#\" onclick=\"setDepth(3,event)\">Chapters</a>\n</p>\n\n- Joshua\n - Entrance into the land (1–5)\n - Joshua’s commissioning; preparations; transjordan obligations (1)\n - Spies sent to Jericho; saved by Rahab (2)\n - Crossing the Jordan; the twelve stones (3–4)\n - Circumcision; passover; cessation of manna; angel commander (5)\n - Conquest of the land (6–12)\n - Destruction of Jericho (6)\n - The sin of Achan (7)\n - Destruction of Ai; Mount Ebal offering and reading (8)\n - Gibeonites fool Joshua into forming a pact (9)\n - Destruction of the southern coalition (10)\n - Destruction of the northern coalition (11)\n - List of conquered kings (12)\n - Division of the land (13–19)\n - Unconquered lands (13.1–6)\n - Transjordaian divisions (13.7–14.5)\n - Caleb’s plea; the inheritance of Judah (14.6–15.63)\n - Inheritance of the Josephites (16–17)\n - Inheritance of the seven smaller tribes (18–19)\n - Cities of refuge (20)\n - Levite cities (21)\n - Settling into the land (22–28)\n - Transjordanian tribes go home; altar of witness (22)\n - Joshua’s farewell speech (23)\n - Covenant at Shechem (24.1–28)\n - Death of Joshua and Eleazar; Joseph’s reburial (24.1–28)\n- Judges\n - Introduction (1.1–3.6)\n - Conquests of Judah (1.1–20)\n - Conquests of the northern tribes (1.21–36)\n - Characterization of the age of judges (2.1–3.6)\n - Acts of the judges (3.7–16)\n - Othniel defeats Cushan Rishathaim of Aram Naharaim (3.7–11)\n - Left-handed Ehud defeats fat Eglon king of Moab (3.12–3.31)\n - Deborah defeats king Jabin of Hazor (4)\n - The song of Deborah (5)\n - Gideon defeats the Midianites with 300 men (6–8)\n - The rule of Abimelech (9)\n - First list of judges (10.1–5)\n - Jephthah defeats Ammonites; daughter sacrifice; Ephraimites slaughtered (10.6–12.7)\n - Second list of judges (12.8–14)\n - Samson’s birth (13)\n - Samson’s women (14–15)\n - Samson’s death (16)\n - Chaos (17–21)\n - Micah’s house (17)\n - The conquest of Dan (18)\n - Men of Gibeah rape the Levite’s concubine (19)\n - War against Benjamin (20)\n - Wives for Benjamin survivors (21)\n- Samuel I\n - Eli (1–4)\n - Hannah’s prayer; Samuel’s birth; Samuel given (1)\n - Hannah’s song (2.1–10)\n - The rise of Samuel and decline of Eli and his sons (2.11–4)\n - Samuel (5–12)\n - The ark in Philistia (5)\n - The ark returned with gold (6)\n - Samuel leads a spiritual revival (7)\n - Israel asks Samuel to anoint a king (8)\n - Saul is lead to Samuel (9)\n - Saul is anointed king (10)\n - Saul summons the Israelites to save Jabesh Giliead (11)\n - Samuel’s farewell speech (12)\n - Saul (13–31)\n - The philistines invade and camp at Michmash (13)\n - Jonathan leads an attack and eats forbidden honey (14)\n - Saul fights the Amelikites but keeps some booty (15)\n - David is appointed and becomes Saul’s lyre player (16)\n - David and Goliath (17)\n - David’s ascent; Saul’s jealousy and sly marriage promises (18)\n - David escapes Saul (19)\n - Jonathan signals David to leave with arrows (20)\n - Ahimelech helps David (21)\n - David leads a band; Saul massacres Ahimelech and priests (22)\n - David’s band saves Keliah; narrow escape at Horesh (23)\n - David spares Saul in a cave (24)\n - David nearly kills Nabal; his death; marriage to Abigail (25)\n - David spares Saul in a camp (26)\n - David allies with Ahish the Philistine; settles Ziklag (27)\n - Philistines march; Saul has Samuel summoned at En-dor (28)\n - David sent back from the Philistines (29)\n - David reclaims women stolen by Amalekites (30)\n - Death of Saul; Philistines celebrate; Jabesh retrieves body (31)\n- Samuel II\n - David’s rise to power (1–10)\n - Saul’s death and crown brought to David by Amalekite (1.1–16)\n - David’s dirge for Saul and Jonathan (1.17–27)\n - David becomes king of Judah (2.1–12)\n - Civil war with house of Saul; Abner kills Asahel (2.13–32)\n - David’s sons; Abner and Ish-Bosheth argue; Abner murdered (3)\n - Ish-Bosheth murdered (4)\n - David establishes himself at Jerusalem; Philistine defeats (5)\n - David retrieves the ark; Michal’s anger (6)\n - God’s promise to David; David’s thanks (7)\n - David expands his empire (8)\n - David brings Jonathan’s son Mephibosheth to Jerusalem (9)\n - Ammonites embarrass messengers; fight Joab; lose to David (10)\n - David’s sins (11–20)\n - David commits adultery with Bathsheba and has Uriah killed (11)\n - Nathan confronts David; Bathsheba’s firstborn dies; Solomon lives (12)\n - Amnon rapes his half-sister, Tamar; Absolom kills Amnon and flees (13)\n - Joab reunites David and Absolom (14)\n - Absolom revolts; David flees (15)\n - David in wilderness; Absolom rapes his concubines (16)\n - Ahitophel’s advice spurned for Hushais’s; suicide (17)\n - Joab defeat’s Absolom’s army and kills him (18)\n - David mourns; Joab rebukes; Shimei, Mephibosheth, Barzillai (19)\n - Sheba continues revolts; Joab kills Amasa; Joab shutters the revolt (20)\n - Appendices (21–24)\n - Famine and sacrifice of Saul’s offspring; Philistines fights (21)\n - David’s victory Psalm (22)\n - David’s last words; lizt of David’s warriors (23)\n - David calls a census; plauge; David builds an altar (24)\n- Kings I\n - Solomon (1–11)\n - Adonijah’s failed usurpation (1)\n - David’s death; Solomon executes political instructions (2)\n - Solomon granted Wisdom at Gibeon; the two prostitutes (3)\n - Solomon’s bureaucracy (4)\n - Solomon’s tributes; preparations for the temple (5)\n - Building the temple; the palace; furnishing the temple (6–7)\n - Solomon consecrates the temple (8)\n - Second revelation; deeds of Solomon (9)\n - Queen of Sheeba; Solomon’s wealth (10)\n - Dissolution of Solomon’s kingdom (11)\n - The divided kingdom (12–22)\n - The kingdoms split; Jeroboam sets up the golden calves (12)\n - Josiah prophesied to destroy calves; disobedient prophet dies (13)\n - Jeroboam’s downfall predicted; Rehoboam’s reign and loss of temple treasures (14)\n - Abijam (bad) then Asa (good) rule Judah; Nadab then Baasha rule Israel (15)\n - Elah reigns in Israel, usurped by Zimri, usurped by Omri, succeeded by Ahab; Jericho’s foundations relaid (16)\n - Elijah fed by ravens then by a widow (17)\n - Elijah’s contest with the Baal prophets (18)\n - Elijah flees to the desert; revelation at Horeb; calls Elisha (19)\n - Ben-hadad of Aram’s two failed invasions (20)\n - Jezebel arranges for Ahab to take Naboth’s Jezreel vineyard (21)\n - Lieing prophets cause war with Aram; Ahab dies; Jehoshapat dies; Ahaziah reigns (22)\n- Kings II\n - The divided kingdom continued (1–17)\n - Ahaziah injured; Elisha’s response with fire; Ahaziah dies (1)\n - Elijah taken up; Elisha’s double portion; heals spring; kills boys (2)\n - Meshe of Moab successfully rebels (3)\n - Elisha’s endless oil; barren benefactors; resurrection; neutralized step; endless bread (4)\n - Elisha has leper Naaman dip in the Jordan; Gehazi’s greed (5)\n - Elisah makes ax head float; foils Aramean raiders (6)\n - Samaria sieged; Arameans flee; Leppers loot; doubter trampled (7)\n - Barren benefactor flees and returns; Elisha prophecies Ben-hadad’s death and Hazael’s rise; reign of Joram; Edom lost; reign of Ahaziah of Judah (8)\n - Elisha annoints Jehu, who kills Joram then Jezreel (9)\n - Jehu purges Ahab’s house and Baal worshipers (10)\n - Queen mother Athaliah takes throne; hidden Joash takes back (11)\n - Jehoash’s reign; temple repairs; buys off Hazael (12)\n - Jehoahaz then Joash rule Israel; Elisha’s death and prophecy of Aram’s doom (13)\n - Amaziah’s reign in Judah; defeated by Joash; Jerusalem plundered; Jeroboams II’s reign (14)\n - Zechariah, Shallum, Menahem, Pekahiah, and Pekah rule Israel; Azariah’s long reign, followed by Jotham. First Assyrians conquest of Israel 733–32 BCE (15)\n - Ahaz’s evil reign of Judah; son sacrificed; plots with Assyria to fight Aram and Israel (16)\n - Hoshea, the final king of Israel; Israel exiled in 722 BCE; God’s justification; merging of religious customs (17)\n - Judah (18–25)\n - Hezekiah’s great reign; Sennacherib invades 701 BCE (18.1–16)\n - Story about failed siege of Jerusalem; Esarhaddon succeeds Sennacherib (18.17–19.37)\n - Hezekiah’s faith, via Isaiah, gives 15 more years; Babylonian visitors and prophesied doom; Hezekiah’s death (20)\n - Manasseh’s evil reign; prophecy of exile; Amon’s evil reign (21)\n - Josiah’s great reign; temple repairs; discovery of the scroll (22)\n - Josiah reads the scroll; clears false gods; centralizes worship; Egyptians kill Josiah in Megiddo; Jehoiakim placed on throne (23)\n - Jehoiamkim becomes a Babylonia vassal, then rebels; Jerusalem sacked once; Jehoichin reigns; surrenders; Jerusalem exiled 597 BCE; Zedekiah placed on throne (24)\n - Zedekiah rebels and defeated; temple destroyed in 586 BCE; Jerusalem’s walls torn down; Gedaliah put in charge, then killed; Jehoiachin released and dines with Babylonian king (25)\n\n## Joshua: Flexible nature of the text\n\nJoshua 5.30–35 is likely a late addition to the book, since it is placed in different parts of the story in different scrolls. A Dead Sea Scroll text places it after the second circumcisions in 5.2. The Septuagint places it after the gathering of kings in 9.2. Josephus, in _The Antiquities of the Jews_ places it after the division of land. R. Ishmael places it at the end of the book. This is concrete evidence that some edits were being made to the text after it was written. In this case, the addition makes sense since it fills in a “hole” in the story—without this passage Deuteronomy 27.3–8 is not fulfilled.\n\n## Genocide and the Incomplete Conquest\n\nGod wanted his people to be separated from the Canaanites who were in the land. Leviticus 18 says that these people were sexually immoral and defiled the land. Deuteronomy 12 says they sacrificed their children to their gods.\n\nThere are two textual difficulties with the conquest of Canaan. First, it is genocidal. Second, it seems like it was not as complete as it was meant to be.\n\nThe archaeological record discredits the historicity of Joshua.\n\nHere are a few verses about demonstrating that the conquests were meant to completely eliminate those present in the land:\n\n<blockquote class=\"prose\">\n<p>And at the seventh time, when the priests had blown the trumpets, Joshua said to the people, “Shout! For the LORD has given you the city. The city and all that is in it shall be devoted to the LORD for destruction. Only Rahab the prostitute and all who are with her in her house shall live because she hid the messengers we sent. As for you, keep away from the things devoted to destruction, so as not to covet and take any of the devoted things and make the camp of Israel an object for destruction, bringing trouble upon it. But all silver and gold, and vessels of bronze and iron, are sacred to the LORD; they shall go into the treasury of the LORD.” So the people shouted, and the trumpets were blown. As soon as the people heard the sound of the trumpets, they raised a great shout, and the wall fell down flat; so the people charged straight ahead into the city and captured it. Then they devoted to destruction by the edge of the sword all in the city, both men and women, young and old, oxen, sheep, and donkeys. <cite>(Joshua 6.16–21)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>When Joshua and all Israel saw that the ambush had taken the city and that the smoke of the city was rising, then they turned back and struck down the men of Ai. And the others came out from the city against them; so they were surrounded by Israelites, some on one side, and some on the other; and Israel struck them down until no one was left who survived or escaped. But the king of Ai was taken alive and brought to Joshua.</p>\n<p>When Israel had finished slaughtering all the inhabitants of Ai in the open wilderness where they pursued them, and when all of them to the very last had fallen by the edge of the sword, all Israel returned to Ai, and attacked it with the edge of the sword. The total of those who fell that day, both men and women, was twelve thousand—all the people of Ai. For Joshua did not draw back his hand, with which he stretched out the sword, until he had utterly destroyed all the inhabitants of Ai. Only the livestock and the spoil of that city Israel took as their booty, according to the word of the LORD that he had issued to Joshua. So Joshua burned Ai, and made it forever a heap of ruins, as it is to this day. And he hanged the king of Ai on a tree until evening; and at sunset Joshua commanded, and they took his body down from the tree, threw it down at the entrance of the gate of the city, and raised over it a great heap of stones, which stands there to this day. <cite>(Joshua 8.21–9)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>So Joshua took all that land: the hill country and all the Negeb and all the land of Goshen and the lowland and the Arabah and the hill country of Israel and its lowland, from Mount Halak, which rises toward Seir, as far as Baal-gad in the valley of Lebanon below Mount Hermon. He took all their kings, struck them down, and put them to death. Joshua made war a long time with all those kings. There was not a town that made peace with the Israelites, except the Hivites, the inhabitants of Gibeon; all were taken in battle. For it was the LORD’s doing to harden their hearts so that they would come against Israel in battle, in order that they might be utterly destroyed, and might receive no mercy, but be exterminated, just as the LORD had commanded Moses. <cite>(Joshua 11.16–20)</cite></p>\n</blockquote>\n\nThe conquest of the land, however, was not complete. This is difficult to explain, since if God promised something, and God is all-powerful, then how did it not come to pass? There are a few explanations for this reaching as far back as Deuteronomy.\n\n<blockquote class=\"prose\">\n<p>Do not be terrified by them, for the LORD your God, who is among you, is a great and awesome God. The LORD your God will drive out those nations before you, little by little. You will not be allowed to eliminate them all at once, or the wild animals will multiply around you. But the LORD your God will deliver them over to you, throwing them into great confusion until they are destroyed. He will give their kings into your hand, and you will wipe out their names from under heaven. No one will be able to stand up against you; you will destroy them. <cite>(Deuteronomy 7.21–4)</cite></p>\n</blockquote>\n\nJoshua 9 explains how the Gibeonites tricked the Israelites. They made it look like they came from far away, and asked to make a treaty.\n\n<blockquote class=\"prose\">\n<p>So the leaders partook of their provisions, and did not ask direction from the LORD. And Joshua made peace with them, guaranteeing their lives by a treaty; and the leaders of the congregation swore an oath to them. <cite>(Joshua 9.14–5)</cite></p>\n</blockquote>\n\nJoshua then discovers they had been tricked, and summons them, saying:\n\n<blockquote class=\"prose\">\n<p>“Why did you deceive us, saying, ‘We are very far from you,’ while in fact you are living among us? Now therefore you are cursed, and some of you shall always be slaves, hewers of wood and drawers of water for the house of my God.” They answered Joshua, “Because it was told to your servants for a certainty that the LORD your God had commanded his servant Moses to give you all the land, and to destroy all the inhabitants of the land before you; so we were in great fear for our lives because of you, and did this thing. And now we are in your hand: do as it seems good and right in your sight to do to us.” This is what he did for them: he saved them from the Israelites; and they did not kill them. But on that day Joshua made them hewers of wood and drawers of water for the congregation and for the altar of the LORD, to continue to this day, in the place that he should choose.” <cite>(Joshua 9.22–27)</cite></p>\n</blockquote>\n\nIn the second half of Joshua, the tribes are blamed for not driving out the inhabitants:\n\n<blockquote class=\"prose\">\n<p>They did not, however, drive out the Canaanites who lived in Gezer: so the Canaanites have lived within Ephraim to this day but have been made to do forced labor. <cite>(Joshua 16.10)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>But the people of Judah could not drive out the Jebusites, the inhabitants of Jerusalem; so the Jebusites live with the people of Judah in Jerusalem to this day. <cite>(Joshua 16.63)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>Yet the Manassites could not take possession of those towns; but the Canaanites continued to live in that land. But when the Israelites grew strong, they put the Canaanites to forced labor, but did not utterly drive them out. <cite>(Joshau 17.12–13)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>The tribe of Joseph said, “The hill country is not enough for us; yet all the Canaanites who live in the plain have chariots of iron, both those in Beth-shean and its villages and those in the Valley of Jezreel.” Then Joshua said to the house of Joseph, to Ephraim and Manasseh, “You are indeed a numerous people, and have great power; you shall not have one lot only, but the hill country shall be yours, for though it is a forest, you shall clear it and possess it to its farthest borders; for you shall drive out the Canaanites, though they have chariots of iron, and though they are strong.” <cite>(Joshau 17.16–18)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>There remained among the Israelites seven tribes whose inheritance had not yet been apportioned. So Joshua said to the Israelites, “How long will you be slack about going in and taking possession of the land that the Lord, the God of your ancestors, has given you? <cite>(Joshua 18.2–3)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>So now I say, I will not drive them out before you; but they shall become adversaries to you, and their gods shall be a snare to you.” <cite>(Judges 2.3)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>So the anger of the Lord was kindled against Israel; and he said, “Because this people have transgressed my covenant that I commanded their ancestors, and have not obeyed my voice, I will no longer drive out before them any of the nations that Joshua left when he died.” <cite>(Judges 2.20–1)</cite></p>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>Now these are the nations that the Lord left to test all those in Israel who had no experience of any war in Canaan (it was only that successive generations of Israelites might know war, to teach those who had no experience of it before): the five lords of the Philistines, and all the Canaanites, and the Sidonians, and the Hivites who lived on Mount Lebanon, from Mount Baal-hermon as far as Lebo-hamath. <cite>(Judges 3.1–3)</cite></p>\n</blockquote>\n\nThese statements appear to conflict with other statements in Joshua:\n\n<blockquote>\n<p>Thus the Lord gave to Israel all the land that he swore to their ancestors that he would give them; and having taken possession of it, they settled there. And the Lord gave them rest on every side just as he had sworn to their ancestors; not one of all their enemies had withstood them, for the Lord had given all their enemies into their hands. Not one of all the good promises that the Lord had made to the house of Israel had failed; all came to pass.</p>\n<p>(Joshua 21.43–45)</p>\n</blockquote>\n\n<script>\ndocument.documentElement.classList.add('js')\nul=document.querySelectorAll('main > ul')[0]\nul.onclick=function(e){\n if(e.target.tagName === 'LI')\n e.target.classList.toggle('hidden-children')\n}\nfunction setDepth(d,e){\n e.preventDefault()\n var s=''\n while(d--){\n s+='li '\n ul.querySelectorAll(s).forEach(function(li){\n if(d!=0)\n li.classList.remove('hidden-children')\n else\n li.classList.add('hidden-children')\n })\n }\n}\n</script>\n" }, { "alpha_fraction": 0.7811984419822693, "alphanum_fraction": 0.7820230722427368, "avg_line_length": 59.63333511352539, "blob_id": "de2b679f667fa85b47c5b5b892c1fdffe49a7e98", "content_id": "2b6a39a1d098fa8eb1158fdfe596defa6db4c0dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3670, "license_type": "no_license", "max_line_length": 314, "num_lines": 60, "path": "/_documents/meaning-and-purpose.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Meaning and Purpose\ndescription: >\n A meandering contemplation of meaning and purpose\ntype: essay\nstatus: incomplete\n---\n\n## Uses of the Word “Meaning”\n\nThe word “meaning” has a few uses:\n\n1. What symbols or actions convey, indicate, or reference\n2. The significance or importance of something\n3. The purpose or intent something\n\nThese uses appear related.\n\n## Meaning as Significance\n\nMy wedding day was more meaningful than yesterday. What makes some days more meaningful than others? I believe the meaning of an event to an individual derives from the impact of that event on the individual.\n\nMy wedding was not meaningful to the caterers who patiently served my family that day. Meaning is in the memory of the beholder and is therefore relative.\n\nMy great grandfathers met my great grandmothers, and begot those that begot those that begot me. The moments of their meetings impacted me greatly, but I do not know anything about them, and they are not meaningful to me. Many great inventions and ideas impact me daily, but are not meaningful to me.\n\nMeaning is not synonymous with impact. Meaning derives from our memories, and the impact of these memories.\n\nMeaning is recursively derived. For example, the meaning in my relationship with my wife is derived from the meaning of many days spent together.\n\n## Meaning as Purpose\n\nPurpose is the reason for which something exists. “Humanity’s chief purpose is to glorify God, and to enjoy him forever.” The purpose of a jar is to decorate or contain. The purpose of my trip to the country was to enjoy nature.\n\nPurpose is a relation between a creator and the created.\n\nWhen someone asks “what is my purpose,” it may mean “for what purpose was I created?” or it may mean “what purpose should be behind the collective actions of my life?” In the first case, God is the creator and the person is the created. In the second case the person is the creator and their actions are created.\n\n## Meaning and a Creator\n\nIf we are created we may find meaning in the fulfillment of our creator’s purpose.\n\nOr we may not—a Sumerian, who believes they were created to supply beer and bread to the gods, may find the endless sacrifices meaningless.\n\nAlternately, there may be a creator, yet we may not have any purpose—perhaps we are agents in a simulation, and we evolved by chance and our universe is entertainment for higher beings who are largely indifferent to our existence.\n\n## Meaning and the Finite\n\nCan there be meaning in the finite? If conscious existence will be snuffed out by entropy, can our lives have lasting meaning?\n\nFor most of us, lasting meaning requires lasting existence. We may die, but our contributions, ideas, art, writing, or offspring will not. Three thousand years pass, and Achilles is still famous, but eventually all memory of Achilles will be lost. Will his striving be meaningless?\n\nWhen faced with our finite existence, we can only find meaning outside of time. Any effect of us having existed may be gone, but we still did exist. We lived our best life. We loved our best, and contributed what we could. We appreciated the beauty of the universe, and that will never change.\n\n## Meaning and the Infinite\n\nThe longer one lives, the less significant any particular day or event becomes. Our first trip abroad is more meaningful than the tenth.\n\nIf meaning originates from significance, then an infinite existence acts to reduce the meaning of any of it. In this way, meaning may be squeezed out by the infinite. Alternately, one may say that all meaning comes from the finite; our lives are valuable _because_ they are short.\n" }, { "alpha_fraction": 0.5581395626068115, "alphanum_fraction": 0.5581395626068115, "avg_line_length": 5.047618865966797, "blob_id": "0100c29fcbd8d662864aff4a3492954c904e21af", "content_id": "4e8a2c1e93d33665740d6b97e15a2fc90798a70f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 129, "license_type": "no_license", "max_line_length": 18, "num_lines": 21, "path": "/templates/note.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n TITLE\ntype: note\ndescription: >\n Notes on \"TITLE\"\n---\n\n## Summary\n\n\n\n## Outline\n\n\n\n## Truth\n\n\n\n## Implications\n\n\n" }, { "alpha_fraction": 0.7863573431968689, "alphanum_fraction": 0.7882964015007019, "avg_line_length": 87.58282470703125, "blob_id": "1e4d60e10c98db3f12b472a2ee4349995c2167a9", "content_id": "4132e432a8d2be55d0f1d1e8788260165fce5a5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14638, "license_type": "no_license", "max_line_length": 1325, "num_lines": 163, "path": "/_documents/the-righteous-mind.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n The Righteous Mind\ndescription: >\n Notes on “The Righteous Mind”\ntype: note\n---\n\n## Summary\n\n## Outline\n\n- Intuitions come first; strategic reasoning second\n - Where does morality come from?\n - Nativist: It is innate (biology or God)\n - Empiricist: From observations or experience; taught by parents and society\n - Rationalist: Self-taught from observations, and especially that the child doesn’t like to be harmed\n - Intuitionism: Moral “tastebuds” are innate; society teaches us what “tastes good”\n - Models of the Mind\n - Plato: Reason could and should be master\n - Hume: Reason should serve the “passions”\n - Jefferson: Reason and emotions are equally good\n - Evidence that institutions come first\n - Evidence that strategic reasoning comes second\n- There’s more to morality than harm and fairness\n - Sociocentric vs individualistic cultures\n - Moral Tastebuds:\n - Care/Harm\n - Fairness/Cheating\n - Loyalty/Betrayal\n - Authority/Subversion\n - Sanctity/Degradation\n - Liberty/Oppression\n- Morality Binds and Blinds\n - Group selection is real\n - Major biological transitions are a form of group selection\n - ,1j\n\n## Questions\n\nWhat is the precise difference between moral rationalism and empiricism?\n\nCertainly the empiricist is allowed to use reason to develop their morality? Perhaps the distinction is that the empiricist believes we merely follow the patterns set by the humans around us, while the rationalist uses first-principles to derive morality.\n\nRationalism and empiricism would then be gradations on a spectrum. The rationalist uses observations and experience, as well as reason.\n\n## The Rationalist Delusion\n\nAt first Haidt seemed to agree with Hume that reason _ought_ to serve emotions. This interpretation is strengthened by his use of the term the “rationalist delusion.” But I think Haidt does _not_ believe reason should serve the emotions. Instead, he is skeptical of the individual’s ability to reason, but ultimately reason is still king.\n\nAt the end of Book I, Haidt presents his most compelling arguments against the rationalist view of the mind (and moral thinking):\n\n<blockquote>\n<p>Anyone who values truth should stop worshipping reason. We all need to take a cold hard look at the evidence and see reasoning for what it is … most of the bizarre and depressing research findings make perfect sense once you see reasoning as having evolved not to help us find truth but to help us engage in arguments, persuasion, and manipulation in the context of discussions with other people … ”This explains why the confirmation bias is so powerful, and so ineradicable. How hard could it be to teach students to look on the other side, to look for evidence against their favored view? Yet, in fact, it’s very hard, and nobody has yet found a way to do it. It’s hard because the confirmation bias is a built-in feature (of an argumentative mind), not a bug that can be removed (from a platonic mind).</p>\n<p>I’m not saying we should all stop reasoning and go with our gut feelings. Gut feelings are sometimes better guides than reasoning for making consumer choices and interpersonal judgments, but they are often disastrous as a basis for public policy, science, and law. Rather, what I’m saying is that we must be wary of any individual’s ability to reason. We should see each individual as being limited, like a neuron. A neuron is really good at one thing: summing up the stimulation coming into its dendrites to “decide” whether to fire a pulse along its axon. A neuron by itself isn’t very smart. But if you put neurons together in the right way you get a brain; you get an emergent system that is much smarter and more flexible than a single neuron.</p>\n<p>In the same way, each individual reasoner is really good at one thing: finding evidence to support the position he or she already holds, usually for intuitive reasons. We should not expect individuals to produce good, open-minded, truth-seeking reasoning, particularly when self-interest or reputational concerns are in play. But if you put individuals together in the right way, such that some individuals can use their reasoning powers to disconfirm the claims of others, and all individuals feel some common bond or shared fate that allows them to interact civilly, you can create a group that ends up producing good reasoning as an emergent property of the social system. This is why it’s so important to have intellectual and ideological diversity within any group or institution whose goal is to find truth (such as an intelligence agency or a community of scientists) or to produce good public policy (such as a legislature or advisory board). And if our goal is to produce good behavior, not just good thinking, then it’s even more important to reject rationalism and embrace intuitionism. <cite>(pp. 104–5)</cite></p>\n</blockquote>\n\nThe evidence presented in part one highlights how difficult it is for individual reasoning to find truth. In this quote, Haidt presents his alternative method—diverse groups civilly debating one another. This alternative method of truth-finding appeals to me; many of my most productive intellectual developments stem from conversations.\n\nThis passage implies that the individual reasoner _can_ arrive at the truth in some cases, especially when within a diverse and civil group. Afterall, the individuals must be able to accept the external arguments which are most true. If they can’t, how could the group arrive at the truth?\n\nHaidt anticipates this tension when he says:\n\n<blockquote>\n<p>I have tried to make a reasoned case that our moral capacities are best described from an intuitionist perspective. I do not claim to have examined the question from all sides, nor to have offered irrefutable proof. Because of the insurmountable power of the confirmation bias, counterarguments will have to be produced by those who disagree with me. Eventually, if the scientific community works as it is supposed to, the truth will emerge as a large number of flawed and limited minds battle it out. <cite>(p. 107)</cite></p>\n</blockquote>\n\nAll skeptics of individual reasoning face this contradiction when they reason.\n\nHaidt focuses on morality, politics, and psychology, fields where truth is ambiguous and our individual bias are profound. These biases are less problematic in other fields, such as math and physics, where reality more immediatly tempers our biases.\n\n<blockquote>\n<p>I have argued that the Humean model (reason is a servant) fits the facts better than the Platonic model (reason could and should rule) or the Jeffersonian model (head and heart are co-emperors). But when Hume said that reason is the “slave” of the passions, I think he went too far … When does the elephant listen to reason? The main way that we change our minds on moral issues is by interacting with other people. We are terrible at seeking evidence that challenges our own beliefs, but other people do us this favor, just as we are quite good at finding errors in other people’s beliefs. When discussions are hostile, the odds of change are slight. The elephant leans away from the opponent, and the rider works frantically to rebut the opponent’s charges. But if there is affection, admiration, or a desire to please the other person, then the elephant leans toward that person and the rider tries to find the truth in the other person’s arguments. The elephant may not often change its direction in response to objections from its own rider, but it is easily steered by the mere presence of friendly elephants (that’s the social persuasion link in the social intuitionist model) or by good arguments given to it by the riders of those friendly elephants (that’s the reasoned persuasion link). <cite>(p. 79)</cite></p>\n</blockquote>\n\nHaidt uses “reason” to mean an individual brain’s flawed “ability to reason,” not the abstract conceptualization of reason as a pure good thing.\n\nTo see why this distinction is important, imagine a biased partisan searching for evidence to affirm their party’s position. In one sense this individual is “reasoning”—he is using the reasoning part of his mind. In another sense, they are only reasoning in proportion to their ability to find the truth. (… but on further consideration, if we define “reason” to be “the path towards truth,” then it is a useless definition … I think Haidt’s definition of the term reason is actually more appropriate …)\n\nHaidt’s skepticism towards reason is less radical that it first seems—it seems that he agrees with Plato that abstract reason _should_ be king, but that individuals are not goo\n\n## What is Reason?\n\nWhat does Haidt mean by “reason?” To begin, lets assume he means what is normally meant. What is normally meant by the word “reason?”\n\nSometimes the word is used as a noun. For example, “my reason for moving to New York.” Here the “reason” is the result of “reasoning.” It is the output of a process. “A cause, explanation, or justification for an action or event.”\n\nThe word “reason” is also used as a verb. To “reason” is to “think, understand, and form judgments by a process of logic.”\n\nThe reasoning process varies with the task. Consider:\n\n- Solving a mathematics problem\n- Designing a physics experiment\n- Modeling weather systems\n- Deducing the conclusions of a psychology experiment\n- Deciding whether to hire a particular individual\n- Predicting the effects of law on society\n\nIt surprises me that so many varied actives are considered “reasoning.” The processes that are followed by a mathematician and a politician are quite different.\n\nGood reasoning tends to lead to true judgments. But even reasoning which leads to false judgments may be “good” in the sense that the conclusions drawn were the most likely given the evidence available.\n\n## Objects vs Relationships\n\nNear the opening of book II, Haidt makes the following claim:\n\n<blockquote>\n<p>The WEIRDer (Western, educated, industrialized, rich, democratic) you are, the more you see a world filled with separate objects, rather than relationships.</p>\n</blockquote>\n\nHe then presents some experimental evidence to back his claim, before proceeding to draw very wide-ranging conclusions from this assessment. For example, he says:\n\n<blockquote>\n<p>But if you live in a non-WEIRD society in which people are more likely to see relationships, contexts, groups, and institutions, then you won’t be so focused on protecting individuals. You’ll have a more sociocentric morality, which means that you place the needs of groups and institutions first, often ahead of the needs of individuals.</p>\n</blockquote>\n\nHaidt’s justification for these claims is insufficient.\n\nFirst he presents an experiment where Eastern Asians and Americans are asked to complete “I am …”, and WEIRD people describe themselves in terms of their own attributes, while Eastern Asian people describe themselves in terms of their relationships with others.\n\nI suspect there _are_ significant differences between these two groups. I even accept that Eastern Asians are more likely to view themselves in terms of their relationships than Westerners (based on my experiences talking to Asian people).\n\nBut the study presented does not seem to be good evidence for the claim that Eastern Asians perceive the world differently.\n\nNext he presents a visual experiment:\n\n<blockquote>\n<p>The differences run deep; even visual perception is affected. In what’s known as the framed-line task, you are shown a square with a line drawn inside it. You then turn the page and see an empty square that is larger or smaller than the original square. Your task is to draw a line that is the same as the line you saw on the previous page, either in absolute terms (same number of centimeters; ignore the new frame) or in relative terms (same proportion relative to the frame). Westerners, and particularly Americans, excel at the absolute task, because they saw the line as an independent object in the first place and stored it separately in memory. East Asians, in contrast, outperform Americans at the relative task, because they automatically perceived and remembered the relationship among the parts.</p>\n</blockquote>\n\nThe connection between the visual experiment and these broad claims about sociocentric cultures is weak at best.\n\nFurthermore, a research group in China [attempted to reproduce](https://doi.org/10.1167/8.12.2) the visual perception experiment, and did not see the cultural differences that Kutayama did.\n\n<blockquote>\n<p>Our data do not support the hypothesis advocated in Kitayama et al. (2003) that basic visual perception is influenced by the perceiver’s cultural background. Instead, the data could be explained by a simpler notion that a visible frame of reference helps encode more precisely a line’s length relative to the frame than the same line’s length independent of the frame (Rock &amp; Ebenholtz, 1959).</p>\n</blockquote>\n\nIn general, I thought the evidence presented in Part II was much weaker than in Part I. For example, Haidt presents the “evolutionary origins” of the different taste receptors, but as best I recall, didn’t provide any evidence (beyond the fact that all his claims are plausible) for them. I appreciated that he said:\n\n<blockquote>\n<p>My goal was to find links between virtues and well-established evolutionary theories. I didn’t want to make the classic mistake of amateur evolutionary theorists, which is to pick a trait and then ask: “Can I think of a story about how this trait might once have been adaptive?” The answer to that question is almost always yes because reasoning can take you wherever you want to go. Anyone with access to an armchair can sit down and generate what Rudyard Kipling called “just-so stories”—fantastical accounts of how the camel got a hump and the elephant got a trunk. My goal, in contrast, was to identify the most obvious links between two fields I deeply respected: anthropology and evolutionary psychology.</p>\n</blockquote>\n\nI think Haidt’s overall thesis is very plausible, and I have so-far enjoyed his discussion a lot and feel that he has provided a nice mental model of morality. But his scientific justification for his thesis feels misleading.\n\n\n## Does Education make us Moral?\n\nI suspect it does, but why?\n\n## Truth\n\n\n\n## Implications\n\n\n## References\n\n- [Hume’s Moral Philosophy](https://plato.stanford.edu/entries/hume-moral/)\n-\n\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7447332739830017, "avg_line_length": 58.756343841552734, "blob_id": "a79b7216446f394314a8e08f75cb0fcbd78e163e", "content_id": "28f1e414075242f7ecfc4a4a9d12441eb996d934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11868, "license_type": "no_license", "max_line_length": 534, "num_lines": 197, "path": "/_documents/the-epic-of-gilgamesh.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n _The Epic of Gilgamesh_\ndescription: >\n A commentary on _The Epic of Gilgamesh_\ntype: note\nstatus: incomplete\n---\n\nAncient and beautiful, *The Epic of Gilgamesh* is the story of the king of Uruk.\n\nGilgamesh was a powerful and handsome king, but he oppressed his people. He forced new brides to have sex with him on their wedding night. The young women of Uruk cried out, and the gods heard them. The gods decided to create the wildman Enkidu to vie with Gilgamesh and to relieve Uruk’s citizens:\n\n<blockquote class=\"poetry\">\n<p>The goddess Aruru, she washed her hands,</p>\n<p class=\"indent\">took a pinch of clay, threw it down in the wild.</p>\n<p>In the wild she created Enkidu, the hero,</p>\n<p class=\"indent\">offspring of silence, knit strong by Ninurta.</p>\n</blockquote>\n\nA game trapper finds Enkidu at a watering hole, and is concerned because he fills in his pits and pulls up his snares. The trapper’s father advises his son to bring Shamhat, a harlot from Uruk, to the watering hole to tempt Enkidu with her charms. Here is the scene where Shamhat tempts Enkidu, and tells him to leave the wilderness and his animals:\n\n<blockquote class=\"poetry\">\n<p>One day and a second they waited by the water-hole,</p>\n<p class=\"indent\">then the herd came down to drink the water.</p>\n<p>The game arrived, their hearts <em>delighted in</em> water,</p>\n<p class=\"indent\">and Enkidu also, born in the uplands.</p>\n<br>\n<p>With the gazelles he grazed on grasses,</p>\n<p class=\"indent\"><em>joining the throng</em> with the game at the water-hole,</p>\n<p>his heart <em>delighting</em> with the beasts in the water:</p>\n<p class=\"indent\">then Shamhat saw him, the child of nature,</p>\n<p>the savage man from the midst of the wild.</p>\n<br>\n<p>⋯</p>\n<br>\n<p>Shamhat unfastened the cloth of her loins,</p>\n<p class=\"indent\">she bared her sex and he took in her charms.</p>\n<p>She did not recoil, she took in his scent:</p>\n<p class=\"indent\">she spread her clothing and he lay upon her.</p>\n<br>\n<p>She did for the man the work of a woman,</p>\n<p class=\"indent\">his passion caressed and embraced her.</p>\n<p>For six days and seven nights</p>\n<p class=\"indent\">Enkidu was erect, as he coupled with Shamhat.</p>\n<br>\n<p>When with her delights he was fully sated,</p>\n<p class=\"indent\">he turned his gaze to his herd.</p>\n<p>The gazelles saw Enkidu, they started to run,</p>\n<p class=\"indent\">the beasts of the field shied away from his presence.</p>\n<br>\n<p>Enkidu had defiled his body so pure,</p>\n<p class=\"indent\">his legs stood still, though his herd was in motion.</p>\n<p>Enkidu was weakened, could not run as before,</p>\n<p class=\"indent\">but now he had <em>reason</em>, and wide understanding.</p>\n<br>\n<p>He came back and sat at the feet of the harlot,</p>\n<p class=\"indent\">watching the harlot, observing her features.</p>\n<p>Then to the harlot’s words he listened intently,</p>\n<p class=\"indent\"><em>as Shamhat</em> talked to him, to Enkidu:</p>\n<br>\n<p>“You are handsome, Enkidu, you are just like a god!</p>\n<p class=\"indent\">Why with the beasts do you wander the wild?</p>\n<p>Come, I will take you to Uruk-the-Sheepfold,</p>\n<p class=\"indent\">to the sacred temple, home of Anu and Ishtar”</p>\n</blockquote>\n\nI am quoting from the Andrew George translation; words in italics were difficult to decipher or were filled in from context.\n\nThis passage has similarities to the Adam and Eve story in the Book of Genesis. In both a man is created from the ground, tempted by a woman, succumbs, gains knowledge or understanding, and must leave their innocent way of life.\n\nThere are more differences between the stories than there are similarities. Eve was the innocent partner of Adam; Shamhat was a prostitute from the city. Adam and Eve tended a garden and named the animals, while Enkidu would run with the animals and free them from traps. Enkidu was “defiled” and gained “wide understanding,” while Adam gained “knowledge of good and evil.” Eve was tempted with knowledge by a snake, and then Eve tempted Adam; Enkidu was tempted with sex by Shamhat.\n\nThere is, however, a snake in the *Epic of Gilgamesh.* Gilgamesh is returning from a journey with a plant that will make him young again. This plant is similar to the tree of life in Genesis. Here is the passage:\n\n<blockquote class=\"poetry\">\n<p>“This plant, Ur-shanabi, is the ‘Plant of Heartbeat,’</p>\n<p class=\"indent\">with it a man can regain his vigour.</p>\n<p>To Uruk-the-Sheepfold I will take it,</p>\n<p class=\"indent\">to an ancient I will feed some and put the plant to the test!</p>\n<br>\n<p>“Its name shall be ‘Old Man Grown Young,’</p>\n<p class=\"indent\">I will eat it myself, and be again as I was in my youth!”</p>\n<p>At twenty leagues they broke bread,</p>\n<p class=\"indent\">at thirty leagues they stopped for the night.</p>\n<br>\n<p>Gilgamesh found a pool whose water was cool,</p>\n<p class=\"indent\">down he went into it, to bathe in the water.</p>\n<p>Of the plant’s fragrance a snake caught scent,</p>\n<p class=\"indent\">came up <em>in silence</em>, and bore the plant off.</p>\n<br>\n<p>As it turned away it sloughed its skin.</p>\n<p class=\"indent\">Then Gilgamesh sat down and wept,</p>\n<p>down his cheeks the tears were coursing.</p>\n</blockquote>\n\nIn both stories a snake causes a man to lose access to a plant which provides eternal life. However, there are many differences. In Genesis, the plant is given to Adam by God; Gilgamesh is told about the plant by the Babylonian Noah and he must find it himself. In Genesis, the plant is a tree in the garden of Eden; in the *Epic of Gilgamesh,* it is a prickly plant at the bottom of the “Ocean Below.”\n\nThe similarities between the story of Noah and the Babylonian texts are manifold. The creation story in Genesis, Job, the Psalms, and Ecclesiastes have traces of concepts from Babylonian texts.\n\nFor example, the Hebrew Bible, like Babylonian mythology, has the idea of the waters above and the waters below:\n\n<blockquote>\n<p>And God said, “Let there be a dome in the midst of the waters, and let it separate the waters from the waters.” So God made the dome and separated the waters that were under the dome from the waters that were above the dome. And it was so. God called the dome Sky. And there was evening and there was morning, the second day.</p>\n<cite>— Genesis 1:6–8, NRSV</cite>\n</blockquote>\n\n<blockquote>\n<p>In the six hundredth year of Noah’s life, in the second month, on the seventeenth day of the month, on that day all the fountains of the great deep burst forth, and the windows of the heavens were opened.</p>\n<cite>— Genesis 7:11, NRSV</cite>\n</blockquote>\n\n<blockquote>\n<p>And God made a wind blow over the earth, and the waters subsided; the fountains of the deep and the windows of the heavens were closed, the rain from the heavens was restrained, and the waters gradually receded from the earth.</p>\n<cite>— Genesis 8:1–3, NRSV</cite>\n</blockquote>\n\n<blockquote>\n<p>Praise him, you highest heavens, and you waters above the heavens!</p>\n<cite>— Psalms 149:4, NRSV</cite>\n</blockquote>\n\nThe most common explanation for the Hebrew’s and Babylonian’s belief in the waters above is that the sky is blue and water is blue.\n\nIn Babylonian mythology, Marduk was the supreme god. Marduk rose to power by killing Tiamat, who was often represented as a great sea dragon, when all the other Babylonian gods were too afraid to confront it. It seems that the Hebrew god references fought a similar battle:\n\n<blockquote class=\"poetry\">\n<p>“Can you draw out Leviathan with a fishhook,</p>\n<p class=\"indent\">or press down its tongue with a cord?</p>\n<p>Can you put a rope in its nose,</p>\n<p class=\"indent\">or pierce its jaw with a hook?</p>\n<p>⋯</p>\n<p>Any hope of capturing it will be disappointed;</p>\n<p class=\"indent\">were not even the gods overwhelmed at the sight of it?”</p>\n<cite>— Job 41:1–9, NRSV</cite>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>You divided the sea by your might;</p>\n<p class=\"indent\">you broke the heads of the dragons in the waters.</p>\n<p>You crushed the heads of Leviathan;</p>\n<p class=\"indent\">you gave him as food for the creatures of the wilderness.</p>\n<cite>— Psalm 74:13–14, NRSV</cite>\n</blockquote>\n\nFinally, parts of Ecclesiastes are very similar to the *Epic of Gilgamesh*. Here is a quote, from a tavern-keeper at the edge of the world, advising Gilgamesh:\n\n<blockquote class=\"poetry\">\n<p>“The life that you seek you never will find:</p>\n<p class=\"indent\">When the gods created mankind,</p>\n<p>Death they dispensed to mankind,</p>\n<p class=\"indent\">Life they kept for themselves.</p>\n<br>\n<p>“But you, Gilgamesh, let your belly be full,</p>\n<p class=\"indent\">Enjoy yourself always by day and by night!</p>\n<p>Make merry each day,</p>\n<p class=\"indent\">Dance and play day and night!</p>\n<br>\n<p>“Let your clothes be clean,</p>\n<p class=\"indent\">Let your head be washed, may you bathe in water!</p>\n<p>Gaze on the child who holds your hand,</p>\n<p class=\"indent\">Let your wife enjoy your repeated embrace!</p>\n<br>\n<p>“For such is the destiny of mortal men”</p>\n</blockquote>\n\nAnd here is a similar saying in Ecclesiastes:\n\n<blockquote>\n<p>The living know that they will die, but the dead know nothing; they have no more reward, and even the memory of them is lost. Their love and their hate and their envy have already perished; never again will they have any share in all that happens under the sun.</p>\n<p>Go, eat your bread with enjoyment, and drink your wine with a merry heart; for God has long ago approved what you do. Let your garments always be white; do not let oil be lacking on your head. Enjoy life with the wife whom you love, all the days of your vain life that are given you under the sun, because that is your portion in life and in your toil at which you toil under the sun. Whatever your hand finds to do, do with your might; for there is no work or though or knowledge or wisdom in Sheol, to which you are going.</p>\n<cite>— Ecclesiastes 9:5–10, NRSV</cite>\n</blockquote>\n\nFinally, the Hebrew and Babylonian flood stories are exceedingly similar. Instead of providing a long list of quotes, I will instead list the similarities:\n\n- Before the flood, men live many hundreds of years\n- Pre-flood individuals are taken directly to heaven (Enoch in the Hebrew Bible; Emmeduranki and others in the Babylonian tradition)\n- The human lifespan is limited\n- A single man to build a boat with specific dimensions\n- The flood wipes out all living creatures that are not on the boat\n- The man makes sacrifices which are pleasing to the gods or God\n- Three birds are sent to find land\n- A covenant established between the man and gods or God.\n\nThus, one can see that there are many similarities between the Babylonian texts and the Hebrew Bible. For any particular similarity one of the following must be true:\n\n1. It is a coincidence\n2. The Hebrew Bible was influenced by Babylonian texts\n3. Babylonian texts were influenced by the Hebrew Bible\n4. Both texts were influenced by a third, older, source.\n\nSome of these similarities may be deemed coincidental, but it seems implausible to believe that all of them are.\n\nEach similarity requires separate analysis. Sometimes we can rely on the dates of the texts to rule out certain possibilities. For example, Solomon is thought to have lived between 1000 and 900 BCE, and thus Ecclesiastes could not have been written earlier than this. The similar quote from *The Epic of Gilgamesh* if from a tablet that is from 1800–1700 BCE. Thus, explanation (3) is implausible.\n\nMost of the Babylonian clay tablets we have recovered were copied around the time of Babylonian captivity, and thus a simplistic archaeological analysis is not possible because we do not know when the age of the original material.\n" }, { "alpha_fraction": 0.7694610953330994, "alphanum_fraction": 0.7694610953330994, "avg_line_length": 26.83333396911621, "blob_id": "1d605e21403e63bef109e48c24906815272a256c", "content_id": "cc7c251d01ab6e2b1b6a5649321f2b7965964ccd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 338, "license_type": "no_license", "max_line_length": 132, "num_lines": 12, "path": "/_documents/a-definition-of-ethics.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n A Definition of Ethics\ndescription: >\n Ethics: the study of how concious beings should act.\ntype: essay\nstatus: incomplete\n---\n\nEthics is the study of how conscious beings should act.\n\nEthics don’t apply to rocks, but I believe dogs and monkeys can act ethically and unethically—proportionally to their consciousness.\n" }, { "alpha_fraction": 0.7968325614929199, "alphanum_fraction": 0.7972850799560547, "avg_line_length": 121.77777862548828, "blob_id": "4732b93ed83eb98fc41588ff752034ded9a7c1d4", "content_id": "1706e7e1f654666d8908032ce52a6a203d235a5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2218, "license_type": "no_license", "max_line_length": 519, "num_lines": 18, "path": "/_documents/altera-motivation.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Altera: Motivation\ndescription: >\n An introduction to Altera—a 2D world within which we will investigate many philosophical questions.\ntype: essay\nstatus: incomplete\n---\n\nI have found it helpful, when asking questions about our universe, to consider how analogous questions could be asked and answered by beings in an alternate, simpler universe. I call this universe Altera. Answers to many questions, when asked in our universe, are obscured by its complex nature and our uncertain place within it. Analogous questions, when asked in Altera, are often plainly answered. We may then be able to generalize these answers to our universe more clearly than if we had pursued them directly.\n\nImagining an alternate universe such as Altera is difficult because our minds are rooted in our own. We must remember that to the beings within it Altera is real. Our sense of normality is biased by our familiarity with, and existence in, our universe. But we have no firm reason to believe that our universe couldn’t have been different, or that alternate universes couldn’t exist.\n\nOur ability to imagine alternate universes is obstructed because we must describe them using familiar language. This difficulty could have been helped somewhat by using made-up words. However, it was burdensome to keep track of them so I repurposed words from our universe. I indicate when I am repurposing a word by placing it in quotes the first time it is used as such.\n\nDespite these difficulties, I have been able to clarify my thoughts using this approach, and I hope that others find similar success. In the least, it may be a clear exposition of many questions previously asked and answered by philosophers. At most, it may lead to new insights.\n\nThis sort of thought experiment has been performed before. The book *Flat Land*, written by Edwin Abbott Abbott, is the earliest example of which I am aware. In *Flat Land*, Abbott investigates the limitations of two-dimensional beings understanding a third dimension. With this regard, the book was successful, however, the extent of his investigation was limited. There are more questions to explore—especially questions about knowledge, metaphysics, and ethics.\n" }, { "alpha_fraction": 0.7914285659790039, "alphanum_fraction": 0.7914285659790039, "avg_line_length": 69, "blob_id": "24378d42a6228d6b7777889e0536ddf19314913e", "content_id": "0aae9f846107271a32570469f664560be9382baa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1750, "license_type": "no_license", "max_line_length": 499, "num_lines": 25, "path": "/documents/religion.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Religion\ndescription: >\n Notes on Religion\ntype: note\n---\n\nIt is difficult to define the word \"religion.\"\n\nWe often speak of \"a religion,\" but within that religion, there are many sub-groups with different beliefs and rituals. These sub-groups tend to be localized in time and space.\n\nNew religions usually branch off of older religions.\n\nReligions evolve over time.\n\nI often conceptualize a religion in terms of its beliefs, but this likely wasn't always the case. Religion has often been a group with set rituals and customs.\n\nBut is the distinction between belief and ritual real? Perhaps they are different views into the same reality.\n\nA human's actions can be determined by it's internal state (its memory of the past and its beliefs and implicit ethical system) and external stimuli.\n\nRituals are one sort of human action, but all human actions (even outside of formalized ritual, but the little decisions of daily life) are determined by beliefs and memories, implicitly or explicitly. If one defines a belief very broadly, such that it does not need to be explicitly considered by the holder, then even primitive humans performing rituals must have implicitly believed they should have performed the ritual. When generalized in this way, belief and ritual may be one and the same.\n\nI care more about beliefs because one can ask \"are they true?\" I care about truth because it will affect how I live my life. Thus, I care about ritual because it lets one deduce the implicit beliefs of a people, and by studying the evolution of beliefs in various religions and judging whether we think these systems are true, we can find epistemological principles which can guide us when we evaluate whether other religions are true.\n" }, { "alpha_fraction": 0.7579377889633179, "alphanum_fraction": 0.7645935416221619, "avg_line_length": 78.6956558227539, "blob_id": "6465a6e70079fe016aa4822b142eff03e04abb70", "content_id": "3180a1b0c3c6f0c19def8b12d5e350dc81f7fce2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18335, "license_type": "no_license", "max_line_length": 920, "num_lines": 230, "path": "/documents/the-master-and-margarita.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n \"The Master and Margarita\"\ndescription: >\n My thoughts, a summary, and a brief analysis of the theme of belief in the supernatural within the Russian classic \"The Master and Margarita.\"\ntype: note\nstatus: incomplete\n---\n\n## Background\n\n*The Master and Margarita* was written by Mikhail Bulgakov (mee-ha-EEL bool-GA-kov). He finished writing it in 1940 and it was first published in 1966.\n\n## Thoughts\n\nI enjoyed reading *The Master and Margarita* because it was funny, fantastical, and unique. The novel felt disjointed until the ending, when somehow, it felt like it congealed. A primary theme is belief in the supernatural.\n\nI noticed many Christian and Fäuste references, and certainly there are many that I missed. As an American reader who is ignorant of Russian history, I must have also missed other themes and satire.\n\n## Characters\n\n**Mikhail Alexandrovich Berlioz** is the short, dark-haired, plump, bald editor of a literary journal and chairman of the board of Massolit.\n\n**Ivan Nikolaevich Ponyrev** is a young, broad-shouldered poet who writes under the pseudonym Homeless.\n\n**Koroviev**, also called Fagott, is Woland's henchman; seven feet tall and unbelievably thin, he has a jeering face.\n\n**Woland** is satan. His left teeth have platinum crowns, his right have gold, his right eye is black, his left green, he has dark hair and appears to be a little over 40.\n\n**Yeshua Ha-Nozri**, Woland's depiction of Jesus. Yeshua is Aramaic for \"Lord of Salvation\" and Ha-Nozri means \"of Nazareth.\"\n\n**Pontius Pilate** was the procurator of Jerusalem.\n\n**Behemoth** is a giant, walking, talking black cat who loves guns and alcohol. He is one Woland's companions.\n\n**Stepan Bogdanovich Likhodeev**, or Styopa for short, is the director of the Variety Theatre, and Berlioz's roommate.\n\n**Azazello** is one of Woland's companions; he is short but extraordinarily broad-shouldered; he wears a bowler hat, has flaming red hair, a fang, and is quite ugly.\n\n**Doctor Stravinksy** is the friendly psychiatrist at the country hospital.\n\n**Nikanor Ivanovich Bosoy** is the chairman of the tenants' association where Berlioz and Styopa lived.\n\n**Grigory Danilovich Rimsky** is the financial directory (findirector) of the Variety Theater.\n\n**Ivan Savelyevich Varenukha** is the administrator of the Variety Theater.\n\n**Georges Bengalsky** is the master of ceremonies for the Variety Theater.\n\n**Vassily Stepanovich Lastochkin** is the bookkeeper at the Variety Theater.\n\n**The Master** is a writer, who wrote a book about Pontius Pilate and subsequently went insane. At the time when Ivan meets him, he is a \"clean shaven, dark-haired man of approximately thirty-eight, with a sharp nose, anxious [brown] eyes, and a wisp of hair hanging down on his forehead.\"\n\n**Margarita Nikolaevna** is a beautiful intelligent woman who lives in Moscow, and is one of the few characters who can accept the supernatural. For this reason Woland and his henchman seem to admire her.\n\nWoland, Homeless, Pontius Pilate, and Margarita were my favourite characters.\n\n## Outline\n\n1. Berlioz and Homeless discuss Jesus' existence with a stranger\n2. (Jerusalem) The stranger recalls Jesus' trial before Pontius Pilate\n3. Berlioz slips and is decapitated by a tram car\n4. Homeless chases then searches for the stranger; he losses is cloths\n5. Massolit members wait for Berlioz; Homeless barges in and is arrested\n6. Enraged Homeless is sedated at the clinic, and sent to the country\n7. Styopa wakes hungover, and Woland takes his theater and apartment, transporting him to Yalta\n8. Homeless wakes at the country hospital, and is convinced to stay\n9. Bosoy is vanished by Woland, after checking Berlioz's apartment\n10. Rimsky and Varenukha receive telegrams from Yalta; Varenukha is intercepted and brought to Woland\n11. Ivan gives up writing a statement to the police, and accepts his situation\n12. Woland's séance---cards, money, Bengalsky's head, dresses, exposure\n13. Ivan meets the master and hears story of love and the rejected novel\n14. Rimsky is ambushed by the ghost of Varenukha, barely escaping when the cock crows\n15. Bosoy arrives at the asylum and dreams about the currency theater\n16. (Jerusalem) Jesus is executed; Matthew Levi attempts to relieve him\n17. The Variety closes; supernatural events follow its bookkeeper until he is arrested\n18. Berlioz's uncle and the Variety's barman visit Woland\n19. Margarita meets Azazello, who proposes a way for her to see the master\n20. The magical cream turns Margarita into a beautiful which\n21. Margarita flies over Moscow and destroys the critic's apartment\n22. Margarita meets Woland, who is playing chess with Behemoth\n23. Margarita greets guests at Woland's super fantastical ball\n24. Woland reunites Margarita and the master in their old apartment\n25. (Jerusalem) Pilate meets with the head of secret police\n26. (Jerusalem) Judas is murdered, while chasing after his lover\n27. The investigation; Berlioz's appartment is destroyed in a fight\n28. Behometh and Koroviev wreck havoc on Moscow\n29. Yeshua intercedes for the master and Margarita and Woland complies\n30. The master and Margarita's magical departure from Moscow\n31. Whistles on the hills overlooking Moscow\n32. Pilate is relieved at last, and the master and Margarita can rest\n33. (Epilogue) The minor Moscow characters's endings\n\n## Theme: Belief in the Supernatural\n\nSatan visits Moscow and accomplishes his plans with many supernatural feats. The book explores how individuals react to these events, and in particular the nature of denial and belief.\n\nThe opening discussion, between the editor Berlioz, the poet Ivan, and the Satan, is regarding the existence of Jesus. After some back and forth, Satan says:\n\n> \"Bear in mind that Jesus did exist.\"\n> \"You see, Professor,\" Berlioz responded with a forced smile, \"we respect your great learning, but on this question we hold to a different point of view.\"\n> \"There's no need for any points of view,\" the strange professor replied, \"he simply existed, that's all.\"\n> \"But there's need for some proof ...\" Berlioz began.\n> \"There's no need for any proofs,\" replied the professor, and he began to speak softly ...\"\n> = (p. 14)\n\nAnd then Satan tells the story of Jesus' trial before Pilate.\n\nLater, Ivan discusses is in the insane asylum discussing his encounter with Satan with another inmate:\n\n> \"Very well,\" the visitor replied, and he said weightily and distinctly: \"Yesterday at the Patriarch's Ponds you met Satan.\"\n> Ivan did not get upset, as he had promised, but even so he was greatly astounded.\n> \"That can't be! He doesn't exist!\"\n> \"Good heavens! Anyone else might say that, but not you. You were apparently one of his first victims. You're sitting, as you yourself understand, in a psychiatric clinic, yet you keep saying he doesn't exist. Really, it's strange!\"\n> \"... And, really, I'm surprised at Berlioz! Now you, of course, are a virginal person,\" here the guest apologized again, \"but that one, from what I've heard about him, had after all read at least something!\"\n> = (p. 133)\n\nSurprisingly, the visitor (who, unknown to Ivan, is the master) doubts the existence of Satan towards the end of the novel, after Satan has returned the master and Margarita back to their little apartment in Moscow:\n\n> \"Pah, the devil!\" exclaimed the master unexpectedly. \"But, just think, it's ...\" he put out his cigarette butt in the ashtray and pressed his head with his hands. \"No, listen, you're an intelligent person and have never been crazy ... are you seriously convinced that we were at Satan's yesterday?\"\n> \"Quite seriously,\" Margarita replied.\n> \"Of course, of course,\" the master said ironically, \"so now instead of one madman there are two---husband and wife!\"\n> = (p. 365)\n\nMargarita, from the start, had less trouble believing in the supernatural, and she tries to convince here lover to believe too:\n\n> \"I swear to you by your life, I swear by the astrologer's son whom you guessed, that all will be well!\"\n> \"Fine, fine,\" responded the master, and he added, laughing: \"of course, when people have been robbed of everything, like you and me, they seek salvation from other-worldly powers! Well, so, I agree to seek there.\"\n> = (p. 367)\n\nBut he is still skeptical, until moments later one of Woland's companions visits:\n\n> \"No, Margarita's right... Of course, this is the devil's messenger sitting before me. No more than two nights ago, I myself tried to prove to Ivan that it was precisely Satan whom he had met at the Patriarch's Ponds, and now for some reason I got scared of the thoughts and started babbling something about hypnotists and hallucination...Devil there's any hypnotists in it!...\"\n> = (p. 368)\n\nMany other characters struggle to reconcile the supernatural events with their reason. The findirector Rimsky, upon receiving telegrams from Styopa who had been in Moscow that morning but was transported by Satan across Russian to Yalta, searches for possible explanations:\n\n> The findirector's position was very difficult. It was necessary at once, right on the spot, to invent ordinary explanations for extraordinary phenomena.\n\nAnd later that evening, during Woland's first séance, the master of ceremonies expresses a common response to the supernatural:\n\n> \"... And so, now comes the famous foreign artiste, Monseiur Woland, with a séance of black magic. Well, both you and I know,\" here Bengalsky smiled a wise smile, \"that there's no such thing in the world, and that it's all just superstition, and Maestro Woland is simply a perfect master of the technique of conjuring, as we shall see from the most interesting part, that is, the exposure of the technique\"\n> = (p. 119)\n\nand, after a couple very impressive \"magic tricks,\" including a rain of cash from the ceiling:\n\n> \"Here, citizens, you and I have just beheld a case of so-called mass hypnosis. A purely scientific experiment, proving in the best way possible that there are no miracles in magic. Let us ask Maestro Woland to expose this experiment for us. Presently, citizens, you will see these supposed banknotes disappear as suddenly as they appeared.\"\n> Here he applauded, but quite alone, while a confident smile played on his face, yet in his eyes there was no such confidence, but rather an expression of entreaty.\n> = (p. 122)\n\nShortly after, Satan has his cat cut off Bengalsky's head (it is put back on later) and then Bengalsky ends up in the insane asylum with other characters who have run into Wooland.\n\nPerhaps the novel's most direct rejection of atheism and disbelief is found in Woland's last words to the beheaded atheist Berlioz at his ball:\n\n> \"Everything came to pass, did it not?\" Woland went on, looking into the head's eyes. \"The head was cut off by a woman, the meeting did not take place, and I am living in your apartment. That is a fact. And fact is the most stubborn thing in the world. But we are now interested in what follows, and not in this already accomplished fact. You have always been an ardent preacher of the theory that, on the cutting off of his head, life ceases in a man, he turns to ashes and goes into non-being. I have the pleasure of informing you, in the presence of my guests, though they serve as proof of quite a different theory, that your theory is both solid and clever. However, one theory is as good as another. There is also one which holds that it will be given to each according to his faith. Let it come true! You go into non-being, and from the cup into which you are to be transformed, I will joyfully drink to being!\"\n> = (p. 273)\n\nThe epilogue describes how the many people who saw Woland's supernatural séance were able to rationalize it away and subsequently forget about it.\n\nThus, from start to finish, the novel explores belief and disbelief in reaction to the devil. The devil, like Jesus in the Bible, wants people to believe in him.\n\n## Quotes\n\nA nice taste of Bulgakov's funny whimsical style is found near the beginning of the novel, when two writers in the park attempt to a seltzer:\n\n> \"Give us seltzer,\" Berlioz asked.\n> \"There is no seltzer,\" the woman in the stand said, and for some reason became offended.\n> \"Is there beer?\" Homeless inquired in a rasping voice.\n> \"Beer'll be delivered towards evening,\" the woman replied.\n> \"Then what is there?\" asked Berlioz.\n> \"Apricot soda, only warm,\" said the woman.\n> \"Well, let's have it, let's have it! ...\"\n> The soda produced an abundance of yellow foam, and the air began to smell of a barber-shop. Having finished drinking, the writers immediately started to hiccup, paid, and sat down on a bench face to the pond and back to Bronnaya.\n> = (p. 3)\n\nThis quote, which has stuck with me perhaps more than any other, appears to be Bulgakov's rejection of human-derived morality:\n\n> \"But here is a question that is troubling me: if there is no God, then, one may ask, who governs human life and, in general, the whole order of things on earth?\"\n> \"Man governs it himself,' Homeless angrily hastened to reply to this admittedly none-too-clear question.\n> \"Pardon me,\" the stranger responded gently, \"but in order to govern, one needs, after all, to have a precise plan for a certain, at least somewhat decent, length of time. Allow me to ask you, then how can man govern, if he is not only deprived of the opportunity of making a plan for at least some ridiculously short period---well, say, a thousand years---but cannot even vouch for his own tomorrow?\"\n> = (pp. 9 - 10)\n\nAnd to make his point, the stranger predicts that Berlioz will die shortly there after, and sure enough he does. And, as we saw earlier, Berlioz meets an unfortunate ending.\n\nThe foreigner describes the process of getting lung-cancer:\n\n> \"You are no longer interested in anyone's fate but your own. Your family starts lying to you. Feeling that something is wrong, you rush to learned doctors, then to quacks, and sometimes to fortune-tellers as well. Like the first, so the second and third are completely senseless, as you understand. And it all ends tragically: a man who still recently thought he was governing something, suddenly winds up lying motionless in a wooden box, and the people around him, seeing that the man lying there is no longer good for anything, burn him in an oven.\"\n> = (p. 10)\n\nYeshua, explaining to Pontius Pilate that he did not incite the Jews to destroy the temple:\n\n> \"These good people ... haven't any learning and have confused everything I told them. Generally, I'm beginning to be afraid that this confusion may go on for a very long time. And all because he writes down the things I say incorrectly.\"\n> = (p. 19)\n\nBulgakov's interpolation of John 18:38, when Pilate asks Jesus \"What is Truth?\":\n\n> \"And why did you stir up the people in the bazaar, you vagrant, talking about the truth, of which you have no notion? What is truth?\"\n> And here the procurator thought: \"Oh, my gods! I'm asking him about something unnecessary at a trial ... my reason no longer serves me ...\" And again he pictured a cup of dark liquid. \"Poison, bring me poison...\"\n> And again he heard the voice:\n> \"The truth is, first of all, that your head aches, and aches so badly that you're having faint-hearted thoughts of death. You're not only unable to speak to me, but it is even hard for you to look at me. And I am now your unwilling torturer, which upsets me. You can't even think about anything and only dream that your dog should come, apparently the one being you are attached to. But your suffering will soon be over, your headache will go away.\"\n> = (p. 21)\n\nBulgakov's disdain for the mystics:\n\n> But no, no! The seductive mystics are lying, there are no Caribbean Seas in the world, no desperate freebooters sail them, no corvette chases after them, no cannon smoke drifts across the waves. There is nothing, and there was nothing! There is that sickly linden over there, there is the cast-iron fence, and the boulevard beyond it ... And the ice is melting in the bowl, and at the next table you see someone's bloodshot, bovine eyes, and you're afraid, afraid ... Oh, gods, my gods, poison, bring me poison! ...\n> = (p. 58)\n\nBulgakov's describes how Berlioz's death is received:\n\n> Yes, he's dead, dead ... But, we, we're alive!\n> Yes, a wave of grief billowed up, held out for a while, but then began to subside, and somebody went back to his table and---sneakily at first, then openly---drank a little vodka and ate a bite. And, really, can one let chicken cutlets de volaille perish? How can we help Mikhail Alexandrovich? By going hungry? But, after all, we're alive!\n> = (p. 59)\n\nThe various schemes to get Berlioz's living space:\n\n> The news of Berlioz's death spread through the whole house with a sort of supernatural speed, and as of seven o'clock Thursday morning, Bosoy began to receive telephone calls and then personal visits with declarations containing claims to the deceased's living space. In the period of two hours, Nikanor Ivanovich received thirty-two such declarations.\n> They contained pleas, threats, libels, denunciations, promises to do renovations at their expense, references to unbearable over-crowding and the impossibility of living in the same apartment with bandits. Among others there were a description, staggering in its artistic power, of the theft from the apartment no. 31 of some meat dumplings, tucked directly into the pocket of a suit jacket, two vows to end life by suicide and one confession of secret pregnancy.\n> = (p. 92)\n\nHow to tell if someone is lying:\n\n> \"Understand that the tongue can conceal the truth, but the eyes---never! A sudden question is put to you, you don't even flinch, in one second you get hold of yourself and know what you must say to conceal the truth, and you speak quite convincingly, and not a wrinkle on your face moves, but---alas---the truth which the question stirs up from the bottom of your soul leaps momentarily into your eyes, and it's all over! They see it, and you're caught!\"\n> = (p. 165)\n\nA lament as the master and Margarita leave the earth:\n\n> Gods, my gods! How sad the evening earth! How mysterious the mists over the swamps! He who has wandered in these mists, he who has suffered much before death, he who has flown over this earth bearing on himself too heavy a burden, knows it. The weary man knows it. And without regret he leaves the mists of the earth, its swamps and rivers, with a light heart he gives himeself into the hands of death, knowing that she alone can bring him peace.\n> = (p. 379)\n\n*All quotes are from the 1997 translation by Richard Pevear and Larissa Volokhonsky.*\n" }, { "alpha_fraction": 0.7504831552505493, "alphanum_fraction": 0.7564881443977356, "avg_line_length": 60.38983154296875, "blob_id": "d98f0a2bea1e5fbc6bcde7823e2062898d76820c", "content_id": "d9a098d319cc9fd2168607942ee2f98d2ef0e189", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14684, "license_type": "no_license", "max_line_length": 603, "num_lines": 236, "path": "/_documents/hesiod.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Hesiod\ndescription: >\n Notes on Hesiod’s “Theogony” and “Works and Days”\ntype: note\n---\n\nHesiod was a famous Greek poet—the ancients often mention him in the same sentence with Homer—who wrote the epic hexameter poems *Theogony* and *Works and Days*. He is thought to have lived sometime between 800 and 600 BCE.\n\n## The Evolution of Myths\n\nUnlike most of the ancient Greeks, I don’t believe that Zeus, Athena, or their other gods existed. But why did the Greeks believe? And where did their myths come from, if they are not true?\n\nSome of Hesiod’s myths are similar to Babylonian and Hittite myths. This continuity is not surprising because new religious ideas usually evolve from older religious ideas. But how did this evolution occur? And where did the earlier myths come from? We don’t have enough evidence to answer either question with certainty, but Hesiod’s poetry provides some small insight into each of them.\n\nHesiod’s *Theogony* organizes and synthesizes older Greek myths while also adding details. Thus, the big question about the evolution of religion can be considered at a smaller scale within Hesiod himself: How did he evolve the Greek Myths?\n\nHesiod appears to believe that the Muses—the nine daughters of Zeus and Memory—inspired his poetry, and perhaps this explains how he felt justified taking creative license with his source material, while also believing in his own stories:\n\n<blockquote class=\"poetry\">\n<p>And they taught Hesiod the art of singing verse,</p>\n<p>While he pastured his lambs on holy Helikon’s slopes.</p>\n<p>And this was the very first thing they told me,</p>\n<p>The Olympian Muses, daughters of Zeus Aegisholder:</p>\n<br>\n<p>“Hillbillies and bellies, poor excuses for shepherds:</p>\n<p>We know how to tell many believable lies,</p>\n<p>But also, when we want to, how to speak the plain truth.”</p>\n<br>\n<p>So spoke the daughters of great Zeus, mincing their words.</p>\n<p>And they gave me a staff, a branch of good sappy laurel,</p>\n<p>Plucking it off, spectacular. And they breathed into me</p>\n<p>A voice divine, so I might celebrate past and future.</p>\n<p>And they told me to hymn the generations of the eternal gods,</p>\n<p>But always to sing of themselves, the Muses, first and last …</p>\n<br>\n<p>Farewell Zeus’s daughters, and bestow song that beguiles.</p>\n<p>Make known the eerie brood of the eternal Immortals</p>\n<p>Who were born of Earth and starry Sky,</p>\n<p>And of dusky Night, and whom the salt Sea bore.</p>\n<p>Tell how first the gods and earth came into being</p>\n<p>And the rivers and the sea, endless and surging,</p>\n<p>And the stars shining and the wide sky above;</p>\n<p>How they divided wealth and allotted honors,</p>\n<p>And first possessed deep-ridged Olympus.</p>\n<br>\n<p>Tell me these things, Olympian Muses,</p>\n<p>From the beginning, and tell which of them came first.</p>\n<cite>— Theogony, 23–35, 103–125</cite>\n</blockquote>\n\nHesiod does not presume that the Muses tell him the truth, but he does presume that they might have told him the truth. In other words, creative stories come from the Muses and may reveal divine truths.\n\nWe get another glimpse into Hesiod’s views of the Muses and truth in *Works and Days*, when he is giving advice to his brother. Hesiod distinguishes between his experience and what the Muses have taught him:\n\n<blockquote class=\"poetry\">\n<p>So if you [my lazy brother] ever turn your addled wits to trade</p>\n<p>To rid yourself of debt and gnawing hunger,</p>\n<p>I can teach you the rhythms of the churning sea,</p>\n<p>Though sailing’s not my line. As far as ships go,</p>\n<p>I’ve never sailed in one on the open sea</p>\n<p>Except to Euboia once from Aulis, …</p>\n<p>That’s the sum of my experience with pegged & dowelled ships.</p>\n<p>Still, I can teach you the mind of Zeus the Storm King,</p>\n<p>Since the Muses have taught me ineffable song.</p>\n<p>Fifty days after the solstice, toward the end</p>\n<p>Of summer, the seasons of scorching heat,</p>\n<p>Comes the sailing seasons. You won’t wreck</p>\n<p>Your ship then, nor the sea drown your men,</p>\n<p>Unless Poseidon Earthshaker has a mind otherwise,</p>\n<p>Or the Lord of Immortals <em>wants</em> to destroy them.</p>\n<cite>— Works and Days, 717–739</cite>\n</blockquote>\n\nIt is difficult for me to understand how someone could create a story while also believing that it is true; it is even more surprising that someone could make up advice on a technical subject and believe it. But it appears this is what Hesiod is doing! It would seem that Hesiod believes that the Muses are inserting ideas into his mind, and thus may contain truth. When pressed, I imagine Hesiod arguing “surely my ideas come from somewhere! Where else, besides the immortal gods, could they come from?”\n\nPerhaps the myths evolved when story-tellers, believing they were inspired, re-told and inserted new details into older religions? In this theory, each re-telling would have to be mostly faithful, since large changes in the foundational myths would have rejected by the listeners.\n\nAs with biological evolution, one wonders how the big jumps were made. How would Zeus replace Ouranos at the head of the Pantheon? One may conjecture, but perhaps the battles of the generations of the gods represent the battles of peoples and cultures in the ancient world?\n\nHesiod’s poetry may also provide some insight into the origination of Myths. Hesiod’s creativity is not arbitrary. Hesiod deduces the existence of a second god, Strife, from the multiple uses of the word “strife”:\n\n<blockquote class=\"poetry\">\n<p>It looks like there’s not just one kind of Strife—</p>\n<p>That’s Eris—after all, but two on the Earth.</p>\n<p>You’d praise one of them once you got to know her,</p>\n<p>But the other’s plain blameworthy. They’ve just got</p>\n<p>Completely opposite temperaments.</p>\n<p>One of them favors war and fighting. She’s a mean cuss</p>\n<p>And nobody likes her, but everybody honors her,</p>\n<p>This ornery Eris. They have to: it’s the gods’ will.</p>\n<br>\n<p>The other was born first though. Ebony Night</p>\n<p>Bore her, and Cronos’s son who sits high in thin air</p>\n<p>Set her in Earth’s roots, and she’s a lot better for humans.</p>\n<p>Even shiftless folks she gets stirred up to work.</p>\n<br>\n<p>When a person’s lazing about and sees his neighbor</p>\n<p>Getting rich, because he hurries to plow and plant</p>\n<p>And put his homestead in order, he tends to compete</p>\n<p>With that neighbor in a race to get rich.</p>\n<br>\n<p>Strife like this does people good.</p>\n<cite>— Works and Days, 21–37</cite>\n</blockquote>\n\nLater in *Works and Days*, towards the end of a list of suggestions for avoiding the god’s anger, Hesiod remarks that “Talk” must be a god too, because it never dies:\n\n<blockquote class=\"poetry\">\n<p>That’s the way to behave. And try to avoid being</p>\n<p>The object of talk. A bad reputation is easy to get,</p>\n<p>Difficult to endure, and hard to get rid of.</p>\n<p>Talk never really dies, not when so many folks</p>\n<p>Are busy with her. Talk too is some kind of a god.</p>\n<cite>— Works and Days, 840–844</cite>\n</blockquote>\n\nIn these two examples, Hesiod deduces the existence of Strife and Talk using etymology and metaphysical reasoning (anything that doesn’t die must be a lie). Perhaps the Greek myths, as well as the earlier myths that inspired them, were based on observations of reality. These rational underpinnings would prop up the beliefs, since adherents could see them in the world around them.\n\nImagine a young Greek girl. All of the adults in her life tell her that Zeus and the gods rule the world and he wields thunderbolts and causes snow storms. Occasionally, at special times of the year, you participate in solemn sacrifices to Zeus, and other gods, involving the bloody ritual slaying of animals. Poets occasionally come through your town, and tell stories of the gods—some you have heard, others are new, but they all include Zeus. If you asked this girl how they knew Zeus was real, she would probably say she knew Zeus was real because she could see the thunderbolts and snow storms!\n\nWe are not certain whether Hesiod (or Homer) existed, but this irrelevant to this discussions—what matters is that the Greek tradition included, and to some degree accepted, the idea of Muses providing divine inspiration via creative human story-telling. This is one mechanism by-which the details of religions beliefs could evolve and develop, despite not being true.\n\nHerodotus’ appears to view Hesiod similarly:\n\n<blockquote>\n<p>But the origin of each of the gods, or whether they always existed, and what they look like: all of this was unknown until just recently—only yesterday, so to speak. For I believe that Hesiod and Homer were contemporaries who lived no more than 400 years before my time. These were the poets who composed for the Hellenes the theogony, assigned to the gods their epithets, defined their particular honors and skills, and described what they look like.</p>\n<cite>— The Histories, 2.53</cite>\n</blockquote>\n\n## Genealogies and Creation\n\nHesiod uses genealogy as an organizational and explanatory scheme for the gods.\n\n<blockquote class=\"poetry\">\n<p>Tell how first the gods and earth came into being</p>\n<p>And the rivers and the sea, endless and surging,</p>\n<p>And the starts shining and the wide sky above;</p>\n<p>How they divided wealth and allotted honors,</p>\n<p>And first possessed deep-ridged Olympus …</p>\n<p>In the beginning there was only Chaos, the Abyss,</p>\n<p>But then Gaia, the Earth, came into being,</p>\n<p>Her broad bosom the ever-firm foundation of all,</p>\n<p>And Tartaros, dim in the underground depths,</p>\n<p>And Eros, loveliest of all the Immortals, who</p>\n<p>Makes their bodies (and men’s bodies) go limp,</p>\n<p>Mastering their minds and subduing their wills.</p>\n<p>From the Abyss were born Erebos and dark Night.</p>\n<p>And Night, pregnant after sweet intercourse</p>\n<p>With Erebos, gave birth to Aether and Day.</p>\n<p>Earth’s first child was Ouranos, starry Heaven,</p>\n<p>Just her size, a perfect fit on all sides.</p>\n<cite>— Theogony, 104–127</cite>\n</blockquote>\n\nAn apparently similar use of genealogies is found in Genesis, and especially the “Table of Nations” in Genesis 10:\n\n<blockquote>\n<p>These are the families of Noah’s sons, according to their genealogies, in their nations; and from these the nations spread abroad on the earth after the flood.</p>\n<cite>— Genesis 10.32, NRSV</cite>\n</blockquote>\n\nAfter the first few generations, Hesiod depicts creation as a sexual act, similar to the *Enuma Elish.* Other traditions conceptualize creation through speech. For example, Genesis 1.3 states “Then God said, ‘Let there be light’ and there was light.” Still others conceptualize creation through material acts. For example, Genesis 2.7 states “then the Lord God formed man from the dust of the ground, and breathed into his nostrils the breath of life.”\n\nSex, speech, and craftsmanship are all creative acts in human life, so it is natural that humans would project them backward to the creation of the world (and the gods).\n\nHesiod presents three types of gods:\n\n1. Personified gods that were worshiped (e.g., Zeus and Athena)\n2. Personified gods that were not worshiped (e.g., Atlas)\n3. Gods which represent abstractions (e.g., Dawn, Strife, and Talk)\n\nIt seemed natural to the Greeks to represent abstract concepts as gods, since they are invisible and immortal.\n\n## Misogyny\n\nHesiod was misogynistic:\n\n<blockquote class=\"poetry\">\n<p>From her [Pandora] is the race of female women,</p>\n<p>The deadly race and population of women,</p>\n<p>A great infestation among mortal men,</p>\n<p>At home with Wealth but not with Poverty.</p>\n<p>It’s the same as with bees in their overhung hives</p>\n<p>Feeding the drones, evil conspirators.</p>\n<p>The bees work every day until the sun goes down,</p>\n<p>Busy all day long making pale honeycombs,</p>\n<p>While the drones stay inside, in the hollow hives,</p>\n<p>Stuffing their stomachs with the work of others.</p>\n<cite>— Theogony, 594–603</cite>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>A man couldn’t steal anything better than a good wife,</p>\n<p>Just as nothing is more horrible than a bad one,</p>\n<p>Some freeloader who roasts her man without a fire</p>\n<p>And serves him up to a raw old age.</p>\n<cite>— Works and Days, 777–780</cite>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>Don’t wash in a woman’s bath-water</p>\n<p>Which for a time has a bitter vengeance in it.</p>\n<cite>— Works and Days, 833–834</cite>\n</blockquote>\n\n## Other Connections\n\nThe Babylonians and Sumerians thought men were created to feed the gods with sacrifices of wheat, animals, and beer. The Greeks also sacrificed to the gods, but they did not seem to believe they were created for this purpose:\n\n<blockquote class=\"poetry\">\n<p>Before [Pandora opened the box] the human race</p>\n<p>Had lived off the land without any trouble, no hard work,</p>\n<p>No sickness or pain that the Fates give to men.</p>\n<cite>— Works and Days, 110–112</cite>\n</blockquote>\n\nBoth Marduk and Zeus were young sky gods who lead a fight over an older generation of gods to become the leading god. Zeus’s division of duties and realms upon defeating Cronos is similar to Marduk’s division after defeating Tiamhat in the *Enuma Elish*, and the Sumerian concept of *me* is also similar (and even older).\n\n<blockquote class=\"poetry\">\n<p>So the blessed gods had done a hard piece of work,</p>\n<p>Settled by force the question of rights with the Titans.</p>\n<p>Then at Gaia’s suggestion they pressed broad-browed Zeus,</p>\n<p>The Olympian, to be their king and rule the Immortals.</p>\n<p>And so Zeus dealt out their privileges and rights.</p>\n<cite>— Theogony, 886–890</cite>\n</blockquote>\n\nHesiod was pessimistic and believes men have gotten weaker over time.\n\nGreek religious beliefs varied geographically and temporally—there was no canonical set of myths. Homer and Hesiod disagreed with each other sometimes. For example, in Hesiod Aphrodite is born from Ouranos’s castrated members floating in the foam off the coast of Cyprus. In Homer, Aphrodite is the daughter of Zeus and Dione.\n\nHesiod spends a long time discussing the relatively unimportant goddess Hekate; perhaps Hesiod was involved with a Hekate cult that was popular in his region?\n\n*Quotations are from the Stanley Lombardo translation, as are the line numbers which are different from the line numbers in the Greek.*\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6286231875419617, "avg_line_length": 35, "blob_id": "842219858e9fd97826b7fe62ad1b4dd53894b74e", "content_id": "119e229565b7eda98b89c6603ae80d9a08cda2ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1656, "license_type": "no_license", "max_line_length": 144, "num_lines": 46, "path": "/index.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\nlayout: basic\ntitle: Arts & Metaphysics\ndescription: Essays, commentaries, and meditations about literature, history, religion, and philosophy.\n---\n{{ page.description }}\n\n<h2 id=\"essays\">Essays</h2>\n<ul class=\"index\">\n {% include li.html id='definitions' %}\n {% include li.html id='justification-via-others-beliefs' %}\n {% include li.html id='beauty-and-truth' %}\n {% include li.html id='my-epistemology' %}\n {% include li.html id='universal-historical-laws' %}\n {% include li.html id='meaning-and-purpose' %}\n {% include li.html id='a-definition-of-faith' %}\n {% include li.html id='faith-and-reason' %}\n {% include li.html id='faith-and-righteousness' %}\n {% include li.html id='fear-of-death' %}\n {% include li.html id='ethical-progress' %}\n {% include li.html id='justice' %}\n {% include li.html id='love-thy-neighbor-as-thyself' %}\n</ul>\n\n<h2 id=\"notes\">Notes and Commentary</h2>\n<ul class=\"index\">\n {% include li.html id='ancient-greece' %}\n {% include li.html id='the-epic-of-gilgamesh' %}\n {% include li.html id='hesiod' %}\n {% include li.html id='the-iliad' %}\n {% include li.html id='the-odyssey' %}\n {% include li.html id='homeric-hymns' %}\n {% include li.html id='the-histories-herodotus' %}\n {% include li.html id='metamorphoses' %}\n {% include li.html id='seneca' %}\n</ul>\n\n<h2 id=\"meditations\">Meditations</h2>\n<ul class=\"index\">\n {%- for p in site.posts -%}\n <li>\n <a title=\"{{ p.description | xml_escape | normalize_whitespace }}\"\n href=\"{{ p.url }}\">{{ p.title | replace_first: \"_\", \"<em>\" | replace: \" _\", \" <em>\" | replace: \"_\", \"</em>\" | normalize_whitespace }}</a>\n </li>\n {%- endfor -%}\n</ul>\n" }, { "alpha_fraction": 0.4498141407966614, "alphanum_fraction": 0.5947955250740051, "avg_line_length": 15.8125, "blob_id": "97a90765255746b5f1c5ebaa00330799b81115ca", "content_id": "547ca97670467dc62e899cf28cdd3cccf6bede7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 269, "license_type": "no_license", "max_line_length": 42, "num_lines": 16, "path": "/documents/ancient-china.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ancient China\ndescription: >\n Notes on Ancient China\ntype: note\n---\n\n## Dynasties\n\n- Shang (c. 1600 - c. 1046 BCE)\n- Zhou (c. 1046 - c. 256 BCE)\n- Qin (221 - 206 BCE)\n- Han (202 BCE - 220 CE)\n- Three Kingdoms; Wei, Shu, Wu (220 - 280)\n- Jin (265 - 420)\n" }, { "alpha_fraction": 0.7040673494338989, "alphanum_fraction": 0.7208976149559021, "avg_line_length": 25.407407760620117, "blob_id": "1da2b1c4be5d5148fd8c5a77526a068929b9ea9d", "content_id": "4ea36c3bb354f863d21fb305adbb58b5ef2196bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 713, "license_type": "no_license", "max_line_length": 130, "num_lines": 27, "path": "/documents/david-hockney.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n David Hockney\ndescription: >\n Notes David Hockney\ntype: note\n---\n\n## Life\n\nBorn in Bradford England in summer 1937. He is a figurative painter. He moved to Los Angeles in 1964.\n\n## Quotes From 2014 Documentary\n\n> We grow small trying to become great.\n\n> New ways of seeing mean new ways of feeling.\n\n> I do believe painting can change the world.\n\n> I think the absence of love is fear. If one can understand love, one can, to a certain extent, be fearless.\n\n> The urge to represent is very deep within us.\n\n> When you stop doing something, it doesn't mean you are rejecting it. You're saying, I wish to take a look round another corner.\n\n> Friends ... that's really the only thread running through my life.\n" }, { "alpha_fraction": 0.7661784887313843, "alphanum_fraction": 0.7685567736625671, "avg_line_length": 176.53334045410156, "blob_id": "ec7e24d1d593d75d7e965fccd4e9e13d115fc36e", "content_id": "d97039a8bd61da3c5709f6b32922d0f987c6dce2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8049, "license_type": "no_license", "max_line_length": 1699, "num_lines": 45, "path": "/_documents/the-republic.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Plato’s “Republic”\ndescription: >\n Notes on Plato’s “Republic”\ntype: note\nstatus: incomplete\n---\n\n## Background\n\nPlato’s *Republic* was believed to be written around 375 BCE.\n\n## Quotes\n\n<blockquote>\n<p>I replied: There is nothing which for my part I like better, Cephalus, than conversing with aged men; for I regard them as travellers who have gone a journey which I too may have to go, and of whom I ought to enquire, whether the way is smooth and easy, or rugged and difficult. And this is a question which I should like to ask of you who have arrived at that time which the poets call the ‘threshold of old age’—Is life harder towards the end, or what report do you give of it?</p>\n<p>I will tell you, Socrates, he said, what my own feeling is. Men of my age flock together; we are birds of a feather, as the old proverb says; and at our meetings the tale of my acquaintance commonly is—I cannot eat, I cannot drink; the pleasures of youth and love are fled away: there was a good time once, but now that is gone, and life is no longer life. Some complain of the slights which are put upon them by relations, and they will tell you sadly of how many evils their old age is the cause. But to me, Socrates, these complainers seem to blame that which is not really in fault. For if old age were the cause, I too being old, and every other old man, would have felt as they do. But this is not my own experience, nor that of others whom I have known. How well I remember the aged poet Sophocles, when in answer to the question, How does love suit with age, Sophocles,—are you still the man you were? Peace, he replied; most gladly have I escaped the thing of which you speak; I feel as if I had escaped from a mad and furious master. His words have often occurred to my mind since, and they seem as good to me now as at the time when he uttered them. For certainly old age has a great sense of calm and freedom; when the passions relax their hold, then, as Sophocles says, we are freed from the grasp not of one mad master only, but of many. The truth is, Socrates, that these regrets, and also the complaints about relations, are to be attributed to the same cause, which is not old age, but men’s characters and tempers; for he who is of a calm and happy nature will hardly feel the pressure of age, but to him who is of an opposite disposition youth and age are equally a burden.</p>\n<p>I listened in admiration, and wanting to draw him out, that he might go on—Yes, Cephalus, I said: but I rather suspect that people in general are not convinced by you when you speak thus; they think that old age sits lightly upon you, not because of your happy disposition, but because you are rich, and wealth is well known to be a great comforter.</p>\n<p>You are right, he replied; they are not convinced: and there is something in what they say; not, however, so much as they imagine. I might answer them as Themistocles answered the Seriphian who was abusing him and saying that he was famous, not for his own merits but because he was an Athenian: ‘If you had been a native of my country or I of yours, neither of us would have been famous.’ And to those who are not rich and are impatient of old age, the same reply may be made; for to the good poor man old age cannot be a light burden, nor can a bad rich man ever have peace with himself.</p>\n<p>May I ask, Cephalus, whether your fortune was for the most part inherited or acquired by you?</p>\n<p>Acquired! Socrates; do you want to know how much I acquired? In the art of making money I have been midway between my father and grandfather: for my grandfather, whose name I bear, doubled and trebled the value of his patrimony, that which he inherited being much what I possess now; but my father Lysanias reduced the property below what it is at present: and I shall be satisfied if I leave to these my sons not less but a little more than I received.</p>\n<p>That was why I asked you the question, I replied, because I see that you are indifferent about money, which is a characteristic rather of those who have inherited their fortunes than of those who have acquired them; the makers of fortunes have a second love of money as a creation of their own, resembling the affection of authors for their own poems, or of parents for their children, besides that natural love of it for the sake of use and profit which is common to them and all men. And hence they are very bad company, for they can talk about nothing but the praises of wealth.</p>\n<p>That is true, he said.</p>\n<p>Yes, that is very true, but may I ask another question?—What do you consider to be the greatest blessing which you have reaped from your wealth?</p>\n<p>One, he said, of which I could not expect easily to convince others. For let me tell you, Socrates, that when a man thinks himself to be near death, fears and cares enter into his mind which he never had before; the tales of a world below and the punishment which is exacted there of deeds done here were once a laughing matter to him, but now he is tormented with the thought that they may be true: either from the weakness of age, or because he is now drawing nearer to that other place, he has a clearer view of these things; suspicions and alarms crowd thickly upon him, and he begins to reflect and consider what wrongs he has done to others. And when he finds that the sum of his transgressions is great he will many a time like a child start up in his sleep for fear, and he is filled with dark forebodings. But to him who is conscious of no sin, sweet hope, as Pindar charmingly says, is the kind nurse of his age:</p>\n<p>‘Hope,’ he says, ‘cherishes the soul of him who lives in justice and holiness, and is the nurse of his age and the companion of his journey;—hope which is mightiest to sway the restless soul of man.’</p>\n<p>How admirable are his words! And the great blessing of riches, I do not say to every man, but to a good man, is, that he has had no occasion to deceive or to defraud others, either intentionally or unintentionally; and when he departs to the world below he is not in any apprehension about offerings due to the gods or debts which he owes to men. Now to this peace of mind the possession of wealth greatly contributes; and therefore I say, that, setting one thing against another, of the many advantages which wealth has to give, to a man of sense this is in my opinion the greatest.</p>\n<p>(328e–331b)</p>\n</blockquote>\n\n<blockquote>\n<p>Let me ask you now:—How would you arrange goods—are there not some which we welcome for their own sakes, and independently of their consequences, as, for example, harmless pleasures and enjoyments, which delight us at the time, although nothing follows from them?</p>\n<p>I agree in thinking that there is such a class, I replied.</p>\n<p>Is there not also a second class of goods, such as knowledge, sight, health, which are desirable not only in themselves, but also for their results?</p>\n<p>Certainly, I said.</p>\n<p>And would you not recognize a third class, such as gymnastic, and the care of the sick, and the physician’s art; also the various ways of money-making—these do us good but we regard them as disagreeable; and no one would choose them for their own sakes, but only for the sake of some reward or result which flows from them?</p>\n<p>There is, I said, this third class also. But why do you ask?</p>\n<p>Because I want to know in which of the three classes you would place justice?</p>\n<p>In the highest class, I replied,—among those goods which he who would be happy desires both for their own sake and for the sake of their results.</p>\n<p>Then the many are of another mind; they think that justice is to be reckoned in the troublesome class, among goods which are to be pursued for the sake of rewards and of reputation, but in themselves are disagreeable and rather to be avoided.</p>\n<p>(357b–358a)</p>\n</blockquote>\n\n*All quotations are taken from Benjamin Jowett’s 1888 translation of the* Republic.\n" }, { "alpha_fraction": 0.7839963436126709, "alphanum_fraction": 0.7844501733779907, "avg_line_length": 156.40475463867188, "blob_id": "0d4fe5bec7b068d396a52c3ba98121337f76b6e2", "content_id": "c50e4c8670a0513f99907425e9a109f1d848370e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6611, "license_type": "no_license", "max_line_length": 1392, "num_lines": 42, "path": "/documents/altera-free-will.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Altera: Free Will\ndescription: >\n Do Nooks have free will? What does free will mean?\ntype: essay\nstatus: incomplete\n---\n\n## Free Will\n\nNookian minds are deterministic, but the Nooks wouldn't know this. They couldn't perfectly predict how their own mind, let alont other Nook's minds, would react to a situation. Furthermore, there is no experiment they could devise to this, since they, like us, would be unable to establish the same \"situation\" twice. By \"situation,\" we mean the complete state relevant to a Nook making a \"choice.\" In other words, the Nook's mind would have to have identical state, and the sensory input that they are deciding on would need to be the same. Establishing identical sensory input would not be too difficult, but it would be impossible for them to establish that a Nook's mind's state has the same state twice in a row. The state of a Nook's mind is complex and would likely have a long history. The Nook being experimented on would remember earlier renditions of the experiment. A Nook's child's mind would be very similar to the parent, but not exactly the same due to the mutation---thus experimenting on a parent-child pair would also be unfeasible.\n\nThus, the Nooks are in a similar situation to ourselves with regards to free will and determinism. They may suspect that their world is perfectly deterministic, but they would be unable to prove it. As a result, they may wonder, like we do, whether they have \"free will.\"\n\nWhat do we mean by \"free will?\" A standard definition is: the ability to choose between different possible courses of action. This definition begs the question---what does it mean for a being to choose? At each time-step, the Nook mind is presented with sensory input and outputs an \"action\" that determines what the Nook will do (nothing, move, eat, or reproduce). If this process is what we mean by choosing, then the Nooks have free will despite being deterministic.\n\nSome would say that, for the Nooks to truly make a \"choice\"---and, by extension, to have \"free will\"---a different outcome must be possible, given the same situation.\n\nIn the case of Altera, one way to accomplish this would be to add randomness into the algorithm that \"runs\" a Nook's decision making process.\n\nThe simplest way we could do this is to alter our program so that each Nook's mind's state has a slight random perturbation applied to its state just before it makes a choice. This introduces another issue, how we will arrive at this \"randomness\"? Computers in our world are deterministic. The only way to introduce true randomness into a computer is using randomness from outside the computer (e.g. from mouse movements, or network traffic delays). By introducing true randomness from our universe into the computer so that we can truly randomly perturb the Nook's mind, we are coupling our universes state to the Nooks state. If our own universe is deterministic, it is entirely possible that the Nook's choices are still deterministic (in the sense that no other outcome was possible). Of course, the Nook's can't tell the difference in either case.\n\nLets assume that our universe is not deterministic, and that we can randomly perturb the Nook's mind's state before they make choices. Now, alternate outcomes would be possible, given the same situation. Do the Nooks now have free will? One may object for a few different reasons, which we will consider in turn.\n\nOne may object because this randomness is added to the Nook's mind from the \"outside.\" Imagine that we are running each Nook's mind on a separate computer, and that each computer has its own randomness which it injects into each mind. Clearly where there randomness comes from is not relevant.\n\nAnother objection is that we are adding randomness that is outside of the \"control\" of the Nook, so it is not possible that this randomness could give the Nook free will. Well, what do we mean by \"control\"? Do we mean that the Nook has the \"will\" to make it act one way or another? Clearly this is begging the question, for we are debating what free will means in the first place. \"No, but really, I don't know how the mechanism would work, but surely there is some way that the Nook could have control over the outcome while not being deterministic!\" When considered in our universe, with its huge complexity and its unknowns, some of us may find this argument convincing. However, when considered in the context of Altera it is clearly silly. There is no mechanism within Altera that would circumvent this problem. To this one may argue that Altera is too simple a world to have free will! In fact, one may argue that, for the same reason, our assumption that consciousness could develop in Altera is also not possible. I will call this the mystical metaphysical argument, because it is arguing that free will is beyond our ability to understand. It is impossible to argue against the mystic---because they can always throw up their hands and say \"it just is---it's impossible for us to understand, its beyond reason, its outside space and time, but it just is. I believe it.\" \n\nWe can not argue against the mystic, but it is worth noting that, from the outside, a being that has free will via this mystical metaphysical substance would be externally indistinguishable from a being that has the random perturbations. In both cases, we would be unable to predict their choices.\n\nThus, if your mother has free-will, but your father does not, you would not be able to tell the difference.\n\nIn conclusion, either:\n\n1. our actions are deterministic\n2. our actions are not deterministic, because randomness is injected from an internal or external source\n3. our actions are not deterministic, because of some mystical metaphysical \"stuff\" that we can not understand, however, this situation would be impossible to distinguish from the previous possibility.\n\nThe meaning of free-will in any case feels different from what we intuitively feel it should mean, but ultimately we must recognize that our intuition is wrong. Nooks (and ourselves) do make choices, so in this sense they have free will. These choices are deterministic, but they are so complicated that no Nook can predict them.\n\nThere is no reason why this result can not be extended to our universe. We also make choices in that no one (not even ourselves) can predict what we will do. If our world is deterministic, than clearly our choices are also deterministic. If our world is not deterministic, then but our choices are not, yet this does not make it likely that we have free will.\n" }, { "alpha_fraction": 0.7868252396583557, "alphanum_fraction": 0.7889600396156311, "avg_line_length": 83.05128479003906, "blob_id": "09271183e28c90c0c9d2fbe5c544451bab7f03d3", "content_id": "ca6bb7b0b9147b4577f7efbe112b00aa2797a140", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3299, "license_type": "no_license", "max_line_length": 536, "num_lines": 39, "path": "/_documents/a-definition-of-faith.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n A Definition of Faith\ndescription: >\n Faith in beliefs is indicated by how drastically our actions change as a result of our belief.\ntype: essay\nstatus: incomplete\n---\n\nWe all have a worldview—a collection of beliefs that direct our actions. Our worldview may be ill-defined, poorly considered, or even inconsistent. Still, if we have ever reasoned about how to act, we have a worldview.\n\nConceptually we can divide our beliefs into two groups:\n\n1. Irreducible, unprovable axioms\n2. Beliefs deduced from these axioms\n\nAlthough enumerating our beliefs, let alone categorizing them so cleanly, would be difficult in practice.\n\nI define “faith” as our willingness to act *and possibly think* consistently with our axioms, despite them being uncertain and unprovable.\n\nMost humans believe that the laws of nature will continue acting as they have in the past, although we can not prove this belief. Many of us adopt this belief unconsciously. I call this implicit faith—faith which is seen only in a person’s actions, but not in their thoughts.\n\nBeliefs require different amounts of faith, proportional to how drastically they require the believer to alter their actions from their current beliefs.\n\nFor most of us, believing in the consistency of nature requires very little faith relative to believing that they may change—we would not drastically alter our thoughts or actions, since, although we admit they may change, we have no way of knowing how or when they would change, if ever. On the other hand, believing that the laws of physics will change drastically tomorrow would require a lot of faith. The believer would likely not go to work; they would gather their loved ones for what they believe could be their final moments.\n\nIf we believe we may go to hell if we have sex outside of marriage, then we have a degree of faith depending on how much we want to have sex outside of marriage. If this isn’t a temptation for us, then perhaps it requires very little faith, since our faith is never tested.\n\nIf we believe we should donate 10% of our money to the church, then we have a significant degree of faith, since this is quite a sacrifice for most people who are not very wealthy.\n\nIf we believe we should fly a plane into a building, then we have an extreme level of faith—without this much faith we are very unlikely to act in this way.\n\nBy this definition, believers that don’t act consistently with their religion have very little faith.\n\nThere are multiple sets of beliefs that could result in the same action. Thus our definition is not purely behavioural—the mental act of thinking plays its part, but it is also not entirely mental.\n\nIs thought a willed act? We will to spend to time thinking about things, but we can not control our thoughts either. If a beautiful woman walks past a man, the man can not usually avoid noticing (a thought) that the women is beautiful. Likewise, we can not will ourselves into believing things we think are obviously false. In the extreme case, we can not will ourselves to believe 2 + 2 = 5. There is a gradation of certainty that we move down, and eventually we can will ourselves to think one way or another.\n\nThus only some beliefs can be willed, depending on how likely a person finds a belief.\n\n" }, { "alpha_fraction": 0.774117648601532, "alphanum_fraction": 0.774117648601532, "avg_line_length": 37.6363639831543, "blob_id": "fdd65e6b71ffe9eccacaf0ad7c88a00119b20ca4", "content_id": "57da057d046aa79c12b236fa7eae6465d6be638e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 429, "license_type": "no_license", "max_line_length": 146, "num_lines": 11, "path": "/_documents/faith-and-righteousness.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Faith and Righteousness\ndescription: >\n Are the faithless more righteous than the faithful?\ntype: essay\nstatus: incomplete\n---\nTwo people do the same good deed—the first believes they will be rewarded, while the second is unsure. Which deed is more righteous?\n\nTwo people live equally charitable lives—the first is a Christian with a strong faith, the second is an agnostic. Which person is more righteous?\n" }, { "alpha_fraction": 0.6711618304252625, "alphanum_fraction": 0.7085062265396118, "avg_line_length": 25.054054260253906, "blob_id": "db9e012cf2cb9a0665aa0b973fb35a80cba67e88", "content_id": "28d2e6456a0ea0746c109b77c5dbc72db39837cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 964, "license_type": "no_license", "max_line_length": 84, "num_lines": 37, "path": "/documents/ancient-rome.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ancient Rome\ndescription: >\n Notes on Ancient Rome\ntype: note\n---\n\nQuick highlights:\n\n- Rome existed from roughly 500 BCE to 500 CE\n- Was a Republic for first 500, and an empire for the second 500\n- Grew for 500 years, peaked for 200 years, declined for 300 years\n\nDetailed notes:\n\n- Pre-historical\n- Kingdom\n - Legendary Romulus founded Rome in 753 BCE.\n - The Roman kings were overthrown c. 509 BCE.\n- Republic\n - Institutions\n - Consuls\n - Two elected positions lasting for a year\n - Each consul could veto the other\n - Became mostly a military position; was limited in Rome, but absolute outside\n - Consuls usually because governors of a province afterwards\n - Senate\n - Had 300 members, serving a life term\n - People\n - Gaius Julius Caesar\n- Empire\n\n - Began when Octavian defeated Mark Antony and Cleopatra\n - Constantine the Great\n - Made Christianity the official religion\n - Ruled from 306 to 337 CE\n" }, { "alpha_fraction": 0.8024652600288391, "alphanum_fraction": 0.8024652600288391, "avg_line_length": 120.69230651855469, "blob_id": "320725a09191978490688541607bee1868887463", "content_id": "8aec1f16048cdf31f0cccb79f9e44ddd97cf13d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3166, "license_type": "no_license", "max_line_length": 619, "num_lines": 26, "path": "/_documents/ethical-progress.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ethical Progress\ndescription: >\n Are we more ethical than the ancients?\ntype: essay\nstatus: incomplete\n---\n\nHas humanity made ethical progress? Are we more moral than the ancients?\n\nTo answer this question we must agree what progress is. We must know how one should act, so that we can compare our actions. If one believes ethics is relative, then progress is impossible. But if we agree that there is a standard, then we agree that progress is possible, even if we can not always identify it.\n\nIn this essay I will assume that we have a shared sense of right and wrong, a shared sense of how one should act, a shared ethical standard. However, outside of the concrete examples, most of the discussion will not hinge on agreeing as to what this standard is.\n\nIt is an important question because its answer should affect how we act moving forward: If we have, then we should find its cause and we should try to continue making progress. If we have not, we should try to identify why not, and should remove these barriers. Furthermore, comparisons can lead us to clarifications.\n\nEthics is situational—to judge the past we need to know and understand the situations that individuals and society faced. Behaviors which may seem unethical may, upon further understanding of the historical situations they occurred in, be ethical. For example polygamy may have been a way to protect widows from starvation. Measuring ethical progress will thus require historical context. Our understanding of the past is limited by the surviving evidence, so our ability to measure progress will be similarly limited.\n\nEthical progress can occur in both individuals and societies. This distinction is key. It seems unlikely that the average person is innately better than the average person used to be; our biology has not changed substantially. But the societies we develop in have changed, and our society affects the individual.\n\nEthical progress is easier to measure in societies than in individuals because individuals face fewer situations. Imagine a situation, which we can call S. There are two choices that an individual in situation S can make, R and W. Choice R is the right choice. Imagine that a person is faced with situation S ten times during their life. Now imagine a society filled with thousands of people, each facing situation S approximately ten times in their lives. The discrete nature of the choices make progress easier to measure, and less susceptible to random variations, when there are more situations being considered.\n\nIt is difficult to discern ethical progress from technological progress. Ethics is the study of how one should act in a given situation. Technological progress will alter the type and frequency of situations that individuals and societies face. For example, medical technology has given rise to many new situations. Free sources of energy have diminished the importance of physical strength, perhaps allowing women a more equal role to men.\n\nProgress may not be uniform. A society progress and treat their disadvantaged individuals better, while the average person is more selfish in their lives.\n" }, { "alpha_fraction": 0.7451063990592957, "alphanum_fraction": 0.7548936009407043, "avg_line_length": 68.11764526367188, "blob_id": "de52e4a552a89836f6ffeca9534bcf0d7022aed8", "content_id": "2c64948efc37475ee5c42c4de056db311634df4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2350, "license_type": "no_license", "max_line_length": 533, "num_lines": 34, "path": "/documents/fear-of-death.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Fear of Death\ndescription: >\n Why are we afraid of death?\ntype: essay\nstatus: incomplete\n---\n\nMany people are afraid of death. Many of us like the idea of living forever, but why?\n\nIf it is simply because we enjoy our life now, or could imagine enjoying it if all our trials were gone, then consider this: perhaps we would get bored of living even the best life? It seems unlikely that it would happen in 100 years, or even in 1000 years, but perhaps, after 10,000 years we would be bored. Maybe we would actually want to die.\n\n> If we are suffering illness, poverty, or misfortune, we think we shall be satisfied on the day it ceases. But there too, we know it is false; so soon as one has got used to not suffering one wants something else.\n> - Simone Weil, Three Essays on the Love of God\n\nOr do we fear death because we fear judgement?\n\n> Say \"If the last home with God is to be for you alone and no one else, then you should long for death, if your claim is true.\" But they will never long for death, because of what they have stored up with their own hands: God is fully aware of the evildoers. [Prophet], you are sure to find them clinging to life more eagerly than any other people, even the polytheists. Any of them would wish to be given a life of a thousand years, though even such a long life would not save them from the torment: God sees everything they do.\n> - Qu'ran 2:94--96, Trans. by M.A.S. Abdel Haleem\n\nOr do we fear death because we are not intended to die?\n\n> For the creation was subjected to futility, not willingly, but because of him who subjected it, in hope that the creation itself will be set free from its bondage to corruption and obtain the freedom of the glory of the children of God. For we know that the whole creation has been groaning together in the pains of childbirth until now. And not only the creation, but we ourselves, who have the first fruits of the Spirit, groan inwardly as we wait eagerly for adoption as sons, the redemption of our bodies.\n> - Romans 8:20--23, English Standard Version\n\nDoes the fear of death keep us trudging along?\n\n> To sleep; perchance to dream. Ay, there's the rub,\n> For in that sleep of death what dreams may come,\n> When we have shuffled off this mortal coil,\n> Must give us pause---there's the respect\n> That makes calamity of so long life.\n> ~ Hamlet III.1\n" }, { "alpha_fraction": 0.7979305982589722, "alphanum_fraction": 0.7994522452354431, "avg_line_length": 120.70370483398438, "blob_id": "23a4c6e22bfe41beedbb797648ac944bff606176", "content_id": "d5b9ae8d77cb348461b0ae192162589dc3077023", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3302, "license_type": "no_license", "max_line_length": 545, "num_lines": 27, "path": "/_documents/altera-appearance-and-reality.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Altera: Appearance and Reality\ndescription: >\n I investigate how Nooks may perceive and sense their world.\ntype: essay\nstatus: incomplete\n---\n\nIs there any knowledge in Altera that is so certain that no reasonable Nook could deny it?\n\nLets begin with Nook’s sense of sight. They see the weights of the discrete objects surrounding them. Can they be certain of their sensory knowledge?\n\nIn our world, we describe the appearance of objects using vague language. We say an object is red, but what we mean is the object is red under usual lighting conditions. Apart from describing our personal sensory experiences, it is difficult to state much about the “color” of the physical object. Precisely describing the object’s color and appearance would require knowledge of our current scientific theory.\n\nWe sense particles in our universe slowly and in aggregate. This may be because our minds and sense organs are constructed out of particles too. Perhaps, to achieve the complex structure required for conscious sensing, our minds and senses must operate above the dimension of particles.\n\nThe Nook’s sense of sight is simpler than ours, and it is embedded in the Alteran physical laws. The complexity of Nook minds can increase without requiring them to increase in space or using more resources. For this reason, it is possible that highly evolved, concious Nooks would still be aware of their bare sensory input.\n\nIt is also possible that they would not be aware of their immediate sensory input. Perhaps, like is likely in our universe, it is not evolutionarily beneficial to be aware of small details like this, and their minds abstract and condense their sensory input for their minds to consider and react to.\n\nSince Nook’s physical size is fixed, I suspect that even highly evolved Nooks will continue to be aware of the discrete locations in Altera, but I can imagine their minds blending many individual sets of 9x9 weights sensed at each timestep, into larger views. This would be similar to how our eyes, visual cortex, abstract objects. Optical illusions occur when these abstractions occur at a low level in our sensory chain, causing us to perceive things that are not there.\n\nIf this sort of abstraction were to evolve inside a Nook’s mind, the\n\n- senses abstracting low-level inputs; we are unaware of the individual neural inputs; we are also unaware of individual quantum events. Not necessarily because we *couldn’t* be (our eyes may be able to detect single photons), but because our relatively vast size makes individual particles less interesting or relevant to our survival. We require a lot of food to keep the apparatus going, if we thought and operated on the level of individual particles, we would never aggregate enough food to sustain ourselves at the timescales we need to.\n- the fundamentally discrete nature of our universe, and Altera, both anchor the size of things (although differently bc Nooks prob stay at the bottom while we are just far enough up to support the correct level of complexity); imagine a universe where the laws of physics did not provide any size-anchoring (i.e. they are scale invariant); you could got infinitely smaller or infinitely larger. You could shrink humans to 1/10th of their current size.\n" }, { "alpha_fraction": 0.7778050303459167, "alphanum_fraction": 0.7796873450279236, "avg_line_length": 116.49038696289062, "blob_id": "9614c4d8ce7133fe29a455ec85df9abae735c09e", "content_id": "85d3cc0077585032641fdec75e396ad7c7dd3582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12367, "license_type": "no_license", "max_line_length": 850, "num_lines": 104, "path": "/_documents/faith-and-reason.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Faith and Reason\ndescription: >\n An exploration of the relationship between faith and reason.\ntype: essay\nstatus: incomplete\n---\n\n## Why Believe\n\nMost reasons to practice a religion can be reduced to “it is true” or “it makes me happier.”\n\nWhat does it mean for a religion to be true?\n\nMost religions make metaphysical claims, for example:\n\n- The pharaoh is a god\n- Trees have spirits\n- The universe was created\n- The laws of physics have never changed\n- Humans have souls\n- All “living” creatures have souls\n- The universe will end\n- Heaven exists\n- Heaven and purgatory exist\n- Your actions (or beliefs) determine your fate after you die\n- Humans can be reincarnated.\n\nI want to believe a religion that makes true metaphysical claims.\n\n{% comment %}\nWhat about religions that don’t make any claims.\n\nWhat about religions that make more claims than another. One religion claims “A,” while another claims “A” and “B.” Which religion should you believe?\n{% endcomment %}\n\nHow can we know whether a metaphysical claim is true? It depends on the claim. Some claims can be verified using the scientific method, however, the scientific method itself assumes a metaphysical claim—that the laws of physics have never changed. If the laws of physics do change, then we can not use our scientific knowledge to draw conclusions about the after or before the laws of physics changed.\n\nEven if we assume that the laws of physics have never changed, science still could not answer many metaphysical claims. Science can not verify or refute the metaphysical claim that, when humans die their soul becomes a ghost that can not interact with world of the living. Even if this metaphysical claim correctly describes reality, the scientific method could neither confirm or deny its validity.\n\nThere are other metaphysical claims that can be confirmed or denied using reason. If god is all-knowing, he must exist outside of time—if he did not, he would not know the future.\n\nMany religions make many metaphysical claims. If they do, these claims must be consistent with one another.\n\n## Faith and Reason in Christianity\n\nThe apostle Paul, in his letter to the Romans, writes:\n\n<blockquote>\n<p>For the wrath of God is revealed from heaven against all ungodliness and unrighteousness of men, who by their unrighteousness suppress the truth. For what can be known about God is plain to them, because God has shown it to them. For his invisible attributes, namely, his eternal power and divine nature, have been clearly perceived, ever since the creation of the world, in the things that have been made. So they are without excuse. For although they knew God, they did not honor him as God or give thanks to him, but they became futile in their thinking, and their foolish hearts were darkened. Claiming to be wise, they became fools, and exchanged the glory of the immortal God for images resembling mortal man and birds and animals and creeping things. (Romans 1:18–23)</p>\n</blockquote>\n\nThe universe is awesome and beautiful. For non-believers, surely the existence of the universe is the supreme mystery. Was it created, or did it always exist? Does it have any unity or purpose? If a being created it, why?\n\nI wish that the answers to these questions were apparent. But they are not to me, and I wonder how they could have been to the people of Paul’s time without revelation. If a god created the universe, then it is apparent from the creation that this god would be very powerful. But how can the non-believer be expected to know that a god exists and that it created the universe? I will expound on why I do not believe the existence of God is obvious in a later chapter.\n\nEven if we accept that a god exists—how can we be expected to know its will? If God is to justly condemn men as being “ungodly” and “unrighteousness” then these same men, devoid of revelation, must be able to deduce his will. Paul explains how they can later in the same letter:\n\n<blockquote>\n<p>For when Gentiles [people who are not Jewish], who do not have the law [God’s instructions for how humans should act, recorded in the sacred Jewish texts], by nature do what the law requires, they are a law to themselves, even though they do not have the law. They show that the work of the law is written on their hearts, while their conscience also bears witness, and their conflicting thoughts accuse or even excuse them on that day when, according to my gospel, God judges the secrets of men by Christ Jesus. (Romans 2:14–16)</p>\n</blockquote>\n\nThese two passages justify God’s judgement of non-believers who have not received God’s revelation. The presence of this justification, regardless of its cogency, implies that it would be unjust if God’s existence and will could not be deduced from the universe. This conclusion is echoed in Paul’s careful distinction between what “can be known” and what must be revealed. He does not want to imply that non-believers could know many of the truths that he, with his revelations, may know.\n\nOther passages in the New Testament place less emphasis on reason. Jesus says:\n\n<blockquote>\n<p>Now Thomas, one of the Twelve, called the Twin, was not with them when Jesus came. So the other disciples told him, “We have seen the Lord.” But he said to them, “Unless I see in his hands the marks of the nails, and place my finger into the mark of the nails, and place my hand into his side, I will never believe.”</p>\n<p>Eight days later, his disciples were inside again, and Thomas was with them. Although the doors were locked, Jesus came and stood among them and said, “Peace be with you.” Then he said to Thomas, “Put your finger here, and see my hands; and put your hand, and place it in my side. Do not disbelieve, but believe.” Thomas answered him, “My Lord and my God!” Jesus said to him, “Have you believed because you have seen me? Blessed are those who have not seen and yet have believed.” (John 20:24–9)</p>\n</blockquote>\n\nJesus’s last statement praises belief without direct evidence. Note that Thomas doubted, despite having witnessed many of Jesus’s miracles and having the testimony of other apostles. Modern Christians, barring personal revelation, are expected to believe the ancient testimonies passed down by the church.\n\nPaul’s first letter to the Corinthians also emphasizes faith over reas9n:\n\n<blockquote>\n<p>For Christ did not send me to baptize but to preach the gospel, and not with words of eloquent wisdom, lest the cross of Christ be emptied of its power.</p>\n<p>For the word of the cross is folly to those who are perishing, but to us who are being saved it is the power of God. For it is written, “I will destroy the wisdom of the wise, and the discernment of the discerning I will thwart.” Where is the one who is wise? Where is the scribe? Where is the debater of this age? Has not God made foolish the wisdom of the world? For since, in the wisdom of God, the world did not know God through wisdom, it pleased God through the folly of what we preach to save those who believe. For Jews demand signs and Greeks seek wisdom, but we preach Christ crucified, a stumbling block to Jews and folly to Gentiles, but to those who are called, both Jews and Greeks, Christ the power of God and the wisdom of God. For the foolishness of God is wiser than men, and the weakness of God is stronger than men.</p>\n<p>For consider your calling, brothers: not many of you were wise according to worldly standards, not many were powerful, not many were of noble birth. But God chose what is foolish in the world to shame the wise; God chose what is weak in the world to shame the strong; God chose what is low and despised in the world, even things that are not, to bring to nothing things that are, so that no human being might boast in the presence of God. And because of him you are in Christ Jesus, who became to us wisdom from God, righteousness and sanctification and redemption, so that, as it is written, “Let the one who boasts, boast in the Lord.”</p>\n<p>And I, when I came to you, brothers, did not come proclaiming to you the testimony of God with lofty speech or wisdom. For I decided to know nothing among you except Jesus Christ and him crucified. And I was with you in weakness and in fear and much trembling, and my speech and my message were not in plausible words of wisdom, but in demonstration of the Spirit and of power, that your faith might not rest in the wisdom of men but in the power of God. (I Corinthians 1:17–2:5)</p>\n</blockquote>\n\nPaul was writing about divisions in the Corinthians church. Some of his comments may not apply to us, still, his comment that “it pleased God through the folly of what we preach to save those who believe” seems to abandon reason entirely.\n\nThese two passages illustrate the tension between faith and reason in the New Testament.\n\n## Justifying Beliefs\n\nThe tension between faith and reason is critical for seekers of the truth. Faith and reason are two means of justifying belief. Seekers of the truth must decide whether they are willing to justify their beliefs with reason, faith, or a combination of the two. If they decide that faith is a permissible justification of belief, then they must decide *what* to have faith in. For example, they must decide between the large variety of religions that exist in the world, many of which claim to be the one true religion, and many of which require their adherents to have faith in their tenants.\n\nUsually people answer these questions without considering them explicitly. The typical answer to the first question is that beliefs may be justified with a combination of faith and reason. The typical answer to the second question is to have faith in their parent’s religion, without seriously considering other religions. Of course these are not the only answers that may be offered.\n\nBefore discussing the various answers that may be offered to these questions, I think it is important to consider what is meant by “faith” and “reason.”\n\nReason is a means of justifying belief using evidence. “Evidence” and “justifying” are vague words. There are many types of evidence, and there many forms of justification. Some are stronger than others. We can justify mathematical and logical beliefs using by reason alone. We can justify beliefs about the world using the scientific method. The scientific method itself is grounded in a belief that “things today will continue as they had in the past.” For example, we believe that gravity will continue to act as it has in the past. Without this implicit belief in “induction,” science can not provide any certain knowledge about the world. We have no reason to believe that “things today will continue as they have in the past.” There is no justification for this belief, but we all act as if it where true.\n\nI think that everyone has a good many beliefs that they never explicitly recognize, but that our actions imply our beliefs. Thus, because we all act as if “things today will continue as they have in the past,” without justification, we all have faith in it. This is an inconsequential faith, however, because there is not really another way that we could act.\n\nIn our every day life we make decisions about how we will act, based on more mundane beliefs. We may believe that the political system underlying our country is stable. Perhaps we don’t consciously consider this belief, however, if we believed otherwise we would buy guns and stock provisions and move to a rural warm area. Unlike our belief in induction, if we believed differently, we could act differently to reflect this belief. We believe that we are likely to live past 65 years old, so we save for retirement. If we did not believe act differently.o\n\nImagine a person who didn’t believe in induction. How would they act? They would probably act the same way you or I do. In fact, I don’t believe in the laws of induction. I think we live in a simulation, and that the creators of the simulation can change the rules of our universe at their whim, but that they seem like they probably won’t any time soon.\n\nAll of my Bible references are taken from the English Standard Version.\n" }, { "alpha_fraction": 0.7627550959587097, "alphanum_fraction": 0.7627550959587097, "avg_line_length": 23.5, "blob_id": "40ba6fbe6f61d1192fbd0c5df07d5de7a9b92538", "content_id": "f82727163fb426bb5f21cf1df87baa5bdfe7b21b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1176, "license_type": "no_license", "max_line_length": 49, "num_lines": 48, "path": "/documents/questioning-poem.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Questioning\ndescription: >\n A poem about life and its questions.\ntype: poem\nstatus: complete\n---\n\n~~~\nA baby is born and the parents love the baby.\nA baby is born and the parents raise the baby.\nA baby is born and the parents teach it words.\nThe words come slowly.\nThe words grow longer\nAnd the words grow clearer.\nThe child is taught to act.\nThe acts of the child are bad.\nThe child is taught discipline.\nThe child grows into a person.\nAnd this person lives how they please.\nPleasures and pursuits fill its time.\n\nLife's pain encroaches.\n\nThe person looks for meaning\nAnd the person searches for purpose\nAnd the person asks how to live.\nReligion tells this person how to live.\nReligion tells this person what exists\nWhat exists but is not seen.\n\nHow do they know?\nHow do they trust the words of the ancient books,\nThe words passed down through the ages\nThe words of the prophets\nThe words of the priests?\n\nI want to act well.\nI want to not do what I should not do\nAnd do what I should do.\n\nThe words of the priests tell me what to do!\nThe prophets speak out!\nThe ancient books pass along their wisdom.\nBut how can I trust their knowledge?\nHow can I know?\n~~~\n" }, { "alpha_fraction": 0.7527768015861511, "alphanum_fraction": 0.7626298666000366, "avg_line_length": 87.6031723022461, "blob_id": "355b54844f0f408e5ada2dd82018dda20dab3c73", "content_id": "9c15496d057d44b244e98a5d25e068d800e316a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5586, "license_type": "no_license", "max_line_length": 910, "num_lines": 63, "path": "/documents/homeric-hymns.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n _The Homeric Hymns_\ndescription: >\n Notes on _The Homeric Hymns_\ntype: note\n---\n\n*The Homeric Hymns* are a collection of thirty-three hexameter poems which honor the ancient Greek gods. Modern scholars believe most of them were written between 700 and 500 BCE. The hymns were traditionally attributed to Homer.\n\nThe Hymns vary from three to over five-hundred lines. Here are the longest and most interesting hymns:\n\n<ol>\n <li value=\"2\">Hymn to Demeter, Persephone and the origin of winter</li>\n <li value=\"3\">Hymn to Apollo, how his temples came about</li>\n <li value=\"4\">Hymn to Hermes, his birth and theft of Apollo's cows</li>\n <li value=\"5\">Hymn to Aphrodite, affair with mortal Anchises</li>\n <li value=\"7\">Hymn to Dionysus, pirates and dolphins</li>\n <li value=\"19\">Hymn to Pan, his domains and dances</li>\n</ol>\n\nThe hymns appear to be used as preludes at poetry competitions or ceremonies.\n\nAll of the quotes here are from the H.G. Evelyn-White translation, and the line numbers are approximate.\n\nA central theme in the hymns, as in *The Theogony*, is the birth of the gods. They seem especially interested in the location of the birth:\n\n> For some say, at Dracanum; and some, on windy Icarus; and some, in Naxos, O Heaven-born, Insewn; and others by the deep-eddying river Alpheus that pregnant Semele bare you to Zeus the thunder-lover. And others yet, lord, say you were born in Thebes; but all these lie. The Father of men and gods gave you birth remote from men and secretly from white-armed Hera.\n> - (1.1--7)\n\n> Rejoice, blessed Leto, for you bare glorious children, the lord Apollo and Artemis who delights in arrows; her in Ortygia, and him in rocky Delos, as you rested against the great mass of the Cynthian hill hard by a palm-tree by the streams of Inopus.\n> - (3.13--8)\n\n> I will sing of Heracles, the son of Zeus and much the mightiest of men on earth. Alcmena bare him in Thebes, the city of lovely dances, when the dark-clouded Son of Cronos had lain with her.\n> - (15.1--4)\n\nAnother theme is the relationship between gods and men:\n\n> Thence, swift as thought, he [Apollo] speeds from earth to Olympus, to the house of Zeus, to join the gathering of the other gods: then straightway the undying gods think only of the lyre and song, and all the Muses together, voice sweetly answering voice, hymn the unending gifts the gods enjoy and the sufferings of men, all that they endure at the hands of the deathless gods, and how they live witless and helpless and cannot find healing for death or defence against old age.\n> - (3.186--92)\n\n> Sing, clear-voiced Muses, of Hephaestus famed for inventions. With bright-eyed Athene he taught men glorious gifts throughout the world, — men who before used to dwell in caves in the mountains like wild beasts. But now that they have learned crafts through Hephaestus the famed worker, easily they live a peaceful life in their own houses the whole year round.\n> - (20.1--7)\n\n> And now because of you [Anchilles] I [Aphrodite] shall have great shame among the deathless gods henceforth, continually. For until now they feared my jibes and the wiles by which, or soon or late, I mated all the immortals with mortal women, making them all subject to my will. But now my mouth shall no more have this power among the gods; for very great has been my madness, my miserable and dreadful madness, and I went astray out of my mind who have gotten a child beneath my girdle, mating with a mortal man.\n> - (5.247--50)\n\nThe Hymn to Demeter describes the Eleusian mysteries:\n\n> Then she [Demeter] went, and to the kings who deal justice, Triptolemus and Diocles, the horse-driver, and to doughty Eumolpus and Celeus, leader of the people, she showed the conduct of her rites and taught them all her mysteries, to Triptolemus and Polyxeinus and Diocles also, — awful mysteries which no one may in any way transgress or pry into or utter, for deep awe of the gods checks the voice. Happy is he among men upon earth who has seen these mysteries; but he who is uninitiate and who has no part in them, never has lot of like good things once he is dead, down in the darkness and gloom.\n> - (2.472--82)\n\nThe Hymn to Gaia is beautiful:\n\n> I will sing of well-founded Earth, mother of all, eldest of all beings. She feeds all creatures that are in the world, all that go upon the goodly land, and all that are in the paths of the seas, and all that fly: all these are fed of her store. Through you, O queen, men are blessed in their children and blessed in their harvests, and to you it belongs to give means of life to mortal men and to take it away. Happy is the man whom you delight to honour! He has all things abundantly: his fruitful land is laden with corn, his pastures are covered with cattle, and his house is filled with good things. Such men rule orderly in their cities of fair women: great riches and wealth follow them: their sons exult with ever-fresh delight, and their daughters in flower-laden bands play and skip merrily over the soft flowers of the field. Thus is it with those whom you honour O holy goddess, bountiful spirit.\n>\n> Hail, Mother of the gods, wife of starry Heaven; freely bestow upon me for this my song substance that cheers the heart! And now I will remember you and another song also\n> - (30.1--19)\n\nThere are a handful of similes. Here is one which I particularly enjoyed:\n\n> As a swift thought darts through the heart of a man when thronging cares haunt him, or as bright glances flash from the eye, so glorious Hermes planned both thought and deed at once.\n> - (4.43--5)\n" }, { "alpha_fraction": 0.8066361546516418, "alphanum_fraction": 0.8066361546516418, "avg_line_length": 99.84615325927734, "blob_id": "721bdf3a42941865b0a268b579866945b2f00e96", "content_id": "aaf28647f6e83239ed4c519a4d07a09982a5789f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2622, "license_type": "no_license", "max_line_length": 757, "num_lines": 26, "path": "/documents/altera-evolving-consciousness.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Altera: Evolving Consciousness\ndescription: >\n I discuss how Nooks could evolve consciousness.\ntype: essay\nstatus: incomplete\n---\n\n## Evolution\n\nAltera's physical laws were designed so that the Nook's minds could evolve. The Nook's are competing for scare Food to avoid starving to death. Nooks that reproduce more frequently are better adapted for their environment. They will propogate their Mind more then less adapted Nooks. Beneficial random mutations will accumulate.\n\n## Conciousness\n\nImagine that, after a long period of time, the Nooks became concious. They developed language, which could be transmitted from one Nook to another via a series of pauses and movements. The developed civilization, wherein different Nooks played different roles. Some Nooks were responsible for gathering food and stockpiling it. Other Nooks were responsible for defense and protection of the food. Some Nooks were kings or priests. Others were dancers and poets. A wealthy civilization could encode knowledge using food, placed at regular intervals corresponding to their \"spoken\" language. In order to transmit information more quickly across their world, they could form communication chains, perhaps by having heavy Nooks push long chains of food.\n\nIt is also quite possible, even likely, that conciousness would never develop. Just because the elements necessary for evolution to occur are present, does not necessitate the development of consciousness. Perhaps the laws of physics that have been contrived are too simplistic to support conciousness. Or perhaps they lead evolution inevitably to a local maximum, or a dead world state wherein all of the Nooks perish.\n\n## Science\n\nThe Nooks could perform scientific experiments to better understand the physical laws of Altera. Some laws would be easier to understand than others. They could learn when certain actions would be \"allowed.\" Perhaps, if all of the Nooks in the universe collaborated together, they could somehow deduce the equation for the pseudo random number generator that governs food placement.\n\nWell before they developed conciousness, their minds would evolve to account for the physical laws of their universe. Thus in a sense they would \"know\" the physical laws without consciously knowing them. In the same way that insects have evolved to account for gravity despite not being aware of knowing the physical laws of gravity.\n\nPerhaps the early concious Nooks would form some sort of religion to explain their existence. It seems likely that food, and its random placement, would be central to their early religions.\n" }, { "alpha_fraction": 0.7631480693817139, "alphanum_fraction": 0.7696565985679626, "avg_line_length": 62.05188751220703, "blob_id": "4a7265f2ef2166766e1855a364f81f9057712932", "content_id": "08b957e5341ab65daa1671f2c293ef9043c9be13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13371, "license_type": "no_license", "max_line_length": 605, "num_lines": 212, "path": "/documents/hesiod.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Hesiod\ndescription: >\n Notes on Hesiod's \"Theogony\" and \"Works and Days\"\ntype: note\n---\n\nHesiod was a famous Greek poet---the ancients often mention him in the same sentence with Homer---who wrote the epic hexameter poems *Theogony* and *Works and Days*. He is thought to have lived sometime between 800 and 600 BCE.\n\n## The Evolution of Myths\n\nUnlike most of the ancient Greeks, I don't believe that Zeus, Athena, or their other gods existed. But why did the Greeks believe? And where did their myths come from, if they are not true?\n\nSome of Hesiod's myths are similar to Babylonian and Hittite myths. This continuity is not surprising because new religious ideas usually evolve from older religious ideas. But how did this evolution occur? And where did the earlier myths come from? We don't have enough evidence to answer either question with certainty, but Hesiod's poetry provides some small insight into each of them.\n\nHesiod's *Theogony* organizes and synthesizes older Greek myths while also adding details. Thus, the big question about the evolution of religion can be considered at a smaller scale within Hesiod himself: How did he evolve the Greek Myths?\n\nHesiod appears to believe that the Muses---the nine daughters of Zeus and Memory---inspired his poetry, and perhaps this explains how he felt justified taking creative license with his source material, while also believing in his own stories:\n\n> And they taught Hesiod the art of singing verse,\n> While he pastured his lambs on holy Helikon's slopes.\n> And this was the very first thing they told me,\n> The Olympian Muses, daughters of Zeus Aegisholder:\n>\n> \"Hillbillies and bellies, poor excuses for shepherds:\n> We know how to tell many believable lies,\n> But also, when we want to, how to speak the plain truth.\"\n>\n> So spoke the daughters of great Zeus, mincing their words.\n> And they gave me a staff, a branch of good sappy laurel,\n> Plucking it off, spectacular. And they breathed into me\n> A voice divine, so I might celebrate past and future.\n> And they told me to hymn the generations of the eternal gods,\n> But always to sing of themselves, the Muses, first and last ...\n>\n> Farewell Zeus's daughters, and bestow song that beguiles.\n> Make known the eerie brood of the eternal Immortals\n> Who were born of Earth and starry Sky,\n> And of dusky Night, and whom the salt Sea bore.\n> Tell how first the gods and earth came into being\n> And the rivers and the sea, endless and surging,\n> And the stars shining and the wide sky above;\n> How they divided wealth and allotted honors,\n> And first possessed deep-ridged Olympus.\n>\n> Tell me these things, Olympian Muses,\n> From the beginning, and tell which of them came first.\n> ~ Theogony, 23--35, 103--125\n\nHesiod does not presume that the Muses tell him the truth, but he does presume that they might have told him the truth. In other words, creative stories come from the Muses and may reveal divine truths.\n\nWe get another glimpse into Hesiod's views of the Muses and truth in *Works and Days*, when he is giving advice to his brother. Hesiod distinguishes between his experience and what the Muses have taught him:\n\n> So if you [my lazy brother] ever turn your addled wits to trade\n> To rid yourself of debt and gnawing hunger,\n> I can teach you the rhythms of the churning sea,\n> Though sailing's not my line. As far as ships go,\n> I've never sailed in one on the open sea\n> Except to Euboia once from Aulis, ...\n> That's the sum of my experience with pegged & dowelled ships.\n> Still, I can teach you the mind of Zeus the Storm King,\n> Since the Muses have taught me ineffable song.\n> Fifty days after the solstice, toward the end\n> Of summer, the seasons of scorching heat,\n> Comes the sailing seasons. You won't wreck\n> Your ship then, nor the sea drown your men,\n> Unless Poseidon Earthshaker has a mind otherwise,\n> Or the Lord of Immortals *wants* to destroy them.\n> ~ Works and Days, 717--739\n\nIt is difficult for me to understand how someone could create a story while also believing that it is true; it is even more surprising that someone could make up advice on a technical subject and believe it. But it appears this is what Hesiod is doing! It would seem that Hesiod believes that the Muses are inserting ideas into his mind, and thus may contain truth. When pressed, I imagine Hesiod arguing \"surely my ideas come from somewhere! Where else, besides the immortal gods, could they come from?\"\n\nPerhaps the myths evolved when story-tellers, believing they were inspired, re-told and inserted new details into older religions? In this theory, each re-telling would have to be mostly faithful, since large changes in the foundational myths would have rejected by the listeners.\n\nAs with biological evolution, one wonders how the big jumps were made. How would Zeus replace Ouranos at the head of the Pantheon? One may conjecture, but perhaps the battles of the generations of the gods represent the battles of peoples and cultures in the ancient world?\n\nHesiod's poetry may also provide some insight into the origination of Myths. Hesiod's creativity is not arbitrary. Hesiod deduces the existence of a second god, Strife, from the multiple uses of the word \"strife\":\n\n> It looks like there's not just one kind of Strife—\n> That's Eris—after all, but two on the Earth.\n> You'd praise one of them once you got to know her,\n> But the other's plain blameworthy. They've just got\n> Completely opposite temperaments.\n> One of them favors war and fighting. She's a mean cuss\n> And nobody likes her, but everybody honors her,\n> This ornery Eris. They have to: it's the gods' will.\n>\n> The other was born first though. Ebony Night\n> Bore her, and Cronos's son who sits high in thin air\n> Set her in Earth's roots, and she's a lot better for humans.\n> Even shiftless folks she gets stirred up to work.\n>\n> When a person's lazing about and sees his neighbor\n> Getting rich, because he hurries to plow and plant\n> And put his homestead in order, he tends to compete\n> With that neighbor in a race to get rich.\n>\n> Strife like this does people good.\n> ~ Works and Days, 21--37\n\nLater in *Works and Days*, towards the end of a list of suggestions for avoiding the god's anger, Hesiod remarks that \"Talk\" must be a god too, because it never dies:\n\n> That's the way to behave. And try to avoid being\n> The object of talk. A bad reputation is easy to get,\n> Difficult to endure, and hard to get rid of.\n> Talk never really dies, not when so many folks\n> Are busy with her. Talk too is some kind of a god.\n> ~ Works and Days, 840--844\n\nIn these two examples, Hesiod deduces the existence of Strife and Talk using etymology and metaphysical reasoning (anything that doesn't die must be a lie). Perhaps the Greek myths, as well as the earlier myths that inspired them, were based on observations of reality. These rational underpinnings would prop up the beliefs, since adherents could see them in the world around them.\n\nImagine a young Greek girl. All of the adults in her life tell her that Zeus and the gods rule the world and he wields thunderbolts and causes snow storms. Occasionally, at special times of the year, you participate in solemn sacrifices to Zeus, and other gods, involving the bloody ritual slaying of animals. Poets occasionally come through your town, and tell stories of the gods---some you have heard, others are new, but they all include Zeus. If you asked this girl how they knew Zeus was real, she would probably say she knew Zeus was real because she could see the thunderbolts and snow storms!\n\nWe are not certain whether Hesiod (or Homer) existed, but this irrelevant to this discussions---what matters is that the Greek tradition included, and to some degree accepted, the idea of Muses providing divine inspiration via creative human story-telling. This is one mechanism by-which the details of religions beliefs could evolve and develop, despite not being true.\n\nHerodotus' appears to view Hesiod similarly:\n\n> But the origin of each of the gods, or whether they always existed, and what they look like: all of this was unknown until just recently---only yesterday, so to speak. For I believe that Hesiod and Homer were contemporaries who lived no more than 400 years before my time. These were the poets who composed for the Hellenes the theogony, assigned to the gods their epithets, defined their particular honors and skills, and described what they look like.\n> - The Histories, 2.53\n\n## Genealogies and Creation\n\nHesiod uses genealogy as an organizational and explanatory scheme for the gods.\n\n> Tell how first the gods and earth came into being\n> And the rivers and the sea, endless and surging,\n> And the starts shining and the wide sky above;\n> How they divided wealth and allotted honors,\n> And first possessed deep-ridged Olympus ...\n> In the beginning there was only Chaos, the Abyss,\n> But then Gaia, the Earth, came into being,\n> Her broad bosom the ever-firm foundation of all,\n> And Tartaros, dim in the underground depths,\n> And Eros, loveliest of all the Immortals, who\n> Makes their bodies (and men's bodies) go limp,\n> Mastering their minds and subduing their wills.\n> From the Abyss were born Erebos and dark Night.\n> And Night, pregnant after sweet intercourse\n> With Erebos, gave birth to Aether and Day.\n> Earth's first child was Ouranos, starry Heaven,\n> Just her size, a perfect fit on all sides.\n> ~ Theogony, 104--127\n\nAn apparently similar use of genealogies is found in Genesis, and especially the \"Table of Nations\" in Genesis 10:\n\n> These are the families of Noah's sons, according to their genealogies, in their nations; and from these the nations spread abroad on the earth after the flood.\n> - Genesis 10.32, NRSV\n\nAfter the first few generations, Hesiod depicts creation as a sexual act, similar to the *Enuma Elish.* Other traditions conceptualize creation through speech. For example, Genesis 1.3 states \"Then God said, 'Let there be light' and there was light.\" Still others conceptualize creation through material acts. For example, Genesis 2.7 states \"then the Lord God formed man from the dust of the ground, and breathed into his nostrils the breath of life.\"\n\nSex, speech, and craftsmanship are all creative acts in human life, so it is natural that humans would project them backward to the creation of the world (and the gods).\n\nHesiod presents three types of gods:\n\n1. Personified gods that were worshiped (e.g., Zeus and Athena)\n2. Personified gods that were not worshiped (e.g., Atlas)\n3. Gods which represent abstractions (e.g., Dawn, Strife, and Talk)\n\nIt seemed natural to the Greeks to represent abstract concepts as gods, since they are invisible and immortal.\n\n## Misogyny\n\nHesiod was misogynistic:\n\n> From her [Pandora] is the race of female women,\n> The deadly race and population of women,\n> A great infestation among mortal men,\n> At home with Wealth but not with Poverty.\n> It's the same as with bees in their overhung hives\n> Feeding the drones, evil conspirators.\n> The bees work every day until the sun goes down,\n> Busy all day long making pale honeycombs,\n> While the drones stay inside, in the hollow hives,\n> Stuffing their stomachs with the work of others.\n> ~ Theogony, 594--603\n\n> A man couldn't steal anything better than a good wife,\n> Just as nothing is more horrible than a bad one,\n> Some freeloader who roasts her man without a fire\n> And serves him up to a raw old age.\n> ~ Works and Days, 777--780\n\n> Don't wash in a woman's bath-water\n> Which for a time has a bitter vengeance in it.\n> ~ Works and Days, 833--834\n\n## Other Connections\n\nThe Babylonians and Sumerians thought men were created to feed the gods with sacrifices of wheat, animals, and beer. The Greeks also sacrificed to the gods, but they did not seem to believe they were created for this purpose:\n\n> Before [Pandora opened the box] the human race\n> Had lived off the land without any trouble, no hard work,\n> No sickness or pain that the Fates give to men.\n> ~ Works and Days, 110--112\n\nBoth Marduk and Zeus were young sky gods who lead a fight over an older generation of gods to become the leading god. Zeus's division of duties and realms upon defeating Cronos is similar to Marduk's division after defeating Tiamhat in the *Enuma Elish*, and the Sumerian concept of *me* is also similar (and even older).\n\n> So the blessed gods had done a hard piece of work,\n> Settled by force the question of rights with the Titans.\n> Then at Gaia's suggestion they pressed broad-browed Zeus,\n> The Olympian, to be their king and rule the Immortals.\n> And so Zeus dealt out their privileges and rights.\n> ~ Theogony, 886--890\n\nHesiod was pessimistic and believes men have gotten weaker over time.\n\nGreek religious beliefs varied geographically and temporally---there was no canonical set of myths. Homer and Hesiod disagreed with each other sometimes. For example, in Hesiod Aphrodite is born from Ouranos's castrated members floating in the foam off the coast of Cyprus. In Homer, Aphrodite is the daughter of Zeus and Dione.\n\nHesiod spends a long time discussing the relatively unimportant goddess Hekate; perhaps Hesiod was involved with a Hekate cult that was popular in his region?\n\n*Quotations are from the Stanley Lombardo translation, as are the line numbers which are different from the line numbers in the Greek.*\n" }, { "alpha_fraction": 0.5074089169502258, "alphanum_fraction": 0.5122146606445312, "avg_line_length": 25.56382942199707, "blob_id": "0379486617caadf9c624103b6b54a554c89c29e0", "content_id": "a68fc43ebd1f0dbc1d19c62b9916956bcb826227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2499, "license_type": "no_license", "max_line_length": 79, "num_lines": 94, "path": "/scripts/process.py", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport sys\nimport re\nimport html\n\n\ndef translate_markdown(lines, printer):\n in_quote = False\n in_poem = False\n quote = []\n for line in lines:\n line = line.rstrip()\n quote_line = line.startswith('> ') or line == '>'\n if not in_quote and quote_line:\n in_quote = True\n elif in_quote and not quote_line:\n in_quote = False\n translate_quote(quote, printer)\n quote = []\n\n if line == '~~~':\n in_poem = not in_poem\n continue\n\n if in_quote:\n quote.append(line)\n elif in_poem:\n printer(line + '<br>')\n else:\n printer(line)\n\n if in_quote:\n translate_quote(quote, printer)\n\n\ndef translate_quote(lines, printer):\n assert len(lines) > 0\n pruned_lines = [strip_quoting(line) for line in lines]\n last_line = pruned_lines[-1]\n is_poetry = last_line.startswith('~')\n is_prose = last_line.startswith('=')\n\n if any(last_line.startswith(q) for q in ['- (', '= (', '~ (']):\n pruned_lines.pop()\n pruned_lines[-1] += ' <cite>' + process_line(last_line[2:]) + '</cite>'\n citation = None\n elif any(last_line.startswith(q) for q in ['- ', '= ', '~ ']):\n citation = process_line(last_line[2:])\n pruned_lines.pop()\n elif any(last_line == q for q in ['-', '=', '~']):\n pruned_lines.pop()\n citation = None\n else:\n citation = None\n\n if is_poetry:\n printer('<blockquote class=\"poetry\">')\n elif is_prose:\n printer('<blockquote class=\"prose\">')\n else:\n printer('<blockquote>')\n\n for line in pruned_lines:\n if line.startswith(' '):\n printer('<p class=\"indent\">' + process_line(line[2:]) + '</p>')\n elif line != '':\n printer('<p>' + process_line(line) + '</p>')\n elif line == '' and is_poetry:\n printer('<br>')\n\n if citation:\n printer('<cite>— ' + citation + '</cite>')\n printer('</blockquote>')\n\n\ndef strip_quoting(line):\n if line.startswith('> '):\n return line[2:]\n elif line == '>':\n return line[1:]\n else:\n raise ValueError()\n\n\ndef process_line(line):\n line = re.sub(r'\\*\\*([^*]*)\\*\\*', r'<strong>\\1</strong>', line)\n line = re.sub(r'\\*([^*]*)\\*', r'<em>\\1</em>', line)\n line = re.sub(r'_([^_]*)_', r'<em>\\1</em>', line)\n return line\n\n\nif __name__ == \"__main__\":\n translate_markdown(sys.stdin, print)\n" }, { "alpha_fraction": 0.8008474707603455, "alphanum_fraction": 0.8013363480567932, "avg_line_length": 129.55319213867188, "blob_id": "793c5d31ccb74ff64ab1d79ed8e2fa3bd414ed98", "content_id": "65d415e2622a70554714ac97907aae5f0084371f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6144, "license_type": "no_license", "max_line_length": 2156, "num_lines": 47, "path": "/documents/on-reading-old-books.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n On Reading Old Books\ndescription: >\n Are old books more worthy of our attention than the new?\ntype: essay\nstatus: incomplete\n---\n\nOne may read for entertainment, to gather information, or to gain understanding.\n\nWhen reading to gain understanding, ask questions of the author. I like to ask:\n\n1. What is the author saying?\n2. Do I agree, in whole or in part?\n3. Is it significant?\n\n---\n\nReading books that were written before women could vote or slaves were free, during the depression, or in Victorian England lets us see our lives in contrast to something completely outside our experience. It gives whole new ways of looking at themes like diversity, gender roles, religion, love, family.\n\nSometimes old books highlight the differences between now and then, and sometimes they highlight the universality of the human condition - then, now and always.\n\n---\n\nUnless you are trying to achieve some goal (e.g. get a degree is something that requires reading), there are no books you \"should\" read. You should read books you enjoy, either in the simple sense of \"enjoyment\" or in the \"it challenges me in a good way\" sense.\n\nEnjoyable books have been written in all eras. Why limit yourself to the current one? That's like only eating at one restaurant. There's no reason you \"should\" eat at other restaurants, but you're missing out on some great food if you don't.\n\n---\n\nEvery age has its own outlook. It is specially good at seeing certain truths and specially liable to make certain mistakes. We all, therefore, need the books that will correct the characteristic mistakes of our own period. And that means the old books. All contemporary writers share to some extent the contemporary outlook - even those, like myself, who seem most opposed to it. Nothing strikes me more when I read the controversies of past ages than the fact that both sides were usually assuming without question a good deal which we should now absolutely deny. They thought that they were as completely opposed as two sides could be, but in fact they were all the time secretly united - united with each other and against earlier and later ages - by a great mass of common assumptions. We may be sure that the characteristic blindness of the twentieth century - the blindness about which posterity will ask, \"But how could they have thought that?\" - lies where we have never suspected it, and concerns something about which there is untroubled agreement between Hitler and President Roosevelt or between Mr. H. G. Wells and Karl Barth. None of us can fully escape this blindness, but we shall certainly increase it, and weaken our guard against it, if we read only modern books. Where they are true they will give us truths which we half knew already. Where they are false they will aggravate the error with which we are already dangerously ill. The only palliative is to keep the clean sea breeze of the centuries blowing through our minds, and this can be done only by reading old books. Not, of course, that there is any magic about the past. People were no cleverer then than they are now; they made as many mistakes as we. But not the same mistakes. They will not flatter us in the errors we are already committing; and their own errors, being now open and palpable, will not endanger us. Two heads are better than one, not because either is infallible, but because they are unlikely to go wrong in the same direction. To be sure, the books of the future would be just as good a corrective as the books of the past, but unfortunately we cannot get at them.\n\n---\n\nA further reason we recommend living books is that the authors of these books typically provide excellent examples to their readers of how to think, not merely what to think. An exposition of how an author has arrived at a conclusion, or simply a narrative statement of their thoughtful observations can help readers better understand the reasoning process. It is particularly important for younger scientists and readers to see each observation and logical inference laid out in succession so that they are given a model for the step-wise process of scientific reasoning. We also find that living books tend to emphasize the observation process, which is another critical skill to model for students of all ages.\n\nFurthermore, as the scientific community continues to pursue difficult questions and continues to engage in research, ideas that have long been accepted as truth will be overturned. And it’s important for young scientists and students to understand that these changes are a natural – and even exciting – part of the trajectory of scientific discovery. Human understanding of scientific phenomena has changed significantly since the beginning of recorded history, and will continue to change as new discoveries are made. However, such discoveries do not necessarily render older findings useless, as those prior beliefs were often a necessary precursor to subsequent ones.\n\nIt’s vital for scientists to look at those invalidated beliefs and the observations that disproved them. Understanding the transitions from older beliefs to newer ones is the process of science, and is also the place, in my opinion, where the greatest educational efforts should be placed. It is examining this process that best teaches students how to think critically. Original texts and living science books serve as particularly invaluable resources in this regard.\n\n- Older books provide an outstanding opportunity to study the history of science even as you study scientific material.\n- The literary merit of older authors is often unmatched by their modern peers.\n- Students gain a deeper and more nuanced understanding of the foundations of science, and the origins of scientific ideas.\n- Readers can learn to critically evaluate primary sources for themselves.\n- Modern readers may be astonished to learn just how much ancient and medieval scientists were able to discover with the limited tools available to them.\n- It is far easier for students who have learned to think critically to learn newer material later on, once they have already established a strong intellectual foundational.\n" }, { "alpha_fraction": 0.7445583939552307, "alphanum_fraction": 0.7830873131752014, "avg_line_length": 42.92307662963867, "blob_id": "33367d14719702456fe34ea704fd15d9fd991b14", "content_id": "c4374efbf65eb5cbb9a2096b90402de8e5181fe3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4035, "license_type": "no_license", "max_line_length": 140, "num_lines": 91, "path": "/_documents/ancient-greece.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ancient Greece\ndescription: >\n Notes on Greece\ntype: note\n---\n\nMany of these notes were taken from _Ancient Greece_ by Thomas R. Martin.\n\n## Minoans\n\n- Named after the legendary king Minos\n- c. 6000 First settlers migrated to Crete\n- c. 2200 Earliest Cretan palaces of Minoan Civilization\n- Constructed large building complexes, referred to as “palaces”\n- Famous palace at Knossos had indoor plumbing, and storage jars which could hold 240,000 gallons of water, olive oil, wine, or other goods.\n- They appear to have had a top-down redistributive economy\n- Were sea-traders; seem to have specialized in luxury goods\n- Colorful frescoes of dolphins, bulls, ships, women, and griffins\n- Minoans are depicted in Egyptian tomb reliefs\n- Archaeological evidence indicates that Minoan civilization existed peaceably for several centuries\n- There are no defensive walls found around the towns or palaces\n- Prominent snake and bull imagery; bull leaping\n- There is some evidence that they practiced human sacrifice\n- c. 1450 most sites on the island were burned\n- c. 1370 The palace at Knossos is destroyed\n\n## Myceneaens\n\n- Named after the city Mycenae\n- c. 1600–1450 shaft graves\n- c. 1450–1240 Koine Era (Highpoint of their civilization)\n- Strongly influenced by the Minoans, who they eventually conquered\n- Unlike the Minoans, they seem like a warrior culture\n- Spoke Greek; wrote using Linear B\n- References to Hera, Zeus, Poseidon, Dionysus and other divinities found in Linear B tablets\n- Built walls with such large blocks that the Greeks believed Cyclops had built them\n- Traded widely, including with the Egyptians\n- c. 1250–1100 Decline\n\n## Greek Dark Age\n\n- c. 1100 All major Myceneaen palaces except Athens destroyed\n- The Greek Dark Age is darker than then Medieval Dark Age\n- Population decline, poverty, greatly decreased trade\n- Quality of pottery and other goods greatly decreased\n- Stopped writing in Linear B; no literary sources\n- Myceneaen culture and religion passed down orally\n- Art has geometric patterns\n- c. 900–800 Population growth and adoption of iron tools and weapons\n- c. 800 Adopt the Phoenician alphabet\n- c. 776 First Olympics—competition between individual naked athletes\n- Later Greeks did not know much about their Mycenaean past\n\n## Greek Archaic Age\n\n- Art-historians thought Greek art from this period was old-fashioned, or archaic, compared to the classical age\n- Population growth\n- Rise of the Polis, a political, social, and religious organization of a city and surrounding areas\n- Political systems included monarchies, oligarchies, tyrants, and early forms of democracy\n- c. 750–500 Population growth and Greek colonization of the Mediterranean and Black Sea; “Frogs around a pond” (Plato)\n- c. 750–700 Homer and Hesiod write epic poems\n- c. 600 chattel slavery is the norm\n\n\n## Greek Classical Age\n\n- 499–494 Ionian revolt in Western Anatolia, which is eventually crushed by the Persians\n- 490 Darius sends force to Athens; Athenians win the battle of Marathon\n- 480 Xerxes leads massive Persian force into Greece; battle of Thermopylae (the 300) and navel battle of Salamis\n- 458 Aeschylus writes _The Oresteia_ (_Agamemnon_, _The Libation Bearers_, and _The Eumenides_)\n- c. 440 Herodotus writes _The Histories_\n- 431–404 Peloponnesian War, written about by Thucydides\n- 399 Trial and execution of Socrates\n- c. 400–380 Plato founds the Academy at Athens\n- 359 Philip II becomes king of Macedonia\n- 336 Philip II murdered, Alexander the Great becomes king\n- 335 Aristotle founds the Lyceum at Athens\n- 334 Alexander begins campaign against Persia\n- 331 Alexander takes Egypt and founds Alexandria\n- 326 Alexander’s army mutinies at the Hyphasis River in India, and they head back to Babylon\n- 323 Alexander dies in Babylon\n\n## Hellenistic Age\n\n- 310 murder of Alexander’s son\n- 310 Zeno founds Stoic school in Athens\n- 307 Epicurus founds his school in Athens\n- 306–304 Alexander’s former commanders split up the empire\n- 304–30 Ptolemys in Egypt\n" }, { "alpha_fraction": 0.7269737124443054, "alphanum_fraction": 0.7269737124443054, "avg_line_length": 18, "blob_id": "e4e5fa7a3b5c4ffab53a9b7ceda5c036b650bba2", "content_id": "f82f080a5309ecf8c9b92ec241c84a498be2d9b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 306, "license_type": "no_license", "max_line_length": 106, "num_lines": 16, "path": "/_documents/buddhism.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Buddhism\ndescription: >\n Notes on Buddhism\ntype: note\nstatus: incomplete\n---\n\n## Words\n\nThe *Sangha* is the monastic community of *bhikkus* (monks) and *bhikkunis* (nuns).\n\nDhamma\n\nTathāgata is a Pali and Sanskrit word; Gautama Buddha uses it when referring to himself in the Pāli Canon.\n" }, { "alpha_fraction": 0.7676506042480469, "alphanum_fraction": 0.7700438499450684, "avg_line_length": 146.4705810546875, "blob_id": "505c5bd0e012677603520959f8fecc195146d5fd", "content_id": "c87698fcffca710d89a4283cb21cb5b5ad1618f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5050, "license_type": "no_license", "max_line_length": 1870, "num_lines": 34, "path": "/_documents/nausea.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n “Nausea” by Jean-Paul Sartre\ntype: note\ndescription: >\n Notes on “Nausea”\n---\n\n## Quotes\n\n<blockquote>\n<p>I am alone in the midst of these happy, reasonable voices. All these creatures spend their time explaining, realizing happily that they agree with each other. In Heaven’s name, why is it so important to think the same things all together. <cite>(p. 8)</cite></p>\n</blockquote>\n\n<blockquote>\n<p>Well, yes: he could have done all that, but it is not proved: I am beginning to believe that nothing can ever be proved. These are honest hypotheses which take the facts into account: but I sense so definitely that they come from me, and that they are simply a way of unifying my own knowledge. Not a glimmer comes from Rollebon’s side. Slow, lazy, sulky, the facts adapt themselves to the rigour of the order I wish to give them; but it remains outside of them. I have the feeling of doing a work of pure imagination. <cite>(p. 13)</cite></p>\n</blockquote>\n\n<blockquote>\n<p>The vocal chorus will be along shortly: I like that part especially and the abrupt manner in which it throws itself forward, like a cliff against the sea. For the moment, the jazz is playing; there is no melody, only notes, a myriad of tiny jolts. They know no rest, an inflexible order gives birth to them and destroys them without even giving them time to recuperate and exist for themselves. They race, they press forward, they strike me a sharp blow in passing and are obliterated. I would like to hold them back, but I know if I succeeded in stopping one it would remain between my fingers only as a raffish languishing sound. I must accept their death; I must even <em>will</em> it. I know few impressions stronger or more harsh.</p>\n<p>I grow warm, I being to feel happy There is nothing extraordinary in this, it is a small happiness of Nausea: it spread at the bottom of the viscous puddle, at the bottom of <em>our</em> time—the time of purple suspenders and broken chair seats; it is made of wide, soft instants, spreading at the edge, like an oil stain. No sooner than born, it is already old, it seems as though I have known it for twenty years. <cite>(p. 21)</cite></p>\n</blockquote>\n\n<blockquote>\n<p>A few seconds more and the Negress will sing. It seems inevitable, so strong is the necessity of this music: nothing can interrupt it, nothing which comes from this time in which the world has fallen; it will stop of itself, as if by order. If I love this beautiful voice it is especially because of that: it is neither for its fullness nor its sadness, rather because it is the event for which so many notes have been preparing, from so far away, dying that it might be born. And yet I am troubled; it would take so little to make the record stop: a broken spring, the whim of Cousin Adolphe. How strange it is, how moving, that this hardness should be so fragile Nothing can interrupt it yet all can break it. <cite>(p. 22)</cite></p>\n</blockquote>\n\n<blockquote>\n<p>For the time being I have seen enough of living things, of dogs, of men, of all flabby masses which move spontaneously. <cite>(p. 24)</cite></p>\n</blockquote>\n\n<blockquote>\n<p>Experienced professionals? They have dragged out their life in stupor and semi-sleep, they have married hastily, out of impatience, they have made children at random. They have met other men in cafes, at weddings and funerals. Sometimes, caught in the tide, they have struggled against it without understanding what was happening to them. All that has happened around them has eluded them; long, obscure shapes, events from afar, brushed by them rapidly and when they turned to look all had vanished. And then, around forty, they christen their small obstinacies and a few proverbs with the name of experience, they being to simulate slot machines: put a coin in the left hand slot and you get tales wrapped in silver paper, put a coin in the slot on the right and you get precious bits of advice that stick to your teeth like caramels. … There are also amateurs. These are secretaries, office workers, shopkeepers, people who listen to others in cafes: around forty they feel swollen, with an experience they can’t get rid of. Luckily they’ve made children on whom they can pass it off. They would like to make us believe that their past is not lost, that their memories are condensed, gently transformed into Wisdom. Convenient past! Past handed out of a pocket! little gilt books full of fine sayings. “Believe me, I’m telling you from experience, all I know I’ve learned from life.” Has life taken charge of their thoughts? They explain the new by the old—and the old they explain by the older still, like those historians who turn a Lenin into a Russian Robespierre, and a Robespierre into a French Cromwell: when all is said and done, they have never understood anything at all… You can imagine a morose idleness behind their importance: they see the long parade of pretenses, they yawn, they think there’s nothing new under the sun. <cite>(pp. 68–9)</cite></p>\n</blockquote>\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 79, "blob_id": "f6ce306f881e4cf912e414a1beafff6768ab0590", "content_id": "bb22a369408f761d8b33de4927a47f9bb9e7ffaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1120, "license_type": "no_license", "max_line_length": 385, "num_lines": 14, "path": "/documents/altera-science.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Altera: Science\ndescription: >\n Nooks can use the scientific method to understand Altera. What can they discover, and what difficulties will they have?\ntype: essay\nstatus: incomplete\n---\n\nThe Nooks could perform scientific experiments to better understand the physical laws of Altera. Some laws would be easier to understand than others. They could learn when certain actions would be \"allowed.\" Perhaps, if all of the Nooks in the universe collaborated together, they could somehow deduce the equation for the pseudo random number generator that governs food placement.\n\nWell before they developed conciousness, their minds would evolve to account for the physical laws of their universe. Thus in a sense they would \"know\" the physical laws without consciously knowing them. In the same way that insects have evolved to account for gravity despite not being aware of knowing the physical laws of gravity.\n\nPerhaps the early concious Nooks would form some sort of religion to explain their existence. It seems likely that food, and its random placement, would be central to their early religions.\n" }, { "alpha_fraction": 0.7570850253105164, "alphanum_fraction": 0.76113361120224, "avg_line_length": 91.625, "blob_id": "b1c95022cb96d5549f7e4780150e739519a7d3c1", "content_id": "c2a727f28cb8812d3f2edeb70cb9c8b19d32d7ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2263, "license_type": "no_license", "max_line_length": 985, "num_lines": 24, "path": "/documents/love-thy-neighbor-as-thyself.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Love Thy Neighbor as Thyself\ndescription: >\n A brief discussion of the second great commandment of the New Testament.\ntype: essay\nstatus: incomplete\n---\n\nJesus distills the law into two commands:\n\n> One of the scribes came near and heard them disputing with one another, and seeing that he answered them well, he asked him, “Which commandment is the first of all?” Jesus answered, “The first is, ‘Hear, O Israel: the Lord our God, the Lord is one; you shall love the Lord your God with all your heart, and with all your soul, and with all your mind, and with all your strength.’ The second is this, ‘You shall love your neighbor as yourself.’ There is no other commandment greater than these.” Then the scribe said to him, “You are right, Teacher; you have truly said that ‘he is one, and besides him there is no other’; and ‘to love him with all the heart, and with all the understanding, and with all the strength,’ and ‘to love one’s neighbor as oneself,’—this is much more important than all whole burnt offerings and sacrifices.” When Jesus saw that he answered wisely, he said to him, “You are not far from the kingdom of God.” After that no one dared to ask him any question.\n> - Mark 12:28--34, NRSV\n\nThe second greatest commandment is extreme. Most of us love ourselves a lot, so loving our neighbors as ourselves is exceedingly difficult. And we must also love our neighbor's children as we love our own children.\n\nWho are our neighbors? Does it include all other humans, or only those in our immediate vicinity? If the latter, hermits can avoid the difficulty of this challenging ethical imperative. If the former, we must love all people as we love ourselves.\n\nThe Golden Rule, as I understand it, is much more moderate:\n\n> \"In everything do to others as you would have them do to you; for this is the law and the prophets.\"\n> - Matthew 7:12, NRSV\n\nI would not expect a stranger to give their life for me. If I was poor, I would not expect a wealthy person on the other side of the world to give all of their wealth to help me. I may expect them to donate *some* amount to help others, but not everything and not to me. I would not expect my neighbor to love me as they love themselves.\n" }, { "alpha_fraction": 0.7332776188850403, "alphanum_fraction": 0.7447938323020935, "avg_line_length": 43.571807861328125, "blob_id": "e65d4a6090c303d434c55f7eb784163d1c0d3419", "content_id": "43dc136745b0ad845b3c053f113d9f71c93034d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16763, "license_type": "no_license", "max_line_length": 476, "num_lines": 376, "path": "/documents/the-odyssey.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n The _Odyssey_\ndescription: >\n Notes on the _Odyssey_\ntype: note\nstatus: incomplete\n---\n\n## Background\n\nThe ancients believed that the *Odyssey* was composed by the blind poet Homer. Modern scholars debate when it was composed and by whom, but most agree it was written between 725 BCE and 675 BCE. It has almost always been held that that the *Odyssey* was written after the *Iliad,* because it refers to material in the *Iliad* frequently, while avoiding any direct duplication.\n\n## Structure and Outline\n\nThe poem has about 12,000 lines of hexameter verse in the ancient Greek, and is split into 24 books. The opening summarizes the theme of the epic:\n\n> Sing to me of the man, Muse, the man of twists and turns\n> driven time and again off course, once he had plundered\n> the hallowed heights of Troy.\n> Many cities of men he saw and learned their minds,\n> many pains he suffered, heartsick on the open sea,\n> fighting to save his life and bring his comrades home.\n> But he could not save them from disaster, hard as he strove---\n> the recklessness of their own ways destroyed them all,\n> the blind fools, they devoured the cattle of the Sun\n> and the Sungod wiped from sight the day of their return.\n> Launch out on his story Muse, daughter of Zeus,\n> start from where you will---sing for our time too.\n> ~ (1.1--10)\n\nIt is interesting that the poet tells the muse to \"start from where you will.\"\n\nHere is an outline:\n\n1. The gods pity Odysseus; Athena inspires Telemachus\n2. The assembly at Ithaca; Telemachus secretly sets sail\n3. Nestor recalls his return; sacrifice to Athena; departure for Lacedaemon\n4. Menelaus recalls his return; the suitors plot their ambush\n5. Hermes visits Calypso; Odysseus' raft; sails then swims to Phaeacia\n6. Athena guides the princess to bring aid to Odysseus\n7. King Alcinous promises to bring Odysseus home\n8. Athletic games; song of Ares and Aphrodite; songs of Troy\n9. Encounter in Polyphemus the Cyclops' cave; Odysseus is cursed\n10. Blown home and back; Laestrygonians destroy the fleet; year with Circe\n11. Odysseus talks to ghosts in the kingdom of the dead\n12. Return to Circe; the Sirens; Scylla and Charybdis; Helios' cattle; Calypso\n13. Athena greets Odysseus on Ithaca; Poseidon petrifies the Phaeacians\n14. Disguised Odysseus talks to the loyal swineherd Eumaeus\n15. Telemachus returns with gifts and a seer; Eumaeus' story\n16. Odysseus and Telemachus meet and plan revenge; the suitors conspire\n17. Mingling with the suitors\n18. Odysseus fights a hobo and chides the disloyal maidens\n19. Penelope questions disguised Odysseus; Eurycleia sees the scar\n20. Odysseus rests and receives omens; Apollo's feast\n21. The trial of the bow; Odysseus signals the attack\n22. Slaughter of the suitors and the disloyal maidens\n23. Odysseus and Penelope reunited\n24. Achilles and Agamemnon greet the suitor's ghosts; Odysseus and Laeretes; final battle and peace\n\n## Justice, Morality, and the Gods\n\nEarly in book 1, the gods are in full assembly---curiously similar to the assemblies the Greeks held---and Zeus makes an interesting statement:\n\n> \"Ah how shameless---the way these mortals blame the gods.\n> From us alone, they say, come all their miseries, yes,\n> but they themselves, with their own reckless ways,\n> compound their pains beyond their proper share.\n> Look at Aegisthus now ...\n> above and beyond *his* share he stole Atrides' wife,\n> he murdered the warlord coming home from Troy\n> though he knew it meant his own total ruin.\"\n> ~ (1.31--37)\n\nFrom the start of the *Odyssey,* the gods seem more concerned with morals and justice than in the *Iliad.*\n\nZeus' implication that men should have a \"proper share\" of pains is interesting. In the Abrahamic religions, pain and suffering are the result of the fall of man. After the fall, there doesn't seem to be an expectation that these pains are distributed evenly. In the Greek religion, they had the myth of Pandora's box, which is in someways similar to the story of Adam and Eve, but even after the fall it appears there is a sense that miseries should be distributed evenly.\n\nShortly after Zeus' comment, Athena responds:\n\n> \"Let them all die so, all who do such things.\n> But my heart breaks for Odysseus ...\n> he, straining for no more than a glimpse\n> of hearth-smoke drifting up from his own land,\n> Odysseus longs to die ... Olympian Zeus,\n> have you no care for *him* in your lofty heart?\n> Did he never win your favor with sacrifices\n> burned besides the ships on the broad plain of Troy?\"\n> ~ (1.46--63)\n\nZeus replies that, no, he is happy with Odysseus, but that Poseidon is the one to blame.\n\nThe Greeks' explanation for the existence of pain and suffering appears to be three fold:\n\n- We all should have a \"fair share\"\n- Some we bring on ourselves through unjust acts\n- Some is due to other gods\n\nThe assembly in book 2 provides some insight into justice in ancient Greece. Telemachus appears to escalate through three authorities. First, is his own strength, second is the people of Ithaca:\n\n> \"Now we have no man like Odysseus in command\n> to drive this curse from the house. We ourselves?\n> We're hardly the ones to fight them off. All we'd do\n> is parade our wretched weakness. A boy inept at battle.\n> Oh I'd swing to attack if I had the power in me.\n> By god, it's intolerable, what they do---disgrace,\n> my house a shambles! You should be ashamed yourselves,\n> mortified in the face of neighbors living round about!\n> Fear the gods' wrath---before they wheel in outrage\n> and make these crimes recoil on your heads.\"\n> ~ (2.57-67)\n\nAnd when the towns people refuse to do anything, Telemachus escalates to the third authority---the gods:\n\n> \"But if you decide the fare is better, richer here,\n> destroying one man's goods and going scot-free,\n> all right then, carve away!\n> But I'll cry out to the everlasting gods in hopes\n> that Zeus will pay you back with a vengeance---all of you\n> destroyed in my house while I go scot-free myself!\"\n> ~ (2.141--5)\n\nIt seems that fear of the gods was the main source of justice in Greek society. Since there were no contracts or court system to build trust between individuals, people relied on oaths---and the fear of the gods if one broke their oath---to build trust. Similarly, if one could not find justice through strength of your fellow men, you could threaten the wrongdoers with a curse. If they feared the gods, they may respond.\n\nIn such a society an atheist or godless person could not be trusted. Right after Telemachus threatens the suitors with a curse, Zeus sends a sign down in the form of two eagles. One of the old townsmen, who excelled in reading omens and bird signs, said that the eagles were a sign from Zeus that the suitors would get what is coming to them. And the suitors respond:\n\n> \"Stop, old man!\"\n> Eurymachus, Polybus' son, rose up to take him on.\n> \"Go home and babble your omens to your children---\n> save *them* from some catastrophe coming soon.\n> I'm a better hand than you at reading portents.\n> Flocks of birds go fluttering under the sun's rays,\n> not all are fraught with meaning.\"\n> ~ (2.177--83)\n\n## The Gods\n\nAthena rebukes Telemachus for doubting the power of the gods to return his father:\n\n> \"Hope, hope as I will,\n> that day will never dawn...\n> not even if the gods should will it so.\" \"Telemachus!\"\n> Pallas Athena broke in sharply, her eyes afire---\n> \"What's this nonsense slipping through your teeth?\n> It's light work for a willing god to save a mortal\n> even half the world away. Myself, I'd rather\n> sail through years of trouble and labor home\n> and see that blessed day, than hurry home\n> to die at my own hearth like Agamemnon,\n> killed by Aegisthus' cunning---by his own wife.\n> But the great leveler, Death: not even the gods\n> can defend a man, not even one they love, that day\n> when fate takes hold and lays him out at last.\"\n> ~ (3.228--39)\n\nAthena reveals herself to many people at once:\n\n> With that the bright-eyed goddess winged away\n> in an eagle's form and flight.\n> Amazement fell on all the Achaeans there.\n> The old king, astonished by what he'd seen,\n> grasped Telemachus' hand and cried out to the prince,\n> \"Dear boy---never fear you'll be a coward or defenseless,\n> not if at your young age the gods will guard you so.\"\n> ~ (3.372--7)\n\n## Women\n\nThe Greeks did not treat women well.\n\n> \"So, mother,\n> go back to your quarters. Tend to your own tasks,\n> the distaff and the loom, and keep the women\n> working hard as well. As for giving orders,\n> men will see to that, but I most of all:\n> I hold the reins of power in this house.\" Astonished,\n> she withdrew to her own room. She took to heart\n> the clear good sense in what her son had sad.\n> ~ (1.355--62)\n\nAgamemnon's ghost's rant against women:\n\n> \"'But she---\n> the queen hell-bent on outrage---bathes in shame\n> not only herself but the whole breed of womankind,\n> even the honest ones to come, forever down the years!'\"\n> So he declared and I cried out, 'How terrible!\n> Zeus from the very start, the thunder king\n> has hated the race of Atreus with a vengeance---\n> his trustiest weapon women's twisted wiles.\n> What armies of us died for the sake of Helen...\n> Clytemnestra schemed your death while you were worlds away!'\"\n> ~ (11.432--40)\n\n## The Good Life\n\n> Alcinous, majesty, shining among your island people,\n> what a fine thing it is to listen to such a bard\n> as we have here---the man sings like a god.\n> The crown of life, I'd say. There's nothing better\n> than when deep joy holds sway throughout the realms\n> and banqueters up and down the palace sit in ranks,\n> enthralled to hear the bard, and before them all, the tables\n> heaped with bread and meats, and drawing wine from a mixing-bowl\n> the steward makes his rounds and keeps the winecups flowing.\n> This, to my mind, is the best that life can offer.\n> ~ (9.2--10)\n\nMy wife observed that is perhaps not a coincidence that Homer's Odysseus believes a talented bard's story is the best that life has to offer.\n\n## The Muses\n\nHomer, like Hesiod, implies that the Muse provides divine inspiration to bards.\n\n> \"I respect you, Demodocus, more than any man alive---\n> surely the Muse has taught you, Zeus's daughter,\n> or god Apollo himself. How true to life,\n> all too true ... you sing the Achaeans' fate,\n> all they did and suffered, all they soldiered through,\n> as if you were there yourself or heard from one who was.\"\n> ...\n> Stirred now by the Muse, the bard launched out\n> in a fine blaze of song, starting at just the point\n> where the main Achaean force, setting their camps afire,\n> hard boarded the oarswept ships and sailed for home ...\n> ~ (8.486--501)\n\n## Other Interesting Quotes\n\nHelen uses a strange drug while feasting with Menelaus, Telemachus, and Pisastratus:\n\n> Then Zeus's daughter Helen thought of something else.\n> Into the mixing-bowl from which they drank their wine\n> she slipped a drug, heart's-ease, dissolving anger,\n> magic to make us all forget our pains...\n> No one who drank it deeply, mulled in wine,\n> could let a tear roll down his cheeks that day,\n> not even if his mother should die, his father die,\n> not even if right before his eyes some enemy brought down\n> a brother or darling son with a sharp bronze blade.\n> ~ (4.218--25)\n\nIn Odysseus' speech to the princess Nausicaa, he describes the ideal marriage:\n\n> \"And may the good gods give you all your heart desires:\n> husband, and house, and lasting harmony too.\n> No finer, greater gift in the world than that...\n> when man and woman possess their home, two minds,\n> two hearts that work as one. Despair to their enemies,\n> a joy to all their friends. Their own best claim to glory.\"\n> ~ (6.180--4)\n\nOdysseus' description of hunger:\n\n> \"But despite my misery, let me finish dinner.\n> The belly's a shameless dog, there's nothing worse.\n> Always insisting, pressing, it never lets us forget---\n> destroyed as I am, my heart racked with sadness,\n> sick with anguish, still it keeps demanding,\n> 'Eat, drink!' It blots out all the memory\n> of my pain, commanding, 'Fill me up!'\"\n> ~ (7.214-20)\n\nOdysseus is cursed by the Cyclops---causing his journey home to be so long:\n\n> \"Hear me---\n> Poseidon, god of the sea-blue mane who rocks the earth!\n> If I really am your son and you claim to be my father---\n> come, grant that Odysseus, raider of cities,\n> Laertes' son who makes his home in Ithaca,\n> never reaches home. Or if he's fated to see\n> his people once again and reach his well-built house\n> and his own native country, let him come home late\n> and come a broken man---all shipmates lost,\n> alone in a stranger's ship---\n> and let him find a world of pain at home!\"\n> ~ (9.527--35)\n\nAchilles in the underworld:\n\n> \"'But you, Achilles,\n> there's not a man in the world more blest than you---\n> there never has been, never will be one.\n> Time was, when you were alive, we Argives\n> honored you as a god, and now down here, I see,\n> you lord it over the dead in all your power.\n> So grieve no more at dying, great Achilles.'\n> I reassured the ghost, but he broke out, protesting,\n> 'No winning words about death to *me*, shining Odysseus!\n> By god, I'd rather slave on earth for another man---\n> some dirt-poor tenant farmer who scrapes to keep alive---\n> than rule down here over all the breathless dead.'\"\n> ~ (11.482--92)\n\nSisyphus in the underworld:\n\n> \"And I saw Sisyphus too, bound to his own torture,\n> grappling his monstrous boulder with both arms working,\n> heaving, hands struggling, legs driving, he kept on\n> thrusting the rock uphill toward the brink, but just\n> as it teetered, set to topple over---time and again\n> the immense weight of the thing would wheel it back and\n> the ruthless boulder would bound and tumble down to the plain again---\n> so once again he would heave, would struggle to thrust it up,\n> sweat drenching his body, dust swirling above his head.\"\n> ~ (11.593--600)\n\nThe swineherd Eumaeus and disguised Odysseus trading stories:\n\n> \"We two will keep to the shelter here, eat and drink\n> and take some joy in each other's heartbreaking sorrows,\n> sharing each other's memories. Over the years, you know,\n> a man finds solace even in old sorrows, true, a man\n> who's weathered many blows and wandered many miles.\"\n> ~ (15.398--402)\n\nThe death of Argos:\n\n> Infested with ticks, half-dead with neglect,\n> here lay the hound, old Argos.\n> But the moment he sensed Odysseus standing by\n> he thumbed his tail, nuzzling low, and his ears dropped,\n> though he had no strength to drag himself an inch\n> toward his master. Odysseus glanced to the side\n> and flicked away a tear, hiding it from Eumaeus\n> ...\n> With that he entered the well-constructed palace,\n> strode through the halls and joined the proud suitors.\n> But the dark shadow of death closed down on Argos' eyes\n> the instant he saw Odysseus, twenty years away.\n> ~ (17.300--27)\n\nOdysseus' advice for the suitor Amphinomus:\n\n> Of all that breathes and crawls across the earth,\n> our mother earth breeds nothing feebler than a man.\n> So long as the gods grant him power, spring in his knees,\n> he thinks he will never suffer affliction down the years.\n> But then, when the happy gods bring on the long hard times,\n> bear them he must, against his will, and steel his heart.\n> Our lives, our mood and mind as we pass across the earth,\n> turn as the days turn...\n> as the father of men and gods makes each day dawn.\n> ~ (18.130--7)\n\n## Similes\n\nWhen Odysseus reaches Phaeacia after swimming for two days:\n\n> Then when Dawn with her lovely locks brought on\n> the third day, the wind fell in an instant,\n> all glazed to a dead calm, and Odysseus,\n> scanning sharply, raised high by a groundswell,\n> looked up and saw it---landfall, just ahead.\n> Joy ... warm as the joy that children feel\n> when they see their father's life dawn again,\n> one who's lain on a sickbed racked with torment,\n> wasting away, slowly, under some angry power's onslaught---\n> So warm, Odysseus' joy when he saw that shore, those trees,\n> as he swam on, anxious to plant his feet on solid ground again.\n> ~ (5.390--9)\n\nJust as the children worried about death for several days, so did Odysseus as he floated in the sea.\n\nLater in the story, when Odysseus has reached his home and is plotting his revenge, Homer gives us this great simile:\n\n> But he himself kept tossing, turning,\n> intent as a cook before some white-hot blazing fire\n> who rolls his sizzling sausage back and forth,\n> packed with fat and blood—keen to broil it quickly,\n> tossing, turning it, this way, that way—so he cast about:\n> how could he get these shameless suitors in his clutches,\n> one man facing a mob?\n> ~ (20.25--30)\n\n*All quotations are taken from Robert Fagle's excellent 1996 translation of the* Odyssey. *Line numbers are approximate.*\n" }, { "alpha_fraction": 0.7512356042861938, "alphanum_fraction": 0.7529588937759399, "avg_line_length": 42.15435028076172, "blob_id": "4486804e1e93ccdc77ad0892fb6a562c6bfe2e2c", "content_id": "48cea2c3ce1207dad775852bca76e0194c0d5a25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 92288, "license_type": "no_license", "max_line_length": 553, "num_lines": 2138, "path": "/documents/metamorphoses.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Ovid's _Metamorphoses_\ndescription: >\n Notes on Ovid's _Metamorphoses_\ntype: note\nstatus: incomplete\n---\n\n## Introduction\n\nThe *Metamorphoses* is Ovid's epic poem about change, which opens with these lines:\n\n> My mind leads me to speak now of forms changed\n> into new bodies: O gods above, inspire\n> this undertaking (which you've changed as well)\n> and guide my poem in its epic sweep\n> from the world's beginning to the present day.\n> ~\n\nThe poem is about 12,000 lines of hexameter verse in Latin, and is split into 15 books. It was first published in 8 AD.\n\nOvid focuses on telling the many stories using beautiful and light-hearted language. His audience was familiar with the stories he tells, so it is his approach to telling the stories that makes them as entertaining as they are.\n\n## Outline\n\n- Book I\n - Proem; forms changed into new bodies\n - The creation by organizing chaos\n - The four ages of man (gold, silver, bronze, iron)\n - War with the Giants\n - Jove recounts Lycaon's evil at the divine assembly\n - The great flood from above and below\n - Devout Deucalion and Pyrrha create more humans from mud\n - The earth generates life from the muck\n - Apollo kills the Python (and establishes the Pythian games)\n - Apollo brags to cupid; then woos and chases Daphne\n - Jove rapes Io then turns her into a cow\n - Pan pursues Syrinx; creates the reed pipe\n - Jove begs for Juno to relent and saves Io\n - Phaëthon sets out to prove he is the sun's son\n- Book II\n - Phaëthon's foolish wish; Apollo attempts to dissuade him\n - Phaëthon's doomed ride; burning heaven and earth; death\n - Phaëthon's sisters become Heliades (and their tears amber)\n - Cycnus turns into a bird as he despairs for Phaëthon\n - Apollo threatens to resign but relents\n - Jove rapes Callisto who births Arcas; turned into constellations\n - Crow warns raven not discloses infidelity; he is turned black\n - The prophetess Ocyrhoë over steps and is turned into a horse\n - Mercury steals cows and the tattletale old man\n - Mercury falls for Herse; Aglauros's her sister demands gold\n - The house of Envy; Envy infects Aglauros\n - Mercury turns Aglauros to stone\n - Jove becomes a beautiful bull to steal Europa\n- Book III\n - Jove rapes Europa\n - Cadmus kills the dragon; sows the teeth; founds Thebes\n - Actaeon sees Diana naked; transformed into a stag and is hunted\n - Jove impregnates Semele; Juno enacts revenge\n - The judgement of Tiresias\n - Echo is cursed by Jove; she falls for Narcissus\n - Narcissus falls for himself and wastes away\n - King Pentheus rejects Bacchus\n - Acoetes's story about Bacchus on the boat\n - Pentheus' mom and sisters kill him in a frenzy\n- Book IV\n - The daughers of Minyas refuse to worship Bacchus\n - Pyramus and Thisbe's accidental suicide\n - Mars and Venus are caught in infidelity\n - Venus's revenge against the Sun (via Leucothoë)\n - The fountain of Salmacis and Hermaphrodite\n - The daughters of Minyas transformed\n - Juno in Hades; revenge against Ino and Athamas (and Seleme)\n - Cadmus and Harmonia despair and become snakes\n - Perseus turns Atlas into a mountain\n - Perseus saves Andromeda from the water monster\n - Perseus recalls Medusa's demise\n- Book V\n - Persues slaughters the suitors\n - Minerva visits the Muses\n - The daughters of Pierus challenge the Muses\n - The rape and kidnap of Proserpina\n - Stellio is turned into a small lizard\n - Ceres searches; Arethusa helps; Appeal to Jove\n - Ascalphus spots Prserpina eating the pomegranate\n - The daughters of Acheloüs transformed into sirens\n - Prosperina's year divided between husband and mother\n - Arethusa's recounts Alpheus' pursuit; becomes fountain\n - Triptolemus scatters seeds; Lyncus of Scythia rejects them\n - The daughters of Pierus transformed into birds\n- Book VI\n - Arachne brags and beats Minerva, but is turned into a spider\n - Niobe brags and her seven sons then daughters are slayed\n - Latona births on Delos; turns unreasonable peasants to frogs\n - Marsyas is stripped\n - Pelops's ivory chip\n - Tereus marries Procne, rapes her sister Philomela, eats his son\n - Boreas steals Orithya as his bride\n- Book VII\n - Jason arrives; Medea's monologue; Jason wins her and the fleece\n - Medea's potion of youth for Aeson\n - Medea fools old Pelias's daughters into killing him\n - Story-filled flight of Medea; Jason's betrayal; Medea's revenge\n - Aegeus marries Medea, who nearly poisons Theseus; celebrations\n - King Minos builds a coalition; Aegina refuses to join\n - Cephalus of Athens requests aid from Aeacus of Aegina\n - The plague at Aegina\n - The Myrmidons prepare for war\n - Aurora rapes Cephalus; jealous, he unfairly tests Procris\n - The plague at Thebes\n - Cephalus accidentally kills Procris\n- Book VIII\n - Scylla betrays Nisus and her country to beautiful King Minos\n - Minos places the Minotaur in Daedulus's labyrinth\n - Ariadne helps Theseus kill it, who betrays then her\n - Daedalus constructs wings so he and Icarus can flee Crete\n - Daedalus jealously murders his talented nephew Perdix\n - Jealous Diana sends a boar; heroes gather and kill it\n - Meleager kills his uncles; his mother kills him\n - Theseus rests with river Acheloüs after the hunt\n - The Echinades and Perimele islands\n - Devout old Baucis and Philemon\n - Erysichthon cuts Ceres' tree; sells daughter; eats himself\n- Book IX\n - Acheloüs recounts wrestling with Hercules and losing his horn\n - Hercules save Deianira; Nessus' revenge by poisoned bloody cloak\n - Hercules' in pain; recounts deeds; climbs mountain\n - Hercules throws Lichas into the sea; he becomes an island\n - Hercules' death and apotheosis\n - Alcmena delivers Hercules; tricky servant turned into weasel\n - Dryope turned into a tree for picking berries\n - Iolaüs and Hebe's prophecy; Zeus blames fate\n - Byblis desires her brother Caunus is rejected\n - Iphis, professed a boy at birth, becomes one on wedding night\n- Book X\n - Orpheus attempts to save Eurydice from the underworld\n - The catalogue of trees\n - Cyparissus accidentally kills the stag; becomes a cypress\n - Songs of Orpheus about boys the gods love and lusting girls\n - Trojan Ganymede becomes Jove's cupbearer\n - Apollo's discuss kills his lover Hyacinthus\n - The Propoetides and the Cerastae\n - Pygmalion falls in love with his statue\n - Myrrha fools her father into sleeping with her\n - Venus falls in love with Myrrha's son Adonis\n - Hippomenes outraces Atalanta with Venus' apples\n - Adonis impaled by a boar; Venus morphs him into an anemone\n- Book XI\n - Orpheus murdered by the Maenads, who are then turned to tree\n - Midas save Silenus; golden touch; Pan vs Apollo; asses' ears\n - Apollo and Neptune build the Trojan walls for Laomedon\n - Zeus ordains that Peleus will marry Thetis; rape leads to Achilles\n - Apollo and Mercury rape Daedalion's daughter; Diana's jealousy\n - The wolf of Psamathe and Peleus' flock\n - Ceyx leaves against Alcyone wishes; drowns in an epic storm\n - The house of Sleep; Juno has Alcyone visited in a dream\n - Alcyone despairs; husbands floating body; both turned to birds\n - Aesacus chases the nymph to her death; cliff jump; becomes bird\n- Book XII\n - Iphigenia sacrificed to appease Diana and the winds\n - The house of Rumor\n - Achilles after failed spearing, strangles invincible Cycnus \n - Old Nestor tells stories\n - Caeneus raped; turned into a man\n - Lapiths fight the centaurs; Caeneus burried\n - Hericles kill Nestor's brothers\n - The death by Paris' arrow, and glory, of Achilles\n- Book XIII\n - Ajax then Ulysses assert their claim on Achilles' shield\n - Achille's ghost demands Hecuba's daughter\n - Hecuba's revenges her son; transformed to a dog\n - Aurora's son Memnon remembered with birds and dew\n - The daughters of Anius make grain; turned to birds\n - Precious goblet; the daughters of Orion\n - Polyphemus, Galatea, and Acis\n - Glaucas tells Scylla of magical grass morphing him into a fish\n- Book XIV\n - Glaucus asks Circe for help; she proposes; rejected, mutates Syclla\n - Aeneas wanders; Dido kills herself\n - The Sibyl helps Aeneas consult dead Anchises and tells her story\n - Macareus escapes Polyphemus and joins Aeneas' crew\n - Macareus recounts Circe's island with Ulysses\n - Women tells of Circe spurned, then transforming Picus\n - Impious Acmon transformed into a bird\n - Shepard turned into a bitter olive tree\n - Aeneas' ships transformed into water nymphs\n - The Heron rises from the ashes of Rome's enemies\n - The deificiation of Aeneas\n - Vertumnus pursues gardening Pomona while disguised\n - Anaxarete turns to stone after spurned Iphis suicides\n - Pomona accepts Vertumnus\n - A Roman spring\n - The deification of Romulus and his wife\n- Book XV\n - Numa, Rome's wise second king\n - Myscelus and the founding of Crotona\n - Pythagoras; the transmigration of souls; change everywhere\n - Egeria and Hippolytus\n - Tages; The spear of Romulus; Cipus\n - Apollo's son moves to Rome\n - The apotheosis of Julius Caesar\n - Ovid's enduring fame\n\n## Book I\n\nIn Ovid's creation account, like Hesiod's, the world begins in Chaos:\n\n> Before the seas and lands had been created,\n> before the sky that covers everything,\n> Nature displayed a single aspect only\n> throughout the cosmos; Chaos was its name,\n> a shapeless, unwrought mass of inert bulk\n> and nothing more, with the discordant seeds\n> of disconnected elements all heaped\n> together in anarchic disarray.\n> ~\n\nHowever, unlike Hesiod's account---which focuses on the sexual creative acts of the gods and their genealogies---Ovid's ignores the gods almost entirely.\n\nAnd unlike in the Genesis account, where God creates and separates, in Ovid matter existed in the beginning and only had to be separated:\n\n> Although the land and sea and air were present,\n> land was unstable, the sea unfit for swimming,\n> and air lacked light; shapes shifted constantly,\n> and all things were at odds with one another,\n> for in a single mass cold strove with warm,\n> wet was opposed to dry and soft to hard,\n> and weightlessness to matter having weight.\n> Some god (or kinder nature) settled this\n> dispute by separating earth from heaven,\n> and then by separating sea from earth\n> and fluid aether from the denser air;\n> and after these were separated out\n> and liberated from the primal heap,\n> he bound the disentangled elements\n> each in its place and all in harmony.\n> ~\n\nHe describes how the four winds are separated:\n\n> Nor did that world-creating god permit\n> the winds to roam ungoverned through the air;\n> for even now, with each of them in charge\n> of his own kingdom, and their blasts controlled,\n> they scarcely can be kept from shattering\n> the world, such is the discord between brothers.\n> Eurus went eastward, to the lands of Dawn,\n> the kingdoms of Arabia and Persia,\n> and to the mountain peaks that lie below\n> the morning's rays; and Zephyr took his place\n> on the western shores warmed by the setting sun.\n> The frozen north and Scythia were seized\n> by bristling Boreas; the lands opposite,\n> continually drenched by fog and rain,\n> are where the south wind, known as Auster, dwells.\n> ~\n\nAfter creation, Ovid describes the four ages of man. It is similar to Hesiod's ages of man in _Works and Days_. Here are the vices of the Iron Age:\n\n> Now men demand that the rich earth provide\n> more than the crops and sustenance it owes,\n> and piercing to the bowels of the earth,\n> the wealth long hidden in Stygian gloom\n> is excavated and induces evil;\n> for iron, which is harmful, and the more\n> pernicious gold (now first produced) create\n> grim warfare, which has need of both; now arms\n> are grasped in bloodstained hands; men live off plunder,\n> and guest has no protection from his host,\n> nor father-in-law from his daughter's husband,\n> and kindness between brothers is infrequent;\n> husband and wife both wish each other dead,\n> and wicked stepmothers concoct the bilious\n> poisons that turn their youthful victims pale;\n> a son goes to a soothsayer to learn\n> the date when he will change from heir to owner,\n> and piety lies vanquished here below.\n> Virgin Astraea, the last immortal left\n> on the bloodstained earth, withdraws from it in horror.\n> ~\n\nHere is part of Hesiod's description of the Iron Age:\n\n> Then fathers won't get along with their kids anymore,\n> Nor guests with their hosts, nor partner with partner,\n> And brothers won't be friends, the way they used to be.\n> Nobody'll honor their parents when they get old\n> But they'll curse them and give them a hard time,\n> Godless rascals, and never think about paying them back\n> For all the trouble it was to raise them.\n> ...\n> And then up to Olympos from the wide-pathed Earth,\n> lovely apportions wrapped in white veils,\n> off to join the Immortals, abandoning humans\n> There go Shame and Nemesis. And horrible suffering\n> Will be left for mortal men, and no defense against evil.\n> ~ Works and Days, 212--35\n\nBoth accounts imply new technologies, such as bronze, iron, and perhaps gold coinage, cause new evils. Both accounts look to an earlier, purer time. A time when the gods still lived on Earth.\n\nUnlike Hesiod, Ovid does does not include the aberrant Age of Heroes in between the bronze and iron ages. The Age of Heroes, unlike the other four, is not named after a metal (it is better than the previous age). I think Hesiod inserted it to meld an older tradition of the metal ages with the Greek's own tradition of the heroes of Thebes and the Trojan ware.\n\nIn response to the wickedness of the Iron Age, Jove calls for a great flood. Unlike the Babylonian Atrahasis flood myth---wherein the gods regret destroying their source of sacrifices---in Ovid, the gods have more foresight:\n\n> Some of the gods give voice to their approval\n> of Jove's words and aggravate his grumbling,\n> while others play their roles with mute assent.\n> Nevertheless, all of them were saddened\n> by the proposed destruction of the human race\n> and wondered what the future form of earth\n> could possibly be like, without men on it:\n> why, who would bring the incense to their altars?\n> ~\n\nOvid's description of the flood is powerful:\n\n> One takes to the hills, another to his skiff,\n> rowing where once he plowed the earth in rows,\n> while yet another sails above his grainfields,\n> or glimpses, far below, his sunken villa;\n> and here in the topmost branches of an elm\n> is someone casting out a fishing line;\n> an anchor grazes in a meadow's grasses,\n> or a curved keel sweeps above a vineyard,\n> and the seal's misshapen figure lies at rest\n> where the slender goats were lately fond of browsing.\n> The Nereids marvel at the sight of groves,\n> cities, and dwelling places all submerged,\n> while dolphins take possession of the woods\n> and shake the lofty branches of the oak\n> as they brush by. The wolf swims among sheep,\n> the tawny lion and the tiger both\n> are carried helplessly upon the waves;\n> the boar's great power, like a lightning bolt,\n> does not avail nor do the stag's swift limbs.\n> After his long search for a landing place,\n> the bird with weary wings collapses seaward.\n> Now unrestrained, the sea conceals the hills,\n> and strange new waves beat at the mountaintops;\n> the greater part are drowned beneath the waves,\n> while those spared drowning perish of starvation.\n> ~\n\nJove stops the flood when he realizes the two human survivors are devout. After describing how the floods recede, Ovid recounts what Deucalian, the last man alive, says to his wife Pyrrha:\n\n> \"O sister, wife, and only woman left,\n> you whom the bonds of race and family\n> and our marriage bed have joined to me,\n> we are now joined by our common perils---\n> for we two are the crowd that fills the lands\n> seen by the rising and the setting sun---\n> we two are all: the sea now has the others.\n> And our claim upon our lives is still\n> doubtful, for those storm clouds frighten me!\n> And how would you be feeling, my poor wretch,\n> if fate had snatched you from the flood without me?\n> How would you bear this terror all alone?\n> Who would console you in your unshared grief?\n> For trust me, if the sea had taken you,\n> I would have followed then, my wife; the sea\n> would not have taken one of us, but two.\"\n> ~\n\nWhile few stories in the _Metamorphoses_ are original, Ovid gives the old characters a new psychological depth; Deucalion's terror at being the only human alive is vivid example of this.\n\nOvid explains how life was biogenerated from the muck (an accepted theory at the time):\n\n> It is when heat and moisture join as one\n> that life is generated; all living forms\n> originate from these opposing sources\n> ~\n\nThe Python is among the forms that are generated, and Ovid tells the tale of Apollo killing the Python (and establishing the Pythian games to ensure memory of his great dead). Next, Ovid weaves in the first rape story of the _Metamorphoses_:\n\n> Daphne, the daughter of the river god\n> Peneus, was the first love of Apollo;\n> this happened not by chance, but by the cruel\n> outrage of Cupid; Phoebus, in the triumph\n> of his great victory against the Python,\n> observed him bending back his bow and said,\n> \"What are *you* doing with such manly arms,\n> lascivious boy? That bow befits *our* brawn,\n> wherewith we deal out wounds to savage beasts\n> and other mortal foes, unerringly:\n> just now with our innumerable arrows\n> we managed to lay low the mighty Python,\n> whose pestilential belly covered acres!\n> Content yourself with kindling love affairs\n> with your wee torch---and don't claim *our* glory!\"\n> The son of Venus answered him with this:\n> \"Your arrow, Phoebus, may strike everything;\n> mine will strike you: as animals to gods,\n> your glory is so much less than mine!\"\n> ~\n\nOvid's ability to weave one story into the next makes the Metamorphoses a joy to read. Here, Apollo's pride at defeating the Python causes him to foolishly boast, propelling us into the next story while also presenting a compelling example of overconfidence.\n\nDaphne escapes, but Io is less fortunate. Jove rapes her, and then he turns her into a cow to hide her from Juno, who, knowing as much, convinces him to hand over the cow. Juno places Argus to watch over her:\n\n> ... Argus, the watchman with a hundred eyes:\n> in strict rotation, his eyes slept in pairs,\n> while those that were not sleeping stayed on guard.\n> No matter where he stood, he looked at Io,\n> even when he had turned his back on her.\n> ~\n\nWhile a cow, Io's father makes an interesting comment:\n\n> \"Nor can I end this suffering by death;\n> it is a hurtful thing to be a god,\n> for the gates of death are firmly closed against me,\n> and our sorrows must go on forever.\"\n> ~\n\nJove can't bear to watch her pain, so he sends Mercury to kill Argus. Mercury lulls Argus to sleep with a tale:\n\n> Now Mercury was ready to continue [his story]\n> until he saw that Argus had succumbed,\n> for all his eyes had been closed down by sleep.\n> He silences himself and waves his wand\n> above those languid orbs to fix the spell.\n> Without delay he grasps the nodding head\n> and where it joins the neck, he severs it\n> with his curved blade and flings it bleeding down\n> the steep rock face, staining it with gore.\n> O Argus, you are fallen, and the light\n> in all your lamps is utterly put out:\n> one hundred eyes, one darkness all the same!\n> But Saturn's daughter rescued them and set\n> those eyes upon the feathers of her bird,\n> filling his tail with constellated gems.\n> ~\n\nMany of Ovid's stories explain the origin of species (especially of birds), rivers, springs, and constellations.\n\nNote that the tale that Mercury tells Argus is about the rape of Syrinx; rape is so common that the story puts Argus to sleep (although his wand may have helped too).\n\n## Book II\n\nThe tale of Phaëthon's doomed journey is one of my favourite in Ovid. Here is the description of Apollo's throne room:\n\n> Phoebus sat\n> In robes of purple high upon a throne\n> that glittered brilliantly with emeralds;\n> and in attendance on his left and right\n> stood Day and Month and Year and Century,\n> and all the Hours, evenly divided;\n> fresh Spring was there, adorned with floral crown,\n> and Summer, naked, bearing ripened grain,\n> and Autumn, stained from treading out her grapes,\n> and Winter with his grey and frosty locks.\n> ~\n\nWhen describing the burning Earth, Ovid's description alludes back to the _Iliad_ (20.60--67):\n\n> The soil cracks everywhere, and now the light\n> seeps to the underworld and terrifies\n> its ruler and his wife\n> ~\n\nAfter Zeus kills Phaëthon with lightening, Apollo mourns:\n\n> His miserable father, sick with grief,\n> drew his cloak up around his head in mourning;\n> for one whole day then, if the tale is true,\n> the sun was quite put out. The conflagration\n> (for the world was still ablaze) provided light;\n> that was a time some good came out of evil.\n> ~\n\nThe stories in the _Metamorphoses_ frequently refer to earlier incidents. For example:\n\n> When Apollo heard\n> the accusation brought against his lover,\n> the laurel resting on his brow slipped down;\n> in not as much time as it takes to tell,\n> his face, his lyre, his high color fell!\n> ~\n\nAlso, when Juno is departing from Tethys and Oceanus in Book II, she rides up on \"peacocks fitted out with Argus' eyes\"---another reference to book I.\n\nThe reference to the laurel tree refers back to the Daphne story in Book I---perhaps hinting that Apollo has already moved on to another lover.\n\nAlmost all of the stories end with physical transformations. I like how Ovid describes Ocyrhoë's transformation into a horse:\n\n> It seems my human form is being taken:\n> the thought of grass for dinner pleases me,\n> and open fields, where I can freely ride\n> as I become my relative---a mare!\n> Whole horse? But why? My father is but a centaur!\"\n> Her whining, waning, becomes whinnying,\n> as mind and speech both grow confused together,\n> and for a moment seemed a sound between\n> the noise a horse makes and a human word,\n> more like someone who imitates a horse,\n> before the sound turned clearly into neighing,\n> as she went on all fours through the tall grass.\n> Her fingers fused together and a single\n> band of light horn surrounded them, a hoof.\n> Her neck and mouth were both increased in size\n> and her long robe was turned into a tail\n> while the hair that used to stray across her neck\n> became a mane that fell on her right side;\n> made over now in voice and form completely,\n> this transformation gave her a new name.\n> ~\n\nThe story of Mercury stealing Apollo's cattle is also told in the Homeric Hymn to Dionysus. Ovid's version is shorter, and there are differences, but in both there is an old man who betrays the location of the cattle. (In Ovid's version the man is less devout and gives away the location confidentially and with little hesitation). It is intriguing to see the development of the story over several centuries.\n\nMinerva visits the goddess Envy to have her enact revenge on irreverent follower. The description of Envy is, even for Ovid, exceptionally vivid:\n\n> She headed straight to Envy's squalid quarters,\n> black with corruption, hidden deep within\n> a sunless valley where no breezes blow,\n> a sad and sluggish place, richly frigid,\n> where cheerful fires die upon the hearth\n> and fog that never lifts embraces all.\n> Arriving here, the warlike maiden stood\n> before the house (for heaven's law denied\n> her entrance) and with her spear tip rapped\n> upon the doors, which instantly flew open,\n> revealing Envy at her feast of snakes,\n> a fitting meal for her corrupted nature:\n> from such a sight, the goddess turned away.\n> The object of her visit sluggishly\n> arises from the ground where she'd been sitting,\n> leaving behind her interrupted dinner\n> of half-eaten reptiles. Stiffly she advances,\n> and when she sees the beauty of the goddess\n> and of her armor, she cannot help but groan,\n> and makes a face, and sighs a wretched sigh.\n> Then she grows pale, and her body shrivels up.\n> Her glance is sidewise and her teeth are black;\n> her nipples drip with poisonous green bile,\n> and venom from her dinner coats her tongue;\n> she only smiles at sight of another's grief,\n> nor does she know, disturbed by wakeful cares,\n> the benefits of slumber; when she beholds\n> another's joy, she falls into decay,\n> and rips down only to be ripped apart,\n> herself the punishment for being her.\n> ~\n\nAfter Io and Callisto, Jove pursues Europa:\n\n> Majestic power and erotic love\n> do not get on together very well,\n> nor do they linger long in the same place:\n> the father and the ruler of all gods,\n> who holds the lightning bolt in his right hand\n> and shakes the world when he but nods his head,\n> now relinquishes authority and power,\n> assuming the appearance of a bull\n> to mingle with the other cattle, lowing\n> as gorgeously he strolls in the new grass.\n> ~\n\n## Book III\n\nAfter Europa is stolen, her father \"in an action bother paternal and perverse\" demands that Cadmus, her brother, find her. Unable to, he decides to flee Tyre and found the new city of Boeotian Thebes. Incidentally, Herodotus believed that Cadmus brought the Phoenician alphabet to the Greeks (_The Histories_ 5.58).\n\nWhile founding Thebes, a great serpent kills many of Cadmus' men, and so he pursues and kills the serpent. Afterwards, Athena instructs him to sow the serpent's seeds into the ground.\n\n> And then, incredibly, the dull clods stir:\n> at first only the little tips of spears\n> are visible, emerging from the furrows,\n> but these, almost at once are followed by\n> the brightly painted waving crests of helmets\n> then shoulders, breasts, and arms heavy with weapons,\n> and finally a dense-packed mass of shields:\n> no different from what you will have seen\n> on feats days, in the theater, when the curtain\n> lifts from the pit, and the images of men\n> painted upon it seem to rise: heads first,\n> and then the rest of them, little by little,\n> drawn up in one unbroken wave until\n> the tiny figures stand erect onstage,\n> complete in all respects, from head to feet.\n> ~\n\nAnd then these men fight each other until Athena stops them. These so-called sown men (Spartoi) founded Thebes with Cadmus. I think this is the oddest story in the Metamorphoses, and I wonder what significance it had to the ancient Greeks.\n\n> Thebes has been founded now, and even though\n> an exile still, you might seem fortunate\n> in having Mars and Venus as your in-laws,\n> Cadmus; nor is this all, for in addition\n> are offspring worthy of your noble wife,\n> your sons and daughters, the pledges of your love,\n> and grandsons too, already grown to manhood.\n> But \"fortunate\"? A judgment best reserved\n> for a man's last day: call no one blest, until\n> he dies and the last rites are said for him.\n> ~\n\nThis reasoning is pervasive in Herodotus.\n\nActaeon stumbles across the virgin goddess Diana, who spitefully turns him into a stag. He is subsequently torn to pieces by his own pack of hunting dogs. (In the _Epic of Gilgamesh_, when Gilgamesh is rejecting Ishtar's love entreaties, he mentions how she turned a prior lover into a wolf who was then chased by his own hunting dogs.)\n\nActaeon is caught, and his dogs tear him to pieces.\n\n> And it is said\n> he did not die until his countless wounds\n> had satisfied Diana's awful wrath.\n> Folks were divided: there were those who found\n> the goddess's actions cruel and unjust,\n> while others considered them appropriate\n> to the defense of her austere virginity.\n> As usual, both parties had their reasons.\n> ~\n\nThroughout the _Metamorphoses_ Ovid playfully questions the god's morals, as in this quote.\n\nAfter the Actaeon story, Jove falls for Semele---Cadmus' daughter. Semele becomes pregnant and Juno, to protect her honor, tricks Semele into requesting Jove make love to her the way he does to Juno. Unbeknownst to Semele, this will kill her. Juno takes the form of Semele's nurse.\n\n> A long, inveigling chat of this and that,\n> until Jove's name came up. Nurse sighted and said,\n> \"I *hope* he's Jupiter---although I doubt it:\n> the divinity plea? An all-to-common ploy\n> among seducers. Suppose he is, though:\n> make him provide assurance of his love;\n> if he's the real thing, ask him to put on\n> all of the trappings of his high office\n> and embrace you, showing such almighty splendor\n> as when he is received by Lady Juno.\"\n> ~\n\n(It is difficult to imagine a woman being seduced by a man claiming to be a god.)\n\nAfter Juno gets her revenge on Semele, her next victim is Tiresias. Tiresias is blinded for agreeing with Jove that women enjoy sex more than men. Tiresias is then blinded by Juno, but Jove (since \"one god can't undo another's doing\") gives him the gift of prophecy. Jove seems to enjoy thwarting Juno's punishments---consider also the Callisto story.\n\nTiresias is a recurring character in the Greek tragedies.\n\nTiresias' first prediction is that Narcissus, if he knows himself, will not live to old age. The meaning of this was unclear, until Narcissus falls in love with himself. Then Tiresias becomes famous.\n\n> \"But *now* I get it! *I* am that other one!\n> I've finally seen through my own image!\n> I burn with love for---*me*! The spark I kindle\n> is the torch I carry: whatever can I do?\n> Am I the favor-seeker, or the favor sought?\n> \"Why seek at all, when all that I desire\n> is mine already? Riches in such abundance\n> that I've been left completely without means!\"\n> ~\n\nOvid paints a compelling, yet humorous, picture of obsession with his description of Narcissus' death:\n\n> His last words were directed to the pool:\n> \"Alas, dear boy, whom I have vainly cherished!\"\n> Those words returned to him again, and when\n> he cried \"Farewell!\" \"*Farewell!*\" cried Echo back.\n> His weary head sank to the grass; death closed\n> those eyes transfixed once by their master's beauty,\n> but on the ferry ride across the Styx,\n> his gaze into its current did not waver.\n> ~\n\nAcoetes' story is similar to the seventh Homeric Hymn to Dionysus.\n\n## Book IV\n\nMost of Book IV is a sequence of stories told by the Minyas daughters, who refuse to join Bacchus' festival.\n\nThe first of their stories, of the suicide of Pyramus and Thisbe, is the original inspiration that lead Shakespeare's Romeo and Juliet (with a few other versions in between). Pyramus' suicide is described with an epic simile:\n\n> \"He carries Thisbe's cloak to the tree of their pact,\n> and presses tears and kisses on the fabric.\n> 'Drink *my* blood now,' he says, drawing his sword,\n> and thrusting it at once in his own guts:\n> a fatal blow; dying, he draws the blade\n> out of his burning wound, and his lifeblood\n> follows it, jetting high into the air,\n> as he lies on his back upon the ground.\n> It was as when a water pipe is ruptured\n> where the lead has rotted, and it springs a leak:\n> a column of water goes hissing through the hole\n> and parts the air with its pulsating thrusts;\n> splashed with his gore, the tree's pale fruit grow dark;\n> blood soaks its roots and surges up to dye\n> the hanging berries purple with its color.\"\n> ~\n\nThe two lovers planned to meet at the tomb of Ninus, who was the king of Assyria and husband of Semiramis. Semiramis was a legendary queen of Assyria. She is often associated with the historical queen Sammurāmat who ruled from 811 - 808 BC.\n\nThe story of Hermaphroditus is a rare example of a woman (sort of) raping a man. The description includes a progression of similes:\n\n> \"'I've won, the boy is mine!'\n> the nymph cries out, and tearing off her clothing,\n> she dives into the middle of the pool,\n> and though he fights her, holds him in her clutches,\n> seizing the kisses he is loath to yield;\n> her hands surprise him, coming from below,\n> caressing that reluctant breast of his---\n> although he strives to tear himself away,\n> the nymph---now here, now there---surrounds her prey,\n> just as the serpent wraps herself around\n> the eagle when he grasps her in his talons\n> and takes her up: dangling from his claws,\n> she twines herself between his head and feet\n> and with her tail, immobilizes him;\n> or just as ivy winds around a tree,\n> and as the octopus beneath the sea\n> securely binds the prey that it has captured\n> with tentacles sent out in all directions;\n> yet still the boy denies the nymph her bliss'\"\n> ~\n\nA description of the underworld:\n\n> There are a thousand ways into this city,\n> and open gates on all sides; as the ocean\n> receives the rivers from around the world,\n> so this place gathers in all mortal souls,\n> and never fills, however many come.\n> Here bloodless, boneless, bodiless shades stray:\n> some make their way to the forum; others seek\n> the palace of the ruler of the dead,\n> or take up once again the crafts they lived by.\n> ~\n\nJuno's frustrated jealous rage fills much of the first four books of Ovid. She eventually drives Cadmus and Harmonia into ruin. Although Juno caused much of their suffering, the story of their transformation (which has may favourite imagery in the book) implies that it was Cadmus' killing of the serpent that lead to his woes:\n\n> \"Was it a sacred serpent that I speared,\"\n> asked Cadmus, \"when, newly come from Sidon,\n> I sprinkled the viper's teeth upon the ground,\n> and seeded a new crop of human beings?\n> If that is what the gods have been avenging\n> by their unwavering wrath for all these years,\n> why then, I pray that I might be extended\n> into a serpent with a gut-like shape---\"\n> And as he said it he became a serpent\n> with a gut-like shape. At once he felt the scales\n> begin to grow out on his thickened skin,\n> and his dark body lighten up with patches\n> of iridescent blue; he fell upon his breast,\n> and his two legs were blended into one,\n> which, gradually lengthening, became\n> an elegant and sharply pointed tail.\n> His arms remained unchanged; he held them out,\n> and as the tears coursed down his cheeks (which were\n> still---for the moment---human), he exclaimed,\n> \"Come closer to me, O most wretched wife,\n> and while there is still something left of me,\n> before I am entirely transformed\n> to serpent, touch me, take these hands in yours!\"\n> He would have said much more, but suddenly\n> the tip of his tongue divided into two,\n> and words no longer would obey his wishes,\n> so that whenever he tried to complain\n> or grieve, he hissed, and could not manage more,\n> for he had been left with no other voice.\n> Now striking her bare breast, his wife cries out,\n> \"Cadmus! Stay as you are! Put off these strange\n> shapes now possessing you, unfortunate man!\n> Cadmus, what's happening? Where are your feet?\n> Your face? Complexion? Even as I speak,\n> where is the rest of you! Heavenly beings,\n> will you not also turn me to a snake?\"\n> The creature's tongue flicked lightly over her lips,\n> and he slipped in between her cherished breasts\n> as though he were familiar with the place,\n> embraced her, and slid right around her neck.\n> Those of his companions who were present\n> were horrified, but she just calmly stroked\n> the smooth, sleek neck of the crested dragon,\n> and at once there were two serpents intertwined,\n> who presently went crawling off and found\n> a hiding place within a nearby grove.\n> ~\n\nPerseus turns Atlas into a mountain:\n\n> Atlas became a mountain just as large\n> as the man had been. His hair and beard became\n> a forest, and his arms and shoulders turned\n> into adjacent ridges; his head was now\n> the mountain's summit and his bones were rock.\n> Each part grew to extraordinary size\n> (as you immortals had ordained), until\n> the weight of heaven rested on his shoulders.\n> ~\n\n## Book V\n\nPerseus slays many men at his wedding to Andromeda, when her prior betrothed casts a spear at him. The scene seems to contrast and slyly tease Homer's epic death scenes. One of my favourite is:\n\n> Pedasus, grinning,\n> saw how he kept himself and his instrument\n> out of harm's way, and shouted to him, \"Sing\n> the remainder of your song to the shades below,\"\n> lodging his shaft above the bard's left eye;\n> and as he fell, his dying fingers struck\n> the lyre's strings, and on that plaintive note\n> the poet and his song came to an end.\n> ~\n\nAfter describing dying men, one after another, Ovid says:\n\n> It really would take far too long to name\n> the ordinary soldiers\n> ~\n\nMinerva visits the nine muses, who tell of the nine sisters who challenged their supremacy and of the contest between them, and retell the story by which they won the contest. As part of this story, Venus makes the following comment:\n\n> \"'\"My son [Cupid], my sword, my strong right arm and source of my power,\n> take up that weapon by which all your victims are vanquished\n> and send your swift arrows into the breast of the deity\n> to whom the last part of the threefold realm was allotted.\n> You govern the gods and their ruler; you rule the defeated\n> gods of the ocean and govern the one who rules them, too;\n> why give up on the dead, when we can extend our empire\n> into their realm? A third part of the world is involved here!\n> And yet the celestial gods spurn our forbearance,\n> and the prestige of Love is diminished, even as mine is.\n> Do you not see how Athena and huntress Diana\n> have both taken leave of me? The virgin daughter of Ceres\n> desires to do likewise---and will, if we let her!\n> But if you take pride in our alliance, advance it\n> by joining her to her uncle!\"'\"\n> ~\n\nVenus' impulse leads to the rape of Persephone and (so they say) the rotation of the seasons.\n\n## Book VI\n\nThis book continues the theme of divine revenge:\n\n> \"To praise is insufficient,\" she [Minerva] reflected;\n> \"we will be praised---and we will not permit\n> those who belittle our divinity\n> to go unpunished!\"\n> ~\n\nMinerva contests the Arachne---an expert weaver. Although she loses, she turns her competitor into a spider.\n\nThis simile from their contest is superb:\n\n> Into their fabrics they weave purple threads\n> of Tyrian dye, and place beside them shades\n> that lighten imperceptibly from these;\n> as when a storm ends and the sun comes out,\n> a rainbow's arch illuminates the sky;\n> although a thousand colors shine in it,\n> they eye cannot say where one color ends\n> and another starts, so gradual the verging;\n> there in the middle, the colors look the same,\n> while, at the edges, they seem different.\n> ~\n\nThe brief stories of Marsyas the Satyr and Pelops (Tantalus' son) feel undeveloped and seem to be included because merely due the transformations involved.\n\nThe story of Tereus, the marauder from Thrace, and the Athenian sister-princesses, Procne and Philomela, is disturbing. Procne is given in marriage to Tereus, to prevent the defeat of Athens. After a few years, she asks her wicked husband to retrieve her sister---but he lusts after her:\n\n> And now delay was unendurable:\n> he eagerly repeated Procne's speech,\n> and raised his own desires under hers.\n> Love lent him eloquence, and when he seemed\n> to go beyond the mandate he'd been given,\n> he said that this was merely Procne's wish,\n> and added tears, as though they too were part\n> of his commission. By the gods above,\n> what utter blindness dwells in human hearts!\n> Here Tereus achieves a reputation\n> for piety while plotting wickedness,\n> and criminal behavior wins him praise!\n> ~\n\nAfter trapping Philomela in a house in the woods and raping her, she cries:\n\n> \"Nevertheless, if the gods are watching this,\n> if heavenly power means anything at all,\n> if, with my honor, all has not been lost,\n> somehow or other I will punish you;\n> I'll cast aside my modesty and speak\n> of what you've done; if I escape this place,\n> I'll go among the people with my tale;\n> imprisoned here, my voice will fill the trees\n> and wring great sobs of grief from senseless rocks!\n> Heaven will hear me, and what gods there are,\n> _if_ there are any gods in all of heaven!\"\n> Such words provoke the savage tyrant's wrath\n> and fear in equal measure\n> ~\n\nHe proceeds to cut out her tongue.\n\n## Book VII\n\nBook VII begins with the story of Jason and the Golden Fleece.\n\nMedea's monologues are brilliant.\n\n> \"All your resistance is in vain, Medea;\n> what god opposes you, I do not know---\n> I wonder if this isn't love, so called,\n> or something rather like it---for why else\n> would these ordeals imposed upon the strangers\n> by my own father seem too harsh to me?\n> Because they _are_! Why do I fear that one\n> whom I have only just now seen will die?\n> What is the power that can cause such fear?\n> There is a fire in your untried heart,\n> poor wretched girl! Dislodge it if you can!\n> I'd act more sanely, if I only could,\n> but this new power overwhelms my will;\n> reason advises this, and passion, that;\n> I see the better way, and I approve it,\n> while I pursue the worse.\"\n> ~\n\nThese lines remind me of Paul's letter to the Romans, where he says:\n\n> I do not understand my own actions. For I do not do what I want, but I do the very thing I hate. Now if I do what I do not want, I agree that the law is good. But in fact it is no longer I that do it, but sin that dwells within me. For I know that nothing good dwells within me, that is, in my flesh. I can will what is right, but I cannot do it. For I do not do the good I want, but the evil I do not want is what I do. Now if I do what I do not want, it is no longer I that do it, but sin that dwells within me.\n> - (Romans 7.15--20)\n\nIn Medea's speech, we hear her grasp onto a small reason to wish Jason well, and slowly expand and rationalize her thoughts. She continues going back and forth. At some point, she weighs whether she can trust Jason, even if she betrays her father:\n\n> \"Will I betray the kingdom of my father,\n> only to have the stranger whom I save\n> set sail without me for another's bed,\n> leaving Medea to her punishment?\n> If he could do that, leave me for another,\n> let the ingrate die! But no: that isn't in him,\n> not in his face, not in his noble spirit,\n> not in a man as beautiful as he,\n> that I should fear duplicity from him,\n> or his neglecting what I am deserved.\"\n> ~\n\nThese lines may ironically refer to Euripides' play, _Medea_. Note that beauty and goodness are thought to be correlated.\n\nThe virgin princess weaves back and forth, but, upon seeing Jason again, decides to betray her family and flee with him.\n\n> Here she was resolute, and her impulsive\n> ardor would appear to be extinguished---\n> but broke out once again at sight of Jason:\n> her cheeks reddened, and a suffusing glow\n> spread across her countenance completely,\n> as when a spark that has been hidden under\n> a crust of ash is nourished by a breeze\n> and comes to life again as it's stirred up,\n> regaining all the vigor it once had;\n> just so her smoldering love, which you'd have thought\n> was almost out, came blazing up anew,\n> to see the young man standing in her presence,\n> and---as it happened---looking even better\n> than usual. You would have understood\n> and pardoned her for her infatuation.\n> ~\n\nAfter returning to Greece, Jason begs Medea to give his father a potion to lengthen his life. She complies:\n\n> After nine days and nights had seen Medea\n> in her dragon-drive chariot, traversing\n> the skies above those regions, she returned\n> to her own home; her reptiles had been touched\n> only by the _odors_ of those herbs,\n> and yet they shed the skins of their old age!\n> ~\n\nOvid pokes fun at readers by not including the full list of ingredients:\n\n> When, with these,\n> and with a thousand other such ingredients\n> (whose names we needn't bother mentioning),\n> the miracle to come had been arranged,\n> the foreign woman took a long-dead branch\n> from a fruitful olive tree and stirred her pot,\n> mixing it thoroughly from top to bottom.\n> But look! Almost at once, that stick turned green,\n> and just a short time later put out leaves,\n> and suddenly was loaded down with fruit!\n> ~\n\nAs Medea flies from this gruesome scene, Ovid lists transformation stories. Then, in a few succinct lines, he tells the story of Jason's betrayal and Medea's revenge:\n\n> But after the new bride that Jason took\n> was poisoned by the old wife he forsook,\n> and fisherfolk off Corinth glimpsed through haze\n> the ruined palace of the king ablaze,\n> the blade that dripped with her own children's gore\n> enraged their father, whom she fled before,\n> her fatal vengeance leaving all undone!\n> ~\n\nAfter Aegeus discovers his unknown son, Theseus, there is a big celebration. Then Ovid gives us this pithy line:\n\n> And yet, no joy is ever unalloyed,\n> and worry worms its way into delight\n> ~\n\nAegeus is worried about King Minos, who wants to revenge his dead son. Fortuneatly, Athens has a loyal ally ruling over Aegina. Cephalus seeks aid, and king Aeacus of Aegina recounts the story of the plague:\n\n> \"At first the animals\n> alone succumbed: the plague confined itself\n> to dogs, birds, sheep, cattle, and wild beasts:\n> the luckless plowman is quite stunned to see\n> his healthy bulls collapsing at their work,\n> falling in midfurrow; woolly flocks\n> give a few feeble bleats, then, without help,\n> shed their thick coats, grow wasted and soon die;\n> the stall-bound horse, once famous for his speed,\n> but now unworthy of his victories,\n> ignores his former honors, whinnying\n> as death prepares to scratch him from the race.\n> The boar does not remember how to rage,\n> nor the deer to trust in swiftness, nor the bear\n> to cull the great herds with his fierce attacks;\n> a languor seizes all; in woods, in fields,\n> along the roads, the fetid corpses lie\n> until the air is blighted with the stench.\n> I'll tell you something quite astonishing:\n> the greedy dogs and vultures---even wolves!---\n> left them untouched; those bodies fell apart,\n> sickening us with their apalling odor\n> and spreading foul contagion everywhere.\n> The plague, grown stronger, now advances on\n> the wretched country folk, then rules within\n> the walls of the great city. Its first symptom\n> is a fierce burning in the viscera,\n> the hidden fire indicated by\n> a flushed complexion, pain in drawing breath;\n> the patient's roughened tongue swells up with fever,\n> and lips that have been parched by the hot winds\n> gape widely, snatching at the torpid air---\n> no bed nor covering is bearable;\n> they fling themselves facedown upon the ground\n> to cool their bodies off; but no: the heat\n> of their poor bodies warms the earth instead!\n> Ungovernable plague! The doctors die,\n> their arts a harm to their practitioners,\n> and those who are the closest to the sick,\n> who serve most faithfully, are first to fall!\n> ...\n> Can you imagine what my feelings were?\n> Like those of anyone in such a case:\n> I hated life and longed to share the fate\n> of my own kind, for everywhere I looked\n> the dead were strewn in heaps, without distinction,\n> like rotten apples shaken from the bough\n> or acorns that the wind strips from an oak.\n> ...\n> Some freed themselves from the fear they had of death\n> by taking their own lives---summoning Fate\n> even as Fate prepared to summon them.\n> No longer were the bodies of the dead\n> carried in processions from the city\n> for burial with the customary rites:\n> no gates were wide enough for such a throng.\n> Either they lay unburied on the ground\n> or, without services, were stacked and burned;\n> and now there are no honors for the dead;\n> dying, men struggle over scraps of wood,\n> and are cremated with a stranger's flame.\n> With none to mourn them, unlamented souls\n> of parents and their children, the young, the old,\n> wander about, their journey uncompleted:\n> no wood is left to burn their bodies now,\n> no bit of land where they may be interred.\"\n> ~\n\n## Book VIII\n\nThe book opens with the story of Scylla, who like Medea, betrays her family and country after falling in love with a man:\n\n> \"Love has led me\n> into this betrayal; I am Scylla,\n> the daughter of King Nisus; I surrender\n> myself, my nation, and my gods as well,\n> and seek no other recompense but you;\n> receive this pledge that guarantees my love,\n> this purple lock---which is no lock at all,\n> but my father's head!\" She stretched out her foul hand\n> with the proffered gift as Minos shrank away,\n> shocked by the sight of this unholy act:\n> \"Shame of the age,\" he said, \"may the gods forbid you\n> their kingdom, and may land and sea deny you!\n> Be sure that I will never let so vile\n> a monster into Crete\"\n> ~\n\nIt is hard to imagine a woman falling in love with a man she hasn't met and cutting her head off. Ovid's portrayal of women's sexual passion feels like pornographic male fantasy.\n\nIronically, when Minos returns to Crete, he realizes his wife had slept with a bull, letting a vile monster onto Crete.\n\n> The scandal of his family had grown\n> past all concealment; now the mother's foul\n> adultery was proven by the strange\n> form of the Minotaur, half man, half bull.\n> Minos determined to remove the cause\n> of this opprobrium from his abode,\n> enclosing it within a labyrinth\n> devised and built by Daedalus, the most\n> distinguished of all living architects,\n> who framed confusion and seduced the eye\n> into a maze of wandering passages.\n> Not otherwise than when Maeander pays\n> his liquid games in the Phrygian fields\n> and flowing back and forth uncertainly,\n> observes its own waves bearing down on it,\n> and sends its doubtful waters on their ways\n> back to their source of down to the open sea:\n> so Daedalus provided numberless\n> confusing corridors and was himself\n> just barely able to find his way out,\n> so utterly deceitful was that place.\n> ~\n\nDaedalus builds wings and flees Crete with his son Icarus, who famously dies because he flies too close to the sun. I love these lines, describing bystanders watching:\n\n> Some fisherman whose line jerks with his catch,\n> some idle shepherd leaning on his crook,\n> some plowman at his plow, looks up and sees\n> something astonishing, and thinks them gods,\n> who have the power to pass through the air.\n> ~\n\nDaedalus is brilliant, but he also demonstrates terrible academic jealousy:\n\n> For, as it happened, the inventor's sister,\n> quite unaware of what the Fates intended,\n> entrusted her own son to his instruction,\n> a likely lad of twelve, who had a mind\n> with the capacity for principles and precepts;\n> and from his observation of the spines\n> of fishes, which he'd taken as his model,\n> incised a row of teeth in an iron strip\n> and thereby managed to invent the saw.\n> Likewise, he was the first to bind two arms\n> of iron at a joint, so one is fixed\n> and the other, as it moves, inscribes a circle.\n> Daedalus envied him, and headlong hurled\n> this lad of precepts from a precipice,\n> the steep acropolis Minerva loves,\n> and lying, said the lad had slipped and fallen.\n> ~\n\nWhen the apostle Paul visits Athens, he stood in front of the Areopagus, and said \"Athenians, I see how extremely religious you are in every way. For as I went through the city and looked carefully at the objects of your worship, I found among them an altar with the inscription, 'To an unknown god.'\" I wonder if pagans worshiped the unknown god to ensure they aren't forgetting to sacrifice to a god they are not aware of. The jealous anger of the pagan gods is common, here is a nice example:\n\n> Commencing with the rural deities,\n> the gods all got the honors they desired;\n> only Diana's altar was ignored,\n> and left, they say, without a gift of incense.\n> Even the gods may be provoked to anger!\n> \"We will not let them get away with this,\"\n> Diana said, \"Dishonored we may be;\n> but none will say that we were unavenged!\"\n> And the spurned goddess sent her vengeful boar\n> straightway onto the fields of Calydon:\n> a beat as great as the bulls of Epirus,\n> and mightier than those of Sicily,\n> with blood and fire shining from his eyes\n> and a neck stiff with bristles just like spear shafts;\n> and as his chest heaved with his grating breast,\n> his heavy shoulders dripped with seething spume;\n> in length his tusks were like an elephant's,\n> and bolts of lightning issued from his mouth,\n> and when he exhaled, trees turned black and died.\n> ~\n\nA band of heroes, including Nestor from the _Iliad_ and Jason of the Golden Fleece, sets out the kill the boar. A few heroes die, and after a fortunate spear ends its life, the heroes bicker over the honors of the dead. One tragedy leads to another, and before long Diana has completed her revenge. Ovid says:\n\n> Not even if some god had given me\n> a hundred mouths, each fitted with a tongue,\n> and genius suitable to the occasion,\n> and all of Helicon for inspiration,\n> not even then would I be able to\n> describe the sad fate of his wretched sisters,\n> who, careless of decorum, beat their breasts,\n> and while his corpse was still displayed among them,\n> caressed him constantly and gave him kisses,\n> and even kissed the bier he was laid out on\n> ~\n\nSome of the heroes, upon their journey home from the hunt, are stopped at the overflowing river Acheloüs. They tell stories with the river to pass the time, including the story of some naiads turned into islands and my favourite story of Baucis and Philemon. Two gods in disguise look for a home to stay in. Many turn them down, but the old couple lets them in and, though pour, try to make them comfortable. The scene seems archetypal---disguised gods testing the devout (consider Abraham being visited by divine messengers).\n\n> \"The gods reclined. And with her skirts hitched up,\n> the trembling old lady set the table,\n> correcting its imbalance with a potsherd\n> slipped underneath the shortest of its legs;\n> and when the table had been stabilized,\n> she scrubbed its surface clean with fragrant mint.\"\n> ~\n\nThe visitors magically refill the winebowl, and the couple realize they are gods.\n\n> \"They had a single goose, the guardian\n> of their small villa, whom they now prepared\n> to sacrifice to their immortal guests;\n> his swiftness, though, left the old pair exhausted.\n> Time after time, he slipped out of their grasp,\n> and then, it seemed, sought refuge with the gods,\n> who would not let the couple do him in\"\n> ~\n\nThe small expressions Ovid uses, like \"the guardian of their small villa,\" let one imagine the scene with so few words.\n\nThe gods destroy the town (similar to Sodom and Gomorrah), and ask the old couple what reward they want.\n\n> \"'We ask to be allowed to guard your temple\n> as its priests, and, since we have lived together\n> so many years in harmony, we ask\n> that the same hour take us both together,\n> and that I should not live to see her tomb\n> nor she survive to bury me in min.'\"\n> ~\n\nAcheloüs tells the story of Erysichton, who chopped down a sacred tree of Ceres, who soon sent famine to enact her revenge. Erysichton was so hungry he sold his daughter into slavery and eventually ate himself to death:\n\n> \"But when at last his illness had consumed\n> all that she brought him, and he still craved more,\n> the wretched man began to tear his limbs\n> asunder, mangling them in his maw,\n> and fed his body as he shrank away.\"\n> ~\n\n## Book IX\n\nHercules' contempt of death, and the Greek ideal:\n\n> And as the eager flames began to spread,\n> you draped the pelt of the Nemean lion\n> over the top, and pillowing your head\n> upon your club, you lay there at your ease,\n> not otherwise than as you would have been\n> reclining at a banquet, flower-wreathed,\n> with wine to drink from cups always refilled.\n> Now spreading out in every direction,\n> the crackling flames came after Hercules,\n> whose carefree limbs received them with contempt.\n> ~\n\nSince its lines contain little advice or philosophical insight, I read the _Metamorphoses_ primarily for their beauty and to know the myths referenced so often in paintings and later literature. Ovid's psychological portrayals of tempted individuals, while maybe not realistic, have made me more empathetic. Media, Scylla, Byblis, and Myrrah---all lusting women, perhaps a weird obsession of Ovid---in particular are interesting. Here are a few quotes from the story of Byblis, who fell in love with her brother, demonstrating how her passion developed:\n\n> Her feelings for him gradually changed,\n> and not for the better; when she visited\n> her brother, she was elegantly dressed,\n> and anxious that he find her beautiful,\n> and envious of those who seemed more lovely.\n> She was, as yet, unconscious of her feelings,\n> and offered up no prayers for satisfaction,\n> but burned with inner fire, nonetheless.\n> She calls him \"Master\" now, and now detests\n> the thought that they are siblings, and prefers\n> that he should call her \"Byblis\" and not \"Sister.\"\n> ~\n\n> \"But even if I keep them out of mind,\n> there is no wrong in _dreaming_ of such things\n> as often as I want to, in my sleep!\n> There are no witnesses to our dreams,\n> and they provide a pleasure almost real!\n> \"O Cupid and sweet Venus, what great joys\n> were given me! And how real they seemed!\n> My marrow melted as I lay asleep!\n> How pleasing to remember! But how brief\n> those pleasures were--the night, with breakneck speed,\n> snatched them away, when they had just begun!\"\n> ~\n\n> \"The sons of Aeolus were not afraid\n> to sleep with their sisters! How do I know this,\n> and why have I come up with this example?\n> Where is this leading me? Depart, indecent thoughts,\n> and let me love my brother not at all,\n> unless my move is sisterly and lawful!\"\n> ~\n\nWhen her brother avoids her advances by fleeing to found a colony, Byblis goes insane and, crying in despair, is morphed into a spring.\n\nThe last story in this chapter is relevant for me, since my wife is pregant with a baby girl:\n\n> For, once upon a time, there lived in Phaestus\n> a freeborn plebeian named Ligdus, who\n> was otherwise unknown and undistinguished,\n> with no more property than fame or status,\n> and yet devout, and blameless in his life.\n> His wife was pregnant. When her time had come,\n> he gave her his instructions with these words:\n> \"There are two things I pray to heaven for\n> on your account: an easy birth and a son.\n> The other fate is much too burdensome,\n> for daughters need what Fortune has denied us:\n> a dowry. Therefore---and may God prevent\n> this happening, but if, by chance, it does\n> and you should be delivered of a girl,\n> unwillingly I order this, and beg\n> pardon for my impiety---_But let it die!_\"\n> He spoke, and tears profusely bathed the cheeks\n> of the instructor and instructed both.\n> Telethusa continued to implore\n> her husband, praying him not to confine\n> their hopes so narrowly---to no avail,\n> for he would not be moved from his decision.\n> Now scarcely able to endure the weight\n> of her womb's burden, as she lay in bed\n> at midnight, a dream-vision came to her:\n> the goddess Io stood (or seemed to sand)\n> before her troubled bed, accompanied\n> with solemn pomp by her mysteries.\n> ~\n\nThe relationship between man and woman is, as is usual, unequal.\n\nInfanticide has apparently been practiced by many, if not most, cultures. In Roman society, the man of the household would inspect the baby. Sometimes it would be killed if thought to be illegitimate or, as in this story, they couldn't afford a girl. (How far has our ethics progressed---probably due mostly to technological advances!)\n\nAs Ovid usually does, he portrays Ligdus in a good light and gives the reader some understanding of how he came to his decision.\n\nIo informs Telthusa to keep the baby, even if it is a girl. It is, and they keep this fact a secret. She grows up, and is arranged to be married! She falls in love with the girl, a family friend. The story is amazing:\n\n> And scarcely holding back her tears, she cries,\n> \"Oh, what will be the end reserved for Iphis,\n> gripped by a strange and monstrous passion known\n> to no one else? If the gods had wished to spare me,\n> they should have; if they wanted to destroy me,\n> they should have given me a natural affliction.\n> Cows do not burn for cows, nor mares for mares;\n> the ram will have his sheep, the stag his does,\n> and birds will do the same when they assemble;\n> there are no animals whose females lust\n> for other females! I wish that I were dead!\n> That Crete might bring forth monsters of all kinds,\n> Queen Pasiphaë was taken by a bull,\n> yet even _that_ was male-and-female passion!\n> My love is much less rational than hers,\n> to tell the truth. At least she had the hope\n> of satisfaction, taking in the bull\n> through guile, and in the image of a cow,\n> thereby deceiving the adulterer!\n> If every form of ingenuity\n> were gathered here from all around the world,\n> if Daedalus flew back on waxen wings,\n> what could he do? Could all his learnèd arts\n> transform me from a girl into a boy?\n> Or could _you_ change into a boy, Ianthe?\n> ~\n\nApparently, while male-male homosexuality was common in ancient Rome, female-female homosexuality was not.\n\nIo turned Iphis into a boy at the last minute.\n\n## Book X\n\nOvid economically relays the death of Orpheus' wife, and how he descends to the underworld to ask for her back. After playing a song:\n\n> These words, accompanied on the plucked strings,\n> so moved the bloodless spirits that they wept;\n> Tantalus did not seek the receding water,\n> and on his wheel lay Ixion, astounded;\n> the birds let go the liver, and the daughters\n> of Danaüs were resting by their urns,\n> while you, O Sisyphus, sat on your stone.\n> ~\n\nWhen an author relies on their audience being well-read, they can paint with great depth and speed by borrowing the images of others.\n\nHades allows Eurydice a second life, but tragically, Orpheus breaks the one condition and looks back at her before leaving the underworld. Ovid's description is haunting and beautiful, but he quickly dispels the epic aura around the tale with:\n\n> Three times the Sun had finished out the year\n> in Pisces of the waters. Orpheus\n> had fled completely from the love of women,\n> either because it hadn't worked for him\n> or else because the pledge that he had given\n> to his Eurydice was permanent;\n> no matter: women burned to have the bard,\n> and many suffered greatly from rejection.\n> Among the Thracians, he originated\n> the practice of transferring the affections\n> to youthful males, plucking the first flower\n> in the brief spring time of their early manhood.\n> ~\n\nThe antecedent of \"it\" must be Orpheus' penis, and Ovid casts doubt on motive for staying away from women, conjecturing that it wasn't of his own choice, and for this reason he turned to young boys. Ovid's lack of reverence is distasteful to me, even being so far separated from the cultural stories he denigrates---still, he is fun to read.\n\nOrpheus proceeds to tell a number of stories, about gods loving boys and girls with unnatural lusts.\n\nA quote from the story of Hyacinthus, makes light of a similar simile in the _Iliad_:\n\n> \"As when a poppy or violet grown in a garden\n> among the lilies (whose tongues are thick yellow and bristly)\n> breaks, and the flower's head shrivels, droops, and collapses,\n> unable to hold itself up, with downcast demeanor,\n> just so the dying boy's head, now lacking all vigor,\n> unable to bear its own weight, lies flat on his shoulder.\"\n> ~\n\nHere is the original:\n\n> As a garden poppy, burst into red bloom, bends,\n> drooping its head to one side, weighed down\n> by its full seeds and a sudden spring shower,\n> so Gorgythion's head fell limp over one shoulder,\n> weighed down by his helmet.\n> ~ Iliad 8.306-9\n\nIn Homer, a great hero has died; in Ovid, a boy-lover dies in a discus accident. Furthermore, Apollo says he will speak about Hyacinthus in his poetry!\n\n> \"'You will be present both in my songs and mu music,\n> and a flower will come into being, inscribed with my mourning;\n> later, a legend involving the boldest of heroes\n> will be conjoined to this flower and read in its markings.'\"\n> ~\n\nOrpheus then tells the story of Pygmallion, and how, after being repulsed by the \"numerous defects of character Nature had given the feminine spirit,\" he falls in love with his statue. Is Ovid demeaning women, or men when he tells of the ridiculous gifts Pygmallion brought:\n\n> he seeks to win its affections with words and with presents\n> pleasing to girls, such as seashells and pebbles, tame birds,\n> armloads of flowers in thousands of different colors,\n> lilies, bright painted balls, curious insects in amber\n> ~\n\nPerhaps Ovid is using the classic story to make fun of men, for helplessly chasing women, and women for being shallowly bought by gifts.\n\nNext Orpheus tells the story of Myrrha, who fell in love with her father and tricked him into sleeping with her. Ovid has the poet warn readers:\n\n> I sing of dire events: depart from me, daughters,\n> depart from me, fathers; or, if you find my poems charming,\n> believe that I lie, believe these events never happened;\n> or, if you believe they did, then believe they were punished.\n> ~\n\n## Book XI\n\nAfter telling stories for most of Book X, Orpheus is torn to pieces by the Maenads. This scene is one of my favorite:\n\n> Meanwhile, as Orpheus compelled the tress\n> and beasts to follow him with suchlike songs,\n> and made the very stones skip in his wake,\n> behold: a raving mob of Thracian women\n> with the pelts of wild beasts draped across their breasts\n> observed him from the summit of a hill\n> setting the words to music on his lyre.\n> One of them tossed her hair in the light breeze:\n> \"Look over there!\" she cried. \"The one who scorns us!\"\n> And with no more ado, she cast her lance\n> at the vocalizing mouth of Apollo's seer;\n> it struck without wounding, being wreathed in leaves.\n> Another's weapon was the stone she cast,\n> that even in midflight was overwhelmed\n> by words and music joined in harmony,\n> and, as though begging pardon for its mad daring,\n> fell at the poet's feet.\n> ~\n\nOvid's commentary on Oracles:\n\n> His brother's transformation and some weird\n> portents that followed it left Ceyx perturbed\n> and eager to consult the oracles\n> that comfort men in their perplexity,\n> but on account of Phorbas and his brigands,\n> the road to Delphi was too dangerous,\n> so he prepared to undertake a journey\n> to Phoebus' shrine at Clarium instead\n> ~\n\nKnowledge of the source of lightening:\n\n> for once they break loose and reach open seas,\n> the winds are wholly uncontrollable,\n> and earth and sea alike are unprotected;\n> indeed, they even vex the clouds in heaven,\n> and shake the lightnings from them by collision!\n> ~\n\nI adore the story of Ceyx and Alcyone---a loving couple separated by death but both turned to birds. The description of Ceyx's death at sea is some of Ovid's most vivid. It includes a great simile:\n\n> Sails were rain-sodden, waters from above\n> were mixed in thoroughly with those below;\n> the stars were all put out, and blackest night\n> bore down with its own darkness and the storm's.\n> That darkness, nonetheless, was shattered by\n> the flickering thunderbolts that lit the sky\n> and made the raindrops glitter as they fell.\n> Boldly the flood now sprang onto the ship,\n> and like a solider, who, surpassing all\n> his many comrades, in the last assault\n> upon the walls of a beleaguered city,\n> after so many tries, achieves his aim,\n> and, fired by the love of praise, leaps over,\n> and one man holds the wall against a thousand;\n> just so, when nine successive waves have battered\n> the hull of that tall ship without success,\n> the tenth wave rushes in with greater force,\n> and does not end its struggle with the weary\n> vessel before it penetrates the wall\n> of the captured ship.\n> ~\n\n## Book XII\n\nThe characteristic abodes of Envy, Sleep, and Rumor are described in the _Metamorphoses_. Rumor's house is fun:\n\n> Crowds fill the entryway, a fickle mob\n> that comes and goes; and rumors everywhere,\n> thousands of fabrications mixed with fact,\n> wander the premises, while false reports\n> flit all about. Some fill their idle ears\n> with others' words, and some go bearing tales\n> elsewhere, while everywhere the fictions grow,\n> as everyone adds on to what he's heard.\n> ~\n\nOvid enjoys making fun of Homer's heroes. He begins withe Achilles'\n\n> The officers all took their ease, reclining\n> on couches where they stuffed themselves with meat\n> and drove away their cares and thirst with wine.\n> No lyres for this lot, no poetry,\n> no flutes of boxwood, pierced with many holes:\n> what pleases them is to extend the night\n> by telling stories of heroic deeds;\n> they reenact old wars, their own and others,\n> and are delighted to remember all\n> the dangers they've endured and gotten through:\n> what else has great Achilles to discuss?\n> What else is there to speak of in his presence?\n> ~\n\nNext in line is Nestor, who even Homer seemed to poke fun at a bit:\n\n> Nestor replied: \"Though my extreme old age\n> is something of an obstacle to me,\n> and much of what I witnessed in my youth\n> I have forgotten, still I remember much,\n> and nothing stands out more in memory,\n> among so many acts of war and peace,\n> than this does. But if great expanse of years\n> makes one a living witness of so much\n> that happened, I have lived two centuries\n> already, and am living in my third!\"\n> ~\n\nAnd then there is the ridiculous death descriptions:\n\n> \"They eyes leapt forth\n> from the disfigured pudding of his face,\n> and his nose was driven back into his palate.\"\n> ~\n\n> \"He plunged the horns into Gryneus' eyes\n> and gouged them out; one to an antler clung,\n> the other dribbled down his beard and hung\n> suspended in a mass of clotting gore.\"\n> ~\n\n> \"and Dictys, as he fled Pirithoüs\n> in fearful haste, toppled over the edge\n> of a mountain with two peaks, plunging headlong\n> until a giant ash tree broke his fall,\n> and left its fractured branches decorated\n> with loops of his intestines.\n> ~\n\n> \"and used his sword to open up his belly;\n> that fierce, unbridled beast bounded forward\n> and spilled his entrails out upon the ground,\n> and what spilled out of him, he trod upon,\n> and what was trodden on was burst asunder\n> and tangled in his legs until he fell,\n> his belly emptied of its viscera.\"\n> ~\n\n> \"shattered the broad dome of his skull, and pressed\n> his fluid brains till they exuded through\n> his mouth, his sinuses, his eyes and ears,\n> as when the whey pours through the oaken basket\n> leaving the curds behind, or as when grapes\n> beneath the press drip through the slender sieve,\n> and juice is squeezed out through the narrow openings.\"\n> ~\n\nOvid includes the sequences of deaths, like Homer:\n\n> \"And with that club, he flattened Nedymnus\n> and Lycopes, skilled with the javelin,\n> and Hippasos, whose breast was covered by\n> his uncut beard, and Ripheus, who loomed\n> above the tallest tress, and Thereus,\n> who caught bears on the peaks of Thessaly\n> and fetched them back still living and indignant.\"\n> ~\n\n> \"Caeneus had already slaughtered five:\n> Styphelus first, then Bromus, Antimachus,\n> Elymus, and axe-wielding Pyracmos;\n> I don't recall the manner of their deaths,\n> for I took note just of the names and numbers.\"\n> ~\n\nHe pokes fun at the Greek's armor obsession:\n\n> Achilles very shield---that you should be aware\n> whose it once was---now instigates a battle,\n> and for his arms, arms are now taken up.\n> ~\n\nHe even makes fun of the role the gods played in Homer, perhaps questioning their existence:\n\n> \"and when he saw the [thrown tree] coming, Theseus\n> moved out of range, upon advice of Pallas---\n> or so he would prefer us to believe.\"\n> ~\n\nMany stories' central metamorphosis is physical, in the story of Achilles death, the change is of a living man into a legacy:\n\n> now he is ashes: and the little left\n> of great Achilles scarcely fills an urn,\n> although his living glory fills the world.\n> That glory is the measure of the man,\n> and it is this that is Achilles' essence,\n> nor does he feel the emptiness of death.\n> ~\n\n## Book XIII\n\nAjax and Ulysses proclaim to the Greek assembly why they should receive Achilles' shield.\n\nAjax' has a few funny arguments:\n\n> \"I realize I seek a great reward,\n> but having such a rival is demeaning\n> and cheats me of the honor I am due:\n> Ajax cannot be proud to win a prize,\n> no matter how substantial, that Ulysses\n> can have the expectation of receiving;\n> he has already gotten his reward,\n> for when his claim has been rejected, he\n> can boast that he and I were fairly matched!\"\n> ~\n\n> \"In truth, if I may say so, it's the prize\n> that seeks association with _my_ glory,\n> and would be honored much more than would I---\n> for it's the armor would be given Ajax,\n> not Ajax the armor.\"\n> ~\n\nUlysses wins; his central argument is that his intellect is more important than fighting prowess. He also pulls the jury to his side by emotionally aligning them against Ajax:\n\n> \"Nor should it shock us that his [Ajax'] stupid mouth\n> should so abuse me, for you also are\n> the targets of his indecent reproaches.\n> Can it be baseness for me to accuse\n> Palamedes unjustly, but correct\n> for you to find him guilty of the charges?\"\n> ~\n\nThe story of the Cyclops, Polyphemus from the _Odyssey_, wooing Galatea is hilarious. Ovid, as he always does, masterfully ridicules without indulging too much. Thus, Polyphemus' advances are funny yet not crude. Here are a few of my favorite lines:\n\n> \"'O Galatea, whiter than the snowy white\n> flowers that decorate the privet hedge,\n> richer in blossoms than the meadow is,\n> taller, more slender than an alder tree,\n> brighter than crystal, more skittish than a kid,\n> smoother than a seashell on the shore\n> worn by the ceaseless motion of the waves,\n> more pleasing than the shade in summertime\n> or sun in winter, swifter than the deer,\n> and even more remarkable to see,\n> far more conspicuous than the tall plane tree;\n> clearer than ice, sweeter than ripe grapes,\n> software than swans' down or the curdled milk,\n> and, of you would not always flee from me,\n> more beautiful than an irrigated garden.\n> Yet you, the very selfsame Galatea,\n> are fiercer than an untamed heifer is,\n> harder than oak, more feigning than the sea,\n> tougher than willow wands or bryony,\n> less movable than the rock I'm sitting on,\n> rougher than rapids, prouder than a peacock,\n> fiercer than fire, bitterer than thistles,\n> grumpier than a nursing mother-bear,\n> more unresponsive even than the ocean,\n> less apt to pity than a stepped-on snake'\"\n> ~\n\n> \"'Just look how big I am! Not even Jove---\n> this Jupiter that you go on about,\n> who you say governs heaven---is as big!\n> Abundant hair hangs over my fierce face\n> and shoulders, shading me, just like a grove;\n> but don't think me unsightly just because\n> I am completely covered in dense bristles:\n> unsightly is the tree that has no leaves,\n> the horse without a mane; birds have their plumage\n> and sheep are most attractive in their wool,\n> so facial hair and a full body beard\n> are really most becoming in a man.\n> In the middle of my forehead is one eye,\n> as large in its appearance as a shield:\n> what of it, then? Does not the mighty Sun\n> see everything that happens here on earth?\n> And as for eyes, he too has only one!\"\n> ~\n\nThe Metropolitan Museum of Art has an original Roman painting, one of the rare survivors, from around the time of Ovid (if I recall). The painting depicts a few scenes of the Polymphemus and Galatea story.\n\nThe story about Glaucas eating magical grass which turns him into a fish is a bizarre (beside the teeth turning into men, in the Jason and Cadmus stories, who then fight one another, this may be the oddest story in the _Metamorphoses_, although I am not sure I could point out why. Perhaps many of the other stories in Ovid would sound odd too, if our culture had not appropriated them. When I read Chinese (or even some Egyptian) stories, they all sound as odd as this one. But the opposite is likely true too.\n\nHere is the especially odd part:\n\n> \"Now comes what sounds like fiction, I admit,\n> but what advantage would I gain by feigning?\n> Lying on the grass, my plunder from the surf\n> began to stir, and flipped from side to side, \n> as all at once, they strove to leave the earth\n> and get back to the water. While I watched,\n> dumbfounded and incapable of moving,\n> they fled, the lot of them, abandoning\n> the shore and their new master for the sea.\n> I stood stock-still in wonder a long time,\n> asking myself how such a thing could be;\n> was it some god---or something in the grass?\n> 'How could mere grass,' I asked, 'be strong as that?'\n> I plucked some and ground it in my teeth,\n> and scarcely had I gulped that unknown liquid,\n> when suddenly my heart began to pound,\n> and my whole sensibility was taken\n> with the desire for another element,\n> which I could not resist for long: 'Farewell,\n> O earth, which I will nevermore return to,'\n> I said, and plunged beneath the ocean's waves.\"\n> ~\n\n## Book XIV\n\nGlaucus, in love with Scylla, asks Circe to help. Instead, she falls in love with him:\n\n> \"I pray you will have me! Only spurn\n> the one who spurns your passion, and return\n> the love of one who loves you: let one deed serve\n> two women as they each of them deserve.\"\n> Glaucus responded to her proposition:\n> \"The leaves of trees will spring out of the ocean,\n> and seaweed will be found on mountain ranges,\n> before my love for Scylla ever changes.\"\n> ~\n\nAnd so, Circe transforms Syclla into a monster:\n\n> \"her private parts deformed into the shapes\n> of barking dogs ...\n> Her lover Glaucus wept at this and fled\n> from having any more to do with Circe,\n> whose use of potent herbs was too aggressive.\"\n> ~\n\nDiomedes recounting the woes of the returning Greeks:\n\n> \"I will not long delay you, setting out\n> our woes in the order they occurred:\n> just say that even Priam would have wept\n> to see how Greece was fairing at that time!\"\n> ~\n\nAnaxarete, after spurning Iphis' advances, sees his body and is turned to stone:\n\n> \"scarcely had she glimpsed\n> the corpse of Iphis laid out on his bier,\n> when her eyes hardened and he cold blood ran\n> in terror from her body: she attempted\n> to step back from the sight, but her feet froze;\n> when she attempted to avert her face,\n> she was unable to; and very soon\n> the stoniness that for so long a time\n> had been within her heart spread through her body.\"\n> ~\n\n## Book XV\n\nPythagoras' pagan skepticism:\n\n> lightning is produced by Jove\n> or by the winds that tear apart the clouds;\n> what causes earthquakes and what keeps the stars\n> from flying off, and other hidden things\n> ~\n\nPythagoras on being vegetarian:\n\n> \"Mortals, refrain from defiling your bodies with sinful\n> feasting, for you have the fruits of the earth and of arbors,\n> whose branches bow with their burden; for you the grapes ripen,\n> for you the delicious greens are made tender by cooking;\n> milk is permitted you too, and thyme-scented honey:\n> Earth is abundantly wealthy and freely provides you\n> her gentle sustenance, offered without any bloodshed.\n> Some of the beasts _do_ eat flesh to allay their own hunger,\n> although not all of them, for horses, sheep, and cattle\n> feed upon grasses; but those of untameable nature---\n> Armenian tigers, furious lions, wolves and bears, too---\n> these creatures take pleasure in feasting on what they have slaughtered.\n> What an indecency, mingling entrails with entrails,\n> fattening one on the flesh from another one's body,\n> saving the life of one by another's destruction!\"\n> ~\n\nPythagoras on the afterlife and fear thereof:\n\n> \"O people stunned with the icy terror of dying,\n> why do you fear the Styx? Why are you frightened of phantoms\n> and names that mean nothing, the empty blather of poets,\n> foolish hobgoblins of a world that never existed?\n> Here is what happens after you die: your body,\n> whether consumed on the pyre of slowly decaying,\n> suffers no evil; souls cannot perish, and always,\n> on leaving their prior abodes, they come to new ones,\n> living on, dwelling again in receptive bodies\"\n> ~\n\nPythagoras on unending change:\n\n> \"And since I am already embarked upon this great sea,\n> have given full sails to the wind, hear me out: nothing\n> endures in this world! The whole of it flows, and all is\n> formed with a changing appearance; even time passes,\n> constant in motion no different from a great river,\n> for neither a river nor a transitory hour\n> is able to stand still; but just as each wave is driven\n> ahead by another, urged on from behind, and urging\n> the next wave before it in an unbroken sequence,\n> so the times flee and at the same time they follow,\n> and always are new; for what has just been is no longer,\n> and what has not been will presently come into being,\n> and every moment's occasion is a renewal.\"\n> ~\n\nPythagoras on geology, and the changing planet:\n\n> \"I truly believe that nothing may keep the same image\n> for a long time; the age of gold yields to iron,\n> and often places will know a reversal of fortune.\n> For with my own eyes, I have seen land that once was quite solid\n> change into water, and I have seen land made from ocean;\n> seashells have been discovered far from the seashore,\n> and rusty anchors right on the summits of mountains;\n> a former plain was converted into a valley\n> by rushing waters, whose force has leveled great mountains;\n> and a onetime marshland has been turned into a desert,\n> while thirsty sands have been transformed into marshland.\"\n> ~\n\nPythagoras on biological change:\n\n> \"Mud contains seeds which generate frogs, at first legless,\n> though soon they develop limbs that equip them for swimming,\n> and so that these same limbs can be used for long-distance leaping,\n> their hind legs are always much greater in length than their forelegs.\n> Nor is the bear cub, when newly brought forth by the she-bear,\n> other than bear-pulp: by her own purposeful licking,\n> the mother bear shapes it and forms it in her own image.\n> Do you not see how the larva of bees, makers of honey,\n> so well protected within their hexagonal chambers\n> of wax, are born without any limbs on their bodies,\n> and only later develop legs and the wings used for flying?\"\n> ~\n\nPythagoras on the shifts of power:\n\n> \"as one nation gains in strength while another collapses:\n> once Troy was great, rich in its wealth and its heroes,\n> and able to go on bleeding both for ten years;\n> now brought to earth, she has nothing to show but her ruins,\n> no wealth besides that which lies in her burial chambers.\n> Sparta was famous, mighty Mycenae once flourished,\n> even as Athens, even as Thebes of the Towers;\n> Sparta is worthless now, lofty Mycenae has toppled,\n> what but the name remains of the Thebes of Oedipus?\n> What but the name remains of Pandion's Athens?\"\n> ~\n\nOvid pandering to Augustus:\n\n> That one approached our altars as a stranger,\n> but Caesar is a god in his own city,\n> raised up to heaven, changed into a star\n> blazing so brilliantly, not by his own\n> remarkable success in war and peace,\n> not by the battles that were crowned in triumph,\n> nor by his service to the commonwealth,\n> nor yet by glory that hastened to his side;\n> but rather by his offspring, for no deed\n> has Caesar done that stands out more than this:\n> he is thew father of our own Augustus!\n> ~\n\nOvid predicts his enduring fame:\n\n> My work is finished now: no wrath of Jove\n> nor sword nor fire nor futurity\n> is capable of laying waste to it.\n> Let that day come then, when it wishes to,\n> which only has my body in its power,\n> and put an end to my uncertain years;\n> no matter, for in spirit I will be\n> borne up to soar beyond the distant stars,\n> immortal in the name I leave behind;\n> wherever Roman governance extends\n> over the subject nations of the world,\n> my words will be upon the people's lips,\n> and if there is truth in poets' prophesies,\n> then in my fame forever I will live.\n> ~\n\n## Metaphysics\n\nThe _Metamorphoses_ were meant to be entertaining, thus it is dangerous to make any theological conclusions from them. Still, some metaphysical comments may represent widely held beliefs from Ovid's time. For example, the role of fate, present in Homer, is laid out:\n\n> Each of the gods there had a favorite,\n> and argued from a partisan position\n> against the others, until Jove spoke up:\n> \"O gods! If you have any reverence\n> for us at all, why leap to such confusions?\n> Does anyone here imagine himself able\n> to overcome the limits set by Fate?\n> Iolaüs was given back the years\n> he was in need of by the will of Fate;\n> not by ambition, not by skill in combat\n> will Callirhoë's sons turn into men\n> from infancy, but by the will of Fate,\n> which governs even us; I tell you this\n> that you might put a better face on it---\n> yes, _you_ are ruled by Fate, and _I_ am too.\"\n> ~ (9.619--35)\n\n> Her [Venus'] father said, \"My dear, are you preparing\n> to alter his [Ceasars'] inevitable fate\n> all by yourself? It is permitted you\n> to enter the Hall of Records kept by the Fates;\n> there you will find the labor of the ages,\n> the universal script, in bronze and iron,\n> which does not fear that clashes in the sky\n> or lightning's rage will bring it down to ruin,\n> for it will be eternally secure.\n> Here you will find, inscribed on adamant\n> that will not perish ever, your son's fate:\n> and I myself have read and noted it,\n> and I will now expound on it to you,\n> so you may understand what is to come.\"\n> ~ (15.1004--17)\n\nMortals had \"deficits\" that needed to be purged before becoming immortal:\n\n> \"The sea god welcomed me, pronounced me fit\n> to join their honorable company,\n> and asked the Ocean and his consort, Tethys,\n> to take away whatever still remained\n> of my mortality; and this they did\n> first, by the recital of a hymn, nine times,\n> to purge me of my evil; then they bade\n> me to immerse myself a hundred times\n> in just as many rivers\"\n> ~ (13.1378--86)\n\n> She [Venus] bade the river god to take Aeneas\n> under the surface of his silent stream\n> and cleanse him of all mortal deficits;\n> he did as she commanded, bathing him,\n> and having purged him of this mortal dross,\n> restored his best, immortal part to him.\n> His mother purified Aeneas' body,\n> anointing it with heavenly perfumes,\n> and touched his lips with sweet ambrosia\n> and nectar both, so he became a god,\n> ~ (14.861--72)\n\nThe gods are limited in a number of ways. Interestingly, Ovid mentions that gods can't undue actions of other gods:\n\n> Venus alone knew that the bolt had fallen\n> and would have put it back and locked the gates,\n> but one god is unable to rescind\n> the actions of another.\n> ~\n\nThis sort of question is unique to polytheism.\n\n## Epistemology\n\nOvid does not appear to take the myths he is telling seriously. Throughout the poem, he inserts comic asides. Here I present a few illustrative examples.\n\nOvid avoids stating which god created the universe:\n\n> Some god (or kinder nature) settled this\n> dispute by separating earth from heaven\n> ...\n> Now when that god (whichever one it was)\n> had given Chaos form\n> ~ (1.26--41)\n\nHe slyly implies that we do not know the source of some stories firsthand:\n\n> So that the skies above might be no more\n> secure than earth, the race of Giants plotted\n> (we hear) to rule in heaven by themselves\n> ~ (1.205--8)\n\nHere he ironically says we have a story on good faith:\n\n> (you needn't take this part of it on faith,\n> for it's supported by an old tradition)---\n> these stones at once begin to lose their hardness\n> and their rigidity; slowly they soften;\n> once softened, they begin to take on shapes.\n> ~ (1.556--60)\n\nIn other places, he speculates about the gods motives:\n\n> He spoke and threw his arms around her neck,\n> imploring her upon his very life,\n> and on that of his stepfather, Merops,\n> and by the wedding torches of his sisters,\n> to give him proof of who his father was.\n> Clymene, moved by Phaêthon's petition\n> (or by the insult to her own good name),\n> ~ (1.1055--64)\n\nHe openly questions the plausibility of the stories and the gods:\n\n> Her [Semele's] child was torn out of her womb unfinished\n> and---this part is scarcely credible---was sewn\n> into his father's thigh, where he was brought to term.\n> ~ (3.400-2)\n\n> She has a virgin's face, and, if our poets\n> are not to be completely disbelieved\n> ~ (13.1063--4)\n\n> \"but war continued,\n> since both sides each had gods supporting them,\n> and courage, which is just as good as gods\"\n> ~ (14.811--3)\n\n## Structure\n\nThe _Metamorphoses_' Stories flow together roughly following time, but not completely. For example, Atlas is said to be carrying the world on his shoulders in book II but does not receive his burden until book IV, and Hercules' apotheosis occurs in book IX but he is present during the sack of Troy in book XI.\n\nStories are often grouped together by family (the Cadmus stories in books III and IV) or by region (the Anatolian stories in book VI).\n\nNested stories at two or three levels are common (on occasion, as with the Arethusa and Alpheus in book V, four levels are present).\n\nThe connections between stories are often weak, for example:\n\n> Rumor might very well have spread the news\n> of this unprecedented transformation [of Byblis into a spring]\n> throughout the hundred towns of Crete, if they\n> had not just had a wonder of their own\n> to talk about---the change that came to Iphis.\n> ~ (9.960--4)\n\n## Similes\n\nApollo's sudden love for Daphne:\n\n> Now just as in a field the harvest stubble\n> is all burned off, or as hedges are set ablaze\n> when, if by chance, some careless traveler\n> should brush one with his torch or toss away\n> the still-smoldering brand at break of day---\n> just so the smitten god went up in flames\n> until his heart was utterly afire,\n> and hope sustained his unrequited passion.\n> ~ (1.678--85)\n\nApollo chasing Daphne, after being unable to woo her:\n\n> But the young god had no further interest\n> in wasting his fine words on her; admonished\n> by his own passion, he accelerates,\n> and runs as swiftly as a Gallic hound\n> chasing a rabbit through an open field;\n> the one seeks shelter and the other, prey---\n> he clings to her, is just about to spring,\n> with his long muzzle straining at her heels,\n> while she, not knowing whether she's been caught,\n> in one swift burst, eludes those snapping jaws,\n> no longer the anticipated feast;\n> so he in hope and she in terror race.\n> ~ (1.732--44)\n\n## Rape\n\nAeacus's casual comment about his wife being worthy:\n\n> \"Her name was Procris: it's likelier you've heard\n> about her ravished sister, Orithyia,\n> but were you to compare the two of them\n> in looks and manner, Procris was more worthy\n> of being ravished!\"\n> ~ (6.990--5)\n\nSometimes the raped women seem to be proud that they attracted the gods and have semi-divine offspring, but, if their flights are not evidence enough of their unwillingness, then Ovid makes it clear other times:\n\n> \"And after Neptune had taken his delight\n> by ravishing the maiden, he announced,\n> 'Whatever you desire will be granted!\n> Fear no refusal; ask and it is given.'\n> Caenis replied: 'The injury you've done me\n> requires a great wish to be set right,\n> that I might never suffer this again,\n> allow that I may be no more a woman,\n> and you will have fulfilled me utterly.'\"\n> ~ (12.292--301)\n\n## Other Interesting Quotes\n\nOvid's description of the heavens is humorous, as the gods themselves have household gods:\n\n> When the nighttime sky is clear, there can be seen\n> a highway visible in heaven, named\n> the Milky Way, distinguished for its whiteness.\n> Gods take this path to the royal apartments\n> of Jove the Thunderer; on either side\n> are palaces with folding doors flung wide,\n> and filled with guests of their distinguished owners;\n> plebeian gods reside in other sections,\n> but here in this exclusive neighborhood,\n> the most renowned of heaven's occupants\n> have *their* own household deities enshrined;\n> and if I were permitted to speak freely,\n> I would not hesitate to call this enclave\n> the Palatine of heaven's ruling class.\n> ~ (1.229--42)\n\nTowards the end of Book I, Clymenes tells her son that:\n\n> \"It will not be a great task to discover\n> the place where your father [Apollo] keeps his household gods.\"\n> ~ (1.1074--5)\n\nProcne carries of her son Itys, to murder him and feed him to her evil husband:\n\n> Now resolute, she carries Itys off,\n> just as a tiger on the Ganges' banks\n> will drag a nursing fawn through the dense woods\n> ~ (6.922-4)\n\nAll quotations are taken from Charles Martin's 2004 translation. Line numbers refer to the translation and not the original Latin.*\n" }, { "alpha_fraction": 0.7906724214553833, "alphanum_fraction": 0.7906724214553833, "avg_line_length": 75.83333587646484, "blob_id": "f0d0dd7f08f44597532d3047b57afeb79b366843", "content_id": "9b2dfe8bc3b7e8eccf91d1cd5fbf1baf5eeaa8b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1866, "license_type": "no_license", "max_line_length": 395, "num_lines": 24, "path": "/_documents/beauty-and-truth.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Beauty and Truth\ndescription: >\n Are beautiful words more likely to be true than plain ones?\n---\n\n{{ page.description }}\n\nThe relationship between beauty and truth is not fundamental, but emerges from how we acquire knowledge from others. Often, we don’t have the time, inclination, or ability to acquire knowledge directly. For example, if unable evaluate a lawyer’s ability, we rely on a recommendation. Thus, we use other people’s beliefs to help us arrive at our own.\n\nWe don’t usually follow blindly. To decide whether someone is malicious or mistaken, we consider their motives and expertise. We trust the astronomy professor when he talks about Jupiter’s moons, we trust someone who is often proven correct, and we trust ten people more than two.\n\nThis last tendency—trusting the crowd—is one connection between beauty and truth. Beauty gets attention for its own sake, becomes widespread, and gains authority. An author’s words are beautiful, so they are repeated. Decades pass and the words become ubiquitous. Many will question and disagree—but most will not have the time to critique the author’s words, and will put faith in its ubiquity.\n\nThe _Iliad_, and its central position in Greek and Roman thought, exemplifies the connection between beauty and truth. (It is also the origin of this essay.) Homer’s writing is beautiful and occasionally profound. I believe its influence can only be understood as originating from its beauty.\n\nAs nice clothing lends a person credibility, beauty lends words credibility. We use clothing and beauty as shortcuts.\n\nThese shortcuts are often appropriate, especially when busy and deciding mundane questions. But I think we should hesitate to use beauty, or the crowd, when considering the most important matters.\n\n{% comment %}\nAdd more details about the Iliad.\n{% endcomment %}\n" }, { "alpha_fraction": 0.8117180466651917, "alphanum_fraction": 0.8123283386230469, "avg_line_length": 147.9545440673828, "blob_id": "9247c73990a27ce409e87d5d6245e0aec9781e9b", "content_id": "4a4465cb8707a342a1d9797f04eed7ae0d74c957", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6606, "license_type": "no_license", "max_line_length": 628, "num_lines": 44, "path": "/_documents/universal-historical-laws.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Universal Historical Laws\ndescription: >\n Is history philosophically uninteresting because it can not provide universal laws?\ntype: essay\nstatus: complete\nredirect_from:\n - /on-historical-laws\n---\n\nSome philosophers think history is uninteresting because it can not provide laws, or law-like explanations, and thus its inferences can’t be rationally evaluated.\n\nI agree that the historian, like the social scientist, can’t produce laws. By law I mean a universally true, conditional statement about reality. (Defining a law to be a _conditional_ statement distinguishes it from particular statements like “Julius Caesar was murdered on the 15th of March, 44 BC.”) The objects of historical study—people, nations, wars, governments, etc.—are too complex to define, let alone deduce universally true conditional statements about.\n\nEven if one agrees that the historian can’t discover universal laws, one may believe they exist. I hope to demonstrate that historical laws—laws pertaining to historical subjects—as distinct from scientific laws, can’t exist. Furthermore I will show that, despite this epistemic limitation, history remains useful and open to rational evaluation.\n\nConsider this statement: When a ruling power’s dominance is threatened by a growing neighbor, the two will go to war. This simple historical statement isn’t universally true and is thus not a law; there are instances of nations peacefully eclipsing their once-dominant neighbors. It may be made into a law by amending conditions. For example, one may add “when the existing nation isn’t distracted by other wars” to account for certain exceptions. It may be possible, after adding three or four such conditions, to make the law fit all available historical examples. Yet there is no reason to believe it is now universally true.\n\nHistorical events may be driven by individuals, thus historical laws must predict the individual’s behavior. To see why this is true, consider the following examples. A nation may war with a smaller neighbor as the result of a few neurotransmitters in their supreme leader’s brain. Or two nuclear powers may avoid war only because of the calm reasoning of a missile operator. These examples are extreme, but to be universally true, a historical law must account for them.\n\nOne may understand Words of languages, are complex patterns formed by particles in time and space. Water molecules are well-defined pattern. A cup is less well-defined, yet more so than a person. The concept of a nation, or a war, are patterns built on patterns, layered recursively like the definitions in a dictionary. Words compress the overwhelming detail needed for complete descriptions, allowing our minds to operate in reality at a higher level of abstraction.\n\nThe compressive and lossy nature of words precludes the existence of historical laws. Said another way, any law whose objects are imprecise patterns of particles will fail to be true in every instance; since the words used to state the law have already blurred out the details necessary to make conclusive predictions.\n\nTo avoid this conclusion one must identify larger objects whose behavior could be predicted with certainty without knowledge of their constituent particles. We refer to such a system as a _black box_. The laws of physics preclude the existence of black boxes.\n\nThere are, however, systems that can be described as statistical black boxes. For example, we may explain and predict the some behavior of a glass of water using a few of numbers—e.g., its temperature and volume. Humans, however, certainly can not be reduced to such simple system! Without being pulled into questions of freewill and determinism, we can conclude that to predict human behavior with the precision required by a universally true law, we would need detailed knowledge of the particles constituting that human.\n\nConsider again our example, “when a ruling power’s dominance is threatened by a growing neighbor, they will go to war.” Now imagine that God were to try and make it true by reviewing all possible wars and amending the statement with conditionals as needed. After considering every possible war, the amended law would be enormous and would account for neurotransmitters and other physical details. Such a law could not be understood by the human mind. In fact, I believe such a law would need to contain even the physical laws of nature to be universally true!\n\nThus, we must abandon any belief in the existence of historical laws, and can consider whether laws, or law-like explanations, are necessary for something to be rationally evaluated.\n\nI don’t believe laws are necessary for historical analysis to be rationally evaluated. I will demonstrate this indirectly, by showing that if such a statement were true, rationality and philosophy would need to relegated to the realms of science.\n\nBusiness books are a practical, and widely used, form of historical knowledge. The conclusions of such books are not universally true (and many are simply incorrect), yet collectively they are not useless. Otherwise, business people would not continue making decisions based on them. Likewise, governments and militaries rely heavily on historical analysis.\n\nIf one defines “rationally evaluable” so as to preclude these uses of historical knowledge in business, government, and the military, it would seem that the realm of philosophy is inappropriately reduced. The desire for the level of precision found in mathematics and the hard sciences is understandable, but by relegating oneself to these tidier fields of inquiry the philosopher avoids the big questions—of people, values, governments, and war—which are most interesting.\n\n(In addition to producing generalized knowledge, the particulars of history form the identity of nations and peoples. Thus, some historical knowledge is necessary to understand human behavior and to appreciate the beauty of our literature and art.)\n\nThe claim investigated in this essay is not unlike the one, made by some philosophers, that only statements verifiable through direct observation or logical proof are meaningful. It is tempting to make such claims when confronting the messy nature of reality and language, but doing so erodes credibility when our everyday reality continually provides evidence of the utility and interest of history.\n\nThe philosopher must settle with sketches, observations, heuristics, and other weaker epistemological devices that history provides, while continuing to apply them to the large questions of human existence.\n" }, { "alpha_fraction": 0.7487703561782837, "alphanum_fraction": 0.7533031105995178, "avg_line_length": 56.60555648803711, "blob_id": "d35b6001472459b43f559193e3bb63f3e779fbfe", "content_id": "ea706edf501e07fbb20aa9f6244219e53364f795", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10369, "license_type": "no_license", "max_line_length": 529, "num_lines": 180, "path": "/documents/the-epic-of-gilgamesh.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n _The Epic of Gilgamesh_\ndescription: >\n A commentary on _The Epic of Gilgamesh_\ntype: note\nstatus: incomplete\n---\n\nAncient and beautiful, *The Epic of Gilgamesh* is the story of the king of Uruk.\n\nGilgamesh was a powerful and handsome king, but he oppressed his people. He forced new brides to have sex with him on their wedding night. The young women of Uruk cried out, and the gods heard them. The gods decided to create the wildman Enkidu to vie with Gilgamesh and to relieve Uruk's citizens:\n\n> The goddess Aruru, she washed her hands,\n> took a pinch of clay, threw it down in the wild.\n> In the wild she created Enkidu, the hero,\n> offspring of silence, knit strong by Ninurta.\n> ~\n\nA game trapper finds Enkidu at a watering hole, and is concerned because he fills in his pits and pulls up his snares. The trapper's father advises his son to bring Shamhat, a harlot from Uruk, to the watering hole to tempt Enkidu with her charms. Here is the scene where Shamhat tempts Enkidu, and tells him to leave the wilderness and his animals:\n\n> One day and a second they waited by the water-hole,\n> then the herd came down to drink the water.\n> The game arrived, their hearts *delighted in* water,\n> and Enkidu also, born in the uplands.\n>\n> With the gazelles he grazed on grasses,\n> *joining the throng* with the game at the water-hole,\n> his heart *delighting* with the beasts in the water:\n> then Shamhat saw him, the child of nature,\n> the savage man from the midst of the wild.\n>\n> ...\n>\n> Shamhat unfastened the cloth of her loins,\n> she bared her sex and he took in her charms.\n> She did not recoil, she took in his scent:\n> she spread her clothing and he lay upon her.\n>\n> She did for the man the work of a woman,\n> his passion caressed and embraced her.\n> For six days and seven nights\n> Enkidu was erect, as he coupled with Shamhat.\n>\n> When with her delights he was fully sated,\n> he turned his gaze to his herd.\n> The gazelles saw Enkidu, they started to run,\n> the beasts of the field shied away from his presence.\n>\n> Enkidu had defiled his body so pure,\n> his legs stood still, though his herd was in motion.\n> Enkidu was weakened, could not run as before,\n> but now he had *reason*, and wide understanding.\n>\n> He came back and sat at the feet of the harlot,\n> watching the harlot, observing her features.\n> Then to the harlot's words he listened intently,\n> *as Shamhat* talked to him, to Enkidu:\n>\n> \"You are handsome, Enkidu, you are just like a god!\n> Why with the beasts do you wander the wild?\n> Come, I will take you to Uruk-the-Sheepfold,\n> to the sacred temple, home of Anu and Ishtar\"\n> ~\n\nI am quoting from the Andrew George translation; words in italics were difficult to decipher or were filled in from context.\n\nThis passage has similarities to the Adam and Eve story in the Book of Genesis. In both a man is created from the ground, tempted by a woman, succumbs, gains knowledge or understanding, and must leave their innocent way of life.\n\nThere are more differences between the stories than there are similarities. Eve was the innocent partner of Adam; Shamhat was a prostitute from the city. Adam and Eve tended a garden and named the animals, while Enkidu would run with the animals and free them from traps. Enkidu was \"defiled\" and gained \"wide understanding,\" while Adam gained \"knowledge of good and evil.\" Eve was tempted with knowledge by a snake, and then Eve tempted Adam; Enkidu was tempted with sex by Shamhat.\n\nThere is, however, a snake in the *Epic of Gilgamesh.* Gilgamesh is returning from a journey with a plant that will make him young again. This plant is similar to the tree of life in Genesis. Here is the passage:\n\n> \"This plant, Ur-shanabi, is the 'Plant of Heartbeat,'\n> with it a man can regain his vigour.\n> To Uruk-the-Sheepfold I will take it,\n> to an ancient I will feed some and put the plant to the test!\n>\n> \"Its name shall be 'Old Man Grown Young,'\n> I will eat it myself, and be again as I was in my youth!\"\n> At twenty leagues they broke bread,\n> at thirty leagues they stopped for the night.\n>\n> Gilgamesh found a pool whose water was cool,\n> down he went into it, to bathe in the water.\n> Of the plant's fragrance a snake caught scent,\n> came up *in silence*, and bore the plant off.\n>\n> As it turned away it sloughed its skin.\n> Then Gilgamesh sat down and wept,\n> down his cheeks the tears were coursing.\n> ~\n\nIn both stories a snake causes a man to lose access to a plant which provides eternal life. However, there are many differences. In Genesis, the plant is given to Adam by God; Gilgamesh is told about the plant by the Babylonian Noah and he must find it himself. In Genesis, the plant is a tree in the garden of Eden; in the *Epic of Gilgamesh,* it is a prickly plant at the bottom of the \"Ocean Below.\"\n\nThe similarities between the story of Noah and the Babylonian texts are manifold. The creation story in Genesis, Job, the Psalms, and Ecclesiastes have traces of concepts from Babylonian texts.\n\nFor example, the Hebrew Bible, like Babylonian mythology, has the idea of the waters above and the waters below:\n\n> And God said, \"Let there be a dome in the midst of the waters, and let it separate the waters from the waters.\" So God made the dome and separated the waters that were under the dome from the waters that were above the dome. And it was so. God called the dome Sky. And there was evening and there was morning, the second day.\n> - Genesis 1:6--8, NRSV\n\n> In the six hundredth year of Noah's life, in the second month, on the seventeenth day of the month, on that day all the fountains of the great deep burst forth, and the windows of the heavens were opened.\n> - Genesis 7:11, NRSV\n\n> And God made a wind blow over the earth, and the waters subsided; the fountains of the deep and the windows of the heavens were closed, the rain from the heavens was restrained, and the waters gradually receded from the earth.\n> - Genesis 8:1--3, NRSV\n\n> Praise him, you highest heavens, and you waters above the heavens!\n> - Psalms 149:4, NRSV\n\nThe most common explanation for the Hebrew's and Babylonian's belief in the waters above is that the sky is blue and water is blue.\n\nIn Babylonian mythology, Marduk was the supreme god. Marduk rose to power by killing Tiamat, who was often represented as a great sea dragon, when all the other Babylonian gods were too afraid to confront it. It seems that the Hebrew god references fought a similar battle:\n\n> \"Can you draw out Leviathan with a fishhook,\n> or press down its tongue with a cord?\n> Can you put a rope in its nose,\n> or pierce its jaw with a hook?\n> ...\n> Any hope of capturing it will be disappointed;\n> were not even the gods overwhelmed at the sight of it?\"\n> ~ Job 41:1--9, NRSV\n\n> You divided the sea by your might;\n> you broke the heads of the dragons in the waters.\n> You crushed the heads of Leviathan;\n> you gave him as food for the creatures of the wilderness.\n> ~ Psalm 74:13--14, NRSV\n\nFinally, parts of Ecclesiastes are very similar to the *Epic of Gilgamesh*. Here is a quote, from a tavern-keeper at the edge of the world, advising Gilgamesh:\n\n> \"The life that you seek you never will find:\n> When the gods created mankind,\n> Death they dispensed to mankind,\n> Life they kept for themselves.\n>\n> \"But you, Gilgamesh, let your belly be full,\n> Enjoy yourself always by day and by night!\n> Make merry each day,\n> Dance and play day and night!\n>\n> \"Let your clothes be clean,\n> Let your head be washed, may you bathe in water!\n> Gaze on the child who holds your hand,\n> Let your wife enjoy your repeated embrace!\n>\n> \"For such is the destiny of mortal men\"\n> ~\n\nAnd here is a similar saying in Ecclesiastes:\n\n> The living know that they will die, but the dead know nothing; they have no more reward, and even the memory of them is lost. Their love and their hate and their envy have already perished; never again will they have any share in all that happens under the sun.\n>\n> Go, eat your bread with enjoyment, and drink your wine with a merry heart; for God has long ago approved what you do. Let your garments always be white; do not let oil be lacking on your head. Enjoy life with the wife whom you love, all the days of your vain life that are given you under the sun, because that is your portion in life and in your toil at which you toil under the sun. Whatever your hand finds to do, do with your might; for there is no work or though or knowledge or wisdom in Sheol, to which you are going.\n> - Ecclesiastes 9:5--10, NRSV\n\nFinally, the Hebrew and Babylonian flood stories are exceedingly similar. Instead of providing a long list of quotes, I will instead list the similarities:\n\n- Before the flood, men live many hundreds of years\n- Pre-flood individuals are taken directly to heaven (Enoch in the Hebrew Bible; Emmeduranki and others in the Babylonian tradition)\n- The human lifespan is limited\n- A single man to build a boat with specific dimensions\n- The flood wipes out all living creatures that are not on the boat\n- The man makes sacrifices which are pleasing to the gods or God\n- Three birds are sent to find land\n- A covenant established between the man and gods or God.\n\nThus, one can see that there are many similarities between the Babylonian texts and the Hebrew Bible. For any particular similarity one of the following must be true:\n\n1. It is a coincidence\n2. The Hebrew Bible was influenced by Babylonian texts\n3. Babylonian texts were influenced by the Hebrew Bible\n4. Both texts were influenced by a third, older, source.\n\nSome of these similarities may be deemed coincidental, but it seems implausible to believe that all of them are.\n\nEach similarity requires separate analysis. Sometimes we can rely on the dates of the texts to rule out certain possibilities. For example, Solomon is thought to have lived between 1000 and 900 BCE, and thus Ecclesiastes could not have been written earlier than this. The similar quote from *The Epic of Gilgamesh* if from a tablet that is from 1800--1700 BCE. Thus, explanation (3) is implausible.\n\nMost of the Babylonian clay tablets we have recovered were copied around the time of Babylonian captivity, and thus a simplistic archaeological analysis is not possible because we do not know when the age of the original material.\n" }, { "alpha_fraction": 0.763239860534668, "alphanum_fraction": 0.763239860534668, "avg_line_length": 44.85714340209961, "blob_id": "c050cfb049e3de168904ed0281a8c7b9966a8886", "content_id": "0ee241335ab5a74014b083631ad6089e3980d3ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 642, "license_type": "no_license", "max_line_length": 234, "num_lines": 14, "path": "/documents/merciful-and-just.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Merciful and Just\ndescription: >\n An argument for why Christian ethics must exist apart from God.\ntype: essay\nstatus: incomplete\n---\n\nIf God _needed_ to send Jesus to be merciful and just when he condemns but forgives sinful humans, then God is bound by an external moral standard.\n\nIf God defines our moral standard he would not _need_ to send Jesus---he could have declared by the fact that he defines right and wrong, justice, and mercy that he both condemns sin and forgives us while also being merciful and just.\n\nA natural response is to conclude that God didn't _need_ to send Jesus, but rather, he merely _wanted_ to.\n" }, { "alpha_fraction": 0.6061562895774841, "alphanum_fraction": 0.6385161876678467, "avg_line_length": 30.674999237060547, "blob_id": "7652d4c9f0a3289f2ce31ad7f52ccbd7fa8f83f3", "content_id": "5a186ba2f60c53ac3c3c1b3451147122f8f6c66c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1267, "license_type": "no_license", "max_line_length": 91, "num_lines": 40, "path": "/scripts/interp_line_numbers.py", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport sys\n\n\ndef interp_line_numbers(y1, y2, x1, x2, qx1, qx2):\n dx = x2 - x1\n dy = y2 - y1\n assert dx > 0\n assert dy > 0\n assert qx1 >= x1\n assert qx2 <= x2\n assert qx2 >= qx1\n slope = float(dy)/float(dx)\n intercept = y1 - slope*x1\n qy1 = int(round(slope*qx1 + intercept))\n qy2 = int(round(slope*qx2 + intercept))\n return qy1, qy2\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 7:\n print('USAGE: interp_line_numbers ORIG1 ORIG2 TRANS1 TRANS2 QUOTE1 QUOTE2')\n sys.exit(1)\n first_original_lineno_page = int(sys.argv[1])\n last_original_lineno_page = int(sys.argv[2])\n first_translation_lineno_page = int(sys.argv[3])\n last_translation_lineno_page = int(sys.argv[4])\n first_translation_lineno_quote = int(sys.argv[5])\n last_translation_lineno_quote = int(sys.argv[6])\n\n first_original_lineno_quote, last_original_lineno_quote = interp_line_numbers(\n first_original_lineno_page,\n last_original_lineno_page,\n first_translation_lineno_page,\n last_translation_lineno_page,\n first_translation_lineno_quote,\n last_translation_lineno_quote)\n\n print(\"{}--{}\".format(first_original_lineno_quote, last_original_lineno_quote), end='')\n" }, { "alpha_fraction": 0.7837632894515991, "alphanum_fraction": 0.7837632894515991, "avg_line_length": 51.720001220703125, "blob_id": "235c17096ad4a607587b10caa88a8272b26390b8", "content_id": "cc69bf65bc61b82ae58f292c17d381d907b71b77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1318, "license_type": "no_license", "max_line_length": 398, "num_lines": 25, "path": "/about.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\nlayout: basic\ntitle: About\ndescription: About the author and this site\n---\n\n## The Author\n\nI live in New York City with my wife and daughter, and I run a medical software development company.\n\nI enjoy reading, thinking, and writing. I'm especially interested in how to live the good life and how to know what the good life is.\n\nI write anonymously, due to the sensitive nature of the topic.\n\n## This Site\n\nThe essays represent my current thoughts on a topic and are revised alongside my view.\n\nThe notes and commentary are likely less interesting to a general audience; they contain many quotations and my summaries on various works---mostly classics. I worry that the number and length of the quotations I included extends beyond what is allowable by fair use; as best I can tell, they do not, but I sincerely hope not to cause harm to any of the translators, authors, or publishers I quote.\n\nThe meditations are short pieces, that reflect my thoughts and questions on a given day. I only rarely edit these once written, and I provide the date when they were primarily written.\n\nI hope that the occasional visitor to this site will contact me and provide new thoughts about the topics I am writing about.\n\nI have set up a basic email list to try and stay in touch with visitors who are interested in the content.\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 56.272727966308594, "blob_id": "771370f7698eee91aece54de169882ecfa48c21a", "content_id": "94199390f1a627ee8bd24975b436dd26edb25665", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 632, "license_type": "no_license", "max_line_length": 301, "num_lines": 11, "path": "/_documents/why-does-hell-exist.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Why Does Hell Exist?\ndescription: >\n Why would and all-loving God allow a place filled with suffering to exist?\ntype: essay\nstatus: complete\n---\nHell, as described by Dante in *The Divine Comedy*, is filled with people being tortured forever by demons. Why does God allow the demons to torture people forever?\n\nHell, as described by C. S. Lewis in *The Great Divorce*, is filled with people who decided not to be with God. Why does God allow the non-believers to continue existing, forever miserable in their separateness from Him? After a person chooses Hell, God could erase them from existence. Why doesn’t he?\n" }, { "alpha_fraction": 0.7378419637680054, "alphanum_fraction": 0.7378419637680054, "avg_line_length": 27.60869598388672, "blob_id": "f2b6438f1b832d834a71fd4c7c1763291d6c938e", "content_id": "7d932e827062109ec370dca6c15d1fdc32dc81c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1318, "license_type": "no_license", "max_line_length": 53, "num_lines": 46, "path": "/_documents/questioning-poem.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Questioning\ndescription: >\n A poem about life and its questions.\ntype: poem\nstatus: complete\n---\n\nA baby is born and the parents love the baby.<br>\nA baby is born and the parents raise the baby.<br>\nA baby is born and the parents teach it words.<br>\nThe words come slowly.<br>\nThe words grow longer<br>\nAnd the words grow clearer.<br>\nThe child is taught to act.<br>\nThe acts of the child are bad.<br>\nThe child is taught discipline.<br>\nThe child grows into a person.<br>\nAnd this person lives how they please.<br>\nPleasures and pursuits fill its time.<br>\n<br>\nLife’s pain encroaches.<br>\n<br>\nThe person looks for meaning<br>\nAnd the person searches for purpose<br>\nAnd the person asks how to live.<br>\nReligion tells this person how to live.<br>\nReligion tells this person what exists<br>\nWhat exists but is not seen.<br>\n<br>\nHow do they know?<br>\nHow do they trust the words of the ancient books,<br>\nThe words passed down through the ages<br>\nThe words of the prophets<br>\nThe words of the priests?<br>\n<br>\nI want to act well.<br>\nI want to not do what I should not do<br>\nAnd do what I should do.<br>\n<br>\nThe words of the priests tell me what to do!<br>\nThe prophets speak out!<br>\nThe ancient books pass along their wisdom.<br>\nBut how can I trust their knowledge?<br>\nHow can I know?<br>\n" }, { "alpha_fraction": 0.7530049085617065, "alphanum_fraction": 0.7553749680519104, "avg_line_length": 94.2741928100586, "blob_id": "4db1ecf02a7d3182f6a33ed4eeae7edf86a8d8c3", "content_id": "4b249f55597bf0c554fff49894c39a25d97f5b86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6019, "license_type": "no_license", "max_line_length": 2079, "num_lines": 62, "path": "/_documents/the-stranger.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n “The Stranger” by Albert Camus\ndescription: >\n Notes on the “The Stranger” by Albert Camus\ntype: note\nstatus: incomplete\n---\n\n## Summary\n\nA man’s mother dies, and he is indifferent. He is offered a promotion, and he is indifferent. A woman falls in love with the man, and he is indifferent. He shoots a man, and he is indifferent. He is sentenced to death, and he is indifferent. Approach death, he yells at a chaplain that life is absurd and meaningless.\n\n## Quotes\n\n<blockquote class=\"prose\">\n<p>Maman died today. Or yesterday maybe, I don’t know. I got a telegram from the home: “Mother deceased. Funeral tomorrow. Faithfully yours.” That doesn’t mean anything. Maybe it was yesterday.</p>\n<cite>— I.1</cite>\n</blockquote>\n\nIf the telegram said, “Mother died February 8th,” then perhaps the opening would be “Maman died today. I know because of the telegram.”\n\n<blockquote class=\"prose\">\n<p>I got up. Raymond gave me a very firm handshake and said that men always understand each other. I left his room, closing the door behind me, and paused for a minute in the dark, on the landing. The house was quiet, and a breath of dark, dank air wafted up from deep in the stairwell. All I could hear was the blood pounding in my ears. I stood there, motionless. And in old Salamano’s room, the dog whimpered softly.</p>\n<cite>— I.2</cite>\n</blockquote>\n\nThis scene of Meursault standing on the landing, after drinking wine and writing a letter for Raymond, was especially vivid for me.\n\n<blockquote class=\"prose\">\n<p>Then he asked me if I wasn’t interested in a change of life. I said that people never change their lives, that in any case one life was as good as another and that I wasn’t dissatisfied with mine here at all. He looked upset and told me that I never gave him a straight answer, that I had no ambition, and that that was disastrous in business So I went back to work. I would rather not have upset him, but I couldn’t see any reason to change my life. Looking back on it, I wasn’t unhappy. When I was a student, I had lots of ambitions like that. But when I had to give up my studies I learned very quickly that none of it really mattered.</p>\n<cite>— I.5</cite>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>That evening Marie came by to see me and asked me if I wanted to marry her. I said it didn’t make any difference to me and that we could if she wanted to. Then she wanted to know if I loved her. I answered the same way I had the last time, that it didn’t meany anything but that I probably didn’t love her. “So why marry me, then?” she said. I explained to her that it didn’t really matter and that if she wanted to, we could get married.</p>\n<cite>— I.5</cite>\n</blockquote>\n\n<blockquote class=\"prose\">\n<p>He said he had peered into it and that he had found nothing, gentlemen of the jury. He said the truth was that I didn’t have a soul and that nothing human, not one of the moral principles that govern men’s hearts, was within my reach. “Of course,” he added, “we cannot blame him for this. We cannot complain that he lacks what is was not in his power to acquire. But here in this court the wholly negative virtue of tolerance must give way to the sterner but loftier virtue of justice.</p>\n<cite>— II.4</cite>\n</blockquote>\n\nI agree with the prosecutor—I don’t think Meursalt had a soul. I also think he was a sociopath.\n\n<blockquote class=\"prose\">\n<p>Then, I don’t know why, but something inside me snapped. I started yelling at the top of my lungs, and I insulted him and told him not to waste his prayers on me. I grabbed him by the collar of his cassock. I was pouring out on him everything that was in my heart, cries of anger and cries of joy. He seemed so certain about everything, didn’t he? And yet none of his certainties was worth one hair of a woman’s head. He wasn’t even sure he was alive, because he was living like a dead man. Whereas it looked as if I was the one who’d come up emptyhanded. But I was sure about me, about everything, surer than he could ever be, sure of my life and sure of the death I had waiting for me. Yes, that was all I had. But at least I had as much of a hold on it as it had on me. I had been right, I was still right, I was always right. I had lived my life one way and I could just as well have lived it another. I had done this and I hadn’t done that. I hadn’t done this thing but I had done another. And so? It was as if I had waited all this time for this moment and for the first light of this dawn to be vindicated. Nothing, nothing mattered, and I knew why. So did he. Throughout the whole absurd life I’d lived, a dark wind had been rising toward me from somewhere deep in my future, across years that were still to come, and as it passed, this wind leveled whatever was was offered to me as the time, in years no more real than the ones I was living. What did other people’s deaths or a mother’s love matter to me; what did his God or the lives people choose or the fate they thing they elect matter to me when we’re all elected by the same fate, me and billions of privileged people like him who also call themselves my brothers? Couldn’t he see, couldn’t he see that? Everybody was privileged. There were only privileged people. The others would all be condemned one day. And he would be condemned, too. What would it matter if he were accused of murder and then executed because he didn’t cry at his mother’s funeral? Salamano’s dog was worth just as much as his wife.</p>\n<cite>— II.6</cite>\n</blockquote>\n\n## Thoughts\n\nIt seems that Camus follows the reasoning:\n\n1. If God doesn’t exist, life is meaningless and there is no moral standard\n2. God doesn’t exist\n3. Therefore, life is meaningless and there is no moral standard\n\nWhile it is unclear to me whether God exists (or, if he does, how he wants us to act), I do not agree with the first premise.\n\n*All quotations are taken from Matthew Ward’s 1990 translation.*\n" }, { "alpha_fraction": 0.7838776707649231, "alphanum_fraction": 0.7852916121482849, "avg_line_length": 307.36492919921875, "blob_id": "76b9015f539c72e05f8799324fd79fae9a456ddd", "content_id": "a1fe876e45616e0b8d8f7abcb15495c471df0778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65308, "license_type": "no_license", "max_line_length": 2744, "num_lines": 211, "path": "/documents/gullivers-travels.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n \"Gulliver's Travels\" by Jonathan Swift\ndescription: >\n Notes on \"Gulliver's Travels\" by Jonathan Swift\ntype: note\n---\n\n## Background\n\nJonathan Swift was born in Dublin in 1667 and died in 1745.\n\nHe was a writer and cleric, and became the Dean of St Patrick's Cathedral in Dublin. He was friends with Alexander Pope.\n\n_Gulliver's Travels_ was first published in 1726.\n\nIn each of Gulliver's four journeys, the focus of Swift's satire shifts.\n\nPart I focuses on the pettiness of humankind. The king of Lilliput is referred to as the \"delight and terror of the universe,\" highlighting how small we are to God and the universe.\n\nPart II focuses on the human body (although he exploring our vices too).\n\nPart III focuses on the mind.\n\nPart IV focuses on our immorality.\n\nHere I collect my favourite quotes from the book.\n\n## Part I: Lilliput\n\nThe famous scene when Gulliver meets the little Lilliputians:\n\n> I lay down on the grass, which was very short and soft, where I slept sounder than ever I remembered to have done in my life, and, as I reckoned, about nine hours; for when I awaked, it was just day-light. I attempted to rise, but was not able to stir: for, as I happened to lie on my back, I found my arms and legs were strongly fastened on each side to the ground; and my hair, which was long and thick, tied down in the same manner. I likewise felt several slender ligatures across my body, from my arm-pits to my thighs. I could only look upwards; the sun began to grow hot, and the light offended my eyes. I heard a confused noise about me; but in the posture I lay, could see nothing except the sky. In a little time I felt something alive moving on my left leg, which advancing gently forward over my breast, came almost up to my chin; when, bending my eyes downwards as much as I could, I perceived it to be a human creature not six inches high, with a bow and arrow in his hands, and a quiver at his back. In the mean time, I felt at least forty more of the same kind (as I conjectured) following the first.\n> = (1.1)\n\nThe first of several discussions of excrement:\n\n> I had been for some hours extremely pressed by the necessities of nature; which was no wonder, it being almost two days since I had last disburdened myself. I was under great difficulties between urgency and shame. The best expedient I could think of, was to creep into my house, which I accordingly did; and shutting the gate after me, I went as far as the length of my chain would suffer, and discharged my body of that uneasy load. But this was the only time I was ever guilty of so uncleanly an action; for which I cannot but hope the candid reader will give some allowance, after he has maturely and impartially considered my case, and the distress I was in. From this time my constant practice was, as soon as I rose, to perform that business in open air, at the full extent of my chain; and due care was taken every morning before company came, that the offensive matter should be carried off in wheel-barrows, by two servants appointed for that purpose. I would not have dwelt so long upon a circumstance that, perhaps, at first sight, may appear not very momentous, if I had not thought it necessary to justify my character, in point of cleanliness, to the world; which, I am told, some of my maligners have been pleased, upon this and other occasions, to call in question.\n> = (1.2)\n\n> In the mean time the emperor held frequent councils, to debate what course should be taken with me; and I was afterwards assured by a particular friend, a person of great quality, who was as much in the secret as any, that the court was under many difficulties concerning me. They apprehended my breaking loose; that my diet would be very expensive, and might cause a famine.\n> = (1.2)\n\n> The natives came, by degrees, to be less apprehensive of any danger from me. I would sometimes lie down, and let five or six of them dance on my hand; and at last the boys and girls would venture to come and play at hide-and-seek in my hair. I had now made a good progress in understanding and speaking the language. The emperor had a mind one day to entertain me with several of the country shows, wherein they exceed all nations I have known, both for dexterity and magnificence. I was diverted with none so much as that of the rope-dancers, performed upon a slender white thread, extended about two feet, and twelve inches from the ground. Upon which I shall desire liberty, with the reader’s patience, to enlarge a little.\n>\n> This diversion is only practised by those persons who are candidates for great employments, and high favour at court. They are trained in this art from their youth, and are not always of noble birth, or liberal education. When a great office is vacant, either by death or disgrace (which often happens,) five or six of those candidates petition the emperor to entertain his majesty and the court with a dance on the rope; and whoever jumps the highest, without falling, succeeds in the office. Very often the chief ministers themselves are commanded to show their skill, and to convince the emperor that they have not lost their faculty. Flimnap, the treasurer, is allowed to cut a caper on the straight rope, at least an inch higher than any other lord in the whole empire. I have seen him do the summerset several times together, upon a trencher fixed on a rope which is no thicker than a common packthread in England. My friend Reldresal, principal secretary for private affairs, is, in my opinion, if I am not partial, the second after the treasurer; the rest of the great officers are much upon a par.\n> = (1.3)\n\n> Golbasto Momarem Evlame Gurdilo Shefin Mully Ully Gue, most mighty Emperor of Lilliput, delight and terror of the universe, whose dominions extend five thousand blustrugs (about twelve miles in circumference) to the extremities of the globe; monarch of all monarchs, taller than the sons of men; whose feet press down to the centre, and whose head strikes against the sun; at whose nod the princes of the earth shake their knees; pleasant as the spring, comfortable as the summer, fruitful as autumn, dreadful as winter\n> = (1.3)\n\n> He began with compliments on my liberty; said “he might pretend to some merit in it;” but, however, added, “that if it had not been for the present situation of things at court, perhaps I might not have obtained it so soon. For,” said he, “as flourishing a condition as we may appear to be in to foreigners, we labour under two mighty evils: a violent faction at home, and the danger of an invasion, by a most potent enemy, from abroad.\n>\n> As to the first, you are to understand, that for about seventy moons past there have been two struggling parties in this empire, under the names of Tramecksan and Slamecksan, from the high and low heels of their shoes, by which they distinguish themselves. It is alleged, indeed, that the high heels are most agreeable to our ancient constitution; but, however this be, his majesty has determined to make use only of low heels in the administration of the government, and all offices in the gift of the crown, as you cannot but observe; and particularly that his majesty’s imperial heels are lower at least by a drurr than any of his court (drurr is a measure about the fourteenth part of an inch). The animosities between these two parties run so high, that they will neither eat, nor drink, nor talk with each other. We compute the Tramecksan, or high heels, to exceed us in number; but the power is wholly on our side. We apprehend his imperial highness, the heir to the crown, to have some tendency towards the high heels; at least we can plainly discover that one of his heels is higher than the other, which gives him a hobble in his gait.\n>\n> Now, in the midst of these intestine disquiets, we are threatened with an invasion from the island of Blefuscu, which is the other great empire of the universe, almost as large and powerful as this of his majesty. For as to what we have heard you affirm, that there are other kingdoms and states in the world inhabited by human creatures as large as yourself, our philosophers are in much doubt, and would rather conjecture that you dropped from the moon, or one of the stars; because it is certain, that a hundred mortals of your bulk would in a short time destroy all the fruits and cattle of his majesty’s dominions: besides, our histories of six thousand moons make no mention of any other regions than the two great empires of Lilliput and Blefuscu. Which two mighty powers have, as I was going to tell you, been engaged in a most obstinate war for six-and-thirty moons past. It began upon the following occasion. It is allowed on all hands, that the primitive way of breaking eggs, before we eat them, was upon the larger end; but his present majesty’s grandfather, while he was a boy, going to eat an egg, and breaking it according to the ancient practice, happened to cut one of his fingers. Whereupon the emperor his father published an edict, commanding all his subjects, upon great penalties, to break the smaller end of their eggs.\n>\n> The people so highly resented this law, that our histories tell us, there have been six rebellions raised on that account; wherein one emperor lost his life, and another his crown. These civil commotions were constantly fomented by the monarchs of Blefuscu; and when they were quelled, the exiles always fled for refuge to that empire. It is computed that eleven thousand persons have at several times suffered death, rather than submit to break their eggs at the smaller end. Many hundred large volumes have been published upon this controversy: but the books of the Big-endians have been long forbidden, and the whole party rendered incapable by law of holding employments. During the course of these troubles, the emperors of Blefusca did frequently expostulate by their ambassadors, accusing us of making a schism in religion, by offending against a fundamental doctrine of our great prophet Lustrog, in the fifty-fourth chapter of the Blundecral (which is their Alcoran). This, however, is thought to be a mere strain upon the text; for the words are these: ‘that all true believers break their eggs at the convenient end.’ And which is the convenient end, seems, in my humble opinion to be left to every man’s conscience, or at least in the power of the chief magistrate to determine. Now, the Big-endian exiles have found so much credit in the emperor of Blefuscu’s court, and so much private assistance and encouragement from their party here at home, that a bloody war has been carried on between the two empires for six-and-thirty moons, with various success; during which time we have lost forty capital ships, and a much a greater number of smaller vessels, together with thirty thousand of our best seamen and soldiers; and the damage received by the enemy is reckoned to be somewhat greater than ours. However, they have now equipped a numerous fleet, and are just preparing to make a descent upon us; and his imperial majesty, placing great confidence in your valour and strength, has commanded me to lay this account of his affairs before you.”\n> = (1.4)\n\n> It is to be observed, that these ambassadors spoke to me, by an interpreter, the languages of both empires differing as much from each other as any two in Europe, and each nation priding itself upon the antiquity, beauty, and energy of their own tongue, with an avowed contempt for that of their neighbour\n> = (1.5)\n\n> I heard the word Burglum repeated incessantly: several of the emperor’s court, making their way through the crowd, entreated me to come immediately to the palace, where her imperial majesty’s apartment was on fire, by the carelessness of a maid of honour, who fell asleep while she was reading a romance. I got up in an instant; and orders being given to clear the way before me, and it being likewise a moonshine night, I made a shift to get to the palace without trampling on any of the people. I found they had already applied ladders to the walls of the apartment, and were well provided with buckets, but the water was at some distance. These buckets were about the size of large thimbles, and the poor people supplied me with them as fast as they could: but the flame was so violent that they did little good. I might easily have stifled it with my coat, which I unfortunately left behind me for haste, and came away only in my leathern jerkin. The case seemed wholly desperate and deplorable; and this magnificent palace would have infallibly been burnt down to the ground, if, by a presence of mind unusual to me, I had not suddenly thought of an expedient. I had, the evening before, drunk plentifully of a most delicious wine called glimigrim, (the Blefuscudians call it flunec, but ours is esteemed the better sort,) which is very diuretic. By the luckiest chance in the world, I had not discharged myself of any part of it. The heat I had contracted by coming very near the flames, and by labouring to quench them, made the wine begin to operate by urine; which I voided in such a quantity, and applied so well to the proper places, that in three minutes the fire was wholly extinguished, and the rest of that noble pile, which had cost so many ages in erecting, preserved from destruction.\n> = (1.5)\n\n> They bury their dead with their heads directly downward, because they hold an opinion, that in eleven thousand moons they are all to rise again; in which period the earth (which they conceive to be flat) will turn upside down, and by this means they shall, at their resurrection, be found ready standing on their feet. The learned among them confess the absurdity of this doctrine; but the practice still continues, in compliance to the vulgar.\n> = (1.6)\n\n> In choosing persons for all employments, they have more regard to good morals than to great abilities; for, since government is necessary to mankind, they believe, that the common size of human understanding is fitted to some station or other; and that Providence never intended to make the management of public affairs a mystery to be comprehended only by a few persons of sublime genius, of which there seldom are three born in an age: but they suppose truth, justice, temperance, and the like, to be in every man’s power; the practice of which virtues, assisted by experience and a good intention, would qualify any man for the service of his country, except where a course of study is required. But they thought the want of moral virtues was so far from being supplied by superior endowments of the mind, that employments could never be put into such dangerous hands as those of persons so qualified; and, at least, that the mistakes committed by ignorance, in a virtuous disposition, would never be of such fatal consequence to the public weal, as the practices of a man, whose inclinations led him to be corrupt, and who had great abilities to manage, to multiply, and defend his corruptions.\n> = (1.6)\n\n> It was a custom introduced by this prince and his ministry (very different, as I have been assured, from the practice of former times,) that after the court had decreed any cruel execution, either to gratify the monarch’s resentment, or the malice of a favourite, the emperor always made a speech to his whole council, expressing his great lenity and tenderness, as qualities known and confessed by all the world. This speech was immediately published throughout the kingdom; nor did any thing terrify the people so much as those encomiums on his majesty’s mercy; because it was observed, that the more these praises were enlarged and insisted on, the more inhuman was the punishment, and the sufferer more innocent.\n> = (1.7)\n\n## Part 2: Brobdingnag\n\n> I was endeavouring to find some gap in the hedge, when I discovered one of the inhabitants in the next field, advancing towards the stile, of the same size with him whom I saw in the sea pursuing our boat. He appeared as tall as an ordinary spire steeple, and took about ten yards at every stride, as near as I could guess. I was struck with the utmost fear and astonishment, and ran to hide myself in the corn, whence I saw him at the top of the stile looking back into the next field on the right hand, and heard him call in a voice many degrees louder than a speaking-trumpet: but the noise was so high in the air, that at first I certainly thought it was thunder.\n> = (2.1)\n\n> for, as human creatures are observed to be more savage and cruel in proportion to their bulk, what could I expect but to be a morsel in the mouth of the first among these enormous barbarians that should happen to seize me? Undoubtedly philosophers are in the right, when they tell us that nothing is great or little otherwise than by comparison. It might have pleased fortune, to have let the Lilliputians find some nation, where the people were as diminutive with respect to them, as they were to me. And who knows but that even this prodigious race of mortals might be equally overmatched in some distant part of the world, whereof we have yet no discovery.\n> = (2.1)\n\n> This prince took a pleasure in conversing with me, inquiring into the manners, religion, laws, government, and learning of Europe; wherein I gave him the best account I was able. His apprehension was so clear, and his judgment so exact, that he made very wise reflections and observations upon all I said. But I confess, that, after I had been a little too copious in talking of my own beloved country, of our trade and wars by sea and land, of our schisms in religion, and parties in the state; the prejudices of his education prevailed so far, that he could not forbear taking me up in his right hand, and stroking me gently with the other, after a hearty fit of laughing, asked me, “whether I was a whig or tory?” Then turning to his first minister, who waited behind him with a white staff, near as tall as the mainmast of the Royal Sovereign, he observed “how contemptible a thing was human grandeur, which could be mimicked by such diminutive insects as I: and yet,” says he, “I dare engage these creatures have their titles and distinctions of honour; they contrive little nests and burrows, that they call houses and cities; they make a figure in dress and equipage; they love, they fight, they dispute, they cheat, they betray!” And thus he continued on, while my colour came and went several times, with indignation, to hear our noble country, the mistress of arts and arms, the scourge of France, the arbitress of Europe, the seat of virtue, piety, honour, and truth, the pride and envy of the world, so contemptuously treated.\n> = (2.3)\n\n> The maids of honour often invited Glumdalclitch to their apartments, and desired she would bring me along with her, on purpose to have the pleasure of seeing and touching me. They would often strip me naked from top to toe, and lay me at full length in their bosoms; wherewith I was much disgusted because, to say the truth, a very offensive smell came from their skins; which I do not mention, or intend, to the disadvantage of those excellent ladies, for whom I have all manner of respect; but I conceive that my sense was more acute in proportion to my littleness, and that those illustrious persons were no more disagreeable to their lovers, or to each other, than people of the same quality are with us in England. And, after all, I found their natural smell was much more supportable, than when they used perfumes, under which I immediately swooned away. I cannot forget, that an intimate friend of mine in Lilliput, took the freedom in a warm day, when I had used a good deal of exercise, to complain of a strong smell about me, although I am as little faulty that way, as most of my sex: but I suppose his faculty of smelling was as nice with regard to me, as mine was to that of this people. Upon this point, I cannot forbear doing justice to the queen my mistress, and Glumdalclitch my nurse, whose persons were as sweet as those of any lady in England.\n>\n> That which gave me most uneasiness among these maids of honour (when my nurse carried me to visit then) was, to see them use me without any manner of ceremony, like a creature who had no sort of consequence: for they would strip themselves to the skin, and put on their smocks in my presence, while I was placed on their toilet, directly before their naked bodies, which I am sure to me was very far from being a tempting sight, or from giving me any other emotions than those of horror and disgust: their skins appeared so coarse and uneven, so variously coloured, when I saw them near, with a mole here and there as broad as a trencher, and hairs hanging from it thicker than packthreads, to say nothing farther concerning the rest of their persons. Neither did they at all scruple, while I was by, to discharge what they had drank, to the quantity of at least two hogsheads, in a vessel that held above three tuns. The handsomest among these maids of honour, a pleasant, frolicsome girl of sixteen, would sometimes set me astride upon one of her nipples, with many other tricks, wherein the reader will excuse me for not being over particular. But I was so much displeased, that I entreated Glumdalclitch to contrive some excuse for not seeing that young lady any more.\n> = (2.5)\n\n> When I attended the king after my recovery, to return him thanks for his favours, he was pleased to rally me a good deal upon this adventure. He asked me, “what my thoughts and speculations were, while I lay in the monkey’s paw; how I liked the victuals he gave me; his manner of feeding; and whether the fresh air on the roof had sharpened my stomach.” He desired to know, “what I would have done upon such an occasion in my own country.” I told his majesty, “that in Europe we had no monkeys, except such as were brought for curiosity from other places, and so small, that I could deal with a dozen of them together, if they presumed to attack me. And as for that monstrous animal with whom I was so lately engaged (it was indeed as large as an elephant), if my fears had suffered me to think so far as to make use of my hanger,” (looking fiercely, and clapping my hand on the hilt, as I spoke) “when he poked his paw into my chamber, perhaps I should have given him such a wound, as would have made him glad to withdraw it with more haste than he put it in.” This I delivered in a firm tone, like a person who was jealous lest his courage should be called in question. However, my speech produced nothing else beside a loud laughter, which all the respect due to his majesty from those about him could not make them contain. This made me reflect, how vain an attempt it is for a man to endeavour to do himself honour among those who are out of all degree of equality or comparison with him. And yet I have seen the moral of my own behaviour very frequent in England since my return; where a little contemptible varlet, without the least title to birth, person, wit, or common sense, shall presume to look with importance, and put himself upon a foot with the greatest persons of the kingdom.\n> = (2.5)\n\n> He [the king] was perfectly astonished with the historical account gave him of our affairs during the last century; protesting “it was only a heap of conspiracies, rebellions, murders, massacres, revolutions, banishments, the very worst effects that avarice, faction, hypocrisy, perfidiousness, cruelty, rage, madness, hatred, envy, lust, malice, and ambition, could produce.”\n>\n> His majesty, in another audience, was at the pains to recapitulate the sum of all I had spoken; compared the questions he made with the answers I had given; then taking me into his hands, and stroking me gently, delivered himself in these words, which I shall never forget, nor the manner he spoke them in: “My little friend Grildrig, you have made a most admirable panegyric upon your country; you have clearly proved, that ignorance, idleness, and vice, are the proper ingredients for qualifying a legislator; that laws are best explained, interpreted, and applied, by those whose interest and abilities lie in perverting, confounding, and eluding them. I observe among you some lines of an institution, which, in its original, might have been tolerable, but these half erased, and the rest wholly blurred and blotted by corruptions. It does not appear, from all you have said, how any one perfection is required toward the procurement of any one station among you; much less, that men are ennobled on account of their virtue; that priests are advanced for their piety or learning; soldiers, for their conduct or valour; judges, for their integrity; senators, for the love of their country; or counsellors for their wisdom. As for yourself,” continued the king, “who have spent the greatest part of your life in travelling, I am well disposed to hope you may hitherto have escaped many vices of your country. But by what I have gathered from your own relation, and the answers I have with much pains wrung and extorted from you, I cannot but conclude the bulk of your natives to be the most pernicious race of little odious vermin that nature ever suffered to crawl upon the surface of the earth.”\n> = (2.6)\n\n## Part 3: Laputa, Balnibarbi, Luggnag, Glubdubdrib, and Japan\n\n> Their heads were all reclined, either to the right, or the left; one of their eyes turned inward, and the other directly up to the zenith. Their outward garments were adorned with the figures of suns, moons, and stars; interwoven with those of fiddles, flutes, harps, trumpets, guitars, harpsichords, and many other instruments of music, unknown to us in Europe. I observed, here and there, many in the habit of servants, with a blown bladder, fastened like a flail to the end of a stick, which they carried in their hands. In each bladder was a small quantity of dried peas, or little pebbles, as I was afterwards informed. With these bladders, they now and then flapped the mouths and ears of those who stood near them, of which practice I could not then conceive the meaning. It seems the minds of these people are so taken up with intense speculations, that they neither can speak, nor attend to the discourses of others, without being roused by some external action upon the organs of speech and hearing; for which reason, those persons who are able to afford it always keep a flapper (the original is climenole) in their family, as one of their domestics; nor ever walk abroad, or make visits, without him. And the business of this officer is, when two, three, or more persons are in company, gently to strike with his bladder the mouth of him who is to speak, and the right ear of him or them to whom the speaker addresses himself. This flapper is likewise employed diligently to attend his master in his walks, and upon occasion to give him a soft flap on his eyes; because he is always so wrapped up in cogitation, that he is in manifest danger of falling down every precipice, and bouncing his head against every post; and in the streets, of justling others, or being justled himself into the kennel.\n> = (3.2)\n\n> They are so perpetually alarmed with the apprehensions of these, and the like impending dangers, that they can neither sleep quietly in their beds, nor have any relish for the common pleasures and amusements of life. When they meet an acquaintance in the morning, the first question is about the sun’s health, how he looked at his setting and rising, and what hopes they have to avoid the stroke of the approaching comet. This conversation they are apt to run into with the same temper that boys discover in delighting to hear terrible stories of spirits and hobgoblins, which they greedily listen to, and dare not go to bed for fear.\n> = (3.2)\n\n> The women of the island have abundance of vivacity: they contemn their husbands, and are exceedingly fond of strangers, whereof there is always a considerable number from the continent below, attending at court, either upon affairs of the several towns and corporations, or their own particular occasions, but are much despised, because they want the same endowments. Among these the ladies choose their gallants: but the vexation is, that they act with too much ease and security; for the husband is always so rapt in speculation, that the mistress and lover may proceed to the greatest familiarities before his face, if he be but provided with paper and implements, and without his flapper at his side.\n> = (3.2)\n\n> The sum of his discourse was to this effect: “That about forty years ago, certain persons went up to Laputa, either upon business or diversion, and, after five months continuance, came back with a very little smattering in mathematics, but full of volatile spirits acquired in that airy region: that these persons, upon their return, began to dislike the management of every thing below, and fell into schemes of putting all arts, sciences, languages, and mechanics, upon a new foot. To this end, they procured a royal patent for erecting an academy of projectors in Lagado; and the humour prevailed so strongly among the people, that there is not a town of any consequence in the kingdom without such an academy. In these colleges the professors contrive new rules and methods of agriculture and building, and new instruments, and tools for all trades and manufactures; whereby, as they undertake, one man shall do the work of ten; a palace may be built in a week, of materials so durable as to last for ever without repairing. All the fruits of the earth shall come to maturity at whatever season we think fit to choose, and increase a hundred fold more than they do at present; with innumerable other happy proposals. The only inconvenience is, that none of these projects are yet brought to perfection; and in the mean time, the whole country lies miserably waste, the houses in ruins, and the people without food or clothes. By all which, instead of being discouraged, they are fifty times more violently bent upon prosecuting their schemes, driven equally on by hope and despair.\"\n> = (3.4)\n\n> There was a most ingenious architect, who had contrived a new method for building houses, by beginning at the roof, and working downward to the foundation; which he justified to me, by the like practice of those two prudent insects, the bee and the spider.\n>\n> There was a man born blind, who had several apprentices in his own condition: their employment was to mix colours for painters, which their master taught them to distinguish by feeling and smelling. It was indeed my misfortune to find them at that time not very perfect in their lessons, and the professor himself happened to be generally mistaken. This artist is much encouraged and esteemed by the whole fraternity.\n> = (3.5)\n\n> I was complaining of a small fit of the colic, upon which my conductor led me into a room where a great physician resided, who was famous for curing that disease, by contrary operations from the same instrument. He had a large pair of bellows, with a long slender muzzle of ivory: this he conveyed eight inches up the anus, and drawing in the wind, he affirmed he could make the guts as lank as a dried bladder. But when the disease was more stubborn and violent, he let in the muzzle while the bellows were full of wind, which he discharged into the body of the patient; then withdrew the instrument to replenish it, clapping his thumb strongly against the orifice of then fundament; and this being repeated three or four times, the adventitious wind would rush out, bringing the noxious along with it, (like water put into a pump), and the patient recovered. I saw him try both experiments upon a dog, but could not discern any effect from the former. After the latter the animal was ready to burst, and made so violent a discharge as was very offensive to me and my companion. The dog died on the spot, and we left the doctor endeavouring to recover him, by the same operation.\n> = (3.5)\n\n> The other project was, a scheme for entirely abolishing all words whatsoever; and this was urged as a great advantage in point of health, as well as brevity. For it is plain, that every word we speak is, in some degree, a diminution of our lungs by corrosion, and, consequently, contributes to the shortening of our lives. An expedient was therefore offered, “that since words are only names for things, it would be more convenient for all men to carry about them such things as were necessary to express a particular business they are to discourse on.” And this invention would certainly have taken place, to the great ease as well as health of the subject, if the women, in conjunction with the vulgar and illiterate, had not threatened to raise a rebellion unless they might be allowed the liberty to speak with their tongues, after the manner of their forefathers; such constant irreconcilable enemies to science are the common people. However, many of the most learned and wise adhere to the new scheme of expressing themselves by things; which has only this inconvenience attending it, that if a man’s business be very great, and of various kinds, he must be obliged, in proportion, to carry a greater bundle of things upon his back, unless he can afford one or two strong servants to attend him. I have often beheld two of those sages almost sinking under the weight of their packs, like pedlars among us, who, when they met in the street, would lay down their loads, open their sacks, and hold conversation for an hour together; then put up their implements, help each other to resume their burdens, and take their leave.\n> = (3.5)\n\n> I desired to see Alexander the Great at the head of his army, just after the battle of Arbela: which, upon a motion of the governor’s finger, immediately appeared in a large field, under the window where we stood. Alexander was called up into the room: it was with great difficulty that I understood his Greek, and had but little of my own. He assured me upon his honour “that he was not poisoned, but died of a bad fever by excessive drinking.”\n>\n> Next, I saw Hannibal passing the Alps, who told me “he had not a drop of vinegar in his camp.”\n>\n> I saw Cæsar and Pompey at the head of their troops, just ready to engage. I saw the former, in his last great triumph. I desired that the senate of Rome might appear before me, in one large chamber, and an assembly of somewhat a later age in counterview, in another. The first seemed to be an assembly of heroes and demigods; the other, a knot of pedlars, pick-pockets, highwayman, and bullies.\n>\n> The governor, at my request, gave the sign for Cæsar and Brutus to advance towards us. I was struck with a profound veneration at the sight of Brutus, and could easily discover the most consummate virtue, the greatest intrepidity and firmness of mind, the truest love of his country, and general benevolence for mankind, in every lineament of his countenance. I observed, with much pleasure, that these two persons were in good intelligence with each other; and Cæsar freely confessed to me, “that the greatest actions of his own life were not equal, by many degrees, to the glory of taking it away.” I had the honour to have much conversation with Brutus; and was told, “that his ancestor Junius, Socrates, Epaminondas, Cato the younger, Sir Thomas More, and himself were perpetually together:” a sextumvirate, to which all the ages of the world cannot add a seventh.\n> = (3.7)\n\n> Having a desire to see those ancients who were most renowned for wit and learning, I set apart one day on purpose. I proposed that Homer and Aristotle might appear at the head of all their commentators; but these were so numerous, that some hundreds were forced to attend in the court, and outward rooms of the palace. I knew, and could distinguish those two heroes, at first sight, not only from the crowd, but from each other. Homer was the taller and comelier person of the two, walked very erect for one of his age, and his eyes were the most quick and piercing I ever beheld. Aristotle stooped much, and made use of a staff. His visage was meagre, his hair lank and thin, and his voice hollow. I soon discovered that both of them were perfect strangers to the rest of the company, and had never seen or heard of them before; and I had a whisper from a ghost who shall be nameless, “that these commentators always kept in the most distant quarters from their principals, in the lower world, through a consciousness of shame and guilt, because they had so horribly misrepresented the meaning of those authors to posterity.” I introduced Didymus and Eustathius to Homer, and prevailed on him to treat them better than perhaps they deserved, for he soon found they wanted a genius to enter into the spirit of a poet. But Aristotle was out of all patience with the account I gave him of Scotus and Ramus, as I presented them to him; and he asked them, “whether the rest of the tribe were as great dunces as themselves?”\n> = (3.8)\n\n> The despatch came from court about the time we expected. It contained a warrant for conducting me and my retinue to Traldragdubh, or Trildrogdrib (for it is pronounced both ways as near as I can remember), by a party of ten horse. All my retinue was that poor lad for an interpreter, whom I persuaded into my service, and, at my humble request, we had each of us a mule to ride on. A messenger was despatched half a day’s journey before us, to give the king notice of my approach, and to desire, “that his majesty would please to appoint a day and hour, when it would by his gracious pleasure that I might have the honour to lick the dust before his footstool.” This is the court style, and I found it to be more than matter of form: for, upon my admittance two days after my arrival, I was commanded to crawl upon my belly, and lick the floor as I advanced; but, on account of my being a stranger, care was taken to have it made so clean, that the dust was not offensive. However, this was a peculiar grace, not allowed to any but persons of the highest rank, when they desire an admittance. Nay, sometimes the floor is strewed with dust on purpose, when the person to be admitted happens to have powerful enemies at court; and I have seen a great lord with his mouth so crammed, that when he had crept to the proper distance from the throne; he was not able to speak a word. Neither is there any remedy; because it is capital for those, who receive an audience to spit or wipe their mouths in his majesty’s presence. There is indeed another custom, which I cannot altogether approve of: when the king has a mind to put any of his nobles to death in a gentle indulgent manner, he commands the floor to be strewed with a certain brown powder of a deadly composition, which being licked up, infallibly kills him in twenty-four hours. But in justice to this prince’s great clemency, and the care he has of his subjects’ lives (wherein it were much to be wished that the Monarchs of Europe would imitate him), it must be mentioned for his honour, that strict orders are given to have the infected parts of the floor well washed after every such execution, which, if his domestics neglect, they are in danger of incurring his royal displeasure. I myself heard him give directions, that one of his pages should be whipped, whose turn it was to give notice about washing the floor after an execution, but maliciously had omitted it; by which neglect a young lord of great hopes, coming to an audience, was unfortunately poisoned, although the king at that time had no design against his life. But this good prince was so gracious as to forgive the poor page his whipping, upon promise that he would do so no more, without special orders.\n> = (3.9)\n\nAn interesting scene where Swift expands on why he would want to live forever. I was disappointed that he didn't explore this further, and instead took the easy way out of the discussion by having the immortal struldbrugs become old and senile.\n\n> One day, in much good company, I was asked by a person of quality, “whether I had seen any of their struldbrugs, or immortals?” I said, “I had not;” and desired he would explain to me “what he meant by such an appellation, applied to a mortal creature.” He told me “that sometimes, though very rarely, a child happened to be born in a family, with a red circular spot in the forehead, directly over the left eyebrow, which was an infallible mark that it should never die.” The spot, as he described it, “was about the compass of a silver threepence, but in the course of time grew larger, and changed its colour; for at twelve years old it became green, so continued till five and twenty, then turned to a deep blue: at five and forty it grew coal black, and as large as an English shilling; but never admitted any further alteration.” He said, “these births were so rare, that he did not believe there could be above eleven hundred struldbrugs, of both sexes, in the whole kingdom; of which he computed about fifty in the metropolis, and, among the rest, a young girl born; about three years ago: that these productions were not peculiar to any family, but a mere effect of chance; and the children of the struldbrugs themselves were equally mortal with the rest of the people.”\n>\n> I freely own myself to have been struck with inexpressible delight, upon hearing this account: and the person who gave it me happening to understand the Balnibarbian language, which I spoke very well, I could not forbear breaking out into expressions, perhaps a little too extravagant. I cried out, as in a rapture, “Happy nation, where every child hath at least a chance for being immortal! Happy people, who enjoy so many living examples of ancient virtue, and have masters ready to instruct them in the wisdom of all former ages! but happiest, beyond all comparison, are those excellent struldbrugs, who, being born exempt from that universal calamity of human nature, have their minds free and disengaged, without the weight and depression of spirits caused by the continual apprehensions of death!” I discovered my admiration, “that I had not observed any of these illustrious persons at court; the black spot on the forehead being so remarkable a distinction, that I could not have easily overlooked it: and it was impossible that his majesty, a most judicious prince, should not provide himself with a good number of such wise and able counsellors. Yet perhaps the virtue of those reverend sages was too strict for the corrupt and libertine manners of a court: and we often find by experience, that young men are too opinionated and volatile to be guided by the sober dictates of their seniors. However, since the king was pleased to allow me access to his royal person, I was resolved, upon the very first occasion, to deliver my opinion to him on this matter freely and at large, by the help of my interpreter; and whether he would please to take my advice or not, yet in one thing I was determined, that his majesty having frequently offered me an establishment in this country, I would, with great thankfulness, accept the favour, and pass my life here in the conversation of those superior beings the struldbrugs, if they would please to admit me.”\n>\n> The gentleman to whom I addressed my discourse, because (as I have already observed) he spoke the language of Balnibarbi, said to me, with a sort of a smile which usually arises from pity to the ignorant, “that he was glad of any occasion to keep me among them, and desired my permission to explain to the company what I had spoke.” He did so, and they talked together for some time in their own language, whereof I understood not a syllable, neither could I observe by their countenances, what impression my discourse had made on them. After a short silence, the same person told me, “that his friends and mine (so he thought fit to express himself) were very much pleased with the judicious remarks I had made on the great happiness and advantages of immortal life, and they were desirous to know, in a particular manner, what scheme of living I should have formed to myself, if it had fallen to my lot to have been born a struldbrug.”\n>\n> I answered, “it was easy to be eloquent on so copious and delightful a subject, especially to me, who had been often apt to amuse myself with visions of what I should do, if I were a king, a general, or a great lord: and upon this very case, I had frequently run over the whole system how I should employ myself, and pass the time, if I were sure to live for ever.\n>\n> “That, if it had been my good fortune to come into the world a struldbrug, as soon as I could discover my own happiness, by understanding the difference between life and death, I would first resolve, by all arts and methods, whatsoever, to procure myself riches. In the pursuit of which, by thrift and management, I might reasonably expect, in about two hundred years, to be the wealthiest man in the kingdom. In the second place, I would, from my earliest youth, apply myself to the study of arts and sciences, by which I should arrive in time to excel all others in learning. Lastly, I would carefully record every action and event of consequence, that happened in the public, impartially draw the characters of the several successions of princes and great ministers of state, with my own observations on every point. I would exactly set down the several changes in customs, language, fashions of dress, diet, and diversions. By all which acquirements, I should be a living treasure of knowledge and wisdom, and certainly become the oracle of the nation.\n>\n> “I would never marry after threescore, but live in a hospitable manner, yet still on the saving side. I would entertain myself in forming and directing the minds of hopeful young men, by convincing them, from my own remembrance, experience, and observation, fortified by numerous examples, of the usefulness of virtue in public and private life. But my choice and constant companions should be a set of my own immortal brotherhood; among whom, I would elect a dozen from the most ancient, down to my own contemporaries. Where any of these wanted fortunes, I would provide them with convenient lodges round my own estate, and have some of them always at my table; only mingling a few of the most valuable among you mortals, whom length of time would harden me to lose with little or no reluctance, and treat your posterity after the same manner; just as a man diverts himself with the annual succession of pinks and tulips in his garden, without regretting the loss of those which withered the preceding year.\n>\n> “These struldbrugs and I would mutually communicate our observations and memorials, through the course of time; remark the several gradations by which corruption steals into the world, and oppose it in every step, by giving perpetual warning and instruction to mankind; which, added to the strong influence of our own example, would probably prevent that continual degeneracy of human nature so justly complained of in all ages.\n>\n> “Add to this, the pleasure of seeing the various revolutions of states and empires; the changes in the lower and upper world; ancient cities in ruins, and obscure villages become the seats of kings; famous rivers lessening into shallow brooks; the ocean leaving one coast dry, and overwhelming another; the discovery of many countries yet unknown; barbarity overrunning the politest nations, and the most barbarous become civilized. I should then see the discovery of the longitude, the perpetual motion, the universal medicine, and many other great inventions, brought to the utmost perfection.\n>\n> “What wonderful discoveries should we make in astronomy, by outliving and confirming our own predictions; by observing the progress and return of comets, with the changes of motion in the sun, moon, and stars!”\n>\n> I enlarged upon many other topics, which the natural desire of endless life, and sublunary happiness, could easily furnish me with. When I had ended, and the sum of my discourse had been interpreted, as before, to the rest of the company, there was a good deal of talk among them in the language of the country, not without some laughter at my expense. At last, the same gentleman who had been my interpreter, said, “he was desired by the rest to set me right in a few mistakes, which I had fallen into through the common imbecility of human nature, and upon that allowance was less answerable for them. That this breed of struldbrugs was peculiar to their country, for there were no such people either in Balnibarbi or Japan, where he had the honour to be ambassador from his majesty, and found the natives in both those kingdoms very hard to believe that the fact was possible: and it appeared from my astonishment when he first mentioned the matter to me, that I received it as a thing wholly new, and scarcely to be credited. That in the two kingdoms above mentioned, where, during his residence, he had conversed very much, he observed long life to be the universal desire and wish of mankind. That whoever had one foot in the grave was sure to hold back the other as strongly as he could. That the oldest had still hopes of living one day longer, and looked on death as the greatest evil, from which nature always prompted him to retreat. Only in this island of Luggnagg the appetite for living was not so eager, from the continual example of the struldbrugs before their eyes.\n>\n> “That the system of living contrived by me, was unreasonable and unjust; because it supposed a perpetuity of youth, health, and vigour, which no man could be so foolish to hope, however extravagant he may be in his wishes. That the question therefore was not, whether a man would choose to be always in the prime of youth, attended with prosperity and health; but how he would pass a perpetual life under all the usual disadvantages which old age brings along with it. For although few men will avow their desires of being immortal, upon such hard conditions, yet in the two kingdoms before mentioned, of Balnibarbi and Japan, he observed that every man desired to put off death some time longer, let it approach ever so late: and he rarely heard of any man who died willingly, except he were incited by the extremity of grief or torture. And he appealed to me, whether in those countries I had travelled, as well as my own, I had not observed the same general disposition.”\n>\n> After this preface, he gave me a particular account of the struldbrugs among them. He said, “they commonly acted like mortals till about thirty years old; after which, by degrees, they grew melancholy and dejected, increasing in both till they came to fourscore. This he learned from their own confession: for otherwise, there not being above two or three of that species born in an age, they were too few to form a general observation by. When they came to fourscore years, which is reckoned the extremity of living in this country, they had not only all the follies and infirmities of other old men, but many more which arose from the dreadful prospect of never dying. They were not only opinionative, peevish, covetous, morose, vain, talkative, but incapable of friendship, and dead to all natural affection, which never descended below their grandchildren. Envy and impotent desires are their prevailing passions. But those objects against which their envy seems principally directed, are the vices of the younger sort and the deaths of the old. By reflecting on the former, they find themselves cut off from all possibility of pleasure; and whenever they see a funeral, they lament and repine that others have gone to a harbour of rest to which they themselves never can hope to arrive. They have no remembrance of anything but what they learned and observed in their youth and middle-age, and even that is very imperfect; and for the truth or particulars of any fact, it is safer to depend on common tradition, than upon their best recollections. The least miserable among them appear to be those who turn to dotage, and entirely lose their memories; these meet with more pity and assistance, because they want many bad qualities which abound in others.\n> = (3.10)\n\n> To this I added another petition, “that for the sake of my patron the king of Luggnagg, his majesty would condescend to excuse my performing the ceremony imposed on my countrymen, of trampling upon the crucifix: because I had been thrown into his kingdom by my misfortunes, without any intention of trading.” When this latter petition was interpreted to the Emperor, he seemed a little surprised; and said, “he believed I was the first of my countrymen who ever made any scruple in this point; and that he began to doubt, whether I was a real Hollander, or not; but rather suspected I must be a Christian.\n> = (3.11)\n\n## Part 4: Houyhnhnms\n\n> The horse immediately ordered a white mare servant of his family to bring me a good quantity of oats in a sort of wooden tray. These I heated before the fire, as well as I could, and rubbed them till the husks came off, which I made a shift to winnow from the grain. I ground and beat them between two stones; then took water, and made them into a paste or cake, which I toasted at the fire and eat warm with milk. It was at first a very insipid diet, though common enough in many parts of Europe, but grew tolerable by time; and having been often reduced to hard fare in my life, this was not the first experiment I had made how easily nature is satisfied.\n> = (4.2)\n\n> I therefore told my master, “that in the country whence I came, those of my kind always covered their bodies with the hairs of certain animals prepared by art, as well for decency as to avoid the inclemencies of air, both hot and cold; of which, as to my own person, I would give him immediate conviction, if he pleased to command me: only desiring his excuse, if I did not expose those parts that nature taught us to conceal.” He said, “my discourse was all very strange, but especially the last part; for he could not understand, why nature should teach us to conceal what nature had given; that neither himself nor family were ashamed of any parts of their bodies; but, however, I might do as I pleased.”\n> = (4.3)\n\n> I therefore told my master, “that in the country whence I came, those of my kind always covered their bodies with the hairs of certain animals prepared by art, as well for decency as to avoid the inclemencies of air, both hot and cold; of which, as to my own person, I would give him immediate conviction, if he pleased to command me: only desiring his excuse, if I did not expose those parts that nature taught us to conceal.” He said, “my discourse was all very strange, but especially the last part; for he could not understand, why nature should teach us to conceal what nature had given; that neither himself nor family were ashamed of any parts of their bodies; but, however, I might do as I pleased.”\n> = (4.5)\n\n> I could not forbear shaking my head, and smiling a little at his ignorance. And being no stranger to the art of war, I gave him a description of cannons, culverins, muskets, carabines, pistols, bullets, powder, swords, bayonets, battles, sieges, retreats, attacks, undermines, countermines, bombardments, sea fights, ships sunk with a thousand men, twenty thousand killed on each side, dying groans, limbs flying in the air, smoke, noise, confusion, trampling to death under horses’ feet, flight, pursuit, victory; fields strewed with carcases, left for food to dogs and wolves and birds of prey; plundering, stripping, ravishing, burning, and destroying. And to set forth the valour of my own dear countrymen, I assured him, “that I had seen them blow up a hundred enemies at once in a siege, and as many in a ship, and beheld the dead bodies drop down in pieces from the clouds, to the great diversion of the spectators.”\n>\n> I was going on to more particulars, when my master commanded me silence. He said, “whoever understood the nature of Yahoos, might easily believe it possible for so vile an animal to be capable of every action I had named, if their strength and cunning equalled their malice. But as my discourse had increased his abhorrence of the whole species, so he found it gave him a disturbance in his mind to which he was wholly a stranger before. He thought his ears, being used to such abominable words, might, by degrees, admit them with less detestation: that although he hated the Yahoos of this country, yet he no more blamed them for their odious qualities, than he did a gnnayh (a bird of prey) for its cruelty, or a sharp stone for cutting his hoof. But when a creature pretending to reason could be capable of such enormities, he dreaded lest the corruption of that faculty might be worse than brutality itself. He seemed therefore confident, that, instead of reason we were only possessed of some quality fitted to increase our natural vices; as the reflection from a troubled stream returns the image of an ill shapen body, not only larger but more distorted.”\n> = (4.5)\n\n\n> I assured his honour, “that the law was a science in which I had not much conversed, further than by employing advocates, in vain, upon some injustices that had been done me: however, I would give him all the satisfaction I was able.”\n>\n> I said, “there was a society of men among us, bred up from their youth in the art of proving, by words multiplied for the purpose, that white is black, and black is white, according as they are paid. To this society all the rest of the people are slaves. For example, if my neighbour has a mind to my cow, he has a lawyer to prove that he ought to have my cow from me. I must then hire another to defend my right, it being against all rules of law that any man should be allowed to speak for himself. Now, in this case, I, who am the right owner, lie under two great disadvantages: first, my lawyer, being practised almost from his cradle in defending falsehood, is quite out of his element when he would be an advocate for justice, which is an unnatural office he always attempts with great awkwardness, if not with ill-will. The second disadvantage is, that my lawyer must proceed with great caution, or else he will be reprimanded by the judges, and abhorred by his brethren, as one that would lessen the practice of the law. And therefore I have but two methods to preserve my cow. The first is, to gain over my adversary’s lawyer with a double fee, who will then betray his client by insinuating that he hath justice on his side. The second way is for my lawyer to make my cause appear as unjust as he can, by allowing the cow to belong to my adversary: and this, if it be skilfully done, will certainly bespeak the favour of the bench. Now your honour is to know, that these judges are persons appointed to decide all controversies of property, as well as for the trial of criminals, and picked out from the most dexterous lawyers, who are grown old or lazy; and having been biassed all their lives against truth and equity, lie under such a fatal necessity of favouring fraud, perjury, and oppression, that I have known some of them refuse a large bribe from the side where justice lay, rather than injure the faculty, by doing any thing unbecoming their nature or their office.\n>\n> “It is a maxim among these lawyers that whatever has been done before, may legally be done again: and therefore they take special care to record all the decisions formerly made against common justice, and the general reason of mankind. These, under the name of precedents, they produce as authorities to justify the most iniquitous opinions; and the judges never fail of directing accordingly.\n>\n> “In pleading, they studiously avoid entering into the merits of the cause; but are loud, violent, and tedious, in dwelling upon all circumstances which are not to the purpose. For instance, in the case already mentioned; they never desire to know what claim or title my adversary has to my cow; but whether the said cow were red or black; her horns long or short; whether the field I graze her in be round or square; whether she was milked at home or abroad; what diseases she is subject to, and the like; after which they consult precedents, adjourn the cause from time to time, and in ten, twenty, or thirty years, come to an issue.\n>\n> “It is likewise to be observed, that this society has a peculiar cant and jargon of their own, that no other mortal can understand, and wherein all their laws are written, which they take special care to multiply; whereby they have wholly confounded the very essence of truth and falsehood, of right and wrong; so that it will take thirty years to decide, whether the field left me by my ancestors for six generations belongs to me, or to a stranger three hundred miles off.\n> = (4.5)\n\n> The many virtues of those excellent quadrupeds, placed in opposite view to human corruptions, had so far opened my eyes and enlarged my understanding, that I began to view the actions and passions of man in a very different light, and to think the honour of my own kind not worth managing; which, besides, it was impossible for me to do, before a person of so acute a judgment as my master, who daily convinced me of a thousand faults in myself, whereof I had not the least perception before, and which, with us, would never be numbered even among human infirmities. I had likewise learned, from his example, an utter detestation of all falsehood or disguise; and truth appeared so amiable to me, that I determined upon sacrificing every thing to it.\n>\n> Let me deal so candidly with the reader as to confess that there was yet a much stronger motive for the freedom I took in my representation of things. I had not yet been a year in this country before I contracted such a love and veneration for the inhabitants, that I entered on a firm resolution never to return to humankind, but to pass the rest of my life among these admirable Houyhnhnms, in the contemplation and practice of every virtue, where I could have no example or incitement to vice.\n> = (4.7)\n\n> When I had answered all his questions, and his curiosity seemed to be fully satisfied, he sent for me one morning early, and commanded me to sit down at some distance (an honour which he had never before conferred upon me). He said, “he had been very seriously considering my whole story, as far as it related both to myself and my country; that he looked upon us as a sort of animals, to whose share, by what accident he could not conjecture, some small pittance of reason had fallen, whereof we made no other use, than by its assistance, to aggravate our natural corruptions, and to acquire new ones, which nature had not given us; that we disarmed ourselves of the few abilities she had bestowed; had been very successful in multiplying our original wants, and seemed to spend our whole lives in vain endeavours to supply them by our own inventions.\n> = (4.7)\n\n> Thus, gentle reader, I have given thee a faithful history of my travels for sixteen years and above seven months: wherein I have not been so studious of ornament as of truth. I could, perhaps, like others, have astonished thee with strange improbable tales; but I rather chose to relate plain matter of fact, in the simplest manner and style; because my principal design was to inform, and not to amuse thee.\n>\n> It is easy for us who travel into remote countries, which are seldom visited by Englishmen or other Europeans, to form descriptions of wonderful animals both at sea and land. Whereas a traveller’s chief aim should be to make men wiser and better, and to improve their minds by the bad, as well as good, example of what they deliver concerning foreign places.\n>\n> I could heartily wish a law was enacted, that every traveller, before he were permitted to publish his voyages, should be obliged to make oath before the Lord High Chancellor, that all he intended to print was absolutely true to the best of his knowledge; for then the world would no longer be deceived, as it usually is, while some writers, to make their works pass the better upon the public, impose the grossest falsities on the unwary reader. I have perused several books of travels with great delight in my younger days; but having since gone over most parts of the globe, and been able to contradict many fabulous accounts from my own observation, it has given me a great disgust against this part of reading, and some indignation to see the credulity of mankind so impudently abused. Therefore, since my acquaintance were pleased to think my poor endeavours might not be unacceptable to my country, I imposed on myself, as a maxim never to be swerved from, that I would strictly adhere to truth; neither indeed can I be ever under the least temptation to vary from it, while I retain in my mind the lectures and example of my noble master and the other illustrious Houyhnhnms of whom I had so long the honour to be an humble hearer.\n> = (4.12)\n" }, { "alpha_fraction": 0.7171598672866821, "alphanum_fraction": 0.7201405167579651, "avg_line_length": 43.52132797241211, "blob_id": "e126c758a2a3ff951633cec89d098d9919a71036", "content_id": "9c24b1b0c598834a9c76454731ada3ad034107b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9514, "license_type": "no_license", "max_line_length": 387, "num_lines": 211, "path": "/_documents/sophocles-theban-plays.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Sophocles’ Theban Plays\ndescription: >\n Notes on Sophocles’ Theban Plays\ntype: note\n---\n\n## Oedipus the King\n\nAngered Tiresias implicates Oedipus:\n\n<blockquote>\n<p>So, you mock my blindness? Let me tell you this.</p>\n<p>You with your precious eyes,</p>\n<p>you’re blind to the corruption of your life,</p>\n<p>to the house you live in, those you live with—</p>\n<p>who <em>are</em> your parents? Do you know? All unknowing</p>\n<p>you are the scourge of your own flesh and blood,</p>\n<p>the dead below the earth and the living here above,</p>\n<p>and the double lash of your mother and your father’s curse</p>\n<p>will whip you from this land one day, their footfall</p>\n<p>treading you down in terror, darkness shrouding</p>\n<p>your eyes that can see the light!</p>\n</blockquote>\n\nThe following quotations expresses two ideas central to the Greek world view. First, that the gods strip down the over-proud man, the man filled with hubris. Second, that we competition is healthy.\n\n<blockquote>\n<p>Destiny guide me always</p>\n<p>Destiny guide me filled with reverence</p>\n<p>pure in word and deed.</p>\n<p>Great laws tower above us, reared on high</p>\n<p>born for the brilliant vault of heaven—</p>\n<p>Olympian Sky their only father,</p>\n<p>nothing mortal, no man gave them birth,</p>\n<p>their memory deathless, never lost in sleep:</p>\n<p>within them lives a mighty god, the god does not</p>\n<p>grow old. Pride breeds the tyrant</p>\n<p>violent pride, gorging, crammed to bursting</p>\n<p>with all that is overripe and rich with ruin—</p>\n<p>clawing up to the heights, headlong pride</p>\n<p>crashes down the abyss—sheer doom!</p>\n<p>No footing helps, all foothold lost and gone.</p>\n<p>But the healthy strife that makes the city strong—</p>\n<p>I pray that god will never end that wrestling:</p>\n<p>god, my champion, I will never let you go.</p>\n</blockquote>\n\nThese two ideas are present in many of the ancient Greek works; Hesiod, near the opening of _Works and Days_, speaks of strife that causes men to compete with one another, doing people good; Herodotus’ stories highlight his belief that the gods tore down overproud men—he also explicitly discusses this idea; the _Iliad_ is filled with proud men striving with one other to “be the best.”\n\nThe Chorus, after Oedipus is revealed:\n\n<blockquote>\n<p>O the generations of men</p>\n<p>the dying generations—adding the total</p>\n<p>of all your lives I find they come to nothing…</p>\n<p>does there exist, is there a man on earth</p>\n<p>who seizes more joy than just a dream, a vision?</p>\n<p>And the vision no sooner dawns than dies</p>\n<p>blazing into oblivion.</p>\n<p>You are my great example, you, your life</p>\n<p>your destiny, Oedipus, man of misery—</p>\n<p>I count no man blest.</p>\n</blockquote>\n\nOedipus, chases after his wife and mother Jocasta:\n\n<blockquote>\n<p>His wife,</p>\n<p>no wife, his mother, where can eh find the mother earth</p>\n<p>that cropped two crops at once, himself and all his children?</p>\n<p>He was raging—one of the dark powers pointing the way,</p>\n<p>with a great shattering cry—someone, something leading him on—</p>\n<p>he hurled at the twin doors and bending the bolts back</p>\n<p>out of their sockets, crashed through the chamber.</p>\n<p>And there we saw the woman hanging by the neck,</p>\n<p>cradled high in a woven noose, spinning,</p>\n<p>swinging back and forth. And when he saw her,</p>\n<p>giving a low, wrenching sob that broke our hearts,</p>\n<p>slipped the halter from her throat, he eased her down,</p>\n<p>in a slow embrace he laid her down, poor thing…</p>\n<p>then, what came next, what horror we beheld!</p>\n<p>He rips off her brooches, the long gold pins</p>\n<p>holding her robes—and lifting them high,</p>\n<p>looking straight up into the points,</p>\n<p>he digs them down the sockets of his eyes, crying, “You,</p>\n<p>you’ll see no more the pain I suffered, all the pain I caused!</p>\n<p>Too long you looked on the ones you never should have seen,</p>\n<p>blind to the ones you longed to see, to know! Blind</p>\n<p>from this hour on! Blind in the darkness—blind!”</p>\n<p>His voice like a dirge, rising, over and over</p>\n<p>raising the pins, raking them down his eyes.</p>\n<p>And at each stroke blood spurts from the roots,</p>\n<p>splashing his beard, a swirl of it, nerves and clots—</p>\n<p>black hail of blood pulsing, gushing down.</p>\n</blockquote>\n\nThe Chorus, at the end of the play:\n\n<blockquote>\n<p>People of Thebes, my countrymen, look on Oedipus.</p>\n<p>He solved the famous riddle with his brilliance,</p>\n<p>he rose to power, a man beyond all power.</p>\n<p>Who could behold his greatness without envy?</p>\n<p>Now what a black sea of terror has overwhelmed him.</p>\n<p>Now as we keep our watch and wait the final day,</p>\n<p>count no many happy till he dies, free of pain at last.</p>\n</blockquote>\n\nThis metric for judging the happy life is in Herodotus’ fable of Solon meeting Croesus.\n\n## Oedipus at Colonus\n\n<blockquote class=\"poetry\">\n<p>Oh Theseus,</p>\n<p>dear friend, only the gods can never age,</p>\n<p>the gods can never die. All else in the world</p>\n<p>almighty Time obliterates, crushes all</p>\n<p>to nothing. The earth’s strength wastes away,</p>\n<p>the strength of a man’s body wastes and dies—</p>\n<p>faith dies, and bad faith comes to life,</p>\n<p>and the same wind of friendship cannot blow forever,</p>\n<p>holding steady and strong between two friends,</p>\n<p>much less between two cities.</p>\n<p>For some of us soon, for others later,</p>\n<p>joy turns to hate and back again to love.</p>\n<p>And even if all is summer sunshine now</p>\n<p>between yourself and Thebes,</p>\n<p>infinite Time, sweeping through its rounds</p>\n<p>gives birth to infinte nights and days…</p>\n<p>and a day will come when the treaties of an hour,</p>\n<p>the pacts firmed by a handclasp will snap—</p>\n<p>at the slightest word a spear will hurl them to the winds—</p>\n<p>some far-off day when my dead body, slumbering, buried</p>\n<p>cold in death, will drain their hot blood down,</p>\n<p>if Zeus is still Zeus and Apollow the son of god</p>\n<p>speaks clear and true. <cite>(685–707)</cite></p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>Here, stranger,</p>\n<p>here in the land of horses are a glory</p>\n<p>you have reached the noblest home on earth</p>\n<p>Colonus glistening, brilliant in the sun—</p>\n<p>where the nightingale sings on,</p>\n<p>her dying music rising clear,</p>\n<p>hovering always, never leavning,</p>\n<p>down the shadows deepening green</p>\n<p>she haunts the glades, the wine-dark ivy,</p>\n<p>dense and dark the untrodden, sacred wood of god</p>\n<p>rich with laurel and olives never touched by the sun</p>\n<p>untouched by storms that blast from every quarter—</p>\n<p>where the Reveler Dionysus strides the earth forever</p>\n<p>where the wild nymphs are dancing round him</p>\n<p>nymphs who nursed his life.</p>\n<p>And here it blooms, fed by the dews of heaven</p>\n<p>lovely, clustering, morning-fresh forever,</p>\n<p>narcissus, crown of the Great Goddesss</p>\n<p>Mother and Daughter dying</p>\n<p>into life from the dawn of time,</p>\n<p>and the gold crocus bursts like break of day</p>\n<p>and the springs will never sleep, will never fail,</p>\n<p>the fountainhead of Cephisus flowing nomad</p>\n<p>quickening life forever, fresh each day—</p>\n<p>life rising up with the river’s pure tide</p>\n<p>flowing over the plains, the swelling breats of earth—</p>\n<p>nor can the dancing Muses bear to leave this land</p>\n<p>or the Goddess Aphrodite, the charioteer</p>\n<p>with the golden reins of love. <cite>(761–89)</cite></p>\n</blockquote>\n\n<blockquote class=\"poetry\">\n<p>Suffer us to live here … even in these straights</p>\n<p>our life is not as pitiful as you’d think,</p>\n<p>so long as we find joy in every hour. <cite>(909–11)</cite></p>\n</blockquote>\n\nOedipus declaring his innocence to Creon, in front of Theseus and the Athenians:\n\n<blockquote class=\"poetry\">\n<p>Unctuous, shameless—where do you think your insults</p>\n<p>do more damage, my old age or yours? Bloodshed</p>\n<p>incest, misery, all your mouth lets fly at me,</p>\n<p>I have suffered it all, and all against my will!</p>\n<p>Such was the pleasure of the gods, raging,</p>\n<p>perhaps, against our race from ages past.</p>\n<p>But as for me alone—</p>\n<p>say my unwilling crimes against myself</p>\n<p>and against my own were payment from the gods</p>\n<p>for something criminal deep inside me…no, look hard,</p>\n<p>you’ll find no guilt to accuse me of—I am innocent!</p>\n<p>⋯</p>\n<p>And my mother…</p>\n<p>wretched man, have you no shame? Your own sister!</p>\n<p>Her marriage—forcing me to talk of that marriage!</p>\n<p>Oh I’ll tell it all, I won’t be silent, not now,</p>\n<p>you and your blasphemous mouth have gone so far.</p>\n<p>She was my mother, yes, she bore me—</p>\n<p>oh the horror—I knew nothing, she knew nothing!—</p>\n<p>and once she’d born me then she bore me children,</p>\n<p>her disgrace. But at least I know one thing:</p>\n<p>you slander her and me of your own free will,</p>\n<p>but I made her my bride against my will,</p>\n<p>I repeat this to the world againnst my will. No,</p>\n<p>I’ll not be branded guilty, not in that marriage,</p>\n<p>not in the murder of my father, all those crimes</p>\n<p>you heap on me relentlessly, harrowing my heart. <cite>(1095–1131)</cite></p>\n</blockquote>\n\n*Quotations are taken from Robert Fagles’ 1982 translation of* The Three Theban Plays*, published by Penguin Classics.*\n" }, { "alpha_fraction": 0.788977861404419, "alphanum_fraction": 0.7894489169120789, "avg_line_length": 87.45833587646484, "blob_id": "99008918cd2166106894a7d8d1b49ce2e653401f", "content_id": "154100baa5cbdd7ce530f15f8ef66449adf7ea29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4302, "license_type": "no_license", "max_line_length": 771, "num_lines": 48, "path": "/_documents/justification-via-others-beliefs.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n Justification via Other’s Beliefs\ndescription: >\n When is it appropriate to justify one’s own beliefs with another’s beliefs?\ntype: essay\nstatus: complete\n---\n\nWe justify our beliefs using a combination of intuition, emotion, reasoning, sensory perception, and other means.\n\nWe may also justify our beliefs using other’s beliefs. For example, someone may believe that the sun’s light comes from nuclear reactions because their teacher believes it. Alternatively, one could listen to why their teacher believes the sun’s light comes from nuclear reactions, study the requisite math and physics, and judge for themselves whether their teacher’s justification was valid.\n\nIn the first case, we are justifying our belief using another’s belief. In the second case, we are adopting another’s justification for ourselves without relying on their belief.\n\nFrequently, we combine these approaches; for example, we may study enough nuclear physics to feel comfortable accepting our teacher’s opinion. In this case, we are justifying our belief partially on our knowledge and reasoning, and partly on our teacher’s belief.\n\nWhen we justify our beliefs using other’s beliefs, we open ourselves up to two problems:\n\n1. The other person is deceiving us.\n2. The other person is mistaken.\n\nGiven these problems, when is it appropriate to justify our beliefs using other’s beliefs?\n\nSome beliefs can only be justified via other’s beliefs. Beliefs that prophets have had religious revelations fall into this category. For example, a prophet says that God wants you to stop going on expensive vacations and to donate to the poor. You can only justify your belief in the prophet by believing what the prophet says; you must believe that they are not deceiving you and they are not mistaken. Beliefs about historical events can only be justified via other’s beliefs because we are not present to see the event ourself. For example, your Uncle tells you that your great great grandfather had Parkinson’s disease; nobody else in the family was aware of this. Your belief that you have a family history of Parkinson’s is justified via your Uncle’s belief.\n\nOther beliefs, while possibly to justify on our own, would require an infeasible amount of resources for us to do so. For example, the experimental evidence for our theory of nuclear reactions in the sun would be difficult for me to reproduce because the theory is complex and the experiments needed to validate it are expensive.\n\nMany beliefs can be justified on our own, but we do not have the interest, time, or ability to do so. For example, I believe that Australia exists although I have never visited.\n\nOf course, some beliefs are more important than others. It would be wise to allocate our limited resources into justifying our most important beliefs on our own as much as possible. And, if we must resort to justification via other’s beliefs, we should take the time to understand the other person’s justification, and consider if they have ulterior motives. This way we may avoid the first problem, but we can not completely avoid the second problem, because we may be mistaken ourself.\n\n{% comment %}\nWhat should one do when “all of the experts agree that” proposition XYZ is true? Should you believe proposition XYZ?\n\nHere are some worthwhile questions to ask:\n\n- How do you define “the experts”, and why?\n- Do you only include people who have studied a particular topic?\n- Do you include people who lived in the past?\n- What are some ways that the experts could all be incorrect?\n - There is new information that is not yet widely known.\n - There are strong political reasons for the experts to all agree.\n- What do all of the non-experts believe?\n- Is there a way to divide people into many groups, where each group tends to believe differently? If so, what causes each group to believe what they believe?\n\nAll of “the experts” agreeing that proposition XYZ is true does not cause it to be true (unless the proposition has to do with the experts’ beliefs—which is a pedantic side case). Still, usually when the experts believe something, it is true. Thus, if you disagree with the experts, it is prudent to have a good reason for disagreeing.\n{% endcomment %}\n" }, { "alpha_fraction": 0.7191057205200195, "alphanum_fraction": 0.7365853786468506, "avg_line_length": 32.698631286621094, "blob_id": "71d6bb2b2848d84ca8dcdc8b3c4e052f02d03550", "content_id": "7b44c743dc6f19b59406ea65f935fc517484d723", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2486, "license_type": "no_license", "max_line_length": 275, "num_lines": 73, "path": "/_documents/job-and-the-problem-of-evil.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n “Job” and the Problem of Evil\ndescription: >\n “Job” and the Problem of Evil\ntype: note\n---\n\n## Outline\n\n- Prose introduction (1 - 2)\n- Poetic dialogue between Job and Eliphaz, Bildad, and Zophar (3 - 31)\n- Poetic monologue of young Elihu (32 - 37)\n- Poetic dialogue between God and Job (38 - 42)\n- Prose epilogue (42)\n\n## The Problem of Evil\n\nJob is a blameless and rich man with ten children. One day, God boasts about Job’s righteousness to Satan, who is unimpressed. “God allows Satan to take his wealth, children, and health. Throughout the book, Job\n\n<blockquote class=\"poetry\">\n<p>“It is all one; therefore I say,</p>\n<p class=\"indent\">he destroys both the blameless and the wicked.” <cite>(9.22 - 24)</cite></p>\n</blockquote>\n\nThe problem of evil is a unique concern for believers of a benevolent and all-powerful God.\n\nIf God was not omnipotent, then they may not be able to prevent the suffering of the innocent. The forces of nature may overwhelm god. Or, if God is one among many, then innocent suffering could be collateral due to the whims of the gods, as is seen throughout the *Iliad*.\n\nIf God was not benevolent or didn’t exist, then there is no expectation that the evil will perish or the good will be blessed.\n\nThus, believers in a benevolent and all-powerful God must explain how the\nThe theological discussion in Job are subtle and comprehensive.\n\nThe existence of the book of Job implies that the writers had been monotheistic for some time by the time it was written, and had thought through the various aspects of the problem of evil in detail.\n\n- Job believed that justice exists apart from God; God seems to refute that idea\n\n## Age of the Book\n\n- Many unknown phrases\n- Iron weapon (v. 20.24) ?\n\n## Cultural References\n\n- The Leviathan\n- The dome in the sky\n- Creating humans is like cheese curdling (10.10)\n- The phoenix\n\n## Interpretation\n\nJob is unaware of the existence of Heaven.\n\n- 14.10 - 12\n- 14.13 - 17 (If only I could hide in Sheol until your anger passes, and then you would let me come back to Earth and would not “number my steps”)\n\nChristian:\n\n- “I know that my redeemer lives”\n- The number of children is not doubled\n\nTextual Analysis:\n\n- Odd re-ordering of passages\n\n## Quotes\n\n<blockquote class=\"poetry\">\n<p>A mortal, born of woman, few of days and full of trouble</p>\n<p> comes up like a flower and withers,</p>\n<p> flees like a shadow and does not last. <cite>(14.1)</cite></p>\n</blockquote>\n" }, { "alpha_fraction": 0.7786180973052979, "alphanum_fraction": 0.782055675983429, "avg_line_length": 99.31034851074219, "blob_id": "7c09126e3fb2d878cff2952b75df73ff261f0767", "content_id": "faf2d7bfb2c381e5b8fc074c1c205c79152471b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2909, "license_type": "no_license", "max_line_length": 401, "num_lines": 29, "path": "/posts/2020-06-20-euthyphro-and-a-universal-morality.md", "repo_name": "weigethoughts/blog", "src_encoding": "UTF-8", "text": "---\ntitle: >\n _Euthyphro_ and a Universal Morality\ndescription: >\n I connect _Euthyphro_'s first two definitions of piety to the belief in a universal moral standard among religions.\n---\n\nEuthyphro initially defines _piety_ as \"something dear to the gods.\" Socrates proceeds to pick at this. He observes that the gods quarrel; Zeus says to help Hercules, while Hera says to hinder him. This definition produces conflicting demands and must be wrong. In response, Euthyphro revises his definition: _piety_ is \"what all the gods love.\"\n\nA monotheist would not be convinced by Socrates' rebuke since a single god could provide a clear definition of piety. With polytheists going extinct, is Socrates' rebuttal, and Euthyphro's response, still relevant? I think it is.\n\nPeople who hope that everyone can get along---that all religions share a universal morality---are like polytheists since religions, like gods, make conflicting demands. In the same way, Euthyphro's second definition reduces piety what is loved by _all_ the gods, so too they must reduce morality to what is shared by all religions.\n\nThis definition may be appealing, but Euthyphro and his humanist ancestors face two difficulties: What if there is no common ground? And who are you to decide what is essential? On what basis do you discard the pilgrimage to Mecca or Christian baptism? Perhaps it is not possible to be a pious Zeus-worshiper and Kronos-worshiper.\n\nSocrates' explanation of what the gods disagree about also remains relevant:\n\n> SOCRATES: What are the subjects that cause hatred and anger? Let us look at it this way. If you and I were to differ about numbers as to which is the greater, would this difference make us enemies and angry with each other, or would we proceed to count and soon resolve our difference about them?\n> EUTHYPHRO: We would certainly do so.\n> SOCRATES: Again, if we differed about the larger and the smaller, we would turn to measurement and soon cease to differ.\n> EUTHYPHRO: That is so ...\n> SOCRATES: What subject of difference would make us angry and hostile to each other if we were unable to come to a decision? ... These subjects are the just and the unjust, the beautiful and the ugly, the good and the bad. Are these not the subjects of difference about which, when we are unable to come to a satisfactory decision, you and I and other men become hostile to each other whenever we do?\n> = (7b--d)\n\nWhile I agree that it is easier to disagree about subjective measures, like justice and beauty, religions also disagree about truth. Not all facts can be verified with measurements, as Socrates implies. Was Muhammad a prophet? Did Jesus rise from the dead?\n\nI am impressed by how relevant _Euthyphro_ remains nearly 2,500 years after Plato wrote it.\n\n_Quotes are from G. M. A. Grube's \"Plato - Five Dialogues: Euthyphro, Apology, Crito, Meno, Phaedo, 2nd Ed.\" published by Hackett Classics in 2002._\n" } ]
87